idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,100
public String getGroupedValue ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( getRegisternummer ( ) ) . append ( Constants . DOT ) ; sb . append ( getAccountType ( ) ) . append ( Constants . DOT ) ; sb . append ( getPartAfterAccountType ( ) ) ; return sb . toString ( ) ; }
Returns the Kontonummer as a String formatted with . s separating the Registernummer AccountType and end part .
5,101
public static List < Fodselsnummer > getFodselsnummerForDateAndGender ( Date date , KJONN kjonn ) { List < Fodselsnummer > result = getManyFodselsnummerForDate ( date ) ; splitByGender ( kjonn , result ) ; return result ; }
Returns a List with valid Fodselsnummer instances for a given Date and gender .
5,102
public static Fodselsnummer getFodselsnummerForDate ( Date date ) { List < Fodselsnummer > fodselsnummerList = getManyFodselsnummerForDate ( date ) ; Collections . shuffle ( fodselsnummerList ) ; return fodselsnummerList . get ( 0 ) ; }
Return one random valid fodselsnummer on a given date
5,103
public static List < Fodselsnummer > getManyDNumberFodselsnummerForDate ( Date date ) { if ( date == null ) { throw new IllegalArgumentException ( ) ; } DateFormat df = new SimpleDateFormat ( "ddMMyy" ) ; String centuryString = getCentury ( date ) ; String dateString = df . format ( date ) ; dateString = new StringBuilder ( ) . append ( Character . toChars ( dateString . charAt ( 0 ) + 4 ) [ 0 ] ) . append ( dateString . substring ( 1 ) ) . toString ( ) ; return generateFodselsnummerForDate ( dateString , centuryString ) ; }
Returns a List with with VALID DNumber Fodselsnummer instances for a given Date .
5,104
public static List < Fodselsnummer > getManyFodselsnummerForDate ( Date date ) { if ( date == null ) { throw new IllegalArgumentException ( ) ; } DateFormat df = new SimpleDateFormat ( "ddMMyy" ) ; String centuryString = getCentury ( date ) ; String dateString = df . format ( date ) ; return generateFodselsnummerForDate ( dateString , centuryString ) ; }
Returns a List with with VALID Fodselsnummer instances for a given Date .
5,105
public static GeoParser getDefault ( String pathToLuceneIndex , int maxHitDepth , int maxContentWindow ) throws ClavinException { return getDefault ( pathToLuceneIndex , maxHitDepth , maxContentWindow , false ) ; }
Get a GeoParser with defined values for maxHitDepth and maxContentWindow .
5,106
public static GeoParser getDefault ( String pathToLuceneIndex , int maxHitDepth , int maxContentWindow , boolean fuzzy ) throws ClavinException { try { LocationExtractor extractor = new ApacheExtractor ( ) ; return getDefault ( pathToLuceneIndex , extractor , maxHitDepth , maxContentWindow , fuzzy ) ; } catch ( IOException ioe ) { throw new ClavinException ( "Error creating ApacheExtractor" , ioe ) ; } }
Get a GeoParser with defined values for maxHitDepth and maxContentWindow and fuzzy matching explicitly turned on or off .
5,107
public static GeoParser getDefault ( String pathToLuceneIndex , LocationExtractor extractor , int maxHitDepth , int maxContentWindow , boolean fuzzy ) throws ClavinException { Gazetteer gazetteer = new LuceneGazetteer ( new File ( pathToLuceneIndex ) ) ; return new GeoParser ( extractor , gazetteer , maxHitDepth , maxContentWindow , fuzzy ) ; }
Get a GeoParser with defined values for maxHitDepth and maxContentWindow fuzzy matching explicitly turned on or off and a specific LocationExtractor to use .
5,108
public static Kidnummer mod10Kid ( String baseNumber , int targetLength ) { if ( baseNumber . length ( ) >= targetLength ) throw new IllegalArgumentException ( "baseNumber too long" ) ; String padded = String . format ( "%0" + ( targetLength - 1 ) + "d" , new BigInteger ( baseNumber ) ) ; Kidnummer k = new Kidnummer ( padded + "0" ) ; return KidnummerValidator . getKidnummer ( padded + calculateMod10CheckSum ( getMod10Weights ( k ) , k ) ) ; }
Create a valid KID numer of the wanted length using MOD10 . Input is padded with leading zeros to reach wanted target length
5,109
public static Kidnummer mod11Kid ( String baseNumber , int targetLength ) { if ( baseNumber . length ( ) >= targetLength ) throw new IllegalArgumentException ( "baseNumber too long" ) ; String padded = String . format ( "%0" + ( targetLength - 1 ) + "d" , new BigInteger ( baseNumber ) ) ; Kidnummer k = new Kidnummer ( padded + "0" ) ; return KidnummerValidator . getKidnummer ( padded + calculateMod11CheckSum ( getMod11Weights ( k ) , k ) ) ; }
Create a valid KID numer of the wanted length using MOD11 . Input is padded with leading zeros to reach wanted target length
5,110
private String sanitizeQueryText ( final GazetteerQuery query ) { String sanitized = "" ; if ( query != null && query . getOccurrence ( ) != null ) { String text = query . getOccurrence ( ) . getText ( ) ; if ( text != null ) { sanitized = escape ( text . trim ( ) . toLowerCase ( ) ) ; } } return sanitized ; }
Sanitizes the text of the LocationOccurrence in the query parameters for use in a Lucene query returning an empty string if no text is found .
5,111
private Filter buildFilter ( final GazetteerQuery params ) { List < Query > queryParts = new ArrayList < Query > ( ) ; if ( ! params . isIncludeHistorical ( ) ) { int val = IndexField . getBooleanIndexValue ( false ) ; queryParts . add ( NumericRangeQuery . newIntRange ( HISTORICAL . key ( ) , val , val , true , true ) ) ; } Set < Integer > parentIds = params . getParentIds ( ) ; if ( ! parentIds . isEmpty ( ) ) { BooleanQuery parentQuery = new BooleanQuery ( ) ; for ( Integer id : parentIds ) { parentQuery . add ( NumericRangeQuery . newIntRange ( ANCESTOR_IDS . key ( ) , id , id , true , true ) , Occur . SHOULD ) ; } queryParts . add ( parentQuery ) ; } Set < FeatureCode > codes = params . getFeatureCodes ( ) ; if ( ! ( codes . isEmpty ( ) || ALL_CODES . equals ( codes ) ) ) { BooleanQuery codeQuery = new BooleanQuery ( ) ; for ( FeatureCode code : codes ) { codeQuery . add ( new TermQuery ( new Term ( FEATURE_CODE . key ( ) , code . name ( ) ) ) , Occur . SHOULD ) ; } queryParts . add ( codeQuery ) ; } Filter filter = null ; if ( ! queryParts . isEmpty ( ) ) { BooleanQuery bq = new BooleanQuery ( ) ; for ( Query part : queryParts ) { bq . add ( part , Occur . MUST ) ; } filter = new QueryWrapperFilter ( bq ) ; } return filter ; }
Builds a Lucene search filter based on the provided parameters .
5,112
private void resolveParents ( final Map < Integer , Set < GeoName > > childMap ) throws IOException { Map < Integer , GeoName > parentMap = new HashMap < Integer , GeoName > ( ) ; Map < Integer , Set < GeoName > > grandParentMap = new HashMap < Integer , Set < GeoName > > ( ) ; for ( Integer parentId : childMap . keySet ( ) ) { Query q = NumericRangeQuery . newIntRange ( GEONAME_ID . key ( ) , parentId , parentId , true , true ) ; TopDocs results = indexSearcher . search ( q , null , 1 , POPULATION_SORT ) ; if ( results . scoreDocs . length > 0 ) { Document doc = indexSearcher . doc ( results . scoreDocs [ 0 ] . doc ) ; GeoName parent = BasicGeoName . parseFromGeoNamesRecord ( doc . get ( GEONAME . key ( ) ) , doc . get ( PREFERRED_NAME . key ( ) ) ) ; parentMap . put ( parent . getGeonameID ( ) , parent ) ; if ( ! parent . isAncestryResolved ( ) ) { Integer grandParentId = PARENT_ID . getValue ( doc ) ; if ( grandParentId != null ) { Set < GeoName > geos = grandParentMap . get ( grandParentId ) ; if ( geos == null ) { geos = new HashSet < GeoName > ( ) ; grandParentMap . put ( grandParentId , geos ) ; } geos . add ( parent ) ; } } } else { LOG . error ( "Unable to find parent GeoName [{}]" , parentId ) ; } } if ( ! grandParentMap . isEmpty ( ) ) { resolveParents ( grandParentMap ) ; } for ( Integer parentId : childMap . keySet ( ) ) { GeoName parent = parentMap . get ( parentId ) ; if ( parent == null ) { LOG . info ( "Unable to find parent with ID [{}]" , parentId ) ; continue ; } for ( GeoName child : childMap . get ( parentId ) ) { child . setParent ( parent ) ; } } }
Retrieves and sets the parents of the provided children .
5,113
protected TokenStreamComponents createComponents ( final String fieldName , final Reader reader ) { return new TokenStreamComponents ( new WhitespaceLowerCaseTokenizer ( matchVersion , reader ) ) ; }
Provides tokenizer access for the analyzer .
5,114
public static void main ( String [ ] args ) throws IOException { Options options = getOptions ( ) ; CommandLine cmd = null ; CommandLineParser parser = new GnuParser ( ) ; try { cmd = parser . parse ( options , args ) ; } catch ( ParseException pe ) { LOG . error ( pe . getMessage ( ) ) ; printHelp ( options ) ; System . exit ( - 1 ) ; } if ( cmd . hasOption ( HELP_OPTION ) ) { printHelp ( options ) ; System . exit ( 0 ) ; } String indexPath = cmd . getOptionValue ( INDEX_PATH_OPTION , DEFAULT_INDEX_DIRECTORY ) ; String [ ] gazetteerPaths = cmd . getOptionValues ( GAZETTEER_FILES_OPTION ) ; if ( gazetteerPaths == null || gazetteerPaths . length == 0 ) { gazetteerPaths = DEFAULT_GAZETTEER_FILES ; } boolean replaceIndex = cmd . hasOption ( REPLACE_INDEX_OPTION ) ; boolean fullAncestry = cmd . hasOption ( FULL_ANCESTRY_OPTION ) ; File idir = new File ( indexPath ) ; if ( idir . exists ( ) ) { if ( replaceIndex ) { LOG . info ( "Replacing index: {}" , idir . getAbsolutePath ( ) ) ; FileUtils . deleteDirectory ( idir ) ; } else { LOG . info ( "{} exists. Remove the directory and try again." , idir . getAbsolutePath ( ) ) ; System . exit ( - 1 ) ; } } List < File > gazetteerFiles = new ArrayList < File > ( ) ; for ( String gp : gazetteerPaths ) { File gf = new File ( gp ) ; if ( gf . isFile ( ) && gf . canRead ( ) ) { gazetteerFiles . add ( gf ) ; } else { LOG . info ( "Unable to read Gazetteer file: {}" , gf . getAbsolutePath ( ) ) ; } } if ( gazetteerFiles . isEmpty ( ) ) { LOG . error ( "No Gazetteer files found." ) ; System . exit ( - 1 ) ; } String altNamesPath = cmd . getOptionValue ( ALTERNATE_NAMES_OPTION ) ; File altNamesFile = altNamesPath != null ? new File ( altNamesPath ) : null ; if ( altNamesFile != null && ! ( altNamesFile . isFile ( ) && altNamesFile . canRead ( ) ) ) { LOG . error ( "Unable to read alternate names file: {}" , altNamesPath ) ; System . exit ( - 1 ) ; } new IndexDirectoryBuilder ( fullAncestry ) . buildIndex ( idir , gazetteerFiles , altNamesFile ) ; }
Turns a GeoNames gazetteer file into a Lucene index and adds some supplementary gazetteer records at the end .
5,115
public static boolean isValid ( String kontonummer ) { try { KontonummerValidator . getKontonummer ( kontonummer ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } }
Return true if the provided String is a valid Kontonummmer .
5,116
public static Kontonummer getKontonummer ( String kontonummer ) throws IllegalArgumentException { validateSyntax ( kontonummer ) ; validateChecksum ( kontonummer ) ; return new Kontonummer ( kontonummer ) ; }
Returns an object that represents a Kontonummer .
5,117
public static Kontonummer getAndForceValidKontonummer ( String kontonummer ) { validateSyntax ( kontonummer ) ; try { validateChecksum ( kontonummer ) ; } catch ( IllegalArgumentException iae ) { Kontonummer k = new Kontonummer ( kontonummer ) ; int checksum = calculateMod11CheckSum ( getMod11Weights ( k ) , k ) ; kontonummer = kontonummer . substring ( 0 , LENGTH - 1 ) + checksum ; } return new Kontonummer ( kontonummer ) ; }
Returns an object that represents a Kontonummer . The checksum of the supplied kontonummer is changed to a valid checksum if the original kontonummer has an invalid checksum .
5,118
private List < ResolvedLocation > pickBestCandidates ( final List < List < ResolvedLocation > > allCandidates ) { List < ResolvedLocation > bestCandidates = new ArrayList < ResolvedLocation > ( ) ; Set < CountryCode > countries ; Set < String > states ; float score ; float newMaxScore = 0 ; float oldMaxScore ; int candidateDepth = 3 ; do { oldMaxScore = newMaxScore ; for ( List < ResolvedLocation > combo : generateAllCombos ( allCandidates , 0 , candidateDepth ) ) { countries = EnumSet . noneOf ( CountryCode . class ) ; states = new HashSet < String > ( ) ; for ( ResolvedLocation location : combo ) { countries . add ( location . getGeoname ( ) . getPrimaryCountryCode ( ) ) ; states . add ( location . getGeoname ( ) . getPrimaryCountryCode ( ) + location . getGeoname ( ) . getAdmin1Code ( ) ) ; } score = ( ( float ) allCandidates . size ( ) / ( countries . size ( ) + states . size ( ) ) ) / candidateDepth ; if ( score > newMaxScore ) { newMaxScore = score ; bestCandidates = combo ; } } candidateDepth ++ ; } while ( newMaxScore > oldMaxScore ) ; return bestCandidates ; }
Uses heuristics to select the best match for each location name extracted from a document choosing from among a list of lists of candidate matches .
5,119
public GazetteerQuery build ( ) { return new GazetteerQuery ( location , maxResults , fuzzyMode , ancestryMode , includeHistorical , filterDupes , parentIds , featureCodes ) ; }
Constructs a query from the current configuration of this Builder .
5,120
public static boolean isEditDistance1 ( String str1 , String str2 ) { if ( ( str1 == null ) || str1 . isEmpty ( ) ) { if ( ( str2 == null ) || str2 . isEmpty ( ) ) { return true ; } else { return ( str2 . length ( ) <= 1 ) ; } } else if ( ( str2 == null ) || str2 . isEmpty ( ) ) { return ( str1 . length ( ) <= 1 ) ; } if ( Math . abs ( str1 . length ( ) - str2 . length ( ) ) > 1 ) return false ; int offset1 = 0 ; int offset2 = 0 ; int i = 0 ; InfiniteCharArray chars1 = new InfiniteCharArray ( str1 . toCharArray ( ) ) ; InfiniteCharArray chars2 = new InfiniteCharArray ( str2 . toCharArray ( ) ) ; while ( ! chars1 . get ( i + offset1 ) . equals ( endMarker ) || ! chars2 . get ( i + offset2 ) . equals ( endMarker ) ) { if ( ! chars1 . get ( i + offset1 ) . equals ( chars2 . get ( i + offset2 ) ) ) { if ( ( chars1 . get ( i + offset1 ) . equals ( chars2 . get ( i + offset2 + 1 ) ) ) && ( chars1 . get ( i + offset1 + 1 ) . equals ( chars2 . get ( i + offset2 ) ) ) && ( chars1 . remainder ( i + offset1 + 2 ) . equals ( chars2 . remainder ( i + offset2 + 2 ) ) ) ) { i = i + 2 ; } else if ( chars1 . remainder ( i + offset1 ) . equals ( chars2 . remainder ( i + offset2 + 1 ) ) ) { offset2 ++ ; } else if ( chars1 . remainder ( i + offset1 + 1 ) . equals ( chars2 . remainder ( i + offset2 ) ) ) { offset1 ++ ; } else if ( chars1 . remainder ( i + offset1 + 1 ) . equals ( chars2 . remainder ( i + offset2 + 1 ) ) ) { i ++ ; } else return false ; } i ++ ; } return true ; }
Fast method for determining whether the Damerau - Levenshtein edit distance between two strings is less than 2 .
5,121
protected String remainder ( int index ) { if ( index > this . array . length ) return "" ; else return new String ( Arrays . copyOfRange ( this . array , index , this . array . length ) ) ; }
Get the contents of the char array to the right of the given index and return it as a String .
5,122
public static < T > Iterable < PSArray < T > > create ( Iterable < T > items , final Comparator < T > comparator ) { MutableArray < T > initial = MutableArrayFromIterable . create ( items ) ; GoodSortingAlgorithm . getInstance ( ) . sort ( initial , comparator ) ; return IterableUsingStatusUpdater . create ( initial , new Updater < PSArray < T > > ( ) { public PSArray < T > getUpdatedOrNull ( PSArray < T > current ) { MutableArray < T > next = MutableArrayFromIterable . create ( current ) ; boolean success = NextPermutation . step ( next , comparator ) ; return success ? next : null ; } } ) ; }
SRM464 - 1 - 250 is a good problem to solve using this .
5,123
public static < V , E extends DirectedEdge < V > > void traverse ( Graph < V , E > graph , DFSVisitor < V , E > visitor ) { MultiSourceDFS . traverse ( graph , graph . getVertices ( ) , visitor ) ; }
Remember that visiting order is not ordered .
5,124
private static < T > IntPair findBridgeIndexes ( PSArray < Point2D < T > > earlyHull , PSArray < Point2D < T > > laterHull , int earlyStart , int laterStart , MultipliableNumberSystem < T > ns ) { int early = earlyStart ; int later = laterStart ; while ( true ) { int nextEarly = getPreIndex ( early , earlyHull . size ( ) ) ; int nextLater = getNextIndex ( later , laterHull . size ( ) ) ; if ( LeftTurn . is ( laterHull . get ( later ) , earlyHull . get ( early ) , earlyHull . get ( nextEarly ) , ns ) ) early = nextEarly ; else if ( RightTurn . is ( earlyHull . get ( early ) , laterHull . get ( later ) , laterHull . get ( nextLater ) , ns ) ) later = nextLater ; else break ; } return new IntPair ( early , later ) ; }
early later are ordered by ccw order .
5,125
public static TrieNodeFactory < Boolean > getInstance ( ) { return new TrieNodeFactory < Boolean > ( ) { public TrieNode < Boolean > create ( ) { return new BooleanTrieNode ( ) ; } } ; }
specialized in speed for boolean keyed nodes .
5,126
public static void renderTemplateAsExcel ( String templateName , Object ... args ) { Scope . RenderArgs templateBinding = Scope . RenderArgs . current ( ) ; for ( Object o : args ) { List < String > names = LocalvariablesNamesEnhancer . LocalVariablesNamesTracer . getAllLocalVariableNames ( o ) ; for ( String name : names ) { templateBinding . put ( name , o ) ; } } templateBinding . put ( "session" , Scope . Session . current ( ) ) ; templateBinding . put ( "request" , Http . Request . current ( ) ) ; templateBinding . put ( "flash" , Scope . Flash . current ( ) ) ; templateBinding . put ( "params" , Scope . Params . current ( ) ) ; if ( null == templateBinding . get ( "fileName" ) ) { templateBinding . put ( "fileName" , templateName . substring ( templateName . lastIndexOf ( "/" ) + 1 ) + ".xls" ) ; } try { templateBinding . put ( "errors" , Validation . errors ( ) ) ; } catch ( Exception ex ) { throw new UnexpectedException ( ex ) ; } try { throw new RenderExcelTemplate ( templateName + ".xls" , templateBinding . data , templateBinding . get ( "fileName" ) . toString ( ) ) ; } catch ( TemplateNotFoundException ex ) { if ( ex . isSourceAvailable ( ) ) { throw ex ; } StackTraceElement element = PlayException . getInterestingStrackTraceElement ( ex ) ; if ( element != null ) { throw new TemplateNotFoundException ( templateName , Play . classes . getApplicationClass ( element . getClassName ( ) ) , element . getLineNumber ( ) ) ; } else { throw ex ; } } }
Render a specific template
5,127
public static void renderExcel ( Object ... args ) { String templateName = null ; final Http . Request request = Http . Request . current ( ) ; if ( args . length > 0 && args [ 0 ] instanceof String && LocalvariablesNamesEnhancer . LocalVariablesNamesTracer . getAllLocalVariableNames ( args [ 0 ] ) . isEmpty ( ) ) { templateName = args [ 0 ] . toString ( ) ; } else { templateName = request . action . replace ( "." , "/" ) ; } if ( templateName . startsWith ( "@" ) ) { templateName = templateName . substring ( 1 ) ; if ( ! templateName . contains ( "." ) ) { templateName = request . controller + "." + templateName ; } templateName = templateName . replace ( "." , "/" ) ; } renderTemplateAsExcel ( templateName , args ) ; }
Render the corresponding template
5,128
public static BigDecimal setup ( BigDecimal n , NumberRoundMode roundMode , NumberFormatMode formatMode , int minIntDigits , int maxFracDigits , int minFracDigits , int maxSigDigits , int minSigDigits ) { RoundingMode mode = roundMode . toRoundingMode ( ) ; boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC ; if ( useSignificant && minSigDigits > 0 && maxSigDigits > 0 ) { if ( n . precision ( ) > maxSigDigits ) { int scale = maxSigDigits - n . precision ( ) + n . scale ( ) ; n = n . setScale ( scale , mode ) ; } if ( formatMode == NumberFormatMode . SIGNIFICANT_MAXFRAC && maxFracDigits < n . scale ( ) ) { n = n . setScale ( maxFracDigits , mode ) ; } n = n . stripTrailingZeros ( ) ; boolean zero = n . signum ( ) == 0 ; int precision = n . precision ( ) ; if ( zero && n . scale ( ) == 1 ) { precision -- ; } if ( precision < minSigDigits ) { int scale = minSigDigits - precision + n . scale ( ) ; n = n . setScale ( scale , mode ) ; } } else { int scale = Math . max ( minFracDigits , Math . min ( n . scale ( ) , maxFracDigits ) ) ; n = n . setScale ( scale , mode ) ; n = n . stripTrailingZeros ( ) ; if ( n . scale ( ) < minFracDigits ) { n = n . setScale ( minFracDigits , mode ) ; } } return n ; }
Calculates the number of integer and fractional digits to emit returning them in a 2 - element array and updates the operands .
5,129
public static void format ( BigDecimal n , DigitBuffer buf , NumberFormatterParams params , boolean currencyMode , boolean grouping , int minIntDigits , int primaryGroupingSize , int secondaryGroupingSize ) { if ( secondaryGroupingSize <= 0 ) { secondaryGroupingSize = primaryGroupingSize ; } int groupSize = primaryGroupingSize ; boolean shouldGroup = false ; long intDigits = integerDigits ( n ) ; if ( minIntDigits == 0 && n . compareTo ( BigDecimal . ONE ) == - 1 ) { intDigits = 0 ; } else { intDigits = Math . max ( intDigits , minIntDigits ) ; } if ( grouping ) { if ( primaryGroupingSize > 0 ) { shouldGroup = intDigits >= ( params . minimumGroupingDigits + primaryGroupingSize ) ; } } String decimal = currencyMode ? params . currencyDecimal : params . decimal ; String group = currencyMode ? params . currencyGroup : params . group ; int bufferStart = buf . length ( ) ; if ( n . signum ( ) == - 1 ) { n = n . negate ( ) ; } String s = n . toPlainString ( ) ; int end = s . length ( ) - 1 ; int idx = s . lastIndexOf ( '.' ) ; if ( idx != - 1 ) { while ( end > idx ) { buf . append ( s . charAt ( end ) ) ; end -- ; } end -- ; buf . append ( decimal ) ; } int emitted = 0 ; while ( intDigits > 0 && end >= 0 ) { if ( shouldGroup ) { boolean emit = emitted > 0 && emitted % groupSize == 0 ; if ( emit ) { buf . append ( group ) ; emitted -= groupSize ; groupSize = secondaryGroupingSize ; } } buf . append ( s . charAt ( end ) ) ; end -- ; emitted ++ ; intDigits -- ; } if ( intDigits > 0 ) { for ( int i = 0 ; i < intDigits ; i ++ ) { if ( shouldGroup ) { boolean emit = emitted > 0 && emitted % groupSize == 0 ; if ( emit ) { buf . append ( group ) ; emitted -= groupSize ; groupSize = secondaryGroupingSize ; } } buf . append ( '0' ) ; emitted ++ ; } } buf . reverse ( bufferStart ) ; }
Formats the number into the digit buffer .
5,130
public int distance ( CLDR . Locale desired , CLDR . Locale supported ) { return distance ( desired , supported , DEFAULT_THRESHOLD ) ; }
Returns the distance between the desired and supported locale using the default distance threshold .
5,131
public int distance ( CLDR . Locale desired , CLDR . Locale supported , int threshold ) { boolean langEquals = desired . language ( ) . equals ( supported . language ( ) ) ; Node node = distanceMap . get ( desired . language ( ) , supported . language ( ) ) ; if ( node == null ) { node = distanceMap . get ( ANY , ANY ) ; } int distance = node . wildcard ( ) ? ( langEquals ? 0 : node . distance ( ) ) : node . distance ( ) ; if ( distance >= threshold ) { return MAX_DISTANCE ; } DistanceMap map = node . map ( ) ; boolean scriptEquals = desired . script ( ) . equals ( supported . script ( ) ) ; node = map . get ( desired . script ( ) , supported . script ( ) ) ; if ( node == null ) { node = map . get ( ANY , ANY ) ; } distance += node . wildcard ( ) ? ( scriptEquals ? 0 : node . distance ( ) ) : node . distance ( ) ; if ( distance >= threshold ) { return MAX_DISTANCE ; } map = node . map ( ) ; if ( desired . territory ( ) . equals ( supported . territory ( ) ) ) { return distance ; } node = map . get ( desired . territory ( ) , supported . territory ( ) ) ; if ( node == null ) { node = scanTerritory ( map , desired . territory ( ) , supported . territory ( ) ) ; } if ( node != null ) { distance += node . distance ( ) ; return distance < threshold ? distance : MAX_DISTANCE ; } int maxDistance = 0 ; boolean match = false ; Set < String > desiredPartitions = PARTITION_TABLE . getRegionPartition ( desired . territory ( ) ) ; Set < String > supportedPartitions = PARTITION_TABLE . getRegionPartition ( supported . territory ( ) ) ; for ( String desiredPartition : desiredPartitions ) { for ( String supportedPartition : supportedPartitions ) { node = map . get ( desiredPartition , supportedPartition ) ; if ( node != null ) { maxDistance = Math . max ( maxDistance , node . distance ( ) ) ; match = true ; } } } if ( ! match ) { node = map . get ( ANY , ANY ) ; maxDistance = Math . max ( maxDistance , node . distance ( ) ) ; } distance += maxDistance ; return distance < threshold ? distance : MAX_DISTANCE ; }
Returns the distance between the desired and supported locale using the given distance threshold . Any distance equal to or greater than the threshold will return the maximum distance .
5,132
private Node scanTerritory ( DistanceMap map , String desired , String supported ) { Node node ; for ( String partition : PARTITION_TABLE . getRegionPartition ( desired ) ) { node = map . get ( partition , supported ) ; if ( node != null ) { return node ; } } for ( String partition : PARTITION_TABLE . getRegionPartition ( supported ) ) { node = map . get ( desired , partition ) ; if ( node != null ) { return node ; } } return null ; }
Scan the desired region against the supported partitions and vice versa . Return the first matching node .
5,133
public String applies ( ZonedDateTime d ) { long epoch = d . toEpochSecond ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Entry entry = entries [ i ] ; if ( entry . from == - 1 ) { if ( entry . to == - 1 || epoch < entry . to ) { return entry . metazoneId ; } } else if ( entry . to == - 1 ) { if ( entry . from <= epoch ) { return entry . metazoneId ; } } else if ( entry . from <= epoch && epoch < entry . to ) { return entry . metazoneId ; } } return null ; }
Find the metazone that applies for a given timestamp .
5,134
public Match match ( List < String > desired , int threshold ) { return matchImpl ( parse ( desired ) , threshold ) ; }
Return the best match that exceeds the threshold . If the default is returned its distance is set to MAX_DISTANCE .
5,135
public List < Match > matches ( List < String > desired ) { return matchesImpl ( parse ( desired ) , DEFAULT_THRESHOLD ) ; }
Return all matches and their distances if they exceed the default threshold . If no match exceeds the threshold this returns an empty list .
5,136
private Match matchImpl ( List < Entry > desiredLocales , int threshold ) { int bestDistance = MAX_DISTANCE ; Entry bestMatch = null ; for ( Entry desired : desiredLocales ) { List < String > exact = exactMatch . get ( desired . locale ) ; if ( exact != null ) { return new Match ( exact . get ( 0 ) , 0 ) ; } for ( Entry supported : supportedLocales ) { int distance = DISTANCE_TABLE . distance ( desired . locale , supported . locale , threshold ) ; if ( distance < bestDistance ) { bestDistance = distance ; bestMatch = supported ; } } } return bestMatch == null ? new Match ( firstEntry . bundleId , MAX_DISTANCE ) : new Match ( bestMatch . bundleId , bestDistance ) ; }
Return the best match that exceeds the threshold or the default . If the default is returned its distance is set to MAX_DISTANCE . An exact match has distance of 0 .
5,137
public void generate ( Path outputDir , DataReader reader ) throws IOException { String className = "_PluralRules" ; TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . addModifiers ( PUBLIC ) . superclass ( TYPE_BASE ) ; Map < String , FieldSpec > fieldMap = buildConditionFields ( reader . cardinals ( ) , reader . ordinals ( ) ) ; for ( Map . Entry < String , FieldSpec > entry : fieldMap . entrySet ( ) ) { type . addField ( entry . getValue ( ) ) ; } buildPluralMethod ( type , "Cardinal" , reader . cardinals ( ) , fieldMap ) ; buildPluralMethod ( type , "Ordinal" , reader . ordinals ( ) , fieldMap ) ; CodeGenerator . saveClass ( outputDir , PACKAGE_CLDR_PLURALS , className , type . build ( ) ) ; }
Generate a class for plural rule evaluation .
5,138
private MethodSpec buildRuleMethod ( String methodName , PluralData data , Map < String , FieldSpec > fieldMap ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( methodName ) . addModifiers ( PRIVATE , STATIC ) . addParameter ( NUMBER_OPERANDS , "o" ) . returns ( PLURAL_CATEGORY ) ; for ( Map . Entry < String , PluralData . Rule > entry : data . rules ( ) . entrySet ( ) ) { String category = entry . getKey ( ) ; if ( category . equals ( "other" ) ) { method . addStatement ( "return PluralCategory.OTHER" ) ; break ; } PluralData . Rule rule = entry . getValue ( ) ; String ruleRepr = PluralRulePrinter . print ( rule . condition ) ; List < String > fields = new ArrayList < > ( ) ; for ( Node < PluralType > condition : rule . condition . asStruct ( ) . nodes ( ) ) { String repr = PluralRulePrinter . print ( condition ) ; fields . add ( fieldMap . get ( repr ) . name ) ; } method . addComment ( " $L" , ruleRepr ) ; if ( ! Objects . equals ( rule . sample , "" ) ) { List < String > samples = Splitter . on ( "@" ) . splitToList ( rule . sample ) ; for ( String sample : samples ) { method . addComment ( " $L" , sample ) ; } } int size = fields . size ( ) ; String stmt = "if (" ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { stmt += " || " ; } stmt += fields . get ( i ) + ".eval(o)" ; } stmt += ")" ; method . beginControlFlow ( stmt ) ; method . addStatement ( "return PluralCategory." + category . toUpperCase ( ) ) ; method . endControlFlow ( ) ; method . addCode ( "\n" ) ; } return method . build ( ) ; }
Builds a method that when called evaluates the rule and returns a PluralCategory .
5,139
private final Map < String , FieldSpec > buildConditionFields ( Map < String , PluralData > ... pluralMaps ) { Map < String , FieldSpec > index = new LinkedHashMap < > ( ) ; int seq = 0 ; for ( Map < String , PluralData > pluralMap : pluralMaps ) { for ( Map . Entry < String , PluralData > entry : pluralMap . entrySet ( ) ) { PluralData data = entry . getValue ( ) ; for ( Map . Entry < String , PluralData . Rule > rule : data . rules ( ) . entrySet ( ) ) { Node < PluralType > orCondition = rule . getValue ( ) . condition ; if ( orCondition == null ) { continue ; } for ( Node < PluralType > andCondition : orCondition . asStruct ( ) . nodes ( ) ) { String repr = PluralRulePrinter . print ( andCondition ) ; if ( index . containsKey ( repr ) ) { continue ; } FieldSpec field = buildConditionField ( seq , andCondition . asStruct ( ) ) ; index . put ( repr , field ) ; seq ++ ; } } } } return index ; }
Maps an integer to each AND condition s canonical representation .
5,140
public FieldSpec buildConditionField ( int index , Struct < PluralType > branch ) { String fieldDoc = PluralRulePrinter . print ( branch ) ; String name = String . format ( "COND_%d" , index ) ; FieldSpec . Builder field = FieldSpec . builder ( PLURAL_CONDITION , name , PRIVATE , STATIC , FINAL ) . addJavadoc ( fieldDoc + "\n" ) ; List < Node < PluralType > > expressions = branch . nodes ( ) ; CodeBlock . Builder code = CodeBlock . builder ( ) ; code . beginControlFlow ( "(o) ->" ) ; int size = expressions . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { renderExpr ( i == 0 , code , expressions . get ( i ) ) ; } code . addStatement ( "return true" ) ; code . endControlFlow ( ) ; field . initializer ( code . build ( ) ) ; return field . build ( ) ; }
Constructs a lambda Condition field that represents a chain of AND conditions that together is a single branch in an OR condition .
5,141
private static void renderExpr ( boolean first , CodeBlock . Builder code , Node < PluralType > expr ) { Iterator < Node < PluralType > > iter = expr . asStruct ( ) . nodes ( ) . iterator ( ) ; Atom < PluralType > operand = iter . next ( ) . asAtom ( ) ; Atom < PluralType > modop = null ; Atom < PluralType > relop = iter . next ( ) . asAtom ( ) ; if ( relop . type ( ) == PluralType . MODOP ) { modop = relop ; relop = iter . next ( ) . asAtom ( ) ; } String var = ( String ) operand . value ( ) ; List < Node < PluralType > > rangeList = iter . next ( ) . asStruct ( ) . nodes ( ) ; boolean decimalsZero = false ; if ( var . equals ( "n" ) && modop != null ) { decimalsZero = true ; } String fmt = "zz = o.$L()" ; if ( first ) { fmt = "long " + fmt ; } if ( modop != null ) { fmt += " % $LL" ; } if ( modop != null ) { code . addStatement ( fmt , var , ( int ) modop . value ( ) ) ; } else { code . addStatement ( fmt , var ) ; } renderExpr ( code , rangeList , relop . value ( ) . equals ( "=" ) , decimalsZero ) ; }
Render the header of a branch method .
5,142
private static void renderExpr ( CodeBlock . Builder code , List < Node < PluralType > > rangeList , boolean equal , boolean decimalsZero ) { int size = rangeList . size ( ) ; String r = "" ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { r += " || " ; } r += renderRange ( "zz" , rangeList . get ( i ) ) ; } String fmt = "if (" ; if ( decimalsZero ) { fmt += "o.nd() != 0 || " ; } if ( equal ) { fmt += size == 1 ? "!$L" : "!($L)" ; } else { fmt += "($L)" ; } fmt += ")" ; code . beginControlFlow ( fmt , r ) ; code . addStatement ( "return false" ) ; code . endControlFlow ( ) ; }
Render the expression body of a branch method .
5,143
private static String renderRange ( String name , Node < PluralType > node ) { if ( node . type ( ) == PluralType . RANGE ) { Struct < PluralType > range = node . asStruct ( ) ; int start = ( Integer ) range . nodes ( ) . get ( 0 ) . asAtom ( ) . value ( ) ; int end = ( Integer ) range . nodes ( ) . get ( 1 ) . asAtom ( ) . value ( ) ; return String . format ( "(%s >= %d && %s <= %d)" , name , start , name , end ) ; } return String . format ( "(%s == %s)" , name , node . asAtom ( ) . value ( ) ) ; }
Render a the range segment of an expression .
5,144
public static String print ( Node < PluralType > node ) { StringBuilder buf = new StringBuilder ( ) ; print ( buf , node ) ; return buf . toString ( ) ; }
Return a recursive representation of the given pluralization node or tree .
5,145
private static void print ( StringBuilder buf , Node < PluralType > node ) { switch ( node . type ( ) ) { case RULE : join ( buf , node , " " ) ; break ; case AND_CONDITION : join ( buf , node , " and " ) ; break ; case OR_CONDITION : join ( buf , node , " or " ) ; break ; case RANGELIST : join ( buf , node , "," ) ; break ; case RANGE : join ( buf , node , ".." ) ; break ; case EXPR : join ( buf , node , " " ) ; break ; case MODOP : buf . append ( "% " ) . append ( node . asAtom ( ) . value ( ) ) ; break ; case INTEGER : case OPERAND : case RELOP : case SAMPLE : buf . append ( node . asAtom ( ) . value ( ) ) ; break ; } }
Recursively visit the structs and atoms in the pluralization node or tree appending the representations to a string buffer .
5,146
private static void join ( StringBuilder buf , Node < PluralType > parent , String delimiter ) { List < Node < PluralType > > nodes = parent . asStruct ( ) . nodes ( ) ; int size = nodes . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( i > 0 ) { buf . append ( delimiter ) ; } print ( buf , nodes . get ( i ) ) ; } }
Print each child node of a struct joining them together with a delimiter string .
5,147
public void format ( ZonedDateTime datetime , CalendarFormatOptions options , StringBuilder buffer ) { String dateSkeleton = options . dateSkeleton ( ) == null ? null : options . dateSkeleton ( ) . skeleton ( ) ; String timeSkeleton = options . timeSkeleton ( ) == null ? null : options . timeSkeleton ( ) . skeleton ( ) ; CalendarFormat wrapperFormat = options . wrapperFormat ( ) ; CalendarFormat dateFormat = options . dateFormat ( ) ; CalendarFormat timeFormat = options . timeFormat ( ) ; if ( wrapperFormat != null ) { dateFormat = dateFormat != null ? dateFormat : ( dateSkeleton == null ? wrapperFormat : null ) ; timeFormat = timeFormat != null ? timeFormat : ( timeSkeleton == null ? wrapperFormat : null ) ; } else { if ( ( dateFormat != null || dateSkeleton != null ) && ( timeFormat != null || timeSkeleton != null ) ) { wrapperFormat = dateFormat != null ? dateFormat : CalendarFormat . SHORT ; } } if ( wrapperFormat != null ) { formatWrapped ( wrapperFormat , dateFormat , timeFormat , dateSkeleton , timeSkeleton , datetime , buffer ) ; } else if ( options . dateFormat ( ) != null ) { formatDate ( options . dateFormat ( ) , datetime , buffer ) ; } else if ( options . timeFormat ( ) != null ) { formatTime ( options . timeFormat ( ) , datetime , buffer ) ; } else { String skeleton = dateSkeleton != null ? dateSkeleton : timeSkeleton ; if ( skeleton == null ) { skeleton = CalendarSkeleton . yMd . skeleton ( ) ; } formatSkeleton ( skeleton , datetime , buffer ) ; } }
Main entry point for date time formatting .
5,148
public void format ( ZonedDateTime start , ZonedDateTime end , DateTimeIntervalSkeleton skeleton , StringBuilder buffer ) { DateTimeField field = CalendarFormattingUtils . greatestDifference ( start , end ) ; if ( skeleton == null ) { switch ( field ) { case YEAR : case MONTH : case DAY : skeleton = DateTimeIntervalSkeleton . yMMMd ; break ; default : skeleton = DateTimeIntervalSkeleton . hmv ; break ; } } formatInterval ( start , end , skeleton . skeleton ( ) , field , buffer ) ; }
Format a date time interval guessing at the best skeleton to use based on the field of greatest difference between the start and end date - time . If the end date - time has a different time zone than the start this is corrected for comparison . If the skeleton is null one is selected automatically using the field of greatest difference .
5,149
public String resolveTimeZoneId ( String zoneId ) { String alias = _CalendarUtils . getTimeZoneAlias ( zoneId ) ; if ( alias != null ) { zoneId = alias ; } alias = TimeZoneAliases . getAlias ( zoneId ) ; if ( alias != null ) { zoneId = alias ; } return zoneId ; }
Check if the zoneId has an alias in the CLDR data .
5,150
public void formatField ( ZonedDateTime datetime , String pattern , StringBuilder buffer ) { int length = pattern . length ( ) ; if ( length == 0 ) { return ; } int i = 0 ; if ( pattern . charAt ( i ) == '+' ) { if ( length == 1 ) { return ; } i ++ ; } int width = 0 ; char field = pattern . charAt ( i ) ; while ( i < length ) { if ( pattern . charAt ( i ) != field ) { break ; } width ++ ; i ++ ; } formatField ( datetime , field , width , buffer ) ; }
Formats a single field based on the first character in the pattern string with repeated characters indicating the field width .
5,151
public void formatField ( ZonedDateTime datetime , char field , int width , StringBuilder buffer ) { switch ( field ) { case 'G' : formatEra ( buffer , datetime , width , eras ) ; break ; case 'y' : formatYear ( buffer , datetime , width ) ; break ; case 'Y' : formatISOYearWeekOfYear ( buffer , datetime , width ) ; break ; case 'u' : case 'U' : case 'r' : break ; case 'Q' : formatQuarter ( buffer , datetime , width , quartersFormat ) ; break ; case 'q' : formatQuarter ( buffer , datetime , width , quartersStandalone ) ; break ; case 'M' : formatMonth ( buffer , datetime , width , monthsFormat ) ; break ; case 'L' : formatMonth ( buffer , datetime , width , monthsStandalone ) ; break ; case 'l' : break ; case 'w' : formatISOWeekOfYear ( buffer , datetime , width ) ; break ; case 'W' : formatWeekOfMonth ( buffer , datetime , width ) ; break ; case 'd' : formatDayOfMonth ( buffer , datetime , width ) ; break ; case 'D' : formatDayOfYear ( buffer , datetime , width ) ; break ; case 'F' : formatDayOfWeekInMonth ( buffer , datetime , width ) ; break ; case 'g' : break ; case 'E' : formatWeekday ( buffer , datetime , width , weekdaysFormat ) ; break ; case 'e' : formatLocalWeekday ( buffer , datetime , width , weekdaysFormat , firstDay ) ; break ; case 'c' : formatLocalWeekdayStandalone ( buffer , datetime , width , weekdaysStandalone , firstDay ) ; break ; case 'a' : formatDayPeriod ( buffer , datetime , width , dayPeriodsFormat ) ; break ; case 'b' : break ; case 'B' : break ; case 'h' : formatHours ( buffer , datetime , width , true ) ; break ; case 'H' : formatHours ( buffer , datetime , width , false ) ; break ; case 'K' : formatHoursAlt ( buffer , datetime , width , true ) ; break ; case 'k' : formatHoursAlt ( buffer , datetime , width , false ) ; break ; case 'j' : case 'J' : case 'C' : break ; case 'm' : formatMinutes ( buffer , datetime , width ) ; break ; case 's' : formatSeconds ( buffer , datetime , width ) ; break ; case 'S' : formatFractionalSeconds ( buffer , datetime , width ) ; break ; case 'A' : break ; case 'z' : formatTimeZone_z ( buffer , datetime , width ) ; break ; case 'Z' : formatTimeZone_Z ( buffer , datetime , width ) ; break ; case 'O' : formatTimeZone_O ( buffer , datetime , width ) ; break ; case 'v' : formatTimeZone_v ( buffer , datetime , width ) ; break ; case 'V' : formatTimeZone_V ( buffer , datetime , width ) ; break ; case 'X' : case 'x' : formatTimeZone_X ( buffer , datetime , width , field ) ; break ; } }
Format a single field of a given width .
5,152
void formatEra ( StringBuilder b , ZonedDateTime d , int width , FieldVariants eras ) { int year = d . getYear ( ) ; int index = year < 0 ? 0 : 1 ; switch ( width ) { case 5 : b . append ( eras . narrow [ index ] ) ; break ; case 4 : b . append ( eras . wide [ index ] ) ; break ; case 3 : case 2 : case 1 : b . append ( eras . abbreviated [ index ] ) ; break ; } }
Format the era based on the year .
5,153
void formatYear ( StringBuilder b , ZonedDateTime d , int width ) { int year = d . getYear ( ) ; _formatYearValue ( b , year , width ) ; }
Format the numeric year zero padding as necessary .
5,154
void formatISOYearWeekOfYear ( StringBuilder b , ZonedDateTime d , int width ) { int year = d . get ( IsoFields . WEEK_BASED_YEAR ) ; _formatYearValue ( b , year , width ) ; }
Formats the year according to ISO week - year .
5,155
void formatQuarter ( StringBuilder b , ZonedDateTime d , int width , FieldVariants quarters ) { int quarter = ( d . getMonth ( ) . getValue ( ) - 1 ) / 3 ; switch ( width ) { case 5 : b . append ( quarters . narrow [ quarter ] ) ; break ; case 4 : b . append ( quarters . wide [ quarter ] ) ; break ; case 3 : b . append ( quarters . abbreviated [ quarter ] ) ; break ; case 2 : b . append ( '0' ) ; case 1 : b . append ( quarter + 1 ) ; break ; } }
Format the quarter based on the month .
5,156
void formatMonth ( StringBuilder b , ZonedDateTime d , int width , FieldVariants months ) { int month = d . getMonth ( ) . getValue ( ) ; switch ( width ) { case 5 : b . append ( months . narrow [ month - 1 ] ) ; break ; case 4 : b . append ( months . wide [ month - 1 ] ) ; break ; case 3 : b . append ( months . abbreviated [ month - 1 ] ) ; break ; case 2 : if ( month < 10 ) { b . append ( '0' ) ; } case 1 : b . append ( month ) ; break ; } }
Format the month numeric or a string name variant .
5,157
void formatWeekOfMonth ( StringBuilder b , ZonedDateTime d , int width ) { int w = d . get ( ChronoField . ALIGNED_WEEK_OF_MONTH ) ; if ( width == 1 ) { b . append ( w ) ; } }
Format the week number of the month .
5,158
void formatISOWeekOfYear ( StringBuilder b , ZonedDateTime d , int width ) { int w = d . get ( IsoFields . WEEK_OF_WEEK_BASED_YEAR ) ; switch ( width ) { case 2 : zeroPad2 ( b , w , 2 ) ; break ; case 1 : b . append ( w ) ; break ; } }
Format the week number of the year .
5,159
void formatWeekday ( StringBuilder b , ZonedDateTime d , int width , FieldVariants weekdays ) { int weekday = d . getDayOfWeek ( ) . getValue ( ) % 7 ; switch ( width ) { case 6 : b . append ( weekdays . short_ [ weekday ] ) ; break ; case 5 : b . append ( weekdays . narrow [ weekday ] ) ; break ; case 4 : b . append ( weekdays . wide [ weekday ] ) ; break ; case 3 : case 2 : case 1 : b . append ( weekdays . abbreviated [ weekday ] ) ; break ; } }
Format the weekday name .
5,160
void formatLocalWeekday ( StringBuilder b , ZonedDateTime d , int width , FieldVariants weekdays , int firstDay ) { if ( width > 2 ) { formatWeekday ( b , d , width , weekdays ) ; return ; } if ( width == 2 ) { b . append ( '0' ) ; } formatWeekdayNumeric ( b , d , firstDay ) ; }
Format the numeric weekday or the format name variant .
5,161
void formatLocalWeekdayStandalone ( StringBuilder b , ZonedDateTime d , int width , FieldVariants weekdays , int firstDay ) { if ( width > 2 ) { formatWeekday ( b , d , width , weekdays ) ; return ; } formatWeekdayNumeric ( b , d , firstDay ) ; }
Format the numeric weekday or the stand - alone name variant .
5,162
private void formatWeekdayNumeric ( StringBuilder b , ZonedDateTime d , int firstDay ) { int weekday = d . getDayOfWeek ( ) . getValue ( ) ; int w = ( 7 - firstDay + weekday ) % 7 + 1 ; b . append ( w ) ; }
Convert from Java s ISO - 8601 week number where Monday = 1 and Sunday = 7 . We need to adjust this according to the locale s first day of the week which in the US is Sunday = 0 .
5,163
void formatDayOfMonth ( StringBuilder b , ZonedDateTime d , int width ) { int day = d . getDayOfMonth ( ) ; zeroPad2 ( b , day , width ) ; }
Format the day of the month optionally zero - padded .
5,164
void formatDayOfYear ( StringBuilder b , ZonedDateTime d , int width ) { int day = d . getDayOfYear ( ) ; int digits = day < 10 ? 1 : day < 100 ? 2 : 3 ; switch ( digits ) { case 1 : if ( width > 1 ) { b . append ( '0' ) ; } case 2 : if ( width > 2 ) { b . append ( '0' ) ; } case 3 : b . append ( day ) ; break ; } }
Format the 3 - digit day of the year zero padded .
5,165
void formatDayOfWeekInMonth ( StringBuilder b , ZonedDateTime d , int width ) { int day = ( ( d . getDayOfMonth ( ) - 1 ) / 7 ) + 1 ; b . append ( day ) ; }
Numeric day of week in month as in 2nd Wednesday in July .
5,166
void formatDayPeriod ( StringBuilder b , ZonedDateTime d , int width , FieldVariants dayPeriods ) { int hours = d . getHour ( ) ; int index = hours < 12 ? 0 : 1 ; switch ( width ) { case 5 : b . append ( dayPeriods . narrow [ index ] ) ; break ; case 4 : b . append ( dayPeriods . wide [ index ] ) ; break ; case 3 : case 2 : case 1 : b . append ( dayPeriods . abbreviated [ index ] ) ; break ; } }
Format the day period variant .
5,167
void formatHours ( StringBuilder b , ZonedDateTime d , int width , boolean twelveHour ) { int hours = d . getHour ( ) ; if ( twelveHour && hours > 12 ) { hours = hours - 12 ; } if ( twelveHour && hours == 0 ) { hours = 12 ; } zeroPad2 ( b , hours , width ) ; }
Format the hours in 12 - or 24 - hour format optionally zero - padded .
5,168
void formatMinutes ( StringBuilder b , ZonedDateTime d , int width ) { zeroPad2 ( b , d . getMinute ( ) , width ) ; }
Format the minutes optionally zero - padded .
5,169
void formatSeconds ( StringBuilder b , ZonedDateTime d , int width ) { zeroPad2 ( b , d . getSecond ( ) , width ) ; }
Format the seconds optionally zero - padded .
5,170
void formatFractionalSeconds ( StringBuilder b , ZonedDateTime d , int width ) { int nano = d . getNano ( ) ; int f = 100000000 ; while ( width > 0 && f > 0 ) { int digit = nano / f ; nano -= ( digit * f ) ; f /= 10 ; b . append ( digit ) ; width -- ; } while ( width > 0 ) { b . append ( '0' ) ; width -- ; } }
Format fractional seconds up to N digits .
5,171
void formatTimeZone_O ( StringBuilder b , ZonedDateTime d , int width ) { int [ ] tz = getTzComponents ( d ) ; switch ( width ) { case 1 : wrapTimeZoneGMT ( b , tz [ TZNEG ] == - 1 , tz [ TZHOURS ] , tz [ TZMINS ] , true ) ; break ; case 4 : wrapTimeZoneGMT ( b , tz [ TZNEG ] == - 1 , tz [ TZHOURS ] , tz [ TZMINS ] , false ) ; break ; } }
Format timezone in localized GMT format for field O .
5,172
void formatTimeZone_z ( StringBuilder b , ZonedDateTime d , int width ) { if ( width > 4 ) { return ; } ZoneId zone = d . getZone ( ) ; ZoneRules zoneRules = null ; try { zoneRules = zone . getRules ( ) ; } catch ( ZoneRulesException e ) { return ; } boolean daylight = zoneRules . isDaylightSavings ( d . toInstant ( ) ) ; Name variants = getTimeZoneName ( zone . getId ( ) , d , width == 4 ) ; String name = variants == null ? null : ( daylight ? variants . daylight ( ) : variants . standard ( ) ) ; switch ( width ) { case 4 : { if ( name != null ) { b . append ( name ) ; } else { formatTimeZone_O ( b , d , 4 ) ; } break ; } case 3 : case 2 : case 1 : { if ( name != null ) { b . append ( name ) ; } else { formatTimeZone_O ( b , d , 1 ) ; } break ; } } }
Format a time zone using a non - location format .
5,173
private int [ ] getTzComponents ( ZonedDateTime d ) { ZoneOffset offset = d . getOffset ( ) ; int secs = offset . getTotalSeconds ( ) ; boolean negative = secs < 0 ; if ( negative ) { secs = - secs ; } int hours = secs / 3600 ; int mins = ( secs % 3600 ) / 60 ; return new int [ ] { negative ? - 1 : 1 , secs , hours , mins } ; }
Decode some fields about a time zone .
5,174
void zeroPad2 ( StringBuilder b , int value , int width ) { switch ( width ) { case 2 : if ( value < 10 ) { b . append ( '0' ) ; } case 1 : b . append ( value ) ; break ; } }
Format 2 - digit number with 0 - padding .
5,175
private static void decimal ( CLDR . Locale locale , String [ ] numbers , DecimalFormatOptions opts ) { for ( String num : numbers ) { BigDecimal n = new BigDecimal ( num ) ; StringBuilder buf = new StringBuilder ( " " ) ; NumberFormatter fmt = CLDR . get ( ) . getNumberFormatter ( locale ) ; fmt . formatDecimal ( n , buf , opts ) ; System . out . println ( buf . toString ( ) ) ; } }
Format decimal numbers in this locale .
5,176
private static void money ( CLDR . Locale locale , CLDR . Currency [ ] currencies , String [ ] numbers , CurrencyFormatOptions opts ) { for ( CLDR . Currency currency : currencies ) { System . out . println ( "Currency " + currency ) ; for ( String num : numbers ) { BigDecimal n = new BigDecimal ( num ) ; NumberFormatter fmt = CLDR . get ( ) . getNumberFormatter ( locale ) ; StringBuilder buf = new StringBuilder ( " " ) ; fmt . formatCurrency ( n , currency , buf , opts ) ; System . out . println ( buf . toString ( ) ) ; } System . out . println ( ) ; } System . out . println ( ) ; }
Format numbers in this locale for several currencies .
5,177
public List < UnitValue > getFactors ( Unit base , RoundingMode mode , Unit ... units ) { List < UnitValue > result = new ArrayList < > ( ) ; for ( int i = 0 ; i < units . length ; i ++ ) { UnitFactor factor = resolve ( units [ i ] , base ) ; if ( factor != null ) { BigDecimal n = factor . rational ( ) . compute ( mode ) ; result . add ( new UnitValue ( n , units [ i ] ) ) ; } } return result ; }
Return an array of factors to convert the array of units to the given base .
5,178
protected UnitFactorMap add ( Unit unit , String n , Unit base ) { check ( unit ) ; check ( base ) ; if ( unit == base ) { throw new IllegalArgumentException ( "Attempt to define a unit " + unit + " in terms of itself." ) ; } Rational rational = new Rational ( n ) ; set ( unit , rational , base , true ) ; return this ; }
Set a factor to convert the unit into a given base .
5,179
protected UnitFactorMap complete ( ) { Set < Unit > units = new LinkedHashSet < > ( ) ; for ( Unit from : factors . keySet ( ) ) { units . add ( from ) ; for ( Map . Entry < Unit , UnitFactor > entry : factors . get ( from ) . entrySet ( ) ) { Unit to = entry . getKey ( ) ; units . add ( to ) ; UnitFactor factor = entry . getValue ( ) ; set ( to , factor . rational ( ) . reciprocal ( ) , from , false ) ; } } for ( Unit from : units ) { for ( Unit to : units ) { if ( from == to ) { continue ; } UnitFactor factor = get ( from , to ) ; if ( factor != null ) { continue ; } Map < Unit , UnitFactor > map = factors . get ( from ) ; if ( map == null ) { map = new EnumMap < > ( Unit . class ) ; factors . put ( from , map ) ; } factor = resolve ( from , to ) ; UnitFactor old = map . get ( from ) ; Rational rational = factor . rational ( ) ; if ( old == null || totalPrecision ( rational ) < totalPrecision ( old . rational ( ) ) ) { set ( from , rational , to , true ) ; } } } List < Unit > unitList = new ArrayList < > ( Unit . forCategory ( category ) ) ; unitList . sort ( ( a , b ) -> { UnitFactor f = get ( a , b ) ; if ( f == null ) { return - 1 ; } BigDecimal r = f . rational ( ) . compute ( RoundingMode . HALF_EVEN ) ; return BigDecimal . ONE . compareTo ( r ) ; } ) ; for ( int i = 0 ; i < unitList . size ( ) ; i ++ ) { unitOrder . put ( unitList . get ( i ) , i ) ; } return this ; }
Creates direct conversion factors between all units by resolving the best conversion path and setting an explicit mapping if one does not already exist .
5,180
protected UnitFactor resolve ( Unit from , Unit to ) { if ( from == to ) { return new UnitFactor ( Rational . ONE , to ) ; } List < UnitFactor > path = getPath ( from , to ) ; if ( path . isEmpty ( ) ) { throw new IllegalStateException ( "Can't find a path to convert " + from + " units into " + to ) ; } UnitFactor factor = path . get ( 0 ) ; int size = path . size ( ) ; for ( int i = 1 ; i < size ; i ++ ) { factor = factor . multiply ( path . get ( i ) ) ; } return factor ; }
Find the best conversion factor path between the FROM and TO units multiply them together and return the resulting factor .
5,181
private int precisionSum ( List < UnitFactor > factors ) { return factors . stream ( ) . map ( f -> totalPrecision ( f . rational ( ) ) ) . reduce ( 0 , Math :: addExact ) ; }
Reduces the list of factors by adding together the precision for all numerators and denominators .
5,182
public UnitFactor get ( Unit from , Unit to ) { Map < Unit , UnitFactor > map = factors . get ( from ) ; if ( map != null ) { UnitFactor factor = map . get ( to ) ; if ( factor != null ) { return factor ; } } return null ; }
Find an exact conversion factor between the from and to units or return null if none exists .
5,183
public String dump ( Unit unit ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( unit ) . append ( ":\n" ) ; Map < Unit , UnitFactor > map = factors . get ( unit ) ; for ( Unit base : map . keySet ( ) ) { UnitFactor factor = map . get ( base ) ; buf . append ( " " ) . append ( factor ) . append ( " " ) ; buf . append ( factor . rational ( ) . compute ( RoundingMode . HALF_EVEN ) . toPlainString ( ) ) . append ( '\n' ) ; } return buf . toString ( ) ; }
Debugging conversion factors .
5,184
private void set ( Unit unit , Rational rational , Unit base , boolean replace ) { Map < Unit , UnitFactor > map = factors . get ( unit ) ; if ( map == null ) { map = new EnumMap < > ( Unit . class ) ; factors . put ( unit , map ) ; } if ( replace || ! map . containsKey ( base ) ) { map . put ( base , new UnitFactor ( rational , base ) ) ; } }
Set a conversion factor that converts UNIT to BASE . If the replace flag is true we always overwrite the mapping .
5,185
private List < UnitFactor > list ( UnitFactor factor ) { List < UnitFactor > list = new ArrayList < > ( ) ; list . add ( factor ) ; return list ; }
Construct a list containing just this factor .
5,186
private List < Unit > getBases ( Unit unit ) { Map < Unit , UnitFactor > map = factors . get ( unit ) ; if ( map != null ) { return map . values ( ) . stream ( ) . map ( u -> u . unit ( ) ) . collect ( Collectors . toList ( ) ) ; } return Collections . emptyList ( ) ; }
Fetch all of the existing bases for the given unit . A base is a conversion factor that was directly added or the inverse of one that was directly added .
5,187
private static int hash ( String k1 , String k2 ) { int h = ( k1 . hashCode ( ) * 33 ) + k2 . hashCode ( ) ; return h ^ ( h >>> 16 ) ; }
Combine the hash codes for the two keys then mix .
5,188
public void setPattern ( NumberPattern pattern , int _maxSigDigits , int _minSigDigits ) { Format format = pattern . format ( ) ; minIntDigits = orDefault ( options . minimumIntegerDigits ( ) , format . minimumIntegerDigits ( ) ) ; maxFracDigits = currencyDigits == - 1 ? format . maximumFractionDigits ( ) : currencyDigits ; maxFracDigits = orDefault ( options . maximumFractionDigits ( ) , maxFracDigits ) ; minFracDigits = currencyDigits == - 1 ? format . minimumFractionDigits ( ) : currencyDigits ; minFracDigits = orDefault ( options . minimumFractionDigits ( ) , minFracDigits ) ; boolean useSignificant = formatMode == SIGNIFICANT || formatMode == SIGNIFICANT_MAXFRAC ; if ( useSignificant ) { maxSigDigits = orDefault ( options . maximumSignificantDigits ( ) , _maxSigDigits ) ; minSigDigits = orDefault ( options . minimumSignificantDigits ( ) , _minSigDigits ) ; } else { maxSigDigits = - 1 ; minSigDigits = - 1 ; } }
Set the pattern and initialize parameters based on the arguments pattern and options settings .
5,189
public BigDecimal adjust ( BigDecimal n ) { return NumberFormattingUtils . setup ( n , options . roundMode ( ) , formatMode , minIntDigits , maxFracDigits , minFracDigits , maxSigDigits , minSigDigits ) ; }
Adjust the number using all of the options .
5,190
public Pair < List < Node > , List < Node > > splitIntervalPattern ( String raw ) { List < Node > pattern = parse ( raw ) ; Set < Character > seen = new HashSet < > ( ) ; List < Node > fst = new ArrayList < > ( ) ; List < Node > snd = new ArrayList < > ( ) ; boolean boundary = false ; for ( Node node : pattern ) { if ( node instanceof Field ) { char ch = ( ( Field ) node ) . ch ( ) ; if ( seen . contains ( ch ) ) { boundary = true ; } else { seen . add ( ch ) ; } } if ( boundary ) { snd . add ( node ) ; } else { fst . add ( node ) ; } } return Pair . pair ( fst , snd ) ; }
Looks for the first repeated field in the pattern splitting it into two parts on that boundary .
5,191
public static String render ( List < Node > nodes ) { StringBuilder buf = new StringBuilder ( ) ; for ( Node node : nodes ) { if ( node instanceof Text ) { String text = ( ( Text ) node ) . text ; boolean inquote = false ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char ch = text . charAt ( i ) ; switch ( ch ) { case 'G' : case 'y' : case 'Y' : case 'u' : case 'U' : case 'r' : case 'Q' : case 'q' : case 'M' : case 'L' : case 'l' : case 'w' : case 'W' : case 'd' : case 'D' : case 'F' : case 'g' : case 'E' : case 'e' : case 'c' : case 'a' : case 'b' : case 'B' : case 'h' : case 'H' : case 'K' : case 'k' : case 'j' : case 'J' : case 'C' : case 'm' : case 's' : case 'S' : case 'A' : case 'z' : case 'Z' : case 'O' : case 'v' : case 'V' : case 'X' : case 'x' : if ( ! inquote ) { buf . append ( '\'' ) ; } buf . append ( ch ) ; break ; default : if ( inquote ) { buf . append ( '\'' ) ; } buf . append ( ch ) ; break ; } } } else if ( node instanceof Field ) { Field field = ( Field ) node ; for ( int i = 0 ; i < field . width ; i ++ ) { buf . append ( field . ch ) ; } } } return buf . toString ( ) ; }
Render the compiled pattern back into string form .
5,192
public List < Node > parse ( String raw ) { StringBuilder buf = new StringBuilder ( ) ; char field = '\0' ; int width = 0 ; boolean inquote = false ; int length = raw . length ( ) ; int i = 0 ; List < Node > nodes = new ArrayList < > ( ) ; while ( i < length ) { char ch = raw . charAt ( i ) ; if ( inquote ) { if ( ch == '\'' ) { inquote = false ; field = '\0' ; } else { buf . append ( ch ) ; } i ++ ; continue ; } switch ( ch ) { case 'G' : case 'y' : case 'Y' : case 'u' : case 'U' : case 'r' : case 'Q' : case 'q' : case 'M' : case 'L' : case 'l' : case 'w' : case 'W' : case 'd' : case 'D' : case 'F' : case 'g' : case 'E' : case 'e' : case 'c' : case 'a' : case 'b' : case 'B' : case 'h' : case 'H' : case 'K' : case 'k' : case 'j' : case 'J' : case 'C' : case 'm' : case 's' : case 'S' : case 'A' : case 'z' : case 'Z' : case 'O' : case 'v' : case 'V' : case 'X' : case 'x' : if ( buf . length ( ) > 0 ) { nodes . add ( new Text ( buf . toString ( ) ) ) ; buf . setLength ( 0 ) ; } if ( ch != field ) { if ( field != '\0' ) { nodes . add ( new Field ( field , width ) ) ; } field = ch ; width = 1 ; } else { width ++ ; } break ; default : if ( field != '\0' ) { nodes . add ( new Field ( field , width ) ) ; } field = '\0' ; if ( ch == '\'' ) { inquote = true ; } else { buf . append ( ch ) ; } break ; } i ++ ; } if ( width > 0 && field != '\0' ) { nodes . add ( new Field ( field , width ) ) ; } else if ( buf . length ( ) > 0 ) { nodes . add ( new Text ( buf . toString ( ) ) ) ; } return nodes ; }
Parses a CLDR date - time pattern into a series of Text and Field nodes .
5,193
public static void generate ( Path outputDir ) throws IOException { DataReader reader = DataReader . get ( ) ; CalendarCodeGenerator datetimeGenerator = new CalendarCodeGenerator ( ) ; Map < LocaleID , ClassName > dateClasses = datetimeGenerator . generate ( outputDir , reader ) ; PluralCodeGenerator pluralGenerator = new PluralCodeGenerator ( ) ; pluralGenerator . generate ( outputDir , reader ) ; NumberCodeGenerator numberGenerator = new NumberCodeGenerator ( ) ; Map < LocaleID , ClassName > numberClasses = numberGenerator . generate ( outputDir , reader ) ; LanguageCodeGenerator languageGenerator = new LanguageCodeGenerator ( ) ; languageGenerator . generate ( outputDir , reader ) ; MethodSpec registerCalendars = indexFormatters ( "registerCalendars" , "registerCalendarFormatter" , dateClasses ) ; MethodSpec registerNumbers = indexFormatters ( "registerNumbers" , "registerNumberFormatter" , numberClasses ) ; MethodSpec constructor = MethodSpec . constructorBuilder ( ) . addModifiers ( PRIVATE ) . build ( ) ; FieldSpec instance = FieldSpec . builder ( CLDR , "instance" , PRIVATE , STATIC , FINAL ) . build ( ) ; MethodSpec getter = MethodSpec . methodBuilder ( "get" ) . addModifiers ( PUBLIC , STATIC ) . returns ( CLDR ) . addStatement ( "return instance" ) . build ( ) ; TypeSpec . Builder type = TypeSpec . classBuilder ( "CLDR" ) . addModifiers ( PUBLIC ) . superclass ( CLDR_BASE ) . addMethod ( constructor ) . addMethod ( getter ) . addMethod ( registerCalendars ) . addMethod ( registerNumbers ) ; Set < LocaleID > availableLocales = reader . availableLocales ( ) . stream ( ) . map ( s -> LocaleID . parse ( s ) ) . collect ( Collectors . toSet ( ) ) ; createLocales ( type , reader . defaultContent ( ) , availableLocales ) ; createLanguageAliases ( type , reader . languageAliases ( ) ) ; createTerritoryAliases ( type , reader . territoryAliases ( ) ) ; createLikelySubtags ( type , reader . likelySubtags ( ) ) ; createCurrencies ( type , numberGenerator . getCurrencies ( reader ) ) ; addPluralRules ( type ) ; type . addStaticBlock ( CodeBlock . builder ( ) . addStatement ( "registerCalendars()" ) . addStatement ( "registerNumbers()" ) . addStatement ( "registerDefaultContent()" ) . addStatement ( "registerLanguageAliases()" ) . addStatement ( "registerTerritoryAliases()" ) . addStatement ( "registerLikelySubtags()" ) . addStatement ( "instance = new CLDR()" ) . build ( ) ) ; type . addField ( instance ) ; saveClass ( outputDir , PACKAGE_CLDR , "CLDR" , type . build ( ) ) ; }
Loads all CLDR data and invokes the code generators for each data type . Output is a series of Java classes under the outputDir .
5,194
public static void saveClass ( Path rootDir , String packageName , String className , TypeSpec type ) throws IOException { List < String > packagePath = Splitter . on ( '.' ) . splitToList ( packageName ) ; Path classPath = Paths . get ( rootDir . toString ( ) , packagePath . toArray ( EMPTY ) ) ; Path outputFile = classPath . resolve ( className + ".java" ) ; JavaFile javaFile = JavaFile . builder ( packageName , type ) . addFileComment ( "\n\nAUTO-GENERATED CLASS - DO NOT EDIT\n\n" ) . build ( ) ; System . out . println ( "saving " + outputFile ) ; Files . createParentDirs ( outputFile . toFile ( ) ) ; CharSink sink = Files . asCharSink ( outputFile . toFile ( ) , Charsets . UTF_8 ) ; sink . write ( javaFile . toString ( ) ) ; }
Saves a Java class file to a path for the given package rooted in rootDir .
5,195
private static void addPluralRules ( TypeSpec . Builder type ) { FieldSpec field = FieldSpec . builder ( PLURAL_RULES , "pluralRules" , PRIVATE , STATIC , FINAL ) . initializer ( "new $T()" , PLURAL_RULES ) . build ( ) ; MethodSpec method = MethodSpec . methodBuilder ( "getPluralRules" ) . addModifiers ( PUBLIC ) . returns ( PLURAL_RULES ) . addStatement ( "return pluralRules" ) . build ( ) ; type . addField ( field ) ; type . addMethod ( method ) ; }
Add static instance of plural rules and accessor method .
5,196
private static MethodSpec indexFormatters ( String methodName , String registerMethodName , Map < LocaleID , ClassName > dateClasses ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( methodName ) . addModifiers ( PRIVATE , STATIC ) ; for ( Map . Entry < LocaleID , ClassName > entry : dateClasses . entrySet ( ) ) { LocaleID localeId = entry . getKey ( ) ; ClassName className = entry . getValue ( ) ; method . addStatement ( "$T.$L(Locale.$L, $L.class)" , CLDR_BASE , registerMethodName , localeId . safe , className ) ; } return method . build ( ) ; }
Generates a static code block that populates the formatter map .
5,197
private static void addLocaleField ( TypeSpec . Builder type , String name , LocaleID locale ) { FieldSpec . Builder field = FieldSpec . builder ( CLDR_LOCALE_IF , name , PUBLIC , STATIC , FINAL ) . initializer ( "new $T($S, $S, $S, $S)" , META_LOCALE , strOrNull ( locale . language ) , strOrNull ( locale . script ) , strOrNull ( locale . territory ) , strOrNull ( locale . variant ) ) ; type . addField ( field . build ( ) ) ; }
Create a public locale field .
5,198
private static void createLanguageAliases ( TypeSpec . Builder type , Map < String , String > languageAliases ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "registerLanguageAliases" ) . addModifiers ( PRIVATE , STATIC ) ; for ( Map . Entry < String , String > entry : languageAliases . entrySet ( ) ) { method . addStatement ( "addLanguageAlias($S, $S)" , entry . getKey ( ) , entry . getValue ( ) ) ; } type . addMethod ( method . build ( ) ) ; }
Create language alias mapping .
5,199
private static void createLikelySubtags ( TypeSpec . Builder type , Map < String , String > likelySubtags ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "registerLikelySubtags" ) . addModifiers ( PRIVATE , STATIC ) ; for ( Map . Entry < String , String > entry : likelySubtags . entrySet ( ) ) { method . addStatement ( "LIKELY_SUBTAGS_MAP.put($T.parse($S), $T.parse($S))" , META_LOCALE , entry . getKey ( ) , META_LOCALE , entry . getValue ( ) ) ; } type . addMethod ( method . build ( ) ) ; }
Create likely subtags mapping .