idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
5,900 | static boolean requireLeftAlignment ( String reference , String alternate ) { return StringUtils . isEmpty ( reference ) || StringUtils . isEmpty ( alternate ) || reference . charAt ( reference . length ( ) - 1 ) == alternate . charAt ( alternate . length ( ) - 1 ) ; } | Reference and alternate are either empty or last base from each is equal |
5,901 | private boolean isNormalizable ( Variant variant ) { return ! variant . getType ( ) . equals ( VariantType . NO_VARIATION ) && ! variant . getType ( ) . equals ( VariantType . SYMBOLIC ) ; } | Non normalizable variants |
5,902 | private int [ ] getGenotypesReorderingMap ( int numAllele , int [ ] alleleMap ) { int numAlleles = alleleMap . length ; int key = numAllele * 100 + numAlleles ; int [ ] map = genotypeReorderMapCache . get ( key ) ; if ( map != null ) { return map ; } else { ArrayList < Integer > mapList = new ArrayList < > ( ) ; for ( int originalA2 = 0 ; originalA2 < alleleMap . length ; originalA2 ++ ) { int newA2 = ArrayUtils . indexOf ( alleleMap , originalA2 ) ; for ( int originalA1 = 0 ; originalA1 <= originalA2 ; originalA1 ++ ) { int newA1 = ArrayUtils . indexOf ( alleleMap , originalA1 ) ; if ( newA1 <= newA2 ) { mapList . add ( ( newA2 * ( newA2 + 1 ) / 2 + newA1 ) ) ; } else { mapList . add ( ( newA1 * ( newA1 + 1 ) / 2 + newA2 ) ) ; } } } map = new int [ mapList . size ( ) ] ; for ( int i = 0 ; i < mapList . size ( ) ; i ++ ) { map [ i ] = mapList . get ( i ) ; } genotypeReorderMapCache . put ( key , map ) ; return map ; } } | Gets an array for reordening the positions of a format field with Number = G and ploidy = 2 . |
5,903 | public static void calculateCoverate ( Path bamPath , Path sqlPath ) throws IOException , AlignmentCoverageException { BamManager bamManager = new BamManager ( bamPath ) ; if ( ! bamPath . getParent ( ) . resolve ( bamPath . getFileName ( ) . toString ( ) + ".bai" ) . toFile ( ) . exists ( ) ) { bamManager . createIndex ( ) ; } SAMFileHeader fileHeader = BamUtils . getFileHeader ( bamPath ) ; initDatabase ( fileHeader . getSequenceDictionary ( ) . getSequences ( ) , sqlPath ) ; Path coveragePath = sqlPath . toAbsolutePath ( ) . resolve ( bamPath . getFileName ( ) + COVERAGE_SUFFIX ) ; AlignmentOptions options = new AlignmentOptions ( ) ; options . setContained ( false ) ; Iterator < SAMSequenceRecord > iterator = fileHeader . getSequenceDictionary ( ) . getSequences ( ) . iterator ( ) ; PrintWriter writer = new PrintWriter ( coveragePath . toFile ( ) ) ; StringBuilder line ; while ( iterator . hasNext ( ) ) { SAMSequenceRecord next = iterator . next ( ) ; for ( int i = 0 ; i < next . getSequenceLength ( ) ; i += MINOR_CHUNK_SIZE ) { Region region = new Region ( next . getSequenceName ( ) , i + 1 , Math . min ( i + MINOR_CHUNK_SIZE , next . getSequenceLength ( ) ) ) ; RegionCoverage regionCoverage = bamManager . coverage ( region , null , options ) ; int meanDepth = Math . min ( regionCoverage . meanCoverage ( ) , 255 ) ; line = new StringBuilder ( ) ; line . append ( region . getChromosome ( ) ) . append ( "_" ) ; line . append ( i / MINOR_CHUNK_SIZE ) . append ( "_" ) . append ( MINOR_CHUNK_SIZE / 1000 ) . append ( "k" ) ; line . append ( "\t" ) . append ( region . getChromosome ( ) ) ; line . append ( "\t" ) . append ( region . getStart ( ) ) ; line . append ( "\t" ) . append ( region . getEnd ( ) ) ; line . append ( "\t" ) . append ( meanDepth ) ; writer . println ( line . toString ( ) ) ; } } writer . close ( ) ; insertCoverageDB ( bamPath , sqlPath ) ; } | Calculate the coverage for the input BAM file . The coverage is stored in a SQLite database located in the sqlPath output directory . |
5,904 | public List < MeasureType . MeasureRelationship > getMeasureRelationship ( ) { if ( measureRelationship == null ) { measureRelationship = new ArrayList < MeasureType . MeasureRelationship > ( ) ; } return this . measureRelationship ; } | Gets the value of the measureRelationship property . |
5,905 | public List < String > getFormat ( ) { return impl . getFormat ( ) == null ? null : Collections . unmodifiableList ( impl . getFormat ( ) ) ; } | Do not modify this list |
5,906 | public static void calculateStatsForVariantsList ( List < Variant > variants , Pedigree ped ) { for ( Variant variant : variants ) { for ( StudyEntry entry : variant . getStudies ( ) ) { VariantStats stats = calculate ( variant , entry ) ; entry . setStats ( StudyEntry . DEFAULT_COHORT , stats ) ; } } } | Calculates the statistics for some variants read from a set of files and optionally given pedigree information . Some statistics like inheritance patterns can only be calculated if pedigree information is provided . |
5,907 | private static int [ ] getGenotypeReorderingMap ( int ploidy , int [ ] map ) { int [ ] gMap ; if ( ploidy == 1 ) { gMap = new int [ map . length + 1 ] ; gMap [ 0 ] = 0 ; for ( int i = 0 ; i < map . length ; i ++ ) { gMap [ i + 1 ] = map [ i ] + 1 ; } } else if ( ploidy == 2 ) { int l = map . length ; gMap = new int [ l * ( l + 1 ) / 2 + l + 1 ] ; for ( int i = 0 ; i < gMap . length ; i ++ ) { gMap [ i ] = - 1 ; } int pos = 0 ; for ( int a2 = 0 ; a2 <= map . length ; a2 ++ ) { int newA2 = remapAlleleReverse ( map , a2 ) ; if ( newA2 < 0 ) { continue ; } for ( int a1 = 0 ; a1 <= a2 ; a1 ++ ) { int newA1 = remapAlleleReverse ( map , a1 ) ; if ( newA1 < 0 ) { continue ; } if ( newA2 > newA1 ) { gMap [ newA2 * ( newA2 + 1 ) / 2 + newA1 ] = pos ++ ; } else { gMap [ newA1 * ( newA1 + 1 ) / 2 + newA2 ] = pos ++ ; } } } } else { List < String > originalOrdering = getOrdering ( ploidy , map . length , null ) ; List < String > reorderedOrdering = getOrdering ( ploidy , map . length , map ) ; gMap = new int [ originalOrdering . size ( ) ] ; for ( int i = 0 ; i < reorderedOrdering . size ( ) ; i ++ ) { gMap [ i ] = originalOrdering . indexOf ( reorderedOrdering . get ( i ) ) ; } } return gMap ; } | Gets an array for reordering the positions of a format field with Number = G and ploidy = 2 . |
5,908 | public static void getOrdering ( int p , int n , List < String > list , int [ ] gt , int pos , int [ ] map ) { for ( int a = 0 ; a <= n ; a ++ ) { if ( map == null ) { gt [ pos ] = a ; } else { gt [ pos ] = remapAllele ( map , a ) ; } if ( p == 1 ) { int prev = gt [ 0 ] ; int [ ] gtSorted = gt ; for ( int g : gt ) { if ( prev > g ) { gtSorted = Arrays . copyOf ( gt , gt . length ) ; Arrays . sort ( gtSorted ) ; break ; } } StringBuilder sb = new StringBuilder ( ) ; for ( int g : gtSorted ) { sb . append ( g ) ; } list . add ( sb . toString ( ) ) ; } else { getOrdering ( p - 1 , a , list , gt , pos - 1 , map ) ; } } } | Recursive genotype ordering algorithm as seen in VCF - spec . |
5,909 | private List < ConsequenceType > setConsequenceTypeParams ( ) { List < ConsequenceType > consequenceTypeList = new ArrayList < > ( ) ; ConsequenceType . Builder consequenceType = ConsequenceType . newBuilder ( ) ; consequenceType . setGeneName ( null ) ; consequenceType . setEnsemblGeneId ( null ) ; consequenceType . setEnsemblTranscriptId ( null ) ; consequenceType . setStrand ( null ) ; consequenceType . setBiotype ( null ) ; consequenceType . setCDnaPosition ( 0 ) ; consequenceType . setCdsPosition ( 0 ) ; consequenceType . setCodon ( null ) ; ProteinVariantAnnotation . Builder proteinVariantAnnotation = ProteinVariantAnnotation . newBuilder ( ) ; proteinVariantAnnotation . addAllSubstitutionScores ( Arrays . asList ( ) ) ; consequenceType . setProteinVariantAnnotation ( proteinVariantAnnotation ) ; List < VariantAnnotationProto . SequenceOntologyTerm > sequenceOntologyTerms = new ArrayList < > ( ) ; VariantAnnotationProto . SequenceOntologyTerm . Builder sequenceOntologyTerm = VariantAnnotationProto . SequenceOntologyTerm . newBuilder ( ) ; sequenceOntologyTerm . setAccession ( null ) ; sequenceOntologyTerm . setName ( null ) ; sequenceOntologyTerms . add ( sequenceOntologyTerm . build ( ) ) ; consequenceType . addAllSequenceOntologyTerms ( sequenceOntologyTerms ) ; consequenceType . setStrand ( null ) ; consequenceTypeList . add ( consequenceType . build ( ) ) ; return consequenceTypeList ; } | method to set Consequence Type Parameters |
5,910 | private List < VariantAnnotationProto . PopulationFrequency > setPopulationFrequencyParams ( ) { List < VariantAnnotationProto . PopulationFrequency > populationFrequencyList = new ArrayList < > ( ) ; VariantAnnotationProto . PopulationFrequency . Builder populationFrequency = VariantAnnotationProto . PopulationFrequency . newBuilder ( ) ; populationFrequency . setAltAllele ( null ) ; populationFrequency . setAltAlleleFreq ( 0.0f ) ; populationFrequency . setAltHomGenotypeFreq ( 0.0f ) ; populationFrequency . setHetGenotypeFreq ( 0.0f ) ; populationFrequency . setPopulation ( null ) ; populationFrequency . setRefAllele ( null ) ; populationFrequency . setRefAlleleFreq ( 0.0f ) ; populationFrequency . setRefHomGenotypeFreq ( 0.0f ) ; populationFrequency . setStudy ( null ) ; populationFrequencyList . add ( populationFrequency . build ( ) ) ; return populationFrequencyList ; } | method to set Population Frequency Parameters |
5,911 | private VariantAnnotationProto . VariantAnnotation setVaraintAnnotationParams ( ) { VariantAnnotationProto . VariantAnnotation . Builder variantAnnotation = VariantAnnotationProto . VariantAnnotation . newBuilder ( ) ; HashMap < String , VariantAnnotationProto . VariantAnnotation . AdditionalAttribute > map = new HashMap < > ( ) ; variantAnnotation . putAllAdditionalAttributes ( map ) ; variantAnnotation . setAlternate ( null ) ; variantAnnotation . setChromosome ( null ) ; VariantAnnotationProto . VariantTraitAssociation . Builder variantTraitAssociation = VariantAnnotationProto . VariantTraitAssociation . newBuilder ( ) ; variantTraitAssociation . addAllClinvar ( Arrays . asList ( ) ) ; variantTraitAssociation . addAllCosmic ( Arrays . asList ( ) ) ; variantTraitAssociation . addAllGwas ( Arrays . asList ( ) ) ; variantAnnotation . setVariantTraitAssociation ( variantTraitAssociation ) ; variantAnnotation . addAllConsequenceTypes ( setConsequenceTypeParams ( ) ) ; List < VariantAnnotationProto . Score > conservationScoreList = new ArrayList < > ( ) ; VariantAnnotationProto . Score . Builder score = VariantAnnotationProto . Score . newBuilder ( ) ; conservationScoreList . add ( score . build ( ) ) ; variantAnnotation . addAllConservation ( conservationScoreList ) ; variantAnnotation . setEnd ( 0 ) ; List < CommonModel . GeneDrugInteraction > geneDrugInteractionList = new ArrayList < > ( ) ; variantAnnotation . addAllGeneDrugInteraction ( geneDrugInteractionList ) ; List < String > hgvsList = new ArrayList < > ( ) ; variantAnnotation . addAllHgvs ( hgvsList ) ; variantAnnotation . setId ( null ) ; variantAnnotation . addAllPopulationFrequencies ( setPopulationFrequencyParams ( ) ) ; variantAnnotation . setReference ( null ) ; variantAnnotation . setStart ( 0 ) ; List < VariantAnnotationProto . VariantAnnotation . Xref > xrefsList = new ArrayList < > ( ) ; VariantAnnotationProto . VariantAnnotation . Xref . Builder xref = VariantAnnotationProto . VariantAnnotation . Xref . newBuilder ( ) ; xrefsList . add ( xref . build ( ) ) ; variantAnnotation . addAllXrefs ( xrefsList ) ; return variantAnnotation . build ( ) ; } | method to set Varaint Annotation Parameters |
5,912 | public Part < T > setContentType ( MediaType contentType ) { headers . add ( HttpHeaders . CONTENT_TYPE , contentType . toString ( ) ) ; return this ; } | Sets the Content - Type of this request . |
5,913 | public void setPartConverters ( List < HttpMessageConverter > partConverters ) { checkNotNull ( partConverters , "'partConverters' must not be null" ) ; checkArgument ( ! partConverters . isEmpty ( ) , "'partConverters' must not be empty" ) ; this . partConverters = partConverters ; } | Set the message body converters to use . These converters are used to convert objects to MIME parts . |
5,914 | public void addPartConverter ( HttpMessageConverter partConverter ) { checkNotNull ( partConverters , "'partConverters' must not be null" ) ; checkArgument ( ! partConverters . isEmpty ( ) , "'partConverters' must not be empty" ) ; this . partConverters . add ( partConverter ) ; } | Add a message body converter . Such a converter is used to convert objects to MIME parts . |
5,915 | public RestClientOptions putGlobalHeaders ( MultiMap headers ) { for ( Map . Entry < String , String > header : headers ) { globalHeaders . add ( header . getKey ( ) , header . getValue ( ) ) ; } return this ; } | Set global headers which will be appended to every HTTP request . The headers defined per request will override this headers . |
5,916 | public RestClientOptions putGlobalHeader ( String name , String value ) { globalHeaders . add ( name , value ) ; return this ; } | Add a global header which will be appended to every HTTP request . The headers defined per request will override this headers . |
5,917 | public byte [ ] getResponseBodyAsByteArray ( ) { final ByteBuf bodyByteBuf = httpInputMessage . getBody ( ) ; final byte [ ] bytes = new byte [ bodyByteBuf . readableBytes ( ) ] ; bodyByteBuf . readBytes ( bytes ) ; return bytes ; } | Return the response body as a byte array . |
5,918 | public < T > T getResponseBody ( Class < T > clazz ) { final ByteBuf byteBuf = httpInputMessage . getBody ( ) ; if ( byteBuf . readableBytes ( ) == 0 || Void . class . isAssignableFrom ( clazz ) ) return null ; final MediaType mediaType = MediaType . parseMediaType ( httpInputMessage . getHeaders ( ) . get ( HttpHeaders . CONTENT_TYPE ) ) ; for ( HttpMessageConverter httpMessageConverter : httpMessageConverters ) { if ( httpMessageConverter . canRead ( clazz , mediaType ) ) { return ( T ) httpMessageConverter . read ( clazz , httpInputMessage ) ; } } return null ; } | Return the response body converted to the given class |
5,919 | public String getResponseBodyAsString ( ) { final ByteBuf bodyByteBuf = httpInputMessage . getBody ( ) ; final String contentEncoding = httpInputMessage . getHeaders ( ) . get ( HttpHeaders . CONTENT_ENCODING ) ; byte [ ] bytes = new byte [ bodyByteBuf . readableBytes ( ) ] ; bodyByteBuf . readBytes ( bytes ) ; return new String ( bytes , contentEncoding != null ? Charset . forName ( contentEncoding ) : Charset . forName ( DEFAULT_CHARSET ) ) ; } | Return the response body as a string . |
5,920 | public File locateResource ( String name ) { for ( int i = 0 ; i < resourcePath . length ; i ++ ) { File fi = new File ( resourcePath [ i ] . getAbsolutePath ( ) + File . separator + name ) ; if ( fi . exists ( ) ) return fi ; } return null ; } | iterate component directories in order and return full path of first file matching |
5,921 | public byte [ ] retrieveBytes ( File impFi ) { if ( resourceLocator != null ) { byte [ ] bytes = resourceLocator . retrieveBytes ( impFi ) ; if ( bytes != null ) return bytes ; } return HtmlImportShim . ResourceLocator . super . retrieveBytes ( impFi ) ; } | this part of locator interface is only implemented if another resourcelocator is set . |
5,922 | private RLSupplier < Value > evaluate ( ) { if ( stackRPN . empty ( ) ) { return ( ) -> new StringValue ( "" ) ; } stackAnswer . clear ( ) ; @ SuppressWarnings ( "unchecked" ) Stack stackRPN = ( Stack ) this . stackRPN . clone ( ) ; while ( ! stackRPN . empty ( ) ) { Object token = stackRPN . pop ( ) ; if ( token instanceof Value ) { stackAnswer . push ( ( RLSupplier ) ( ) -> token ) ; } else if ( token instanceof Operator ) { int arity = ( ( Operator ) token ) . getArity ( ) ; if ( arity == 2 ) { RLSupplier a = ( RLSupplier ) stackAnswer . pop ( ) ; RLSupplier b = ( RLSupplier ) stackAnswer . pop ( ) ; stackAnswer . push ( ( ( Operator ) token ) . getEval ( a , b ) ) ; } else { RLSupplier a = ( RLSupplier ) stackAnswer . pop ( ) ; stackAnswer . push ( ( ( Operator ) token ) . getEval ( a , null ) ) ; } } else if ( token instanceof VarPath ) { VarPath vp = ( VarPath ) token ; stackAnswer . push ( vp . getEval ( ) ) ; } else if ( token instanceof FuncOperand ) { FuncOperand func = ( FuncOperand ) token ; RLSupplier < Value > args [ ] = new RLSupplier [ func . getArity ( ) ] ; for ( int i = 0 ; i < args . length ; i ++ ) { args [ args . length - i - 1 ] = ( ( RLSupplier < Value > ) stackAnswer . pop ( ) ) ; } stackAnswer . push ( func . getEval ( args ) ) ; } } if ( stackAnswer . size ( ) > 1 ) { throw new QParseException ( "Some operator is missing" ) ; } return ( RLSupplier < Value > ) stackAnswer . pop ( ) ; } | Evaluates once parsed to a lambda term |
5,923 | public WebSocketPublisher toWS ( ) { return new WebSocketPublisher ( ) . coding ( coding ) . facade ( facade ) . hostName ( hostName ) . port ( port ) . urlPath ( urlPath ) ; } | enables sharing of common settings if publishing also as websocket service |
5,924 | public IPromise scheduleSendLoop ( ConnectionRegistry reg ) { Promise promise = new Promise ( ) ; sendJobs . add ( new ScheduleEntry ( reg , promise ) ) ; synchronized ( this ) { if ( ! loopStarted ) { loopStarted = true ; Actor . current ( ) . execute ( this ) ; } } return promise ; } | return a future which is completed upon connection close |
5,925 | public void run ( ) { pollThread = Thread . currentThread ( ) ; if ( underway ) return ; underway = true ; try { int count = 1 ; while ( count > 0 ) { count = onePoll ( ) ; if ( sendJobs . size ( ) > 0 ) { if ( count > 0 ) { int debug = 1 ; } else { if ( remoteRefCounter == 0 ) { Actor . current ( ) . delayed ( 100 , this ) ; } else { Actor . current ( ) . delayed ( 1 , this ) ; } } } else { Actor . current ( ) . delayed ( 100 , this ) ; } } } finally { underway = false ; } } | counts active remote refs if none backoff remoteref polling massively eats cpu |
5,926 | public void withCallback ( String arg , Callback callback ) { callback . pipe ( "Hello" ) ; callback . pipe ( arg ) ; callback . finish ( ) ; } | identical but uses convenience methods |
5,927 | public KUrl unified ( ) { KUrl res = new KUrl ( toUrlString ( false ) ) ; res . elements [ 0 ] = normalizeDomain ( elements [ 0 ] ) ; return res ; } | removes www protocol and country |
5,928 | protected String normalizeDomain ( String s ) { int idx = s . lastIndexOf ( "." ) ; if ( idx >= 0 ) { s = s . substring ( 0 , idx ) ; } if ( s . startsWith ( "www." ) ) s = s . substring ( 4 ) ; return s ; } | removes www in case and removes country code . EXPECT protocol to be absent |
5,929 | public IPromise < T > then ( Runnable result ) { return then ( ( r , e ) -> result . run ( ) ) ; } | see IPromise interface |
5,930 | public Promise getNext ( ) { while ( ! lock . compareAndSet ( false , true ) ) { } try { if ( nextFuture == null ) return new Promise ( ) ; else return ( Promise ) nextFuture ; } finally { lock . set ( false ) ; } } | special method for tricky things . Creates a nextFuture or returns it . current |
5,931 | public void finallyDo ( Callback resultCB ) { while ( ! lock . compareAndSet ( false , true ) ) { } try { if ( resultReceiver != null ) throw new RuntimeException ( "Double register of future listener" ) ; resultReceiver = resultCB ; if ( hadResult ) { hasFired = true ; lock . set ( false ) ; resultCB . complete ( result , error ) ; } } finally { lock . set ( false ) ; } } | same as then but avoid creation of new promise |
5,932 | public static < T extends Actor > T AsActor ( Class < T > actorClazz ) { return ( T ) instance . newProxy ( actorClazz , defaultScheduler . get ( ) , - 1 ) ; } | create an new actor . If this is called outside an actor a new DispatcherThread will be scheduled . If called from inside actor code the new actor will share the thread + queue with the caller . |
5,933 | public static < T extends Actor > T AsActor ( Class < T > actorClazz , Scheduler scheduler , int qsize ) { return ( T ) instance . newProxy ( actorClazz , scheduler , qsize ) ; } | create an new actor dispatched in the given DispatcherThread |
5,934 | public static < T > IPromise < IPromise < T > [ ] > all ( IPromise < T > ... futures ) { Promise res = new Promise ( ) ; awaitSettle ( futures , res ) ; return res ; } | similar to es6 Promise . all method however non - IPromise objects are not allowed |
5,935 | public static < T > IPromise < List < T > > allMapped ( List < IPromise < T > > futures ) { Promise returned = new Promise ( ) ; Promise res = new Promise ( ) ; awaitSettle ( futures , res ) ; res . then ( ( r , e ) -> { if ( r != null ) { returned . resolve ( ( ( List < Promise > ) r ) . stream ( ) . map ( p -> p . get ( ) ) . collect ( Collectors . toList ( ) ) ) ; } else { returned . complete ( null , e ) ; } } ) ; return returned ; } | similar all but map promises to their content |
5,936 | public static < T > IPromise < T > complete ( T res , Object err ) { return new Promise < > ( res , err ) ; } | abbreviation for Promise creation to make code more concise |
5,937 | public static void main ( String [ ] args ) { Actor remote = ( Actor ) new WebSocketConnectable ( ) . actorClass ( Actor . class ) . url ( "ws://localhost:3999" ) . serType ( SerializerType . JsonNoRef ) . connect ( ( x , y ) -> System . out . println ( "disconnect " + x + " " + y ) ) . await ( ) ; remote . ask ( "greet" , "Kontraktor" , 1000 ) . then ( ( r , e ) -> System . out . println ( r ) ) ; } | with Java - implemented Servers . Use typed clients meanwhile |
5,938 | protected IPromise < JsonObject > getDistributions ( String module ) { Promise res = new Promise ( ) ; http . getContent ( config . getRepo ( ) + "/-/package/" + module + "/dist-tags" ) . then ( ( cont , err ) -> { if ( cont != null ) { JsonObject parse = Json . parse ( cont ) . asObject ( ) ; res . resolve ( parse ) ; } else { res . reject ( err ) ; } } ) ; return res ; } | map of tag = > version |
5,939 | public void addTagName ( char c ) { if ( tagName == null ) tagName = new StringBuilder ( 10 ) ; if ( c > 0 ) tagName . append ( c ) ; } | attrs if this is tag |
5,940 | void removeActorImmediate ( Actor act ) { if ( Thread . currentThread ( ) != this ) throw new RuntimeException ( "wrong thread" ) ; Actor newAct [ ] = new Actor [ actors . length - 1 ] ; int idx = 0 ; for ( int i = 0 ; i < actors . length ; i ++ ) { Actor actor = actors [ i ] ; if ( actor != act ) newAct [ idx ++ ] = actor ; } if ( idx != newAct . length ) throw new RuntimeException ( "could not remove actor" ) ; actors = newAct ; } | removes immediate must be called from this thread |
5,941 | public void schedulePendingAdds ( ) { ArrayList < Actor > newOnes = new ArrayList < > ( ) ; Actor a ; while ( ( a = toAdd . poll ( ) ) != null ) { newOnes . add ( a ) ; } if ( newOnes . size ( ) > 0 ) { Actor newQueue [ ] = new Actor [ newOnes . size ( ) + actors . length ] ; System . arraycopy ( actors , 0 , newQueue , 0 , actors . length ) ; for ( int i = 0 ; i < newOnes . size ( ) ; i ++ ) { Actor actor = newOnes . get ( i ) ; newQueue [ actors . length + i ] = actor ; } actors = newQueue ; } } | add actors which have been marked to be scheduled on this |
5,942 | public int getAccumulatedQSizes ( ) { int res = 0 ; final Actor actors [ ] = this . actors ; for ( int i = 0 ; i < actors . length ; i ++ ) { res += actors [ i ] . getQSizes ( ) ; } return res ; } | accumulated queue sizes of all actors |
5,943 | public boolean schedules ( Object receiverRef ) { if ( Thread . currentThread ( ) != this ) { throw new RuntimeException ( "cannot call from foreign thread" ) ; } if ( receiverRef instanceof Actor ) { return ( ( Actor ) receiverRef ) . __currentDispatcher == this ; } return false ; } | can be called from the dispacther thread itself only |
5,944 | protected String [ ] getResourcePathElements ( BasicWebAppConfig cfg ) { return new String [ ] { cfg . getClientRoot ( ) , cfg . getClientRoot ( ) + "/node_modules" , } ; } | need to patch resourcepath as browserify expects node modules at same level as local imports |
5,945 | public void finish ( ) { if ( finSignal == null && finished ) return ; cb . complete ( null , null ) ; finished = true ; } | to be called at remote side when using streaming to deliver multiple results call this in order to signal no further results are expected . |
5,946 | public String scanLastNWSDouble ( ) { int off = - 1 ; while ( Character . isWhitespace ( ch ( off ) ) && off + index >= 0 ) { off -- ; } return "" + ch ( off ) + ch ( off - 1 ) ; } | last two nonws chars |
5,947 | protected IPromise < BasicAuthenticationResult > getCredentials ( String user , String pw , String jwt ) { Promise p = new Promise ( ) ; if ( SESSIONID_SPECIAL_STRING . equals ( pw ) ) { sessionStorage . getUserFromSessionId ( user ) . then ( ( r , e ) -> { if ( r != null ) { sessionStorage . getUser ( r ) . then ( ( rec , err ) -> { if ( rec != null ) getCredentials ( rec . getKey ( ) , rec . getString ( "pwd" ) , null ) . then ( p ) ; else p . reject ( "unknown user" ) ; } ) ; } else { p . reject ( "authentication failed" ) ; } } ) ; } else { sessionStorage . getUser ( user ) . then ( ( rec , err ) -> { if ( rec == null ) { p . reject ( "wrong user or password" ) ; } else { if ( pw . equals ( rec . getString ( "pwd" ) ) ) { if ( ! rec . getBool ( "verified" ) ) { p . reject ( "account not verified" ) ; } else p . resolve ( new BasicAuthenticationResult ( ) . userName ( rec . getKey ( ) ) ) ; } } } ) ; } return p ; } | does a lookup for a user record using user as key . Compares pw with pwd of user record if found if user denotes a vaild old session id and pwd == SESSION_ID a session is created from a previous authentication |
5,948 | public IPromise < Actor > reanimate ( String sessionId , long remoteRefId ) { if ( sessionStorage == null ) return resolve ( null ) ; Promise res = new Promise ( ) ; sessionStorage . getUserFromSessionId ( sessionId ) . then ( ( user , err ) -> { if ( user == null ) res . resolve ( null ) ; else { getSessionForReanimation ( user , sessionId ) . then ( res ) ; } } ) ; return res ; } | An existing spa client made a request after being inactive for a long time . |
5,949 | public void handleDirectRequest ( HttpServerExchange exchange ) { Log . Info ( this , "direct request received " + exchange ) ; getDirectRequestResponse ( exchange . getRequestPath ( ) ) . then ( ( s , err ) -> { exchange . setResponseCode ( 200 ) ; exchange . getResponseHeaders ( ) . put ( Headers . CONTENT_TYPE , "text/html; charset=utf-8" ) ; exchange . getResponseSender ( ) . send ( s == null ? "" + err : s ) ; } ) ; } | reply a request catched by interceptor note this is server dependent and bound to undertow . for servlet containers just override KontraktorServlet methods |
5,950 | public void msg ( Thread t , int severity , Object source , Throwable ex , String msg ) { logger . msg ( t , severity , source , ex , msg ) ; } | async mother method |
5,951 | public void sendShortPoll ( ) { myExec . execute ( new Runnable ( ) { public void run ( ) { Object [ ] req = new Object [ ] { "SP" , lastSeenSeq } ; sendCallArray ( req ) ; } } ) ; } | send an empty request polling for messages on server side . Unlike long poll this request returns immediately and is not delayed by the server |
5,952 | protected int processResponse ( byte [ ] b ) { if ( DumpProtocol ) { try { System . out . println ( "resp:" + new String ( b , "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } Object o [ ] = ( Object [ ] ) conf . asObject ( b ) ; if ( SENDDEBUG ) System . out . println ( "RECEIVE:" + ( o . length - 1 ) ) ; int seq = ( ( Number ) o [ o . length - 1 ] ) . intValue ( ) ; if ( seq == lastSeenSeq + 1 || lastSeenSeq == 0 || noSeqChecking ) { lastSeenSeq = seq ; processDecodedResultArray ( o ) ; Object next [ ] ; while ( ( next = ( Object [ ] ) sequenceCache . get ( lastSeenSeq + 1 ) ) != null ) { lastSeenSeq ++ ; sequenceCache . remove ( lastSeenSeq ) ; log ( "replay " + lastSeenSeq ) ; processDecodedResultArray ( next ) ; } } else { log ( "ignored result with sequence:" + seq + " lastSeen:" + lastSeenSeq ) ; if ( seq > lastSeenSeq ) { sequenceCache . put ( seq , o ) ; if ( sequenceCache . size ( ) > 5 ) { disconnect ( "Unrecoverable Gap" ) ; } } } return o . length - 1 ; } | caches early responses in case of response race |
5,953 | public byte [ ] retrieveBytes ( File impFi ) { String fname = impFi . getName ( ) ; int idx = fname . indexOf ( '.' ) ; if ( idx >= 0 ) { String ext = fname . substring ( idx + 1 ) . toLowerCase ( ) ; TranspilerHook transpilerHook = transpilerMap . get ( ext ) ; if ( transpilerHook != null ) { return transpilerHook . transpile ( impFi , this , new HashMap ( ) ) ; } } return null ; } | invoke transpilers during prodmode inlining |
5,954 | public Pair < Boolean , Object > hasValueChanged ( String fieldId ) { for ( int i = 0 ; i < changedFields . length ; i ++ ) { String changedField = changedFields [ i ] ; if ( fieldId . equals ( changedField ) ) { return new Pair < > ( true , oldValues [ i ] ) ; } } return new Pair < > ( false , null ) ; } | return wether field is in changedfieldlist and old value of this field |
5,955 | public int originalSize ( ) { Block < T > currentHeadBlock = getHeadBlock ( ) ; int head = currentHeadBlock . head ( ) ; int size = 0 ; while ( true ) { if ( head == getBlockSize ( ) ) { Block < T > nextHeadBlock = currentHeadBlock . next ( ) ; if ( nextHeadBlock == null ) { break ; } else { currentHeadBlock = nextHeadBlock ; head = currentHeadBlock . head ( ) ; } } else { Object element = currentHeadBlock . peek ( head ) ; if ( element == REMOVED_ELEMENT ) { ++ head ; } else if ( element != null ) { ++ size ; ++ head ; } else { break ; } } } return size ; } | this method has been modified from original jetty version it only returns a size rounded to blockSize |
5,956 | public void tellSubscribers ( Actor sender , String topic , Object message ) { List < ReceiverActor > subscriber = topic2Subscriber . get ( topic ) ; if ( subscriber != null ) { subscriber . stream ( ) . filter ( subs -> ! subs . equals ( sender ) ) . forEach ( subs -> subs . receiveTell ( topic , message ) ) ; } } | send a fire and forget message to all |
5,957 | public void askSubscribers ( Actor sender , String topic , Object message , Callback cb ) { List < ReceiverActor > subscriber = topic2Subscriber . get ( topic ) ; if ( subscriber != null ) { List < IPromise > results = subscriber . stream ( ) . filter ( subs -> ! subs . equals ( sender ) ) . map ( subs -> subs . receiveAsk ( topic , message ) ) . collect ( Collectors . toList ( ) ) ; try { all ( ( List ) results ) . await ( 5000 ) ; } catch ( Exception ex ) { Log . Info ( this , "timeout in broadcast" ) ; } results . forEach ( promise -> cb . pipe ( promise . get ( ) ) ) ; cb . finish ( ) ; } } | send a message to all and stream the result of each receiver back to sender |
5,958 | public void complete ( T result , Object error ) { synchronized ( this ) { if ( isComplete ) { throw new RuntimeException ( "Promise can be completed only once" ) ; } this . result = result ; this . error = error ; isComplete = true ; tryFire ( ) ; } } | to be called by code returning an result or error . |
5,959 | private boolean couldBeRegexp ( Inp in ) { return "(,=:[!&|?{};" . indexOf ( in . scanLastNWS ( ) ) >= 0 || "*/" . equalsIgnoreCase ( in . scanLastNWSDouble ( ) ) || in . isFirstCharAfterLineBreak ( ) ; } | assumes comments are logically excluded |
5,960 | public IPromise atomicQuery ( String key , RLFunction < Record , Object > action ) { Record rec = getStore ( ) . get ( key ) ; if ( rec == null ) { final Object apply = action . apply ( rec ) ; if ( apply instanceof ChangeMessage ) { receive ( ( ChangeMessage ) apply ) ; } return new Promise ( apply ) ; } else { PatchingRecord pr = new PatchingRecord ( rec ) ; final Object res = action . apply ( pr ) ; if ( res instanceof ChangeMessage ) { receive ( ( ChangeMessage ) res ) ; } else { UpdateMessage updates = pr . getUpdates ( 0 ) ; if ( updates != null ) { receive ( updates ) ; } } return new Promise ( res ) ; } } | apply the function to the record with given key and return the result inside a promise |
5,961 | public RealLiveTable tbl ( String name ) { return ( RealLiveTable ) getActor ( ) . syncTableAccess . get ( name ) ; } | shorthand for getTable |
5,962 | public static ServiceActor RunTCP ( String args [ ] , Class < ? extends ServiceActor > serviceClazz , Class < ? extends ServiceArgs > argsClazz ) { ServiceActor myService = AsActor ( serviceClazz ) ; ServiceArgs options = null ; try { options = ServiceRegistry . parseCommandLine ( args , null , argsClazz . newInstance ( ) ) ; } catch ( Exception e ) { FSTUtil . rethrow ( e ) ; } TCPConnectable connectable = new TCPConnectable ( ServiceRegistry . class , options . getRegistryHost ( ) , options . getRegistryPort ( ) ) ; myService . init ( connectable , options , true ) . await ( 30_000 ) ; Log . Info ( myService . getClass ( ) , "Init finished" ) ; return myService ; } | run & connect a service with given cmdline args and classes |
5,963 | protected void registerSelf ( ) { publishSelf ( ) ; serviceRegistry . get ( ) . registerService ( getServiceDescription ( ) ) ; serviceRegistry . get ( ) . subscribe ( ( pair , err ) -> { serviceEvent ( pair . car ( ) , pair . cdr ( ) , err ) ; } ) ; heartBeat ( ) ; Log . Info ( this , "registered at serviceRegistry." ) ; } | register at service registry |
5,964 | public void initFromIterator ( Iterator < IN > iterator ) { this . pending = new ArrayDeque < > ( ) ; isIteratorBased = true ; Executor iteratorThread = new ThreadPoolExecutor ( 0 , 1 , 10L , TimeUnit . MILLISECONDS , new LinkedBlockingQueue < Runnable > ( ) ) ; producer = new Subscription ( ) { boolean complete = false ; public void request ( long outern ) { iteratorThread . execute ( ( ) -> { if ( complete ) { return ; } long n = outern ; try { while ( iterator . hasNext ( ) && n -- > 0 ) { self ( ) . onNext ( iterator . next ( ) ) ; } if ( ! iterator . hasNext ( ) ) { complete = true ; self ( ) . onComplete ( ) ; } } catch ( Throwable t ) { self ( ) . onError ( t ) ; } } ) ; } public void cancel ( ) { } } ; processor = in -> ( OUT ) in ; onSubscribe ( producer ) ; Thread . currentThread ( ) . setName ( Thread . currentThread ( ) + " (rx async stream processor)" ) ; } | acts as an pull based event producer then |
5,965 | public void _cancel ( int id ) { if ( doOnSubscribe != null ) { doOnSubscribe . add ( ( ) -> _cancel ( id ) ) ; } else subscribers . remove ( id ) ; } | private . remoted cancel |
5,966 | public void _rq ( long l , int id ) { if ( doOnSubscribe != null ) { doOnSubscribe . add ( ( ) -> _rq ( l , id ) ) ; } else { SubscriberEntry se = getSE ( id ) ; if ( se != null ) { se . addCredits ( l ) ; } else { Log . Warn ( this , "ignored credits " + l + " on id " + id ) ; } emitRequestNext ( ) ; } } | private . remoted request next |
5,967 | public void onNext ( IN in ) { if ( in == null ) throw null ; _onNext ( in ) ; } | same as with onError |
5,968 | protected IPromise directWrite ( ByteBuffer buf ) { checkThread ( ) ; if ( myActor == null ) myActor = Actor . current ( ) ; if ( writePromise != null ) throw new RuntimeException ( "concurrent write con:" + chan . isConnected ( ) + " open:" + chan . isOpen ( ) ) ; writePromise = new Promise ( ) ; writingBuffer = buf ; Promise res = writePromise ; try { int written = 0 ; written = chan . write ( buf ) ; if ( written < 0 ) { writeFinished ( new IOException ( "connection closed" ) ) ; } if ( buf . remaining ( ) > 0 ) { } else { writeFinished ( null ) ; } } catch ( Exception e ) { res . reject ( e ) ; FSTUtil . rethrow ( e ) ; } return res ; } | originally for debugging but now used to reschedule .. |
5,969 | void writeFinished ( Object error ) { checkThread ( ) ; writingBuffer = null ; Promise wp = this . writePromise ; writePromise = null ; if ( ! wp . isSettled ( ) ) { if ( error != null ) wp . reject ( error ) ; else wp . resolve ( ) ; } } | error = null = > ok |
5,970 | public synchronized Pair < PathHandler , Undertow > getServer ( int port , String hostName ) { return getServer ( port , hostName , null ) ; } | creates or gets an undertow web server instance mapped by port . hostname must be given in case a new server instance has to be instantiated |
5,971 | public Http4K publishFileSystem ( String hostName , String urlPath , int port , File root ) { if ( ! root . exists ( ) ) root . mkdirs ( ) ; if ( ! root . isDirectory ( ) ) { throw new RuntimeException ( "root must be an existing direcory:" + root . getAbsolutePath ( ) ) ; } Pair < PathHandler , Undertow > server = getServer ( port , hostName ) ; server . car ( ) . addPrefixPath ( urlPath , new ResourceHandler ( new FileResourceManager ( root , 100 ) ) ) ; return this ; } | publishes given file root |
5,972 | static byte [ ] gzip ( byte [ ] val ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( val . length ) ; GZIPOutputStream gos = null ; try { gos = new GZIPOutputStream ( bos ) ; gos . write ( val , 0 , val . length ) ; gos . finish ( ) ; gos . flush ( ) ; bos . flush ( ) ; val = bos . toByteArray ( ) ; } finally { if ( gos != null ) gos . close ( ) ; if ( bos != null ) bos . close ( ) ; } return val ; } | only called once in case no need for optimization |
5,973 | public Hoarde < T > each ( BiConsumer < T , Integer > init ) { for ( int i = 0 ; i < actors . length ; i ++ ) { init . accept ( ( T ) actors [ i ] , i ) ; } return this ; } | same as other each but with index |
5,974 | public < T > KxPublisher < T > asKxPublisher ( Publisher < T > p ) { if ( p instanceof KxPublisher ) return ( KxPublisher < T > ) p ; return new KxPublisher < T > ( ) { public void subscribe ( Subscriber < ? super T > s ) { p . subscribe ( s ) ; } public KxReactiveStreams getKxStreamsInstance ( ) { return KxReactiveStreams . this ; } } ; } | interop obtain a RxPublisher from an arbitrary rxstreams publisher . |
5,975 | public IPromise < String > getDataSimple ( ) { Promise result = new Promise ( ) ; result . complete ( "Data" , null ) ; return result ; } | these methods are identical ... |
5,976 | public static KeybindComponent of ( final String keybind , final TextColor color ) { return of ( keybind , color , Collections . emptySet ( ) ) ; } | Creates a keybind component with content and optional color . |
5,977 | public static KeybindComponent of ( final String keybind , final TextColor color , final Set < TextDecoration > decorations ) { return builder ( keybind ) . color ( color ) . decorations ( decorations , true ) . build ( ) ; } | Creates a keybind component with content and optional color and decorations . |
5,978 | public KeybindComponent keybind ( final String keybind ) { return new KeybindComponent ( this . children , this . color , this . obfuscated , this . bold , this . strikethrough , this . underlined , this . italic , this . clickEvent , this . hoverEvent , this . insertion , requireNonNull ( keybind , "keybind" ) ) ; } | Sets the keybind . |
5,979 | public static TranslatableComponent of ( final String key , final TextColor color ) { return builder ( key ) . color ( color ) . build ( ) ; } | Creates a translatable component with a translation key . |
5,980 | public TranslatableComponent key ( final String key ) { return new TranslatableComponent ( this . children , this . color , this . obfuscated , this . bold , this . strikethrough , this . underlined , this . italic , this . clickEvent , this . hoverEvent , this . insertion , requireNonNull ( key , "key" ) , this . args ) ; } | Sets the translation key . |
5,981 | public TranslatableComponent args ( final List < Component > args ) { return new TranslatableComponent ( this . children , this . color , this . obfuscated , this . bold , this . strikethrough , this . underlined , this . italic , this . clickEvent , this . hoverEvent , this . insertion , this . key , args ) ; } | Sets the translation arguments for this component . |
5,982 | public static Builder builder ( final String name , final String objective ) { return new Builder ( ) . name ( name ) . objective ( objective ) ; } | Creates a score component builder with a name and objective . |
5,983 | public static ScoreComponent of ( final String name , final String objective ) { return of ( name , objective , null ) ; } | Creates a score component with a name and objective . |
5,984 | public static ScoreComponent of ( final String name , final String objective , final String value ) { return builder ( ) . name ( name ) . objective ( objective ) . value ( value ) . build ( ) ; } | Creates a score component with a name objective and optional value . |
5,985 | public static ClickEvent openUrl ( final String url ) { return new ClickEvent ( Action . OPEN_URL , url ) ; } | Creates a click event that opens a url . |
5,986 | public static ClickEvent openFile ( final String file ) { return new ClickEvent ( Action . OPEN_FILE , file ) ; } | Creates a click event that opens a file . |
5,987 | public static ClickEvent runCommand ( final String command ) { return new ClickEvent ( Action . RUN_COMMAND , command ) ; } | Creates a click event that runs a command . |
5,988 | public static ClickEvent suggestCommand ( final String command ) { return new ClickEvent ( Action . SUGGEST_COMMAND , command ) ; } | Creates a click event that suggests a command . |
5,989 | public static ClickEvent changePage ( final String page ) { return new ClickEvent ( Action . CHANGE_PAGE , page ) ; } | Creates a click event that changes to a page . |
5,990 | public SelectorComponent pattern ( final String pattern ) { return new SelectorComponent ( this . children , this . color , this . obfuscated , this . bold , this . strikethrough , this . underlined , this . italic , this . clickEvent , this . hoverEvent , this . insertion , requireNonNull ( pattern , "pattern" ) ) ; } | Sets the selector pattern . |
5,991 | public static TextComponent of ( final String content , final TextColor color ) { return of ( content , color , Collections . emptySet ( ) ) ; } | Creates a text component with content and optional color . |
5,992 | public TextComponent content ( final String content ) { return new TextComponent ( this . children , this . color , this . obfuscated , this . bold , this . strikethrough , this . underlined , this . italic , this . clickEvent , this . hoverEvent , this . insertion , requireNonNull ( content , "content" ) ) ; } | Sets the plain text content . |
5,993 | public static GsonBuilder populate ( final GsonBuilder builder ) { builder . registerTypeHierarchyAdapter ( Component . class , INSTANCE ) . registerTypeAdapter ( ClickEvent . Action . class , new NameMapSerializer < > ( "click action" , ClickEvent . Action . NAMES ) ) . registerTypeAdapter ( HoverEvent . Action . class , new NameMapSerializer < > ( "hover action" , HoverEvent . Action . NAMES ) ) . registerTypeAdapter ( TextColorWrapper . class , new TextColorWrapper . Serializer ( ) ) . registerTypeAdapter ( TextColor . class , new NameMapSerializer < > ( "text color" , TextColor . NAMES ) ) . registerTypeAdapter ( TextDecoration . class , new NameMapSerializer < > ( "text decoration" , TextDecoration . NAMES ) ) ; return builder ; } | Populate a builder with our serializers . |
5,994 | public static < T extends Enum < T > > NameMap < T > create ( final T [ ] constants , final Function < T , String > namer ) { final Map < String , T > byName = new HashMap < > ( constants . length ) ; final Map < T , String > byValue = new HashMap < > ( constants . length ) ; for ( int i = 0 , length = constants . length ; i < length ; i ++ ) { final T constant = constants [ i ] ; final String name = namer . apply ( constant ) ; byName . put ( name , constant ) ; byValue . put ( constant , name ) ; } return new NameMap < > ( Collections . unmodifiableMap ( byName ) , Collections . unmodifiableMap ( byValue ) ) ; } | Creates a name map . |
5,995 | public Optional < T > get ( final String name ) { return Optional . ofNullable ( this . byName . get ( name ) ) ; } | Gets a value by its name . |
5,996 | public static HoverEvent showText ( final Component text ) { return new HoverEvent ( Action . SHOW_TEXT , text ) ; } | Creates a hover event that shows text on hover . |
5,997 | public static HoverEvent showItem ( final Component item ) { return new HoverEvent ( Action . SHOW_ITEM , item ) ; } | Creates a hover event that shows an item on hover . |
5,998 | public static HoverEvent showEntity ( final Component entity ) { return new HoverEvent ( Action . SHOW_ENTITY , entity ) ; } | Creates a hover event that shows an entity on hover . |
5,999 | private static void commitSuicide ( String msg ) { Thread t = new Thread ( ( ) -> { try { System . exit ( - 1 ) ; } catch ( SecurityException ex ) { LOGGER . info ( "SecurityException prevented system exit" , ex ) ; } try { while ( true ) { Thread . sleep ( 5000L ) ; LOGGER . error ( "VM is in an unreliable state - please abort it!" ) ; } } catch ( InterruptedException e ) { LOGGER . info ( "JVM Instability logger terminated by interrupt" ) ; } } ) ; t . setDaemon ( true ) ; t . start ( ) ; throw new Error ( msg ) ; } | Try to terminate the VM as soon as possible no matter the method and how abrupt it may be . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.