@Override public void execute(final MessageEvent event, final String[] args) { User sender = event.getUser(); Channel channel = event.getChannel(); if (!System.getProperty("os.name").toLowerCase().contains("win")) { try { int unixTime = Integer.parseInt( new Scanner(new FileInputStream("/proc/uptime")) .next() .replaceAll("\\.[0-9]+", "")); int day = (int) TimeUnit.SECONDS.toDays(unixTime); long hours = TimeUnit.SECONDS.toHours(unixTime) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(unixTime) - (TimeUnit.SECONDS.toHours(unixTime) * 60); long seconds = TimeUnit.SECONDS.toSeconds(unixTime) - (TimeUnit.SECONDS.toMinutes(unixTime) * 60); channel .send() .message( Utils.colourise( String.format( "&2System uptime: &r%s days %s hours %s minutes %s seconds", day, hours, minute, seconds))); } catch (FileNotFoundException ex) { sender.send().notice("File \"/proc/uptime\" not found. Are you sure you're using Linux?"); } return; } sender.send().notice("This command is only supported on Unix based systems."); }
/** * Returns an icon for the vehicle that should be shown on the map * * @param isRealtime true if the marker shown indicate real-time info, false if it should * indicate schedule * @param status the vehicles status to add to the map * @param response the response which contained the provided status * @return an icon for the vehicle that should be shown on the map */ private BitmapDescriptor getVehicleIcon( boolean isRealtime, ObaTripStatus status, ObaTripsForRouteResponse response) { int colorResource; Resources r = Application.get().getResources(); if (isRealtime) { long deviationMin = TimeUnit.SECONDS.toMinutes(status.getScheduleDeviation()); colorResource = ArrivalInfo.computeColorFromDeviation(deviationMin); } else { colorResource = R.color.stop_info_scheduled_time; } int color = r.getColor(colorResource); double direction = MathUtils.toDirection(status.getOrientation()); int halfWind = MathUtils.getHalfWindIndex((float) direction, NUM_DIRECTIONS - 1); // Log.d(TAG, "VehicleId=" + status.getVehicleId() + ", orientation= " + // status.getOrientation() + ", direction=" + direction + ", halfWind= " + halfWind + ", // deviation=" + status.getScheduleDeviation()); String key = createBitmapCacheKey(halfWind, colorResource); Bitmap b = getBitmapFromCache(key); if (b == null) { // Cache miss - create Bitmap and add to cache b = UIUtils.colorBitmap(vehicle_icons[halfWind], color); addBitmapToCache(key, b); } return BitmapDescriptorFactory.fromBitmap(b); }
private long getSessionTimeoutInMinutes() { long sessionTimeout = getSessionTimeout(); if (sessionTimeout > 0) { sessionTimeout = Math.max(TimeUnit.SECONDS.toMinutes(sessionTimeout), 1L); } return sessionTimeout; }
public static CharSequence formatRoutingTime( Context context, int seconds, @DimenRes int unitsSize) { long minutes = TimeUnit.SECONDS.toMinutes(seconds) % 60; long hours = TimeUnit.SECONDS.toHours(seconds); String min = context.getString(R.string.minute); String hour = context.getString(R.string.hour); @DimenRes int textSize = R.dimen.text_size_routing_number; SpannableStringBuilder displayedH = Utils.formatUnitsText(context, textSize, unitsSize, String.valueOf(hours), hour); SpannableStringBuilder displayedM = Utils.formatUnitsText(context, textSize, unitsSize, String.valueOf(minutes), min); return hours == 0 ? displayedM : TextUtils.concat(displayedH + " ", displayedM); }
/** * Send a update account email to the user * * <p>An email contains a link the user can click to perform a set of required actions. The * redirectUri and clientId parameters are optional. The default for the redirect is the account * client. * * @param id User is * @param redirectUri Redirect uri * @param clientId Client id * @param actions required actions the user needs to complete * @return */ @Path("{id}/execute-actions-email") @PUT @Consumes(MediaType.APPLICATION_JSON) public Response executeActionsEmail( @PathParam("id") String id, @QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, @QueryParam(OIDCLoginProtocol.CLIENT_ID_PARAM) String clientId, List<String> actions) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { return ErrorResponse.error("User not found", Response.Status.NOT_FOUND); } if (user.getEmail() == null) { return ErrorResponse.error("User email missing", Response.Status.BAD_REQUEST); } ClientSessionModel clientSession = createClientSession(user, redirectUri, clientId); for (String action : actions) { clientSession.addRequiredAction(action); } ClientSessionCode accessCode = new ClientSessionCode(realm, clientSession); accessCode.setAction(ClientSessionModel.Action.EXECUTE_ACTIONS.name()); try { UriBuilder builder = Urls.executeActionsBuilder(uriInfo.getBaseUri()); builder.queryParam("key", accessCode.getCode()); String link = builder.build(realm.getName()).toString(); long expiration = TimeUnit.SECONDS.toMinutes(realm.getAccessCodeLifespanUserAction()); this.session .getProvider(EmailTemplateProvider.class) .setRealm(realm) .setUser(user) .sendExecuteActions(link, expiration); // audit.user(user).detail(Details.EMAIL, user.getEmail()).detail(Details.CODE_ID, // accessCode.getCodeId()).success(); adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); return Response.ok().build(); } catch (EmailException e) { logger.failedToSendActionsEmail(e); return ErrorResponse.error( "Failed to send execute actions email", Response.Status.INTERNAL_SERVER_ERROR); } }
private String calculateRemTime(long seconds) { int days = (int) TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(days); long minutes = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.DAYS.toMinutes(days) - TimeUnit.HOURS.toMinutes(hours); long secs = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.DAYS.toSeconds(days) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.MINUTES.toSeconds(minutes); return String.format("%dd %d:%02d:%02d", days, hours, minutes, secs); }
public static String convertDurationToTime(int seconds) { String ret = ""; int day = (int) TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); // long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) // *60); if (day > 0) { ret += day + " "; if (day == 1) { ret += "jour"; } else { ret += "jours"; } ret += " "; } if (hours > 0) { ret += hours + " "; if (hours == 1) { ret += "heure"; } else { ret += "heures"; } ret += " "; } if (minute > 0) { ret += minute + " "; if (minute == 1) { ret += "minute"; } else { ret += "minutes"; } ret += " "; } return ret; }
@Override public View getInfoContents(Marker marker) { if (mMarkerData == null) { // Markers haven't been initialized yet - use default rendering return null; } ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); if (status == null) { // Marker that the user tapped on wasn't a vehicle - use default rendering mCurrentFocusVehicleMarker = null; return null; } mCurrentFocusVehicleMarker = marker; View view = mInflater.inflate(R.layout.vehicle_info_window, null); Resources r = mContext.getResources(); TextView routeView = (TextView) view.findViewById(R.id.route_and_destination); TextView statusView = (TextView) view.findViewById(R.id.status); TextView lastUpdatedView = (TextView) view.findViewById(R.id.last_updated); ImageView moreView = (ImageView) view.findViewById(R.id.trip_more_info); moreView.setColorFilter(r.getColor(R.color.switch_thumb_normal_material_dark)); // Get route/trip details ObaTrip trip = mLastResponse.getTrip(status.getActiveTripId()); ObaRoute route = mLastResponse.getRoute(trip.getRouteId()); routeView.setText( UIUtils.getRouteDisplayName(route) + " " + mContext.getString(R.string.trip_info_separator) + " " + trip.getHeadsign()); boolean isRealtime = isLocationRealtime(status); statusView.setBackgroundResource(R.drawable.round_corners_style_b_status); GradientDrawable d = (GradientDrawable) statusView.getBackground(); // Set padding on status view int pSides = UIUtils.dpToPixels(mContext, 5); int pTopBottom = UIUtils.dpToPixels(mContext, 2); int statusColor; if (isRealtime) { long deviationMin = TimeUnit.SECONDS.toMinutes(status.getScheduleDeviation()); String statusString = ArrivalInfo.computeArrivalLabelFromDelay(r, deviationMin); statusView.setText(statusString); statusColor = ArrivalInfo.computeColorFromDeviation(deviationMin); d.setColor(r.getColor(statusColor)); statusView.setPadding(pSides, pTopBottom, pSides, pTopBottom); } else { // Scheduled info statusView.setText(r.getString(R.string.stop_info_scheduled_arrival)); statusColor = R.color.stop_info_scheduled_time; d.setColor(r.getColor(statusColor)); lastUpdatedView.setText(r.getString(R.string.vehicle_last_updated_scheduled)); statusView.setPadding(pSides, pTopBottom, pSides, pTopBottom); return view; } // Update last updated time (only shown for real-time info) long now = System.currentTimeMillis(); long lastUpdateTime; // Use the last updated time for the position itself, if its available if (status.getLastLocationUpdateTime() != 0) { lastUpdateTime = status.getLastLocationUpdateTime(); } else { // Use the status timestamp for last updated time lastUpdateTime = status.getLastUpdateTime(); } long elapsedSec = TimeUnit.MILLISECONDS.toSeconds(now - lastUpdateTime); long elapsedMin = TimeUnit.SECONDS.toMinutes(elapsedSec); long secMod60 = elapsedSec % 60; String lastUpdated; if (elapsedSec < 60) { lastUpdated = r.getString(R.string.vehicle_last_updated_sec, elapsedSec); } else { lastUpdated = r.getString(R.string.vehicle_last_updated_min_and_sec, elapsedMin, secMod60); } lastUpdatedView.setText(lastUpdated); if (mMarkerRefreshHandler != null) { mMarkerRefreshHandler.removeCallbacks(mMarkerRefresh); mMarkerRefreshHandler.postDelayed(mMarkerRefresh, MARKER_REFRESH_PERIOD); } return view; }
// TODO: Cleanup, modulate where possible @Override public void onInlineQueryReceived(InlineQueryReceivedEvent event) { try { // Handle subscription prompting InlineQueryResponse.InlineQueryResponseBuilder subscriptionButton; InlineQueryResultArticle latestUpdate; if (!instance .getSubscriptionHandler() .isSubscribed(TelegramHook.getBot().getChat(event.getQuery().getSender().getId()))) { subscriptionButton = InlineQueryResponse.builder() .switch_pm_text("Click here to subscribe to @RedditLiveBot.") .switch_pm_parameter("subscribe"); } else { subscriptionButton = InlineQueryResponse.builder().switch_pm_text("You are subscribed to @RedditLiveBot."); } // Handle posting of last threads if (instance.getRedditHandler().getCurrentLiveThread() == null) { // Nothing to post latestUpdate = InlineQueryResultArticle.builder() .title("Latest update") .description("Not following any live threads!") .thumbUrl( new URL( "https://camo.githubusercontent.com/b13830f5a9baecd3d83ef5cae4d5107d25cdbfbe/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f3732313033382f313732383830352f35336532613364382d363262352d313165332d383964312d3934376632373062646430332e706e67")) .hideUrl(true) .thumbHeight(512) .thumbWidth(512) .id("latestNews") .inputMessageContent( InputTextMessageContent.builder() .messageText("*RedditLive is not following any live threads.*") .parseMode(ParseMode.MARKDOWN) .build()) .build(); } else { // Variables LiveThreadBroadcasterTask liveThreadBroadcasterTask = RedditLiveBot.instance.getRedditHandler().getCurrentLiveThread(); LiveThreadChildrenData lastPost = liveThreadBroadcasterTask.getLastActualPost(); if (lastPost == null) { latestUpdate = InlineQueryResultArticle.builder() .title("No last post available") .description("Try again soon") .thumbUrl( new URL( "https://camo.githubusercontent.com/b13830f5a9baecd3d83ef5cae4d5107d25cdbfbe/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f3732313033382f313732383830352f35336532613364382d363262352d313165332d383964312d3934376632373062646430332e706e67")) .hideUrl(true) .thumbHeight(512) .thumbWidth(512) .id("latestNews") .inputMessageContent( InputTextMessageContent.builder() .messageText("*No last post available.*") .parseMode(ParseMode.MARKDOWN) .build()) .build(); } else { long delay = (System.currentTimeMillis() / 1000) - lastPost.getCreated_utc(); long minutes = TimeUnit.SECONDS.toMinutes(delay); long seconds = delay - TimeUnit.MINUTES.toSeconds(minutes); String title = "Latest update - Posted " + String.format("%d min, %d sec ago", minutes, seconds); String body = String.format( Lang.LIVE_THREAD_REPOST_UPDATE, liveThreadBroadcasterTask.getThreadID(), lastPost.getAuthor(), lastPost.getBody()); latestUpdate = InlineQueryResultArticle.builder() .title(title) .description(lastPost.getBody()) .thumbUrl( new URL( "https://camo.githubusercontent.com/b13830f5a9baecd3d83ef5cae4d5107d25cdbfbe/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f3732313033382f313732383830352f35336532613364382d363262352d313165332d383964312d3934376632373062646430332e706e67")) .hideUrl(true) .thumbHeight(512) .thumbWidth(512) .id("latestNews") .inputMessageContent( InputTextMessageContent.builder() .messageText(body) .parseMode(ParseMode.MARKDOWN) .build()) .build(); } } event .getQuery() .answer( TelegramHook.getBot(), subscriptionButton.results(latestUpdate).cache_time(0).build()); } catch (MalformedURLException e) { e.printStackTrace(); } }
public static String convertDurationToString(int sec) { return String.format( "%02d:%02d", TimeUnit.SECONDS.toMinutes(sec), (sec - TimeUnit.SECONDS.toMinutes(sec) * 60)); }
/** * Get minutes from seconds * * @param seconds * @return */ public static long getMinutesFromSeconds(long seconds) { return TimeUnit.SECONDS.toMinutes(seconds); }
@Override public void methodToCallback(String print) { String timediff; live_list = new ArrayList<HashMap<String, String>>(); try { array1 = new JSONArray(print); for (int i = 0; i < array1.length(); i++) { JSONObject obj1 = array1.getJSONObject(i); HashMap<String, String> map = new HashMap<String, String>(); String event = obj1.getString("event"); map.put("name", event); map.put("fulldata", obj1.toString()); /// caluclation difference in time String time = obj1.getString("$ts"); // time in seconds Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.SECOND, 0); long timenow = cal.getTimeInMillis(); try { long recivetime = (long) Double.parseDouble(time); long diff = (timenow - recivetime) / 1000; int day = (int) TimeUnit.SECONDS.toDays(diff); long hours = TimeUnit.SECONDS.toHours(diff) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(diff) - (TimeUnit.SECONDS.toHours(diff) * 60); long second = TimeUnit.SECONDS.toSeconds(diff) - (TimeUnit.SECONDS.toMinutes(diff) * 60); if (day == 0) { if (hours == 0) { if (minute == 0) { timediff = second + " S ago"; } else { timediff = minute + " M ago"; } } else { timediff = hours + " H ago"; } } else { timediff = day + " D ago"; } map.put("time", timediff); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } //// ///////// adding region///////// /////////////////// String location; JSONObject obj2 = null; try { obj2 = obj1.getJSONObject("properties"); String region = obj2.getString("$region"); String country = obj2.getString("mp_country_code"); location = region + "," + country; } catch (Exception e) { if (obj2.has("mp_country_code")) { location = obj2.getString("mp_country_code"); } else { location = "N/A"; } e.printStackTrace(); } map.put("location", location); ///////////////////// live_list.add(map); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } /////////// updateing data into list ListAdapter temp = null; setListAdapter(temp); Collections.reverse(live_list); // reversing the order of list adapter = new SimpleAdapter( this, live_list, R.layout.list_live_first, new String[] {"name", "time", "location", "fulldata"}, new int[] {R.id.live_name, R.id.live_time, R.id.live_location}); setadapter(); }
public int getHeartbeatIntervalInMinutes() { return (int) TimeUnit.SECONDS.toMinutes(heartbeatInterval); }
private void scheduleAndPrintTime(int delay) { long minutes = TimeUnit.SECONDS.toMinutes(remainingTime); String msg = String.format(format, minutes, remainingTime % 60); sendTimeMessage(getCurrentColor() + msg); schedule(delay); }
public String getDuration() { String s = String.format("%d", TimeUnit.SECONDS.toMinutes(this.duration / 60)); return s; }
/** * Normalize a time to be displayed in mm:ss format * * @param time The time to normalize * @return The normalized time */ private String normalizeTime(int time) { long minutes = TimeUnit.SECONDS.toMinutes(time); long seconds = time - minutes * 60; return String.format("%02d:%02d", minutes, seconds); }