idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
32,600
public void replace ( final int pos , final double latitude , final double longitude ) { this . longitude [ pos ] = longitude ; this . latitude [ pos ] = latitude ; }
Replace the position at the index with new values
32,601
public void remove ( final int pos ) { System . arraycopy ( longitude , pos + 1 , longitude , pos , size - pos - 1 ) ; System . arraycopy ( latitude , pos + 1 , latitude , pos , size - pos - 1 ) ; -- size ; }
Remove the position at the index the rest of the list is shifted one place to the left
32,602
private String findBaseURI ( final Element root ) throws MalformedURLException { String ret = null ; if ( findAtomLink ( root , "self" ) != null ) { ret = findAtomLink ( root , "self" ) ; if ( "." . equals ( ret ) || "./" . equals ( ret ) ) { ret = "" ; } if ( ret . indexOf ( "/" ) != - 1 ) { ret = ret . substring ( 0 , ret . lastIndexOf ( "/" ) ) ; } ret = resolveURI ( null , root , ret ) ; } return ret ; }
Find base URI of feed considering relative URIs .
32,603
private String findAtomLink ( final Element parent , final String rel ) { String ret = null ; final List < Element > linksList = parent . getChildren ( "link" , ATOM_10_NS ) ; if ( linksList != null ) { for ( final Element element : linksList ) { final Element link = element ; final Attribute relAtt = getAttribute ( link , "rel" ) ; final Attribute hrefAtt = getAttribute ( link , "href" ) ; if ( relAtt == null && "alternate" . equals ( rel ) || relAtt != null && relAtt . getValue ( ) . equals ( rel ) ) { ret = hrefAtt . getValue ( ) ; break ; } } } return ret ; }
Return URL string of Atom link element under parent element . Link with no rel attribute is considered to be rel = alternate
32,604
private static String formURI ( String base , String append ) { base = stripTrailingSlash ( base ) ; append = stripStartingSlash ( append ) ; if ( append . startsWith ( ".." ) ) { final String [ ] parts = append . split ( "/" ) ; for ( final String part : parts ) { if ( ".." . equals ( part ) ) { final int last = base . lastIndexOf ( "/" ) ; if ( last != - 1 ) { base = base . substring ( 0 , last ) ; append = append . substring ( 3 , append . length ( ) ) ; } else { break ; } } } } return base + "/" + append ; }
Form URI by combining base with append portion and giving special consideration to append portions that begin with ..
32,605
private static String stripStartingSlash ( String s ) { if ( s != null && s . startsWith ( "/" ) ) { s = s . substring ( 1 , s . length ( ) ) ; } return s ; }
Strip starting slash from beginning of string .
32,606
private static String stripTrailingSlash ( String s ) { if ( s != null && s . endsWith ( "/" ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) ; } return s ; }
Strip trailing slash from end of string .
32,607
public static Entry parseEntry ( final Reader rd , final String baseURI , final Locale locale ) throws JDOMException , IOException , IllegalArgumentException , FeedException { final SAXBuilder builder = new SAXBuilder ( ) ; final Document entryDoc = builder . build ( rd ) ; final Element fetchedEntryElement = entryDoc . getRootElement ( ) ; fetchedEntryElement . detach ( ) ; final Feed feed = new Feed ( ) ; feed . setFeedType ( "atom_1.0" ) ; final WireFeedOutput wireFeedOutput = new WireFeedOutput ( ) ; final Document feedDoc = wireFeedOutput . outputJDom ( feed ) ; feedDoc . getRootElement ( ) . addContent ( fetchedEntryElement ) ; if ( baseURI != null ) { feedDoc . getRootElement ( ) . setAttribute ( "base" , baseURI , Namespace . XML_NAMESPACE ) ; } final WireFeedInput input = new WireFeedInput ( false , locale ) ; final Feed parsedFeed = ( Feed ) input . build ( feedDoc ) ; return parsedFeed . getEntries ( ) . get ( 0 ) ; }
Parse entry from reader .
32,608
public Feed getFeedDocument ( ) throws AtomException { InputStream in = null ; synchronized ( FileStore . getFileStore ( ) ) { in = FileStore . getFileStore ( ) . getFileInputStream ( getFeedPath ( ) ) ; if ( in == null ) { in = createDefaultFeedDocument ( contextURI + servletPath + "/" + handle + "/" + collection ) ; } } try { final WireFeedInput input = new WireFeedInput ( ) ; final WireFeed wireFeed = input . build ( new InputStreamReader ( in , "UTF-8" ) ) ; return ( Feed ) wireFeed ; } catch ( final Exception ex ) { throw new AtomException ( ex ) ; } }
Get feed document representing collection .
32,609
public List < Categories > getCategories ( final boolean inline ) { final Categories cats = new Categories ( ) ; cats . setFixed ( true ) ; cats . setScheme ( contextURI + "/" + handle + "/" + singular ) ; if ( inline ) { for ( final String catName : catNames ) { final Category cat = new Category ( ) ; cat . setTerm ( catName ) ; cats . addCategory ( cat ) ; } } else { cats . setHref ( getCategoriesURI ( ) ) ; } return Collections . singletonList ( cats ) ; }
Get list of one Categories object containing categories allowed by collection .
32,610
public Entry addEntry ( final Entry entry ) throws Exception { synchronized ( FileStore . getFileStore ( ) ) { final Feed f = getFeedDocument ( ) ; final String fsid = FileStore . getFileStore ( ) . getNextId ( ) ; updateTimestamps ( entry ) ; final String entryPath = getEntryPath ( fsid ) ; final OutputStream os = FileStore . getFileStore ( ) . getFileOutputStream ( entryPath ) ; updateEntryAppLinks ( entry , fsid , true ) ; Atom10Generator . serializeEntry ( entry , new OutputStreamWriter ( os , "UTF-8" ) ) ; os . flush ( ) ; os . close ( ) ; updateEntryAppLinks ( entry , fsid , false ) ; updateFeedDocumentWithNewEntry ( f , entry ) ; return entry ; } }
Add entry to collection .
32,611
public Entry getEntry ( String fsid ) throws Exception { if ( fsid . endsWith ( ".media-link" ) ) { fsid = fsid . substring ( 0 , fsid . length ( ) - ".media-link" . length ( ) ) ; } final String entryPath = getEntryPath ( fsid ) ; checkExistence ( entryPath ) ; final InputStream in = FileStore . getFileStore ( ) . getFileInputStream ( entryPath ) ; final Entry entry ; final File resource = new File ( fsid ) ; if ( resource . exists ( ) ) { entry = loadAtomResourceEntry ( in , resource ) ; updateMediaEntryAppLinks ( entry , fsid , true ) ; } else { entry = loadAtomEntry ( in ) ; updateEntryAppLinks ( entry , fsid , true ) ; } return entry ; }
Get an entry from the collection .
32,612
public AtomMediaResource getMediaResource ( final String fileName ) throws Exception { final String filePath = getEntryMediaPath ( fileName ) ; final File resource = new File ( filePath ) ; return new AtomMediaResource ( resource ) ; }
Get media resource wrapping a file .
32,613
public void updateEntry ( final Entry entry , String fsid ) throws Exception { synchronized ( FileStore . getFileStore ( ) ) { final Feed f = getFeedDocument ( ) ; if ( fsid . endsWith ( ".media-link" ) ) { fsid = fsid . substring ( 0 , fsid . length ( ) - ".media-link" . length ( ) ) ; } updateTimestamps ( entry ) ; updateEntryAppLinks ( entry , fsid , false ) ; updateFeedDocumentWithExistingEntry ( f , entry ) ; final String entryPath = getEntryPath ( fsid ) ; final OutputStream os = FileStore . getFileStore ( ) . getFileOutputStream ( entryPath ) ; updateEntryAppLinks ( entry , fsid , true ) ; Atom10Generator . serializeEntry ( entry , new OutputStreamWriter ( os , "UTF-8" ) ) ; os . flush ( ) ; os . close ( ) ; } }
Update an entry in the collection .
32,614
public Entry updateMediaEntry ( final String fileName , final String contentType , final InputStream is ) throws Exception { synchronized ( FileStore . getFileStore ( ) ) { final File tempFile = File . createTempFile ( fileName , "tmp" ) ; final FileOutputStream fos = new FileOutputStream ( tempFile ) ; Utilities . copyInputToOutput ( is , fos ) ; fos . close ( ) ; final FileInputStream fis = new FileInputStream ( tempFile ) ; saveMediaFile ( fileName , contentType , tempFile . length ( ) , fis ) ; fis . close ( ) ; final File resourceFile = new File ( getEntryMediaPath ( fileName ) ) ; final String entryPath = getEntryPath ( fileName ) ; final InputStream in = FileStore . getFileStore ( ) . getFileInputStream ( entryPath ) ; final Entry atomEntry = loadAtomResourceEntry ( in , resourceFile ) ; updateTimestamps ( atomEntry ) ; updateMediaEntryAppLinks ( atomEntry , fileName , false ) ; final Feed f = getFeedDocument ( ) ; updateFeedDocumentWithExistingEntry ( f , atomEntry ) ; final OutputStream os = FileStore . getFileStore ( ) . getFileOutputStream ( entryPath ) ; updateMediaEntryAppLinks ( atomEntry , fileName , true ) ; Atom10Generator . serializeEntry ( atomEntry , new OutputStreamWriter ( os , "UTF-8" ) ) ; os . flush ( ) ; os . close ( ) ; return atomEntry ; } }
Update media associated with a media - link entry .
32,615
public void deleteEntry ( final String fsid ) throws Exception { synchronized ( FileStore . getFileStore ( ) ) { final Feed feed = getFeedDocument ( ) ; updateFeedDocumentRemovingEntry ( feed , fsid ) ; final String entryFilePath = getEntryPath ( fsid ) ; FileStore . getFileStore ( ) . deleteFile ( entryFilePath ) ; final String entryMediaPath = getEntryMediaPath ( fsid ) ; if ( entryMediaPath != null ) { FileStore . getFileStore ( ) . deleteFile ( entryMediaPath ) ; } final String entryDirPath = getEntryDirPath ( fsid ) ; FileStore . getFileStore ( ) . deleteDirectory ( entryDirPath ) ; try { Thread . sleep ( 500L ) ; } catch ( final Exception ignored ) { } } }
Delete an entry and any associated media file .
32,616
private Entry loadAtomEntry ( final InputStream in ) { try { return Atom10Parser . parseEntry ( new BufferedReader ( new InputStreamReader ( in , "UTF-8" ) ) , null , Locale . US ) ; } catch ( final Exception e ) { e . printStackTrace ( ) ; return null ; } }
Create a Rome Atom entry based on a Roller entry . Content is escaped . Link is stored as rel = alternate link .
32,617
private void saveMediaFile ( final String name , final String contentType , final long size , final InputStream is ) throws AtomException { final byte [ ] buffer = new byte [ 8192 ] ; int bytesRead = 0 ; final File dirPath = new File ( getEntryMediaPath ( name ) ) ; if ( ! dirPath . getParentFile ( ) . exists ( ) ) { dirPath . getParentFile ( ) . mkdirs ( ) ; } OutputStream bos = null ; try { bos = new FileOutputStream ( dirPath . getAbsolutePath ( ) ) ; while ( ( bytesRead = is . read ( buffer , 0 , 8192 ) ) != - 1 ) { bos . write ( buffer , 0 , bytesRead ) ; } } catch ( final Exception e ) { throw new AtomException ( "ERROR uploading file" , e ) ; } finally { try { bos . flush ( ) ; bos . close ( ) ; } catch ( final Exception ignored ) { } } }
Save file to website s resource directory .
32,618
private String createFileName ( final String title , final String contentType ) { if ( handle == null ) { throw new IllegalArgumentException ( "weblog handle cannot be null" ) ; } if ( contentType == null ) { throw new IllegalArgumentException ( "contentType cannot be null" ) ; } String fileName = null ; final SimpleDateFormat sdf = new SimpleDateFormat ( ) ; sdf . applyPattern ( "yyyyMMddHHssSSS" ) ; final String [ ] typeTokens = contentType . split ( "/" ) ; final String ext = typeTokens [ 1 ] ; if ( title != null && ! title . trim ( ) . equals ( "" ) ) { final String base = Utilities . replaceNonAlphanumeric ( title , ' ' ) ; final StringTokenizer toker = new StringTokenizer ( base ) ; String tmp = null ; int count = 0 ; while ( toker . hasMoreTokens ( ) && count < 5 ) { String s = toker . nextToken ( ) ; s = s . toLowerCase ( ) ; tmp = tmp == null ? s : tmp + "_" + s ; count ++ ; } fileName = tmp + "-" + sdf . format ( new Date ( ) ) + "." + ext ; } else { fileName = handle + "-" + sdf . format ( new Date ( ) ) + "." + ext ; } return fileName ; }
Creates a file name for a file based on a weblog handle title string and a content - type .
32,619
public static < T > T firstNotNull ( final T ... objects ) { for ( final T object : objects ) { if ( object != null ) { return object ; } } return null ; }
Returns the first object that is not null
32,620
private void loadPlugins ( ) { final List < T > finalPluginsList = new ArrayList < T > ( ) ; pluginsList = new ArrayList < T > ( ) ; pluginsMap = new HashMap < String , T > ( ) ; String className = null ; try { final Class < T > [ ] classes = getClasses ( ) ; for ( final Class < T > clazz : classes ) { className = clazz . getName ( ) ; final T plugin = clazz . newInstance ( ) ; if ( plugin instanceof DelegatingModuleParser ) { ( ( DelegatingModuleParser ) plugin ) . setFeedParser ( parentParser ) ; } if ( plugin instanceof DelegatingModuleGenerator ) { ( ( DelegatingModuleGenerator ) plugin ) . setFeedGenerator ( parentGenerator ) ; } pluginsMap . put ( getKey ( plugin ) , plugin ) ; pluginsList . add ( plugin ) ; } final Collection < T > plugins = pluginsMap . values ( ) ; for ( final T plugin : plugins ) { finalPluginsList . add ( plugin ) ; } final Iterator < T > iterator = pluginsList . iterator ( ) ; while ( iterator . hasNext ( ) ) { final T plugin = iterator . next ( ) ; if ( ! finalPluginsList . contains ( plugin ) ) { iterator . remove ( ) ; } } } catch ( final Exception ex ) { throw new RuntimeException ( "could not instantiate plugin " + className , ex ) ; } catch ( final ExceptionInInitializerError er ) { throw new RuntimeException ( "could not instantiate plugin " + className , er ) ; } }
PRIVATE - LOADER PART
32,621
public static String toLowerCase ( final String s ) { if ( s == null ) { return null ; } else { return s . toLowerCase ( Locale . ENGLISH ) ; } }
null - safe lower - case conversion of a String .
32,622
public static String streamToString ( final InputStream is ) throws IOException { final StringBuffer sb = new StringBuffer ( ) ; final BufferedReader in = new BufferedReader ( new InputStreamReader ( is ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { sb . append ( line ) ; sb . append ( LS ) ; } return sb . toString ( ) ; }
Read input from stream and into string .
32,623
public static void copyInputToOutput ( final InputStream input , final OutputStream output ) throws IOException { final BufferedInputStream in = new BufferedInputStream ( input ) ; final BufferedOutputStream out = new BufferedOutputStream ( output ) ; final byte buffer [ ] = new byte [ 8192 ] ; for ( int count = 0 ; count != - 1 ; ) { count = in . read ( buffer , 0 , 8192 ) ; if ( count != - 1 ) { out . write ( buffer , 0 , count ) ; } } try { in . close ( ) ; out . close ( ) ; } catch ( final IOException ex ) { throw new IOException ( "Closing file streams, " + ex . getMessage ( ) ) ; } }
Copy input stream to output stream using 8K buffer .
32,624
public static String replaceNonAlphanumeric ( final String str , final char subst ) { final StringBuffer ret = new StringBuffer ( str . length ( ) ) ; final char [ ] testChars = str . toCharArray ( ) ; for ( final char testChar : testChars ) { if ( Character . isLetterOrDigit ( testChar ) ) { ret . append ( testChar ) ; } else { ret . append ( subst ) ; } } return ret . toString ( ) ; }
Replaces occurences of non - alphanumeric characters with a supplied char .
32,625
public static String [ ] stringToStringArray ( final String instr , final String delim ) throws NoSuchElementException , NumberFormatException { final StringTokenizer toker = new StringTokenizer ( instr , delim ) ; final String stringArray [ ] = new String [ toker . countTokens ( ) ] ; int i = 0 ; while ( toker . hasMoreTokens ( ) ) { stringArray [ i ++ ] = toker . nextToken ( ) ; } return stringArray ; }
Convert string to string array .
32,626
public static String stringArrayToString ( final String [ ] stringArray , final String delim ) { String ret = "" ; for ( final String element : stringArray ) { if ( ret . length ( ) > 0 ) { ret = ret + delim + element ; } else { ret = element ; } } return ret ; }
Convert string array to string .
32,627
public static Integer parse ( final String s ) { try { return Integer . parseInt ( s ) ; } catch ( final NumberFormatException e ) { return null ; } }
Converts a String into an Integer .
32,628
public void addUpdate ( final Update update ) { if ( updates == null ) { updates = new ArrayList < Update > ( ) ; } updates . add ( update ) ; }
Add an update to this history
32,629
private void generateThumbails ( final Metadata m , final Element e ) { for ( final Thumbnail thumb : m . getThumbnail ( ) ) { final Element t = new Element ( "thumbnail" , NS ) ; addNotNullAttribute ( t , "url" , thumb . getUrl ( ) ) ; addNotNullAttribute ( t , "width" , thumb . getWidth ( ) ) ; addNotNullAttribute ( t , "height" , thumb . getHeight ( ) ) ; addNotNullAttribute ( t , "time" , thumb . getTime ( ) ) ; e . addContent ( t ) ; } }
Generation of thumbnail tags .
32,630
private void generateComments ( final Metadata m , final Element e ) { final Element commentsElements = new Element ( "comments" , NS ) ; for ( final String comment : m . getComments ( ) ) { addNotNullElement ( commentsElements , "comment" , comment ) ; } if ( ! commentsElements . getChildren ( ) . isEmpty ( ) ) { e . addContent ( commentsElements ) ; } }
Generation of comments tag .
32,631
private void generateCommunity ( final Metadata m , final Element e ) { if ( m . getCommunity ( ) == null ) { return ; } final Element communityElement = new Element ( "community" , NS ) ; if ( m . getCommunity ( ) . getStarRating ( ) != null ) { final Element starRatingElement = new Element ( "starRating" , NS ) ; addNotNullAttribute ( starRatingElement , "average" , m . getCommunity ( ) . getStarRating ( ) . getAverage ( ) ) ; addNotNullAttribute ( starRatingElement , "count" , m . getCommunity ( ) . getStarRating ( ) . getCount ( ) ) ; addNotNullAttribute ( starRatingElement , "min" , m . getCommunity ( ) . getStarRating ( ) . getMin ( ) ) ; addNotNullAttribute ( starRatingElement , "max" , m . getCommunity ( ) . getStarRating ( ) . getMax ( ) ) ; if ( starRatingElement . hasAttributes ( ) ) { communityElement . addContent ( starRatingElement ) ; } } if ( m . getCommunity ( ) . getStatistics ( ) != null ) { final Element statisticsElement = new Element ( "statistics" , NS ) ; addNotNullAttribute ( statisticsElement , "views" , m . getCommunity ( ) . getStatistics ( ) . getViews ( ) ) ; addNotNullAttribute ( statisticsElement , "favorites" , m . getCommunity ( ) . getStatistics ( ) . getFavorites ( ) ) ; if ( statisticsElement . hasAttributes ( ) ) { communityElement . addContent ( statisticsElement ) ; } } if ( m . getCommunity ( ) . getTags ( ) != null && ! m . getCommunity ( ) . getTags ( ) . isEmpty ( ) ) { final Element tagsElement = new Element ( "tags" , NS ) ; for ( final Tag tag : m . getCommunity ( ) . getTags ( ) ) { if ( ! tagsElement . getTextTrim ( ) . isEmpty ( ) ) { tagsElement . addContent ( ", " ) ; } if ( tag . getWeight ( ) == null ) { tagsElement . addContent ( tag . getName ( ) ) ; } else { tagsElement . addContent ( tag . getName ( ) ) ; tagsElement . addContent ( ":" ) ; tagsElement . addContent ( String . valueOf ( tag . getWeight ( ) ) ) ; } } if ( ! tagsElement . getTextTrim ( ) . isEmpty ( ) ) { communityElement . addContent ( tagsElement ) ; } } if ( ! communityElement . getChildren ( ) . isEmpty ( ) ) { e . addContent ( communityElement ) ; } }
Generation of community tag .
32,632
private void generateEmbed ( final Metadata m , final Element e ) { if ( m . getEmbed ( ) == null ) { return ; } final Element embedElement = new Element ( "embed" , NS ) ; addNotNullAttribute ( embedElement , "url" , m . getEmbed ( ) . getUrl ( ) ) ; addNotNullAttribute ( embedElement , "width" , m . getEmbed ( ) . getWidth ( ) ) ; addNotNullAttribute ( embedElement , "height" , m . getEmbed ( ) . getHeight ( ) ) ; for ( final Param param : m . getEmbed ( ) . getParams ( ) ) { final Element paramElement = addNotNullElement ( embedElement , "param" , param . getValue ( ) ) ; if ( paramElement != null ) { addNotNullAttribute ( paramElement , "name" , param . getName ( ) ) ; } } if ( embedElement . hasAttributes ( ) || ! embedElement . getChildren ( ) . isEmpty ( ) ) { e . addContent ( embedElement ) ; } }
Generation of embed tag .
32,633
private void generateScenes ( final Metadata m , final Element e ) { final Element scenesElement = new Element ( "scenes" , NS ) ; for ( final Scene scene : m . getScenes ( ) ) { final Element sceneElement = new Element ( "scene" , NS ) ; addNotNullElement ( sceneElement , "sceneTitle" , scene . getTitle ( ) ) ; addNotNullElement ( sceneElement , "sceneDescription" , scene . getDescription ( ) ) ; addNotNullElement ( sceneElement , "sceneStartTime" , scene . getStartTime ( ) ) ; addNotNullElement ( sceneElement , "sceneEndTime" , scene . getEndTime ( ) ) ; if ( ! sceneElement . getChildren ( ) . isEmpty ( ) ) { scenesElement . addContent ( sceneElement ) ; } } if ( ! scenesElement . getChildren ( ) . isEmpty ( ) ) { e . addContent ( scenesElement ) ; } }
Generation of scenes tag .
32,634
private void generateLocations ( final Metadata m , final Element e ) { final GMLGenerator geoRssGenerator = new GMLGenerator ( ) ; for ( final Location location : m . getLocations ( ) ) { final Element locationElement = new Element ( "location" , NS ) ; addNotNullAttribute ( locationElement , "description" , location . getDescription ( ) ) ; addNotNullAttribute ( locationElement , "start" , location . getStart ( ) ) ; addNotNullAttribute ( locationElement , "end" , location . getEnd ( ) ) ; if ( location . getGeoRss ( ) != null ) { geoRssGenerator . generate ( location . getGeoRss ( ) , locationElement ) ; } if ( locationElement . hasAttributes ( ) || ! locationElement . getChildren ( ) . isEmpty ( ) ) { e . addContent ( locationElement ) ; } } }
Generation of location tags .
32,635
private void generatePeerLinks ( final Metadata m , final Element e ) { for ( final PeerLink peerLink : m . getPeerLinks ( ) ) { final Element peerLinkElement = new Element ( "peerLink" , NS ) ; addNotNullAttribute ( peerLinkElement , "type" , peerLink . getType ( ) ) ; addNotNullAttribute ( peerLinkElement , "href" , peerLink . getHref ( ) ) ; if ( peerLinkElement . hasAttributes ( ) ) { e . addContent ( peerLinkElement ) ; } } }
Generation of peerLink tags .
32,636
private void generateSubTitles ( final Metadata m , final Element e ) { for ( final SubTitle subTitle : m . getSubTitles ( ) ) { final Element subTitleElement = new Element ( "subTitle" , NS ) ; addNotNullAttribute ( subTitleElement , "type" , subTitle . getType ( ) ) ; addNotNullAttribute ( subTitleElement , "lang" , subTitle . getLang ( ) ) ; addNotNullAttribute ( subTitleElement , "href" , subTitle . getHref ( ) ) ; if ( subTitleElement . hasAttributes ( ) ) { e . addContent ( subTitleElement ) ; } } }
Generation of subTitle tags .
32,637
private void generateLicenses ( final Metadata m , final Element e ) { for ( final License license : m . getLicenses ( ) ) { final Element licenseElement = new Element ( "license" , NS ) ; addNotNullAttribute ( licenseElement , "type" , license . getType ( ) ) ; addNotNullAttribute ( licenseElement , "href" , license . getHref ( ) ) ; if ( license . getValue ( ) != null ) { licenseElement . addContent ( license . getValue ( ) ) ; } if ( licenseElement . hasAttributes ( ) || ! licenseElement . getTextTrim ( ) . isEmpty ( ) ) { e . addContent ( licenseElement ) ; } } }
Generation of license tags .
32,638
private void generateResponses ( final Metadata m , final Element e ) { if ( m . getResponses ( ) == null || m . getResponses ( ) . length == 0 ) { return ; } final Element responsesElements = new Element ( "responses" , NS ) ; for ( final String response : m . getResponses ( ) ) { addNotNullElement ( responsesElements , "response" , response ) ; } e . addContent ( responsesElements ) ; }
Generation of responses tag .
32,639
private void generateStatus ( final Metadata m , final Element e ) { if ( m . getStatus ( ) == null ) { return ; } final Element statusElement = new Element ( "status" , NS ) ; if ( m . getStatus ( ) . getState ( ) != null ) { statusElement . setAttribute ( "state" , m . getStatus ( ) . getState ( ) . name ( ) ) ; } addNotNullAttribute ( statusElement , "reason" , m . getStatus ( ) . getReason ( ) ) ; if ( statusElement . hasAttributes ( ) ) { e . addContent ( statusElement ) ; } }
Generation of status tag .
32,640
public void copyFrom ( final CopyFrom obj ) { final AppModule m = ( AppModule ) obj ; setDraft ( m . getDraft ( ) ) ; setEdited ( m . getEdited ( ) ) ; }
Copy from other module
32,641
private static String getContentTypeMime ( final String httpContentType ) { String mime = null ; if ( httpContentType != null ) { final int i = httpContentType . indexOf ( ";" ) ; if ( i == - 1 ) { mime = httpContentType . trim ( ) ; } else { mime = httpContentType . substring ( 0 , i ) . trim ( ) ; } } return mime ; }
returns MIME type or NULL if httpContentType is NULL
32,642
private static String getContentTypeEncoding ( final String httpContentType ) { String encoding = null ; if ( httpContentType != null ) { final int i = httpContentType . indexOf ( ";" ) ; if ( i > - 1 ) { final String postMime = httpContentType . substring ( i + 1 ) ; final Matcher m = CHARSET_PATTERN . matcher ( postMime ) ; if ( m . find ( ) ) { encoding = m . group ( 1 ) ; } if ( encoding != null ) { encoding = encoding . toUpperCase ( Locale . ENGLISH ) ; } } if ( encoding != null && ( encoding . startsWith ( "\"" ) && encoding . endsWith ( "\"" ) || encoding . startsWith ( "'" ) && encoding . endsWith ( "'" ) ) ) { encoding = encoding . substring ( 1 , encoding . length ( ) - 1 ) ; } } return encoding ; }
httpContentType is NULL
32,643
private static String getBOMEncoding ( final BufferedInputStream is ) throws IOException { String encoding = null ; final int [ ] bytes = new int [ 3 ] ; is . mark ( 3 ) ; bytes [ 0 ] = is . read ( ) ; bytes [ 1 ] = is . read ( ) ; bytes [ 2 ] = is . read ( ) ; if ( bytes [ 0 ] == 0xFE && bytes [ 1 ] == 0xFF ) { encoding = UTF_16BE ; is . reset ( ) ; is . read ( ) ; is . read ( ) ; } else if ( bytes [ 0 ] == 0xFF && bytes [ 1 ] == 0xFE ) { encoding = UTF_16LE ; is . reset ( ) ; is . read ( ) ; is . read ( ) ; } else if ( bytes [ 0 ] == 0xEF && bytes [ 1 ] == 0xBB && bytes [ 2 ] == 0xBF ) { encoding = UTF_8 ; } else { is . reset ( ) ; } return encoding ; }
if there was BOM the in the stream it is consumed
32,644
private static boolean isAppXml ( final String mime ) { return mime != null && ( mime . equals ( "application/xml" ) || mime . equals ( "application/xml-dtd" ) || mime . equals ( "application/xml-external-parsed-entity" ) || mime . startsWith ( "application/" ) && mime . endsWith ( "+xml" ) ) ; }
indicates if the MIME type belongs to the APPLICATION XML family
32,645
private static boolean isTextXml ( final String mime ) { return mime != null && ( mime . equals ( "text/xml" ) || mime . equals ( "text/xml-external-parsed-entity" ) || mime . startsWith ( "text/" ) && mime . endsWith ( "+xml" ) ) ; }
indicates if the MIME type belongs to the TEXT XML family
32,646
public static < T extends Extendable > List < T > group ( final List < T > values , final Group [ ] groups ) { final SortableList < T > list = getSortableList ( values ) ; final GroupStrategy strategy = new GroupStrategy ( ) ; for ( int i = groups . length - 1 ; i >= 0 ; i -- ) { list . sortOnProperty ( groups [ i ] , true , strategy ) ; } return list ; }
Groups values by the groups from the SLE .
32,647
public static < T extends Extendable > List < T > sort ( final List < T > values , final Sort sort , final boolean ascending ) { final SortableList < T > list = getSortableList ( values ) ; list . sortOnProperty ( sort , ascending , new SortStrategy ( ) ) ; return list ; }
Sorts a list of values based on a given sort field using a selection sort .
32,648
public static < T extends Extendable > List < T > sortAndGroup ( final List < T > values , final Group [ ] groups , final Sort sort , final boolean ascending ) { List < T > list = sort ( values , sort , ascending ) ; list = group ( list , groups ) ; return list ; }
Sorts and groups a set of entries .
32,649
public static ClientAtomService getAtomService ( final String uri , final AuthStrategy authStrategy ) throws ProponoException { return new ClientAtomService ( uri , authStrategy ) ; }
Create AtomService by reading service doc from Atom Server .
32,650
public static ClientCollection getCollection ( final String uri , final AuthStrategy authStrategy ) throws ProponoException { return new ClientCollection ( uri , authStrategy ) ; }
Create ClientCollection bound to URI .
32,651
public void setReference ( final Reference reference ) { this . reference = reference ; if ( reference instanceof PlayerReference ) { setPlayer ( ( PlayerReference ) reference ) ; } }
The player or URL reference for the item
32,652
public static void inject ( final WebDriver driver , final URL scriptUrl , Boolean skipFrames ) { final String script = getContents ( scriptUrl ) ; if ( ! skipFrames ) { final ArrayList < WebElement > parents = new ArrayList < WebElement > ( ) ; injectIntoFrames ( driver , script , parents ) ; } JavascriptExecutor js = ( JavascriptExecutor ) driver ; driver . switchTo ( ) . defaultContent ( ) ; js . executeScript ( script ) ; }
Recursively injects a script to the top level document with the option to skip iframes .
32,653
private static void injectIntoFrames ( final WebDriver driver , final String script , final ArrayList < WebElement > parents ) { final JavascriptExecutor js = ( JavascriptExecutor ) driver ; final List < WebElement > frames = driver . findElements ( By . tagName ( "iframe" ) ) ; for ( WebElement frame : frames ) { driver . switchTo ( ) . defaultContent ( ) ; if ( parents != null ) { for ( WebElement parent : parents ) { driver . switchTo ( ) . frame ( parent ) ; } } driver . switchTo ( ) . frame ( frame ) ; js . executeScript ( script ) ; ArrayList < WebElement > localParents = ( ArrayList < WebElement > ) parents . clone ( ) ; localParents . add ( frame ) ; injectIntoFrames ( driver , script , localParents ) ; } }
Recursively find frames and inject a script into them .
32,654
public static void writeResults ( final String name , final Object output ) { Writer writer = null ; try { writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( name + ".json" ) , "utf-8" ) ) ; writer . write ( output . toString ( ) ) ; } catch ( IOException ignored ) { } finally { try { writer . close ( ) ; } catch ( Exception ignored ) { } } }
Writes a raw object out to a JSON file with the specified name .
32,655
public void add ( IWord word ) { if ( word . getEntity ( ) == null ) { word . setEntity ( rootWord . getEntity ( ) ) ; } if ( word . getPartSpeech ( ) == null ) { word . setPartSpeech ( rootWord . getPartSpeech ( ) ) ; } word . setSyn ( this ) ; synsList . add ( word ) ; }
add a new synonyms word and the newly added word will extends the part of speech and the entity from the base word if there are not set
32,656
public static int isCNNumeric ( char c ) { Integer i = cnNumeric . get ( c ) ; if ( i == null ) return - 1 ; return i . intValue ( ) ; }
check if the given char is a Chinese numeric or not
32,657
public static boolean isCNNumericString ( String str , int sIdx , int eIdx ) { for ( int i = sIdx ; i < eIdx ; i ++ ) { if ( ! cnNumeric . containsKey ( str . charAt ( i ) ) ) { return false ; } } return true ; }
check if the specified string is a Chinese numeric string
32,658
protected void response ( int code , String data ) { response . setContentType ( "application/json;charset=" + config . getCharset ( ) ) ; JSONWriter json = JSONWriter . create ( ) . put ( "code" , code ) . put ( "data" , data ) ; output . println ( json . toString ( ) ) ; output . flush ( ) ; json = null ; }
global output protocol
32,659
protected void response ( int code , List < Object > data ) { response ( code , JSONWriter . list2JsonString ( data ) ) ; }
global list output protocol
32,660
protected void response ( int code , Map < String , Object > data ) { response ( code , JSONWriter . map2JsonString ( data ) ) ; }
global map output protocol
32,661
public JSONWriter put ( String key , Object obj ) { data . put ( key , obj ) ; return this ; }
put a new mapping with a string
32,662
public JSONWriter put ( String key , Object [ ] vector ) { data . put ( key , vector2JsonString ( vector ) ) ; return this ; }
put a new mapping with a vector
32,663
@ SuppressWarnings ( "unchecked" ) public static String vector2JsonString ( Object [ ] vector ) { IStringBuffer sb = new IStringBuffer ( ) ; sb . append ( '[' ) ; for ( Object o : vector ) { if ( o instanceof List < ? > ) { sb . append ( list2JsonString ( ( List < Object > ) o ) ) . append ( ',' ) ; } else if ( o instanceof Object [ ] ) { sb . append ( vector2JsonString ( ( Object [ ] ) o ) ) . append ( ',' ) ; } else if ( o instanceof Map < ? , ? > ) { sb . append ( map2JsonString ( ( Map < String , Object > ) o ) ) . append ( ',' ) ; } else if ( ( o instanceof Boolean ) || ( o instanceof Byte ) || ( o instanceof Short ) || ( o instanceof Integer ) || ( o instanceof Long ) || ( o instanceof Float ) || ( o instanceof Double ) ) { sb . append ( o . toString ( ) ) . append ( ',' ) ; } else { String v = o . toString ( ) ; int last = v . length ( ) - 1 ; if ( v . length ( ) > 1 && ( ( v . charAt ( 0 ) == '{' && v . charAt ( last ) == '}' ) || ( v . charAt ( 0 ) == '[' && v . charAt ( last ) == ']' ) ) ) { sb . append ( v ) . append ( ',' ) ; } else { sb . append ( '"' ) . append ( v ) . append ( "\"," ) ; } } } if ( sb . length ( ) > 1 ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } sb . append ( ']' ) ; return sb . toString ( ) ; }
vector to json string
32,664
@ SuppressWarnings ( "unchecked" ) public static String map2JsonString ( Map < String , Object > map ) { IStringBuffer sb = new IStringBuffer ( ) ; sb . append ( '{' ) ; for ( Map . Entry < String , Object > entry : map . entrySet ( ) ) { sb . append ( '"' ) . append ( entry . getKey ( ) . toString ( ) ) . append ( "\": " ) ; Object obj = entry . getValue ( ) ; if ( obj instanceof List < ? > ) { sb . append ( list2JsonString ( ( List < Object > ) obj ) ) . append ( ',' ) ; } else if ( obj instanceof Object [ ] ) { sb . append ( vector2JsonString ( ( Object [ ] ) obj ) ) . append ( ',' ) ; } else if ( obj instanceof Map < ? , ? > ) { sb . append ( map2JsonString ( ( Map < String , Object > ) obj ) ) . append ( ',' ) ; } else if ( ( obj instanceof Boolean ) || ( obj instanceof Byte ) || ( obj instanceof Short ) || ( obj instanceof Integer ) || ( obj instanceof Long ) || ( obj instanceof Float ) || ( obj instanceof Double ) ) { sb . append ( obj . toString ( ) ) . append ( ',' ) ; } else { String v = obj . toString ( ) ; int last = v . length ( ) - 1 ; if ( v . length ( ) > 1 && ( ( v . charAt ( 0 ) == '{' && v . charAt ( last ) == '}' ) || ( v . charAt ( 0 ) == '[' && v . charAt ( last ) == ']' ) ) ) { sb . append ( v ) . append ( ',' ) ; } else { sb . append ( '"' ) . append ( v ) . append ( "\"," ) ; } } } if ( sb . length ( ) > 1 ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } sb . append ( '}' ) ; return sb . toString ( ) ; }
map to json string
32,665
public static Object stringToValue ( String string ) { if ( "true" . equalsIgnoreCase ( string ) ) { return Boolean . TRUE ; } if ( "false" . equalsIgnoreCase ( string ) ) { return Boolean . FALSE ; } if ( "null" . equalsIgnoreCase ( string ) ) { return JSONObject . NULL ; } try { char initial = string . charAt ( 0 ) ; if ( initial == '-' || ( initial >= '0' && initial <= '9' ) ) { Long value = new Long ( string ) ; if ( value . toString ( ) . equals ( string ) ) { return value ; } } } catch ( Exception ignore ) { try { Double value = new Double ( string ) ; if ( value . toString ( ) . equals ( string ) ) { return value ; } } catch ( Exception ignoreAlso ) { } } return string ; }
Try to convert a string into a number boolean or null . If the string can t be converted return the string . This is much less ambitious than JSONObject . stringToValue especially because it does not attempt to convert plus forms octal forms hex forms or E forms lacking decimal points .
32,666
public boolean pad ( int width ) throws IOException { boolean result = true ; int gap = ( int ) this . nrBits % width ; if ( gap < 0 ) { gap += width ; } if ( gap != 0 ) { int padding = width - gap ; while ( padding > 0 ) { if ( bit ( ) ) { result = false ; } padding -= 1 ; } } return result ; }
Check that the rest of the block has been padded with zeroes .
32,667
public int read ( int width ) throws IOException { if ( width == 0 ) { return 0 ; } if ( width < 0 || width > 32 ) { throw new IOException ( "Bad read width." ) ; } int result = 0 ; while ( width > 0 ) { if ( this . available == 0 ) { this . unread = this . in . read ( ) ; if ( this . unread < 0 ) { throw new IOException ( "Attempt to read past end." ) ; } this . available = 8 ; } int take = width ; if ( take > this . available ) { take = this . available ; } result |= ( ( this . unread >>> ( this . available - take ) ) & ( ( 1 << take ) - 1 ) ) << ( width - take ) ; this . nrBits += take ; this . available -= take ; width -= take ; } return result ; }
Read some bits .
32,668
public int read ( char [ ] cbuf , int off , int len ) throws IOException { int size = queue . size ( ) ; if ( size > 0 ) { throw new IOException ( "Method not implemented yet" ) ; } return reader . read ( cbuf , off , len ) ; }
read the specified block from the stream
32,669
public void unread ( char [ ] cbuf , int off , int len ) { for ( int i = 0 ; i < len ; i ++ ) { queue . enQueue ( cbuf [ off + i ] ) ; } }
unread a block from a char array to the stream
32,670
public void load ( File file ) throws NumberFormatException , FileNotFoundException , IOException { loadWords ( config , this , file , synBuffer ) ; }
load all the words from a specified lexicon file
32,671
public void loadDirectory ( String lexDir ) throws IOException { File path = new File ( lexDir ) ; if ( ! path . exists ( ) ) { throw new IOException ( "Lexicon directory [" + lexDir + "] does'n exists." ) ; } File [ ] files = path . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return ( name . startsWith ( "lex-" ) && name . endsWith ( ".lex" ) ) ; } } ) ; for ( File file : files ) { load ( file ) ; } }
load the all the words from all the files under a specified lexicon directory
32,672
public void loadClassPath ( ) throws IOException { Class < ? > dClass = this . getClass ( ) ; CodeSource codeSrc = this . getClass ( ) . getProtectionDomain ( ) . getCodeSource ( ) ; if ( codeSrc == null ) { return ; } String codePath = codeSrc . getLocation ( ) . getPath ( ) ; if ( codePath . toLowerCase ( ) . endsWith ( ".jar" ) ) { ZipInputStream zip = new ZipInputStream ( codeSrc . getLocation ( ) . openStream ( ) ) ; while ( true ) { ZipEntry e = zip . getNextEntry ( ) ; if ( e == null ) { break ; } String fileName = e . getName ( ) ; if ( fileName . endsWith ( ".lex" ) && fileName . startsWith ( "lexicon/lex-" ) ) { load ( dClass . getResourceAsStream ( "/" + fileName ) ) ; } } } else { loadDirectory ( codePath + "/lexicon" ) ; } }
load all the words from all the files under the specified class path .
32,673
public void startAutoload ( ) { if ( autoloadThread != null || config . getLexiconPath ( ) == null ) { return ; } autoloadThread = new Thread ( new Runnable ( ) { public void run ( ) { String [ ] paths = config . getLexiconPath ( ) ; AutoLoadFile [ ] files = new AutoLoadFile [ paths . length ] ; for ( int i = 0 ; i < files . length ; i ++ ) { files [ i ] = new AutoLoadFile ( paths [ i ] + "/" + AL_TODO_FILE ) ; files [ i ] . setLastUpdateTime ( files [ i ] . getFile ( ) . lastModified ( ) ) ; } while ( true ) { try { Thread . sleep ( config . getPollTime ( ) * 1000 ) ; } catch ( InterruptedException e ) { break ; } File f = null ; AutoLoadFile af = null ; for ( int i = 0 ; i < files . length ; i ++ ) { af = files [ i ] ; f = files [ i ] . getFile ( ) ; if ( ! f . exists ( ) ) continue ; if ( f . lastModified ( ) <= af . getLastUpdateTime ( ) ) { continue ; } try { BufferedReader reader = new BufferedReader ( new FileReader ( f ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . indexOf ( '#' ) != - 1 ) continue ; if ( "" . equals ( line ) ) continue ; load ( paths [ i ] + "/" + line ) ; } reader . close ( ) ; FileWriter fw = new FileWriter ( f ) ; fw . write ( "" ) ; fw . close ( ) ; af . setLastUpdateTime ( f . lastModified ( ) ) ; } catch ( IOException e ) { break ; } } resetSynonymsNet ( ) ; } } } ) ; autoloadThread . setDaemon ( true ) ; autoloadThread . start ( ) ; }
start the lexicon autoload thread
32,674
public static int getIndex ( String key ) { if ( key == null ) { return - 1 ; } key = key . toUpperCase ( ) ; if ( key . startsWith ( "CJK_WORD" ) ) { return ILexicon . CJK_WORD ; } else if ( key . startsWith ( "CJK_CHAR" ) ) { return ILexicon . CJK_CHAR ; } else if ( key . startsWith ( "CJK_UNIT" ) ) { return ILexicon . CJK_UNIT ; } else if ( key . startsWith ( "CN_LNAME_ADORN" ) ) { return ILexicon . CN_LNAME_ADORN ; } else if ( key . startsWith ( "CN_LNAME" ) ) { return ILexicon . CN_LNAME ; } else if ( key . startsWith ( "CN_SNAME" ) ) { return ILexicon . CN_SNAME ; } else if ( key . startsWith ( "CN_DNAME_1" ) ) { return ILexicon . CN_DNAME_1 ; } else if ( key . startsWith ( "CN_DNAME_2" ) ) { return ILexicon . CN_DNAME_2 ; } else if ( key . startsWith ( "STOP_WORD" ) ) { return ILexicon . STOP_WORD ; } else if ( key . startsWith ( "DOMAIN_SUFFIX" ) ) { return ILexicon . DOMAIN_SUFFIX ; } else if ( key . startsWith ( "NUMBER_UNIT" ) ) { return ILexicon . NUMBER_UNIT ; } else if ( key . startsWith ( "CJK_SYN" ) ) { return ILexicon . CJK_SYN ; } return ILexicon . CJK_WORD ; }
get the key s type index located in ILexicon interface
32,675
public static void loadWords ( JcsegTaskConfig config , ADictionary dic , File file , List < String [ ] > buffer ) throws NumberFormatException , FileNotFoundException , IOException { loadWords ( config , dic , new FileInputStream ( file ) , buffer ) ; }
load all the words in the specified lexicon file into the dictionary
32,676
public final static void appendSynonyms ( LinkedList < IWord > wordPool , IWord wd ) { List < IWord > synList = wd . getSyn ( ) . getList ( ) ; synchronized ( synList ) { for ( int j = 0 ; j < synList . size ( ) ; j ++ ) { IWord curWord = synList . get ( j ) ; if ( curWord . getValue ( ) . equals ( wd . getValue ( ) ) ) { continue ; } IWord synWord = synList . get ( j ) . clone ( ) ; synWord . setPosition ( wd . getPosition ( ) ) ; wordPool . add ( synWord ) ; } } }
quick interface to do the synonyms append word You got check if the specified has any synonyms first
32,677
public T get ( E key ) { Entry < E , T > entry = null ; synchronized ( this ) { entry = map . get ( key ) ; if ( map . get ( key ) == null ) return null ; entry . prev . next = entry . next ; entry . next . prev = entry . prev ; entry . prev = this . head ; entry . next = this . head . next ; this . head . next . prev = entry ; this . head . next = entry ; } return entry . value ; }
get a element from map with specified key
32,678
public void set ( E key , T value ) { Entry < E , T > entry = new Entry < E , T > ( key , value , null , null ) ; synchronized ( this ) { if ( map . get ( key ) == null ) { if ( this . length >= this . capacity ) this . removeLeastUsedElements ( ) ; entry . prev = this . head ; entry . next = this . head . next ; this . head . next . prev = entry ; this . head . next = entry ; this . length ++ ; map . put ( key , entry ) ; } else { entry = map . get ( key ) ; entry . value = value ; entry . prev . next = entry . next ; entry . next . prev = entry . prev ; entry . prev = this . head ; entry . next = this . head . next ; this . head . next . prev = entry ; this . head . next = entry ; } } }
set a element to list
32,679
public synchronized void remove ( E key ) { Entry < E , T > entry = map . get ( key ) ; this . tail . prev = entry . prev ; entry . prev . next = this . tail ; map . remove ( entry . key ) ; this . length -- ; }
remove a element from list
32,680
public synchronized void removeLeastUsedElements ( ) { int rows = this . removePercent / 100 * this . length ; rows = rows == 0 ? 1 : rows ; while ( rows > 0 && this . length > 0 ) { Entry < E , T > entry = this . tail . prev ; this . tail . prev = entry . prev ; entry . prev . next = this . tail ; map . remove ( entry . key ) ; this . length -- ; rows -- ; } }
remove least used elements
32,681
public synchronized void printList ( ) { Entry < E , T > entry = this . head . next ; System . out . println ( "\n|----- key list----|" ) ; while ( entry != this . tail ) { System . out . println ( " -> " + entry . key ) ; entry = entry . next ; } System . out . println ( "|------- end --------|\n" ) ; }
print the list
32,682
public void write ( int bits , int width ) throws IOException { if ( bits == 0 && width == 0 ) { return ; } if ( width <= 0 || width > 32 ) { throw new IOException ( "Bad write width." ) ; } while ( width > 0 ) { int actual = width ; if ( actual > this . vacant ) { actual = this . vacant ; } this . unwritten |= ( ( bits >>> ( width - actual ) ) & ( ( 1 << actual ) - 1 ) ) << ( this . vacant - actual ) ; width -= actual ; nrBits += actual ; this . vacant -= actual ; if ( this . vacant == 0 ) { this . out . write ( this . unwritten ) ; this . unwritten = 0 ; this . vacant = 8 ; } } }
Write some bits . Up to 32 bits can be written at a time .
32,683
public String __toString ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( value ) ; sb . append ( '/' ) ; if ( partspeech != null ) { for ( int j = 0 ; j < partspeech . length ; j ++ ) { if ( j == 0 ) { sb . append ( partspeech [ j ] ) ; } else { sb . append ( ',' ) ; sb . append ( partspeech [ j ] ) ; } } } else { sb . append ( "null" ) ; } sb . append ( '/' ) ; sb . append ( pinyin ) ; sb . append ( '/' ) ; if ( syn != null ) { List < IWord > synsList = syn . getList ( ) ; synchronized ( synsList ) { for ( int i = 0 ; i < synsList . size ( ) ; i ++ ) { if ( i == 0 ) { sb . append ( synsList . get ( i ) ) ; } else { sb . append ( ',' ) ; sb . append ( synsList . get ( i ) ) ; } } } } else { sb . append ( "null" ) ; } if ( value . length ( ) == 1 ) { sb . append ( '/' ) ; sb . append ( fre ) ; } if ( entity != null ) { sb . append ( '/' ) ; sb . append ( ArrayUtil . implode ( "|" , entity ) ) ; } if ( parameter != null ) { sb . append ( '/' ) ; sb . append ( parameter ) ; } return sb . toString ( ) ; }
for debug only
32,684
public static < T extends Comparable < ? super T > > void insertionSort ( T [ ] arr ) { int j ; for ( int i = 1 ; i < arr . length ; i ++ ) { T tmp = arr [ i ] ; for ( j = i ; j > 0 && tmp . compareTo ( arr [ j - 1 ] ) < 0 ; j -- ) { arr [ j ] = arr [ j - 1 ] ; } if ( j < i ) arr [ j ] = tmp ; } }
insert sort method
32,685
public static < T extends Comparable < ? super T > > void shellSort ( T [ ] arr ) { int j , k = 0 , gap ; for ( ; GAPS [ k ] < arr . length ; k ++ ) ; while ( k -- > 0 ) { gap = GAPS [ k ] ; for ( int i = gap ; i < arr . length ; i ++ ) { T tmp = arr [ i ] ; for ( j = i ; j >= gap && tmp . compareTo ( arr [ j - gap ] ) < 0 ; j -= gap ) { arr [ j ] = arr [ j - gap ] ; } if ( j < i ) arr [ j ] = tmp ; } } }
shell sort algorithm
32,686
@ SuppressWarnings ( "unchecked" ) public static < T extends Comparable < ? super T > > void mergeSort ( T [ ] arr ) { T [ ] tmpArr = ( T [ ] ) new Comparable [ arr . length ] ; mergeSort ( arr , tmpArr , 0 , arr . length - 1 ) ; }
merge sort algorithm
32,687
private static < T extends Comparable < ? super T > > void mergeSort ( T [ ] arr , T [ ] tmpArr , int left , int right ) { if ( left < right ) { int center = ( left + right ) / 2 ; mergeSort ( arr , tmpArr , left , center ) ; mergeSort ( arr , tmpArr , center + 1 , right ) ; merge ( arr , tmpArr , left , center + 1 , right ) ; } }
internal method to make a recursive call
32,688
private static < T extends Comparable < ? super T > > void merge ( T [ ] arr , T [ ] tmpArr , int lPos , int rPos , int rEnd ) { int lEnd = rPos - 1 ; int tPos = lPos ; int leftTmp = lPos ; while ( lPos <= lEnd && rPos <= rEnd ) { if ( arr [ lPos ] . compareTo ( arr [ rPos ] ) <= 0 ) { tmpArr [ tPos ++ ] = arr [ lPos ++ ] ; } else { tmpArr [ tPos ++ ] = arr [ rPos ++ ] ; } } while ( lPos <= lEnd ) { tmpArr [ tPos ++ ] = arr [ lPos ++ ] ; } while ( rPos <= rEnd ) { tmpArr [ tPos ++ ] = arr [ rPos ++ ] ; } for ( ; rEnd >= leftTmp ; rEnd -- ) { arr [ rEnd ] = tmpArr [ rEnd ] ; } }
internal method to merge the sorted halves of a subarray
32,689
private static < T > void swapReferences ( T [ ] arr , int idx1 , int idx2 ) { T tmp = arr [ idx1 ] ; arr [ idx1 ] = arr [ idx2 ] ; arr [ idx2 ] = tmp ; }
method to swap elements in an array
32,690
public static < T extends Comparable < ? super T > > void quicksort ( T [ ] arr ) { quicksort ( arr , 0 , arr . length - 1 ) ; }
quick sort algorithm
32,691
public static < T extends Comparable < ? super T > > void insertionSort ( T [ ] arr , int start , int end ) { int i ; for ( int j = start + 1 ; j <= end ; j ++ ) { T tmp = arr [ j ] ; for ( i = j ; i > start && tmp . compareTo ( arr [ i - 1 ] ) < 0 ; i -- ) { arr [ i ] = arr [ i - 1 ] ; } if ( i < j ) arr [ i ] = tmp ; } }
method to sort an subarray from start to end with insertion sort algorithm
32,692
private static < T extends Comparable < ? super T > > void quicksort ( T [ ] arr , int left , int right ) { if ( left + CUTOFF <= right ) { T pivot = median ( arr , left , right ) ; int i = left , j = right - 1 ; for ( ; ; ) { while ( arr [ ++ i ] . compareTo ( pivot ) < 0 ) ; while ( arr [ -- j ] . compareTo ( pivot ) > 0 ) ; if ( i < j ) { swapReferences ( arr , i , j ) ; } else { break ; } } swapReferences ( arr , i , right - 1 ) ; quicksort ( arr , left , i - 1 ) ; quicksort ( arr , i + 1 , right ) ; } else { insertionSort ( arr , left , right ) ; } }
internal method to sort the array with quick sort algorithm
32,693
public static < T extends Comparable < ? super T > > void quickSelect ( T [ ] arr , int k ) { quickSelect ( arr , 0 , arr . length - 1 , k ) ; }
quick select algorithm
32,694
public static void bucketSort ( int [ ] arr , int m ) { int [ ] count = new int [ m ] ; int j , i = 0 ; for ( j = 0 ; j < arr . length ; j ++ ) { count [ arr [ j ] ] ++ ; } for ( j = 0 ; j < m ; j ++ ) { if ( count [ j ] > 0 ) { while ( count [ j ] -- > 0 ) { arr [ i ++ ] = j ; } } } }
bucket sort algorithm
32,695
public static String getJarHome ( Object o ) { String path = o . getClass ( ) . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) . getFile ( ) ; File jarFile = new File ( path ) ; return jarFile . getParentFile ( ) . getAbsolutePath ( ) ; }
get the absolute parent path for the jar file .
32,696
public static void printMatrix ( double [ ] [ ] matrix ) { StringBuffer sb = new StringBuffer ( ) ; sb . append ( '[' ) . append ( '\n' ) ; for ( double [ ] line : matrix ) { for ( double column : line ) { sb . append ( column ) . append ( ", " ) ; } sb . append ( '\n' ) ; } sb . append ( ']' ) ; System . out . println ( sb . toString ( ) ) ; }
print the specified matrix
32,697
public void resetFromFile ( String configFile ) throws IOException { IStringBuffer isb = new IStringBuffer ( ) ; String line = null ; BufferedReader reader = new BufferedReader ( new FileReader ( configFile ) ) ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . equals ( "" ) ) continue ; if ( line . charAt ( 0 ) == '#' ) continue ; isb . append ( line ) . append ( '\n' ) ; line = null ; } globalConfig = new JSONObject ( isb . toString ( ) ) ; isb = null ; reader . close ( ) ; reader = null ; }
initialize it from the specified config file
32,698
public boolean enQueue ( int data ) { Entry o = new Entry ( data , head . next ) ; head . next = o ; size ++ ; return true ; }
add a new item to the queue
32,699
public static ADictionary createDictionary ( Class < ? extends ADictionary > _class , Class < ? > [ ] paramType , Object [ ] args ) { try { Constructor < ? > cons = _class . getConstructor ( paramType ) ; return ( ( ADictionary ) cons . newInstance ( args ) ) ; } catch ( Exception e ) { System . err . println ( "can't create the ADictionary instance " + "with classpath [" + _class . getName ( ) + "]" ) ; e . printStackTrace ( ) ; } return null ; }
create a new ADictionary instance