idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
38,000
|
public static MethodNode findMethod ( Collection < MethodNode > methodNodes , boolean isStatic , Type returnType , String name , Type ... paramTypes ) { Validate . notNull ( methodNodes ) ; Validate . notNull ( returnType ) ; Validate . notNull ( name ) ; Validate . notNull ( paramTypes ) ; Validate . noNullElements ( methodNodes ) ; Validate . noNullElements ( paramTypes ) ; Validate . isTrue ( returnType . getSort ( ) != Type . METHOD ) ; for ( Type paramType : paramTypes ) { Validate . isTrue ( paramType . getSort ( ) != Type . METHOD && paramType . getSort ( ) != Type . VOID ) ; } Collection < MethodNode > ret = methodNodes ; ret = findMethodsWithName ( ret , name ) ; ret = findMethodsWithParameters ( ret , paramTypes ) ; if ( isStatic ) { ret = findStaticMethods ( ret ) ; } Validate . validState ( ret . size ( ) <= 1 ) ; return ret . isEmpty ( ) ? null : ret . iterator ( ) . next ( ) ; }
|
Find a method within a class .
|
38,001
|
public static List < AbstractInsnNode > findInvocationsOf ( InsnList insnList , Method expectedMethod ) { Validate . notNull ( insnList ) ; Validate . notNull ( expectedMethod ) ; List < AbstractInsnNode > ret = new ArrayList < > ( ) ; Type expectedMethodDesc = Type . getType ( expectedMethod ) ; Type expectedMethodOwner = Type . getType ( expectedMethod . getDeclaringClass ( ) ) ; String expectedMethodName = expectedMethod . getName ( ) ; Iterator < AbstractInsnNode > it = insnList . iterator ( ) ; while ( it . hasNext ( ) ) { AbstractInsnNode instructionNode = it . next ( ) ; Type methodDesc ; Type methodOwner ; String methodName ; if ( instructionNode instanceof MethodInsnNode ) { MethodInsnNode methodInsnNode = ( MethodInsnNode ) instructionNode ; methodDesc = Type . getType ( methodInsnNode . desc ) ; methodOwner = Type . getObjectType ( methodInsnNode . owner ) ; methodName = expectedMethod . getName ( ) ; } else { continue ; } if ( methodDesc . equals ( expectedMethodDesc ) && methodOwner . equals ( expectedMethodOwner ) && methodName . equals ( expectedMethodName ) ) { ret . add ( instructionNode ) ; } } return ret ; }
|
Find invocations of a certain method .
|
38,002
|
public static List < AbstractInsnNode > findInvocationsWithParameter ( InsnList insnList , Type expectedParamType ) { Validate . notNull ( insnList ) ; Validate . notNull ( expectedParamType ) ; Validate . isTrue ( expectedParamType . getSort ( ) != Type . METHOD && expectedParamType . getSort ( ) != Type . VOID ) ; List < AbstractInsnNode > ret = new ArrayList < > ( ) ; Iterator < AbstractInsnNode > it = insnList . iterator ( ) ; while ( it . hasNext ( ) ) { AbstractInsnNode instructionNode = it . next ( ) ; Type [ ] methodParamTypes ; if ( instructionNode instanceof MethodInsnNode ) { MethodInsnNode methodInsnNode = ( MethodInsnNode ) instructionNode ; Type methodType = Type . getType ( methodInsnNode . desc ) ; methodParamTypes = methodType . getArgumentTypes ( ) ; } else if ( instructionNode instanceof InvokeDynamicInsnNode ) { InvokeDynamicInsnNode invokeDynamicInsnNode = ( InvokeDynamicInsnNode ) instructionNode ; Type methodType = Type . getType ( invokeDynamicInsnNode . desc ) ; methodParamTypes = methodType . getArgumentTypes ( ) ; } else { continue ; } if ( Arrays . asList ( methodParamTypes ) . contains ( expectedParamType ) ) { ret . add ( instructionNode ) ; } } return ret ; }
|
Find invocations of any method where the parameter list contains a type .
|
38,003
|
public static List < AbstractInsnNode > searchForOpcodes ( InsnList insnList , int ... opcodes ) { Validate . notNull ( insnList ) ; Validate . notNull ( opcodes ) ; Validate . isTrue ( opcodes . length > 0 ) ; List < AbstractInsnNode > ret = new LinkedList < > ( ) ; Set < Integer > opcodeSet = new HashSet < > ( ) ; Arrays . stream ( opcodes ) . forEach ( ( x ) -> opcodeSet . add ( x ) ) ; Iterator < AbstractInsnNode > it = insnList . iterator ( ) ; while ( it . hasNext ( ) ) { AbstractInsnNode insnNode = it . next ( ) ; if ( opcodeSet . contains ( insnNode . getOpcode ( ) ) ) { ret . add ( insnNode ) ; } } return ret ; }
|
Find instructions in a certain class that are of a certain set of opcodes .
|
38,004
|
public static LineNumberNode findLineNumberForInstruction ( InsnList insnList , AbstractInsnNode insnNode ) { Validate . notNull ( insnList ) ; Validate . notNull ( insnNode ) ; int idx = insnList . indexOf ( insnNode ) ; Validate . isTrue ( idx != - 1 ) ; ListIterator < AbstractInsnNode > insnIt = insnList . iterator ( idx ) ; while ( insnIt . hasPrevious ( ) ) { AbstractInsnNode node = insnIt . previous ( ) ; if ( node instanceof LineNumberNode ) { return ( LineNumberNode ) node ; } } return null ; }
|
Find line number associated with an instruction .
|
38,005
|
public static LocalVariableNode findLocalVariableNodeForInstruction ( List < LocalVariableNode > lvnList , InsnList insnList , final AbstractInsnNode insnNode , int idx ) { Validate . notNull ( insnList ) ; Validate . notNull ( insnNode ) ; Validate . isTrue ( idx >= 0 ) ; int insnIdx = insnList . indexOf ( insnNode ) ; Validate . isTrue ( insnIdx != - 1 ) ; lvnList = lvnList . stream ( ) . filter ( lvn -> lvn . index == idx ) . filter ( lvn -> { AbstractInsnNode currentInsnNode = insnNode . getPrevious ( ) ; while ( currentInsnNode != null ) { if ( currentInsnNode == lvn . start ) { return true ; } currentInsnNode = currentInsnNode . getPrevious ( ) ; } return false ; } ) . filter ( lvn -> { AbstractInsnNode currentInsnNode = insnNode . getNext ( ) ; while ( currentInsnNode != null ) { if ( currentInsnNode == lvn . end ) { return true ; } currentInsnNode = currentInsnNode . getNext ( ) ; } return false ; } ) . collect ( Collectors . toList ( ) ) ; if ( lvnList . isEmpty ( ) ) { return null ; } for ( LocalVariableNode lvn : lvnList ) { int start = insnList . indexOf ( lvn . start ) ; int end = insnList . indexOf ( lvn . end ) ; Validate . validState ( end > start ) ; } for ( LocalVariableNode lvnTester : lvnList ) { int startTester = insnList . indexOf ( lvnTester . start ) ; int endTester = insnList . indexOf ( lvnTester . end ) ; Range rangeTester = Range . between ( startTester , endTester ) ; for ( LocalVariableNode lvnTestee : lvnList ) { if ( lvnTester == lvnTestee ) { continue ; } int startTestee = insnList . indexOf ( lvnTestee . start ) ; int endTestee = insnList . indexOf ( lvnTestee . end ) ; Range rangeTestee = Range . between ( startTestee , endTestee ) ; Range intersectRange = rangeTester . intersectionWith ( rangeTestee ) ; Validate . validState ( intersectRange . equals ( rangeTester ) || intersectRange . equals ( rangeTestee ) ) ; Validate . validState ( rangeTester . getMinimum ( ) != rangeTestee . getMinimum ( ) ) ; } } return Collections . min ( lvnList , ( o1 , o2 ) -> { int o1Len = insnList . indexOf ( o1 . end ) - insnList . indexOf ( o1 . start ) ; int o2Len = insnList . indexOf ( o2 . end ) - insnList . indexOf ( o2 . start ) ; return Integer . compare ( o1Len , o2Len ) ; } ) ; }
|
Find local variable node for a local variable at some instruction .
|
38,006
|
public static FieldNode findField ( ClassNode classNode , String name ) { Validate . notNull ( classNode ) ; Validate . notNull ( name ) ; Validate . notEmpty ( name ) ; return classNode . fields . stream ( ) . filter ( x -> name . equals ( x . name ) ) . findAny ( ) . orElse ( null ) ; }
|
Find field within a class by its name .
|
38,007
|
public static void validateXMLSchema ( String xsdPath , String xmlPath ) throws IOException , SAXException { InputStream xsdStream = null ; InputStream xmlStream = null ; try { xsdStream = XmlUtils . class . getResourceAsStream ( xsdPath ) ; if ( xsdStream == null ) { File xsdFile = new File ( xsdPath ) ; xsdStream = new FileInputStream ( xsdFile ) ; } xmlStream = XmlUtils . class . getResourceAsStream ( xmlPath ) ; if ( xmlStream == null ) { File xmlFile = new File ( xmlPath ) ; xmlStream = new FileInputStream ( xmlFile ) ; } validateXMLSchema ( xsdStream , xmlStream ) ; } finally { if ( xsdStream != null ) { try { xsdStream . close ( ) ; } catch ( Exception e ) { xsdStream = null ; } } if ( xmlStream != null ) { try { xmlStream . close ( ) ; } catch ( Exception e ) { xmlStream = null ; } } } }
|
Validate XML matches XSD . Path - based method . Simple redirect to the overloaded version that accepts streams .
|
38,008
|
public static void validateXMLSchema ( InputStream xsdStream , InputStream xmlStream ) throws IOException , SAXException { SchemaFactory factory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; Schema schema = factory . newSchema ( new StreamSource ( xsdStream ) ) ; Validator validator = schema . newValidator ( ) ; validator . validate ( new StreamSource ( xmlStream ) ) ; }
|
Validate XML matches XSD . Stream - based method .
|
38,009
|
public static String getElementQualifiedName ( XMLStreamReader xmlReader , Map < String , String > namespaces ) { String namespaceUri = null ; String localName = null ; switch ( xmlReader . getEventType ( ) ) { case XMLStreamConstants . START_ELEMENT : case XMLStreamConstants . END_ELEMENT : namespaceUri = xmlReader . getNamespaceURI ( ) ; localName = xmlReader . getLocalName ( ) ; break ; default : localName = StringUtils . EMPTY ; break ; } return namespaces . get ( namespaceUri ) + ":" + localName ; }
|
Helper method for getting qualified name from stax reader given a set of specified schema namespaces
|
38,010
|
public static DateTime fromString ( String rfc3339Timestamp ) { if ( rfc3339Timestamp == null ) { return null ; } DateTime dateTime = new DateTime ( rfc3339Timestamp , DateTimeZone . UTC ) ; return dateTime ; }
|
Helper for parsing rfc3339 compliant timestamp from string
|
38,011
|
private ServerConfiguration loadConfiguration ( ServerConfigurationReader configurationReader ) throws ConfigurationException { ServerConfiguration configuration = configurationReader . read ( ) ; return configuration ; }
|
Bootstrap mechanism that loads the configuration for the server object based on the specified configuration reading mechanism .
|
38,012
|
public Collection < String > getRelatedDetectionSystems ( DetectionSystem detectionSystem ) { Collection < String > relatedDetectionSystems = new HashSet < String > ( ) ; relatedDetectionSystems . add ( detectionSystem . getDetectionSystemId ( ) ) ; if ( correlationSets != null ) { for ( CorrelationSet correlationSet : correlationSets ) { if ( correlationSet . getClientApplications ( ) != null ) { if ( correlationSet . getClientApplications ( ) . contains ( detectionSystem . getDetectionSystemId ( ) ) ) { relatedDetectionSystems . addAll ( correlationSet . getClientApplications ( ) ) ; } } } } return relatedDetectionSystems ; }
|
Find related detection systems based on a given detection system . This simply means those systems that have been configured along with the specified system id as part of a correlation set .
|
38,013
|
private Collection < String > buildTopicNames ( Response response ) { Collection < String > topicNames = new HashSet < > ( ) ; Collection < String > detectionSystemNames = appSensorServer . getConfiguration ( ) . getRelatedDetectionSystems ( response . getDetectionSystem ( ) ) ; for ( String detectionSystemName : detectionSystemNames ) { topicNames . add ( KafkaUtils . buildResponseTopicName ( detectionSystemName ) ) ; } return topicNames ; }
|
build the appropriate topic names to send this response to based on related detection systems
|
38,014
|
public void analyze ( Response response ) { if ( response != null ) { logger . info ( "NO-OP Response for user <" + response . getUser ( ) . getUsername ( ) + "> - should be executing response action " + response . getAction ( ) ) ; } }
|
This method simply logs responses .
|
38,015
|
public Collection < Response > findResponses ( SearchCriteria criteria , Collection < Response > responses ) { if ( criteria == null ) { throw new IllegalArgumentException ( "criteria must be non-null" ) ; } Collection < Response > matches = new ArrayList < Response > ( ) ; User user = criteria . getUser ( ) ; Collection < String > detectionSystemIds = criteria . getDetectionSystemIds ( ) ; DateTime earliest = DateUtils . fromString ( criteria . getEarliest ( ) ) ; for ( Response response : responses ) { boolean userMatch = ( user != null ) ? user . equals ( response . getUser ( ) ) : true ; boolean detectionSystemMatch = ( detectionSystemIds != null && detectionSystemIds . size ( ) > 0 ) ? detectionSystemIds . contains ( response . getDetectionSystem ( ) . getDetectionSystemId ( ) ) : true ; DateTime responseTimestamp = DateUtils . fromString ( response . getTimestamp ( ) ) ; boolean earliestMatch = ( earliest != null ) ? ( earliest . isBefore ( responseTimestamp ) || earliest . isEqual ( responseTimestamp ) ) : true ; if ( userMatch && detectionSystemMatch && earliestMatch ) { matches . add ( response ) ; } } return matches ; }
|
Finder for responses in the ResponseStore
|
38,016
|
private ClientConfiguration loadConfiguration ( ClientConfigurationReader configurationReader ) throws ConfigurationException { ClientConfiguration configuration = configurationReader . read ( ) ; return configuration ; }
|
Bootstrap mechanism that loads the configuration for the client object based on the specified configuration reading mechanism .
|
38,017
|
private Collection < String > buildQueueNames ( Response response ) { Collection < String > queueNames = new HashSet < > ( ) ; Collection < String > detectionSystemNames = appSensorServer . getConfiguration ( ) . getRelatedDetectionSystems ( response . getDetectionSystem ( ) ) ; for ( String detectionSystemName : detectionSystemNames ) { queueNames . add ( RabbitMqUtils . buildResponseQueueName ( detectionSystemName ) ) ; } return queueNames ; }
|
build the appropriate queues to send this response to based on related detection systems
|
38,018
|
protected String encodeCEFHeader ( String text ) { String encoded = text ; encoded = encoded . replace ( "\\" , "\\\\" ) ; encoded = encoded . replace ( "|" , "\\|" ) ; encoded = encoded . replace ( "\r" , "" ) ; encoded = encoded . replace ( "\n" , "" ) ; return encoded ; }
|
header needs to encode | \ \ r \ n
|
38,019
|
protected String encodeCEFExtension ( String text ) { String encoded = text ; encoded = encoded . replace ( "\\" , "\\\\" ) ; encoded = encoded . replace ( "=" , "\\=" ) ; encoded = encoded . replace ( "\r" , "" ) ; encoded = encoded . replace ( "\n" , "" ) ; return encoded ; }
|
extension needs to encode \ = \ r \ n
|
38,020
|
public void analyze ( Response response ) { if ( response == null ) { return ; } if ( ResponseHandler . LOG . equals ( response . getAction ( ) ) ) { logger . info ( "Handling <log> response for user <{}>" , response . getUser ( ) . getUsername ( ) ) ; } else { logger . info ( "Delegating response for user <{}> to configured response handler <{}>" , response . getUser ( ) . getUsername ( ) , responseHandler . getClass ( ) . getName ( ) ) ; responseHandler . handle ( response ) ; } }
|
This method simply logs or executes responses .
|
38,021
|
public long next ( ) { long currentTime = System . currentTimeMillis ( ) ; long counter ; synchronized ( this ) { if ( currentTime < referenceTime ) { throw new RuntimeException ( String . format ( "Last referenceTime %s is after reference time %s" , referenceTime , currentTime ) ) ; } else if ( currentTime > referenceTime ) { this . sequence = 0 ; } else { if ( this . sequence < Snowflake . MAX_SEQUENCE ) { this . sequence ++ ; } else { throw new RuntimeException ( "Sequence exhausted at " + this . sequence ) ; } } counter = this . sequence ; referenceTime = currentTime ; } return currentTime << NODE_SHIFT << SEQ_SHIFT | node << SEQ_SHIFT | counter ; }
|
Generates a k - ordered unique 64 - bit integer . Subsequent invocations of this method will produce increasing integer values .
|
38,022
|
public void addTimexAnnotation ( String timexType , int begin , int end , Sentence sentence , String timexValue , String timexQuant , String timexFreq , String timexMod , String emptyValue , String timexId , String foundByRule , JCas jcas ) { Timex3 annotation = new Timex3 ( jcas ) ; annotation . setBegin ( begin ) ; annotation . setEnd ( end ) ; annotation . setFilename ( sentence . getFilename ( ) ) ; annotation . setSentId ( sentence . getSentenceId ( ) ) ; annotation . setEmptyValue ( emptyValue ) ; FSIterator iterToken = jcas . getAnnotationIndex ( Token . type ) . subiterator ( sentence ) ; String allTokIds = "" ; while ( iterToken . hasNext ( ) ) { Token tok = ( Token ) iterToken . next ( ) ; if ( tok . getBegin ( ) <= begin && tok . getEnd ( ) > begin ) { annotation . setFirstTokId ( tok . getTokenId ( ) ) ; allTokIds = "BEGIN< + tok . getTokenId ( ) ; } if ( ( tok . getBegin ( ) > begin ) && ( tok . getEnd ( ) <= end ) ) { allTokIds = allTokIds + "< + tok . getTokenId ( ) ; } } annotation . setAllTokIds ( allTokIds ) ; annotation . setTimexType ( timexType ) ; annotation . setTimexValue ( timexValue ) ; annotation . setTimexId ( timexId ) ; annotation . setFoundByRule ( foundByRule ) ; if ( ( timexType . equals ( "DATE" ) ) || ( timexType . equals ( "TIME" ) ) ) { if ( ( timexValue . startsWith ( "X" ) ) || ( timexValue . startsWith ( "UNDEF" ) ) ) { annotation . setFoundByRule ( foundByRule + "-relative" ) ; } else { annotation . setFoundByRule ( foundByRule + "-explicit" ) ; } } if ( ! ( timexQuant == null ) ) { annotation . setTimexQuant ( timexQuant ) ; } if ( ! ( timexFreq == null ) ) { annotation . setTimexFreq ( timexFreq ) ; } if ( ! ( timexMod == null ) ) { annotation . setTimexMod ( timexMod ) ; } annotation . addToIndexes ( ) ; this . timex_counter ++ ; Logger . printDetail ( annotation . getTimexId ( ) + "EXTRACTION PHASE: " + " found by:" + annotation . getFoundByRule ( ) + " text:" + annotation . getCoveredText ( ) ) ; Logger . printDetail ( annotation . getTimexId ( ) + "NORMALIZATION PHASE:" + " found by:" + annotation . getFoundByRule ( ) + " text:" + annotation . getCoveredText ( ) + " value:" + annotation . getTimexValue ( ) ) ; }
|
Add timex annotation to CAS object .
|
38,023
|
public void specifyAmbiguousValues ( JCas jcas ) { List < Timex3 > linearDates = new ArrayList < Timex3 > ( ) ; FSIterator iterTimex = jcas . getAnnotationIndex ( Timex3 . type ) . iterator ( ) ; while ( iterTimex . hasNext ( ) ) { Timex3 timex = ( Timex3 ) iterTimex . next ( ) ; if ( timex . getTimexType ( ) . equals ( "DATE" ) || timex . getTimexType ( ) . equals ( "TIME" ) ) { linearDates . add ( timex ) ; } if ( timex . getTimexType ( ) . equals ( "DURATION" ) && ! timex . getEmptyValue ( ) . equals ( "" ) ) { linearDates . add ( timex ) ; } } for ( int i = 0 ; i < linearDates . size ( ) ; i ++ ) { Timex3 t_i = ( Timex3 ) linearDates . get ( i ) ; String value_i = t_i . getTimexValue ( ) ; String valueNew = value_i ; if ( t_i . getTimexType ( ) . equals ( "TIME" ) || t_i . getTimexType ( ) . equals ( "DATE" ) ) valueNew = specifyAmbiguousValuesString ( value_i , t_i , i , linearDates , jcas ) ; if ( t_i . getEmptyValue ( ) != null && t_i . getEmptyValue ( ) . length ( ) > 0 ) { String emptyValueNew = specifyAmbiguousValuesString ( t_i . getEmptyValue ( ) , t_i , i , linearDates , jcas ) ; t_i . setEmptyValue ( emptyValueNew ) ; } t_i . removeFromIndexes ( ) ; Logger . printDetail ( t_i . getTimexId ( ) + " DISAMBIGUATION PHASE: foundBy:" + t_i . getFoundByRule ( ) + " text:" + t_i . getCoveredText ( ) + " value:" + t_i . getTimexValue ( ) + " NEW value:" + valueNew ) ; t_i . setTimexValue ( valueNew ) ; t_i . addToIndexes ( ) ; linearDates . set ( i , t_i ) ; } }
|
Under - specified values are disambiguated here . Only Timexes of types date and time can be under - specified .
|
38,024
|
public boolean checkPosConstraint ( Sentence s , String posConstraint , MatchResult m , JCas jcas ) { Pattern paConstraint = Pattern . compile ( "group\\(([0-9]+)\\):(.*?):" ) ; for ( MatchResult mr : Toolbox . findMatches ( paConstraint , posConstraint ) ) { int groupNumber = Integer . parseInt ( mr . group ( 1 ) ) ; int tokenBegin = s . getBegin ( ) + m . start ( groupNumber ) ; int tokenEnd = s . getBegin ( ) + m . end ( groupNumber ) ; String pos = mr . group ( 2 ) ; String pos_as_is = getPosFromMatchResult ( tokenBegin , tokenEnd , s , jcas ) ; if ( pos_as_is . matches ( pos ) ) { Logger . printDetail ( "POS CONSTRAINT IS VALID: pos should be " + pos + " and is " + pos_as_is ) ; } else { return false ; } } return true ; }
|
Check whether the part of speech constraint defined in a rule is satisfied .
|
38,025
|
private Boolean isValidDCT ( JCas jcas ) { FSIterator dctIter = jcas . getAnnotationIndex ( Dct . type ) . iterator ( ) ; if ( ! dctIter . hasNext ( ) ) { return true ; } else { Dct dct = ( Dct ) dctIter . next ( ) ; String dctVal = dct . getValue ( ) ; if ( dctVal == null ) return false ; if ( dctVal . matches ( "\\d{8}" ) || dctVal . matches ( "\\d{4}.\\d{2}.\\d{2}.*" ) ) { return true ; } else { return false ; } } }
|
Check whether or not a jcas object has a correct DCT value . If there is no DCT present we canonically return true since fallback calculation takes care of that scenario .
|
38,026
|
void startScanSFeaturesAt ( List seq , int pos ) { sFeatures . clear ( ) ; sFeatureIdx = 0 ; Observation obsr = ( Observation ) seq . get ( pos ) ; for ( int i = 0 ; i < obsr . cps . length ; i ++ ) { Element elem = ( Element ) dict . dict . get ( new Integer ( obsr . cps [ i ] ) ) ; if ( elem == null ) { continue ; } if ( ! ( elem . isScanned ) ) { Iterator it = elem . lbCntFidxes . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Integer label = ( Integer ) it . next ( ) ; CountFeatureIdx cntFidx = ( CountFeatureIdx ) elem . lbCntFidxes . get ( label ) ; if ( cntFidx . fidx >= 0 ) { Feature sF = new Feature ( ) ; sF . sFeature1Init ( label . intValue ( ) , obsr . cps [ i ] ) ; sF . idx = cntFidx . fidx ; elem . cpFeatures . add ( sF ) ; } } elem . isScanned = true ; } for ( int j = 0 ; j < elem . cpFeatures . size ( ) ; j ++ ) { sFeatures . add ( elem . cpFeatures . get ( j ) ) ; } } }
|
Start scan s features at .
|
38,027
|
Feature nextSFeature ( ) { Feature sF = ( Feature ) sFeatures . get ( sFeatureIdx ) ; sFeatureIdx ++ ; return sF ; }
|
Next s feature .
|
38,028
|
Feature nextEFeature ( ) { Feature eF = ( Feature ) eFeatures . get ( eFeatureIdx ) ; eFeatureIdx ++ ; return eF ; }
|
Next e feature .
|
38,029
|
public void updateFeatures ( ) { for ( int i = 0 ; i < feaGen . features . size ( ) ; i ++ ) { Feature f = ( Feature ) feaGen . features . get ( i ) ; f . wgt = lambda [ f . idx ] ; } }
|
Update features .
|
38,030
|
public void initInference ( ) { if ( lambda == null ) { System . out . println ( "numFetures: " + feaGen . numFeatures ( ) ) ; lambda = new double [ feaGen . numFeatures ( ) + 1 ] ; for ( int i = 0 ; i < feaGen . features . size ( ) ; i ++ ) { Feature f = ( Feature ) feaGen . features . get ( i ) ; lambda [ f . idx ] = f . wgt ; } } }
|
Inits the inference .
|
38,031
|
public void compMult ( DoubleVector dv ) { for ( int i = 0 ; i < len ; i ++ ) { vect [ i ] *= dv . vect [ i ] ; } }
|
Comp mult .
|
38,032
|
public static int findFirstOf ( String container , String chars , int begin ) { int minIdx = - 1 ; for ( int i = 0 ; i < chars . length ( ) && i >= 0 ; ++ i ) { int idx = container . indexOf ( chars . charAt ( i ) , begin ) ; if ( ( idx < minIdx && idx != - 1 ) || minIdx == - 1 ) { minIdx = idx ; } } return minIdx ; }
|
Find the first occurrence .
|
38,033
|
public static int findLastOf ( String container , String charSeq , int begin ) { for ( int i = begin ; i < container . length ( ) && i >= 0 ; -- i ) { if ( charSeq . contains ( "" + container . charAt ( i ) ) ) return i ; } return - 1 ; }
|
Find the last occurrence .
|
38,034
|
public static int findFirstNotOf ( String container , String chars , int begin ) { for ( int i = begin ; i < container . length ( ) && i >= 0 ; ++ i ) if ( ! chars . contains ( "" + container . charAt ( i ) ) ) return i ; return - 1 ; }
|
Find the first occurrence of characters not in the charSeq from begin
|
38,035
|
public static int findLastNotOf ( String container , String charSeq , int end ) { for ( int i = end ; i < container . length ( ) && i >= 0 ; -- i ) { if ( ! charSeq . contains ( "" + container . charAt ( i ) ) ) return i ; } return - 1 ; }
|
Find last not of .
|
38,036
|
public static boolean containNumber ( String str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( Character . isDigit ( str . charAt ( i ) ) ) { return true ; } } return false ; }
|
Contain number .
|
38,037
|
public static boolean isAllNumber ( String str ) { boolean hasNumber = false ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! ( Character . isDigit ( str . charAt ( i ) ) || str . charAt ( i ) == '.' || str . charAt ( i ) == ',' || str . charAt ( i ) == '%' || str . charAt ( i ) == '$' || str . charAt ( i ) == '_' ) ) { return false ; } else if ( Character . isDigit ( str . charAt ( i ) ) ) hasNumber = true ; } if ( hasNumber == true ) return true ; else return false ; }
|
Checks if is all number .
|
38,038
|
public static boolean isFirstCap ( String str ) { if ( isAllCap ( str ) ) return false ; if ( str . length ( ) > 0 && Character . isLetter ( str . charAt ( 0 ) ) && Character . isUpperCase ( str . charAt ( 0 ) ) ) { return true ; } return false ; }
|
Checks if is first cap .
|
38,039
|
public static boolean endsWithPunc ( String str ) { if ( str . endsWith ( "." ) || str . endsWith ( "?" ) || str . endsWith ( "!" ) || str . endsWith ( "," ) || str . endsWith ( ":" ) || str . endsWith ( "\"" ) || str . endsWith ( "'" ) || str . endsWith ( "''" ) || str . endsWith ( ";" ) ) { return true ; } return false ; }
|
Ends with sign .
|
38,040
|
public static boolean endsWithStop ( String str ) { if ( str . endsWith ( "." ) || str . endsWith ( "?" ) || str . endsWith ( "!" ) ) { return true ; } return false ; }
|
Ends with stop .
|
38,041
|
public static int countStops ( String str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '.' || str . charAt ( i ) == '?' || str . charAt ( i ) == '!' ) { count ++ ; } } return count ; }
|
Count stops .
|
38,042
|
public static int countPuncs ( String str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '.' || str . charAt ( i ) == '?' || str . charAt ( i ) == '!' || str . charAt ( i ) == ',' || str . charAt ( i ) == ':' || str . charAt ( i ) == ';' ) { count ++ ; } } return count ; }
|
Count signs .
|
38,043
|
public static boolean isStop ( String str ) { if ( str . compareTo ( "." ) == 0 ) { return true ; } if ( str . compareTo ( "?" ) == 0 ) { return true ; } if ( str . compareTo ( "!" ) == 0 ) { return true ; } return false ; }
|
Checks if is stop .
|
38,044
|
public static boolean isPunc ( String str ) { if ( str == null ) return false ; str = str . trim ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( Character . isDigit ( c ) || Character . isLetter ( c ) ) { return false ; } } return true ; }
|
Checks if is punctuation .
|
38,045
|
public static String capitalizeWord ( String s ) { if ( ( s == null ) || ( s . length ( ) == 0 ) ) { return s ; } return s . substring ( 0 , 1 ) . toUpperCase ( ) + s . substring ( 1 ) . toLowerCase ( ) ; }
|
Capitalises the first letter of a given string .
|
38,046
|
public static String sort ( String s ) { char [ ] chars = s . toCharArray ( ) ; Arrays . sort ( chars ) ; return new String ( chars ) ; }
|
Sorts the characters in the specified string .
|
38,047
|
public String convert ( String text ) { String ret = text ; if ( cpsUni2Uni == null ) return ret ; Iterator < String > it = cpsUni2Uni . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { String cpsChar = it . next ( ) ; ret = ret . replaceAll ( cpsChar , cpsUni2Uni . get ( cpsChar ) ) ; } return ret ; }
|
Convert a vietnamese string with composite unicode encoding to unicode encoding .
|
38,048
|
public static void printDetail ( Class < ? > c , String msg ) { if ( Logger . printDetails ) { String preamble ; if ( c != null ) preamble = "[" + c . getSimpleName ( ) + "]" ; else preamble = "" ; synchronized ( System . err ) { System . err . println ( preamble + " " + msg ) ; } } }
|
print DEBUG level information with package name
|
38,049
|
public static void printError ( Class < ? > c , String msg ) { String preamble ; if ( c != null ) preamble = "[" + c . getSimpleName ( ) + "]" ; else preamble = "" ; synchronized ( System . err ) { System . err . println ( preamble + " " + msg ) ; } }
|
print an ERROR - Level message with package name
|
38,050
|
protected boolean readFeatureParameters ( Element node ) { try { NodeList childrent = node . getChildNodes ( ) ; cpnames = new Vector < String > ( ) ; paras = new Vector < Vector < Integer > > ( ) ; for ( int i = 0 ; i < childrent . getLength ( ) ; i ++ ) if ( childrent . item ( i ) instanceof Element ) { Element child = ( Element ) childrent . item ( i ) ; String value = child . getAttribute ( "value" ) ; String [ ] parastr = value . split ( ":" ) ; Vector < Integer > para = new Vector < Integer > ( ) ; for ( int j = 3 ; j < parastr . length ; ++ j ) { para . add ( Integer . parseInt ( parastr [ j ] ) ) ; } cpnames . add ( parastr [ 2 ] ) ; paras . add ( para ) ; } } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; return false ; } return true ; }
|
Read feature parameters .
|
38,051
|
public static Vector < Element > readFeatureNodes ( String templateFile ) { Vector < Element > feaTypes = new Vector < Element > ( ) ; try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; InputStream feaTplStream = new FileInputStream ( templateFile ) ; Document doc = builder . parse ( feaTplStream ) ; Element root = doc . getDocumentElement ( ) ; NodeList childrent = root . getChildNodes ( ) ; for ( int i = 0 ; i < childrent . getLength ( ) ; i ++ ) if ( childrent . item ( i ) instanceof Element ) { Element child = ( Element ) childrent . item ( i ) ; feaTypes . add ( child ) ; } } catch ( Exception e ) { System . out . println ( "Reading featuretemplate fail " + e . getMessage ( ) ) ; e . printStackTrace ( ) ; } return feaTypes ; }
|
Read feature nodes .
|
38,052
|
public void generateTrainData ( String inputPath , String outputPath ) { try { File file = new File ( inputPath ) ; ArrayList < Sentence > data = new ArrayList < Sentence > ( ) ; if ( file . isFile ( ) ) { System . out . println ( "Reading " + file . getName ( ) ) ; data = ( ArrayList < Sentence > ) reader . readFile ( inputPath ) ; } else if ( file . isDirectory ( ) ) { String [ ] filenames = file . list ( ) ; for ( String filename : filenames ) { System . out . println ( "Reading " + filename ) ; ArrayList < Sentence > temp = ( ArrayList < Sentence > ) reader . readFile ( file . getPath ( ) + File . separator + filename ) ; data . addAll ( temp ) ; } } String result = "" ; System . out . println ( data . size ( ) + "sentences read" ) ; for ( int i = 0 ; i < data . size ( ) ; ++ i ) { if ( i % 20 == 0 ) System . out . println ( "Finished " + i + " in " + data . size ( ) + " sentences" ) ; Sentence sent = data . get ( i ) ; for ( int j = 0 ; j < sent . size ( ) ; ++ j ) { String line = "" ; String context = tagger . getContextStr ( sent , j ) ; line = context + " " ; line += sent . getTagAt ( j ) ; result += line + "\n" ; } result += "\n" ; } BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( outputPath + ".tagged" ) , "UTF-8" ) ) ; writer . write ( result ) ; writer . close ( ) ; } catch ( Exception e ) { System . out . println ( "Error while generating training data" ) ; System . out . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } }
|
Generate train data .
|
38,053
|
public String getContextStr ( Sentence sent , int wordIdx ) { String cpStr = "" ; for ( int i = 0 ; i < cntxGenVector . size ( ) ; ++ i ) { String [ ] context = cntxGenVector . get ( i ) . getContext ( sent , wordIdx ) ; if ( context != null ) { for ( int j = 0 ; j < context . length ; ++ j ) { if ( context [ j ] . trim ( ) . equals ( "" ) ) continue ; cpStr += context [ j ] + " " ; } } } return cpStr . trim ( ) ; }
|
Gets the context str .
|
38,054
|
public void writeCpMaps ( Dictionary dict , PrintWriter fout ) throws IOException { Iterator it = null ; if ( cpStr2Int == null ) { return ; } int count = 0 ; for ( it = cpStr2Int . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String cpStr = ( String ) it . next ( ) ; Integer cpInt = ( Integer ) cpStr2Int . get ( cpStr ) ; Element elem = ( Element ) dict . dict . get ( cpInt ) ; if ( elem != null ) { if ( elem . chosen == 1 ) { count ++ ; } } } fout . println ( Integer . toString ( count ) ) ; for ( it = cpStr2Int . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String cpStr = ( String ) it . next ( ) ; Integer cpInt = ( Integer ) cpStr2Int . get ( cpStr ) ; Element elem = ( Element ) dict . dict . get ( cpInt ) ; if ( elem != null ) { if ( elem . chosen == 1 ) { fout . println ( cpStr + " " + cpInt . toString ( ) ) ; } } } fout . println ( Option . modelSeparator ) ; }
|
Write cp maps .
|
38,055
|
public void writeLbMaps ( PrintWriter fout ) throws IOException { if ( lbStr2Int == null ) { return ; } fout . println ( Integer . toString ( lbStr2Int . size ( ) ) ) ; for ( Iterator it = lbStr2Int . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String lbStr = ( String ) it . next ( ) ; Integer lbInt = ( Integer ) lbStr2Int . get ( lbStr ) ; fout . println ( lbStr + " " + lbInt . toString ( ) ) ; } fout . println ( Option . modelSeparator ) ; }
|
Write lb maps .
|
38,056
|
public void readTstData ( String dataFile ) { if ( tstData != null ) { tstData . clear ( ) ; } else { tstData = new ArrayList ( ) ; } BufferedReader fin = null ; try { fin = new BufferedReader ( new InputStreamReader ( new FileInputStream ( dataFile ) , "UTF-8" ) ) ; System . out . println ( "Reading testing data ..." ) ; String line ; while ( ( line = fin . readLine ( ) ) != null ) { StringTokenizer strTok = new StringTokenizer ( line , " \t\r\n" ) ; int len = strTok . countTokens ( ) ; if ( len <= 1 ) { continue ; } List strCps = new ArrayList ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { strCps . add ( strTok . nextToken ( ) ) ; } String labelStr = strTok . nextToken ( ) ; List intCps = new ArrayList ( ) ; for ( int i = 0 ; i < strCps . size ( ) ; i ++ ) { String cpStr = ( String ) strCps . get ( i ) ; Integer cpInt = ( Integer ) cpStr2Int . get ( cpStr ) ; if ( cpInt != null ) { intCps . add ( cpInt ) ; } else { } } Integer labelInt = ( Integer ) lbStr2Int . get ( labelStr ) ; if ( labelInt == null ) { System . out . println ( "Reading testing observation, label not found or invalid" ) ; return ; } int [ ] cps = new int [ intCps . size ( ) ] ; for ( int i = 0 ; i < cps . length ; i ++ ) { cps [ i ] = ( ( Integer ) intCps . get ( i ) ) . intValue ( ) ; } Observation obsr = new Observation ( labelInt . intValue ( ) , cps ) ; tstData . add ( obsr ) ; } System . out . println ( "Reading " + Integer . toString ( tstData . size ( ) ) + " testing data examples completed!" ) ; } catch ( IOException e ) { System . out . println ( e . toString ( ) ) ; return ; } option . numTestExps = tstData . size ( ) ; }
|
Read tst data .
|
38,057
|
public void setFilename ( String v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_filename == null ) jcasType . jcas . throwFeatMissing ( "filename" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_filename , v ) ; }
|
setter for filename - sets
|
38,058
|
public int getTokId ( ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_tokId == null ) jcasType . jcas . throwFeatMissing ( "tokId" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; return jcasType . ll_cas . ll_getIntValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_tokId ) ; }
|
getter for tokId - gets
|
38,059
|
public void setTokId ( int v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_tokId == null ) jcasType . jcas . throwFeatMissing ( "tokId" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_tokId , v ) ; }
|
setter for tokId - sets
|
38,060
|
public String getEventId ( ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_eventId == null ) jcasType . jcas . throwFeatMissing ( "eventId" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_eventId ) ; }
|
getter for eventId - gets
|
38,061
|
public void setEventId ( String v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_eventId == null ) jcasType . jcas . throwFeatMissing ( "eventId" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_eventId , v ) ; }
|
setter for eventId - sets
|
38,062
|
public int getEventInstanceId ( ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_eventInstanceId == null ) jcasType . jcas . throwFeatMissing ( "eventInstanceId" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; return jcasType . ll_cas . ll_getIntValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_eventInstanceId ) ; }
|
getter for eventInstanceId - gets
|
38,063
|
public void setEventInstanceId ( int v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_eventInstanceId == null ) jcasType . jcas . throwFeatMissing ( "eventInstanceId" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_eventInstanceId , v ) ; }
|
setter for eventInstanceId - sets
|
38,064
|
public String getModality ( ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_modality == null ) jcasType . jcas . throwFeatMissing ( "modality" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_modality ) ; }
|
getter for modality - gets
|
38,065
|
public void setModality ( String v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_modality == null ) jcasType . jcas . throwFeatMissing ( "modality" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_modality , v ) ; }
|
setter for modality - sets
|
38,066
|
public String getTense ( ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_tense == null ) jcasType . jcas . throwFeatMissing ( "tense" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_tense ) ; }
|
getter for tense - gets
|
38,067
|
public void setTense ( String v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_tense == null ) jcasType . jcas . throwFeatMissing ( "tense" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_tense , v ) ; }
|
setter for tense - sets
|
38,068
|
public void setToken ( Token v ) { if ( Event_Type . featOkTst && ( ( Event_Type ) jcasType ) . casFeat_token == null ) jcasType . jcas . throwFeatMissing ( "token" , "de.unihd.dbs.uima.types.heideltime.Event" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Event_Type ) jcasType ) . casFeatCode_token , jcasType . ll_cas . ll_getFSRef ( v ) ) ; }
|
setter for token - sets
|
38,069
|
public void addTWord ( String word , String tag ) { TWord tword = new TWord ( word , tag ) ; sentence . add ( tword ) ; }
|
Adds the t word .
|
38,070
|
public void initialize ( Language language , String hunpos_path , String hunpos_model_path , Boolean annotateTokens , Boolean annotateSentences , Boolean annotatePOS ) { this . initialize ( new HunPosTaggerContext ( language , hunpos_path , hunpos_model_path , annotateTokens , annotateSentences , annotatePOS ) ) ; }
|
Initializes the wrapper with the given language and settings what to annotate . Sentences will not be annotated even if set to True unless POS annotation occurs .
|
38,071
|
public void initialize ( UimaContext aContext ) { annotate_tokens = ( Boolean ) aContext . getConfigParameterValue ( PARAM_ANNOTATE_TOKENS ) ; annotate_sentences = ( Boolean ) aContext . getConfigParameterValue ( PARAM_ANNOTATE_SENTENCES ) ; annotate_pos = ( Boolean ) aContext . getConfigParameterValue ( PARAM_ANNOTATE_POS ) ; this . language = Language . getLanguageFromString ( ( String ) aContext . getConfigParameterValue ( PARAM_LANGUAGE ) ) ; String hunposPath = ( String ) aContext . getConfigParameterValue ( PARAM_PATH ) ; String modelPath = ( String ) aContext . getConfigParameterValue ( PARAM_MODEL_PATH ) ; HunPosWrapper . initialize ( modelPath , hunposPath ) ; }
|
Initializes the wrapper from UIMA context . See other initialize method for parameters required within context .
|
38,072
|
public boolean init ( String modelDir ) { try { classifier = new Classification ( modelDir ) ; feaGen = new FeatureGenerator ( ) ; classifier . init ( ) ; return true ; } catch ( Exception e ) { System . out . println ( "Error while initilizing classifier: " + e . getMessage ( ) ) ; return false ; } }
|
Creates a new instance of JVnSenSegmenter .
|
38,073
|
public static void main ( String args [ ] ) { if ( args . length != 4 ) { displayHelp ( ) ; System . exit ( 1 ) ; } try { JVnSenSegmenter senSegmenter = new JVnSenSegmenter ( ) ; senSegmenter . init ( args [ 1 ] ) ; String option = args [ 2 ] ; if ( option . equalsIgnoreCase ( "-inputfile" ) ) { senSegmentFile ( args [ 3 ] , args [ 3 ] + ".sent" , senSegmenter ) ; } else if ( option . equalsIgnoreCase ( "-inputdir" ) ) { File inputDir = new File ( args [ 3 ] ) ; File [ ] childrent = inputDir . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".txt" ) ; } } ) ; for ( int i = 0 ; i < childrent . length ; ++ i ) { System . out . println ( "Segmenting sentences in " + childrent [ i ] ) ; senSegmentFile ( childrent [ i ] . getPath ( ) , childrent [ i ] . getPath ( ) + ".sent" , senSegmenter ) ; } } else displayHelp ( ) ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; return ; } }
|
main method of JVnSenSegmenter to use this tool from command line .
|
38,074
|
private static void senSegmentFile ( String infile , String outfile , JVnSenSegmenter senSegmenter ) { try { BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( infile ) , "UTF-8" ) ) ; BufferedWriter out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( outfile ) , "UTF-8" ) ) ; String para = "" , line = "" , text = "" ; while ( ( line = in . readLine ( ) ) != null ) { if ( ! line . equals ( "" ) ) { if ( line . charAt ( 0 ) == '#' ) { text += line + "\n" ; continue ; } para = senSegmenter . senSegment ( line ) . trim ( ) ; text += para . trim ( ) + "\n\n" ; } else { text += "\n" ; } } text = text . trim ( ) ; out . write ( text ) ; out . newLine ( ) ; in . close ( ) ; out . close ( ) ; } catch ( Exception e ) { System . out . println ( "Error in sensegment file " + infile ) ; } }
|
Segment sentences .
|
38,075
|
public static void loadVietnameseDict ( String filename ) { try { FileInputStream in = new FileInputStream ( filename ) ; if ( hsVietnameseDict == null ) { hsVietnameseDict = new HashSet ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in , "UTF-8" ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . substring ( 0 , 2 ) . equals ( "##" ) ) { String word = line . substring ( 2 ) ; word = word . toLowerCase ( ) ; hsVietnameseDict . add ( word ) ; } } } } catch ( Exception e ) { System . err . print ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } }
|
Load vietnamese dict .
|
38,076
|
public static void loadViPersonalNames ( String filename ) { try { FileInputStream in = new FileInputStream ( filename ) ; if ( hsViFamilyNames == null ) { hsViFamilyNames = new HashSet ( ) ; hsViLastNames = new HashSet ( ) ; hsViMiddleNames = new HashSet ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in , "UTF-8" ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . equals ( "" ) ) continue ; int idxSpace = line . indexOf ( ' ' ) ; int lastIdxSpace = line . lastIndexOf ( ' ' ) ; if ( idxSpace != - 1 ) { String strFamilyName = line . substring ( 0 , idxSpace ) ; hsViFamilyNames . add ( strFamilyName ) ; } if ( ( idxSpace != - 1 ) && ( lastIdxSpace > idxSpace + 1 ) ) { String strMiddleName = line . substring ( idxSpace + 1 , lastIdxSpace - 1 ) ; hsViMiddleNames . add ( strMiddleName ) ; } if ( lastIdxSpace != - 1 ) { String strLastName = line . substring ( lastIdxSpace + 1 , line . length ( ) ) ; hsViLastNames . add ( strLastName ) ; } } in . close ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; System . err . print ( e . getMessage ( ) ) ; } }
|
Load vi personal names .
|
38,077
|
public static void loadViLocationList ( String filename ) { try { FileInputStream in = new FileInputStream ( filename ) ; if ( hsViLocations == null ) { hsViLocations = new HashSet ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in , "UTF-8" ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { String word = line . trim ( ) ; hsViLocations . add ( word ) ; } } } catch ( Exception e ) { System . err . print ( e . getMessage ( ) ) ; } }
|
Load vi location list .
|
38,078
|
public String getFilename ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_filename == null ) jcasType . jcas . throwFeatMissing ( "filename" , "de.unihd.dbs.uima.types.heideltime.Token" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_filename ) ; }
|
getter for filename - gets
|
38,079
|
public int getTokenId ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_tokenId == null ) jcasType . jcas . throwFeatMissing ( "tokenId" , "de.unihd.dbs.uima.types.heideltime.Token" ) ; return jcasType . ll_cas . ll_getIntValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_tokenId ) ; }
|
getter for tokenId - gets
|
38,080
|
public void setTokenId ( int v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_tokenId == null ) jcasType . jcas . throwFeatMissing ( "tokenId" , "de.unihd.dbs.uima.types.heideltime.Token" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_tokenId , v ) ; }
|
setter for tokenId - sets
|
38,081
|
public void setSentId ( int v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_sentId == null ) jcasType . jcas . throwFeatMissing ( "sentId" , "de.unihd.dbs.uima.types.heideltime.Token" ) ; jcasType . ll_cas . ll_setIntValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_sentId , v ) ; }
|
setter for sentId - sets
|
38,082
|
public String getPos ( ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_pos == null ) jcasType . jcas . throwFeatMissing ( "pos" , "de.unihd.dbs.uima.types.heideltime.Token" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_pos ) ; }
|
getter for pos - gets
|
38,083
|
public void setPos ( String v ) { if ( Token_Type . featOkTst && ( ( Token_Type ) jcasType ) . casFeat_pos == null ) jcasType . jcas . throwFeatMissing ( "pos" , "de.unihd.dbs.uima.types.heideltime.Token" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Token_Type ) jcasType ) . casFeatCode_pos , v ) ; }
|
setter for pos - sets
|
38,084
|
public String getEasterSunday ( int year , int days ) { int K = year / 100 ; int M = 15 + ( ( 3 * K + 3 ) / 4 ) - ( ( 8 * K + 13 ) / 25 ) ; int S = 2 - ( ( 3 * K + 3 ) / 4 ) ; int A = year % 19 ; int D = ( 19 * A + M ) % 30 ; int R = ( D / 29 ) + ( ( D / 28 ) - ( D / 29 ) * ( A / 11 ) ) ; int OG = 21 + D - R ; int SZ = 7 - ( year + ( year / 4 ) + S ) % 7 ; int OE = 7 - ( OG - SZ ) % 7 ; int OS = OG + OE ; SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd" ) ; Calendar c = Calendar . getInstance ( ) ; String date ; if ( OS <= 31 ) { date = String . format ( "%04d-03-%02d" , year , OS ) ; } else { date = String . format ( "%04d-04-%02d" , year , ( OS - 31 ) ) ; } try { c . setTime ( formatter . parse ( date ) ) ; c . add ( Calendar . DAY_OF_MONTH , days ) ; date = formatter . format ( c . getTime ( ) ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } return date ; }
|
Get the date of a day relative to Easter Sunday in a given year . Algorithm used is from the Physikalisch - Technische Bundesanstalt Braunschweig PTB .
|
38,085
|
public String getShroveTideWeekOrthodox ( int year ) { String easterOrthodox = getEasterSundayOrthodox ( year ) ; SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd" ) ; try { Calendar calendar = Calendar . getInstance ( ) ; Date date = formatter . parse ( easterOrthodox ) ; calendar . setTime ( date ) ; calendar . add ( Calendar . DAY_OF_MONTH , - 49 ) ; int shroveTideWeek = calendar . get ( Calendar . WEEK_OF_YEAR ) ; if ( shroveTideWeek < 10 ) { return year + "-W0" + shroveTideWeek ; } return year + "-W" + shroveTideWeek ; } catch ( ParseException pe ) { Logger . printError ( "ParseException:" + pe . getMessage ( ) ) ; return "unknown" ; } }
|
Get the date of the Shrove - Tide week in a given year
|
38,086
|
public String getWeekdayOfMonth ( int number , int weekday , int month , int year ) { return getWeekdayRelativeTo ( String . format ( "%04d-%02d-01" , year , month ) , weekday , number , true ) ; }
|
Get the date of a the first second third etc . weekday in a month
|
38,087
|
public boolean containsKey ( Object key ) { if ( cache . containsKey ( key ) ) return true ; if ( container . containsKey ( key ) ) return true ; Iterator < String > regexKeys = container . keySet ( ) . iterator ( ) ; while ( regexKeys . hasNext ( ) ) { if ( Pattern . matches ( regexKeys . next ( ) , ( String ) key ) ) return true ; } return false ; }
|
checks whether the cache or container contain a specific key then evaluates the container s keys as regexes and checks whether they match the specific key .
|
38,088
|
public boolean containsValue ( Object value ) { if ( cache . containsValue ( value ) ) return true ; if ( container . containsValue ( value ) ) return true ; return false ; }
|
checks whether a specific value is container within either container or cache
|
38,089
|
public Set < Entry < String , T > > entrySet ( ) { HashSet < Entry < String , T > > set = new HashSet < Entry < String , T > > ( ) ; set . addAll ( container . entrySet ( ) ) ; set . addAll ( cache . entrySet ( ) ) ; return set ; }
|
returns a merged entryset containing within both the container and cache entrysets
|
38,090
|
public T get ( Object key ) { if ( key == null ) return null ; T result = null ; if ( ( result = cache . get ( key ) ) != null ) { return result ; } else if ( ( result = container . get ( key ) ) != null ) { return result ; } else { Iterator < Entry < String , T > > regexKeys = container . entrySet ( ) . iterator ( ) ; while ( regexKeys . hasNext ( ) ) { Entry < String , T > entry = regexKeys . next ( ) ; if ( Pattern . matches ( entry . getKey ( ) , ( String ) key ) ) { putCache ( ( String ) key , entry . getValue ( ) ) ; return entry . getValue ( ) ; } } } return null ; }
|
checks whether the requested key has a direct match in either cache or container and if it doesn t also evaluates the container s keyset as regexes to match against the input key and if any of those methods yield a value returns that value if a value is found doing regex evaluation use that regex - key s match as a non - regex key with the regex s value to form a new entry in the cache .
|
38,091
|
public Set < String > keySet ( ) { HashSet < String > set = new HashSet < String > ( ) ; set . addAll ( container . keySet ( ) ) ; set . addAll ( cache . keySet ( ) ) ; return set ; }
|
returns the keysets of both the container and cache hashmaps
|
38,092
|
public T put ( String key , T value ) { return container . put ( key , value ) ; }
|
associates a key with a value in the container hashmap
|
38,093
|
public T putCache ( String key , T value ) { return cache . put ( key , value ) ; }
|
associates a key with a value in the cache hashmap .
|
38,094
|
public Collection < T > values ( ) { HashSet < T > set = new HashSet < T > ( ) ; set . addAll ( container . values ( ) ) ; set . addAll ( cache . values ( ) ) ; return set ; }
|
returns the combined collection of both the values of the container as well as the cache .
|
38,095
|
public PrintWriter openTrainLogFile ( ) { String filename = modelDir + File . separator + trainLogFile ; PrintWriter fout = null ; try { fout = new PrintWriter ( new OutputStreamWriter ( ( new FileOutputStream ( filename ) ) , "UTF-8" ) ) ; } catch ( IOException e ) { System . out . println ( e . toString ( ) ) ; return null ; } return fout ; }
|
Open train log file .
|
38,096
|
public BufferedReader openModelFile ( ) { String filename = modelDir + File . separator + modelFile ; BufferedReader fin = null ; try { fin = new BufferedReader ( new InputStreamReader ( new FileInputStream ( filename ) , "UTF-8" ) ) ; } catch ( IOException e ) { System . out . println ( e . toString ( ) ) ; return null ; } return fin ; }
|
Open model file .
|
38,097
|
public void writeOptions ( PrintWriter fout ) { fout . println ( "OPTION VALUES:" ) ; fout . println ( "==============" ) ; fout . println ( "Model directory: " + modelDir ) ; fout . println ( "Model file: " + modelFile ) ; fout . println ( "Option file: " + optionFile ) ; fout . println ( "Training log file: " + trainLogFile + " (this one)" ) ; fout . println ( "Training data file: " + trainDataFile ) ; fout . println ( "Testing data file: " + testDataFile ) ; fout . println ( "Number of training examples " + Integer . toString ( numTrainExps ) ) ; fout . println ( "Number of testing examples " + Integer . toString ( numTestExps ) ) ; fout . println ( "Number of class labels: " + Integer . toString ( numLabels ) ) ; fout . println ( "Number of context predicates: " + Integer . toString ( numCps ) ) ; fout . println ( "Number of features: " + Integer . toString ( numFeatures ) ) ; fout . println ( "Rare threshold for context predicates: " + Integer . toString ( cpRareThreshold ) ) ; fout . println ( "Rare threshold for features: " + Integer . toString ( fRareThreshold ) ) ; fout . println ( "Number of training iterations: " + Integer . toString ( numIterations ) ) ; fout . println ( "Initial value of feature weights: " + Double . toString ( initLambdaVal ) ) ; fout . println ( "Sigma square: " + Double . toString ( sigmaSquare ) ) ; fout . println ( "Epsilon for convergence: " + Double . toString ( epsForConvergence ) ) ; fout . println ( "Number of corrections in L-BFGS: " + Integer . toString ( mForHessian ) ) ; if ( evaluateDuringTraining ) { fout . println ( "Evaluation during training: true" ) ; } else { fout . println ( "Evaluation during training: false" ) ; } if ( saveBestModel ) { fout . println ( "Save the best model towards testing data: true" ) ; } else { fout . println ( "Save the best model towards testing data: false" ) ; } fout . println ( ) ; }
|
Write options .
|
38,098
|
public static String getXNextDay ( String date , Integer x ) { SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd" ) ; String newDate = "" ; Calendar c = Calendar . getInstance ( ) ; try { c . setTime ( formatter . parse ( date ) ) ; c . add ( Calendar . DAY_OF_MONTH , x ) ; c . getTime ( ) ; newDate = formatter . format ( c . getTime ( ) ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } return newDate ; }
|
get the x - next day of date .
|
38,099
|
public static String getXNextWeek ( String date , Integer x , Language language ) { NormalizationManager nm = NormalizationManager . getInstance ( language , false ) ; String date_no_W = date . replace ( "W" , "" ) ; SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-w" ) ; String newDate = "" ; Calendar c = Calendar . getInstance ( ) ; try { c . setTime ( formatter . parse ( date_no_W ) ) ; c . add ( Calendar . WEEK_OF_YEAR , x ) ; c . getTime ( ) ; newDate = formatter . format ( c . getTime ( ) ) ; newDate = newDate . substring ( 0 , 4 ) + "-W" + nm . getFromNormNumber ( newDate . substring ( 5 ) ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } return newDate ; }
|
get the x - next week of date
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.