signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class LogServerRole { /** * Handles a backup request .
* @ param request the backup request
* @ return future to be completed with the backup response */
public CompletableFuture < BackupResponse > backup ( BackupRequest request ) { } } | logRequest ( request ) ; return CompletableFuture . completedFuture ( logResponse ( BackupResponse . error ( ) ) ) ; |
public class CodaBarReader { /** * Assumes that counters [ position ] is a bar . */
private int toNarrowWidePattern ( int position ) { } } | int end = position + 7 ; if ( end >= counterLength ) { return - 1 ; } int [ ] theCounters = counters ; int maxBar = 0 ; int minBar = Integer . MAX_VALUE ; for ( int j = position ; j < end ; j += 2 ) { int currentCounter = theCounters [ j ] ; if ( currentCounter < minBar ) { minBar = currentCounter ; } if ( currentCounter > maxBar ) { maxBar = currentCounter ; } } int thresholdBar = ( minBar + maxBar ) / 2 ; int maxSpace = 0 ; int minSpace = Integer . MAX_VALUE ; for ( int j = position + 1 ; j < end ; j += 2 ) { int currentCounter = theCounters [ j ] ; if ( currentCounter < minSpace ) { minSpace = currentCounter ; } if ( currentCounter > maxSpace ) { maxSpace = currentCounter ; } } int thresholdSpace = ( minSpace + maxSpace ) / 2 ; int bitmask = 1 << 7 ; int pattern = 0 ; for ( int i = 0 ; i < 7 ; i ++ ) { int threshold = ( i & 1 ) == 0 ? thresholdBar : thresholdSpace ; bitmask >>= 1 ; if ( theCounters [ position + i ] > threshold ) { pattern |= bitmask ; } } for ( int i = 0 ; i < CHARACTER_ENCODINGS . length ; i ++ ) { if ( CHARACTER_ENCODINGS [ i ] == pattern ) { return i ; } } return - 1 ; |
public class ExampleVideoMosaic { /** * Checks to see if the point is near the image border */
private static boolean nearBorder ( Point2D_F64 p , StitchingFromMotion2D < ? , ? > stitch ) { } } | int r = 10 ; if ( p . x < r || p . y < r ) return true ; if ( p . x >= stitch . getStitchedImage ( ) . width - r ) return true ; if ( p . y >= stitch . getStitchedImage ( ) . height - r ) return true ; return false ; |
public class FootprintGenerator { /** * Calculate a footprint of a string
* @ param stringToFootprint The string for which the footprint is calculated
* @ return The footprint calculated */
public static String footprint ( String stringToFootprint ) { } } | try { MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; return byteArrayToHexString ( md . digest ( stringToFootprint . getBytes ( ) ) ) ; } catch ( NoSuchAlgorithmException nsae ) { LOGGER . warn ( "Unable to calculate the footprint for string [{}]." , stringToFootprint ) ; return null ; } |
public class StoryState { /** * counting */
void setChosenPath ( Path path , boolean incrementingTurnIndex ) throws Exception { } } | // Changing direction , assume we need to clear current set of choices
currentChoices . clear ( ) ; Pointer newPointer = new Pointer ( story . pointerAtPath ( path ) ) ; if ( ! newPointer . isNull ( ) && newPointer . index == - 1 ) newPointer . index = 0 ; setCurrentPointer ( newPointer ) ; if ( incrementingTurnIndex ) currentTurnIndex ++ ; |
public class TableFactorBuilder { /** * Gets a { @ code TableFactorBuilder } containing the same assignments and
* weights as { @ code probabilities } .
* @ param variables
* @ param probabilities
* @ return */
public static TableFactorBuilder fromMap ( VariableNumMap variables , Map < Assignment , Double > probabilities ) { } } | TableFactorBuilder builder = new TableFactorBuilder ( variables ) ; for ( Map . Entry < Assignment , Double > outcome : probabilities . entrySet ( ) ) { builder . setWeight ( outcome . getKey ( ) , outcome . getValue ( ) ) ; } return builder ; |
public class ContainerDefinition { /** * A list of hostnames and IP address mappings to append to the < code > / etc / hosts < / code > file on the container . This
* parameter maps to < code > ExtraHosts < / code > in the < a
* href = " https : / / docs . docker . com / engine / api / v1.35 / # operation / ContainerCreate " > Create a container < / a > section of the
* < a href = " https : / / docs . docker . com / engine / api / v1.35 / " > Docker Remote API < / a > and the < code > - - add - host < / code > option
* to < a href = " https : / / docs . docker . com / engine / reference / run / " > docker run < / a > .
* < note >
* This parameter is not supported for Windows containers or tasks that use the < code > awsvpc < / code > network mode .
* < / note >
* @ param extraHosts
* A list of hostnames and IP address mappings to append to the < code > / etc / hosts < / code > file on the
* container . This parameter maps to < code > ExtraHosts < / code > in the < a
* href = " https : / / docs . docker . com / engine / api / v1.35 / # operation / ContainerCreate " > Create a container < / a > section
* of the < a href = " https : / / docs . docker . com / engine / api / v1.35 / " > Docker Remote API < / a > and the
* < code > - - add - host < / code > option to < a href = " https : / / docs . docker . com / engine / reference / run / " > docker
* run < / a > . < / p > < note >
* This parameter is not supported for Windows containers or tasks that use the < code > awsvpc < / code > network
* mode . */
public void setExtraHosts ( java . util . Collection < HostEntry > extraHosts ) { } } | if ( extraHosts == null ) { this . extraHosts = null ; return ; } this . extraHosts = new com . amazonaws . internal . SdkInternalList < HostEntry > ( extraHosts ) ; |
public class ApiOvhLicenseoffice { /** * Delete existing office user
* REST : DELETE / license / office / { serviceName } / user / { activationEmail }
* @ param serviceName [ required ] The unique identifier of your Office service
* @ param activationEmail [ required ] Email used to activate Microsoft Office */
public OvhOfficeTask serviceName_user_activationEmail_DELETE ( String serviceName , String activationEmail ) throws IOException { } } | String qPath = "/license/office/{serviceName}/user/{activationEmail}" ; StringBuilder sb = path ( qPath , serviceName , activationEmail ) ; String resp = exec ( qPath , "DELETE" , sb . toString ( ) , null ) ; return convertTo ( resp , OvhOfficeTask . class ) ; |
public class nsevents { /** * Use this API to fetch filtered set of nsevents resources .
* filter string should be in JSON format . eg : " port : 80 , servicetype : HTTP " . */
public static nsevents [ ] get_filtered ( nitro_service service , String filter ) throws Exception { } } | nsevents obj = new nsevents ( ) ; options option = new options ( ) ; option . set_filter ( filter ) ; nsevents [ ] response = ( nsevents [ ] ) obj . getfiltered ( service , option ) ; return response ; |
public class PatriciaTrieFormatter { /** * Get node id used to distinguish nodes internally
* @ param node
* @ return node id , not null */
private String getNodeId ( PatriciaTrie . PatriciaNode < V > node ) { } } | if ( node == null ) { return "null" ; } else { return node . getKey ( ) ; } |
public class JsonWriter { /** * This method writes assignment data to a JSON file . */
private void writeAssignments ( ) throws IOException { } } | writeAttributeTypes ( "assignment_types" , AssignmentField . values ( ) ) ; m_writer . writeStartList ( "assignments" ) ; for ( ResourceAssignment assignment : m_projectFile . getResourceAssignments ( ) ) { writeFields ( null , assignment , AssignmentField . values ( ) ) ; } m_writer . writeEndList ( ) ; |
public class DateUtils { /** * < p > Parses a string representing a date by trying a variety of different parsers . < / p >
* < p > The parse will try each parse pattern in turn .
* A parse is only deemed successful if it parses the whole of the input string .
* If no parse patterns match , a ParseException is thrown . < / p >
* The parser will be lenient toward the parsed date .
* @ param str the date to parse , not null
* @ param parsePatterns the date format patterns to use , see SimpleDateFormat , not null
* @ return the parsed date
* @ throws IllegalArgumentException if the date string or pattern array is null
* @ throws ParseException if none of the date patterns were suitable ( or there were none ) */
public static Date parseDate ( String str , String ... parsePatterns ) throws ParseException { } } | return parseDate ( str , null , parsePatterns ) ; |
public class SoyNodeCompiler { /** * Returns true if the print expression should check the rendering buffer and generate a detach .
* < p > We do not generate detaches for css ( ) and xid ( ) builtin functions , since they are typically
* very short . */
private static boolean shouldCheckBuffer ( PrintNode node ) { } } | if ( ! ( node . getExpr ( ) . getRoot ( ) instanceof FunctionNode ) ) { return true ; } FunctionNode fn = ( FunctionNode ) node . getExpr ( ) . getRoot ( ) ; if ( ! ( fn . getSoyFunction ( ) instanceof BuiltinFunction ) ) { return true ; } BuiltinFunction bfn = ( BuiltinFunction ) fn . getSoyFunction ( ) ; if ( bfn != BuiltinFunction . XID && bfn != BuiltinFunction . CSS ) { return true ; } return false ; |
public class NotEqualsRule { /** * Get new instance from top two elements of stack .
* @ param stack stack .
* @ return new instance . */
public static Rule getRule ( final Stack stack ) { } } | if ( stack . size ( ) < 2 ) { throw new IllegalArgumentException ( "Invalid NOT EQUALS rule - expected two parameters but received " + stack . size ( ) ) ; } String p2 = stack . pop ( ) . toString ( ) ; String p1 = stack . pop ( ) . toString ( ) ; if ( p1 . equalsIgnoreCase ( LoggingEventFieldResolver . LEVEL_FIELD ) ) { return NotLevelEqualsRule . getRule ( p2 ) ; } else { return new NotEqualsRule ( p1 , p2 ) ; } |
public class CommerceDiscountPersistenceImpl { /** * Returns the commerce discount with the primary key or returns < code > null < / code > if it could not be found .
* @ param primaryKey the primary key of the commerce discount
* @ return the commerce discount , or < code > null < / code > if a commerce discount with the primary key could not be found */
@ Override public CommerceDiscount fetchByPrimaryKey ( Serializable primaryKey ) { } } | Serializable serializable = entityCache . getResult ( CommerceDiscountModelImpl . ENTITY_CACHE_ENABLED , CommerceDiscountImpl . class , primaryKey ) ; if ( serializable == nullModel ) { return null ; } CommerceDiscount commerceDiscount = ( CommerceDiscount ) serializable ; if ( commerceDiscount == null ) { Session session = null ; try { session = openSession ( ) ; commerceDiscount = ( CommerceDiscount ) session . get ( CommerceDiscountImpl . class , primaryKey ) ; if ( commerceDiscount != null ) { cacheResult ( commerceDiscount ) ; } else { entityCache . putResult ( CommerceDiscountModelImpl . ENTITY_CACHE_ENABLED , CommerceDiscountImpl . class , primaryKey , nullModel ) ; } } catch ( Exception e ) { entityCache . removeResult ( CommerceDiscountModelImpl . ENTITY_CACHE_ENABLED , CommerceDiscountImpl . class , primaryKey ) ; throw processException ( e ) ; } finally { closeSession ( session ) ; } } return commerceDiscount ; |
public class AssignedAddOn { /** * Create a AssignedAddOnCreator to execute create .
* @ param pathAccountSid The SID of the Account that will create the resource
* @ param pathResourceSid The SID of the Phone Number to assign the Add - on
* @ param installedAddOnSid The SID that identifies the Add - on installation
* @ return AssignedAddOnCreator capable of executing the create */
public static AssignedAddOnCreator creator ( final String pathAccountSid , final String pathResourceSid , final String installedAddOnSid ) { } } | return new AssignedAddOnCreator ( pathAccountSid , pathResourceSid , installedAddOnSid ) ; |
public class VisOdomDirectColorDepth { /** * Estimates the motion relative to the key frame .
* @ param input Next image in the sequence
* @ param hintKeyToInput estimated transform from keyframe to the current input image
* @ return true if it was successful at estimating the motion or false if it failed for some reason */
public boolean estimateMotion ( Planar < I > input , Se3_F32 hintKeyToInput ) { } } | InputSanityCheck . checkSameShape ( derivX , input ) ; initMotion ( input ) ; keyToCurrent . set ( hintKeyToInput ) ; boolean foundSolution = false ; float previousError = Float . MAX_VALUE ; for ( int i = 0 ; i < maxIterations ; i ++ ) { constructLinearSystem ( input , keyToCurrent ) ; if ( ! solveSystem ( ) ) break ; if ( Math . abs ( previousError - errorOptical ) / previousError < convergeTol ) break ; else { // update the estimated motion from the computed twist
previousError = errorOptical ; keyToCurrent . concat ( motionTwist , tmp ) ; keyToCurrent . set ( tmp ) ; foundSolution = true ; } } return foundSolution ; |
public class AbstractTimeoutSlidingBound { /** * Add new value
* @ param value */
@ Override public void accept ( double value ) { } } | writeLock . lock ( ) ; try { eliminate ( ) ; if ( parent == null && count ( ) >= size ) { grow ( ) ; } endIncr ( ) ; PrimitiveIterator . OfInt rev = modReverseIterator ( ) ; int e = rev . nextInt ( ) ; assign ( e , value ) ; while ( rev . hasNext ( ) ) { e = rev . nextInt ( ) ; if ( exceedsBounds ( e , value ) ) { assign ( e , value ) ; } else { break ; } } } finally { writeLock . unlock ( ) ; } |
public class RestTool { /** * Makes a call to the MangoPay API .
* This generic method handles calls targeting single
* < code > Dto < / code > instances . In order to process collections of objects ,
* use < code > requestList < / code > method instead .
* @ param < T > Type on behalf of which the request is being called .
* @ param classOfT Type on behalf of which the request is being called .
* @ param urlMethod Relevant method key .
* @ param requestType HTTP request term , one of the GET , PUT or POST .
* @ return The Dto instance returned from API .
* @ throws Exception */
public < T extends Dto > T request ( Class < T > classOfT , String idempotencyKey , String urlMethod , String requestType ) throws Exception { } } | return request ( classOfT , idempotencyKey , urlMethod , requestType , null , null , null ) ; |
public class Organizer { public static double [ ] toDoubles ( List < Double > objects ) { } } | if ( objects == null || objects . isEmpty ( ) ) return null ; double [ ] rets = new double [ objects . size ( ) ] ; for ( int i = 0 ; i < rets . length ; i ++ ) { rets [ i ] = objects . get ( i ) ; } return rets ; |
public class AwsSecurityFindingFilters { /** * The name of the malware that was observed .
* @ param malwareName
* The name of the malware that was observed . */
public void setMalwareName ( java . util . Collection < StringFilter > malwareName ) { } } | if ( malwareName == null ) { this . malwareName = null ; return ; } this . malwareName = new java . util . ArrayList < StringFilter > ( malwareName ) ; |
public class NioController { /** * Start selector manager
* @ throws IOException */
protected void initialSelectorManager ( ) throws IOException { } } | if ( this . selectorManager == null ) { this . selectorManager = new SelectorManager ( this . selectorPoolSize , this , this . configuration ) ; this . selectorManager . start ( ) ; } |
public class CountBytes { /** * Print the length of the indicated file .
* < p > This uses the normal Java NIO Api , so it can take advantage of any installed NIO Filesystem
* provider without any extra effort . */
private static void countFile ( String fname ) { } } | // large buffers pay off
final int bufSize = 50 * 1024 * 1024 ; try { Path path = Paths . get ( new URI ( fname ) ) ; long size = Files . size ( path ) ; System . out . println ( fname + ": " + size + " bytes." ) ; ByteBuffer buf = ByteBuffer . allocate ( bufSize ) ; System . out . println ( "Reading the whole file..." ) ; Stopwatch sw = Stopwatch . createStarted ( ) ; try ( SeekableByteChannel chan = Files . newByteChannel ( path ) ) { long total = 0 ; int readCalls = 0 ; MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; while ( chan . read ( buf ) > 0 ) { readCalls ++ ; md . update ( buf . array ( ) , 0 , buf . position ( ) ) ; total += buf . position ( ) ; buf . flip ( ) ; } readCalls ++ ; // We must count the last call
long elapsed = sw . elapsed ( TimeUnit . SECONDS ) ; System . out . println ( "Read all " + total + " bytes in " + elapsed + "s. " + "(" + readCalls + " calls to chan.read)" ) ; String hex = String . valueOf ( BaseEncoding . base16 ( ) . encode ( md . digest ( ) ) ) ; System . out . println ( "The MD5 is: 0x" + hex ) ; if ( total != size ) { System . out . println ( "Wait, this doesn't match! We saw " + total + " bytes, " + "yet the file size is listed at " + size + " bytes." ) ; } } } catch ( Exception ex ) { System . out . println ( fname + ": " + ex . toString ( ) ) ; } |
public class RDBMSEntityReader { /** * Populate enhance entities .
* @ param m
* the m
* @ param relationNames
* the relation names
* @ param client
* the client
* @ param sqlQuery
* the sql query
* @ return the list */
private List < EnhanceEntity > populateEnhanceEntities ( EntityMetadata m , List < String > relationNames , Client client , String sqlQuery ) { } } | List < EnhanceEntity > ls = null ; List result = ( ( HibernateClient ) client ) . find ( sqlQuery , relationNames , m ) ; if ( ! result . isEmpty ( ) ) { ls = new ArrayList < EnhanceEntity > ( result . size ( ) ) ; for ( Object o : result ) { EnhanceEntity entity = null ; if ( ! o . getClass ( ) . isAssignableFrom ( EnhanceEntity . class ) ) { entity = new EnhanceEntity ( o , getId ( o , m ) , null ) ; } else { entity = ( EnhanceEntity ) o ; } ls . add ( entity ) ; } } return ls ; |
public class TranslateExprNodeVisitor { /** * Generates the code for a field access , e . g . { @ code . foo } or { @ code . getFoo ( ) } .
* @ param baseType The type of the object that contains the field .
* @ param fieldAccessNode The field access node .
* @ param fieldName The field name . */
private FieldAccess genCodeForFieldAccess ( SoyType baseType , FieldAccessNode fieldAccessNode , String fieldName ) { } } | Preconditions . checkNotNull ( baseType ) ; // For unions , attempt to generate the field access code for each member
// type , and then see if they all agree .
if ( baseType . getKind ( ) == SoyType . Kind . UNION ) { // TODO ( msamuel ) : We will need to generate fallback code for each variant .
UnionType unionType = ( UnionType ) baseType ; FieldAccess fieldAccess = null ; for ( SoyType memberType : unionType . getMembers ( ) ) { if ( memberType . getKind ( ) != SoyType . Kind . NULL ) { FieldAccess fieldAccessForType = genCodeForFieldAccess ( memberType , fieldAccessNode , fieldName ) ; if ( fieldAccess == null ) { fieldAccess = fieldAccessForType ; } else if ( ! fieldAccess . equals ( fieldAccessForType ) ) { errorReporter . report ( fieldAccessNode . getSourceLocation ( ) , UNION_ACCESSOR_MISMATCH , fieldName , baseType ) ; } } } return fieldAccess ; } if ( baseType . getKind ( ) == SoyType . Kind . PROTO ) { SoyProtoType protoType = ( SoyProtoType ) baseType ; FieldDescriptor desc = protoType . getFieldDescriptor ( fieldName ) ; Preconditions . checkNotNull ( desc , "Error in proto %s, field not found: %s" , protoType . getDescriptor ( ) . getFullName ( ) , fieldName ) ; return FieldAccess . protoCall ( fieldName , desc ) ; } return FieldAccess . id ( fieldName ) ; |
public class Decimal { /** * then ` precision ` is checked . if precision overflow , it will return ` null ` */
public static Decimal fromBigDecimal ( BigDecimal bd , int precision , int scale ) { } } | bd = bd . setScale ( scale , RoundingMode . HALF_UP ) ; if ( bd . precision ( ) > precision ) { return null ; } long longVal = - 1 ; if ( precision <= MAX_COMPACT_PRECISION ) { longVal = bd . movePointRight ( scale ) . longValueExact ( ) ; } return new Decimal ( precision , scale , longVal , bd ) ; |
public class CmsFlexBucketConfiguration { /** * Gets the bucket of which the given path is a part . < p >
* @ param path a root path
* @ return the set of buckets for the given path */
private Set < String > getBucketsForPath ( String path ) { } } | Set < String > result = Sets . newHashSet ( ) ; boolean foundBucket = false ; for ( int i = 0 ; i < m_bucketNames . size ( ) ; i ++ ) { for ( String bucketPath : m_bucketPathLists . get ( i ) ) { if ( CmsStringUtil . isPrefixPath ( bucketPath , path ) ) { String bucketName = m_bucketNames . get ( i ) ; result . add ( bucketName ) ; if ( ! BUCKET_OTHER . equals ( bucketName ) ) { foundBucket = true ; } } } } if ( ! foundBucket ) { result . add ( BUCKET_OTHER ) ; } return result ; |
public class ObjectMapperFactory { /** * / * package private */
static < T > Optional < Class < ? extends T > > getClass ( final String className ) { } } | try { @ SuppressWarnings ( "unchecked" ) final Optional < Class < ? extends T > > clazz = Optional . < Class < ? extends T > > of ( ( Class < T > ) Class . forName ( className ) ) ; return clazz ; } catch ( final ClassNotFoundException e ) { return Optional . empty ( ) ; } |
public class ArrayRewriter { /** * rhs is an array creation , we can optimize with " SetAndConsume " . */
@ Override public boolean visit ( Assignment node ) { } } | Expression lhs = node . getLeftHandSide ( ) ; TypeMirror lhsType = lhs . getTypeMirror ( ) ; if ( lhs instanceof ArrayAccess && ! lhsType . getKind ( ) . isPrimitive ( ) ) { FunctionInvocation newAssignment = newArrayAssignment ( node , ( ArrayAccess ) lhs , lhsType ) ; node . replaceWith ( newAssignment ) ; newAssignment . accept ( this ) ; return false ; } return true ; |
public class Checkbox { /** * Sets the value string considered as checked / enabled .
* Maintains the checked status considering the current value enabled string .
* @ param value Checked value , { @ code DEFAULT _ ENABLED _ VALUE } by default
* @ return This element */
public Checkbox setEnabledValueString ( String value ) { } } | boolean checked = this . isChecked ( ) ; // Maintain checked status
this . setProperty ( "value" , value ) ; this . setChecked ( checked ) ; return this ; |
public class AbstractModel { /** * A method that tries to generate a model identifier
* for those times when models arrive without an identifier
* @ return The String value that is to be used to identify the model */
private String generateModelId ( ) { } } | String mt = this . modelType . toString ( ) ; StringBuilder mid = new StringBuilder ( mt ) ; Integer lastId = null ; if ( generatedModelIds . containsKey ( mt ) ) { lastId = generatedModelIds . get ( mt ) ; } else { lastId = new Integer ( - 1 ) ; } lastId ++ ; mid . append ( lastId ) ; generatedModelIds . put ( mt , lastId ) ; return mid . toString ( ) ; |
public class ProtoParser { /** * com / dyuproject / protostuff / parser / ProtoParser . g : 523:1 : enum _ block [ Proto proto , Message message ] : ENUM ID LEFTCURLY ( enum _ body [ proto , message , enumGroup ] ) * RIGHTCURLY ( ( SEMICOLON ) ? ) ; */
public final ProtoParser . enum_block_return enum_block ( Proto proto , Message message ) throws RecognitionException { } } | ProtoParser . enum_block_return retval = new ProtoParser . enum_block_return ( ) ; retval . start = input . LT ( 1 ) ; Object root_0 = null ; Token ENUM118 = null ; Token ID119 = null ; Token LEFTCURLY120 = null ; Token RIGHTCURLY122 = null ; Token SEMICOLON123 = null ; ProtoParser . enum_body_return enum_body121 = null ; Object ENUM118_tree = null ; Object ID119_tree = null ; Object LEFTCURLY120_tree = null ; Object RIGHTCURLY122_tree = null ; Object SEMICOLON123_tree = null ; EnumGroup enumGroup = null ; try { // com / dyuproject / protostuff / parser / ProtoParser . g : 527:5 : ( ENUM ID LEFTCURLY ( enum _ body [ proto , message , enumGroup ] ) * RIGHTCURLY ( ( SEMICOLON ) ? ) )
// com / dyuproject / protostuff / parser / ProtoParser . g : 527:9 : ENUM ID LEFTCURLY ( enum _ body [ proto , message , enumGroup ] ) * RIGHTCURLY ( ( SEMICOLON ) ? )
{ root_0 = ( Object ) adaptor . nil ( ) ; ENUM118 = ( Token ) match ( input , ENUM , FOLLOW_ENUM_in_enum_block2076 ) ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) { ENUM118_tree = ( Object ) adaptor . create ( ENUM118 ) ; adaptor . addChild ( root_0 , ENUM118_tree ) ; } ID119 = ( Token ) match ( input , ID , FOLLOW_ID_in_enum_block2078 ) ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) { ID119_tree = ( Object ) adaptor . create ( ID119 ) ; adaptor . addChild ( root_0 , ID119_tree ) ; } if ( state . backtracking == 0 ) { enumGroup = new EnumGroup ( ( ID119 != null ? ID119 . getText ( ) : null ) , message , proto ) ; proto . addAnnotationsTo ( enumGroup ) ; } LEFTCURLY120 = ( Token ) match ( input , LEFTCURLY , FOLLOW_LEFTCURLY_in_enum_block2091 ) ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) { LEFTCURLY120_tree = ( Object ) adaptor . create ( LEFTCURLY120 ) ; adaptor . addChild ( root_0 , LEFTCURLY120_tree ) ; } // com / dyuproject / protostuff / parser / ProtoParser . g : 531:19 : ( enum _ body [ proto , message , enumGroup ] ) *
loop22 : do { int alt22 = 2 ; switch ( input . LA ( 1 ) ) { case AT : case OPTION : case ID : { alt22 = 1 ; } break ; } switch ( alt22 ) { case 1 : // com / dyuproject / protostuff / parser / ProtoParser . g : 531:20 : enum _ body [ proto , message , enumGroup ]
{ pushFollow ( FOLLOW_enum_body_in_enum_block2094 ) ; enum_body121 = enum_body ( proto , message , enumGroup ) ; state . _fsp -- ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) adaptor . addChild ( root_0 , enum_body121 . getTree ( ) ) ; } break ; default : break loop22 ; } } while ( true ) ; RIGHTCURLY122 = ( Token ) match ( input , RIGHTCURLY , FOLLOW_RIGHTCURLY_in_enum_block2099 ) ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) { RIGHTCURLY122_tree = ( Object ) adaptor . create ( RIGHTCURLY122 ) ; adaptor . addChild ( root_0 , RIGHTCURLY122_tree ) ; } if ( state . backtracking == 0 ) { if ( ! proto . annotations . isEmpty ( ) ) throw new IllegalStateException ( "Misplaced annotations: " + proto . annotations ) ; } // com / dyuproject / protostuff / parser / ProtoParser . g : 534:11 : ( ( SEMICOLON ) ? )
// com / dyuproject / protostuff / parser / ProtoParser . g : 534:12 : ( SEMICOLON ) ?
{ // com / dyuproject / protostuff / parser / ProtoParser . g : 534:12 : ( SEMICOLON ) ?
int alt23 = 2 ; switch ( input . LA ( 1 ) ) { case SEMICOLON : { alt23 = 1 ; } break ; } switch ( alt23 ) { case 1 : // com / dyuproject / protostuff / parser / ProtoParser . g : 534:12 : SEMICOLON
{ SEMICOLON123 = ( Token ) match ( input , SEMICOLON , FOLLOW_SEMICOLON_in_enum_block2104 ) ; if ( state . failed ) return retval ; if ( state . backtracking == 0 ) { SEMICOLON123_tree = ( Object ) adaptor . create ( SEMICOLON123 ) ; adaptor . addChild ( root_0 , SEMICOLON123_tree ) ; } } break ; } } } retval . stop = input . LT ( - 1 ) ; if ( state . backtracking == 0 ) { retval . tree = ( Object ) adaptor . rulePostProcessing ( root_0 ) ; adaptor . setTokenBoundaries ( retval . tree , retval . start , retval . stop ) ; } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; retval . tree = ( Object ) adaptor . errorNode ( input , retval . start , input . LT ( - 1 ) , re ) ; } finally { } return retval ; |
public class FixedURLGenerator { /** * Generate the fixed url for a static topic node .
* @ param topicNode The topic node to generate the static fixed url for .
* @ return The fixed url for the node . */
public static String getStaticFixedURLForTopicNode ( final ITopicNode topicNode ) { } } | if ( topicNode . getTopicType ( ) == TopicType . REVISION_HISTORY ) { return "appe-Revision_History" ; } else if ( topicNode . getTopicType ( ) == TopicType . LEGAL_NOTICE ) { return "Legal_Notice" ; } else if ( topicNode . getTopicType ( ) == TopicType . AUTHOR_GROUP ) { return "Author_Group" ; } else if ( topicNode . getTopicType ( ) == TopicType . ABSTRACT ) { return "Abstract" ; } else { return null ; } |
public class PagingComponent { /** * Cuts off long queries . Actually they are restricted to 50 characters . The
* full query is available with descriptions ( tooltip in gui )
* @ param text the query to display in the result view panel */
public void setInfo ( String text ) { } } | if ( text != null && text . length ( ) > 0 ) { String prefix = "Result for: <span class=\"" + Helper . CORPUS_FONT_FORCE + "\">" ; lblInfo . setDescription ( prefix + text . replaceAll ( "\n" , " " ) + "</span>" ) ; lblInfo . setValue ( text . length ( ) < 50 ? prefix + StringEscapeUtils . escapeHtml4 ( text . substring ( 0 , text . length ( ) ) ) : prefix + StringEscapeUtils . escapeHtml4 ( text . substring ( 0 , 50 ) ) + " ... </span>" ) ; } |
public class Dcs_updown { /** * Sparse Cholesky rank - 1 update / downdate , L * L ' + sigma * w * w ' ( sigma = + 1 or
* @ param L
* factorization to update / downdate
* @ param sigma
* + 1 for update , - 1 for downdate
* @ param C
* the vector c
* @ param parent
* the elimination tree of L
* @ return true if successful , false on error */
public static boolean cs_updown ( Dcs L , int sigma , Dcs C , int [ ] parent ) { } } | int n , p , f , j , Lp [ ] , Li [ ] , Cp [ ] , Ci [ ] ; double Lx [ ] , Cx [ ] , alpha , beta = 1 , delta , gamma , w1 , w2 , w [ ] , beta2 = 1 ; if ( ! Dcs_util . CS_CSC ( L ) || ! Dcs_util . CS_CSC ( C ) || parent == null ) return ( false ) ; /* check inputs */
Lp = L . p ; Li = L . i ; Lx = L . x ; n = L . n ; Cp = C . p ; Ci = C . i ; Cx = C . x ; if ( ( p = Cp [ 0 ] ) >= Cp [ 1 ] ) return ( true ) ; /* return if C empty */
w = new double [ n ] ; /* get workspace */
f = Ci [ p ] ; for ( ; p < Cp [ 1 ] ; p ++ ) f = Math . min ( f , Ci [ p ] ) ; /* f = min ( find ( C ) ) */
for ( j = f ; j != - 1 ; j = parent [ j ] ) w [ j ] = 0 ; /* clear workspace w */
for ( p = Cp [ 0 ] ; p < Cp [ 1 ] ; p ++ ) w [ Ci [ p ] ] = Cx [ p ] ; /* w = C */
for ( j = f ; j != - 1 ; j = parent [ j ] ) /* walk path f up to root */
{ p = Lp [ j ] ; alpha = w [ j ] / Lx [ p ] ; /* alpha = w ( j ) / L ( j , j ) */
beta2 = beta * beta + sigma * alpha * alpha ; if ( beta2 <= 0 ) break ; /* not positive definite */
beta2 = Math . sqrt ( beta2 ) ; delta = ( sigma > 0 ) ? ( beta / beta2 ) : ( beta2 / beta ) ; gamma = sigma * alpha / ( beta2 * beta ) ; Lx [ p ] = delta * Lx [ p ] + ( ( sigma > 0 ) ? ( gamma * w [ j ] ) : 0 ) ; beta = beta2 ; for ( p ++ ; p < Lp [ j + 1 ] ; p ++ ) { w1 = w [ Li [ p ] ] ; w [ Li [ p ] ] = w2 = w1 - alpha * Lx [ p ] ; Lx [ p ] = delta * Lx [ p ] + gamma * ( ( sigma > 0 ) ? w1 : w2 ) ; } } return ( beta2 > 0 ) ; |
public class PermissionsConfigType { /** * ( non - Javadoc )
* @ see com . ibm . ws . javaee . ddmodel . DDParser . ParsableElement # handleChild ( com . ibm . ws . javaee . ddmodel . DDParser , java . lang . String ) */
@ Override public boolean handleChild ( DDParser parser , String localName ) throws ParseException { } } | if ( "permission" . equals ( localName ) ) { parsePermission ( parser ) ; return true ; } return false ; |
public class Iterators { /** * Returns an unmodifiable view of { @ code iterator } . */
public static < T > UnmodifiableIterator < T > unmodifiableIterator ( final Iterator < T > iterator ) { } } | checkNotNull ( iterator ) ; if ( iterator instanceof UnmodifiableIterator ) { return ( UnmodifiableIterator < T > ) iterator ; } return new UnmodifiableIterator < T > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public T next ( ) { return iterator . next ( ) ; } } ; |
public class BeanMappingFactory { /** * ヘッダーのマッピングの処理や設定を組み立てます 。
* @ param < T > Beanのタイプ
* @ param beanMapping Beanのマッピング情報
* @ param beanAnno アノテーション { @ literal @ CsvBean } のインタンス */
protected < T > void buildHeaderMapper ( final BeanMapping < T > beanMapping , final CsvBean beanAnno ) { } } | final HeaderMapper headerMapper = ( HeaderMapper ) configuration . getBeanFactory ( ) . create ( beanAnno . headerMapper ( ) ) ; beanMapping . setHeaderMapper ( headerMapper ) ; beanMapping . setHeader ( beanAnno . header ( ) ) ; beanMapping . setValidateHeader ( beanAnno . validateHeader ( ) ) ; |
public class ExponentalBackoff { /** * Called on failure , wait required time before exiting method
* @ throws InterruptedException if waiting was interrupted */
public void onFailure ( ) throws InterruptedException { } } | int val = currentFailureCount . incrementAndGet ( ) ; if ( val > 50 ) { currentFailureCount . compareAndSet ( val , MAX_FAILURE_COUNT ) ; val = MAX_FAILURE_COUNT ; } int delay = MIN_DELAY + ( ( MAX_DELAY - MIN_DELAY ) / MAX_FAILURE_COUNT ) * val ; synchronized ( this ) { Logger . d ( TAG , "onFailure: wait " + delay + " ms" ) ; wait ( delay ) ; } |
public class HttpMethodBase { /** * Executes this method using the specified < code > HttpConnection < / code > and
* < code > HttpState < / code > .
* @ param state { @ link HttpState state } information to associate with this
* request . Must be non - null .
* @ param conn the { @ link HttpConnection connection } to used to execute
* this HTTP method . Must be non - null .
* @ return the integer status code if one was obtained , or < tt > - 1 < / tt >
* @ throws IOException if an I / O ( transport ) error occurs
* @ throws HttpException if a protocol exception occurs . */
@ Override public int execute ( HttpState state , HttpConnection conn ) throws HttpException , IOException { } } | LOG . trace ( "enter HttpMethodBase.execute(HttpState, HttpConnection)" ) ; // this is our connection now , assign it to a local variable so
// that it can be released later
this . responseConnection = conn ; checkExecuteConditions ( state , conn ) ; this . statusLine = null ; this . connectionCloseForced = false ; conn . setLastResponseInputStream ( null ) ; // determine the effective protocol version
if ( this . effectiveVersion == null ) { this . effectiveVersion = this . params . getVersion ( ) ; } writeRequest ( state , conn ) ; this . requestSent = true ; readResponse ( state , conn ) ; // the method has successfully executed
used = true ; return statusLine . getStatusCode ( ) ; |
public class AbstractDomainQuery { /** * Retrieve the count for every DomainObjectMatch of the query
* in order to support pagination
* @ return a CountQueryResult */
public CountQueryResult executeCount ( ) { } } | CountQueryResult ret = new CountQueryResult ( this ) ; Object so = this . queryExecutor . getMappingInfo ( ) . getInternalDomainAccess ( ) . getSyncObject ( ) ; if ( so != null ) { synchronized ( so ) { this . queryExecutor . executeCount ( ) ; } } else this . queryExecutor . executeCount ( ) ; return ret ; |
public class ConciseSet { /** * { @ inheritDoc } */
@ SuppressWarnings ( "CompareToUsesNonFinalVariable" ) @ Override public int compareTo ( IntSet o ) { } } | // empty set cases
if ( this . isEmpty ( ) && o . isEmpty ( ) ) { return 0 ; } if ( this . isEmpty ( ) ) { return - 1 ; } if ( o . isEmpty ( ) ) { return 1 ; } final ConciseSet other = convert ( o ) ; // the word at the end must be the same
int res = Integer . compare ( this . last , other . last ) ; if ( res != 0 ) { return res ; } // scan words from MSB to LSB
int thisIndex = this . lastWordIndex ; int otherIndex = other . lastWordIndex ; int thisWord = this . words [ thisIndex ] ; int otherWord = other . words [ otherIndex ] ; while ( thisIndex >= 0 && otherIndex >= 0 ) { if ( ! isLiteral ( thisWord ) ) { if ( ! isLiteral ( otherWord ) ) { // compare two sequences
// note that they are made up of at least two blocks , and we
// start comparing from the end , that is at blocks with no
// ( un ) set bits
if ( isZeroSequence ( thisWord ) ) { if ( isOneSequence ( otherWord ) ) { // zeros < ones
return - 1 ; } // compare two sequences of zeros
res = Integer . compare ( getSequenceCount ( otherWord ) , getSequenceCount ( thisWord ) ) ; if ( res != 0 ) { return res ; } } else { if ( isZeroSequence ( otherWord ) ) { // ones > zeros
return 1 ; } // compare two sequences of ones
res = Integer . compare ( getSequenceCount ( thisWord ) , getSequenceCount ( otherWord ) ) ; if ( res != 0 ) { return res ; } } // if the sequences are the same ( both zeros or both ones )
// and have the same length , compare the first blocks in the
// next loop since such blocks might contain ( un ) set bits
thisWord = getLiteral ( thisWord ) ; otherWord = getLiteral ( otherWord ) ; } else { // zeros < literal - - > - 1
// ones > literal - - > + 1
// note that the sequence is made up of at least two blocks ,
// and we start comparing from the end , that is at a block
// with no ( un ) set bits
if ( isZeroSequence ( thisWord ) ) { if ( otherWord != ConciseSetUtils . ALL_ZEROS_LITERAL ) { return - 1 ; } } else { if ( otherWord != ConciseSetUtils . ALL_ONES_LITERAL ) { return 1 ; } } if ( getSequenceCount ( thisWord ) == 1 ) { thisWord = getLiteral ( thisWord ) ; } else { thisWord -- ; } if ( -- otherIndex >= 0 ) { otherWord = other . words [ otherIndex ] ; } } } else if ( ! isLiteral ( otherWord ) ) { // literal > zeros - - > + 1
// literal < ones - - > - 1
// note that the sequence is made up of at least two blocks ,
// and we start comparing from the end , that is at a block
// with no ( un ) set bits
if ( isZeroSequence ( otherWord ) ) { if ( thisWord != ConciseSetUtils . ALL_ZEROS_LITERAL ) { return 1 ; } } else { if ( thisWord != ConciseSetUtils . ALL_ONES_LITERAL ) { return - 1 ; } } if ( -- thisIndex >= 0 ) { thisWord = this . words [ thisIndex ] ; } if ( getSequenceCount ( otherWord ) == 1 ) { otherWord = getLiteral ( otherWord ) ; } else { otherWord -- ; } } else { // equals compare ( getLiteralBits ( thisWord ) , getLiteralBits ( otherWord ) )
res = Integer . compare ( thisWord , otherWord ) ; if ( res != 0 ) { return res ; } if ( -- thisIndex >= 0 ) { thisWord = this . words [ thisIndex ] ; } if ( -- otherIndex >= 0 ) { otherWord = other . words [ otherIndex ] ; } } } return thisIndex >= 0 ? 1 : ( otherIndex >= 0 ? - 1 : 0 ) ; |
public class JobsInner { /** * Gets information about a Job .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param workspaceName The name of the workspace . Workspace names can only contain a combination of alphanumeric characters along with dash ( - ) and underscore ( _ ) . The name must be from 1 through 64 characters long .
* @ param experimentName The name of the experiment . Experiment names can only contain a combination of alphanumeric characters along with dash ( - ) and underscore ( _ ) . The name must be from 1 through 64 characters long .
* @ param jobName The name of the job within the specified resource group . Job names can only contain a combination of alphanumeric characters along with dash ( - ) and underscore ( _ ) . The name must be from 1 through 64 characters long .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the JobInner object */
public Observable < JobInner > getAsync ( String resourceGroupName , String workspaceName , String experimentName , String jobName ) { } } | return getWithServiceResponseAsync ( resourceGroupName , workspaceName , experimentName , jobName ) . map ( new Func1 < ServiceResponse < JobInner > , JobInner > ( ) { @ Override public JobInner call ( ServiceResponse < JobInner > response ) { return response . body ( ) ; } } ) ; |
public class FunctorFactory { /** * Create a functor without parameter , wrapping a call to another method .
* @ param instance
* instance to call the method upon . Should not be null .
* @ param methodName
* Name of the method , it must exist .
* @ return a Functor that call the specified method on the specified instance .
* @ throws Exception if there is a problem to deal with . */
public static Functor instanciateFunctorAsAnInstanceMethodWrapper ( final Object instance , String methodName ) throws Exception { } } | if ( null == instance ) { throw new NullPointerException ( "Instance is null" ) ; } Method _method = instance . getClass ( ) . getMethod ( methodName , ( Class < ? > [ ] ) null ) ; return instanciateFunctorAsAMethodWrapper ( instance , _method ) ; |
public class PlacesInterface { /** * Find Flickr Places information by Place URL .
* This method does not require authentication .
* @ deprecated This method has been deprecated . It won ' t be removed but you should use { @ link PlacesInterface # getInfoByUrl ( String ) } instead .
* @ param flickrPlacesUrl
* @ return A Location
* @ throws FlickrException */
@ Deprecated public Location resolvePlaceURL ( String flickrPlacesUrl ) throws FlickrException { } } | Map < String , Object > parameters = new HashMap < String , Object > ( ) ; parameters . put ( "method" , METHOD_RESOLVE_PLACE_URL ) ; parameters . put ( "url" , flickrPlacesUrl ) ; Response response = transportAPI . get ( transportAPI . getPath ( ) , parameters , apiKey , sharedSecret ) ; if ( response . isError ( ) ) { throw new FlickrException ( response . getErrorCode ( ) , response . getErrorMessage ( ) ) ; } Element locationElement = response . getPayload ( ) ; return parseLocation ( locationElement ) ; |
public class BaseTangramEngine { /** * Replace original data to Tangram at target position . It cause full screen item ' s rebinding , be careful .
* @ param position Target replace position .
* @ param data Parsed data list . */
@ Deprecated public void replaceData ( int position , @ Nullable List < Card > data ) { } } | Preconditions . checkState ( mGroupBasicAdapter != null , "Must call bindView() first" ) ; this . mGroupBasicAdapter . replaceGroup ( position , data ) ; |
public class UiLifecycleHelper { /** * To be called from an Activity or Fragment ' s onResume method . */
public void onResume ( ) { } } | Session session = Session . getActiveSession ( ) ; if ( session != null ) { if ( callback != null ) { session . addCallback ( callback ) ; } if ( SessionState . CREATED_TOKEN_LOADED . equals ( session . getState ( ) ) ) { session . openForRead ( null ) ; } } // add the broadcast receiver
IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( Session . ACTION_ACTIVE_SESSION_SET ) ; filter . addAction ( Session . ACTION_ACTIVE_SESSION_UNSET ) ; // Add a broadcast receiver to listen to when the active Session
// is set or unset , and add / remove our callback as appropriate
broadcastManager . registerReceiver ( receiver , filter ) ; |
public class A_CmsTreeTabDataPreloader { /** * Creates the preload data for a collection of resources which correspond to " opened " tree items . < p >
* @ param cms the CMS context to use
* @ param openResources the resources which correspond to opened tree items
* @ param selectedResources resources which should be part of the tree , but not opened
* @ return the root tree entry bean which was created
* @ throws CmsException if something goes wrong */
public T preloadData ( CmsObject cms , Set < CmsResource > openResources , Set < CmsResource > selectedResources ) throws CmsException { } } | assert m_cms == null : "Instance can't be used more than once!" ; if ( openResources == null ) { openResources = Sets . newHashSet ( ) ; } if ( selectedResources == null ) { selectedResources = Sets . newHashSet ( ) ; } boolean ignoreOpen = false ; if ( ! selectedResources . isEmpty ( ) && ! openResources . isEmpty ( ) ) { // if selected and opened resources are in different sites ,
// we do * not * want to start from the common root folder ( usually ' / ' ) ,
// so ignore the ' open ' resources .
String siteForSelected = getCommonSite ( selectedResources ) ; String siteForOpen = getCommonSite ( openResources ) ; if ( ! Objects . equal ( siteForSelected , siteForOpen ) ) { ignoreOpen = true ; } } Set < CmsResource > allParamResources = Sets . newHashSet ( ) ; if ( ! ignoreOpen ) { allParamResources . addAll ( openResources ) ; } allParamResources . addAll ( selectedResources ) ; m_cms = OpenCms . initCmsObject ( cms ) ; m_cms . getRequestContext ( ) . setSiteRoot ( "" ) ; // first determine the common root of all open resources
findRoot ( allParamResources ) ; m_mustLoadChildren . add ( m_rootResource ) ; m_mustLoadChildren . addAll ( openResources ) ; // now load ancestors of all open resources
for ( CmsResource resource : allParamResources ) { loadAncestors ( resource ) ; } // ensure that all children of ancestors of open resources are loaded
loadChildren ( ) ; // finally create the beans for the loaded resources
return createBeans ( ) ; |
public class ManagementGroupVertex { /** * Returns the management vertex with the given index .
* @ param index
* the index of the management vertex to be returned
* @ return the management vertex with the given index or < code > null < / code > if no such vertex exists */
public ManagementVertex getGroupMember ( final int index ) { } } | if ( index < this . groupMembers . size ( ) ) { return this . groupMembers . get ( index ) ; } return null ; |
public class XMLAssert { /** * Assert the value of an Xpath expression in an XML document .
* @ param expectedValue
* @ param xpathExpression
* @ param control
* @ throws SAXException
* @ throws IOException
* @ see XpathEngine which provides the underlying evaluation mechanism */
public static void assertXpathEvaluatesTo ( String expectedValue , String xpathExpression , InputSource control ) throws SAXException , IOException , XpathException { } } | Document document = XMLUnit . buildControlDocument ( control ) ; assertXpathEvaluatesTo ( expectedValue , xpathExpression , document ) ; |
public class MD5 { /** * Update buffer with given string .
* @ param sString to be update to hash ( is used as
* s . getBytes ( ) ) */
final public void Update ( String s ) { } } | byte [ ] chars = s . getBytes ( ) ; // Changed on 2004-04-10 due to getBytes ( int , int , char [ ] , byte ) being deprecated
// bytechars [ ] ;
// chars = new byte [ s . length ( ) ] ;
// s . getBytes ( 0 , s . length ( ) , chars , 0 ) ;
Update ( chars , chars . length ) ; |
public class Utility { /** * Do a smart conversion of this object to an unfomatted string ( ie . , toString ) .
* @ param obj In
* @ return String out . */
public static String convertObjectToString ( Object objData ) { } } | if ( objData == null ) return null ; try { return Utility . convertObjectToString ( objData , objData . getClass ( ) , null ) ; } catch ( Exception ex ) { return null ; } |
public class SARLAgentMainLaunchConfigurationTab { /** * Loads the context identifier type from the launch configuration ' s preference store .
* @ param config the config to load the agent name from */
protected void updateContextIdentifierTypeFromConfig ( ILaunchConfiguration config ) { } } | final RootContextIdentifierType type = this . accessor . getDefaultContextIdentifier ( config ) ; assert type != null ; switch ( type ) { case RANDOM_CONTEXT_ID : this . randomContextIdentifierButton . setSelection ( true ) ; break ; case BOOT_AGENT_CONTEXT_ID : this . bootContextIdentifierButton . setSelection ( true ) ; break ; case DEFAULT_CONTEXT_ID : default : this . defaultContextIdentifierButton . setSelection ( true ) ; break ; } |
public class HttpHandler { /** * This method must be called in a Vert . X context . It finalizes the response and send it to the client .
* @ param context the HTTP context
* @ param request the Vert . x request
* @ param result the computed result
* @ param stream the stream of the result
* @ param success a flag indicating whether or not the request was successfully handled
* @ param handleFlashAndSessionCookie if the flash and session cookie need to be send with the response
* @ param closeConnection whehter or not the ( underlying ) TCP connection must be closed */
private void finalizeWriteReponse ( final ContextFromVertx context , final HttpServerRequest request , Result result , InputStream stream , boolean success , boolean handleFlashAndSessionCookie , boolean closeConnection ) { } } | Renderable < ? > renderable = result . getRenderable ( ) ; if ( renderable == null ) { renderable = NoHttpBody . INSTANCE ; } // Decide whether to close the connection or not .
boolean keepAlive = HttpUtils . isKeepAlive ( request ) ; // Build the response object .
final HttpServerResponse response = request . response ( ) ; // Copy headers from the result
for ( Map . Entry < String , String > header : result . getHeaders ( ) . entrySet ( ) ) { response . putHeader ( header . getKey ( ) , header . getValue ( ) ) ; } if ( ! result . getHeaders ( ) . containsKey ( HeaderNames . SERVER ) ) { // Add the server metadata
response . putHeader ( HeaderNames . SERVER , SERVER_NAME ) ; } String fullContentType = result . getFullContentType ( ) ; if ( fullContentType == null ) { if ( renderable . mimetype ( ) != null ) { response . putHeader ( HeaderNames . CONTENT_TYPE , renderable . mimetype ( ) ) ; } } else { response . putHeader ( HeaderNames . CONTENT_TYPE , fullContentType ) ; } // copy cookies / flash and session
if ( handleFlashAndSessionCookie ) { context . flash ( ) . save ( context , result ) ; context . session ( ) . save ( context , result ) ; } // copy cookies
for ( org . wisdom . api . cookies . Cookie cookie : result . getCookies ( ) ) { // Encode cookies :
final String encoded = ServerCookieEncoder . LAX . encode ( CookieHelper . convertWisdomCookieToNettyCookie ( cookie ) ) ; // Here we use the ' add ' method to add a new value to the header .
response . headers ( ) . add ( HeaderNames . SET_COOKIE , encoded ) ; } response . setStatusCode ( HttpUtils . getStatusFromResult ( result , success ) ) ; if ( renderable . mustBeChunked ( ) ) { LOGGER . debug ( "Building the chunked response for {} {} ({})" , request . method ( ) , request . uri ( ) , context ) ; if ( renderable . length ( ) > 0 && ! response . headers ( ) . contains ( HeaderNames . CONTENT_LENGTH ) ) { response . putHeader ( HeaderNames . CONTENT_LENGTH , Long . toString ( renderable . length ( ) ) ) ; } if ( ! response . headers ( ) . contains ( HeaderNames . CONTENT_TYPE ) ) { // No content is not legal , set default to binary .
response . putHeader ( HeaderNames . CONTENT_TYPE , MimeTypes . BINARY ) ; } // Can ' t determine the size , so switch to chunked .
response . setChunked ( true ) ; response . putHeader ( HeaderNames . TRANSFER_ENCODING , "chunked" ) ; // In addition , we can ' t keep the connection open .
response . putHeader ( HeaderNames . CONNECTION , "close" ) ; final AsyncInputStream s = new AsyncInputStream ( vertx , accessor . getExecutor ( ) , stream ) ; s . setContext ( context . vertxContext ( ) ) ; final Pump pump = Pump . pump ( s , response ) ; s . endHandler ( event -> context . vertxContext ( ) . runOnContext ( event1 -> { LOGGER . debug ( "Ending chunked response for {}" , request . uri ( ) ) ; response . end ( ) ; response . close ( ) ; cleanup ( context ) ; } ) ) ; s . exceptionHandler ( event -> context . vertxContext ( ) . runOnContext ( event1 -> { LOGGER . error ( "Cannot read the result stream" , event1 ) ; response . close ( ) ; cleanup ( context ) ; } ) ) ; context . vertxContext ( ) . runOnContext ( event -> pump . start ( ) ) ; } else { byte [ ] cont = new byte [ 0 ] ; try { cont = IOUtils . toByteArray ( stream ) ; } catch ( IOException e ) { LOGGER . error ( "Cannot copy the response to {}" , request . uri ( ) , e ) ; } if ( ! response . headers ( ) . contains ( HeaderNames . CONTENT_LENGTH ) ) { // Because of the HEAD implementation , if the length is already set , do not update it .
// ( HEAD would mean no content )
response . putHeader ( HeaderNames . CONTENT_LENGTH , Long . toString ( cont . length ) ) ; } if ( keepAlive ) { // Add keep alive header as per :
// - http : / / www . w3 . org / Protocols / HTTP / 1.1 / draft - ietf - http - v11 - spec - 01 . html # Connection
response . putHeader ( HeaderNames . CONNECTION , "keep-alive" ) ; } response . write ( Buffer . buffer ( cont ) ) ; if ( HttpUtils . isKeepAlive ( request ) && ! closeConnection ) { response . end ( ) ; } else { response . end ( ) ; response . close ( ) ; } cleanup ( context ) ; } |
public class Restarter { /** * Add additional URLs to be includes in the next restart .
* @ param urls the urls to add */
public void addUrls ( Collection < URL > urls ) { } } | Assert . notNull ( urls , "Urls must not be null" ) ; this . urls . addAll ( urls ) ; |
public class InternalXbaseParser { /** * InternalXbase . g : 1517:1 : ruleXCatchClause : ( ( rule _ _ XCatchClause _ _ Group _ _ 0 ) ) ; */
public final void ruleXCatchClause ( ) throws RecognitionException { } } | int stackSize = keepStackSize ( ) ; try { // InternalXbase . g : 1521:2 : ( ( ( rule _ _ XCatchClause _ _ Group _ _ 0 ) ) )
// InternalXbase . g : 1522:2 : ( ( rule _ _ XCatchClause _ _ Group _ _ 0 ) )
{ // InternalXbase . g : 1522:2 : ( ( rule _ _ XCatchClause _ _ Group _ _ 0 ) )
// InternalXbase . g : 1523:3 : ( rule _ _ XCatchClause _ _ Group _ _ 0 )
{ if ( state . backtracking == 0 ) { before ( grammarAccess . getXCatchClauseAccess ( ) . getGroup ( ) ) ; } // InternalXbase . g : 1524:3 : ( rule _ _ XCatchClause _ _ Group _ _ 0 )
// InternalXbase . g : 1524:4 : rule _ _ XCatchClause _ _ Group _ _ 0
{ pushFollow ( FOLLOW_2 ) ; rule__XCatchClause__Group__0 ( ) ; state . _fsp -- ; if ( state . failed ) return ; } if ( state . backtracking == 0 ) { after ( grammarAccess . getXCatchClauseAccess ( ) . getGroup ( ) ) ; } } } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; } finally { restoreStackSize ( stackSize ) ; } return ; |
public class WordNet { /** * Gets the sense for the associated information
* @ param word The word
* @ param pos The part of speech
* @ param senseNum The sense number
* @ param language The language
* @ return The sense */
public Optional < Sense > getSense ( @ NonNull String word , @ NonNull POS pos , int senseNum , @ NonNull Language language ) { } } | for ( String lemma : Lemmatizers . getLemmatizer ( language ) . allPossibleLemmas ( word , pos ) ) { for ( Sense sense : db . getSenses ( lemma . toLowerCase ( ) ) ) { if ( ( pos == POS . ANY || pos . isInstance ( sense . getPOS ( ) ) ) && sense . getSenseNumber ( ) == senseNum && sense . getLanguage ( ) == language ) { return Optional . of ( sense ) ; } } } return Optional . empty ( ) ; |
public class SqlInfoBuilder { /** * 构建普通查询需要的SqlInfo信息 .
* @ param fieldText 数据库字段的文本
* @ param value 参数值
* @ param suffix 后缀 , 如 : 大于 、 等于 、 小于等
* @ return sqlInfo */
public SqlInfo buildNormalSql ( String fieldText , Object value , String suffix ) { } } | join . append ( prefix ) . append ( fieldText ) . append ( suffix ) ; params . add ( value ) ; return sqlInfo . setJoin ( join ) . setParams ( params ) ; |
public class ReflectionUtils { /** * Squishy way to find a setter method .
* @ param onClass , targetClass */
public static Method findSetter ( Class < ? > onClass , Class < ? > targetClass ) { } } | Method [ ] methods = onClass . getMethods ( ) ; for ( Method method : methods ) { Class < ? > [ ] ptypes = method . getParameterTypes ( ) ; if ( method . getName ( ) . startsWith ( "set" ) && ptypes . length == 1 && ptypes [ 0 ] == targetClass ) { // $ NON - NLS - 1 $
return method ; } } return null ; |
public class CmsSearchWidgetDialog { /** * Returns the creation date the resources have to have as minimum . < p >
* @ return the creation date the resources have to have as minimum */
public String getMinDateCreated ( ) { } } | if ( m_searchParams . getMinDateCreated ( ) == Long . MIN_VALUE ) { return "" ; } return Long . toString ( m_searchParams . getMinDateCreated ( ) ) ; |
public class AlertBean { /** * Creates default alert as in { @ link # create ( AlertType , String ) } with dismiss functionality . */
public static AlertBean createDismissible ( AlertType type , String message ) { } } | final AlertBean result = create ( type , message ) ; result . setDismissible ( true ) ; return result ; |
public class AmazonCloudFormationClient { /** * Returns descriptions of all resources of the specified stack .
* For deleted stacks , ListStackResources returns resource information for up to 90 days after the stack has been
* deleted .
* @ param listStackResourcesRequest
* The input for the < a > ListStackResource < / a > action .
* @ return Result of the ListStackResources operation returned by the service .
* @ sample AmazonCloudFormation . ListStackResources
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / cloudformation - 2010-05-15 / ListStackResources "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public ListStackResourcesResult listStackResources ( ListStackResourcesRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListStackResources ( request ) ; |
public class Matrix3x2f { /** * Apply shearing to this matrix by shearing along the Y axis using the X axis factor < code > xFactor < / code > ,
* and store the result in < code > dest < / code > .
* @ param xFactor
* the factor for the X component to shear along the Y axis
* @ param dest
* will hold the result
* @ return dest */
public Matrix3x2f shearY ( float xFactor , Matrix3x2f dest ) { } } | float nm00 = m00 + m10 * xFactor ; float nm01 = m01 + m11 * xFactor ; dest . m00 = nm00 ; dest . m01 = nm01 ; dest . m10 = m10 ; dest . m11 = m11 ; dest . m20 = m20 ; dest . m21 = m21 ; return dest ; |
public class BloomFilter { /** * rather than using the threadLocal like we do in production */
@ VisibleForTesting public long [ ] getHashBuckets ( ByteBuffer key , int hashCount , long max ) { } } | long [ ] hash = new long [ 2 ] ; hash ( key , key . position ( ) , key . remaining ( ) , 0L , hash ) ; long [ ] indexes = new long [ hashCount ] ; setIndexes ( hash [ 0 ] , hash [ 1 ] , hashCount , max , indexes ) ; return indexes ; |
public class WithMavenStepExecution2 { /** * Detects if this step is running inside < code > docker . image ( ) < / code > or < code > container ( ) < / code >
* This has the following implications :
* < li > Tool intallers do no work , as they install in the host , see :
* https : / / issues . jenkins - ci . org / browse / JENKINS - 36159
* < li > Environment variables do not apply because they belong either to the master or the agent , but not to the
* container running the < code > sh < / code > command for maven This is due to the fact that < code > docker . image ( ) < / code > all it
* does is decorate the launcher and excute the command with a < code > docker run < / code > which means that the inherited
* environment from the OS will be totally different eg : MAVEN _ HOME , JAVA _ HOME , PATH , etc .
* < li > Kubernetes ' < code > container ( ) < / code > support is still in early stages , and environment variables might not be
* completely configured , depending on the version of the Jenkins Kubernetes plugin .
* @ return true if running inside a container with < code > docker . image ( ) < / code > or < code > container ( ) < / code >
* @ see < a href =
* " https : / / github . com / jenkinsci / docker - workflow - plugin / blob / master / src / main / java / org / jenkinsci / plugins / docker / workflow / WithContainerStep . java " >
* WithContainerStep < / a > and < a href =
* " https : / / github . com / jenkinsci / kubernetes - plugin / blob / master / src / main / java / org / csanchez / jenkins / plugins / kubernetes / pipeline / ContainerStep . java " >
* ContainerStep < / a > */
private boolean detectWithContainer ( ) { } } | Launcher launcher1 = launcher ; while ( launcher1 instanceof Launcher . DecoratedLauncher ) { String launcherClassName = launcher1 . getClass ( ) . getName ( ) ; if ( launcherClassName . contains ( "org.csanchez.jenkins.plugins.kubernetes.pipeline.ContainerExecDecorator" ) ) { LOGGER . log ( Level . FINE , "Step running within Kubernetes withContainer(): {1}" , launcherClassName ) ; return false ; } if ( launcherClassName . contains ( "WithContainerStep" ) ) { LOGGER . log ( Level . FINE , "Step running within docker.image(): {1}" , launcherClassName ) ; return true ; } else if ( launcherClassName . contains ( "ContainerExecDecorator" ) ) { LOGGER . log ( Level . FINE , "Step running within docker.image(): {1}" , launcherClassName ) ; return true ; } launcher1 = ( ( Launcher . DecoratedLauncher ) launcher1 ) . getInner ( ) ; } return false ; |
public class SessionContext { /** * Associates the current { @ code HttpSession } with this instance .
* @ param context The current { @ code HttpSession } . */
public void associate ( HttpSession context ) { } } | try { context . setAttribute ( COMPONENTS , new ConcurrentHashMap < Descriptor < ? > , Object > ( ) ) ; } catch ( Exception e ) { logger . debug ( "HTTP session is disabled or invalid in the current environment" , e ) ; } |
public class TypedProperties { /** * Equivalent to { @ link # getLong ( String , long )
* getLong } { @ code ( key . name ( ) , defaultValue ) } .
* If { @ code key } is null , { @ code defaultValue } is returned . */
public long getLong ( Enum < ? > key , long defaultValue ) { } } | if ( key == null ) { return defaultValue ; } return getLong ( key . name ( ) , defaultValue ) ; |
public class CodeWriter { /** * TODO ( jwilson ) : also honor superclass members when resolving names . */
private ClassName resolve ( String simpleName ) { } } | // Match a child of the current ( potentially nested ) class .
for ( int i = typeSpecStack . size ( ) - 1 ; i >= 0 ; i -- ) { TypeSpec typeSpec = typeSpecStack . get ( i ) ; if ( typeSpec . nestedTypesSimpleNames . contains ( simpleName ) ) { return stackClassName ( i , simpleName ) ; } } // Match the top - level class .
if ( typeSpecStack . size ( ) > 0 && Objects . equals ( typeSpecStack . get ( 0 ) . name , simpleName ) ) { return ClassName . get ( packageName , simpleName ) ; } // Match an imported type .
ClassName importedType = importedTypes . get ( simpleName ) ; if ( importedType != null ) return importedType ; // No match .
return null ; |
public class DateMidnight { /** * Returns a copy of this date with the specified duration added .
* If the addition is zero , then < code > this < / code > is returned .
* @ param durationToAdd the duration to add to this one , null means zero
* @ param scalar the amount of times to add , such as - 1 to subtract once
* @ return a copy of this datetime with the duration added
* @ throws ArithmeticException if the new datetime exceeds the capacity of a long */
public DateMidnight withDurationAdded ( ReadableDuration durationToAdd , int scalar ) { } } | if ( durationToAdd == null || scalar == 0 ) { return this ; } return withDurationAdded ( durationToAdd . getMillis ( ) , scalar ) ; |
public class HttpServer { /** * Get an array of FilterConfiguration specified in the conf */
private static FilterInitializer [ ] getFilterInitializers ( Configuration conf ) { } } | if ( conf == null ) { return null ; } Class < ? > [ ] classes = conf . getClasses ( FILTER_INITIALIZER_PROPERTY ) ; if ( classes == null ) { return null ; } FilterInitializer [ ] initializers = new FilterInitializer [ classes . length ] ; for ( int i = 0 ; i < classes . length ; i ++ ) { initializers [ i ] = ( FilterInitializer ) ReflectionUtils . newInstance ( classes [ i ] , conf ) ; } return initializers ; |
public class MethodBuilder { /** * Add proxy method that exposes the linkToDeath */
private void addProxyDeathMethod ( TypeSpec . Builder classBuilder , String deathMethod , String doc ) { } } | MethodSpec . Builder methodBuilder = MethodSpec . methodBuilder ( deathMethod ) . addModifiers ( Modifier . PUBLIC ) . returns ( TypeName . VOID ) . addParameter ( ClassName . get ( "android.os" , "IBinder.DeathRecipient" ) , "deathRecipient" ) . beginControlFlow ( "try" ) . addStatement ( "mRemote." + deathMethod + "(deathRecipient, 0)" ) . endControlFlow ( ) . beginControlFlow ( "catch ($T ignored)" , Exception . class ) . endControlFlow ( ) . addJavadoc ( doc ) ; classBuilder . addMethod ( methodBuilder . build ( ) ) ; |
public class ListDeploymentInstancesResult { /** * A list of instance IDs .
* @ param instancesList
* A list of instance IDs . */
public void setInstancesList ( java . util . Collection < String > instancesList ) { } } | if ( instancesList == null ) { this . instancesList = null ; return ; } this . instancesList = new com . amazonaws . internal . SdkInternalList < String > ( instancesList ) ; |
public class HostVsanSystem { /** * Recommission this host to VSAN cluster .
* Users may use this API to recommission a node that has been evacuated in VsanHostDecommissionMode .
* @ return This method returns a Task object with which to monitor the operation .
* @ throws InvalidState
* @ throws RuntimeFault
* @ throws VsanFault
* @ throws RemoteException
* @ see com . vmware . vim25 . mo . HostVsanSystem # evacuateVsanNode _ Task
* @ see VsanHostDecommissionMode
* @ since 6.0 */
public Task recommissionVsanNode_Task ( ) throws InvalidState , RuntimeFault , VsanFault , RemoteException { } } | return new Task ( getServerConnection ( ) , getVimService ( ) . recommissionVsanNode_Task ( getMOR ( ) ) ) ; |
public class RoundedMoney { /** * ( non - Javadoc )
* @ see javax . money . MonetaryAmount # scaleByPowerOfTen ( int ) */
@ Override public RoundedMoney scaleByPowerOfTen ( int n ) { } } | return new RoundedMoney ( number . scaleByPowerOfTen ( n ) , currency , rounding ) ; |
public class NettyNetworkService { /** * Waits for the underlying network service to terminate .
* @ param timeout Maximum time to wait in seconds .
* @ return { @ code true } if the underlying network service has terminated , { @ code false } if the underlying network
* service is still active after waiting the specified time .
* @ throws InterruptedException if the thread performing the operation is interrupted . */
public boolean awaitTermination ( long timeout ) throws InterruptedException { } } | final String methodName = "awaitTermination" ; logger . entry ( methodName ) ; final boolean terminated ; if ( bootstrap != null ) { terminated = bootstrap . group ( ) . awaitTermination ( timeout , TimeUnit . SECONDS ) ; } else { terminated = true ; } logger . exit ( methodName , terminated ) ; return terminated ; |
public class OperationValidationFactory { /** * / * ( non - Javadoc )
* @ see com . impetus . kundera . validation . AbstractValidationFactory # validate ( java . lang . reflect . Field , java . lang . Object , com . impetus . kundera . validation . rules . IRule [ ] ) */
@ Override public boolean validate ( Field field , Object fieldValue , IRule ... rules ) throws RuleValidationException { } } | if ( rules == null ) { return super . validate ( field , fieldValue , this . ruleFactory . getJpaRules ( ) ) ; } else { return super . validate ( field , fieldValue , rules ) ; } |
public class UnitRequest { /** * { @ link # getList ( String , Class ) } 的快捷方式 , 不过需要你自己注意类型转换异常 */
@ SuppressWarnings ( "unchecked" ) public < T > List < T > getList ( String key ) { } } | return Reflection . toType ( get ( key ) , List . class ) ; |
public class WhiteboxImpl { /** * Checks if is potential var args method .
* @ param method the method
* @ param arguments the arguments
* @ return true , if is potential var args method */
private static boolean isPotentialVarArgsMethod ( Method method , Object [ ] arguments ) { } } | return doesParameterTypesMatchForVarArgsInvocation ( method . isVarArgs ( ) , method . getParameterTypes ( ) , arguments ) ; |
public class ClassReader { /** * Creates a label with the Label . DEBUG flag set , if there is no already
* existing label for the given offset ( otherwise does nothing ) . The label
* is created with a call to { @ link # readLabel } .
* @ param offset
* a bytecode offset in a method .
* @ param labels
* the already created labels , indexed by their offset . */
private void createDebugLabel ( int offset , Label [ ] labels ) { } } | if ( labels [ offset ] == null ) { readLabel ( offset , labels ) . status |= Label . DEBUG ; } |
public class CmsSecurityManager { /** * Creates a new user . < p >
* @ param context the current request context
* @ param name the name for the new user
* @ param password the password for the new user
* @ param description the description for the new user
* @ param additionalInfos the additional infos for the user
* @ return the created user
* @ see CmsObject # createUser ( String , String , String , Map )
* @ throws CmsException if something goes wrong
* @ throws CmsRoleViolationException if the current user does not own the rule { @ link CmsRole # ACCOUNT _ MANAGER } */
public CmsUser createUser ( CmsRequestContext context , String name , String password , String description , Map < String , Object > additionalInfos ) throws CmsException , CmsRoleViolationException { } } | CmsDbContext dbc = m_dbContextFactory . getDbContext ( context ) ; CmsUser result = null ; try { checkRole ( dbc , CmsRole . ACCOUNT_MANAGER . forOrgUnit ( getParentOrganizationalUnit ( name ) ) ) ; result = m_driverManager . createUser ( dbc , CmsOrganizationalUnit . removeLeadingSeparator ( name ) , password , description , additionalInfos ) ; } catch ( Exception e ) { dbc . report ( null , Messages . get ( ) . container ( Messages . ERR_CREATE_USER_1 , name ) , e ) ; } finally { dbc . clear ( ) ; } return result ; |
public class CMMClassifier { /** * Build a Dataset from some data . Used for training a classifier .
* By passing in extra featureIndex and classIndex , you can get a Dataset based on featureIndex and
* classIndex
* @ param data This variable is a list of lists of CoreLabel . That is ,
* it is a collection of documents , each of which is represented
* as a sequence of CoreLabel objects .
* @ param classIndex if you want to get a Dataset based on featureIndex and
* classIndex in an existing origDataset
* @ return The Dataset which is an efficient encoding of the information
* in a List of Datums */
public Dataset < String , String > getDataset ( Collection < List < IN > > data , Index < String > featureIndex , Index < String > classIndex ) { } } | makeAnswerArraysAndTagIndex ( data ) ; int size = 0 ; for ( List < IN > doc : data ) { size += doc . size ( ) ; } System . err . println ( "Making Dataset..." ) ; Dataset < String , String > train ; if ( featureIndex != null && classIndex != null ) { System . err . println ( "Using feature/class Index from existing Dataset..." ) ; System . err . println ( "(This is used when getting Dataset from adaptation set. We want to make the index consistent.)" ) ; // pichuan
train = new Dataset < String , String > ( size , featureIndex , classIndex ) ; } else { train = new Dataset < String , String > ( size ) ; } for ( List < IN > doc : data ) { if ( flags . useReverse ) { Collections . reverse ( doc ) ; } for ( int i = 0 , dsize = doc . size ( ) ; i < dsize ; i ++ ) { Datum < String , String > d = makeDatum ( doc , i , featureFactory ) ; // CoreLabel fl = doc . get ( i ) ;
train . add ( d ) ; } if ( flags . useReverse ) { Collections . reverse ( doc ) ; } } System . err . println ( "done." ) ; // reset printing before test data
// what is this ? ? ? ? - JRF
// if ( featureFactory instanceof FeatureFactory ) {
// ( ( FeatureFactory ) featureFactory ) . resetPrintFeatures ( ) ;
if ( flags . featThreshFile != null ) { System . err . println ( "applying thresholds..." ) ; List < Pair < Pattern , Integer > > thresh = getThresholds ( flags . featThreshFile ) ; train . applyFeatureCountThreshold ( thresh ) ; } else if ( flags . featureThreshold > 1 ) { System . err . println ( "Removing Features with counts < " + flags . featureThreshold ) ; train . applyFeatureCountThreshold ( flags . featureThreshold ) ; } train . summaryStatistics ( ) ; return train ; |
public class ShareDirectoryRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ShareDirectoryRequest shareDirectoryRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( shareDirectoryRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( shareDirectoryRequest . getDirectoryId ( ) , DIRECTORYID_BINDING ) ; protocolMarshaller . marshall ( shareDirectoryRequest . getShareNotes ( ) , SHARENOTES_BINDING ) ; protocolMarshaller . marshall ( shareDirectoryRequest . getShareTarget ( ) , SHARETARGET_BINDING ) ; protocolMarshaller . marshall ( shareDirectoryRequest . getShareMethod ( ) , SHAREMETHOD_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class JSONEmitter { /** * Add a one - field object consisting of the given name and string value . This
* generates the JSON text :
* < pre >
* { " name " : " value " }
* < / pre >
* @ param name Name of new field .
* @ param value Value of new field as a string .
* @ return The same JSONEmitter object , which allows call chaining . */
public JSONEmitter addObject ( String name , String value ) { } } | checkComma ( ) ; write ( "{\"" ) ; write ( encodeString ( name ) ) ; write ( "\":\"" ) ; if ( value != null ) { write ( encodeString ( value ) ) ; } write ( "\"}" ) ; return this ; |
public class PatternPathMotion { /** * Sets the Path defining a pattern of motion between two coordinates .
* The pattern will be translated , rotated , and scaled to fit between the start and end points .
* The pattern must not be empty and must have the end point differ from the start point .
* @ param patternPath A Path to be used as a pattern for two - dimensional motion .
* @ attr ref android . R . styleable # PatternPathMotion _ patternPathData */
public void setPatternPath ( @ Nullable Path patternPath ) { } } | PathMeasure pathMeasure = new PathMeasure ( patternPath , false ) ; float length = pathMeasure . getLength ( ) ; float [ ] pos = new float [ 2 ] ; pathMeasure . getPosTan ( length , pos , null ) ; float endX = pos [ 0 ] ; float endY = pos [ 1 ] ; pathMeasure . getPosTan ( 0 , pos , null ) ; float startX = pos [ 0 ] ; float startY = pos [ 1 ] ; if ( startX == endX && startY == endY ) { throw new IllegalArgumentException ( "pattern must not end at the starting point" ) ; } mTempMatrix . setTranslate ( - startX , - startY ) ; float dx = endX - startX ; float dy = endY - startY ; float distance = ( float ) Math . hypot ( dx , dy ) ; float scale = 1 / distance ; mTempMatrix . postScale ( scale , scale ) ; double angle = Math . atan2 ( dy , dx ) ; mTempMatrix . postRotate ( ( float ) Math . toDegrees ( - angle ) ) ; if ( patternPath != null ) { patternPath . transform ( mTempMatrix , mPatternPath ) ; } mOriginalPatternPath = patternPath ; |
public class DoubleArrayList { /** * Returns the index of the first occurrence of the specified
* element . Returns < code > - 1 < / code > if the receiver does not contain this element .
* Searches between < code > from < / code > , inclusive and < code > to < / code > , inclusive .
* Tests for identity .
* @ param element element to search for .
* @ param from the leftmost search position , inclusive .
* @ param to the rightmost search position , inclusive .
* @ return the index of the first occurrence of the element in the receiver ; returns < code > - 1 < / code > if the element is not found .
* @ exception IndexOutOfBoundsException index is out of range ( < tt > size ( ) & gt ; 0 & & ( from & lt ; 0 | | from & gt ; to | | to & gt ; = size ( ) ) < / tt > ) . */
public int indexOfFromTo ( double element , int from , int to ) { } } | // overridden for performance only .
if ( size == 0 ) return - 1 ; checkRangeFromTo ( from , to , size ) ; double [ ] theElements = elements ; for ( int i = from ; i <= to ; i ++ ) { if ( element == theElements [ i ] ) { return i ; } // found
} return - 1 ; // not found |
public class PageBuffer { /** * Return a page from the buffer , or null if none exists */
public synchronized Page poll ( ) { } } | if ( settableFuture != null ) { settableFuture . set ( null ) ; settableFuture = null ; } return pages . poll ( ) ; |
public class DomUtils { /** * transforms a string into a Document object . TODO This needs more optimizations . As it seems
* the getDocument is called way too much times causing a lot of parsing which is slow and not
* necessary .
* @ param html the HTML string .
* @ return The DOM Document version of the HTML string .
* @ throws IOException if an IO failure occurs . */
public static Document asDocument ( String html ) throws IOException { } } | DOMParser domParser = new DOMParser ( ) ; try { domParser . setProperty ( "http://cyberneko.org/html/properties/names/elems" , "match" ) ; domParser . setFeature ( "http://xml.org/sax/features/namespaces" , false ) ; domParser . parse ( new InputSource ( new StringReader ( html ) ) ) ; } catch ( SAXException e ) { throw new IOException ( "Error while reading HTML: " + html , e ) ; } return domParser . getDocument ( ) ; |
public class MarkTimingTypeAdapter { /** * ( non - Javadoc )
* @ see com . google . gson . TypeAdapter # read ( com . google . gson . stream . JsonReader ) */
@ Override public MarkTiming read ( JsonReader in ) throws IOException { } } | if ( in . peek ( ) == JsonToken . NULL ) { in . nextNull ( ) ; return null ; } final MarkTiming markTiming = new MarkTiming ( ) ; in . beginArray ( ) ; if ( in . peek ( ) == JsonToken . STRING ) { markTiming . setMark ( in . nextString ( ) ) ; } if ( in . peek ( ) == JsonToken . NUMBER ) { markTiming . setTime ( in . nextDouble ( ) ) ; } in . endArray ( ) ; return markTiming ; |
public class TransactionableDataManager { /** * { @ inheritDoc } */
public boolean getChildNodesDataByPage ( final NodeData parent , int fromOrderNum , int offset , int pageSize , List < NodeData > childs ) throws RepositoryException { } } | boolean hasNext = storageDataManager . getChildNodesDataByPage ( parent , fromOrderNum , offset , pageSize , childs ) ; if ( txStarted ( ) ) { // merge data
List < ItemState > txChanges = transactionLog . getChildrenChanges ( parent . getIdentifier ( ) , true ) ; if ( txChanges . size ( ) > 0 ) { int minOrderNum = childs . size ( ) != 0 ? childs . get ( 0 ) . getOrderNumber ( ) : - 1 ; int maxOrderNum = childs . size ( ) != 0 ? childs . get ( childs . size ( ) - 1 ) . getOrderNumber ( ) : - 1 ; for ( ItemState state : txChanges ) { NodeData data = ( NodeData ) state . getData ( ) ; if ( ( state . isAdded ( ) || state . isRenamed ( ) || state . isPathChanged ( ) ) && ! hasNext ) { childs . add ( data ) ; } else if ( state . isDeleted ( ) ) { childs . remove ( data ) ; } else if ( state . isMixinChanged ( ) || state . isUpdated ( ) ) { childs . remove ( state . getData ( ) ) ; if ( minOrderNum <= data . getOrderNumber ( ) && data . getOrderNumber ( ) <= maxOrderNum ) { childs . add ( data ) ; } } } } } return hasNext ; |
public class GreenPepperXmlRpcServer { /** * { @ inheritDoc } */
public Vector < Object > getRequirementSummary ( Vector < Object > requirementParams ) { } } | try { Requirement requirement = XmlRpcDataMarshaller . toRequirement ( requirementParams ) ; RequirementSummary requirementSummary = service . getRequirementSummary ( requirement ) ; log . debug ( "Retrieved Requirement " + requirement . getName ( ) + " Summary" ) ; return requirementSummary . marshallize ( ) ; } catch ( Exception e ) { return new RequirementSummary ( ) . marshallize ( ) ; } |
public class EncryptionInfoMarshaller { /** * Marshall the given parameter object . */
public void marshall ( EncryptionInfo encryptionInfo , ProtocolMarshaller protocolMarshaller ) { } } | if ( encryptionInfo == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( encryptionInfo . getEncryptionAtRest ( ) , ENCRYPTIONATREST_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class WsFederationNavigationController { /** * Redirect to provider . Receive the client name from the request and then try to determine and build the endpoint url
* for the redirection . The redirection data / url must contain a delegated client ticket id so that the request be can
* restored on the trip back . SAML clients use the relay - state session attribute while others use request parameters .
* @ param request the request
* @ param response the response
* @ return the view */
@ GetMapping ( ENDPOINT_REDIRECT ) public View redirectToProvider ( final HttpServletRequest request , final HttpServletResponse response ) { } } | val wsfedId = request . getParameter ( PARAMETER_NAME ) ; try { val cfg = configurations . stream ( ) . filter ( c -> c . getId ( ) . equals ( wsfedId ) ) . findFirst ( ) . orElse ( null ) ; if ( cfg == null ) { throw new IllegalArgumentException ( "Could not locate WsFederation configuration for " + wsfedId ) ; } val service = determineService ( request ) ; val id = wsFederationHelper . getRelyingPartyIdentifier ( service , cfg ) ; val url = cfg . getAuthorizationUrl ( id , cfg . getId ( ) ) ; wsFederationCookieManager . store ( request , response , cfg . getId ( ) , service , cfg ) ; return new RedirectView ( url ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , StringUtils . EMPTY ) ; |
public class VictimsSQL { /** * Given a hash get the first occurance ' s record id .
* @ param hash
* @ return
* @ throws SQLException */
protected int selectRecordId ( String hash ) throws SQLException { } } | int id = - 1 ; Connection connection = getConnection ( ) ; try { PreparedStatement ps = setObjects ( connection , Query . GET_RECORD_ID , hash ) ; ResultSet rs = ps . executeQuery ( ) ; try { while ( rs . next ( ) ) { id = rs . getInt ( "id" ) ; break ; } } finally { rs . close ( ) ; ps . close ( ) ; } } finally { connection . close ( ) ; } return id ; |
public class I18nSync { /** * Entry point for command line tool . */
public static void main ( String [ ] args ) { } } | if ( args . length <= 1 ) { System . err . println ( "Usage: I18nSyncTask rootDir rootDir/com/mypackage/Foo.properties " + "[.../Bar.properties ...]" ) ; System . exit ( 255 ) ; } File rootDir = new File ( args [ 0 ] ) ; if ( ! rootDir . isDirectory ( ) ) { System . err . println ( "Invalid root directory: " + rootDir ) ; System . exit ( 255 ) ; } I18nSync tool = new I18nSync ( ) ; boolean errors = false ; for ( int ii = 1 ; ii < args . length ; ii ++ ) { try { tool . process ( rootDir , new File ( args [ ii ] ) ) ; } catch ( IOException ioe ) { System . err . println ( "Error processing '" + args [ ii ] + "': " + ioe ) ; errors = true ; } } System . exit ( errors ? 255 : 0 ) ; |
public class OptionsHttpSessionsPanel { /** * Gets the chk proxy only .
* @ return the chk proxy only */
private JCheckBox getChkProxyOnly ( ) { } } | if ( proxyOnlyCheckbox == null ) { proxyOnlyCheckbox = new JCheckBox ( ) ; proxyOnlyCheckbox . setText ( Constant . messages . getString ( "httpsessions.options.label.proxyOnly" ) ) ; } return proxyOnlyCheckbox ; |
public class Searcher { /** * Constructs a Searcher , creating its { @ link Searcher # searchable } and { @ link Searcher # client } with the given parameters .
* @ param appId your Algolia Application ID .
* @ param apiKey a search - only API Key . ( never use API keys that could modify your records ! see https : / / www . algolia . com / doc / guides / security / api - keys )
* @ param indexName the name of the searchable to target .
* @ return the new instance . */
@ SuppressWarnings ( { } } | "WeakerAccess" , "unused" } ) // For library users
public static Searcher create ( @ NonNull final String appId , @ NonNull final String apiKey , @ NonNull final String indexName ) { return create ( new Client ( appId , apiKey ) . getIndex ( indexName ) , indexName ) ; |
public class InheritanceHelper { /** * Extract and replies the Ecore type , provided by { @ link SarlPackage } for the given JvmElement .
* @ param type the JVM type to test .
* @ return the code of the type , see { @ link SarlPackage } ; or { @ code 0 } if the code is unknown .
* @ since 0.6 */
public int getSarlElementEcoreType ( JvmGenericType type ) { } } | final JvmAnnotationReference annotationRef = this . annotationUtil . findAnnotation ( type , SarlElementType . class . getName ( ) ) ; if ( annotationRef != null ) { final Integer intValue = this . annotationUtil . findIntValue ( annotationRef ) ; if ( intValue != null ) { return intValue . intValue ( ) ; } } return 0 ; |
public class NamingLocator { /** * Returns the naming context . */
public static Context getContext ( ) { } } | if ( ctx == null ) { try { setContext ( null ) ; } catch ( Exception e ) { log . error ( "Cannot instantiate the InitialContext" , e ) ; throw new OJBRuntimeException ( e ) ; } } return ctx ; |
public class AbstractServer { /** * Create a new evaluation iterator from the given stream . */
private static evaluate_response newEvalStream ( Stream < Collection < CollectHistory . NamedEvaluation > > tsc , int fetch ) { } } | final BufferedIterator < Collection < CollectHistory . NamedEvaluation > > iter = new BufferedIterator ( tsc . iterator ( ) , EVAL_QUEUE_SIZE ) ; final long idx = EVAL_ITERS_ALLOC . getAndIncrement ( ) ; final IteratorAndCookie < Collection < CollectHistory . NamedEvaluation > > iterAndCookie = new IteratorAndCookie < > ( iter ) ; EVAL_ITERS . put ( idx , iterAndCookie ) ; final List < Collection < CollectHistory . NamedEvaluation > > result = fetchFromIter ( iter , fetch , MAX_EVAL_FETCH ) ; EncDec . NewIterResponse < Collection < CollectHistory . NamedEvaluation > > responseObj = new EncDec . NewIterResponse < > ( idx , result , iter . atEnd ( ) , iterAndCookie . getCookie ( ) ) ; LOG . log ( Level . FINE , "responseObj = {0}" , responseObj ) ; return EncDec . encodeEvaluateResponse ( responseObj ) ; |
public class Controller { /** * Calls startActivity ( Intent ) from this Controller ' s host Activity . */
public final void startActivity ( @ NonNull final Intent intent ) { } } | executeWithRouter ( new RouterRequiringFunc ( ) { @ Override public void execute ( ) { router . startActivity ( intent ) ; } } ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.