idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
29,700 | public void start ( final BiConsumer < EvolutionResult < PolygonGene , Double > , EvolutionResult < PolygonGene , Double > > callback ) { final Thread thread = new Thread ( ( ) -> { final MinMax < EvolutionResult < PolygonGene , Double > > best = MinMax . of ( ) ; _engine . stream ( ) . limit ( result -> ! Thread . currentThread ( ) . isInterrupted ( ) ) . peek ( best ) . forEach ( r -> { waiting ( ) ; if ( callback != null ) { callback . accept ( r , best . getMax ( ) ) ; } } ) ; } ) ; thread . start ( ) ; _thread = thread ; } | Starts the evolution worker with the given evolution result callback . The callback may be null . | 146 | 18 |
29,701 | public void stop ( ) { resume ( ) ; final Thread thread = _thread ; if ( thread != null ) { thread . interrupt ( ) ; try { thread . join ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } finally { _thread = null ; } } } | Stops the current evolution if running . | 69 | 8 |
29,702 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > AltererResult < G , C > of ( final ISeq < Phenotype < G , C > > population , final int alterations ) { return new AltererResult <> ( population , alterations ) ; } | Return a new alter result for the given arguments . | 65 | 10 |
29,703 | public long [ ] toArray ( final long [ ] array ) { final long [ ] a = array . length >= length ( ) ? array : new long [ length ( ) ] ; for ( int i = length ( ) ; -- i >= 0 ; ) { a [ i ] = longValue ( i ) ; } return a ; } | Returns an long array containing all of the elements in this chromosome in proper sequence . If the chromosome fits in the specified array it is returned therein . Otherwise a new array is allocated with the length of this chromosome . | 70 | 42 |
29,704 | public double eval ( final double ... args ) { final double val = apply ( DoubleStream . of ( args ) . boxed ( ) . toArray ( Double [ ] :: new ) ) ; return val == - 0.0 ? 0.0 : val ; } | Convenient method which lets you apply the program function without explicitly create a wrapper array . | 54 | 17 |
29,705 | public static Tree < ? extends Op < Double > , ? > simplify ( final Tree < ? extends Op < Double > , ? > tree ) { return MathExprRewriter . prune ( TreeNode . ofTree ( tree ) ) ; } | Tries to simplify the given math tree . | 51 | 9 |
29,706 | private < A > void crossover ( final MSeq < Chromosome < G > > c1 , final MSeq < Chromosome < G > > c2 , final int index ) { @ SuppressWarnings ( "unchecked" ) final TreeNode < A > tree1 = ( TreeNode < A > ) TreeNode . ofTree ( c1 . get ( index ) . getGene ( ) ) ; @ SuppressWarnings ( "unchecked" ) final TreeNode < A > tree2 = ( TreeNode < A > ) TreeNode . ofTree ( c2 . get ( index ) . getGene ( ) ) ; crossover ( tree1 , tree2 ) ; final FlatTreeNode < A > flat1 = FlatTreeNode . of ( tree1 ) ; final FlatTreeNode < A > flat2 = FlatTreeNode . of ( tree2 ) ; @ SuppressWarnings ( "unchecked" ) final TreeGene < A , ? > template = ( TreeGene < A , ? > ) c1 . get ( 0 ) . getGene ( ) ; final ISeq < G > genes1 = flat1 . map ( tree -> gene ( template , tree ) ) ; final ISeq < G > genes2 = flat2 . map ( tree -> gene ( template , tree ) ) ; c1 . set ( index , c1 . get ( index ) . newInstance ( genes1 ) ) ; c2 . set ( index , c2 . get ( index ) . newInstance ( genes2 ) ) ; } | the abstract crossover method usually don t have to do additional casts . | 326 | 13 |
29,707 | public static < T > Const < T > of ( final String name , final T value ) { return new Const <> ( requireNonNull ( name ) , value ) ; } | Return a new constant with the given name and value . | 37 | 11 |
29,708 | public static CharacterGene of ( final CharSeq validCharacters ) { return new CharacterGene ( validCharacters , RandomRegistry . getRandom ( ) . nextInt ( validCharacters . length ( ) ) ) ; } | Create a new CharacterGene with a randomly chosen character from the set of valid characters . | 44 | 17 |
29,709 | public static void create ( final Path input , final Template template , final Params < ? > params , final Path output , final SampleSummary summary , final SampleSummary ... summaries ) throws IOException { final Stream < SampleSummary > summaryStream = Stream . concat ( Stream . of ( summary ) , Stream . of ( summaries ) ) ; summaryStream . forEach ( s -> { if ( params . size ( ) != s . parameterCount ( ) ) { throw new IllegalArgumentException ( format ( "Parameters have different size: %d" , params . size ( ) ) ) ; } } ) ; final Path templatePath = tempPath ( ) ; try { IO . write ( template . content ( ) , templatePath ) ; final Path dataPath = tempPath ( ) ; try { final String data = IntStream . range ( 0 , params . size ( ) ) . mapToObj ( i -> toLineString ( i , params , summary , summaries ) ) . collect ( Collectors . joining ( "\n" ) ) ; IO . write ( data , dataPath ) ; final Gnuplot gnuplot = new Gnuplot ( templatePath ) ; gnuplot . setEnv ( params ( input ) ) ; gnuplot . create ( dataPath , output ) ; } finally { deleteIfExists ( dataPath ) ; } } finally { deleteIfExists ( templatePath ) ; } } | Create a performance diagram . | 297 | 5 |
29,710 | public SampleSummary summary ( ) { return _samples . stream ( ) . filter ( Sample :: isFull ) . collect ( toSampleSummary ( sampleSize ( ) ) ) ; } | Calculate the sample summary of this data object . | 38 | 11 |
29,711 | public static < T > Params < T > of ( final String name , final ISeq < T > params ) { return new Params <> ( name , params ) ; } | Return a new parameters object . | 38 | 6 |
29,712 | static < A > ISeq < AnyGene < A > > seq ( final IntRange lengthRange , final Supplier < ? extends A > supplier , final Predicate < ? super A > validator ) { return MSeq . < AnyGene < A > > ofLength ( random . nextInt ( lengthRange , getRandom ( ) ) ) . fill ( ( ) -> of ( supplier . get ( ) , supplier , validator ) ) . toISeq ( ) ; } | Create gene sequence . | 100 | 4 |
29,713 | public static void swap ( final byte [ ] data , final int start , final int end , final byte [ ] otherData , final int otherStart ) { for ( int i = end - start ; -- i >= 0 ; ) { final boolean temp = get ( data , i + start ) ; set ( data , i + start , get ( otherData , otherStart + i ) ) ; set ( otherData , otherStart + i , temp ) ; } } | Swap a given range with a range of the same size with another array . | 96 | 16 |
29,714 | public static byte [ ] flip ( final byte [ ] data , final int index ) { return get ( data , index ) ? unset ( data , index ) : set ( data , index ) ; } | Flip the bit at the given index . | 42 | 9 |
29,715 | public static byte [ ] copy ( final byte [ ] data , final int start , final int end ) { if ( start > end ) { throw new IllegalArgumentException ( String . format ( "start > end: %d > %d" , start , end ) ) ; } if ( start < 0 || start > data . length << 3 ) { throw new ArrayIndexOutOfBoundsException ( String . format ( "%d < 0 || %d > %d" , start , start , data . length * 8 ) ) ; } final int to = min ( data . length << 3 , end ) ; final int byteStart = start >>> 3 ; final int bitStart = start & 7 ; final int bitLength = to - start ; final byte [ ] copy = new byte [ toByteLength ( to - start ) ] ; if ( copy . length > 0 ) { // Perform the byte wise right shift. System . arraycopy ( data , byteStart , copy , 0 , copy . length ) ; // Do the remaining bit wise right shift. shiftRight ( copy , bitStart ) ; // Add the 'lost' bits from the next byte, if available. if ( data . length > copy . length + byteStart ) { copy [ copy . length - 1 ] |= ( byte ) ( data [ byteStart + copy . length ] << ( Byte . SIZE - bitStart ) ) ; } // Trim (delete) the overhanging bits. copy [ copy . length - 1 ] &= 0xFF >>> ( ( copy . length << 3 ) - bitLength ) ; } return copy ; } | Copies the specified range of the specified array into a new array . | 337 | 14 |
29,716 | public static < T > MutatorResult < T > of ( final T result , final int mutations ) { return new MutatorResult <> ( result , mutations ) ; } | Create a new mutation result with the given values . | 36 | 10 |
29,717 | @ Override protected MutatorResult < Chromosome < G > > mutate ( final Chromosome < G > chromosome , final double p , final Random random ) { final MutatorResult < Chromosome < G > > result ; if ( chromosome . length ( ) > 1 ) { final MSeq < G > genes = chromosome . toSeq ( ) . copy ( ) ; final int mutations = ( int ) indexes ( random , genes . length ( ) , p ) . peek ( i -> genes . swap ( i , random . nextInt ( genes . length ( ) ) ) ) . count ( ) ; result = MutatorResult . of ( chromosome . newInstance ( genes . toISeq ( ) ) , mutations ) ; } else { result = MutatorResult . of ( chromosome ) ; } return result ; } | Swaps the genes in the given array with the mutation probability of this mutation . | 174 | 16 |
29,718 | public static double nonNegative ( final double value , final String message ) { if ( value < 0 ) { throw new IllegalArgumentException ( format ( "%s must not be negative: %f." , message , value ) ) ; } return value ; } | Check if the specified value is not negative . | 54 | 9 |
29,719 | static Function < ISeq < Item > , Double > fitness ( final double size ) { return items -> { final Item sum = items . stream ( ) . collect ( Item . toSum ( ) ) ; return sum . size <= size ? sum . value : 0 ; } ; } | Creating the fitness function . | 58 | 5 |
29,720 | public static DoubleMoments of ( final long count , final double min , final double max , final double sum , final double mean , final double variance , final double skewness , final double kurtosis ) { return new DoubleMoments ( count , min , max , sum , mean , variance , skewness , kurtosis ) ; } | Create an immutable object which contains statistical values . | 72 | 9 |
29,721 | private static < A > ProgramChromosome < A > create ( final Tree < ? extends Op < A > , ? > program , final Predicate < ? super ProgramChromosome < A > > validator , final ISeq < ? extends Op < A > > operations , final ISeq < ? extends Op < A > > terminals ) { final ISeq < ProgramGene < A > > genes = FlatTreeNode . of ( program ) . stream ( ) . map ( n -> new ProgramGene <> ( n . getValue ( ) , n . childOffset ( ) , operations , terminals ) ) . collect ( ISeq . toISeq ( ) ) ; return new ProgramChromosome <> ( genes , validator , operations , terminals ) ; } | Create the chromosomes without checks . | 162 | 6 |
29,722 | static List < Token > tokenize ( final String value ) { final List < Token > tokens = new ArrayList <> ( ) ; char pc = ' ' ; int pos = 0 ; final StringBuilder token = new StringBuilder ( ) ; for ( int i = 0 ; i < value . length ( ) ; ++ i ) { final char c = value . charAt ( i ) ; if ( isTokenSeparator ( c ) && pc != ESCAPE_CHAR ) { tokens . add ( new Token ( unescape ( token . toString ( ) ) , pos ) ) ; tokens . add ( new Token ( Character . toString ( c ) , i ) ) ; token . setLength ( 0 ) ; pos = i ; } else { token . append ( c ) ; } pc = c ; } if ( token . length ( ) > 0 ) { tokens . add ( new Token ( unescape ( token . toString ( ) ) , pos ) ) ; } return tokens ; } | Tokenize the given parentheses string . | 207 | 7 |
29,723 | static < B > TreeNode < B > parse ( final String value , final Function < ? super String , ? extends B > mapper ) { requireNonNull ( value ) ; requireNonNull ( mapper ) ; final TreeNode < B > root = TreeNode . of ( ) ; final Deque < TreeNode < B > > parents = new ArrayDeque <> ( ) ; TreeNode < B > current = root ; for ( Token token : tokenize ( value . trim ( ) ) ) { switch ( token . seq ) { case "(" : if ( current == null ) { throw new IllegalArgumentException ( format ( "Illegal parentheses tree string: '%s'." , value ) ) ; } final TreeNode < B > tn1 = TreeNode . of ( ) ; current . attach ( tn1 ) ; parents . push ( current ) ; current = tn1 ; break ; case "," : if ( parents . isEmpty ( ) ) { throw new IllegalArgumentException ( format ( "Expect '(' at position %d." , token . pos ) ) ; } final TreeNode < B > tn2 = TreeNode . of ( ) ; assert parents . peek ( ) != null ; parents . peek ( ) . attach ( tn2 ) ; current = tn2 ; break ; case ")" : if ( parents . isEmpty ( ) ) { throw new IllegalArgumentException ( format ( "Unbalanced parentheses at position %d." , token . pos ) ) ; } current = parents . pop ( ) ; if ( parents . isEmpty ( ) ) { current = null ; } break ; default : if ( current == null ) { throw new IllegalArgumentException ( format ( "More than one root element at pos %d: '%s'." , token . pos , value ) ) ; } if ( current . getValue ( ) == null ) { current . setValue ( mapper . apply ( token . seq ) ) ; } break ; } } if ( ! parents . isEmpty ( ) ) { throw new IllegalArgumentException ( "Unbalanced parentheses." ) ; } return root ; } | Parses the given parentheses tree string | 450 | 8 |
29,724 | @ Override public ProgramGene < A > newInstance ( final Op < A > op ) { if ( getValue ( ) . arity ( ) != op . arity ( ) ) { throw new IllegalArgumentException ( format ( "New operation must have same arity: %s[%d] != %s[%d]" , getValue ( ) . name ( ) , getValue ( ) . arity ( ) , op . name ( ) , op . arity ( ) ) ) ; } return new ProgramGene <> ( op , childOffset ( ) , _operations , _terminals ) ; } | Create a new program gene with the given operation . | 131 | 10 |
29,725 | private ISeq < Phenotype < G , C > > selectSurvivors ( final ISeq < Phenotype < G , C > > population ) { return _survivorsCount > 0 ? _survivorsSelector . select ( population , _survivorsCount , _optimize ) : ISeq . empty ( ) ; } | Selects the survivors population . A new population object is returned . | 71 | 13 |
29,726 | private ISeq < Phenotype < G , C > > selectOffspring ( final ISeq < Phenotype < G , C > > population ) { return _offspringCount > 0 ? _offspringSelector . select ( population , _offspringCount , _optimize ) : ISeq . empty ( ) ; } | Selects the offspring population . A new population object is returned . | 67 | 13 |
29,727 | private FilterResult < G , C > filter ( final Seq < Phenotype < G , C > > population , final long generation ) { int killCount = 0 ; int invalidCount = 0 ; final MSeq < Phenotype < G , C > > pop = MSeq . of ( population ) ; for ( int i = 0 , n = pop . size ( ) ; i < n ; ++ i ) { final Phenotype < G , C > individual = pop . get ( i ) ; if ( ! _validator . test ( individual ) ) { pop . set ( i , newPhenotype ( generation ) ) ; ++ invalidCount ; } else if ( individual . getAge ( generation ) > _maximalPhenotypeAge ) { pop . set ( i , newPhenotype ( generation ) ) ; ++ killCount ; } } return new FilterResult <> ( pop . toISeq ( ) , killCount , invalidCount ) ; } | Filters out invalid and old individuals . Filtering is done in place . | 202 | 15 |
29,728 | private Phenotype < G , C > newPhenotype ( final long generation ) { int count = 0 ; Phenotype < G , C > phenotype ; do { phenotype = Phenotype . of ( _genotypeFactory . newInstance ( ) , generation , _fitnessFunction , _fitnessScaler ) ; } while ( ++ count < _individualCreationRetries && ! _validator . test ( phenotype ) ) ; return phenotype ; } | Create a new and valid phenotype | 93 | 6 |
29,729 | @ SafeVarargs public static < T > T eval ( final Tree < ? extends Op < T > , ? > tree , final T ... variables ) { requireNonNull ( tree ) ; requireNonNull ( variables ) ; final Op < T > op = tree . getValue ( ) ; return op . isTerminal ( ) ? eval ( op , variables ) : eval ( op , tree . childStream ( ) . map ( child -> eval ( child , variables ) ) . toArray ( size -> newArray ( variables . getClass ( ) , size ) ) ) ; } | Evaluates the given operation tree with the given variables . | 120 | 12 |
29,730 | public static void check ( final Tree < ? extends Op < ? > , ? > program ) { requireNonNull ( program ) ; program . forEach ( Program :: checkArity ) ; } | Validates the given program tree . | 40 | 7 |
29,731 | static int [ ] offsets ( final ISeq < ? extends FlatTree < ? extends Op < ? > , ? > > nodes ) { final int [ ] offsets = new int [ nodes . size ( ) ] ; int offset = 1 ; for ( int i = 0 ; i < offsets . length ; ++ i ) { final Op < ? > op = nodes . get ( i ) . getValue ( ) ; offsets [ i ] = op . isTerminal ( ) ? - 1 : offset ; offset += op . arity ( ) ; } return offsets ; } | Create the offset array for the given nodes . The offsets are calculated using the arity of the stored operations . | 117 | 22 |
29,732 | public static void divide ( final double [ ] values , final double divisor ) { for ( int i = values . length ; -- i >= 0 ; ) { values [ i ] /= divisor ; } } | Component wise division of the given double array . | 46 | 9 |
29,733 | public static long pow ( final long b , final long e ) { long base = b ; long exp = e ; long result = 1 ; while ( exp != 0 ) { if ( ( exp & 1 ) != 0 ) { result *= base ; } exp >>>= 1 ; base *= base ; } return result ; } | Binary exponentiation algorithm . | 68 | 6 |
29,734 | @ Override public ISeq < Phenotype < G , C > > select ( final Seq < Phenotype < G , C > > population , final int count , final Optimize opt ) { requireNonNull ( population , "Population" ) ; requireNonNull ( opt , "Optimization" ) ; if ( count < 0 ) { throw new IllegalArgumentException ( format ( "Selection count must be greater or equal then zero, but was %s" , count ) ) ; } final MSeq < Phenotype < G , C > > selection = MSeq . ofLength ( population . isEmpty ( ) ? 0 : count ) ; if ( count > 0 && ! population . isEmpty ( ) ) { final MSeq < Phenotype < G , C > > copy = population . asISeq ( ) . copy ( ) ; copy . sort ( ( a , b ) -> opt . < C > descending ( ) . compare ( a . getFitness ( ) , b . getFitness ( ) ) ) ; int size = count ; do { final int length = min ( min ( copy . size ( ) , size ) , _n ) ; for ( int i = 0 ; i < length ; ++ i ) { selection . set ( ( count - size ) + i , copy . get ( i ) ) ; } size -= length ; } while ( size > 0 ) ; } return selection . toISeq ( ) ; } | This method sorts the population in descending order while calculating the selection probabilities . If the selection size is greater the the population size the whole population is duplicated until the desired sample size is reached . | 306 | 38 |
29,735 | public static Concurrency with ( final Executor executor ) { if ( executor instanceof ForkJoinPool ) { return new ForkJoinPoolConcurrency ( ( ForkJoinPool ) executor ) ; } else if ( executor instanceof ExecutorService ) { return new ExecutorServiceConcurrency ( ( ExecutorService ) executor ) ; } else if ( executor == SERIAL_EXECUTOR ) { return SERIAL_EXECUTOR ; } else { return new ExecutorConcurrency ( executor ) ; } } | Return an new Concurrency object from the given executor . | 112 | 12 |
29,736 | public ISeq < Genotype < G > > getGenotypes ( ) { return _population . stream ( ) . map ( Phenotype :: getGenotype ) . collect ( ISeq . toISeq ( ) ) ; } | Return the current list of genotypes of this evolution result . | 47 | 12 |
29,737 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > Collector < EvolutionResult < G , C > , ? , EvolutionResult < G , C > > toBestEvolutionResult ( ) { return Collector . of ( MinMax :: < EvolutionResult < G , C > > of , MinMax :: accept , MinMax :: combine , mm -> mm . getMax ( ) != null ? mm . getMax ( ) . withTotalGenerations ( mm . getCount ( ) ) : null ) ; } | Return a collector which collects the best result of an evolution stream . | 114 | 13 |
29,738 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > Collector < EvolutionResult < G , C > , ? , Phenotype < G , C > > toBestPhenotype ( ) { return Collector . of ( MinMax :: < EvolutionResult < G , C > > of , MinMax :: accept , MinMax :: combine , mm -> mm . getMax ( ) != null ? mm . getMax ( ) . getBestPhenotype ( ) : null ) ; } | Return a collector which collects the best phenotype of an evolution stream . | 109 | 13 |
29,739 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > Collector < EvolutionResult < G , C > , ? , Genotype < G > > toBestGenotype ( ) { return Collector . of ( MinMax :: < EvolutionResult < G , C > > of , MinMax :: accept , MinMax :: combine , mm -> mm . getMax ( ) != null ? mm . getMax ( ) . getBestPhenotype ( ) != null ? mm . getMax ( ) . getBestPhenotype ( ) . getGenotype ( ) : null : null ) ; } | Return a collector which collects the best genotype of an evolution stream . | 131 | 14 |
29,740 | public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > UnaryOperator < EvolutionResult < G , C > > toUniquePopulation ( final int maxRetries ) { return result -> { final Factory < Genotype < G > > factory = result . getPopulation ( ) . get ( 0 ) . getGenotype ( ) ; final UnaryOperator < EvolutionResult < G , C > > unifier = toUniquePopulation ( factory , maxRetries ) ; return unifier . apply ( result ) ; } ; } | Return a mapping function which removes duplicate individuals from the population and replaces it with newly created one by the existing genotype factory . | 119 | 25 |
29,741 | static < A > int swap ( final TreeNode < A > that , final TreeNode < A > other ) { assert that != null ; assert other != null ; final Random random = RandomRegistry . getRandom ( ) ; final ISeq < TreeNode < A > > seq1 = that . breadthFirstStream ( ) . collect ( ISeq . toISeq ( ) ) ; final ISeq < TreeNode < A > > seq2 = other . breadthFirstStream ( ) . collect ( ISeq . toISeq ( ) ) ; final int changed ; if ( seq1 . length ( ) > 1 && seq2 . length ( ) > 1 ) { final TreeNode < A > n1 = seq1 . get ( random . nextInt ( seq1 . length ( ) - 1 ) + 1 ) ; final TreeNode < A > p1 = n1 . getParent ( ) . orElseThrow ( AssertionError :: new ) ; final TreeNode < A > n2 = seq2 . get ( random . nextInt ( seq2 . length ( ) - 1 ) + 1 ) ; final TreeNode < A > p2 = n2 . getParent ( ) . orElseThrow ( AssertionError :: new ) ; final int i1 = p1 . getIndex ( n1 ) ; final int i2 = p2 . getIndex ( n2 ) ; p1 . insert ( i1 , n2 . detach ( ) ) ; p2 . insert ( i2 , n1 . detach ( ) ) ; changed = 2 ; } else { changed = 0 ; } return changed ; } | The static method makes it easier to test . | 338 | 9 |
29,742 | static double [ ] sortAndRevert ( final double [ ] array ) { final int [ ] indexes = sort ( array ) ; // Copy the elements in reversed order. final double [ ] result = new double [ array . length ] ; for ( int i = 0 ; i < result . length ; ++ i ) { result [ indexes [ result . length - 1 - i ] ] = array [ indexes [ i ] ] ; } return result ; } | Package private for testing . | 94 | 5 |
29,743 | private static void checkAndCorrect ( final double [ ] probabilities ) { boolean ok = true ; for ( int i = probabilities . length ; -- i >= 0 && ok ; ) { ok = Double . isFinite ( probabilities [ i ] ) ; } if ( ! ok ) { final double value = 1.0 / probabilities . length ; for ( int i = probabilities . length ; -- i >= 0 ; ) { probabilities [ i ] = value ; } } } | Checks if the given probability values are finite . If not all values are set to the same probability . | 96 | 21 |
29,744 | static boolean sum2one ( final double [ ] probabilities ) { final double sum = probabilities . length > 0 ? DoubleAdder . sum ( probabilities ) : 1.0 ; return abs ( ulpDistance ( sum , 1.0 ) ) < MAX_ULP_DISTANCE ; } | Check if the given probabilities sum to one . | 61 | 9 |
29,745 | static int indexOfBinary ( final double [ ] incr , final double v ) { int imin = 0 ; int imax = incr . length ; int index = - 1 ; while ( imax > imin && index == - 1 ) { final int imid = ( imin + imax ) >>> 1 ; if ( imid == 0 || ( incr [ imid ] >= v && incr [ imid - 1 ] < v ) ) { index = imid ; } else if ( incr [ imid ] <= v ) { imin = imid + 1 ; } else if ( incr [ imid ] > v ) { imax = imid ; } } return index ; } | Perform a binary - search on the summed probability array . | 152 | 12 |
29,746 | static int indexOfSerial ( final double [ ] incr , final double v ) { int index = - 1 ; for ( int i = 0 ; i < incr . length && index == - 1 ; ++ i ) { if ( incr [ i ] >= v ) { index = i ; } } return index ; } | Perform a serial - search on the summed probability array . | 68 | 12 |
29,747 | static double [ ] incremental ( final double [ ] values ) { final DoubleAdder adder = new DoubleAdder ( values [ 0 ] ) ; for ( int i = 1 ; i < values . length ; ++ i ) { values [ i ] = adder . add ( values [ i ] ) . doubleValue ( ) ; } return values ; } | In - place summation of the probability array . | 74 | 10 |
29,748 | @ Override public TreeNode < T > getChild ( final int index ) { if ( _children == null ) { throw new ArrayIndexOutOfBoundsException ( format ( "Child index is out of bounds: %s" , index ) ) ; } return _children . get ( index ) ; } | Returns the child at the specified index in this node s child array . | 64 | 14 |
29,749 | public static void ensureValidResource ( JsonNode resource ) { if ( ! resource . has ( JSONAPISpecConstants . DATA ) && ! resource . has ( JSONAPISpecConstants . META ) ) { throw new InvalidJsonApiResourceException ( ) ; } } | Asserts that provided resource has required data or meta node . | 61 | 13 |
29,750 | public static void ensureNotError ( ObjectMapper mapper , JsonNode resourceNode ) { if ( resourceNode != null && resourceNode . hasNonNull ( JSONAPISpecConstants . ERRORS ) ) { try { throw new ResourceParseException ( ErrorUtils . parseError ( mapper , resourceNode , Errors . class ) ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( e ) ; } } } | Ensures that provided node does not hold errors attribute . | 96 | 12 |
29,751 | @ NotNull public static JSONAPIDocument < ? > createErrorDocument ( Iterable < ? extends Error > errors ) { JSONAPIDocument < ? > result = new JSONAPIDocument ( ) ; result . errors = errors ; return result ; } | Factory method for creating JSONAPIDocument that holds the Error object . | 53 | 14 |
29,752 | public void addLink ( String linkName , Link link ) { if ( links == null ) { links = new Links ( new HashMap < String , Link > ( ) ) ; } links . addLink ( linkName , link ) ; } | Adds a named link . | 50 | 5 |
29,753 | public Field getRelationshipField ( Class < ? > clazz , String fieldName ) { return relationshipFieldMap . get ( clazz ) . get ( fieldName ) ; } | Returns relationship field . | 37 | 4 |
29,754 | public Class < ? > getRelationshipType ( Class < ? > clazz , String fieldName ) { return relationshipTypeMap . get ( clazz ) . get ( fieldName ) ; } | Returns a type of a relationship . | 40 | 7 |
29,755 | public String getTypeName ( Class < ? > clazz ) { Type type = typeAnnotations . get ( clazz ) ; if ( type != null ) { return type . value ( ) ; } return null ; } | Resolves and returns name of the type given to provided class . | 46 | 13 |
29,756 | public Field getRelationshipMetaField ( Class < ? > clazz , String relationshipName ) { return relationshipMetaFieldMap . get ( clazz ) . get ( relationshipName ) ; } | Returns relationship meta field . | 39 | 5 |
29,757 | public Class < ? > getRelationshipMetaType ( Class < ? > clazz , String relationshipName ) { return relationshipMetaTypeMap . get ( clazz ) . get ( relationshipName ) ; } | Returns a type of a relationship meta field . | 42 | 9 |
29,758 | public Field getRelationshipLinksField ( Class < ? > clazz , String relationshipName ) { return relationshipLinksFieldMap . get ( clazz ) . get ( relationshipName ) ; } | Returns relationship links field . | 39 | 5 |
29,759 | public void setTypeResolver ( RelationshipResolver resolver , Class < ? > type ) { if ( resolver != null ) { String typeName = ReflectionUtils . getTypeName ( type ) ; if ( typeName != null ) { typedResolvers . put ( type , resolver ) ; } } } | Registers relationship resolver for given type . Resolver will be used if relationship resolution is enabled trough relationship annotation . | 68 | 23 |
29,760 | @ Deprecated public < T > T readObject ( byte [ ] data , Class < T > clazz ) { return readDocument ( data , clazz ) . get ( ) ; } | Converts raw data input into requested target type . | 39 | 10 |
29,761 | @ Deprecated public < T > List < T > readObjectCollection ( byte [ ] data , Class < T > clazz ) { return readDocumentCollection ( data , clazz ) . get ( ) ; } | Converts rawdata input into a collection of requested output objects . | 44 | 13 |
29,762 | private < T > T readObject ( JsonNode source , Class < T > clazz , boolean handleRelationships ) throws IOException , IllegalAccessException , InstantiationException { String identifier = createIdentifier ( source ) ; T result = ( T ) resourceCache . get ( identifier ) ; if ( result == null ) { Class < ? > type = getActualType ( source , clazz ) ; if ( source . has ( ATTRIBUTES ) ) { result = ( T ) objectMapper . treeToValue ( source . get ( ATTRIBUTES ) , type ) ; } else { if ( type . isInterface ( ) ) { result = null ; } else { result = ( T ) objectMapper . treeToValue ( objectMapper . createObjectNode ( ) , type ) ; } } // Handle meta if ( source . has ( META ) ) { Field field = configuration . getMetaField ( type ) ; if ( field != null ) { Class < ? > metaType = configuration . getMetaType ( type ) ; Object metaObject = objectMapper . treeToValue ( source . get ( META ) , metaType ) ; field . set ( result , metaObject ) ; } } // Handle links if ( source . has ( LINKS ) ) { Field linkField = configuration . getLinksField ( type ) ; if ( linkField != null ) { linkField . set ( result , new Links ( mapLinks ( source . get ( LINKS ) ) ) ) ; } } if ( result != null ) { // Add parsed object to cache resourceCache . cache ( identifier , result ) ; // Set object id setIdValue ( result , source . get ( ID ) ) ; if ( handleRelationships ) { // Handle relationships handleRelationships ( source , result ) ; } } } return result ; } | Converts provided input into a target object . After conversion completes any relationships defined are resolved . | 387 | 18 |
29,763 | private Map < String , Object > parseIncluded ( JsonNode parent ) throws IOException , IllegalAccessException , InstantiationException { Map < String , Object > result = new HashMap <> ( ) ; if ( parent . has ( INCLUDED ) ) { // Get resources Map < String , Object > includedResources = getIncludedResources ( parent ) ; if ( ! includedResources . isEmpty ( ) ) { // Add to result for ( String identifier : includedResources . keySet ( ) ) { result . put ( identifier , includedResources . get ( identifier ) ) ; } ArrayNode includedArray = ( ArrayNode ) parent . get ( INCLUDED ) ; for ( int i = 0 ; i < includedArray . size ( ) ; i ++ ) { // Handle relationships JsonNode node = includedArray . get ( i ) ; Object resourceObject = includedResources . get ( createIdentifier ( node ) ) ; if ( resourceObject != null ) { handleRelationships ( node , resourceObject ) ; } } } } return result ; } | Converts included data and returns it as pairs of its unique identifiers and converted types . | 217 | 17 |
29,764 | private Map < String , Object > getIncludedResources ( JsonNode parent ) throws IOException , IllegalAccessException , InstantiationException { Map < String , Object > result = new HashMap <> ( ) ; if ( parent . has ( INCLUDED ) ) { for ( JsonNode jsonNode : parent . get ( INCLUDED ) ) { String type = jsonNode . get ( TYPE ) . asText ( ) ; Class < ? > clazz = configuration . getTypeClass ( type ) ; if ( clazz != null ) { Object object = readObject ( jsonNode , clazz , false ) ; if ( object != null ) { result . put ( createIdentifier ( jsonNode ) , object ) ; } } else if ( ! deserializationFeatures . contains ( DeserializationFeature . ALLOW_UNKNOWN_INCLUSIONS ) ) { throw new IllegalArgumentException ( "Included section contains unknown resource type: " + type ) ; } } } return result ; } | Parses out included resources excluding relationships . | 208 | 9 |
29,765 | private Object parseRelationship ( JsonNode relationshipDataNode , Class < ? > type ) throws IOException , IllegalAccessException , InstantiationException { if ( ValidationUtils . isRelationshipParsable ( relationshipDataNode ) ) { String identifier = createIdentifier ( relationshipDataNode ) ; if ( resourceCache . contains ( identifier ) ) { return resourceCache . get ( identifier ) ; } else { // Never cache relationship objects resourceCache . lock ( ) ; try { return readObject ( relationshipDataNode , type , true ) ; } finally { resourceCache . unlock ( ) ; } } } return null ; } | Creates relationship object by consuming provided data node . | 130 | 10 |
29,766 | private void setIdValue ( Object target , JsonNode idValue ) throws IllegalAccessException { Field idField = configuration . getIdField ( target . getClass ( ) ) ; ResourceIdHandler idHandler = configuration . getIdHandler ( target . getClass ( ) ) ; if ( idValue != null ) { idField . set ( target , idHandler . fromString ( idValue . asText ( ) ) ) ; } } | Sets an id attribute value to a target object . | 91 | 11 |
29,767 | private RelationshipResolver getResolver ( Class < ? > type ) { RelationshipResolver resolver = typedResolvers . get ( type ) ; return resolver != null ? resolver : globalResolver ; } | Returns relationship resolver for given type . In case no specific type resolver is registered global resolver is returned . | 45 | 23 |
29,768 | public boolean registerType ( Class < ? > type ) { if ( ! configuration . isRegisteredType ( type ) && ConverterConfiguration . isEligibleType ( type ) ) { return configuration . registerType ( type ) ; } return false ; } | Registers new type to be used with this converter instance . | 52 | 12 |
29,769 | public static List < Field > getAnnotatedFields ( Class < ? > clazz , Class < ? extends Annotation > annotation , boolean checkSuperclass ) { Field [ ] fields = clazz . getDeclaredFields ( ) ; List < Field > result = new ArrayList <> ( ) ; for ( Field field : fields ) { if ( field . isAnnotationPresent ( annotation ) ) { result . add ( field ) ; } } if ( checkSuperclass && clazz . getSuperclass ( ) != null && ! clazz . getSuperclass ( ) . equals ( Object . class ) ) { result . addAll ( getAnnotatedFields ( clazz . getSuperclass ( ) , annotation , true ) ) ; } return result ; } | Returns all field from a given class that are annotated with provided annotation type . | 162 | 16 |
29,770 | public static String getTypeName ( Class < ? > clazz ) { Type typeAnnotation = clazz . getAnnotation ( Type . class ) ; return typeAnnotation != null ? typeAnnotation . value ( ) : null ; } | Returns the type name defined using Type annotation on provided class . | 50 | 12 |
29,771 | public void init ( ) { if ( initDepth . get ( ) == null ) { initDepth . set ( 1 ) ; } else { initDepth . set ( initDepth . get ( ) + 1 ) ; } if ( resourceCache . get ( ) == null ) { resourceCache . set ( new HashMap < String , Object > ( ) ) ; } if ( cacheLocked . get ( ) == null ) { cacheLocked . set ( Boolean . FALSE ) ; } } | Initialises cache for current thread - scope . | 101 | 9 |
29,772 | public void clear ( ) { verifyState ( ) ; initDepth . set ( initDepth . get ( ) - 1 ) ; if ( initDepth . get ( ) == 0 ) { resourceCache . set ( null ) ; cacheLocked . set ( null ) ; initDepth . set ( null ) ; } } | Clears current thread scope state . | 65 | 7 |
29,773 | public void cache ( Map < String , Object > resources ) { verifyState ( ) ; if ( ! cacheLocked . get ( ) ) { resourceCache . get ( ) . putAll ( resources ) ; } } | Adds multiple resources to cache . | 45 | 6 |
29,774 | public void cache ( String identifier , Object resource ) { verifyState ( ) ; if ( ! cacheLocked . get ( ) ) { resourceCache . get ( ) . put ( identifier , resource ) ; } } | Adds resource to cache . | 44 | 5 |
29,775 | public static < T extends Errors > T parseErrorResponse ( ObjectMapper mapper , ResponseBody errorResponse , Class < T > cls ) throws IOException { return mapper . readValue ( errorResponse . bytes ( ) , cls ) ; } | Parses provided ResponseBody and returns it as T . | 53 | 12 |
29,776 | public static < T extends Errors > T parseError ( ObjectMapper mapper , JsonNode errorResponse , Class < T > cls ) throws JsonProcessingException { return mapper . treeToValue ( errorResponse , cls ) ; } | Parses provided JsonNode and returns it as T . | 53 | 13 |
29,777 | public static < L , R > Either < L , R > left ( L l ) { return new Left <> ( l ) ; } | Static factory method for creating a left value . | 29 | 9 |
29,778 | public static < L , R > Either < L , R > right ( R r ) { return new Right <> ( r ) ; } | Static factory method for creating a right value . | 29 | 9 |
29,779 | public static < X > Lens . Simple < List < X > , List < X > > asCopy ( ) { return simpleLens ( ArrayList :: new , ( xs , ys ) -> ys ) ; } | Convenience static factory method for creating a lens over a copy of a list . Useful for composition to avoid mutating a list reference . | 46 | 28 |
29,780 | public static < T extends Throwable , A > Try < T , A > success ( A a ) { return new Success <> ( a ) ; } | Static factory method for creating a success value . | 32 | 9 |
29,781 | public static < T extends Throwable , A > Try < T , A > failure ( T t ) { return new Failure <> ( t ) ; } | Static factory method for creating a failure value . | 32 | 9 |
29,782 | public < B > State < S , B > mapState ( Fn1 < ? super Tuple2 < A , S > , ? extends Product2 < B , S > > fn ) { return state ( s -> fn . apply ( run ( s ) ) ) ; } | Map both the result and the final state to a new result and final state . | 57 | 16 |
29,783 | public State < S , A > withState ( Fn1 < ? super S , ? extends S > fn ) { return state ( s -> run ( fn . apply ( s ) ) ) ; } | Map the final state to a new final state using the provided function . | 41 | 14 |
29,784 | public static < Head , Tail extends HList > HCons < Head , Tail > cons ( Head head , Tail tail ) { return new HCons <> ( head , tail ) ; } | Static factory method for creating an HList from the given head and tail . | 39 | 15 |
29,785 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 > Tuple2 < _1 , _2 > tuple ( _1 _1 , _2 _2 ) { return singletonHList ( _2 ) . cons ( _1 ) ; } | Static factory method for creating a 2 - element HList . | 61 | 12 |
29,786 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 > Tuple3 < _1 , _2 , _3 > tuple ( _1 _1 , _2 _2 , _3 _3 ) { return tuple ( _2 , _3 ) . cons ( _1 ) ; } | Static factory method for creating a 3 - element HList . | 72 | 12 |
29,787 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 , _4 > Tuple4 < _1 , _2 , _3 , _4 > tuple ( _1 _1 , _2 _2 , _3 _3 , _4 _4 ) { return tuple ( _2 , _3 , _4 ) . cons ( _1 ) ; } | Static factory method for creating a 4 - element HList . | 86 | 12 |
29,788 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 , _4 , _5 > Tuple5 < _1 , _2 , _3 , _4 , _5 > tuple ( _1 _1 , _2 _2 , _3 _3 , _4 _4 , _5 _5 ) { return tuple ( _2 , _3 , _4 , _5 ) . cons ( _1 ) ; } | Static factory method for creating a 5 - element HList . | 100 | 12 |
29,789 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 , _4 , _5 , _6 > Tuple6 < _1 , _2 , _3 , _4 , _5 , _6 > tuple ( _1 _1 , _2 _2 , _3 _3 , _4 _4 , _5 _5 , _6 _6 ) { return tuple ( _2 , _3 , _4 , _5 , _6 ) . cons ( _1 ) ; } | Static factory method for creating a 6 - element HList . | 114 | 12 |
29,790 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 , _4 , _5 , _6 , _7 > Tuple7 < _1 , _2 , _3 , _4 , _5 , _6 , _7 > tuple ( _1 _1 , _2 _2 , _3 _3 , _4 _4 , _5 _5 , _6 _6 , _7 _7 ) { return tuple ( _2 , _3 , _4 , _5 , _6 , _7 ) . cons ( _1 ) ; } | Static factory method for creating a 7 - element HList . | 128 | 12 |
29,791 | @ SuppressWarnings ( "JavaDoc" ) public static < _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 > Tuple8 < _1 , _2 , _3 , _4 , _5 , _6 , _7 , _8 > tuple ( _1 _1 , _2 _2 , _3 _3 , _4 _4 , _5 _5 , _6 _6 , _7 _7 , _8 _8 ) { return tuple ( _2 , _3 , _4 , _5 , _6 , _7 , _8 ) . cons ( _1 ) ; } | Static factory method for creating an 8 - element HList . | 142 | 12 |
29,792 | public static < A > Lazy < A > lazy ( Supplier < A > supplier ) { return new Later <> ( fn0 ( supplier ) ) ; } | Wrap a computation in a lazy computation . | 34 | 9 |
29,793 | public static < K , V > Lens . Simple < Map < K , V > , Map < K , V > > asCopy ( ) { return adapt ( asCopy ( HashMap :: new ) ) ; } | A lens that focuses on a copy of a Map . Useful for composition to avoid mutating a map reference . | 44 | 22 |
29,794 | public static < K , V > Lens . Simple < Map < K , V > , Set < K > > keys ( ) { return simpleLens ( m -> new HashSet <> ( m . keySet ( ) ) , ( m , ks ) -> { HashSet < K > ksCopy = new HashSet <> ( ks ) ; Map < K , V > updated = new HashMap <> ( m ) ; Set < K > keys = updated . keySet ( ) ; keys . retainAll ( ksCopy ) ; ksCopy . removeAll ( keys ) ; ksCopy . forEach ( k -> updated . put ( k , null ) ) ; return updated ; } ) ; } | A lens that focuses on the keys of a map . | 150 | 11 |
29,795 | @ SuppressWarnings ( "unchecked" ) public < A , B > Maybe < B > get ( TypeSafeKey < A , B > key ) { return maybe ( ( A ) table . get ( key ) ) . fmap ( view ( key ) ) ; } | Retrieve the value at this key . | 59 | 8 |
29,796 | public < V > HMap put ( TypeSafeKey < ? , V > key , V value ) { return alter ( t -> t . put ( key , view ( key . mirror ( ) , value ) ) ) ; } | Store a value for the given key . | 47 | 8 |
29,797 | public static < V > HMap singletonHMap ( TypeSafeKey < ? , V > key , V value ) { return emptyHMap ( ) . put ( key , value ) ; } | Static factory method for creating a singleton HMap . | 41 | 11 |
29,798 | public static < V1 , V2 > HMap hMap ( TypeSafeKey < ? , V1 > key1 , V1 value1 , TypeSafeKey < ? , V2 > key2 , V2 value2 ) { return singletonHMap ( key1 , value1 ) . put ( key2 , value2 ) ; } | Static factory method for creating an HMap from two given associations . | 72 | 13 |
29,799 | public static < V1 , V2 , V3 > HMap hMap ( TypeSafeKey < ? , V1 > key1 , V1 value1 , TypeSafeKey < ? , V2 > key2 , V2 value2 , TypeSafeKey < ? , V3 > key3 , V3 value3 ) { return hMap ( key1 , value1 , key2 , value2 ) . put ( key3 , value3 ) ; } | Static factory method for creating an HMap from three given associations . | 96 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.