idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
26,400 | private static Map < String , Object > parseAlData ( JSONArray dataArray ) throws JSONException { HashMap < String , Object > al = new HashMap < String , Object > ( ) ; for ( int i = 0 ; i < dataArray . length ( ) ; i ++ ) { JSONObject tag = dataArray . getJSONObject ( i ) ; String name = tag . getString ( "property" ) ; String [ ] nameComponents = name . split ( ":" ) ; if ( ! nameComponents [ 0 ] . equals ( META_TAG_PREFIX ) ) { continue ; } Map < String , Object > root = al ; for ( int j = 1 ; j < nameComponents . length ; j ++ ) { @ SuppressWarnings ( "unchecked" ) List < Map < String , Object > > children = ( List < Map < String , Object > > ) root . get ( nameComponents [ j ] ) ; if ( children == null ) { children = new ArrayList < Map < String , Object > > ( ) ; root . put ( nameComponents [ j ] , children ) ; } Map < String , Object > child = children . size ( ) > 0 ? children . get ( children . size ( ) - 1 ) : null ; if ( child == null || j == nameComponents . length - 1 ) { child = new HashMap < String , Object > ( ) ; children . add ( child ) ; } root = child ; } if ( tag . has ( "content" ) ) { if ( tag . isNull ( "content" ) ) { root . put ( KEY_AL_VALUE , null ) ; } else { root . put ( KEY_AL_VALUE , tag . getString ( "content" ) ) ; } } } return al ; } | Builds up a data structure filled with the app link data from the meta tags on a page . The structure of this object is a dictionary where each key holds an array of app link data dictionaries . Values are stored in a key called _value . | 385 | 51 |
26,401 | public void cancel ( ) { List < CancellationTokenRegistration > registrations ; synchronized ( lock ) { throwIfClosed ( ) ; if ( cancellationRequested ) { return ; } cancelScheduledCancellation ( ) ; cancellationRequested = true ; registrations = new ArrayList <> ( this . registrations ) ; } notifyListeners ( registrations ) ; } | Cancels the token if it has not already been cancelled . | 77 | 13 |
26,402 | @ Override public void close ( ) { synchronized ( lock ) { if ( closed ) { return ; } closed = true ; tokenSource . unregister ( this ) ; tokenSource = null ; action = null ; } } | Unregisters the callback runnable from the cancellation token . | 46 | 13 |
26,403 | public static ExecutorService newCachedThreadPool ( ) { ThreadPoolExecutor executor = new ThreadPoolExecutor ( CORE_POOL_SIZE , MAX_POOL_SIZE , KEEP_ALIVE_TIME , TimeUnit . SECONDS , new LinkedBlockingQueue < Runnable > ( ) ) ; allowCoreThreadTimeout ( executor , true ) ; return executor ; } | Creates a proper Cached Thread Pool . Tasks will reuse cached threads if available or create new threads until the core pool is full . tasks will then be queued . If an task cannot be queued a new thread will be created unless this would exceed max pool size then the task will be rejected . Threads will time out after 1 second . | 87 | 71 |
26,404 | public static Bundle getAppLinkExtras ( Intent intent ) { Bundle appLinkData = getAppLinkData ( intent ) ; if ( appLinkData == null ) { return null ; } return appLinkData . getBundle ( KEY_NAME_EXTRAS ) ; } | Gets the App Link extras for an intent if there is any . | 58 | 14 |
26,405 | public static Uri getTargetUrl ( Intent intent ) { Bundle appLinkData = getAppLinkData ( intent ) ; if ( appLinkData != null ) { String targetString = appLinkData . getString ( KEY_NAME_TARGET ) ; if ( targetString != null ) { return Uri . parse ( targetString ) ; } } return intent . getData ( ) ; } | Gets the target URL for an intent regardless of whether the intent is from an App Link . If the intent is from an App Link this will be the App Link target . Otherwise it will be the data Uri from the intent itself . | 80 | 47 |
26,406 | public static Uri getTargetUrlFromInboundIntent ( Context context , Intent intent ) { Bundle appLinkData = getAppLinkData ( intent ) ; if ( appLinkData != null ) { String targetString = appLinkData . getString ( KEY_NAME_TARGET ) ; if ( targetString != null ) { MeasurementEvent . sendBroadcastEvent ( context , MeasurementEvent . APP_LINK_NAVIGATE_IN_EVENT_NAME , intent , null ) ; return Uri . parse ( targetString ) ; } } return null ; } | Gets the target URL for an intent . If the intent is from an App Link this will be the App Link target . Otherwise it return null ; For app link intent this function will broadcast APP_LINK_NAVIGATE_IN_EVENT_NAME event . | 120 | 56 |
26,407 | private Bundle buildAppLinkDataForNavigation ( Context context ) { Bundle data = new Bundle ( ) ; Bundle refererAppLinkData = new Bundle ( ) ; if ( context != null ) { String refererAppPackage = context . getPackageName ( ) ; if ( refererAppPackage != null ) { refererAppLinkData . putString ( KEY_NAME_REFERER_APP_LINK_PACKAGE , refererAppPackage ) ; } ApplicationInfo appInfo = context . getApplicationInfo ( ) ; if ( appInfo != null ) { String refererAppName = context . getString ( appInfo . labelRes ) ; if ( refererAppName != null ) { refererAppLinkData . putString ( KEY_NAME_REFERER_APP_LINK_APP_NAME , refererAppName ) ; } } } data . putAll ( getAppLinkData ( ) ) ; data . putString ( AppLinks . KEY_NAME_TARGET , getAppLink ( ) . getSourceUrl ( ) . toString ( ) ) ; data . putString ( KEY_NAME_VERSION , VERSION ) ; data . putString ( KEY_NAME_USER_AGENT , "Bolts Android " + Bolts . VERSION ) ; data . putBundle ( KEY_NAME_REFERER_APP_LINK , refererAppLinkData ) ; data . putBundle ( AppLinks . KEY_NAME_EXTRAS , getExtras ( ) ) ; return data ; } | Creates a bundle containing the final constructed App Link data to be used in navigation . | 325 | 17 |
26,408 | private JSONObject getJSONForBundle ( Bundle bundle ) throws JSONException { JSONObject root = new JSONObject ( ) ; for ( String key : bundle . keySet ( ) ) { root . put ( key , getJSONValue ( bundle . get ( key ) ) ) ; } return root ; } | Gets a JSONObject equivalent to the input bundle for use when falling back to a web navigation . | 63 | 20 |
26,409 | public NavigationResult navigate ( Context context ) { PackageManager pm = context . getPackageManager ( ) ; Bundle finalAppLinkData = buildAppLinkDataForNavigation ( context ) ; Intent eligibleTargetIntent = null ; for ( AppLink . Target target : getAppLink ( ) . getTargets ( ) ) { Intent targetIntent = new Intent ( Intent . ACTION_VIEW ) ; if ( target . getUrl ( ) != null ) { targetIntent . setData ( target . getUrl ( ) ) ; } else { targetIntent . setData ( appLink . getSourceUrl ( ) ) ; } targetIntent . setPackage ( target . getPackageName ( ) ) ; if ( target . getClassName ( ) != null ) { targetIntent . setClassName ( target . getPackageName ( ) , target . getClassName ( ) ) ; } targetIntent . putExtra ( AppLinks . KEY_NAME_APPLINK_DATA , finalAppLinkData ) ; ResolveInfo resolved = pm . resolveActivity ( targetIntent , PackageManager . MATCH_DEFAULT_ONLY ) ; if ( resolved != null ) { eligibleTargetIntent = targetIntent ; break ; } } Intent outIntent = null ; NavigationResult result = NavigationResult . FAILED ; if ( eligibleTargetIntent != null ) { outIntent = eligibleTargetIntent ; result = NavigationResult . APP ; } else { // Fall back to the web if it's available Uri webUrl = getAppLink ( ) . getWebUrl ( ) ; if ( webUrl != null ) { JSONObject appLinkDataJson ; try { appLinkDataJson = getJSONForBundle ( finalAppLinkData ) ; } catch ( JSONException e ) { sendAppLinkNavigateEventBroadcast ( context , eligibleTargetIntent , NavigationResult . FAILED , e ) ; throw new RuntimeException ( e ) ; } webUrl = webUrl . buildUpon ( ) . appendQueryParameter ( AppLinks . KEY_NAME_APPLINK_DATA , appLinkDataJson . toString ( ) ) . build ( ) ; outIntent = new Intent ( Intent . ACTION_VIEW , webUrl ) ; result = NavigationResult . WEB ; } } sendAppLinkNavigateEventBroadcast ( context , outIntent , result , null ) ; if ( outIntent != null ) { context . startActivity ( outIntent ) ; } return result ; } | Performs the navigation . | 526 | 5 |
26,410 | public static void setRegistry ( Registry registry ) { SpectatorContext . registry = registry ; if ( registry instanceof NoopRegistry ) { initStacktrace = null ; } else { Exception cause = initStacktrace ; Exception e = new IllegalStateException ( "called SpectatorContext.setRegistry(" + registry . getClass ( ) . getName ( ) + ")" , cause ) ; e . fillInStackTrace ( ) ; initStacktrace = e ; if ( cause != null ) { LOGGER . warn ( "Registry used with Servo's SpectatorContext has been overwritten. This could " + "result in missing metrics." , e ) ; } } } | Set the registry to use . By default it will use the NoopRegistry . | 144 | 17 |
26,411 | public static LazyGauge gauge ( MonitorConfig config ) { return new LazyGauge ( Registry :: gauge , registry , createId ( config ) ) ; } | Create a gauge based on the config . | 36 | 8 |
26,412 | public static LazyGauge maxGauge ( MonitorConfig config ) { return new LazyGauge ( Registry :: maxGauge , registry , createId ( config ) ) ; } | Create a max gauge based on the config . | 42 | 9 |
26,413 | public static Id createId ( MonitorConfig config ) { // Need to ensure that Servo type tag is removed to avoid incorrectly reprocessing the // data in later transforms Map < String , String > tags = new HashMap <> ( config . getTags ( ) . asMap ( ) ) ; tags . remove ( "type" ) ; return registry . createId ( config . getName ( ) ) . withTags ( tags ) ; } | Convert servo config to spectator id . | 91 | 9 |
26,414 | public static PolledMeter . Builder polledGauge ( MonitorConfig config ) { long delayMillis = Math . max ( Pollers . getPollingIntervals ( ) . get ( 0 ) - 1000 , 5000 ) ; Id id = createId ( config ) ; PolledMeter . remove ( registry , id ) ; return PolledMeter . using ( registry ) . withId ( id ) . withDelay ( Duration . ofMillis ( delayMillis ) ) . scheduleOn ( gaugePool ( ) ) ; } | Create builder for a polled gauge based on the config . | 112 | 11 |
26,415 | public static void register ( Monitor < ? > monitor ) { if ( monitor instanceof SpectatorMonitor ) { ( ( SpectatorMonitor ) monitor ) . initializeSpectator ( BasicTagList . EMPTY ) ; } else if ( ! isEmptyComposite ( monitor ) ) { ServoMeter m = new ServoMeter ( monitor ) ; PolledMeter . remove ( registry , m . id ( ) ) ; PolledMeter . monitorMeter ( registry , m ) ; monitorMonitonicValues ( monitor ) ; } } | Register a custom monitor . | 114 | 5 |
26,416 | public static AmazonCloudWatch cloudWatch ( AWSCredentialsProvider credentials ) { AmazonCloudWatch client = new AmazonCloudWatchClient ( credentials ) ; client . setEndpoint ( System . getProperty ( AwsPropertyKeys . AWS_CLOUD_WATCH_END_POINT . getBundle ( ) , "monitoring.amazonaws.com" ) ) ; return client ; } | Get a CloudWatch client whose endpoint is configured based on properties . | 81 | 13 |
26,417 | public static AmazonAutoScaling autoScaling ( AWSCredentials credentials ) { AmazonAutoScaling client = new AmazonAutoScalingClient ( credentials ) ; client . setEndpoint ( System . getProperty ( AwsPropertyKeys . AWS_AUTO_SCALING_END_POINT . getBundle ( ) , "autoscaling.amazonaws.com" ) ) ; return client ; } | Get an AutoScaling client whose endpoint is configured based on properties . | 86 | 14 |
26,418 | public static Stopwatch start ( MonitorConfig config , TimeUnit unit ) { return INSTANCE . get ( config , unit ) . start ( ) ; } | Returns a stopwatch that has been started and will automatically record its result to the dynamic timer specified by the given config . | 31 | 24 |
26,419 | public static Stopwatch start ( MonitorConfig config ) { return INSTANCE . get ( config , TimeUnit . MILLISECONDS ) . start ( ) ; } | Returns a stopwatch that has been started and will automatically record its result to the dynamic timer specified by the given config . The timer will report the times in milliseconds to observers . | 34 | 35 |
26,420 | public static void record ( MonitorConfig config , long duration ) { INSTANCE . get ( config , TimeUnit . MILLISECONDS ) . record ( duration , TimeUnit . MILLISECONDS ) ; } | Record result to the dynamic timer indicated by the provided config with a TimeUnit of milliseconds . | 45 | 18 |
26,421 | public static void record ( MonitorConfig config , long duration , TimeUnit unit ) { INSTANCE . get ( config , unit ) . record ( duration , unit ) ; } | Record a duration to the dynamic timer indicated by the provided config . The units in which the timer is reported and the duration unit are the same . | 35 | 29 |
26,422 | public static Stopwatch start ( String name , TagList list , TimeUnit unit ) { final MonitorConfig config = new MonitorConfig . Builder ( name ) . withTags ( list ) . build ( ) ; return INSTANCE . get ( config , unit ) . start ( ) ; } | Returns a stopwatch that has been started and will automatically record its result to the dynamic timer specified by the given config . The timer uses a TimeUnit of milliseconds . | 58 | 33 |
26,423 | @ Override public long getDuration ( ) { final long end = running . get ( ) ? System . nanoTime ( ) : endTime . get ( ) ; return end - startTime . get ( ) ; } | Returns the duration in nanoseconds . No checks are performed to ensure that the stopwatch has been properly started and stopped before executing this method . If called before stop it will return the current duration . | 45 | 41 |
26,424 | public static < T > Memoizer < T > create ( Callable < T > getter , long duration , TimeUnit unit ) { return new Memoizer <> ( getter , duration , unit ) ; } | Create a memoizer that caches the value produced by getter for a given duration . | 46 | 17 |
26,425 | public T get ( ) { long expiration = whenItExpires ; long now = System . nanoTime ( ) ; // if uninitialized or expired update value if ( expiration == 0 || now >= expiration ) { synchronized ( this ) { // ensure a different thread didn't update it if ( whenItExpires == expiration ) { whenItExpires = now + durationNanos ; try { value = getter . call ( ) ; } catch ( Exception e ) { // shouldn't happen throw Throwables . propagate ( e ) ; } } } } return value ; } | Get or refresh and return the latest value . | 117 | 9 |
26,426 | public void push ( List < Metric > rawMetrics ) { List < Metric > validMetrics = ValidCharacters . toValidValues ( filter ( rawMetrics ) ) ; List < Metric > metrics = transformMetrics ( validMetrics ) ; LOGGER . debug ( "Scheduling push of {} metrics" , metrics . size ( ) ) ; final UpdateTasks tasks = getUpdateTasks ( BasicTagList . EMPTY , identifyCountersForPush ( metrics ) ) ; final int maxAttempts = 5 ; int attempts = 1 ; while ( ! pushQueue . offer ( tasks ) && attempts <= maxAttempts ) { ++ attempts ; final UpdateTasks droppedTasks = pushQueue . remove ( ) ; LOGGER . warn ( "Removing old push task due to queue full. Dropping {} metrics." , droppedTasks . numMetrics ) ; numMetricsDroppedQueueFull . increment ( droppedTasks . numMetrics ) ; } if ( attempts >= maxAttempts ) { LOGGER . error ( "Unable to push update of {}" , tasks ) ; numMetricsDroppedQueueFull . increment ( tasks . numMetrics ) ; } else { LOGGER . debug ( "Queued push of {}" , tasks ) ; } } | Immediately send metrics to the backend . | 266 | 8 |
26,427 | protected Func1 < HttpClientResponse < ByteBuf > , Integer > withBookkeeping ( final int batchSize ) { return response -> { boolean ok = response . getStatus ( ) . code ( ) == 200 ; if ( ok ) { numMetricsSent . increment ( batchSize ) ; } else { LOGGER . info ( "Status code: {} - Lost {} metrics" , response . getStatus ( ) . code ( ) , batchSize ) ; numMetricsDroppedHttpErr . increment ( batchSize ) ; } return batchSize ; } ; } | Utility function to map an Observable< ; ByteBuf > to an Observable< ; Integer > while also updating our counters for metrics sent and errors . | 120 | 35 |
26,428 | public static ServoAtlasConfig getAtlasConfig ( ) { return new ServoAtlasConfig ( ) { @ Override public String getAtlasUri ( ) { return getAtlasObserverUri ( ) ; } @ Override public int getPushQueueSize ( ) { return 1000 ; } @ Override public boolean shouldSendMetrics ( ) { return isAtlasObserverEnabled ( ) ; } @ Override public int batchSize ( ) { return 10000 ; } } ; } | Get config for the atlas observer . | 105 | 8 |
26,429 | public static Set < Field > getAllFields ( Class < ? > classs ) { Set < Field > set = new HashSet <> ( ) ; Class < ? > c = classs ; while ( c != null ) { set . addAll ( Arrays . asList ( c . getDeclaredFields ( ) ) ) ; c = c . getSuperclass ( ) ; } return set ; } | Gets all fields from class and its super classes . | 87 | 11 |
26,430 | public static Set < Method > getAllMethods ( Class < ? > classs ) { Set < Method > set = new HashSet <> ( ) ; Class < ? > c = classs ; while ( c != null ) { set . addAll ( Arrays . asList ( c . getDeclaredMethods ( ) ) ) ; c = c . getSuperclass ( ) ; } return set ; } | Gets all methods from class and its super classes . | 85 | 11 |
26,431 | public static Set < Field > getFieldsAnnotatedBy ( Class < ? > classs , Class < ? extends Annotation > ann ) { Set < Field > set = new HashSet <> ( ) ; for ( Field field : getAllFields ( classs ) ) { if ( field . isAnnotationPresent ( ann ) ) { set . add ( field ) ; } } return set ; } | Gets all fields annotated by annotation . | 86 | 9 |
26,432 | public static Set < Method > getMethodsAnnotatedBy ( Class < ? > classs , Class < ? extends Annotation > ann ) { Set < Method > set = new HashSet <> ( ) ; for ( Method method : getAllMethods ( classs ) ) { if ( method . isAnnotationPresent ( ann ) ) { set . add ( method ) ; } } return set ; } | Gets all methods annotated by annotation . | 84 | 9 |
26,433 | protected M getMonitorForCurrentContext ( ) { MonitorConfig contextConfig = getConfig ( ) ; M monitor = monitors . get ( contextConfig ) ; if ( monitor == null ) { M newMon = newMonitor . apply ( contextConfig ) ; if ( newMon instanceof SpectatorMonitor ) { ( ( SpectatorMonitor ) newMon ) . initializeSpectator ( spectatorTags ) ; } monitor = monitors . putIfAbsent ( contextConfig , newMon ) ; if ( monitor == null ) { monitor = newMon ; } } return monitor ; } | Returns a monitor instance for the current context . If no monitor exists for the current context then a new one will be created . | 115 | 25 |
26,434 | static Tag internCustom ( Tag t ) { return ( t instanceof BasicTag ) ? t : newTag ( t . getKey ( ) , t . getValue ( ) ) ; } | Interns custom tag types assumes that basic tags are already interned . This is used to ensure that we have a common view of tags internally . In particular different subclasses of Tag may not be equal even if they have the same key and value . Tag lists should use this to ensure the equality will work as expected . | 39 | 64 |
26,435 | public static Tag newTag ( String key , String value ) { Tag newTag = new BasicTag ( intern ( key ) , intern ( value ) ) ; return intern ( newTag ) ; } | Create a new tag instance . | 40 | 6 |
26,436 | public String getTimeUnitAbbreviation ( ) { switch ( timeUnit ) { case DAYS : return "day" ; case HOURS : return "hr" ; case MICROSECONDS : return "\u00B5s" ; case MILLISECONDS : return "ms" ; case MINUTES : return "min" ; case NANOSECONDS : return "ns" ; case SECONDS : return "s" ; default : return "unkwn" ; } } | Returns an abbreviation for the Bucket s TimeUnit . | 107 | 11 |
26,437 | public synchronized void start ( ) { if ( ! running ) { running = true ; Thread t = new Thread ( new CpuStatRunnable ( ) , "ThreadCpuStatsCollector" ) ; t . setDaemon ( true ) ; t . start ( ) ; } } | Start collecting cpu stats for the threads . | 60 | 8 |
26,438 | public static String toDuration ( long inputTime ) { final long second = 1000000000L ; final long minute = 60 * second ; final long hour = 60 * minute ; final long day = 24 * hour ; final long week = 7 * day ; long time = inputTime ; final StringBuilder buf = new StringBuilder ( ) ; buf . append ( ' ' ) ; time = append ( buf , ' ' , week , time ) ; time = append ( buf , ' ' , day , time ) ; buf . append ( ' ' ) ; time = append ( buf , ' ' , hour , time ) ; time = append ( buf , ' ' , minute , time ) ; append ( buf , ' ' , second , time ) ; return buf . toString ( ) ; } | Convert time in nanoseconds to a duration string . This is used to provide a more human readable order of magnitude for the duration . We assume standard fixed size quantities for all units . | 161 | 39 |
26,439 | private void updateStats ( ) { final ThreadMXBean bean = ManagementFactory . getThreadMXBean ( ) ; if ( bean . isThreadCpuTimeEnabled ( ) ) { // Update stats for all current threads final long [ ] ids = bean . getAllThreadIds ( ) ; Arrays . sort ( ids ) ; long totalCpuTime = 0L ; for ( long id : ids ) { long cpuTime = bean . getThreadCpuTime ( id ) ; if ( cpuTime != - 1 ) { totalCpuTime += cpuTime ; CpuUsage usage = threadCpuUsages . get ( id ) ; if ( usage == null ) { final ThreadInfo info = bean . getThreadInfo ( id ) ; usage = new CpuUsage ( id , info . getThreadName ( ) ) ; threadCpuUsages . put ( id , usage ) ; } usage . update ( cpuTime ) ; } } // Update jvm cpu usage, if possible we query the operating system mxbean so we get // an accurate total including any threads that may have been started and stopped // between sampling. As a fallback we use the sum of the cpu time for all threads found // in this interval. // // Total cpu time can be found in: // http://docs.oracle.com/javase/7/docs/jre/api/management/extension/\ // com/sun/management/OperatingSystemMXBean.html // // We use reflection to avoid direct dependency on com.sun.* classes. final OperatingSystemMXBean osBean = ManagementFactory . getOperatingSystemMXBean ( ) ; try { final Method m = osBean . getClass ( ) . getMethod ( "getProcessCpuTime" ) ; final long jvmCpuTime = ( Long ) m . invoke ( osBean ) ; jvmCpuUsage . update ( ( jvmCpuTime < 0 ) ? totalCpuTime : jvmCpuTime ) ; } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e ) { jvmCpuUsage . update ( totalCpuTime ) ; } // Handle ids in the map that no longer exist: // * Remove old entries if the last update time is over AGE_LIMIT // * Otherwise, update usage so rolling window is correct final long now = System . currentTimeMillis ( ) ; final Iterator < Map . Entry < Long , CpuUsage > > iter = threadCpuUsages . entrySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { final Map . Entry < Long , CpuUsage > entry = iter . next ( ) ; final long id = entry . getKey ( ) ; final CpuUsage usage = entry . getValue ( ) ; if ( now - usage . getLastUpdateTime ( ) > AGE_LIMIT ) { iter . remove ( ) ; } else if ( Arrays . binarySearch ( ids , id ) < 0 ) { usage . updateNoValue ( ) ; } } } else { LOGGER . debug ( "ThreadMXBean.isThreadCpuTimeEnabled() == false, cannot collect stats" ) ; } } | Update the stats for all threads and the jvm . | 691 | 11 |
26,440 | public < T > T callWithTimeout ( Callable < T > callable , long duration , TimeUnit unit ) throws Exception { Future < T > future = executor . submit ( callable ) ; try { return future . get ( duration , unit ) ; } catch ( InterruptedException e ) { future . cancel ( true ) ; throw e ; } catch ( ExecutionException e ) { Throwable cause = e . getCause ( ) ; if ( cause == null ) { cause = e ; } if ( cause instanceof Exception ) { throw ( Exception ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } throw e ; } catch ( TimeoutException e ) { future . cancel ( true ) ; throw new UncheckedTimeoutException ( e ) ; } } | Invokes a specified Callable timing out after the specified time limit . If the target method call finished before the limit is reached the return value or exception is propagated to the caller exactly as - is . If on the other hand the time limit is reached we attempt to abort the call to the Callable and throw an exception . | 165 | 66 |
26,441 | public static Timer newTimer ( String name , TimeUnit unit ) { return new BasicTimer ( MonitorConfig . builder ( name ) . build ( ) , unit ) ; } | Create a new timer with only the name specified . | 36 | 10 |
26,442 | public static Counter newCounter ( String name , TaggingContext context ) { final MonitorConfig config = MonitorConfig . builder ( name ) . build ( ) ; return new ContextualCounter ( config , context , COUNTER_FUNCTION ) ; } | Create a new counter with a name and context . The returned counter will maintain separate sub - monitors for each distinct set of tags returned from the context on an update operation . | 51 | 34 |
26,443 | public static CompositeMonitor < ? > newObjectMonitor ( String id , Object obj ) { final TagList tags = getMonitorTags ( obj ) ; List < Monitor < ? > > monitors = new ArrayList <> ( ) ; addMonitors ( monitors , id , tags , obj ) ; final Class < ? > c = obj . getClass ( ) ; final String objectId = ( id == null ) ? DEFAULT_ID : id ; return new BasicCompositeMonitor ( newObjectConfig ( c , objectId , tags ) , monitors ) ; } | Helper function to easily create a composite for all monitor fields and annotated attributes of a given object . | 116 | 20 |
26,444 | public static CompositeMonitor < ? > newThreadPoolMonitor ( String id , ThreadPoolExecutor pool ) { return newObjectMonitor ( id , new MonitoredThreadPool ( pool ) ) ; } | Creates a new monitor for a thread pool with standard metrics for the pool size queue size task counts etc . | 40 | 22 |
26,445 | public static CompositeMonitor < ? > newCacheMonitor ( String id , Cache < ? , ? > cache ) { return newObjectMonitor ( id , new MonitoredCache ( cache ) ) ; } | Creates a new monitor for a cache with standard metrics for the hits misses and loads . | 40 | 18 |
26,446 | public static boolean isObjectRegistered ( String id , Object obj ) { return DefaultMonitorRegistry . getInstance ( ) . isRegistered ( newObjectMonitor ( id , obj ) ) ; } | Check whether an object is currently registered with the default registry . | 39 | 12 |
26,447 | @ SuppressWarnings ( "unchecked" ) static < T > Monitor < T > wrap ( TagList tags , Monitor < T > monitor ) { Monitor < T > m ; if ( monitor instanceof CompositeMonitor < ? > ) { m = new CompositeMonitorWrapper <> ( tags , ( CompositeMonitor < T > ) monitor ) ; } else { m = MonitorWrapper . create ( tags , monitor ) ; } return m ; } | Returns a new monitor that adds the provided tags to the configuration returned by the wrapped monitor . | 94 | 18 |
26,448 | static void addMonitors ( List < Monitor < ? > > monitors , String id , TagList tags , Object obj ) { addMonitorFields ( monitors , id , tags , obj ) ; addAnnotatedFields ( monitors , id , tags , obj ) ; } | Extract all monitors across class hierarchy . | 57 | 8 |
26,449 | private static TagList getMonitorTags ( Object obj ) { try { Set < Field > fields = getFieldsAnnotatedBy ( obj . getClass ( ) , MonitorTags . class ) ; for ( Field field : fields ) { field . setAccessible ( true ) ; return ( TagList ) field . get ( obj ) ; } Set < Method > methods = getMethodsAnnotatedBy ( obj . getClass ( ) , MonitorTags . class ) ; for ( Method method : methods ) { method . setAccessible ( true ) ; return ( TagList ) method . invoke ( obj ) ; } } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } return null ; } | Get tags from annotation . | 148 | 5 |
26,450 | private static void checkType ( com . netflix . servo . annotations . Monitor anno , Class < ? > type , Class < ? > container ) { if ( ! isNumericType ( type ) ) { final String msg = "annotation of type " + anno . type ( ) . name ( ) + " can only be used" + " with numeric values, " + anno . name ( ) + " in class " + container . getName ( ) + " is applied to a field or method of type " + type . getName ( ) ; throw new IllegalArgumentException ( msg ) ; } } | Verify that the type for the annotated field is numeric . | 131 | 13 |
26,451 | private static MonitorConfig newObjectConfig ( Class < ? > c , String id , TagList tags ) { final MonitorConfig . Builder builder = MonitorConfig . builder ( id ) ; final String className = className ( c ) ; if ( ! className . isEmpty ( ) ) { builder . withTag ( "class" , className ) ; } if ( tags != null ) { builder . withTags ( tags ) ; } return builder . build ( ) ; } | Creates a monitor config for a composite object . | 98 | 10 |
26,452 | private static MonitorConfig newConfig ( Class < ? > c , String defaultName , String id , com . netflix . servo . annotations . Monitor anno , TagList tags ) { String name = anno . name ( ) ; if ( name . isEmpty ( ) ) { name = defaultName ; } MonitorConfig . Builder builder = MonitorConfig . builder ( name ) ; builder . withTag ( "class" , className ( c ) ) ; builder . withTag ( anno . type ( ) ) ; builder . withTag ( anno . level ( ) ) ; if ( tags != null ) { builder . withTags ( tags ) ; } if ( id != null ) { builder . withTag ( "id" , id ) ; } return builder . build ( ) ; } | Creates a monitor config based on an annotation . | 165 | 10 |
26,453 | public void stop ( ) { try { if ( socket != null ) { socket . close ( ) ; socket = null ; LOGGER . info ( "Disconnected from graphite server: {}" , graphiteServerURI ) ; } } catch ( IOException e ) { LOGGER . warn ( "Error Stopping" , e ) ; } } | Stop sending metrics to the graphite server . | 72 | 9 |
26,454 | public Tag get ( String key ) { int idx = binarySearch ( tagArray , key ) ; if ( idx < 0 ) { return null ; } else { return tagArray [ idx ] ; } } | Get the tag associated with a given key . | 45 | 9 |
26,455 | public void record ( long n ) { values [ Integer . remainderUnsigned ( pos ++ , size ) ] = n ; if ( curSize < size ) { ++ curSize ; } } | Record a new value for this buffer . | 39 | 8 |
26,456 | public void computeStats ( ) { if ( statsComputed . getAndSet ( true ) ) { return ; } if ( curSize == 0 ) { return ; } Arrays . sort ( values , 0 , curSize ) ; // to compute percentileValues min = values [ 0 ] ; max = values [ curSize - 1 ] ; total = 0L ; double sumSquares = 0.0 ; for ( int i = 0 ; i < curSize ; ++ i ) { total += values [ i ] ; sumSquares += values [ i ] * values [ i ] ; } mean = ( double ) total / curSize ; if ( curSize == 1 ) { variance = 0d ; } else { variance = ( sumSquares - ( ( double ) total * total / curSize ) ) / ( curSize - 1 ) ; } stddev = Math . sqrt ( variance ) ; computePercentiles ( curSize ) ; } | Compute stats for the current set of values . | 197 | 10 |
26,457 | Double truncate ( Number numberValue ) { // http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html double doubleValue = numberValue . doubleValue ( ) ; if ( truncateEnabled ) { final int exponent = Math . getExponent ( doubleValue ) ; if ( Double . isNaN ( doubleValue ) ) { doubleValue = 0.0 ; } else if ( exponent >= MAX_EXPONENT ) { doubleValue = ( doubleValue < 0.0 ) ? - MAX_VALUE : MAX_VALUE ; } else if ( exponent <= MIN_EXPONENT ) { doubleValue = 0.0 ; } } return doubleValue ; } | Adjust a double value so it can be successfully written to cloudwatch . This involves capping values with large exponents to an experimentally determined max value and converting values with large negative exponents to 0 . In addition NaN values will be converted to 0 . | 155 | 52 |
26,458 | public static Metric toValidValue ( Metric metric ) { MonitorConfig cfg = metric . getConfig ( ) ; MonitorConfig . Builder cfgBuilder = MonitorConfig . builder ( toValidCharset ( cfg . getName ( ) ) ) ; for ( Tag orig : cfg . getTags ( ) ) { final String key = orig . getKey ( ) ; if ( RELAXED_GROUP_KEYS . contains ( key ) ) { cfgBuilder . withTag ( key , toValidCharsetTable ( CHARS_ALLOWED_GROUPS , orig . getValue ( ) ) ) ; } else { cfgBuilder . withTag ( toValidCharset ( key ) , toValidCharset ( orig . getValue ( ) ) ) ; } } cfgBuilder . withPublishingPolicy ( cfg . getPublishingPolicy ( ) ) ; return new Metric ( cfgBuilder . build ( ) , metric . getTimestamp ( ) , metric . getValue ( ) ) ; } | Return a new metric where the name and all tags are using the valid character set . | 218 | 17 |
26,459 | public static List < Metric > toValidValues ( List < Metric > metrics ) { return metrics . stream ( ) . map ( ValidCharacters :: toValidValue ) . collect ( Collectors . toList ( ) ) ; } | Create a new list of metrics where all metrics are using the valid character set . | 48 | 16 |
26,460 | public static void tagToJson ( JsonGenerator gen , Tag tag ) throws IOException { final String key = tag . getKey ( ) ; if ( RELAXED_GROUP_KEYS . contains ( key ) ) { gen . writeStringField ( key , toValidCharsetTable ( CHARS_ALLOWED_GROUPS , tag . getValue ( ) ) ) ; } else { gen . writeStringField ( toValidCharset ( tag . getKey ( ) ) , toValidCharset ( tag . getValue ( ) ) ) ; } } | Serialize a tag to the given JsonGenerator . | 124 | 12 |
26,461 | public void record ( long measurement ) { lastUsed = clock . now ( ) ; if ( isExpired ( ) ) { LOGGER . info ( "Attempting to get the value for an expired monitor: {}." + "Will start computing stats again." , getConfig ( ) . getName ( ) ) ; startComputingStats ( executor , statsConfig . getFrequencyMillis ( ) ) ; } synchronized ( updateLock ) { cur . record ( measurement ) ; } count . increment ( ) ; totalMeasurement . increment ( measurement ) ; } | Record the measurement we want to perform statistics on . | 116 | 10 |
26,462 | @ Override public Long getValue ( int pollerIndex ) { final long n = getCount ( pollerIndex ) ; return n > 0 ? totalMeasurement . getValue ( pollerIndex ) . longValue ( ) / n : 0L ; } | Get the value of the measurement . | 54 | 7 |
26,463 | public List < V > values ( ) { final Collection < Entry < V > > values = map . values ( ) ; // Note below that e.value avoids updating the access time final List < V > res = values . stream ( ) . map ( e -> e . value ) . collect ( Collectors . toList ( ) ) ; return Collections . unmodifiableList ( res ) ; } | Get the list of all values that are members of this cache . Does not affect the access time used for eviction . | 82 | 23 |
26,464 | public void addPoller ( PollRunnable task , long delay , TimeUnit timeUnit ) { ScheduledExecutorService service = executor . get ( ) ; if ( service != null ) { service . scheduleWithFixedDelay ( task , 0 , delay , timeUnit ) ; } else { throw new IllegalStateException ( "you must start the scheduler before tasks can be submitted" ) ; } } | Add a tasks to execute at a fixed rate based on the provided delay . | 86 | 15 |
26,465 | public void start ( ) { int numThreads = Runtime . getRuntime ( ) . availableProcessors ( ) ; ThreadFactory factory = ThreadFactories . withName ( "ServoPollScheduler-%d" ) ; start ( Executors . newScheduledThreadPool ( numThreads , factory ) ) ; } | Start scheduling tasks with a default thread pool sized based on the number of available processors . | 70 | 17 |
26,466 | public void stop ( ) { ScheduledExecutorService service = executor . get ( ) ; if ( service != null && executor . compareAndSet ( service , null ) ) { service . shutdown ( ) ; } else { throw new IllegalStateException ( "scheduler must be started before you stop it" ) ; } } | Stop the poller shutting down the current executor service . | 70 | 12 |
26,467 | public static String join ( String separator , Iterator < ? > parts ) { Preconditions . checkNotNull ( separator , "separator" ) ; Preconditions . checkNotNull ( parts , "parts" ) ; StringBuilder builder = new StringBuilder ( ) ; if ( parts . hasNext ( ) ) { builder . append ( parts . next ( ) . toString ( ) ) ; while ( parts . hasNext ( ) ) { builder . append ( separator ) ; builder . append ( parts . next ( ) . toString ( ) ) ; } } return builder . toString ( ) ; } | Join the string representation of each part separated by the given separator string . | 130 | 15 |
26,468 | public static < T > T checkNotNull ( T obj , String name ) { if ( obj == null ) { String msg = String . format ( "parameter '%s' cannot be null" , name ) ; throw new NullPointerException ( msg ) ; } return obj ; } | Ensures the object reference is not null . | 61 | 10 |
26,469 | public void update ( long v ) { for ( int i = 0 ; i < Pollers . NUM_POLLERS ; ++ i ) { updateMin ( i , v ) ; } } | Update the min if the provided value is smaller than the current min . | 40 | 14 |
26,470 | public long getCurrentValue ( int nth ) { long v = min . getCurrent ( nth ) . get ( ) ; return ( v == Long . MAX_VALUE ) ? 0L : v ; } | Returns the current min value since the last reset . | 44 | 10 |
26,471 | public List < List < Metric > > getObservations ( ) { List < List < Metric >> builder = new ArrayList <> ( ) ; int pos = next ; for ( List < Metric > ignored : observations ) { if ( observations [ pos ] != null ) { builder . add ( observations [ pos ] ) ; } pos = ( pos + 1 ) % observations . length ; } return Collections . unmodifiableList ( builder ) ; } | Returns the current set of observations . | 96 | 7 |
26,472 | private MonitorConfig . Builder copy ( ) { return MonitorConfig . builder ( name ) . withTags ( tags ) . withPublishingPolicy ( policy ) ; } | Returns a copy of the current MonitorConfig . | 33 | 9 |
26,473 | public void update ( long v ) { spectatorGauge . set ( v ) ; for ( int i = 0 ; i < Pollers . NUM_POLLERS ; ++ i ) { updateMax ( i , v ) ; } } | Update the max if the provided value is larger than the current max . | 50 | 14 |
26,474 | public int sendAll ( Iterable < Observable < Integer > > batches , final int numMetrics , long timeoutMillis ) { final AtomicBoolean err = new AtomicBoolean ( false ) ; final AtomicInteger updated = new AtomicInteger ( 0 ) ; LOGGER . debug ( "Got {} ms to send {} metrics" , timeoutMillis , numMetrics ) ; try { final CountDownLatch completed = new CountDownLatch ( 1 ) ; final Subscription s = Observable . mergeDelayError ( Observable . from ( batches ) ) . timeout ( timeoutMillis , TimeUnit . MILLISECONDS ) . subscribeOn ( Schedulers . immediate ( ) ) . subscribe ( updated :: addAndGet , exc -> { logErr ( "onError caught" , exc , updated . get ( ) , numMetrics ) ; err . set ( true ) ; completed . countDown ( ) ; } , completed :: countDown ) ; try { completed . await ( timeoutMillis , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException interrupted ) { err . set ( true ) ; s . unsubscribe ( ) ; LOGGER . warn ( "Timed out sending metrics. {}/{} sent" , updated . get ( ) , numMetrics ) ; } } catch ( Exception e ) { err . set ( true ) ; logErr ( "Unexpected " , e , updated . get ( ) , numMetrics ) ; } if ( updated . get ( ) < numMetrics && ! err . get ( ) ) { LOGGER . warn ( "No error caught, but only {}/{} sent." , updated . get ( ) , numMetrics ) ; } return updated . get ( ) ; } | Attempt to send all the batches totalling numMetrics in the allowed time . | 372 | 16 |
26,475 | public Response get ( HttpClientRequest < ByteBuf > req , long timeout , TimeUnit timeUnit ) { final String uri = req . getUri ( ) ; final Response result = new Response ( ) ; try { final Func1 < HttpClientResponse < ByteBuf > , Observable < byte [ ] > > process = response -> { result . status = response . getStatus ( ) . code ( ) ; result . headers = response . getHeaders ( ) ; final Func2 < ByteArrayOutputStream , ByteBuf , ByteArrayOutputStream > accumulator = ( baos , bb ) -> { try { bb . readBytes ( baos , bb . readableBytes ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return baos ; } ; return response . getContent ( ) . reduce ( new ByteArrayOutputStream ( ) , accumulator ) . map ( ByteArrayOutputStream :: toByteArray ) ; } ; result . body = rxHttp . submit ( req ) . flatMap ( process ) . subscribeOn ( Schedulers . io ( ) ) . toBlocking ( ) . toFuture ( ) . get ( timeout , timeUnit ) ; return result ; } catch ( Exception e ) { throw new RuntimeException ( "failed to get url: " + uri , e ) ; } } | Perform an HTTP get in the allowed time . | 294 | 10 |
26,476 | public static void increment ( String name , TagList list ) { final MonitorConfig config = new MonitorConfig . Builder ( name ) . withTags ( list ) . build ( ) ; increment ( config ) ; } | Increment the counter for a given name tagList . | 43 | 11 |
26,477 | public static void increment ( String name , TagList list , long delta ) { final MonitorConfig config = MonitorConfig . builder ( name ) . withTags ( list ) . build ( ) ; increment ( config , delta ) ; } | Increment the counter for a given name tagList by a given delta . | 47 | 15 |
26,478 | @ Override public Collection < Monitor < ? > > getRegisteredMonitors ( ) { if ( updatePending . getAndSet ( false ) ) { monitorList . set ( UnmodifiableList . copyOf ( monitors . values ( ) ) ) ; } return monitorList . get ( ) ; } | The set of registered Monitor objects . | 63 | 7 |
26,479 | public void set ( Long n ) { spectatorGauge . set ( n ) ; AtomicLong number = getNumber ( ) ; number . set ( n ) ; } | Set the current value . | 35 | 5 |
26,480 | public Long getCount ( int pollerIndex ) { long updates = 0 ; for ( Counter c : bucketCount ) { updates += c . getValue ( pollerIndex ) . longValue ( ) ; } updates += overflowCount . getValue ( pollerIndex ) . longValue ( ) ; return updates ; } | Get the total number of updates . | 65 | 7 |
26,481 | private TagList createTagList ( ObjectName name ) { Map < String , String > props = name . getKeyPropertyList ( ) ; SmallTagMap . Builder tagsBuilder = SmallTagMap . builder ( ) ; for ( Map . Entry < String , String > e : props . entrySet ( ) ) { String key = PROP_KEY_PREFIX + "." + e . getKey ( ) ; tagsBuilder . add ( Tags . newTag ( key , e . getValue ( ) ) ) ; } tagsBuilder . add ( Tags . newTag ( DOMAIN_KEY , name . getDomain ( ) ) ) ; tagsBuilder . add ( CLASS_TAG ) ; if ( defaultTags != null ) { defaultTags . forEach ( tagsBuilder :: add ) ; } return new BasicTagList ( tagsBuilder . result ( ) ) ; } | Creates a tag list from an object name . | 179 | 10 |
26,482 | private void addMetric ( List < Metric > metrics , String name , TagList tags , Object value ) { long now = System . currentTimeMillis ( ) ; if ( onlyNumericMetrics ) { value = asNumber ( value ) ; } if ( value != null ) { TagList newTags = counters . matches ( MonitorConfig . builder ( name ) . withTags ( tags ) . build ( ) ) ? getTagListWithAdditionalTag ( tags , DataSourceType . COUNTER ) : getTagListWithAdditionalTag ( tags , DataSourceType . GAUGE ) ; Metric m = new Metric ( name , newTags , now , value ) ; metrics . add ( m ) ; } } | Create a new metric object and add it to the list . | 150 | 12 |
26,483 | private static Number asNumber ( Object value ) { Number num = null ; if ( value == null ) { num = null ; } else if ( value instanceof Number ) { num = ( Number ) value ; } else if ( value instanceof Boolean ) { num = ( ( Boolean ) value ) ? 1 : 0 ; } return num ; } | Try to convert an object into a number . Boolean values will return 1 if true and 0 if false . If the value is null or an unknown data type null will be returned . | 71 | 36 |
26,484 | public static void set ( String name , double value ) { set ( MonitorConfig . builder ( name ) . build ( ) , value ) ; } | Increment a gauge specified by a name . | 30 | 9 |
26,485 | public static void set ( String name , TagList list , double value ) { final MonitorConfig config = MonitorConfig . builder ( name ) . withTags ( list ) . build ( ) ; set ( config , value ) ; } | Set the gauge for a given name tagList by a given value . | 47 | 14 |
26,486 | private static String join ( long [ ] a ) { assert ( a . length > 0 ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( a [ 0 ] ) ; for ( int i = 1 ; i < a . length ; ++ i ) { builder . append ( ' ' ) ; builder . append ( a [ i ] ) ; } return builder . toString ( ) ; } | For debugging . Simple toString for non - empty arrays | 85 | 11 |
26,487 | static long [ ] parse ( String pollers ) { String [ ] periods = pollers . split ( ",\\s*" ) ; long [ ] result = new long [ periods . length ] ; boolean errors = false ; Logger logger = LoggerFactory . getLogger ( Pollers . class ) ; for ( int i = 0 ; i < periods . length ; ++ i ) { String period = periods [ i ] ; try { result [ i ] = Long . parseLong ( period ) ; if ( result [ i ] <= 0 ) { logger . error ( "Invalid polling interval: {} must be positive." , period ) ; errors = true ; } } catch ( NumberFormatException e ) { logger . error ( "Cannot parse '{}' as a long: {}" , period , e . getMessage ( ) ) ; errors = true ; } } if ( errors || periods . length == 0 ) { logger . info ( "Using a default configuration for poller intervals: {}" , join ( DEFAULT_PERIODS ) ) ; return DEFAULT_PERIODS ; } else { return result ; } } | Parse the content of the system property that describes the polling intervals and in case of errors use the default of one poller running every minute . | 238 | 29 |
26,488 | private List < Container > filterByVolumeAndWeight ( List < Box > boxes , List < Container > containers , int count ) { long volume = 0 ; long minVolume = Long . MAX_VALUE ; long weight = 0 ; long minWeight = Long . MAX_VALUE ; for ( Box box : boxes ) { // volume long boxVolume = box . getVolume ( ) ; volume += boxVolume ; if ( boxVolume < minVolume ) { minVolume = boxVolume ; } // weight long boxWeight = box . getWeight ( ) ; weight += boxWeight ; if ( boxWeight < minWeight ) { minWeight = boxWeight ; } } long maxVolume = Long . MIN_VALUE ; long maxWeight = Long . MIN_VALUE ; for ( Container container : containers ) { // volume long boxVolume = container . getVolume ( ) ; if ( boxVolume > maxVolume ) { maxVolume = boxVolume ; } // weight long boxWeight = container . getWeight ( ) ; if ( boxWeight > maxWeight ) { maxWeight = boxWeight ; } } if ( maxVolume * count < volume || maxWeight * count < weight ) { // no containers will work at current count return Collections . emptyList ( ) ; } List < Container > list = new ArrayList <> ( containers . size ( ) ) ; for ( Container container : containers ) { if ( container . getVolume ( ) < minVolume || container . getWeight ( ) < minWeight ) { // this box cannot even fit a single box continue ; } if ( container . getVolume ( ) + maxVolume * ( count - 1 ) < volume || container . getWeight ( ) + maxWeight * ( count - 1 ) < weight ) { // this box cannot be used even together with all biggest boxes continue ; } if ( count == 1 ) { if ( ! canHoldAll ( container , boxes ) ) { continue ; } } else { if ( ! canHoldAtLeastOne ( container , boxes ) ) { continue ; } } list . add ( container ) ; } return list ; } | Return a list of containers which can potentially hold the boxes . | 429 | 12 |
26,489 | public Box rotate3D ( ) { int height = this . height ; this . height = width ; this . width = depth ; this . depth = height ; return this ; } | Rotate box i . e . in 3D | 37 | 10 |
26,490 | boolean fitRotate2D ( Dimension dimension ) { if ( dimension . getHeight ( ) < height ) { return false ; } return fitRotate2D ( dimension . getWidth ( ) , dimension . getDepth ( ) ) ; } | Rotate box within a free space in 2D | 51 | 10 |
26,491 | protected int isBetter2D ( Box a , Box b ) { int compare = Long . compare ( a . getVolume ( ) , b . getVolume ( ) ) ; if ( compare != 0 ) { return compare ; } return Long . compare ( b . getFootprint ( ) , a . getFootprint ( ) ) ; // i.e. smaller i better } | Is box b better than a? | 78 | 7 |
26,492 | protected int isBetter3D ( Box a , Box b , Space space ) { int compare = Long . compare ( a . getVolume ( ) , b . getVolume ( ) ) ; if ( compare != 0 ) { return compare ; } // determine lowest fit a . fitRotate3DSmallestFootprint ( space ) ; b . fitRotate3DSmallestFootprint ( space ) ; return Long . compare ( b . getFootprint ( ) , a . getFootprint ( ) ) ; // i.e. smaller i better } | Is box b strictly better than a? | 117 | 8 |
26,493 | public void removePermutations ( List < Integer > removed ) { int [ ] permutations = new int [ this . permutations . length ] ; int index = 0 ; permutations : for ( int j : this . permutations ) { for ( int i = 0 ; i < removed . size ( ) ; i ++ ) { if ( removed . get ( i ) == j ) { // skip this removed . remove ( i ) ; continue permutations ; } } permutations [ index ] = j ; index ++ ; } int [ ] effectivePermutations = new int [ index ] ; System . arraycopy ( permutations , 0 , effectivePermutations , 0 , index ) ; this . rotations = new int [ permutations . length ] ; this . reset = new int [ permutations . length ] ; this . permutations = effectivePermutations ; Arrays . sort ( permutations ) ; // ascending order to make the permutation logic work } | Remove permutations if present . | 200 | 6 |
26,494 | public Dimension getFreeLevelSpace ( ) { int remainder = height - getStackHeight ( ) ; if ( remainder < 0 ) { throw new IllegalArgumentException ( "Remaining free space is negative at " + remainder + " for " + this ) ; } return new Dimension ( width , depth , remainder ) ; } | Get the free level space i . e . container height with height of levels subtracted . | 66 | 18 |
26,495 | public void process ( List < Point3D_F64 > worldPts , List < Point2D_F64 > observed , Se3_F64 solutionModel ) { if ( worldPts . size ( ) < 4 ) throw new IllegalArgumentException ( "Must provide at least 4 points" ) ; if ( worldPts . size ( ) != observed . size ( ) ) throw new IllegalArgumentException ( "Must have the same number of observations and world points" ) ; // select world control points using the points statistics selectWorldControlPoints ( worldPts , controlWorldPts ) ; // compute barycentric coordinates for the world control points computeBarycentricCoordinates ( controlWorldPts , alphas , worldPts ) ; // create the linear system whose null space will contain the camera control points constructM ( observed , alphas , M ) ; // the camera points are a linear combination of these null points extractNullPoints ( M ) ; // compute the full constraint matrix, the others are extracted from this if ( numControl == 4 ) { L_full . reshape ( 6 , 10 ) ; y . reshape ( 6 , 1 ) ; UtilLepetitEPnP . constraintMatrix6x10 ( L_full , y , controlWorldPts , nullPts ) ; // compute 4 solutions using the null points estimateCase1 ( solutions . get ( 0 ) ) ; estimateCase2 ( solutions . get ( 1 ) ) ; estimateCase3 ( solutions . get ( 2 ) ) ; // results are bad in general, so skip unless needed // always considering this case seems to hurt runtime speed a little bit if ( worldPts . size ( ) == 4 ) estimateCase4 ( solutions . get ( 3 ) ) ; } else { L_full . reshape ( 3 , 6 ) ; y . reshape ( 3 , 1 ) ; UtilLepetitEPnP . constraintMatrix3x6 ( L_full , y , controlWorldPts , nullPts ) ; estimateCase1 ( solutions . get ( 0 ) ) ; estimateCase2 ( solutions . get ( 1 ) ) ; if ( worldPts . size ( ) == 3 ) estimateCase3_planar ( solutions . get ( 2 ) ) ; } computeResultFromBest ( solutionModel ) ; } | Compute camera motion given a set of features with observations and 3D locations | 489 | 15 |
26,496 | private void computeResultFromBest ( Se3_F64 solutionModel ) { double bestScore = Double . MAX_VALUE ; int bestSolution = - 1 ; for ( int i = 0 ; i < numControl ; i ++ ) { double score = score ( solutions . get ( i ) ) ; if ( score < bestScore ) { bestScore = score ; bestSolution = i ; } // System.out.println(i+" score "+score); } double [ ] solution = solutions . get ( bestSolution ) ; if ( numIterations > 0 ) { gaussNewton ( solution ) ; } UtilLepetitEPnP . computeCameraControl ( solution , nullPts , solutionPts , numControl ) ; motionFit . process ( controlWorldPts . toList ( ) , solutionPts . toList ( ) ) ; solutionModel . set ( motionFit . getTransformSrcToDst ( ) ) ; } | Selects the best motion hypothesis based on the actual observations and optionally optimizes the solution . | 200 | 18 |
26,497 | private double score ( double betas [ ] ) { UtilLepetitEPnP . computeCameraControl ( betas , nullPts , solutionPts , numControl ) ; int index = 0 ; double score = 0 ; for ( int i = 0 ; i < numControl ; i ++ ) { Point3D_F64 si = solutionPts . get ( i ) ; Point3D_F64 wi = controlWorldPts . get ( i ) ; for ( int j = i + 1 ; j < numControl ; j ++ , index ++ ) { double ds = si . distance ( solutionPts . get ( j ) ) ; double dw = wi . distance ( controlWorldPts . get ( j ) ) ; score += ( ds - dw ) * ( ds - dw ) ; } } return score ; } | Score a solution based on distance between control points . Closer the camera control points are from the world control points the better the score . This is similar to how optimization score works and not the way recommended in the original paper . | 180 | 45 |
26,498 | public void selectWorldControlPoints ( List < Point3D_F64 > worldPts , FastQueue < Point3D_F64 > controlWorldPts ) { UtilPoint3D_F64 . mean ( worldPts , meanWorldPts ) ; // covariance matrix elements, summed up here for speed double c11 = 0 , c12 = 0 , c13 = 0 , c22 = 0 , c23 = 0 , c33 = 0 ; final int N = worldPts . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Point3D_F64 p = worldPts . get ( i ) ; double dx = p . x - meanWorldPts . x ; double dy = p . y - meanWorldPts . y ; double dz = p . z - meanWorldPts . z ; c11 += dx * dx ; c12 += dx * dy ; c13 += dx * dz ; c22 += dy * dy ; c23 += dy * dz ; c33 += dz * dz ; } c11 /= N ; c12 /= N ; c13 /= N ; c22 /= N ; c23 /= N ; c33 /= N ; DMatrixRMaj covar = new DMatrixRMaj ( 3 , 3 , true , c11 , c12 , c13 , c12 , c22 , c23 , c13 , c23 , c33 ) ; // find the data's orientation and check to see if it is planar svd . decompose ( covar ) ; double [ ] singularValues = svd . getSingularValues ( ) ; DMatrixRMaj V = svd . getV ( null , false ) ; SingularOps_DDRM . descendingOrder ( null , false , singularValues , 3 , V , false ) ; // planar check if ( singularValues [ 0 ] < singularValues [ 2 ] * 1e13 ) { numControl = 4 ; } else { numControl = 3 ; } // put control points along the data's major axises controlWorldPts . reset ( ) ; for ( int i = 0 ; i < numControl - 1 ; i ++ ) { double m = Math . sqrt ( singularValues [ 1 ] ) * magicNumber ; double vx = V . unsafe_get ( 0 , i ) * m ; double vy = V . unsafe_get ( 1 , i ) * m ; double vz = V . unsafe_get ( 2 , i ) * m ; controlWorldPts . grow ( ) . set ( meanWorldPts . x + vx , meanWorldPts . y + vy , meanWorldPts . z + vz ) ; } // set a control point to be the centroid controlWorldPts . grow ( ) . set ( meanWorldPts . x , meanWorldPts . y , meanWorldPts . z ) ; } | Selects control points along the data s axis and the data s centroid . If the data is determined to be planar then only 3 control points are selected . | 633 | 33 |
26,499 | protected static void constructM ( List < Point2D_F64 > obsPts , DMatrixRMaj alphas , DMatrixRMaj M ) { int N = obsPts . size ( ) ; M . reshape ( 3 * alphas . numCols , 2 * N , false ) ; for ( int i = 0 ; i < N ; i ++ ) { Point2D_F64 p2 = obsPts . get ( i ) ; int row = i * 2 ; for ( int j = 0 ; j < alphas . numCols ; j ++ ) { int col = j * 3 ; double alpha = alphas . unsafe_get ( i , j ) ; M . unsafe_set ( col , row , alpha ) ; M . unsafe_set ( col + 1 , row , 0 ) ; M . unsafe_set ( col + 2 , row , - alpha * p2 . x ) ; M . unsafe_set ( col , row + 1 , 0 ) ; M . unsafe_set ( col + 1 , row + 1 , alpha ) ; M . unsafe_set ( col + 2 , row + 1 , - alpha * p2 . y ) ; } } } | Constructs the linear system which is to be solved . | 256 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.