idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
7,500
@ Nonnull public final HCOutput setFor ( @ Nullable final IHCHasID < ? > aFor ) { if ( aFor == null ) m_sFor = null ; else m_sFor = aFor . ensureID ( ) . getID ( ) ; return this ; }
Specifies the relationship between the result of the calculation and the elements used in the calculation
63
17
7,501
@ Override public void visitLdcInsn ( Object cst ) { // We use this method to support accesses to .class. if ( cst instanceof Type ) { int sort = ( ( Type ) cst ) . getSort ( ) ; if ( sort == Type . OBJECT ) { String className = Types . descToInternalName ( ( ( Type ) cst ) . getDescriptor ( ) ) ; insertTInvocation0 ( className , mProbeCounter . incrementAndGet ( ) ) ; } } mv . visitLdcInsn ( cst ) ; }
METHOD VISITOR INTERFACE
128
6
7,502
private void insertTInvocation0 ( String className , int probeId ) { // Check if class name has been seen since the last label. if ( ! mSeenClasses . add ( className ) ) return ; // Check if this class name should be ignored. if ( Types . isIgnorableInternalName ( className ) ) return ; // x. (we tried). Surround invocation of monitor with // try/finally. This approach did not work in some cases as I // was using local variables to save exception exception that // has to be thrown; however, the same local variable may be // used in finally block, so I would override. // NOTE: The following is deprecated and excluded from code // (see monitor for new approach and accesses to fields): // We check if class contains "$" in which case we assume (without // consequences) that the class is inner and we invoke coverage method // that takes string as input. The reason for this special treatment is // access policy, as the inner class may be private and we cannot load // its .class. (See 57f5365935d26d2e6c47ec368612c6b003a2da79 for the // test that is throwing an exception without this.) However, note // that this slows down the execution a lot. // boolean isNonInnerClass = !className.contains("$"); boolean isNonInnerClass = true ; // See the class visitor; currently we override // the version number to 49 for all classes that have lower version // number (so else branch should not be executed for this reason any // more). Earlier comment: Note that we have to use class name in case // of classes that have classfiles with major version of 48 or lower // as ldc could not load .class prior to version 49 (in theory we // could generate a method that does it for us, as the compiler // would do, but then we would change bytecode too much). if ( isNonInnerClass && mIsNewerThanJava4 ) { insertTInvocation ( className , probeId ) ; } else { // DEPRECATED: This part is deprecated and should never be executed. // Using Class.forName(className) was very slow. mv . visitLdcInsn ( className . replaceAll ( "/" , "." ) ) ; mv . visitMethodInsn ( Opcodes . INVOKESTATIC , Names . COVERAGE_MONITOR_VM , Instr . COVERAGE_MONITOR_MNAME , Instr . STRING_V_DESC , false ) ; } }
Checks if the class name belongs to a set of classes that should be ignored ; if not an invocation to coverage monitor is inserted .
553
27
7,503
protected Plugin lookupPlugin ( String key ) { List < Plugin > plugins = project . getBuildPlugins ( ) ; for ( Iterator < Plugin > iterator = plugins . iterator ( ) ; iterator . hasNext ( ) ; ) { Plugin plugin = iterator . next ( ) ; if ( key . equalsIgnoreCase ( plugin . getKey ( ) ) ) { return plugin ; } } return null ; }
Find plugin based on the plugin key . Returns null if plugin cannot be located .
84
16
7,504
protected boolean isRestoreGoalPresent ( ) { Plugin ekstaziPlugin = lookupPlugin ( EKSTAZI_PLUGIN_KEY ) ; if ( ekstaziPlugin == null ) { return false ; } for ( Object execution : ekstaziPlugin . getExecutions ( ) ) { for ( Object goal : ( ( PluginExecution ) execution ) . getGoals ( ) ) { if ( ( ( String ) goal ) . equals ( "restore" ) ) { return true ; } } } return false ; }
Returns true if restore goal is present false otherwise .
115
10
7,505
private void restoreExcludesFile ( File excludesFileFile ) throws MojoExecutionException { if ( ! excludesFileFile . exists ( ) ) { return ; } try { String [ ] lines = FileUtil . readLines ( excludesFileFile ) ; List < String > newLines = new ArrayList < String > ( ) ; for ( String line : lines ) { if ( line . equals ( EKSTAZI_LINE_MARKER ) ) break ; newLines . add ( line ) ; } FileUtil . writeLines ( excludesFileFile , newLines ) ; } catch ( IOException ex ) { throw new MojoExecutionException ( "Could not restore 'excludesFile'" , ex ) ; } }
Removes lines from excludesFile that are added by Ekstazi .
158
14
7,506
private static List < byte [ ] > parsePrivateKeyASN1 ( ByteBuffer byteBuffer ) { final List < byte [ ] > collection = new ArrayList < byte [ ] > ( ) ; while ( byteBuffer . hasRemaining ( ) ) { byte type = byteBuffer . get ( ) ; int length = UnsignedBytes . toInt ( byteBuffer . get ( ) ) ; if ( ( length & 0x80 ) != 0 ) { int numberOfOctets = length ^ 0x80 ; length = 0 ; for ( int i = 0 ; i < numberOfOctets ; ++ i ) { int lengthChunk = UnsignedBytes . toInt ( byteBuffer . get ( ) ) ; length += lengthChunk << ( numberOfOctets - i - 1 ) * 8 ; } } if ( length < 0 ) { throw new IllegalArgumentException ( ) ; } if ( type == 0x30 ) { int position = byteBuffer . position ( ) ; byte [ ] data = Arrays . copyOfRange ( byteBuffer . array ( ) , position , position + length ) ; return parsePrivateKeyASN1 ( ByteBuffer . wrap ( data ) ) ; } if ( type == 0x02 ) { byte [ ] segment = new byte [ length ] ; byteBuffer . get ( segment ) ; collection . add ( segment ) ; } } return collection ; }
This is a simplistic ASN . 1 parser that can only parse a collection of primitive types .
290
19
7,507
@ Nonnull @ ReturnsMutableCopy public static ICommonsList < String > getCleanPathParts ( @ Nonnull final String sPath ) { // Remove leading and trailing whitespaces and slashes String sRealPath = StringHelper . trimStartAndEnd ( sPath . trim ( ) , "/" , "/" ) ; // Remove obscure path parts sRealPath = FilenameHelper . getCleanPath ( sRealPath ) ; // Split into pieces final ICommonsList < String > aPathParts = StringHelper . getExploded ( ' ' , sRealPath ) ; return aPathParts ; }
Clean the provided path and split it into parts separated by slashes .
127
14
7,508
@ Nonnull public FineUploader5Paste setDefaultName ( @ Nonnull @ Nonempty final String sDefaultName ) { ValueEnforcer . notEmpty ( sDefaultName , "DefaultName" ) ; m_sPasteDefaultName = sDefaultName ; return this ; }
The default name given to pasted images .
60
9
7,509
public String ordinalize ( int number ) { String numberStr = Integer . toString ( number ) ; if ( 11 <= number && number <= 13 ) return numberStr + "th" ; int remainder = number % 10 ; if ( remainder == 1 ) return numberStr + "st" ; if ( remainder == 2 ) return numberStr + "nd" ; if ( remainder == 3 ) return numberStr + "rd" ; return numberStr + "th" ; }
Turns a non - negative number into an ordinal string used to denote the position in an ordered sequence such as 1st 2nd 3rd 4th .
98
32
7,510
@ OverrideOnDemand protected boolean isLoginInProgress ( @ Nonnull final IRequestWebScopeWithoutResponse aRequestScope ) { return CLogin . REQUEST_ACTION_VALIDATE_LOGIN_CREDENTIALS . equals ( aRequestScope . params ( ) . getAsString ( CLogin . REQUEST_PARAM_ACTION ) ) ; }
Check if the login process is in progress
79
8
7,511
@ Nullable @ OverrideOnDemand protected String getLoginName ( @ Nonnull final IRequestWebScopeWithoutResponse aRequestScope ) { return aRequestScope . params ( ) . getAsString ( CLogin . REQUEST_ATTR_USERID ) ; }
Get the current login name
57
5
7,512
@ Nullable @ OverrideOnDemand protected String getPassword ( @ Nonnull final IRequestWebScopeWithoutResponse aRequestScope ) { return aRequestScope . params ( ) . getAsString ( CLogin . REQUEST_ATTR_PASSWORD ) ; }
Get the current password
57
4
7,513
@ Nonnull public final EContinue checkUserAndShowLogin ( @ Nonnull final IRequestWebScopeWithoutResponse aRequestScope , @ Nonnull final UnifiedResponse aUnifiedResponse ) { final LoggedInUserManager aLoggedInUserManager = LoggedInUserManager . getInstance ( ) ; String sSessionUserID = aLoggedInUserManager . getCurrentUserID ( ) ; boolean bLoggedInInThisRequest = false ; if ( sSessionUserID == null ) { // No user currently logged in -> start login boolean bLoginError = false ; ICredentialValidationResult aLoginResult = ELoginResult . SUCCESS ; // Is the special login-check action present? if ( isLoginInProgress ( aRequestScope ) ) { // Login screen was already shown // -> Check request parameters final String sLoginName = getLoginName ( aRequestScope ) ; final String sPassword = getPassword ( aRequestScope ) ; // Resolve user - may be null final IUser aUser = getUserOfLoginName ( sLoginName ) ; // Try main login aLoginResult = aLoggedInUserManager . loginUser ( aUser , sPassword , m_aRequiredRoleIDs ) ; if ( aLoginResult . isSuccess ( ) ) { // Credentials are valid - implies that the user was resolved // correctly sSessionUserID = aUser . getID ( ) ; bLoggedInInThisRequest = true ; } else { // Credentials are invalid if ( GlobalDebug . isDebugMode ( ) ) LOGGER . warn ( "Login of '" + sLoginName + "' failed because " + aLoginResult ) ; // Anyway show the error message only if at least some credential // values are passed bLoginError = StringHelper . hasText ( sLoginName ) || StringHelper . hasText ( sPassword ) ; } } if ( sSessionUserID == null ) { // Show login screen as no user is in the session final IHTMLProvider aLoginScreenProvider = createLoginScreen ( bLoginError , aLoginResult ) ; PhotonHTMLHelper . createHTMLResponse ( aRequestScope , aUnifiedResponse , aLoginScreenProvider ) ; } } // Update details final LoginInfo aLoginInfo = aLoggedInUserManager . getLoginInfo ( sSessionUserID ) ; if ( aLoginInfo != null ) { // Update last login info aLoginInfo . setLastAccessDTNow ( ) ; // Set custom attributes modifyLoginInfo ( aLoginInfo , aRequestScope , bLoggedInInThisRequest ) ; } else { // Internal inconsistency if ( sSessionUserID != null ) LOGGER . error ( "Failed to resolve LoginInfo of user ID '" + sSessionUserID + "'" ) ; } if ( bLoggedInInThisRequest ) { // Avoid double submit by simply redirecting to the desired destination // URL without the login parameters aUnifiedResponse . setRedirect ( aRequestScope . getURL ( ) ) ; return EContinue . BREAK ; } // Continue only, if a valid user ID is present return EContinue . valueOf ( sSessionUserID != null ) ; }
Main login routine .
666
4
7,514
@ Nonnull public static JSInvocation setSelectOptions ( @ Nonnull final IJSExpression aSelector , @ Nonnull final IJSExpression aValueList ) { return getFormHelper ( ) . invoke ( "setSelectOptions" ) . arg ( aSelector ) . arg ( aValueList ) ; }
Set all options of a &lt ; select&gt ;
68
12
7,515
protected boolean isMagicCorrect ( BufferedReader br ) throws IOException { if ( mCheckMagicSequence ) { String magicLine = br . readLine ( ) ; return ( magicLine != null && magicLine . equals ( mMode . getMagicSequence ( ) ) ) ; } else { return true ; } }
Check magic sequence . Note that subclasses are responsible to decide if something should be read from buffer . This approach was taken to support old format without magic sequence .
67
32
7,516
protected RegData parseLine ( State state , String line ) { // Note. Initial this method was using String.split, but that method // seems to be much more expensive than playing with indexOf and // substring. int sepIndex = line . indexOf ( SEPARATOR ) ; String urlExternalForm = line . substring ( 0 , sepIndex ) ; String hash = line . substring ( sepIndex + SEPARATOR_LEN ) ; return new RegData ( urlExternalForm , hash ) ; }
Parses a single line from the file . This method is never invoked for magic sequence . The line includes path to file and hash . Subclasses may include more fields .
107
35
7,517
protected void printLine ( State state , Writer pw , String externalForm , String hash ) throws IOException { pw . write ( externalForm ) ; pw . write ( SEPARATOR ) ; pw . write ( hash ) ; pw . write ( ' ' ) ; }
Prints one line to the given writer ; the line includes path to file and hash . Subclasses may include more fields .
60
25
7,518
public void update ( final float delta ) { if ( transitionInProgress ) { currentValue += ( targetValue - initialValue ) * delta / transitionLength ; if ( isInitialGreater ) { if ( currentValue <= targetValue ) { finalizeTransition ( ) ; } } else { if ( currentValue >= targetValue ) { finalizeTransition ( ) ; } } } }
Updates current value as long as it doesn t match the target value .
80
15
7,519
public void setCurrentValue ( final float currentValue ) { this . currentValue = currentValue ; initialValue = currentValue ; targetValue = currentValue ; transitionInProgress = false ; }
Ends transition . Immediately changes managed current value .
39
10
7,520
@ Nonnull public static IHCNode markdown ( @ Nullable final String sMD ) { try { final HCNodeList aNL = MARKDOWN_PROC . process ( sMD ) . getNodeList ( ) ; // Replace a single <p> element with its contents if ( aNL . getChildCount ( ) == 1 && aNL . getChildAtIndex ( 0 ) instanceof HCP ) return ( ( HCP ) aNL . getChildAtIndex ( 0 ) ) . getAllChildrenAsNodeList ( ) ; return aNL ; } catch ( final Exception ex ) { LOGGER . warn ( "Failed to markdown '" + sMD + "': " + ex . getMessage ( ) ) ; return new HCTextNode ( sMD ) ; } }
Process the provided String as Markdown and return the created IHCNode .
167
15
7,521
public final void getContent ( @ Nonnull final WPECTYPE aWPEC ) { if ( isValidToDisplayPage ( aWPEC ) . isValid ( ) ) { // "before"-callback beforeFillContent ( aWPEC ) ; // Create the main page content fillContent ( aWPEC ) ; // "after"-callback afterFillContent ( aWPEC ) ; } else { // Invalid to display page onInvalidToDisplayPage ( aWPEC ) ; } }
Default implementation calling the abstract fillContent method and creating the help node if desired .
101
16
7,522
@ Nonnull public static final AjaxFunctionDeclaration addAjax ( @ Nullable final String sPrefix , @ Nonnull final IAjaxExecutor aExecutor ) { // null means random name final String sFuncName = StringHelper . hasText ( sPrefix ) ? sPrefix + AjaxFunctionDeclaration . getUniqueFunctionID ( ) : null ; final AjaxFunctionDeclaration aFunction = AjaxFunctionDeclaration . builder ( sFuncName ) . withExecutor ( aExecutor ) . build ( ) ; GlobalAjaxInvoker . getInstance ( ) . getRegistry ( ) . registerFunction ( aFunction ) ; return aFunction ; }
Add a per - page AJAX executor with an automatically generated name . It is automatically generated with the global AjaxInvoker .
143
26
7,523
public QRSCT reference ( String reference ) { if ( reference != null && reference . length ( ) <= 35 ) { this . text = "" ; //$NON-NLS-1$ this . reference = checkValidSigns ( reference ) ; return this ; } throw new IllegalArgumentException ( "supplied reference [" + reference //$NON-NLS-1$ + "] not valid: has to be not null and of max length 35" ) ; //$NON-NLS-1$ }
Sets the reference of this builder !!!If you set this attribute attribute text will be reset to an empty string!!! It s only possible to define one of these attributes
111
34
7,524
public QRSCT text ( String text ) { if ( text != null && text . length ( ) <= 140 ) { this . reference = "" ; //$NON-NLS-1$ this . text = checkValidSigns ( text ) ; return this ; } throw new IllegalArgumentException ( "supplied text [" + text //$NON-NLS-1$ + "] not valid: has to be not null and of max length 140" ) ; //$NON-NLS-1$ }
Sets the text of this builder !!!If you set this attribute attribute reference will be reset to an empty string!!! It s only possible to define one of these attributes
111
34
7,525
private void processClasspath ( String classpathElement ) throws ResourceNotFoundException , ParseErrorException , Exception { // getLog().info("Classpath is " + classpathElement); if ( classpathElement . endsWith ( ".jar" ) ) { // TODO: implement JAR scanning } else { final File dir = new File ( classpathElement ) ; processPackage ( dir , dir ) ; } }
Process the classes for a specified package
87
7
7,526
private void processPackage ( File root , File dir ) { getLog ( ) . debug ( "- package: " + dir ) ; if ( null != dir && dir . isDirectory ( ) ) { for ( File f : dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { return pathname . isDirectory ( ) || pathname . getName ( ) . endsWith ( ".class" ) ; } } ) ) { if ( f . isDirectory ( ) ) { processPackage ( root , f ) ; } else if ( f . getParentFile ( ) . getAbsolutePath ( ) . replace ( File . separatorChar , ' ' ) . endsWith ( basePackage + ' ' + domainPackageName ) ) { final String simpleName = f . getName ( ) . substring ( 0 , f . getName ( ) . lastIndexOf ( ".class" ) ) ; final String className = String . format ( "%s.%s.%s" , basePackage , domainPackageName , simpleName ) ; getLog ( ) . debug ( String . format ( "--- class %s" , className ) ) ; try { Class clazz = loader . loadClass ( className ) ; if ( ! Modifier . isAbstract ( clazz . getModifiers ( ) ) && isEntity ( clazz ) ) { getLog ( ) . debug ( "@Entity " + clazz . getName ( ) ) ; final Entity entity = new Entity ( ) ; entity . setClazz ( clazz ) ; final String packageName = clazz . getPackage ( ) . getName ( ) ; Group group = packages . get ( packageName ) ; if ( null == group ) { group = new Group ( ) ; group . setName ( packageName ) ; packages . put ( packageName , group ) ; } group . getEntities ( ) . put ( simpleName , entity ) ; entities . put ( entity . getClassName ( ) , entity ) ; } } catch ( ClassNotFoundException ex ) { Logger . getLogger ( ProcessDomainMojo . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } } }
Recursive method to process a folder or file ; if a folder call recursively for each file . If for a file process the file using the classVisitor .
474
34
7,527
@ Nonnull @ ReturnsMutableCopy private HolidayMap _getHolidays ( final int nYear , @ Nonnull final Configuration aConfig , @ Nullable final String ... aArgs ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Adding holidays for " + aConfig . getDescription ( ) ) ; final HolidayMap aHolidayMap = new HolidayMap ( ) ; for ( final IHolidayParser aParser : _getParsers ( aConfig . getHolidays ( ) ) ) aParser . parse ( nYear , aHolidayMap , aConfig . getHolidays ( ) ) ; if ( ArrayHelper . isNotEmpty ( aArgs ) ) { final String sHierarchy = aArgs [ 0 ] ; for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) { if ( sHierarchy . equalsIgnoreCase ( aSubConfig . getHierarchy ( ) ) ) { // Recursive call final HolidayMap aSubHolidays = _getHolidays ( nYear , aSubConfig , ArrayHelper . getCopy ( aArgs , 1 , aArgs . length - 1 ) ) ; aHolidayMap . addAll ( aSubHolidays ) ; break ; } } } return aHolidayMap ; }
Parses the provided configuration for the provided year and fills the list of holidays .
280
17
7,528
private static void _validateConfigurationHierarchy ( @ Nonnull final Configuration aConfig ) { final ICommonsSet < String > aHierarchySet = new CommonsHashSet <> ( ) ; for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) { final String sHierarchy = aSubConfig . getHierarchy ( ) ; if ( ! aHierarchySet . add ( sHierarchy ) ) throw new IllegalArgumentException ( "Configuration for " + aConfig . getHierarchy ( ) + " contains multiple SubConfigurations with the same hierarchy id '" + sHierarchy + "'. " ) ; } for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) _validateConfigurationHierarchy ( aSubConfig ) ; }
Validates the content of the provided configuration by checking for multiple hierarchy entries within one configuration . It traverses down the configuration tree .
176
26
7,529
@ Nonnull private static CalendarHierarchy _createConfigurationHierarchy ( @ Nonnull final Configuration aConfig , @ Nullable final CalendarHierarchy aParent ) { final ECountry eCountry = ECountry . getFromIDOrNull ( aConfig . getHierarchy ( ) ) ; final CalendarHierarchy aHierarchy = new CalendarHierarchy ( aParent , aConfig . getHierarchy ( ) , eCountry ) ; for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) { final CalendarHierarchy aSubHierarchy = _createConfigurationHierarchy ( aSubConfig , aHierarchy ) ; aHierarchy . addChild ( aSubHierarchy ) ; } return aHierarchy ; }
Creates the configuration hierarchy for the provided configuration .
165
10
7,530
public static void setDbType ( JdbcDialect dialect , String key , String type ) { Properties props = getTypesProps ( dialect ) ; props . setProperty ( key , type ) ; }
Add a type for your DB s dialect
43
8
7,531
private static ICommonsSet < LocalDate > _getEthiopianOrthodoxHolidaysInGregorianYear ( final int nGregorianYear , final int nEOMonth , final int nEODay ) { return CalendarHelper . getDatesFromChronologyWithinGregorianYear ( nEOMonth , nEODay , nGregorianYear , CopticChronology . INSTANCE ) ; }
Returns a set of gregorian dates within a gregorian year which equal the Ethiopian orthodox month and day . Because the Ethiopian orthodox year different from the gregorian there may be more than one occurrence of an Ethiopian orthodox date in an gregorian year .
91
53
7,532
@ Override public Result parse ( Command cmd , InputStream input , ResultType type ) { return parseResults ( cmd , input , type ) ; }
Parses the input stream as either XML select or ask results .
31
14
7,533
public static Result parseResults ( Command cmd , InputStream input , ResultType type ) throws SparqlException { try { return createResults ( cmd , input , type ) ; } catch ( Throwable t ) { logger . debug ( "Error parsing results from stream, cleaning up." ) ; try { input . close ( ) ; } catch ( IOException e ) { logger . warn ( "Error closing input stream from failed protocol response" , e ) ; } throw SparqlException . convert ( "Error parsing SPARQL protocol results from stream" , t ) ; } }
Parses an XMLResults object based on the contents of the given stream .
120
16
7,534
private static Result createResults ( Command cmd , InputStream stream , ResultType type ) throws SparqlException { XMLInputFactory xmlStreamFactory = XMLInputFactory . newInstance ( ) ; // Tell the factory to combine adjacent character blocks into a single event, so we don't have to do it ourselves. xmlStreamFactory . setProperty ( XMLInputFactory . IS_COALESCING , true ) ; // Tell the factory to create a reader that will close the underlying stream when done. xmlStreamFactory . setProperty ( XMLInputFactory2 . P_AUTO_CLOSE_INPUT , true ) ; XMLStreamReader rdr ; try { rdr = xmlStreamFactory . createXMLStreamReader ( stream , "UTF-8" ) ; } catch ( XMLStreamException e ) { throw new SparqlException ( "Unable to open XML data" , e ) ; } List < String > cols = new ArrayList < String > ( ) ; List < String > md = new ArrayList < String > ( ) ; try { if ( rdr . nextTag ( ) != START_ELEMENT || ! nameIs ( rdr , SPARQL ) ) { throw new SparqlException ( "Result is not a SPARQL XML result document" ) ; } // Initialize the base URI to the String base = null ; if ( cmd != null ) { base = ( ( ProtocolDataSource ) cmd . getConnection ( ) . getDataSource ( ) ) . getUrl ( ) . toString ( ) ; } // read the header information parseHeader ( base , rdr , cols , md ) ; // move the cursor into the results, and read in the first row if ( rdr . nextTag ( ) != START_ELEMENT ) throw new SparqlException ( "No body to result document" ) ; String typeName = rdr . getLocalName ( ) ; if ( typeName . equalsIgnoreCase ( RESULTS . toString ( ) ) ) { if ( type != null && type != ResultType . SELECT ) { throw new SparqlException ( "Unexpected result type; expected " + type + " but found SELECT." ) ; } return new XMLSelectResults ( cmd , rdr , cols , md ) ; } if ( typeName . equalsIgnoreCase ( BOOLEAN . toString ( ) ) ) { if ( type != null && type != ResultType . ASK ) { throw new SparqlException ( "Unexpected result type; expected " + type + " but found ASK." ) ; } if ( ! cols . isEmpty ( ) ) { logger . warn ( "Boolean result contained column definitions in head: {}" , cols ) ; } return parseBooleanResult ( cmd , rdr , md ) ; } throw new SparqlException ( "Unknown element type in result document. Expected <results> or <boolean> but got <" + typeName + ">" ) ; } catch ( XMLStreamException e ) { throw new SparqlException ( "Error reading the XML stream" , e ) ; } }
Sets up an XML parser for the input and creates the appropriate result type based on the parsed XML .
658
21
7,535
static private void parseHeader ( String base , XMLStreamReader rdr , List < String > cols , List < String > md ) throws XMLStreamException , SparqlException { logger . debug ( "xml:base is initially {}" , base ) ; base = getBase ( base , rdr ) ; testOpen ( rdr , rdr . nextTag ( ) , HEAD , "Missing header from XML results" ) ; base = getBase ( base , rdr ) ; boolean endedVars = false ; int eventType ; while ( ( eventType = rdr . nextTag ( ) ) != END_ELEMENT || ! nameIs ( rdr , HEAD ) ) { if ( eventType == START_ELEMENT ) { if ( nameIs ( rdr , VARIABLE ) ) { if ( endedVars ) throw new SparqlException ( "Encountered a variable after header metadata" ) ; String var = rdr . getAttributeValue ( null , "name" ) ; if ( var != null ) cols . add ( var ) ; else logger . warn ( "<variable> element without 'name' attribute" ) ; } else if ( nameIs ( rdr , LINK ) ) { String b = getBase ( base , rdr ) ; // Copy to a new var since we're looping. String href = rdr . getAttributeValue ( null , HREF ) ; if ( href != null ) md . add ( resolve ( b , href ) ) ; else logger . warn ( "<link> element without 'href' attribute" ) ; endedVars = true ; } } } // ending on </head>. next() should be <results> or <boolean> testClose ( rdr , eventType , HEAD , "Unexpected element in header: " + rdr . getLocalName ( ) ) ; }
Parse the &lt ; head&gt ; element with the variables and metadata .
391
17
7,536
static final boolean nameIs ( XMLStreamReader rdr , Element elt ) { return rdr . getLocalName ( ) . equalsIgnoreCase ( elt . name ( ) ) ; }
Convenience method to test if the current local name is the same as an expected element .
41
19
7,537
public static void runOnUiThread ( @ NonNull final Runnable runnable ) { Condition . INSTANCE . ensureNotNull ( runnable , "The runnable may not be null" ) ; new Handler ( Looper . getMainLooper ( ) ) . post ( runnable ) ; }
Executes a specific runnable on the UI thread .
68
12
7,538
@ SafeVarargs private final boolean notifyOnLoad ( @ NonNull final KeyType key , @ NonNull final ParamType ... params ) { boolean result = true ; for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { result &= listener . onLoadData ( this , key , params ) ; } return result ; }
Notifies all listeners that the data binder starts to load data asynchronously .
77
17
7,539
@ SafeVarargs private final void notifyOnFinished ( @ NonNull final KeyType key , @ Nullable final DataType data , @ NonNull final ViewType view , @ NonNull final ParamType ... params ) { for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { listener . onFinished ( this , key , data , view , params ) ; } }
Notifies all listeners that the data binder is showing data which has been loaded either asynchronously or from cache .
87
24
7,540
private void notifyOnCanceled ( ) { for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { listener . onCanceled ( this ) ; } }
Notifies all listeners that the data binder has been canceled .
44
13
7,541
@ Nullable private DataType getCachedData ( @ NonNull final KeyType key ) { synchronized ( cache ) { return cache . get ( key ) ; } }
Returns the data which corresponds to a specific key from the cache .
35
13
7,542
private void cacheData ( @ NonNull final KeyType key , @ NonNull final DataType data ) { synchronized ( cache ) { if ( useCache ) { cache . put ( key , data ) ; } } }
Adds the data which corresponds to a specific key to the cache if caching is enabled .
45
17
7,543
private void loadDataAsynchronously ( @ NonNull final Task < DataType , KeyType , ViewType , ParamType > task ) { threadPool . submit ( new Runnable ( ) { @ Override public void run ( ) { if ( ! isCanceled ( ) ) { while ( ! notifyOnLoad ( task . key , task . params ) ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { break ; } } task . result = loadData ( task ) ; Message message = Message . obtain ( ) ; message . obj = task ; sendMessage ( message ) ; } } } ) ; }
Asynchronously executes a specific task in order to load data and to display it afterwards .
137
18
7,544
@ Nullable private DataType loadData ( @ NonNull final Task < DataType , KeyType , ViewType , ParamType > task ) { try { DataType data = doInBackground ( task . key , task . params ) ; if ( data != null ) { cacheData ( task . key , data ) ; } logger . logInfo ( getClass ( ) , "Loaded data with key " + task . key ) ; return data ; } catch ( Exception e ) { logger . logError ( getClass ( ) , "An error occurred while loading data with key " + task . key , e ) ; return null ; } }
Executes a specific task in order to load data .
133
11
7,545
public final void addListener ( @ NonNull final Listener < DataType , KeyType , ViewType , ParamType > listener ) { listeners . add ( listener ) ; }
Adds a new listener which should be notified about the events of the data binder .
36
17
7,546
public final void removeListener ( @ NonNull final Listener < DataType , KeyType , ViewType , ParamType > listener ) { listeners . remove ( listener ) ; }
Removes a specific listener which should not be notified about the events of the data binder anymore .
36
20
7,547
@ SafeVarargs public final void load ( @ NonNull final KeyType key , @ NonNull final ViewType view , @ NonNull final ParamType ... params ) { load ( key , view , true , params ) ; }
Loads the the data which corresponds to a specific key and displays it in a specific view . If the data has already been loaded it will be retrieved from the cache . By default the data is loaded in a background thread .
47
45
7,548
@ SafeVarargs public final void load ( @ NonNull final KeyType key , @ NonNull final ViewType view , final boolean async , @ NonNull final ParamType ... params ) { Condition . INSTANCE . ensureNotNull ( key , "The key may not be null" ) ; Condition . INSTANCE . ensureNotNull ( view , "The view may not be null" ) ; Condition . INSTANCE . ensureNotNull ( params , "The array may not be null" ) ; setCanceled ( false ) ; views . put ( view , key ) ; DataType data = getCachedData ( key ) ; if ( ! isCanceled ( ) ) { if ( data != null ) { onPostExecute ( view , data , 0 , params ) ; notifyOnFinished ( key , data , view , params ) ; logger . logInfo ( getClass ( ) , "Loaded data with key " + key + " from cache" ) ; } else { onPreExecute ( view , params ) ; Task < DataType , KeyType , ViewType , ParamType > task = new Task <> ( view , key , params ) ; if ( async ) { loadDataAsynchronously ( task ) ; } else { data = loadData ( task ) ; onPostExecute ( view , data , 0 , params ) ; notifyOnFinished ( key , data , view , params ) ; } } } }
Loads the the data which corresponds to a specific key and displays it in a specific view . If the data has already been loaded it will be retrieved from the cache .
301
34
7,549
public final boolean isCached ( @ NonNull final KeyType key ) { Condition . INSTANCE . ensureNotNull ( key , "The key may not be null" ) ; synchronized ( cache ) { return cache . get ( key ) != null ; } }
Returns whether the data which corresponds to a specific key is currently cached or not .
54
16
7,550
public final void useCache ( final boolean useCache ) { synchronized ( cache ) { this . useCache = useCache ; logger . logDebug ( getClass ( ) , useCache ? "Enabled" : "Disabled" + " caching" ) ; if ( ! useCache ) { clearCache ( ) ; } } }
Sets whether data should be cached or not .
67
10
7,551
private static void profile ( Task task , String message , int tries ) { for ( int i = 0 ; i < tries ; i ++ ) { long start = System . nanoTime ( ) ; task . run ( ) ; long finish = System . nanoTime ( ) ; System . out . println ( String . format ( "[Try %d] %-30s: %-5.2fms" , i + 1 , message , ( finish - start ) / 1000000.0 ) ) ; } }
Poor mans profiler
106
4
7,552
private void obtainShadowElevation ( @ NonNull final TypedArray typedArray ) { int defaultValue = getResources ( ) . getDimensionPixelSize ( R . dimen . elevation_shadow_view_shadow_elevation_default_value ) ; elevation = pixelsToDp ( getContext ( ) , typedArray . getDimensionPixelSize ( R . styleable . ElevationShadowView_shadowElevation , defaultValue ) ) ; }
Obtains the elevation of the shadow which is visualized by the view from a specific typed array .
98
20
7,553
private void obtainShadowOrientation ( @ NonNull final TypedArray typedArray ) { int defaultValue = getResources ( ) . getInteger ( R . integer . elevation_shadow_view_shadow_orientation_default_value ) ; orientation = Orientation . fromValue ( typedArray . getInteger ( R . styleable . ElevationShadowView_shadowOrientation , defaultValue ) ) ; }
Obtains the orientation of the shadow which is visualized by the view from a specific typed array .
86
20
7,554
private void obtainEmulateParallelLight ( @ NonNull final TypedArray typedArray ) { boolean defaultValue = getResources ( ) . getBoolean ( R . bool . elevation_shadow_view_emulate_parallel_light_default_value ) ; emulateParallelLight = typedArray . getBoolean ( R . styleable . ElevationShadowView_emulateParallelLight , defaultValue ) ; }
Obtains the boolean value which specifies whether parallel light should be emulated from a specific typed array .
89
20
7,555
private void adaptElevationShadow ( ) { setImageBitmap ( createElevationShadow ( getContext ( ) , elevation , orientation , emulateParallelLight ) ) ; setScaleType ( orientation == Orientation . LEFT || orientation == Orientation . TOP || orientation == Orientation . RIGHT || orientation == Orientation . BOTTOM ? ScaleType . FIT_XY : ScaleType . FIT_CENTER ) ; }
Adapts the shadow which is visualized by the view depending on its current attributes .
91
17
7,556
public final void setShadowElevation ( final int elevation ) { Condition . INSTANCE . ensureAtLeast ( elevation , 0 , "The elevation must be at least 0" ) ; Condition . INSTANCE . ensureAtMaximum ( elevation , ElevationUtil . MAX_ELEVATION , "The elevation must be at maximum " + ElevationUtil . MAX_ELEVATION ) ; this . elevation = elevation ; adaptElevationShadow ( ) ; }
Sets the elevation of the shadow which should be visualized by the view .
99
16
7,557
public final void setShadowOrientation ( @ NonNull final Orientation orientation ) { Condition . INSTANCE . ensureNotNull ( orientation , "The orientation may not be null" ) ; this . orientation = orientation ; adaptElevationShadow ( ) ; }
Sets the orientation of the shadow which should be visualized by the view .
54
16
7,558
@ Override public boolean hasError ( Response < ByteSource > rs ) { StatusType statusType = StatusType . valueOf ( rs . getStatus ( ) ) ; return ( statusType == StatusType . CLIENT_ERROR || statusType == StatusType . SERVER_ERROR ) ; }
Returns TRUE in case status code of response starts with 4 or 5
60
13
7,559
protected void handleError ( URI requestUri , HttpMethod requestMethod , int statusCode , String statusMessage , ByteSource errorBody ) throws RestEndpointIOException { throw new RestEndpointException ( requestUri , requestMethod , statusCode , statusMessage , errorBody ) ; }
Handler methods for HTTP client errors
61
6
7,560
public void init ( APUtils utils ) throws DuzztInitializationException { URL url = GenerateEDSLProcessor . class . getResource ( ST_RESOURCE_NAME ) ; this . sourceGenGroup = new STGroupFile ( url , ST_ENCODING , ST_DELIM_START_CHAR , ST_DELIM_STOP_CHAR ) ; sourceGenGroup . setListener ( new ReporterDiagnosticListener ( utils . getReporter ( ) ) ) ; sourceGenGroup . load ( ) ; if ( ! sourceGenGroup . isDefined ( ST_MAIN_TEMPLATE_NAME ) ) { sourceGenGroup = null ; throw new DuzztInitializationException ( "Could not find main template '" + ST_MAIN_TEMPLATE_NAME + "' in template group file " + url . toString ( ) ) ; } this . isJava9OrNewer = isJava9OrNewer ( utils . getProcessingEnv ( ) . getSourceVersion ( ) ) ; }
Initialize the Duzzt embedded DSL generator .
228
10
7,561
public void process ( Element elem , GenerateEmbeddedDSL annotation , Elements elementUtils , Types typeUtils , Filer filer , Reporter reporter ) throws IOException { if ( ! ElementUtils . checkElementKind ( elem , ElementKind . CLASS , ElementKind . INTERFACE ) ) { throw new IllegalArgumentException ( "Annotation " + GenerateEmbeddedDSL . class . getSimpleName ( ) + " can only be used on class or interface declarations!" ) ; } TypeElement te = ( TypeElement ) elem ; ReporterDiagnosticListener dl = new ReporterDiagnosticListener ( reporter ) ; DSLSettings settings = new DSLSettings ( annotation ) ; DSLSpecification spec = DSLSpecification . create ( te , settings , elementUtils , typeUtils ) ; BricsCompiler compiler = new BricsCompiler ( spec . getImplementation ( ) ) ; DuzztAutomaton automaton = compiler . compile ( spec . getDSLSyntax ( ) , spec . getSubExpressions ( ) ) ; // Make sure classes have same name if generated twice from the same spec automaton . reassignStateIds ( typeUtils ) ; render ( spec , automaton , filer , dl ) ; }
Process an annotated element .
268
6
7,562
public static boolean isPermissionGranted ( @ NonNull final Context context , @ NonNull final String permission ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Condition . INSTANCE . ensureNotNull ( permission , "The permission may not be null" ) ; Condition . INSTANCE . ensureNotEmpty ( permission , "The permission may not be empty" ) ; return Build . VERSION . SDK_INT < Build . VERSION_CODES . M || ContextCompat . checkSelfPermission ( context , permission ) == PackageManager . PERMISSION_GRANTED ; }
Returns whether a specific permission is granted or not .
133
10
7,563
public static boolean areAllPermissionsGranted ( @ NonNull final Context context , @ NonNull final String ... permissions ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Condition . INSTANCE . ensureNotNull ( permissions , "The array may not be null" ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M ) { for ( String permission : permissions ) { if ( ! isPermissionGranted ( context , permission ) ) { return false ; } } } return true ; }
Returns whether all permissions which are contained by a specific array are granted or not .
124
16
7,564
@ NonNull public static String [ ] getNotGrantedPermissions ( @ NonNull final Context context , @ NonNull final String ... permissions ) { Condition . INSTANCE . ensureNotNull ( permissions , "The array may not be null" ) ; Collection < String > notGrantedPermissions = new LinkedList <> ( ) ; for ( String permission : permissions ) { if ( ! isPermissionGranted ( context , permission ) ) { notGrantedPermissions . add ( permission ) ; } } String [ ] result = new String [ notGrantedPermissions . size ( ) ] ; notGrantedPermissions . toArray ( result ) ; return result ; }
Returns the subset of specific permissions which are not granted .
142
11
7,565
private List < O > findByDate ( String dateField , Date start , Date end , int numObjects , boolean asc ) { if ( start == null ) start = new Date ( 0 ) ; if ( end == null ) end = new Date ( ) ; return getDatastore ( ) . find ( clazz ) . filter ( dateField + " >" , start ) . filter ( dateField + " <" , end ) . order ( asc ? dateField : ' ' + dateField ) . limit ( numObjects ) . asList ( ) ; }
A private helper method that can be applied to creationDate crawledDate lastModifiedDate . For usage sample see the methods below
120
25
7,566
public List < O > createdInPeriod ( Date start , Date end , int numObjects ) { return findByDate ( "creationDate" , start , end , numObjects , true ) ; }
Returns a list of images created in the time period specified by start and end
44
15
7,567
public List < Similarity > similar ( Image object , double threshold ) { //return getDatastore().find(Similarity.class).field("firstObject").equal(object).order("similarityScore").asList(); Query < Similarity > q = getDatastore ( ) . createQuery ( Similarity . class ) ; q . or ( q . criteria ( "firstObject" ) . equal ( object ) , q . criteria ( "secondObject" ) . equal ( object ) ) ; return q . order ( "-similarityScore" ) . filter ( "similarityScore >" , threshold ) . asList ( ) ; }
Returns a list of objects that are similar to the specified object
135
12
7,568
public void createZookeeperBase ( ) throws WorkerDaoException { createPersistentEmptyNodeIfNotExist ( BASE_ZK ) ; createPersistentEmptyNodeIfNotExist ( WORKERS_ZK ) ; createPersistentEmptyNodeIfNotExist ( PLANS_ZK ) ; createPersistentEmptyNodeIfNotExist ( SAVED_ZK ) ; createPersistentEmptyNodeIfNotExist ( LOCKS_ZK ) ; createPersistentEmptyNodeIfNotExist ( PLAN_WORKERS_ZK ) ; }
Creates all the required base directories in ZK for the application to run
122
15
7,569
public List < String > findWorkersWorkingOnPlan ( Plan plan ) throws WorkerDaoException { try { Stat exists = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) ) ; if ( exists == null ) { return new ArrayList < String > ( ) ; } return framework . getCuratorFramework ( ) . getChildren ( ) . forPath ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) ) ; } catch ( Exception e ) { throw new WorkerDaoException ( e ) ; } }
Returns the node name of all the ephemeral nodes under a plan . This is effectively who is working on the plan .
139
25
7,570
public Plan findPlanByName ( String name ) throws WorkerDaoException { Stat planStat ; byte [ ] planBytes ; try { planStat = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLANS_ZK + "/" + name ) ; if ( planStat == null ) { return null ; } planBytes = framework . getCuratorFramework ( ) . getData ( ) . forPath ( PLANS_ZK + "/" + name ) ; } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } Plan p = null ; try { p = deserializePlan ( planBytes ) ; } catch ( JsonParseException | JsonMappingException e ) { LOGGER . warn ( "while parsing plan " + name , e ) ; } catch ( IOException e ) { LOGGER . warn ( "while parsing plan " + name , e ) ; } return p ; }
Search zookeeper for a plan with given name .
213
11
7,571
public void createOrUpdatePlan ( Plan plan ) throws WorkerDaoException { try { createZookeeperBase ( ) ; Stat s = this . framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLANS_ZK + "/" + plan . getName ( ) ) ; if ( s != null ) { framework . getCuratorFramework ( ) . setData ( ) . withVersion ( s . getVersion ( ) ) . forPath ( PLANS_ZK + "/" + plan . getName ( ) , serializePlan ( plan ) ) ; } else { framework . getCuratorFramework ( ) . create ( ) . withMode ( CreateMode . PERSISTENT ) . withACL ( Ids . OPEN_ACL_UNSAFE ) . forPath ( PLANS_ZK + "/" + plan . getName ( ) , serializePlan ( plan ) ) ; } } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } }
Creates or updates a plan in zookeeper .
229
11
7,572
public void createEphemeralNodeForDaemon ( TeknekDaemon d ) throws WorkerDaoException { try { byte [ ] hostbytes = d . getHostname ( ) . getBytes ( ENCODING ) ; framework . getCuratorFramework ( ) . create ( ) . withMode ( CreateMode . EPHEMERAL ) . withACL ( Ids . OPEN_ACL_UNSAFE ) . forPath ( WORKERS_ZK + "/" + d . getMyId ( ) , hostbytes ) ; } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } }
Creates an ephemeral node so that we can determine how many current live nodes there are
143
19
7,573
public List < WorkerStatus > findAllWorkerStatusForPlan ( Plan plan , List < String > otherWorkers ) throws WorkerDaoException { List < WorkerStatus > results = new ArrayList < WorkerStatus > ( ) ; try { Stat preCheck = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) ) ; if ( preCheck == null ) { return results ; } } catch ( Exception e1 ) { LOGGER . warn ( e1 ) ; throw new WorkerDaoException ( e1 ) ; } for ( String worker : otherWorkers ) { String lookAtPath = PLAN_WORKERS_ZK + "/" + plan . getName ( ) + "/" + worker ; try { Stat stat = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( lookAtPath ) ; byte [ ] data = framework . getCuratorFramework ( ) . getData ( ) . storingStatIn ( stat ) . forPath ( lookAtPath ) ; results . add ( MAPPER . readValue ( data , WorkerStatus . class ) ) ; } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } } return results ; }
Gets the status of each worker . The status contains the partitionId being consumed . This information helps the next worker bind to an unconsumed partition
285
29
7,574
public void registerWorkerStatus ( ZooKeeper zk , Plan plan , WorkerStatus s ) throws WorkerDaoException { String writeToPath = PLAN_WORKERS_ZK + "/" + plan . getName ( ) + "/" + s . getWorkerUuid ( ) ; try { Stat planBase = zk . exists ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) , false ) ; if ( planBase == null ) { try { zk . create ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) , new byte [ 0 ] , Ids . OPEN_ACL_UNSAFE , CreateMode . PERSISTENT ) ; } catch ( Exception ignore ) { } } zk . create ( writeToPath , MAPPER . writeValueAsBytes ( s ) , Ids . OPEN_ACL_UNSAFE , CreateMode . EPHEMERAL ) ; LOGGER . debug ( "Registered as ephemeral " + writeToPath ) ; zk . exists ( PLANS_ZK + "/" + plan . getName ( ) , true ) ; //watch job for events } catch ( KeeperException | InterruptedException | IOException e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } }
Registers an ephemeral node representing ownership of a feed partition . Note we do not use curator here because we want a standard watch not from the main thread!
286
33
7,575
public void deletePlan ( Plan p ) throws WorkerDaoException { String planNode = PLANS_ZK + "/" + p . getName ( ) ; try { Stat s = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( planNode ) ; framework . getCuratorFramework ( ) . delete ( ) . withVersion ( s . getVersion ( ) ) . forPath ( planNode ) ; } catch ( Exception e ) { throw new WorkerDaoException ( e ) ; } }
Note you should call stop the plan if it is running before deleting
113
13
7,576
public static int indexOf ( @ NonNull final boolean [ ] array , final boolean value ) { Condition . INSTANCE . ensureNotNull ( array , "The array may not be null" ) ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == value ) { return i ; } } return - 1 ; }
Returns the index of the first item of an array which equals a specific boolean value .
78
17
7,577
protected final void addUnusedView ( @ NonNull final View view , final int viewType ) { if ( useCache ) { if ( unusedViews == null ) { unusedViews = new SparseArray <> ( adapter . getViewTypeCount ( ) ) ; } Queue < View > queue = unusedViews . get ( viewType ) ; if ( queue == null ) { queue = new LinkedList <> ( ) ; unusedViews . put ( viewType , queue ) ; } queue . add ( view ) ; } }
Adds an unused view to the cache .
115
8
7,578
@ Nullable protected final View pollUnusedView ( final int viewType ) { if ( useCache && unusedViews != null ) { Queue < View > queue = unusedViews . get ( viewType ) ; if ( queue != null ) { return queue . poll ( ) ; } } return null ; }
Retrieves an unused view which corresponds to a specific view type from the cache if any is available .
66
21
7,579
@ Nullable public final View getView ( @ NonNull final ItemType item ) { Condition . INSTANCE . ensureNotNull ( item , "The item may not be null" ) ; return activeViews . get ( item ) ; }
Returns the view which is currently used to visualize a specific item .
50
13
7,580
public final void clearCache ( ) { if ( unusedViews != null ) { unusedViews . clear ( ) ; unusedViews = null ; } logger . logDebug ( getClass ( ) , "Removed all unused views from cache" ) ; }
Removes all unused views from the cache .
53
9
7,581
public final void clearCache ( final int viewType ) { if ( unusedViews != null ) { unusedViews . remove ( viewType ) ; } logger . logDebug ( getClass ( ) , "Removed all unused views of view type " + viewType + " from cache" ) ; }
Removes all unused views which correspond to a specific view type from the cache .
62
16
7,582
public void init ( ) { try { zk = new ZooKeeper ( parent . getProperties ( ) . get ( TeknekDaemon . ZK_SERVER_LIST ) . toString ( ) , 30000 , this ) ; } catch ( IOException e1 ) { throw new RuntimeException ( e1 ) ; } Feed feed = DriverFactory . buildFeed ( plan . getFeedDesc ( ) ) ; List < WorkerStatus > workerStatus ; try { workerStatus = parent . getWorkerDao ( ) . findAllWorkerStatusForPlan ( plan , otherWorkers ) ; } catch ( WorkerDaoException e1 ) { throw new RuntimeException ( e1 ) ; } if ( workerStatus . size ( ) >= feed . getFeedPartitions ( ) . size ( ) ) { throw new RuntimeException ( "Number of running workers " + workerStatus . size ( ) + " >= feed partitions " + feed . getFeedPartitions ( ) . size ( ) + " plan should be fixed " + plan . getName ( ) ) ; } FeedPartition toProcess = findPartitionToProcess ( workerStatus , feed . getFeedPartitions ( ) ) ; if ( toProcess != null ) { driver = DriverFactory . createDriver ( toProcess , plan , parent . getMetricRegistry ( ) ) ; driver . initialize ( ) ; WorkerStatus iGotThis = new WorkerStatus ( myId . toString ( ) , toProcess . getPartitionId ( ) , parent . getMyId ( ) ) ; try { parent . getWorkerDao ( ) . registerWorkerStatus ( zk , plan , iGotThis ) ; } catch ( WorkerDaoException e ) { throw new RuntimeException ( e ) ; } } else { throw new RuntimeException ( "Could not start plan " + plan . getName ( ) ) ; } }
Deterine what partitions of the feed are already attached to other workers .
396
15
7,583
private void shutdown ( ) { parent . workerThreads . get ( plan ) . remove ( this ) ; if ( zk != null ) { try { logger . debug ( "closing " + zk . getSessionId ( ) ) ; zk . close ( ) ; zk = null ; } catch ( InterruptedException e1 ) { logger . debug ( e1 ) ; } logger . debug ( "shutdown complete" ) ; } }
Remove ourselves from parents worker threads and close our zk connection
95
12
7,584
@ Nonnull public String getDescription ( final Locale aContentLocale ) { final String ret = m_eCountry == null ? null : m_eCountry . getDisplayText ( aContentLocale ) ; return ret != null ? ret : "undefined" ; }
Returns the hierarchies description text from the resource bundle .
58
11
7,585
private static RDFNode toNode ( Object value ) { if ( value == null ) { return null ; } else if ( value instanceof RDFNode ) { return ( RDFNode ) value ; } else if ( value instanceof IRI ) { return new NamedNodeImpl ( URI . create ( ( ( IRI ) value ) . iri . toString ( ) ) ) ; } else if ( value instanceof PlainLiteral ) { PlainLiteral pl = ( PlainLiteral ) value ; String lang = pl . language != null ? pl . language . toString ( ) : null ; return new PlainLiteralImpl ( pl . lexical . toString ( ) , lang ) ; } else if ( value instanceof TypedLiteral ) { TypedLiteral tl = ( TypedLiteral ) value ; return new TypedLiteralImpl ( tl . lexical . toString ( ) , URI . create ( tl . datatype . toString ( ) ) ) ; } else if ( value instanceof BNode ) { return new BlankNodeImpl ( ( ( BNode ) value ) . label . toString ( ) ) ; } else { // Sherpa passes strings as something other than java.lang.String, so convert. if ( value instanceof CharSequence ) { value = value . toString ( ) ; } // What's left is a primitive Java type, convert it to an XSD-typed literal. // Falls back to xsd:anySimpleType for unrecognized classes return Conversions . toLiteral ( value ) ; } }
Convert a protocol data object to an RDFNode .
341
12
7,586
public List < M > findNear ( double latitude , double longitude , int numImages ) { return getDatastore ( ) . find ( clazz ) . field ( "location.coordinates" ) . near ( latitude , longitude ) . limit ( numImages ) . asList ( ) ; }
Returns a list of media items that are geographically near the specified coordinates
64
13
7,587
public List < M > search ( String datefield , Date date , int width , int height , int count , int offset , UserAccount account , String query , List < String > sources ) { List < Criteria > l = new ArrayList <> ( ) ; Query < M > q = getDatastore ( ) . createQuery ( clazz ) ; if ( query != null ) { Pattern p = Pattern . compile ( "(.*)" + query + "(.*)" , Pattern . CASE_INSENSITIVE ) ; l . add ( q . or ( q . criteria ( "title" ) . equal ( p ) , q . criteria ( "description" ) . equal ( p ) ) ) ; } if ( account != null ) { l . add ( q . criteria ( "contributor" ) . equal ( account ) ) ; } if ( width > 0 ) l . add ( q . criteria ( "width" ) . greaterThanOrEq ( width ) ) ; if ( height > 0 ) l . add ( q . criteria ( "height" ) . greaterThanOrEq ( height ) ) ; if ( date != null ) l . add ( q . criteria ( datefield ) . greaterThanOrEq ( date ) ) ; if ( sources != null ) l . add ( q . criteria ( "source" ) . in ( sources ) ) ; q . and ( l . toArray ( new Criteria [ l . size ( ) ] ) ) ; return q . order ( "crawlDate" ) . offset ( offset ) . limit ( count ) . asList ( ) ; }
A search function
341
3
7,588
@ SuppressWarnings ( "deprecation" ) public static void setBackground ( @ NonNull final View view , @ Nullable final Drawable background ) { Condition . INSTANCE . ensureNotNull ( view , "The view may not be null" ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN ) { view . setBackground ( background ) ; } else { view . setBackgroundDrawable ( background ) ; } }
Sets the background of a view . Depending on the device s API level different methods are used for setting the background .
107
24
7,589
@ SuppressWarnings ( "deprecation" ) public static void removeOnGlobalLayoutListener ( @ NonNull final ViewTreeObserver observer , @ Nullable final OnGlobalLayoutListener listener ) { Condition . INSTANCE . ensureNotNull ( observer , "The view tree observer may not be null" ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN ) { observer . removeOnGlobalLayoutListener ( listener ) ; } else { observer . removeGlobalOnLayoutListener ( listener ) ; } }
Removes a previous registered global layout listener from a view tree observer . Depending on the device s API level different methods are used for removing the listener .
121
30
7,590
public static void removeFromParent ( @ NonNull final View view ) { Condition . INSTANCE . ensureNotNull ( view , "The view may not be null" ) ; ViewParent parent = view . getParent ( ) ; if ( parent instanceof ViewGroup ) { ( ( ViewGroup ) parent ) . removeView ( view ) ; } }
Removes a specific view from its parent if there is any .
72
13
7,591
private void obtainScaledEdge ( @ NonNull final TypedArray typedArray ) { int defaultValue = Edge . VERTICAL . getValue ( ) ; Edge scaledEdge = Edge . fromValue ( typedArray . getInt ( R . styleable . SquareImageView_scaledEdge , defaultValue ) ) ; setScaledEdge ( scaledEdge ) ; }
Obtains the scaled edge from a specific typed array .
76
11
7,592
private static boolean _isValidForCycle ( @ Nonnull final Holiday aHoliday , final int nYear ) { final String sEvery = aHoliday . getEvery ( ) ; if ( sEvery != null && ! "EVERY_YEAR" . equals ( sEvery ) ) { if ( "ODD_YEARS" . equals ( sEvery ) ) return nYear % 2 != 0 ; if ( "EVEN_YEARS" . equals ( sEvery ) ) return nYear % 2 == 0 ; if ( aHoliday . getValidFrom ( ) != null ) { int nCycleYears = 0 ; if ( "2_YEARS" . equalsIgnoreCase ( sEvery ) ) nCycleYears = 2 ; else if ( "3_YEARS" . equalsIgnoreCase ( sEvery ) ) nCycleYears = 3 ; else if ( "4_YEARS" . equalsIgnoreCase ( sEvery ) ) nCycleYears = 4 ; else if ( "5_YEARS" . equalsIgnoreCase ( sEvery ) ) nCycleYears = 5 ; else if ( "6_YEARS" . equalsIgnoreCase ( sEvery ) ) nCycleYears = 6 ; else throw new IllegalArgumentException ( "Cannot handle unknown cycle type '" + sEvery + "'." ) ; return ( nYear - aHoliday . getValidFrom ( ) . intValue ( ) ) % nCycleYears == 0 ; } } return true ; }
Checks cyclic holidays and checks if the requested year is hit within the cycles .
329
17
7,593
private static boolean _isValidInYear ( @ Nonnull final Holiday aHoliday , final int nYear ) { return ( aHoliday . getValidFrom ( ) == null || aHoliday . getValidFrom ( ) . intValue ( ) <= nYear ) && ( aHoliday . getValidTo ( ) == null || aHoliday . getValidTo ( ) . intValue ( ) >= nYear ) ; }
Checks whether the holiday is within the valid date range .
90
12
7,594
protected static final boolean shallBeMoved ( @ Nonnull final LocalDate aFixed , @ Nonnull final MovingCondition aMoveCond ) { return aFixed . getDayOfWeek ( ) == XMLHolidayHelper . getWeekday ( aMoveCond . getSubstitute ( ) ) ; }
Determines if the provided date shall be substituted .
62
11
7,595
private static LocalDate _moveDate ( final MovingCondition aMoveCond , final LocalDate aDate ) { final DayOfWeek nWeekday = XMLHolidayHelper . getWeekday ( aMoveCond . getWeekday ( ) ) ; final int nDirection = aMoveCond . getWith ( ) == With . NEXT ? 1 : - 1 ; LocalDate aMovedDate = aDate ; while ( aMovedDate . getDayOfWeek ( ) != nWeekday ) { aMovedDate = aMovedDate . plusDays ( nDirection ) ; } return aMovedDate ; }
Moves the date using the FixedMoving information
129
9
7,596
protected static final LocalDate moveDate ( final MoveableHoliday aMoveableHoliday , final LocalDate aFixed ) { for ( final MovingCondition aMoveCond : aMoveableHoliday . getMovingCondition ( ) ) if ( shallBeMoved ( aFixed , aMoveCond ) ) return _moveDate ( aMoveCond , aFixed ) ; return aFixed ; }
Moves a date if there are any moving conditions for this holiday and any of them fit .
80
19
7,597
protected final void setCurrentParentView ( @ NonNull final View currentParentView ) { Condition . INSTANCE . ensureNotNull ( currentParentView , "The parent view may not be null" ) ; this . currentParentView = currentParentView ; }
Sets the parent view whose appearance should currently be customized by the decorator . This method should never be called or overridden by any custom adapter implementation .
53
31
7,598
@ SuppressWarnings ( "unchecked" ) protected final < ViewType extends View > ViewType findViewById ( @ IdRes final int viewId ) { Condition . INSTANCE . ensureNotNull ( currentParentView , "No parent view set" , IllegalStateException . class ) ; ViewHolder viewHolder = ( ViewHolder ) currentParentView . getTag ( ) ; if ( viewHolder == null ) { viewHolder = new ViewHolder ( currentParentView ) ; currentParentView . setTag ( viewHolder ) ; } return ( ViewType ) viewHolder . findViewById ( viewId ) ; }
References the view which belongs to a specific resource ID by using the view holder pattern . The view is implicitly casted to the type of the field it is assigned to .
137
34
7,599
private void writeSlot ( T data , Throwable error ) { dataLock . lock ( ) ; try { this . error = error ; this . data = data ; availableCondition . signalAll ( ) ; } finally { dataLock . unlock ( ) ; } }
either data or error should be non - null
54
9