repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
192
func_name
stringlengths
5
108
whole_func_string
stringlengths
75
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.91k
func_code_tokens
listlengths
21
629
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
111
306
foundation-runtime/service-directory
2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java
ServiceInstanceUtils.isOptionalFieldValid
public static boolean isOptionalFieldValid(String field, String reg) { if (field == null || field.length() == 0) { return true; } return Pattern.matches(reg, field); }
java
public static boolean isOptionalFieldValid(String field, String reg) { if (field == null || field.length() == 0) { return true; } return Pattern.matches(reg, field); }
[ "public", "static", "boolean", "isOptionalFieldValid", "(", "String", "field", ",", "String", "reg", ")", "{", "if", "(", "field", "==", "null", "||", "field", ".", "length", "(", ")", "==", "0", ")", "{", "return", "true", ";", "}", "return", "Pattern...
Validate the optional field String against regex. @param field the field value String. @param reg the regex. @return true if field is empty of matched the pattern.
[ "Validate", "the", "optional", "field", "String", "against", "regex", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/ServiceInstanceUtils.java#L92-L97
wisdom-framework/wisdom
extensions/wisdom-raml/wisdom-source-watcher/src/main/java/org/wisdom/source/ast/visitor/ClassSourceVisitor.java
ClassSourceVisitor.containsClassName
private boolean containsClassName(List<ClassOrInterfaceType> klassList, Set<String> simpleNames) { for (ClassOrInterfaceType ctype : klassList) { if (simpleNames.contains(ctype.getName())) { return true; } } return false; }
java
private boolean containsClassName(List<ClassOrInterfaceType> klassList, Set<String> simpleNames) { for (ClassOrInterfaceType ctype : klassList) { if (simpleNames.contains(ctype.getName())) { return true; } } return false; }
[ "private", "boolean", "containsClassName", "(", "List", "<", "ClassOrInterfaceType", ">", "klassList", ",", "Set", "<", "String", ">", "simpleNames", ")", "{", "for", "(", "ClassOrInterfaceType", "ctype", ":", "klassList", ")", "{", "if", "(", "simpleNames", "...
Check if the list of class or interface contains a class which name is given in the <code>simpleNames</code> set. @param klassList The list of class or interface @param simpleNames a set of class simple name. @return <code>true</code> if the list contains a class or interface which name is present in the <code>simpleNames</code> set.
[ "Check", "if", "the", "list", "of", "class", "or", "interface", "contains", "a", "class", "which", "name", "is", "given", "in", "the", "<code", ">", "simpleNames<", "/", "code", ">", "set", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-raml/wisdom-source-watcher/src/main/java/org/wisdom/source/ast/visitor/ClassSourceVisitor.java#L129-L136
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java
Log.printRawLines
public static void printRawLines(PrintWriter writer, String msg) { int nl; while ((nl = msg.indexOf('\n')) != -1) { writer.println(msg.substring(0, nl)); msg = msg.substring(nl+1); } if (msg.length() != 0) writer.println(msg); }
java
public static void printRawLines(PrintWriter writer, String msg) { int nl; while ((nl = msg.indexOf('\n')) != -1) { writer.println(msg.substring(0, nl)); msg = msg.substring(nl+1); } if (msg.length() != 0) writer.println(msg); }
[ "public", "static", "void", "printRawLines", "(", "PrintWriter", "writer", ",", "String", "msg", ")", "{", "int", "nl", ";", "while", "(", "(", "nl", "=", "msg", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "{", "writer", ".", "p...
Print the text of a message, translating newlines appropriately for the platform.
[ "Print", "the", "text", "of", "a", "message", "translating", "newlines", "appropriately", "for", "the", "platform", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java#L615-L622
Erudika/para
para-server/src/main/java/com/erudika/para/security/SecurityUtils.java
SecurityUtils.checkIfActive
public static UserAuthentication checkIfActive(UserAuthentication userAuth, User user, boolean throwException) { if (userAuth == null || user == null || user.getIdentifier() == null) { if (throwException) { throw new BadCredentialsException("Bad credentials."); } else { logger.debug("Bad credentials. {}", userAuth); return null; } } else if (!user.getActive()) { if (throwException) { throw new LockedException("Account " + user.getId() + " (" + user.getAppid() + "/" + user.getIdentifier() + ") is locked."); } else { logger.warn("Account {} ({}/{}) is locked.", user.getId(), user.getAppid(), user.getIdentifier()); return null; } } return userAuth; }
java
public static UserAuthentication checkIfActive(UserAuthentication userAuth, User user, boolean throwException) { if (userAuth == null || user == null || user.getIdentifier() == null) { if (throwException) { throw new BadCredentialsException("Bad credentials."); } else { logger.debug("Bad credentials. {}", userAuth); return null; } } else if (!user.getActive()) { if (throwException) { throw new LockedException("Account " + user.getId() + " (" + user.getAppid() + "/" + user.getIdentifier() + ") is locked."); } else { logger.warn("Account {} ({}/{}) is locked.", user.getId(), user.getAppid(), user.getIdentifier()); return null; } } return userAuth; }
[ "public", "static", "UserAuthentication", "checkIfActive", "(", "UserAuthentication", "userAuth", ",", "User", "user", ",", "boolean", "throwException", ")", "{", "if", "(", "userAuth", "==", "null", "||", "user", "==", "null", "||", "user", ".", "getIdentifier"...
Checks if account is active. @param userAuth user authentication object @param user user object @param throwException throw or not @return the authentication object if {@code user.active == true}
[ "Checks", "if", "account", "is", "active", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-server/src/main/java/com/erudika/para/security/SecurityUtils.java#L391-L409
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/TokenFelligiSunter.java
TokenFelligiSunter.explainScore
public String explainScore(StringWrapper s, StringWrapper t) { BagOfTokens sBag = (BagOfTokens)s; BagOfTokens tBag = (BagOfTokens)t; StringBuffer buf = new StringBuffer(""); PrintfFormat fmt = new PrintfFormat("%.3f"); buf.append("Common tokens: "); for (Iterator i = sBag.tokenIterator(); i.hasNext(); ) { Token tok = (Token)i.next(); if (tBag.contains(tok)) { buf.append(" "+tok.getValue()+": "); buf.append(fmt.sprintf(tBag.getWeight(tok))); } } buf.append("\nscore = "+score(s,t)); return buf.toString(); }
java
public String explainScore(StringWrapper s, StringWrapper t) { BagOfTokens sBag = (BagOfTokens)s; BagOfTokens tBag = (BagOfTokens)t; StringBuffer buf = new StringBuffer(""); PrintfFormat fmt = new PrintfFormat("%.3f"); buf.append("Common tokens: "); for (Iterator i = sBag.tokenIterator(); i.hasNext(); ) { Token tok = (Token)i.next(); if (tBag.contains(tok)) { buf.append(" "+tok.getValue()+": "); buf.append(fmt.sprintf(tBag.getWeight(tok))); } } buf.append("\nscore = "+score(s,t)); return buf.toString(); }
[ "public", "String", "explainScore", "(", "StringWrapper", "s", ",", "StringWrapper", "t", ")", "{", "BagOfTokens", "sBag", "=", "(", "BagOfTokens", ")", "s", ";", "BagOfTokens", "tBag", "=", "(", "BagOfTokens", ")", "t", ";", "StringBuffer", "buf", "=", "n...
Explain how the distance was computed. In the output, the tokens in S and T are listed, and the common tokens are marked with an asterisk.
[ "Explain", "how", "the", "distance", "was", "computed", ".", "In", "the", "output", "the", "tokens", "in", "S", "and", "T", "are", "listed", "and", "the", "common", "tokens", "are", "marked", "with", "an", "asterisk", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/TokenFelligiSunter.java#L75-L91
Azure/azure-sdk-for-java
resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java
ResourcesInner.beginUpdateById
public GenericResourceInner beginUpdateById(String resourceId, String apiVersion, GenericResourceInner parameters) { return beginUpdateByIdWithServiceResponseAsync(resourceId, apiVersion, parameters).toBlocking().single().body(); }
java
public GenericResourceInner beginUpdateById(String resourceId, String apiVersion, GenericResourceInner parameters) { return beginUpdateByIdWithServiceResponseAsync(resourceId, apiVersion, parameters).toBlocking().single().body(); }
[ "public", "GenericResourceInner", "beginUpdateById", "(", "String", "resourceId", ",", "String", "apiVersion", ",", "GenericResourceInner", "parameters", ")", "{", "return", "beginUpdateByIdWithServiceResponseAsync", "(", "resourceId", ",", "apiVersion", ",", "parameters", ...
Updates a resource by ID. @param resourceId The fully qualified ID of the resource, including the resource name and resource type. Use the format, /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} @param apiVersion The API version to use for the operation. @param parameters Update resource parameters. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the GenericResourceInner object if successful.
[ "Updates", "a", "resource", "by", "ID", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L2302-L2304
netty/netty
buffer/src/main/java/io/netty/buffer/ByteBufUtil.java
ByteBufUtil.appendPrettyHexDump
public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length) { HexUtil.appendPrettyHexDump(dump, buf, offset, length); }
java
public static void appendPrettyHexDump(StringBuilder dump, ByteBuf buf, int offset, int length) { HexUtil.appendPrettyHexDump(dump, buf, offset, length); }
[ "public", "static", "void", "appendPrettyHexDump", "(", "StringBuilder", "dump", ",", "ByteBuf", "buf", ",", "int", "offset", ",", "int", "length", ")", "{", "HexUtil", ".", "appendPrettyHexDump", "(", "dump", ",", "buf", ",", "offset", ",", "length", ")", ...
Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified {@link StringBuilder} that is easy to read by humans, starting at the given {@code offset} using the given {@code length}.
[ "Appends", "the", "prettified", "multi", "-", "line", "hexadecimal", "dump", "of", "the", "specified", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java#L935-L937
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionRangeConfig.java
CollisionRangeConfig.imports
public static CollisionRange imports(XmlReader node) { Check.notNull(node); final String axisName = node.readString(ATT_AXIS); try { final Axis axis = Axis.valueOf(axisName); final int minX = node.readInteger(ATT_MIN_X); final int maxX = node.readInteger(ATT_MAX_X); final int minY = node.readInteger(ATT_MIN_Y); final int maxY = node.readInteger(ATT_MAX_Y); return new CollisionRange(axis, minX, maxX, minY, maxY); } catch (final IllegalArgumentException exception) { throw new LionEngineException(exception, ERROR_TYPE + axisName); } }
java
public static CollisionRange imports(XmlReader node) { Check.notNull(node); final String axisName = node.readString(ATT_AXIS); try { final Axis axis = Axis.valueOf(axisName); final int minX = node.readInteger(ATT_MIN_X); final int maxX = node.readInteger(ATT_MAX_X); final int minY = node.readInteger(ATT_MIN_Y); final int maxY = node.readInteger(ATT_MAX_Y); return new CollisionRange(axis, minX, maxX, minY, maxY); } catch (final IllegalArgumentException exception) { throw new LionEngineException(exception, ERROR_TYPE + axisName); } }
[ "public", "static", "CollisionRange", "imports", "(", "XmlReader", "node", ")", "{", "Check", ".", "notNull", "(", "node", ")", ";", "final", "String", "axisName", "=", "node", ".", "readString", "(", "ATT_AXIS", ")", ";", "try", "{", "final", "Axis", "a...
Create the collision range data from a node. @param node The node reference (must not be <code>null</code>). @return The collision range data. @throws LionEngineException If error when reading node.
[ "Create", "the", "collision", "range", "data", "from", "a", "node", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/CollisionRangeConfig.java#L58-L77
cdk/cdk
base/silent/src/main/java/org/openscience/cdk/silent/MolecularFormula.java
MolecularFormula.setProperties
@Override public void setProperties(Map<Object, Object> properties) { Iterator<Object> keys = properties.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); lazyProperties().put(key, properties.get(key)); } }
java
@Override public void setProperties(Map<Object, Object> properties) { Iterator<Object> keys = properties.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); lazyProperties().put(key, properties.get(key)); } }
[ "@", "Override", "public", "void", "setProperties", "(", "Map", "<", "Object", ",", "Object", ">", "properties", ")", "{", "Iterator", "<", "Object", ">", "keys", "=", "properties", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(",...
Sets the properties of this object. @param properties a Hashtable specifying the property values @see #getProperties
[ "Sets", "the", "properties", "of", "this", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/silent/src/main/java/org/openscience/cdk/silent/MolecularFormula.java#L357-L365
Impetus/Kundera
src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java
OracleNoSQLClient.addDiscriminatorColumn
private void addDiscriminatorColumn(Row row, EntityType entityType, Table schemaTable) { String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn(); String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue(); // No need to check for empty or blank, as considering it as valid name // for nosql! if (discrColumn != null && discrValue != null) { // Key // Key key = Key.createKey(majorKeyComponent, discrColumn); byte[] valueInBytes = PropertyAccessorHelper.getBytes(discrValue); NoSqlDBUtils.add(schemaTable.getField(discrColumn), row, discrValue, discrColumn); } }
java
private void addDiscriminatorColumn(Row row, EntityType entityType, Table schemaTable) { String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn(); String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue(); // No need to check for empty or blank, as considering it as valid name // for nosql! if (discrColumn != null && discrValue != null) { // Key // Key key = Key.createKey(majorKeyComponent, discrColumn); byte[] valueInBytes = PropertyAccessorHelper.getBytes(discrValue); NoSqlDBUtils.add(schemaTable.getField(discrColumn), row, discrValue, discrColumn); } }
[ "private", "void", "addDiscriminatorColumn", "(", "Row", "row", ",", "EntityType", "entityType", ",", "Table", "schemaTable", ")", "{", "String", "discrColumn", "=", "(", "(", "AbstractManagedType", ")", "entityType", ")", ".", "getDiscriminatorColumn", "(", ")", ...
Process discriminator columns. @param row kv row object. @param entityType metamodel attribute. @param schemaTable the schema table
[ "Process", "discriminator", "columns", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java#L1143-L1159
googleapis/google-cloud-java
google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobInfo.java
JobInfo.of
public static JobInfo of(JobId jobId, JobConfiguration configuration) { return newBuilder(configuration).setJobId(jobId).build(); }
java
public static JobInfo of(JobId jobId, JobConfiguration configuration) { return newBuilder(configuration).setJobId(jobId).build(); }
[ "public", "static", "JobInfo", "of", "(", "JobId", "jobId", ",", "JobConfiguration", "configuration", ")", "{", "return", "newBuilder", "(", "configuration", ")", ".", "setJobId", "(", "jobId", ")", ".", "build", "(", ")", ";", "}" ]
Returns a builder for a {@code JobInfo} object given the job identity and configuration. Use {@link CopyJobConfiguration} for a job that copies an existing table. Use {@link ExtractJobConfiguration} for a job that exports a table to Google Cloud Storage. Use {@link LoadJobConfiguration} for a job that loads data from Google Cloud Storage into a table. Use {@link QueryJobConfiguration} for a job that runs a query.
[ "Returns", "a", "builder", "for", "a", "{" ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobInfo.java#L365-L367
mygreen/super-csv-annotation
src/main/java/com/github/mygreen/supercsv/builder/LazyBeanMappingFactory.java
LazyBeanMappingFactory.buildColumnMappingList
@Override protected <T> void buildColumnMappingList(final BeanMapping<T> beanMapping, final Class<T> beanType, final Class<?>[] groups) { final List<ColumnMapping> columnMappingList = new ArrayList<>(); for(Field field : beanType.getDeclaredFields()) { final CsvColumn columnAnno = field.getAnnotation(CsvColumn.class); if(columnAnno != null) { columnMappingList.add(createColumnMapping(field, columnAnno, groups)); } } beanMapping.addAllColumns(columnMappingList); }
java
@Override protected <T> void buildColumnMappingList(final BeanMapping<T> beanMapping, final Class<T> beanType, final Class<?>[] groups) { final List<ColumnMapping> columnMappingList = new ArrayList<>(); for(Field field : beanType.getDeclaredFields()) { final CsvColumn columnAnno = field.getAnnotation(CsvColumn.class); if(columnAnno != null) { columnMappingList.add(createColumnMapping(field, columnAnno, groups)); } } beanMapping.addAllColumns(columnMappingList); }
[ "@", "Override", "protected", "<", "T", ">", "void", "buildColumnMappingList", "(", "final", "BeanMapping", "<", "T", ">", "beanMapping", ",", "final", "Class", "<", "T", ">", "beanType", ",", "final", "Class", "<", "?", ">", "[", "]", "groups", ")", "...
アノテーション{@link CsvColumn}を元に、カラムのマッピング情報を組み立てる。 <p>カラム番号の検証や、部分的なカラムのカラムの組み立てはスキップ。</p> @param beanMapping Beanのマッピング情報 @param beanType Beanのクラスタイプ @param groups グループ情報
[ "アノテーション", "{" ]
train
https://github.com/mygreen/super-csv-annotation/blob/9910320cb6dc143be972c7d10d9ab5ffb09c3b84/src/main/java/com/github/mygreen/supercsv/builder/LazyBeanMappingFactory.java#L82-L97
Cornutum/tcases
tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java
SystemInputJson.asVarDef
private static IVarDef asVarDef( String varName, String varType, Annotated groupAnnotations, JsonObject json) { try { validIdentifier( varName); AbstractVarDef varDef = json.containsKey( MEMBERS_KEY) ? new VarSet( varName) : new VarDef( varName); varDef.setType( varType); // Get annotations for this variable Optional.ofNullable( json.getJsonObject( HAS_KEY)) .ifPresent( has -> has.keySet().stream().forEach( key -> varDef.setAnnotation( key, has.getString( key)))); // Get the condition for this variable Optional.ofNullable( json.getJsonObject( WHEN_KEY)) .ifPresent( object -> varDef.setCondition( asValidCondition( object))); if( json.containsKey( MEMBERS_KEY)) { VarSet varSet = (VarSet) varDef; getVarDefs( varType, json.getJsonObject( MEMBERS_KEY)) .forEach( member -> varSet.addMember( member)); if( !varSet.getMembers().hasNext()) { throw new SystemInputException( String.format( "No members defined for VarSet=%s", varName)); } } else { VarDef var = (VarDef) varDef; getValueDefs( json.getJsonObject( VALUES_KEY)) .forEach( valueDef -> var.addValue( valueDef)); if( !var.getValidValues().hasNext()) { throw new SystemInputException( String.format( "No valid values defined for Var=%s", varName)); } } // Add any group annotations varDef.addAnnotations( groupAnnotations); return varDef; } catch( SystemInputException e) { throw new SystemInputException( String.format( "Error defining variable=%s", varName), e); } }
java
private static IVarDef asVarDef( String varName, String varType, Annotated groupAnnotations, JsonObject json) { try { validIdentifier( varName); AbstractVarDef varDef = json.containsKey( MEMBERS_KEY) ? new VarSet( varName) : new VarDef( varName); varDef.setType( varType); // Get annotations for this variable Optional.ofNullable( json.getJsonObject( HAS_KEY)) .ifPresent( has -> has.keySet().stream().forEach( key -> varDef.setAnnotation( key, has.getString( key)))); // Get the condition for this variable Optional.ofNullable( json.getJsonObject( WHEN_KEY)) .ifPresent( object -> varDef.setCondition( asValidCondition( object))); if( json.containsKey( MEMBERS_KEY)) { VarSet varSet = (VarSet) varDef; getVarDefs( varType, json.getJsonObject( MEMBERS_KEY)) .forEach( member -> varSet.addMember( member)); if( !varSet.getMembers().hasNext()) { throw new SystemInputException( String.format( "No members defined for VarSet=%s", varName)); } } else { VarDef var = (VarDef) varDef; getValueDefs( json.getJsonObject( VALUES_KEY)) .forEach( valueDef -> var.addValue( valueDef)); if( !var.getValidValues().hasNext()) { throw new SystemInputException( String.format( "No valid values defined for Var=%s", varName)); } } // Add any group annotations varDef.addAnnotations( groupAnnotations); return varDef; } catch( SystemInputException e) { throw new SystemInputException( String.format( "Error defining variable=%s", varName), e); } }
[ "private", "static", "IVarDef", "asVarDef", "(", "String", "varName", ",", "String", "varType", ",", "Annotated", "groupAnnotations", ",", "JsonObject", "json", ")", "{", "try", "{", "validIdentifier", "(", "varName", ")", ";", "AbstractVarDef", "varDef", "=", ...
Returns the variable definition represented by the given JSON object.
[ "Returns", "the", "variable", "definition", "represented", "by", "the", "given", "JSON", "object", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/io/SystemInputJson.java#L274-L327
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/widget/FacebookDialog.java
FacebookDialog.canPresentOpenGraphActionDialog
public static boolean canPresentOpenGraphActionDialog(Context context, OpenGraphActionDialogFeature... features) { return handleCanPresent(context, EnumSet.of(OpenGraphActionDialogFeature.OG_ACTION_DIALOG, features)); }
java
public static boolean canPresentOpenGraphActionDialog(Context context, OpenGraphActionDialogFeature... features) { return handleCanPresent(context, EnumSet.of(OpenGraphActionDialogFeature.OG_ACTION_DIALOG, features)); }
[ "public", "static", "boolean", "canPresentOpenGraphActionDialog", "(", "Context", "context", ",", "OpenGraphActionDialogFeature", "...", "features", ")", "{", "return", "handleCanPresent", "(", "context", ",", "EnumSet", ".", "of", "(", "OpenGraphActionDialogFeature", "...
Determines whether the version of the Facebook application installed on the user's device is recent enough to support specific features of the native Open Graph action dialog, which in turn may be used to determine which UI, etc., to present to the user. @param context the calling Context @param features zero or more features to check for; {@link OpenGraphActionDialogFeature#OG_ACTION_DIALOG} is implicitly checked if not explicitly specified @return true if all of the specified features are supported by the currently installed version of the Facebook application; false if any of the features are not supported
[ "Determines", "whether", "the", "version", "of", "the", "Facebook", "application", "installed", "on", "the", "user", "s", "device", "is", "recent", "enough", "to", "support", "specific", "features", "of", "the", "native", "Open", "Graph", "action", "dialog", "...
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/widget/FacebookDialog.java#L399-L401
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java
CQLSchemaManager.modifyKeyspace
public void modifyKeyspace(Map<String, String> options) { if (!options.containsKey("ReplicationFactor")) { return; } String cqlKeyspace = m_dbservice.getKeyspace(); m_logger.info("Modifying keyspace: {}", cqlKeyspace); StringBuilder cql = new StringBuilder(); cql.append("ALTER KEYSPACE "); cql.append(cqlKeyspace); cql.append(" WITH REPLICATION = {'class':'"); String strategyClass = "SimpleStrategy"; Map<String, Object> ksDefs = m_dbservice.getParamMap("ks_defaults"); if (ksDefs != null && ksDefs.containsKey("strategy_class")) { strategyClass = ksDefs.get("strategy_class").toString(); } cql.append(strategyClass); cql.append("','replication_factor':"); cql.append(options.get("ReplicationFactor")); cql.append("};"); executeCQL(cql.toString()); }
java
public void modifyKeyspace(Map<String, String> options) { if (!options.containsKey("ReplicationFactor")) { return; } String cqlKeyspace = m_dbservice.getKeyspace(); m_logger.info("Modifying keyspace: {}", cqlKeyspace); StringBuilder cql = new StringBuilder(); cql.append("ALTER KEYSPACE "); cql.append(cqlKeyspace); cql.append(" WITH REPLICATION = {'class':'"); String strategyClass = "SimpleStrategy"; Map<String, Object> ksDefs = m_dbservice.getParamMap("ks_defaults"); if (ksDefs != null && ksDefs.containsKey("strategy_class")) { strategyClass = ksDefs.get("strategy_class").toString(); } cql.append(strategyClass); cql.append("','replication_factor':"); cql.append(options.get("ReplicationFactor")); cql.append("};"); executeCQL(cql.toString()); }
[ "public", "void", "modifyKeyspace", "(", "Map", "<", "String", ",", "String", ">", "options", ")", "{", "if", "(", "!", "options", ".", "containsKey", "(", "\"ReplicationFactor\"", ")", ")", "{", "return", ";", "}", "String", "cqlKeyspace", "=", "m_dbservi...
Modify the keyspace with the given name with the given options. The only option that can be modified is ReplicationFactor. If it is present, the keyspace is altered with the following CQL command: <pre> ALTER KEYSPACE "<i>keyspace</i>" WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor' : <i>replication_factor</i> }; </pre> @param options Modified options to use for keyspace. Only the option "replication_factor" is examined.
[ "Modify", "the", "keyspace", "with", "the", "given", "name", "with", "the", "given", "options", ".", "The", "only", "option", "that", "can", "be", "modified", "is", "ReplicationFactor", ".", "If", "it", "is", "present", "the", "keyspace", "is", "altered", ...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLSchemaManager.java#L72-L92
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.getKeyAsync
public ServiceFuture<KeyBundle> getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback<KeyBundle> serviceCallback) { return ServiceFuture.fromResponse(getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); }
java
public ServiceFuture<KeyBundle> getKeyAsync(String vaultBaseUrl, String keyName, String keyVersion, final ServiceCallback<KeyBundle> serviceCallback) { return ServiceFuture.fromResponse(getKeyWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion), serviceCallback); }
[ "public", "ServiceFuture", "<", "KeyBundle", ">", "getKeyAsync", "(", "String", "vaultBaseUrl", ",", "String", "keyName", ",", "String", "keyVersion", ",", "final", "ServiceCallback", "<", "KeyBundle", ">", "serviceCallback", ")", "{", "return", "ServiceFuture", "...
Gets the public part of a stored key. The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released in the response. This operation requires the keys/get permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyName The name of the key to get. @param keyVersion Adding the version parameter retrieves a specific version of a key. @param serviceCallback the async ServiceCallback to handle successful and failed responses. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceFuture} object
[ "Gets", "the", "public", "part", "of", "a", "stored", "key", ".", "The", "get", "key", "operation", "is", "applicable", "to", "all", "key", "types", ".", "If", "the", "requested", "key", "is", "symmetric", "then", "no", "key", "material", "is", "released...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L1400-L1402
carewebframework/carewebframework-vista
org.carewebframework.vista.ui-parent/org.carewebframework.vista.ui.core/src/main/java/org/carewebframework/vista/ui/mbroker/AsyncRPCEventDispatcher.java
AsyncRPCEventDispatcher.callRPCAsync
public int callRPCAsync(String rpcName, Object... args) { abort(); this.rpcName = rpcName; asyncHandle = broker.callRPCAsync(rpcName, this, args); return asyncHandle; }
java
public int callRPCAsync(String rpcName, Object... args) { abort(); this.rpcName = rpcName; asyncHandle = broker.callRPCAsync(rpcName, this, args); return asyncHandle; }
[ "public", "int", "callRPCAsync", "(", "String", "rpcName", ",", "Object", "...", "args", ")", "{", "abort", "(", ")", ";", "this", ".", "rpcName", "=", "rpcName", ";", "asyncHandle", "=", "broker", ".", "callRPCAsync", "(", "rpcName", ",", "this", ",", ...
Make an asynchronous call. @param rpcName The RPC name. @param args The RPC arguments. @return The async handle.
[ "Make", "an", "asynchronous", "call", "." ]
train
https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.ui-parent/org.carewebframework.vista.ui.core/src/main/java/org/carewebframework/vista/ui/mbroker/AsyncRPCEventDispatcher.java#L66-L71
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/list/EditableComboBoxAutoCompletion.java
EditableComboBoxAutoCompletion.startsWithIgnoreCase
private boolean startsWithIgnoreCase(String str1, String str2) { return str1 != null && str2 != null && str1.toUpperCase().startsWith(str2.toUpperCase()); }
java
private boolean startsWithIgnoreCase(String str1, String str2) { return str1 != null && str2 != null && str1.toUpperCase().startsWith(str2.toUpperCase()); }
[ "private", "boolean", "startsWithIgnoreCase", "(", "String", "str1", ",", "String", "str2", ")", "{", "return", "str1", "!=", "null", "&&", "str2", "!=", "null", "&&", "str1", ".", "toUpperCase", "(", ")", ".", "startsWith", "(", "str2", ".", "toUpperCase"...
See if one string begins with another, ignoring case. @param str1 The string to test @param str2 The prefix to test for @return true if str1 starts with str2, ingnoring case
[ "See", "if", "one", "string", "begins", "with", "another", "ignoring", "case", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/list/EditableComboBoxAutoCompletion.java#L98-L100
google/j2objc
jre_emul/android/frameworks/base/core/java/android/util/ArrayMap.java
ArrayMap.putAll
public void putAll(ArrayMap<? extends K, ? extends V> array) { final int N = array.mSize; ensureCapacity(mSize + N); if (mSize == 0) { if (N > 0) { System.arraycopy(array.mHashes, 0, mHashes, 0, N); System.arraycopy(array.mArray, 0, mArray, 0, N<<1); mSize = N; } } else { for (int i=0; i<N; i++) { put(array.keyAt(i), array.valueAt(i)); } } }
java
public void putAll(ArrayMap<? extends K, ? extends V> array) { final int N = array.mSize; ensureCapacity(mSize + N); if (mSize == 0) { if (N > 0) { System.arraycopy(array.mHashes, 0, mHashes, 0, N); System.arraycopy(array.mArray, 0, mArray, 0, N<<1); mSize = N; } } else { for (int i=0; i<N; i++) { put(array.keyAt(i), array.valueAt(i)); } } }
[ "public", "void", "putAll", "(", "ArrayMap", "<", "?", "extends", "K", ",", "?", "extends", "V", ">", "array", ")", "{", "final", "int", "N", "=", "array", ".", "mSize", ";", "ensureCapacity", "(", "mSize", "+", "N", ")", ";", "if", "(", "mSize", ...
Perform a {@link #put(Object, Object)} of all key/value pairs in <var>array</var> @param array The array whose contents are to be retrieved.
[ "Perform", "a", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/frameworks/base/core/java/android/util/ArrayMap.java#L502-L516
jayantk/jklol
src/com/jayantkrish/jklol/util/HeapUtils.java
HeapUtils.removeMin
public static final void removeMin(long[] heapKeys, double[] heapValues, int heapSize) { heapValues[0] = heapValues[heapSize - 1]; heapKeys[0] = heapKeys[heapSize - 1]; int curIndex = 0; int leftIndex, rightIndex, minIndex; boolean done = false; while (!done) { done = true; leftIndex = 1 + (curIndex * 2); rightIndex = leftIndex + 1; minIndex = -1; if (rightIndex < heapSize) { minIndex = heapValues[leftIndex] <= heapValues[rightIndex] ? leftIndex : rightIndex; } else if (leftIndex < heapSize) { minIndex = leftIndex; } if (minIndex != -1 && heapValues[minIndex] < heapValues[curIndex]) { swap(heapKeys, heapValues, curIndex, minIndex); done = false; curIndex = minIndex; } } }
java
public static final void removeMin(long[] heapKeys, double[] heapValues, int heapSize) { heapValues[0] = heapValues[heapSize - 1]; heapKeys[0] = heapKeys[heapSize - 1]; int curIndex = 0; int leftIndex, rightIndex, minIndex; boolean done = false; while (!done) { done = true; leftIndex = 1 + (curIndex * 2); rightIndex = leftIndex + 1; minIndex = -1; if (rightIndex < heapSize) { minIndex = heapValues[leftIndex] <= heapValues[rightIndex] ? leftIndex : rightIndex; } else if (leftIndex < heapSize) { minIndex = leftIndex; } if (minIndex != -1 && heapValues[minIndex] < heapValues[curIndex]) { swap(heapKeys, heapValues, curIndex, minIndex); done = false; curIndex = minIndex; } } }
[ "public", "static", "final", "void", "removeMin", "(", "long", "[", "]", "heapKeys", ",", "double", "[", "]", "heapValues", ",", "int", "heapSize", ")", "{", "heapValues", "[", "0", "]", "=", "heapValues", "[", "heapSize", "-", "1", "]", ";", "heapKeys...
Removes the smallest key/value pair from the heap represented by {@code heapKeys} and {@code heapValues}. After calling this method, the size of the heap shrinks by 1. @param heapKeys @param heapValues @param heapSize
[ "Removes", "the", "smallest", "key", "/", "value", "pair", "from", "the", "heap", "represented", "by", "{", "@code", "heapKeys", "}", "and", "{", "@code", "heapValues", "}", ".", "After", "calling", "this", "method", "the", "size", "of", "the", "heap", "...
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/HeapUtils.java#L75-L100
apache/groovy
src/main/java/org/codehaus/groovy/ast/tools/ParameterUtils.java
ParameterUtils.parametersCompatible
public static boolean parametersCompatible(Parameter[] source, Parameter[] target) { return parametersMatch(source, target, t -> ClassHelper.getWrapper(t.getV2()).getTypeClass() .isAssignableFrom(ClassHelper.getWrapper(t.getV1()).getTypeClass()) ); }
java
public static boolean parametersCompatible(Parameter[] source, Parameter[] target) { return parametersMatch(source, target, t -> ClassHelper.getWrapper(t.getV2()).getTypeClass() .isAssignableFrom(ClassHelper.getWrapper(t.getV1()).getTypeClass()) ); }
[ "public", "static", "boolean", "parametersCompatible", "(", "Parameter", "[", "]", "source", ",", "Parameter", "[", "]", "target", ")", "{", "return", "parametersMatch", "(", "source", ",", "target", ",", "t", "->", "ClassHelper", ".", "getWrapper", "(", "t"...
check whether parameters type are compatible each parameter should match the following condition: {@code targetParameter.getType().getTypeClass().isAssignableFrom(sourceParameter.getType().getTypeClass())} @param source source parameters @param target target parameters @return the check result @since 3.0.0
[ "check", "whether", "parameters", "type", "are", "compatible" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/tools/ParameterUtils.java#L51-L56
esigate/esigate
esigate-core/src/main/java/org/esigate/http/HttpResponseUtils.java
HttpResponseUtils.getFirstHeader
public static String getFirstHeader(String headerName, HttpResponse httpResponse) { Header header = httpResponse.getFirstHeader(headerName); if (header != null) { return header.getValue(); } return null; }
java
public static String getFirstHeader(String headerName, HttpResponse httpResponse) { Header header = httpResponse.getFirstHeader(headerName); if (header != null) { return header.getValue(); } return null; }
[ "public", "static", "String", "getFirstHeader", "(", "String", "headerName", ",", "HttpResponse", "httpResponse", ")", "{", "Header", "header", "=", "httpResponse", ".", "getFirstHeader", "(", "headerName", ")", ";", "if", "(", "header", "!=", "null", ")", "{"...
Get the value of the first header matching "headerName". @param headerName @param httpResponse @return value of the first header or null if it doesn't exist.
[ "Get", "the", "value", "of", "the", "first", "header", "matching", "headerName", "." ]
train
https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/http/HttpResponseUtils.java#L82-L88
citrusframework/citrus
modules/citrus-core/src/main/java/com/consol/citrus/xml/schema/WsdlXsdSchema.java
WsdlXsdSchema.getWsdlDefinition
private Definition getWsdlDefinition(Resource wsdl) { try { Definition definition; if (wsdl.getURI().toString().startsWith("jar:")) { // Locate WSDL imports in Jar files definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(new JarWSDLLocator(wsdl)); } else { definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(wsdl.getURI().getPath(), new InputSource(wsdl.getInputStream())); } return definition; } catch (IOException e) { throw new CitrusRuntimeException("Failed to read wsdl file resource", e); } catch (WSDLException e) { throw new CitrusRuntimeException("Failed to wsdl schema instance", e); } }
java
private Definition getWsdlDefinition(Resource wsdl) { try { Definition definition; if (wsdl.getURI().toString().startsWith("jar:")) { // Locate WSDL imports in Jar files definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(new JarWSDLLocator(wsdl)); } else { definition = WSDLFactory.newInstance().newWSDLReader().readWSDL(wsdl.getURI().getPath(), new InputSource(wsdl.getInputStream())); } return definition; } catch (IOException e) { throw new CitrusRuntimeException("Failed to read wsdl file resource", e); } catch (WSDLException e) { throw new CitrusRuntimeException("Failed to wsdl schema instance", e); } }
[ "private", "Definition", "getWsdlDefinition", "(", "Resource", "wsdl", ")", "{", "try", "{", "Definition", "definition", ";", "if", "(", "wsdl", ".", "getURI", "(", ")", ".", "toString", "(", ")", ".", "startsWith", "(", "\"jar:\"", ")", ")", "{", "// Lo...
Reads WSDL definition from resource. @param wsdl @return @throws IOException @throws WSDLException
[ "Reads", "WSDL", "definition", "from", "resource", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/xml/schema/WsdlXsdSchema.java#L185-L201
beanshell/beanshell
src/main/java/bsh/NameSpace.java
NameSpace.getNameResolver
Name getNameResolver(final String ambigname) { if (!this.names.containsKey(ambigname)) this.names.put(ambigname, new Name(this, ambigname)); return this.names.get(ambigname); }
java
Name getNameResolver(final String ambigname) { if (!this.names.containsKey(ambigname)) this.names.put(ambigname, new Name(this, ambigname)); return this.names.get(ambigname); }
[ "Name", "getNameResolver", "(", "final", "String", "ambigname", ")", "{", "if", "(", "!", "this", ".", "names", ".", "containsKey", "(", "ambigname", ")", ")", "this", ".", "names", ".", "put", "(", "ambigname", ",", "new", "Name", "(", "this", ",", ...
This is the factory for Name objects which resolve names within this namespace (e.g. toObject(), toClass(), toLHS()). <p> This was intended to support name resolver caching, allowing Name objects to cache info about the resolution of names for performance reasons. However this not proven useful yet. <p> We'll leave the caching as it will at least minimize Name object creation. <p> (This method would be called getName() if it weren't already used for the simple name of the NameSpace) <p> This method was public for a time, which was a mistake. Use get() instead. @param ambigname the ambigname @return the name resolver
[ "This", "is", "the", "factory", "for", "Name", "objects", "which", "resolve", "names", "within", "this", "namespace", "(", "e", ".", "g", ".", "toObject", "()", "toClass", "()", "toLHS", "()", ")", ".", "<p", ">", "This", "was", "intended", "to", "supp...
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/NameSpace.java#L1277-L1281
micronaut-projects/micronaut-core
core/src/main/java/io/micronaut/core/util/StringUtils.java
StringUtils.tokenizeToStringArray
@SuppressWarnings({"unchecked"}) public static String[] tokenizeToStringArray( String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return tokens.toArray(new String[0]); }
java
@SuppressWarnings({"unchecked"}) public static String[] tokenizeToStringArray( String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if (str == null) { return null; } StringTokenizer st = new StringTokenizer(str, delimiters); List<String> tokens = new ArrayList(); while (st.hasMoreTokens()) { String token = st.nextToken(); if (trimTokens) { token = token.trim(); } if (!ignoreEmptyTokens || token.length() > 0) { tokens.add(token); } } return tokens.toArray(new String[0]); }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", "}", ")", "public", "static", "String", "[", "]", "tokenizeToStringArray", "(", "String", "str", ",", "String", "delimiters", ",", "boolean", "trimTokens", ",", "boolean", "ignoreEmptyTokens", ")", "{", "if", ...
Tokenize the given String into a String array via a StringTokenizer. <p>The given delimiters string is supposed to consist of any number of delimiter characters. Each of those characters can be used to separate tokens. A delimiter is always a single character; for multi-character delimiters, consider using <code>delimitedListToStringArray</code> <p/> <p>Copied from the Spring Framework while retaining all license, copyright and author information. @param str the String to tokenize @param delimiters the delimiter characters, assembled as String (each of those characters is individually considered as delimiter) @param trimTokens trim the tokens via String's <code>trim</code> @param ignoreEmptyTokens omit empty tokens from the result array (only applies to tokens that are empty after trimming; StringTokenizer will not consider subsequent delimiters as token in the first place). @return an array of the tokens (<code>null</code> if the input String was <code>null</code>) @see java.util.StringTokenizer @see java.lang.String#trim()
[ "Tokenize", "the", "given", "String", "into", "a", "String", "array", "via", "a", "StringTokenizer", ".", "<p", ">", "The", "given", "delimiters", "string", "is", "supposed", "to", "consist", "of", "any", "number", "of", "delimiter", "characters", ".", "Each...
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/util/StringUtils.java#L194-L213
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java
TheMovieDbApi.getEpisodeAccountState
public MediaState getEpisodeAccountState(int tvID, int seasonNumber, int episodeNumber, String sessionID) throws MovieDbException { return tmdbEpisodes.getEpisodeAccountState(tvID, seasonNumber, episodeNumber, sessionID); }
java
public MediaState getEpisodeAccountState(int tvID, int seasonNumber, int episodeNumber, String sessionID) throws MovieDbException { return tmdbEpisodes.getEpisodeAccountState(tvID, seasonNumber, episodeNumber, sessionID); }
[ "public", "MediaState", "getEpisodeAccountState", "(", "int", "tvID", ",", "int", "seasonNumber", ",", "int", "episodeNumber", ",", "String", "sessionID", ")", "throws", "MovieDbException", "{", "return", "tmdbEpisodes", ".", "getEpisodeAccountState", "(", "tvID", "...
This method lets users get the status of whether or not the TV episode has been rated. A valid session id is required. @param tvID tvID @param seasonNumber seasonNumber @param episodeNumber episodeNumber @param sessionID sessionID @return @throws MovieDbException exception
[ "This", "method", "lets", "users", "get", "the", "status", "of", "whether", "or", "not", "the", "TV", "episode", "has", "been", "rated", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L1802-L1804
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/ch/epfl/bbp/uima/types/Topic.java
Topic.setScores
public void setScores(int i, double v) { if (Topic_Type.featOkTst && ((Topic_Type)jcasType).casFeat_scores == null) jcasType.jcas.throwFeatMissing("scores", "ch.epfl.bbp.uima.types.Topic"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Topic_Type)jcasType).casFeatCode_scores), i); jcasType.ll_cas.ll_setDoubleArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Topic_Type)jcasType).casFeatCode_scores), i, v);}
java
public void setScores(int i, double v) { if (Topic_Type.featOkTst && ((Topic_Type)jcasType).casFeat_scores == null) jcasType.jcas.throwFeatMissing("scores", "ch.epfl.bbp.uima.types.Topic"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Topic_Type)jcasType).casFeatCode_scores), i); jcasType.ll_cas.ll_setDoubleArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Topic_Type)jcasType).casFeatCode_scores), i, v);}
[ "public", "void", "setScores", "(", "int", "i", ",", "double", "v", ")", "{", "if", "(", "Topic_Type", ".", "featOkTst", "&&", "(", "(", "Topic_Type", ")", "jcasType", ")", ".", "casFeat_scores", "==", "null", ")", "jcasType", ".", "jcas", ".", "throwF...
indexed setter for scores - sets an indexed value - @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "scores", "-", "sets", "an", "indexed", "value", "-" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/ch/epfl/bbp/uima/types/Topic.java#L117-L121
spring-projects/spring-data-solr
src/main/java/org/springframework/data/solr/core/query/HighlightOptions.java
HighlightOptions.addHighlightParameter
public HighlightOptions addHighlightParameter(String parameterName, Object value) { return addHighlightParameter(new HighlightParameter(parameterName, value)); }
java
public HighlightOptions addHighlightParameter(String parameterName, Object value) { return addHighlightParameter(new HighlightParameter(parameterName, value)); }
[ "public", "HighlightOptions", "addHighlightParameter", "(", "String", "parameterName", ",", "Object", "value", ")", "{", "return", "addHighlightParameter", "(", "new", "HighlightParameter", "(", "parameterName", ",", "value", ")", ")", ";", "}" ]
Add parameter by name @param parameterName must not be null @param value @return
[ "Add", "parameter", "by", "name" ]
train
https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/core/query/HighlightOptions.java#L224-L226
jtablesaw/tablesaw
html/src/main/java/tech/tablesaw/io/html/HtmlReadOptions.java
HtmlReadOptions.builder
public static Builder builder(Reader reader, String tableName) { Builder builder = new Builder(reader); return builder.tableName(tableName); }
java
public static Builder builder(Reader reader, String tableName) { Builder builder = new Builder(reader); return builder.tableName(tableName); }
[ "public", "static", "Builder", "builder", "(", "Reader", "reader", ",", "String", "tableName", ")", "{", "Builder", "builder", "=", "new", "Builder", "(", "reader", ")", ";", "return", "builder", ".", "tableName", "(", "tableName", ")", ";", "}" ]
This method may cause tablesaw to buffer the entire InputStream. <p> If you have a large amount of data, you can do one of the following: 1. Use the method taking a File instead of a reader, or 2. Provide the array of column types as an option. If you provide the columnType array, we skip type detection and can avoid reading the entire file
[ "This", "method", "may", "cause", "tablesaw", "to", "buffer", "the", "entire", "InputStream", "." ]
train
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/html/src/main/java/tech/tablesaw/io/html/HtmlReadOptions.java#L70-L73
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/util/ReflectionUtil.java
ReflectionUtil.inspectRecursively
private static void inspectRecursively(Class<?> c, List<Method> s, Class<? extends Annotation> annotationType) { for (Method m : c.getDeclaredMethods()) { // don't bother if this method has already been overridden by a subclass if (notFound(m, s) && m.isAnnotationPresent(annotationType)) { s.add(m); } } if (!c.equals(Object.class)) { if (!c.isInterface()) { inspectRecursively(c.getSuperclass(), s, annotationType); } for (Class<?> ifc : c.getInterfaces()) inspectRecursively(ifc, s, annotationType); } }
java
private static void inspectRecursively(Class<?> c, List<Method> s, Class<? extends Annotation> annotationType) { for (Method m : c.getDeclaredMethods()) { // don't bother if this method has already been overridden by a subclass if (notFound(m, s) && m.isAnnotationPresent(annotationType)) { s.add(m); } } if (!c.equals(Object.class)) { if (!c.isInterface()) { inspectRecursively(c.getSuperclass(), s, annotationType); } for (Class<?> ifc : c.getInterfaces()) inspectRecursively(ifc, s, annotationType); } }
[ "private", "static", "void", "inspectRecursively", "(", "Class", "<", "?", ">", "c", ",", "List", "<", "Method", ">", "s", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationType", ")", "{", "for", "(", "Method", "m", ":", "c", ".", "ge...
Inspects a class and its superclasses (all the way to {@link Object} for method instances that contain a given annotation. This even identifies private, package and protected methods, not just public ones.
[ "Inspects", "a", "class", "and", "its", "superclasses", "(", "all", "the", "way", "to", "{" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/util/ReflectionUtil.java#L115-L130
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java
DateUtil.betweenMonth
public static long betweenMonth(Date beginDate, Date endDate, boolean isReset) { return new DateBetween(beginDate, endDate).betweenMonth(isReset); }
java
public static long betweenMonth(Date beginDate, Date endDate, boolean isReset) { return new DateBetween(beginDate, endDate).betweenMonth(isReset); }
[ "public", "static", "long", "betweenMonth", "(", "Date", "beginDate", ",", "Date", "endDate", ",", "boolean", "isReset", ")", "{", "return", "new", "DateBetween", "(", "beginDate", ",", "endDate", ")", ".", "betweenMonth", "(", "isReset", ")", ";", "}" ]
计算两个日期相差月数<br> 在非重置情况下,如果起始日期的天小于结束日期的天,月数要少算1(不足1个月) @param beginDate 起始日期 @param endDate 结束日期 @param isReset 是否重置时间为起始时间(重置天时分秒) @return 相差月数 @since 3.0.8
[ "计算两个日期相差月数<br", ">", "在非重置情况下,如果起始日期的天小于结束日期的天,月数要少算1(不足1个月)" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L1292-L1294
Netflix/conductor
es6-persistence/src/main/java/com/netflix/conductor/dao/es6/index/ElasticSearchRestDAOV6.java
ElasticSearchRestDAOV6.addMappingToIndex
private void addMappingToIndex(final String index, final String mappingType, final String mappingFilename) throws IOException { logger.info("Adding '{}' mapping to index '{}'...", mappingType, index); String resourcePath = "/" + index + "/_mapping/" + mappingType; if (doesResourceNotExist(resourcePath)) { HttpEntity entity = new NByteArrayEntity(loadTypeMappingSource(mappingFilename).getBytes(), ContentType.APPLICATION_JSON); elasticSearchAdminClient.performRequest(HttpMethod.PUT, resourcePath, Collections.emptyMap(), entity); logger.info("Added '{}' mapping", mappingType); } else { logger.info("Mapping '{}' already exists", mappingType); } }
java
private void addMappingToIndex(final String index, final String mappingType, final String mappingFilename) throws IOException { logger.info("Adding '{}' mapping to index '{}'...", mappingType, index); String resourcePath = "/" + index + "/_mapping/" + mappingType; if (doesResourceNotExist(resourcePath)) { HttpEntity entity = new NByteArrayEntity(loadTypeMappingSource(mappingFilename).getBytes(), ContentType.APPLICATION_JSON); elasticSearchAdminClient.performRequest(HttpMethod.PUT, resourcePath, Collections.emptyMap(), entity); logger.info("Added '{}' mapping", mappingType); } else { logger.info("Mapping '{}' already exists", mappingType); } }
[ "private", "void", "addMappingToIndex", "(", "final", "String", "index", ",", "final", "String", "mappingType", ",", "final", "String", "mappingFilename", ")", "throws", "IOException", "{", "logger", ".", "info", "(", "\"Adding '{}' mapping to index '{}'...\"", ",", ...
Adds a mapping type to an index if it does not exist. @param index The name of the index. @param mappingType The name of the mapping type. @param mappingFilename The name of the mapping file to use to add the mapping if it does not exist. @throws IOException If an error occurred during requests to ES.
[ "Adds", "a", "mapping", "type", "to", "an", "index", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/es6-persistence/src/main/java/com/netflix/conductor/dao/es6/index/ElasticSearchRestDAOV6.java#L310-L323
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/Trash.java
Trash.safeFsMkdir
private boolean safeFsMkdir(FileSystem fs, Path f, FsPermission permission) throws IOException { try { return fs.mkdirs(f, permission); } catch (IOException e) { // To handle the case when trash folder is created by other threads // The case is rare and we don't put synchronized keywords for performance consideration. if (!fs.exists(f)) { throw new IOException("Failed to create trash folder while it is still not existed yet."); } else { LOG.debug("Target folder %s has been created by other threads.", f.toString()); return true; } } }
java
private boolean safeFsMkdir(FileSystem fs, Path f, FsPermission permission) throws IOException { try { return fs.mkdirs(f, permission); } catch (IOException e) { // To handle the case when trash folder is created by other threads // The case is rare and we don't put synchronized keywords for performance consideration. if (!fs.exists(f)) { throw new IOException("Failed to create trash folder while it is still not existed yet."); } else { LOG.debug("Target folder %s has been created by other threads.", f.toString()); return true; } } }
[ "private", "boolean", "safeFsMkdir", "(", "FileSystem", "fs", ",", "Path", "f", ",", "FsPermission", "permission", ")", "throws", "IOException", "{", "try", "{", "return", "fs", ".", "mkdirs", "(", "f", ",", "permission", ")", ";", "}", "catch", "(", "IO...
Safe creation of trash folder to ensure thread-safe. @throws IOException
[ "Safe", "creation", "of", "trash", "folder", "to", "ensure", "thread", "-", "safe", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/Trash.java#L287-L300
buschmais/jqa-java-plugin
src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java
VisitorHelper.addReads
void addReads(MethodDescriptor methodDescriptor, final Integer lineNumber, FieldDescriptor fieldDescriptor) { ReadsDescriptor readsDescriptor = scannerContext.getStore().create(methodDescriptor, ReadsDescriptor.class, fieldDescriptor); readsDescriptor.setLineNumber(lineNumber); }
java
void addReads(MethodDescriptor methodDescriptor, final Integer lineNumber, FieldDescriptor fieldDescriptor) { ReadsDescriptor readsDescriptor = scannerContext.getStore().create(methodDescriptor, ReadsDescriptor.class, fieldDescriptor); readsDescriptor.setLineNumber(lineNumber); }
[ "void", "addReads", "(", "MethodDescriptor", "methodDescriptor", ",", "final", "Integer", "lineNumber", ",", "FieldDescriptor", "fieldDescriptor", ")", "{", "ReadsDescriptor", "readsDescriptor", "=", "scannerContext", ".", "getStore", "(", ")", ".", "create", "(", "...
Add a reads relation between a method and a field. @param methodDescriptor The method. @param lineNumber The line number. @param fieldDescriptor The field.
[ "Add", "a", "reads", "relation", "between", "a", "method", "and", "a", "field", "." ]
train
https://github.com/buschmais/jqa-java-plugin/blob/4c050943e9c28cf1c4a08aa962d5b5bf03c4fe54/src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java#L151-L154
hypercube1024/firefly
firefly/src/main/java/com/firefly/codec/http2/model/MultiPartContentProvider.java
MultiPartContentProvider.addFilePart
public void addFilePart(String name, String fileName, ContentProvider content, HttpFields fields) { addPart(new Part(name, fileName, "application/octet-stream", content, fields)); }
java
public void addFilePart(String name, String fileName, ContentProvider content, HttpFields fields) { addPart(new Part(name, fileName, "application/octet-stream", content, fields)); }
[ "public", "void", "addFilePart", "(", "String", "name", ",", "String", "fileName", ",", "ContentProvider", "content", ",", "HttpFields", "fields", ")", "{", "addPart", "(", "new", "Part", "(", "name", ",", "fileName", ",", "\"application/octet-stream\"", ",", ...
<p>Adds a file part with the given {@code name} as field name, the given {@code fileName} as file name, and the given {@code content} as part content.</p> @param name the part name @param fileName the file name associated to this part @param content the part content @param fields the headers associated with this part
[ "<p", ">", "Adds", "a", "file", "part", "with", "the", "given", "{", "@code", "name", "}", "as", "field", "name", "the", "given", "{", "@code", "fileName", "}", "as", "file", "name", "and", "the", "given", "{", "@code", "content", "}", "as", "part", ...
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/http2/model/MultiPartContentProvider.java#L83-L85
nemerosa/ontrack
ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/TemplateDefinition.java
TemplateDefinition.templateInstanceExecution
public TemplateInstanceExecution templateInstanceExecution(String sourceName, ExpressionEngine expressionEngine) { // Transforms each parameter in a name/value pair, using only the source name as input Map<String, String> sourceNameInput = Collections.singletonMap("sourceName", sourceName); Map<String, String> parameterMap = Maps.transformValues( Maps.uniqueIndex( parameters, TemplateParameter::getName ), parameter -> expressionEngine.render(parameter.getExpression(), sourceNameInput) ); // Concatenates the maps Map<String, String> inputMap = new HashMap<>(sourceNameInput); inputMap.putAll(parameterMap); // Resolves the final expression return new TemplateInstanceExecution( value -> expressionEngine.render(value, inputMap), parameterMap ); }
java
public TemplateInstanceExecution templateInstanceExecution(String sourceName, ExpressionEngine expressionEngine) { // Transforms each parameter in a name/value pair, using only the source name as input Map<String, String> sourceNameInput = Collections.singletonMap("sourceName", sourceName); Map<String, String> parameterMap = Maps.transformValues( Maps.uniqueIndex( parameters, TemplateParameter::getName ), parameter -> expressionEngine.render(parameter.getExpression(), sourceNameInput) ); // Concatenates the maps Map<String, String> inputMap = new HashMap<>(sourceNameInput); inputMap.putAll(parameterMap); // Resolves the final expression return new TemplateInstanceExecution( value -> expressionEngine.render(value, inputMap), parameterMap ); }
[ "public", "TemplateInstanceExecution", "templateInstanceExecution", "(", "String", "sourceName", ",", "ExpressionEngine", "expressionEngine", ")", "{", "// Transforms each parameter in a name/value pair, using only the source name as input", "Map", "<", "String", ",", "String", ">"...
Gets the execution context for the creation of a template instance. @param sourceName Input for the expression @param expressionEngine Expression engine to use @return Transformed string
[ "Gets", "the", "execution", "context", "for", "the", "creation", "of", "a", "template", "instance", "." ]
train
https://github.com/nemerosa/ontrack/blob/37b0874cbf387b58aba95cd3c1bc3b15e11bc913/ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/TemplateDefinition.java#L53-L71
groupon/odo
client/src/main/java/com/groupon/odo/client/Client.java
Client.setCustomForDefaultClient
protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) { try { Client client = new Client(profileName, false); client.toggleProfile(true); client.setCustom(isResponse, pathName, customData); if (isResponse) { client.toggleResponseOverride(pathName, true); } else { client.toggleRequestOverride(pathName, true); } return true; } catch (Exception e) { e.printStackTrace(); } return false; }
java
protected static boolean setCustomForDefaultClient(String profileName, String pathName, Boolean isResponse, String customData) { try { Client client = new Client(profileName, false); client.toggleProfile(true); client.setCustom(isResponse, pathName, customData); if (isResponse) { client.toggleResponseOverride(pathName, true); } else { client.toggleRequestOverride(pathName, true); } return true; } catch (Exception e) { e.printStackTrace(); } return false; }
[ "protected", "static", "boolean", "setCustomForDefaultClient", "(", "String", "profileName", ",", "String", "pathName", ",", "Boolean", "isResponse", ",", "String", "customData", ")", "{", "try", "{", "Client", "client", "=", "new", "Client", "(", "profileName", ...
set custom response or request for a profile's default client, ensures profile and path are enabled @param profileName profileName to modift, default client is used @param pathName friendly name of path @param isResponse true if response, false for request @param customData custom response/request data @return true if success, false otherwise
[ "set", "custom", "response", "or", "request", "for", "a", "profile", "s", "default", "client", "ensures", "profile", "and", "path", "are", "enabled" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L793-L808
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/property/A_CmsPropertyEditor.java
A_CmsPropertyEditor.checkWidgetRequirements
public static void checkWidgetRequirements(String key, I_CmsFormWidget widget) { if (widget instanceof CmsTinyMCEWidget) { return; } if (!((widget instanceof I_CmsHasGhostValue) && (widget instanceof HasValueChangeHandlers<?>))) { throw new CmsWidgetNotSupportedException(key); } }
java
public static void checkWidgetRequirements(String key, I_CmsFormWidget widget) { if (widget instanceof CmsTinyMCEWidget) { return; } if (!((widget instanceof I_CmsHasGhostValue) && (widget instanceof HasValueChangeHandlers<?>))) { throw new CmsWidgetNotSupportedException(key); } }
[ "public", "static", "void", "checkWidgetRequirements", "(", "String", "key", ",", "I_CmsFormWidget", "widget", ")", "{", "if", "(", "widget", "instanceof", "CmsTinyMCEWidget", ")", "{", "return", ";", "}", "if", "(", "!", "(", "(", "widget", "instanceof", "I...
Checks whether a widget can be used in the sitemap entry editor, and throws an exception otherwise.<p> @param key the widget key @param widget the created widget
[ "Checks", "whether", "a", "widget", "can", "be", "used", "in", "the", "sitemap", "entry", "editor", "and", "throws", "an", "exception", "otherwise", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/property/A_CmsPropertyEditor.java#L115-L123
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.addPreQualifiedClassLink
public void addPreQualifiedClassLink(LinkInfoImpl.Kind context, TypeElement typeElement, boolean isStrong, Content contentTree) { PackageElement pkg = utils.containingPackage(typeElement); if(pkg != null && ! configuration.shouldExcludeQualifier(pkg.getSimpleName().toString())) { contentTree.addContent(getEnclosingPackageName(typeElement)); } LinkInfoImpl linkinfo = new LinkInfoImpl(configuration, context, typeElement) .label(utils.getSimpleName(typeElement)) .strong(isStrong); Content link = getLink(linkinfo); contentTree.addContent(link); }
java
public void addPreQualifiedClassLink(LinkInfoImpl.Kind context, TypeElement typeElement, boolean isStrong, Content contentTree) { PackageElement pkg = utils.containingPackage(typeElement); if(pkg != null && ! configuration.shouldExcludeQualifier(pkg.getSimpleName().toString())) { contentTree.addContent(getEnclosingPackageName(typeElement)); } LinkInfoImpl linkinfo = new LinkInfoImpl(configuration, context, typeElement) .label(utils.getSimpleName(typeElement)) .strong(isStrong); Content link = getLink(linkinfo); contentTree.addContent(link); }
[ "public", "void", "addPreQualifiedClassLink", "(", "LinkInfoImpl", ".", "Kind", "context", ",", "TypeElement", "typeElement", ",", "boolean", "isStrong", ",", "Content", "contentTree", ")", "{", "PackageElement", "pkg", "=", "utils", ".", "containingPackage", "(", ...
Add the class link with the package portion of the label in plain text. If the qualifier is excluded, it will not be included in the link label. @param context the id of the context where the link will be added @param typeElement the class to link to @param isStrong true if the link should be strong @param contentTree the content tree to which the link with be added
[ "Add", "the", "class", "link", "with", "the", "package", "portion", "of", "the", "label", "in", "plain", "text", ".", "If", "the", "qualifier", "is", "excluded", "it", "will", "not", "be", "included", "in", "the", "link", "label", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java#L1318-L1329
buschmais/jqa-core-framework
scanner/src/main/java/com/buschmais/jqassistant/core/scanner/impl/ScannerImpl.java
ScannerImpl.popDescriptor
private <D extends Descriptor> void popDescriptor(Class<D> type, D descriptor) { if (descriptor != null) { scannerContext.setCurrentDescriptor(null); scannerContext.pop(type); } }
java
private <D extends Descriptor> void popDescriptor(Class<D> type, D descriptor) { if (descriptor != null) { scannerContext.setCurrentDescriptor(null); scannerContext.pop(type); } }
[ "private", "<", "D", "extends", "Descriptor", ">", "void", "popDescriptor", "(", "Class", "<", "D", ">", "type", ",", "D", "descriptor", ")", "{", "if", "(", "descriptor", "!=", "null", ")", "{", "scannerContext", ".", "setCurrentDescriptor", "(", "null", ...
Pop the given descriptor from the context. @param descriptor The descriptor. @param <D> The descriptor type.
[ "Pop", "the", "given", "descriptor", "from", "the", "context", "." ]
train
https://github.com/buschmais/jqa-core-framework/blob/0e63ff509cfe52f9063539a23d5f9f183b2ea4a5/scanner/src/main/java/com/buschmais/jqassistant/core/scanner/impl/ScannerImpl.java#L201-L206
gwtplus/google-gin
src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java
PrettyPrinter.formatArgTo
private static void formatArgTo(List<Dependency> path, StringBuilder builder) { if (path.isEmpty()) { return; } builder.append("\n"); boolean first = true; Key<?> previousTarget = null; // For sanity-checking. for (Dependency dependency : path) { Key<?> source = dependency.getSource(); Key<?> target = dependency.getTarget(); // Sanity-check. if (previousTarget != null && !previousTarget.equals(source)) { throw new IllegalArgumentException("Dependency list is not a path."); } // There are two possible overall shapes of the list: // // If it starts with GINJECTOR, we get this: // // Key1 [context] // -> Key2 [context] // ... // // Otherwise (e.g., if we're dumping a cycle), we get this: // // Key1 // -> Key2 [context] // -> Key3 [context] // ... if (first) { if (source == Dependency.GINJECTOR) { formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } else { formatArgTo(source, builder); builder.append("\n -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } first = false; } else { builder.append(" -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } previousTarget = target; } }
java
private static void formatArgTo(List<Dependency> path, StringBuilder builder) { if (path.isEmpty()) { return; } builder.append("\n"); boolean first = true; Key<?> previousTarget = null; // For sanity-checking. for (Dependency dependency : path) { Key<?> source = dependency.getSource(); Key<?> target = dependency.getTarget(); // Sanity-check. if (previousTarget != null && !previousTarget.equals(source)) { throw new IllegalArgumentException("Dependency list is not a path."); } // There are two possible overall shapes of the list: // // If it starts with GINJECTOR, we get this: // // Key1 [context] // -> Key2 [context] // ... // // Otherwise (e.g., if we're dumping a cycle), we get this: // // Key1 // -> Key2 [context] // -> Key3 [context] // ... if (first) { if (source == Dependency.GINJECTOR) { formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } else { formatArgTo(source, builder); builder.append("\n -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } first = false; } else { builder.append(" -> "); formatArgTo(target, builder); builder.append(String.format(" [%s]%n", dependency.getContext())); } previousTarget = target; } }
[ "private", "static", "void", "formatArgTo", "(", "List", "<", "Dependency", ">", "path", ",", "StringBuilder", "builder", ")", "{", "if", "(", "path", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "builder", ".", "append", "(", "\"\\n\"", ")"...
Formats a list of dependencies as a dependency path; see the class comments.
[ "Formats", "a", "list", "of", "dependencies", "as", "a", "dependency", "path", ";", "see", "the", "class", "comments", "." ]
train
https://github.com/gwtplus/google-gin/blob/595e61ee0d2fa508815c016e924ec0e5cea2a2aa/src/main/java/com/google/gwt/inject/rebind/util/PrettyPrinter.java#L146-L197
facebook/fresco
samples/gestures/src/main/java/com/facebook/samples/gestures/MultiPointerGestureDetector.java
MultiPointerGestureDetector.getPressedPointerIndex
private int getPressedPointerIndex(MotionEvent event, int i) { final int count = event.getPointerCount(); final int action = event.getActionMasked(); final int index = event.getActionIndex(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { if (i >= index) { i++; } } return (i < count) ? i : -1; }
java
private int getPressedPointerIndex(MotionEvent event, int i) { final int count = event.getPointerCount(); final int action = event.getActionMasked(); final int index = event.getActionIndex(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { if (i >= index) { i++; } } return (i < count) ? i : -1; }
[ "private", "int", "getPressedPointerIndex", "(", "MotionEvent", "event", ",", "int", "i", ")", "{", "final", "int", "count", "=", "event", ".", "getPointerCount", "(", ")", ";", "final", "int", "action", "=", "event", ".", "getActionMasked", "(", ")", ";",...
Gets the index of the i-th pressed pointer. Normally, the index will be equal to i, except in the case when the pointer is released. @return index of the specified pointer or -1 if not found (i.e. not enough pointers are down)
[ "Gets", "the", "index", "of", "the", "i", "-", "th", "pressed", "pointer", ".", "Normally", "the", "index", "will", "be", "equal", "to", "i", "except", "in", "the", "case", "when", "the", "pointer", "is", "released", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/gestures/src/main/java/com/facebook/samples/gestures/MultiPointerGestureDetector.java#L116-L127
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.appendStringInto
public static void appendStringInto( String s, File outputFile ) throws IOException { OutputStreamWriter fw = null; try { fw = new OutputStreamWriter( new FileOutputStream( outputFile, true ), StandardCharsets.UTF_8 ); fw.append( s ); } finally { Utils.closeQuietly( fw ); } }
java
public static void appendStringInto( String s, File outputFile ) throws IOException { OutputStreamWriter fw = null; try { fw = new OutputStreamWriter( new FileOutputStream( outputFile, true ), StandardCharsets.UTF_8 ); fw.append( s ); } finally { Utils.closeQuietly( fw ); } }
[ "public", "static", "void", "appendStringInto", "(", "String", "s", ",", "File", "outputFile", ")", "throws", "IOException", "{", "OutputStreamWriter", "fw", "=", "null", ";", "try", "{", "fw", "=", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", ...
Appends a string into a file. @param s the string to write (not null) @param outputFile the file to write into @throws IOException if something went wrong
[ "Appends", "a", "string", "into", "a", "file", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L418-L428
Alluxio/alluxio
job/server/src/main/java/alluxio/job/util/JobUtils.java
JobUtils.loadBlock
public static void loadBlock(FileSystem fs, FileSystemContext context, String path, long blockId) throws AlluxioException, IOException { AlluxioBlockStore blockStore = AlluxioBlockStore.create(context); String localHostName = NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, ServerConfiguration.global()); List<BlockWorkerInfo> workerInfoList = blockStore.getAllWorkers(); WorkerNetAddress localNetAddress = null; for (BlockWorkerInfo workerInfo : workerInfoList) { if (workerInfo.getNetAddress().getHost().equals(localHostName)) { localNetAddress = workerInfo.getNetAddress(); break; } } if (localNetAddress == null) { throw new NotFoundException(ExceptionMessage.NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK .getMessage(blockId)); } // TODO(jiri): Replace with internal client that uses file ID once the internal client is // factored out of the core server module. The reason to prefer using file ID for this job is // to avoid the the race between "replicate" and "rename", so that even a file to replicate is // renamed, the job is still working on the correct file. URIStatus status = fs.getStatus(new AlluxioURI(path)); OpenFilePOptions openOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); AlluxioConfiguration conf = ServerConfiguration.global(); InStreamOptions inOptions = new InStreamOptions(status, openOptions, conf); // Set read location policy always to loca first for loading blocks for job tasks inOptions.setUfsReadLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); OutStreamOptions outOptions = OutStreamOptions.defaults(conf); // Set write location policy always to local first for loading blocks for job tasks outOptions.setLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); // use -1 to reuse the existing block size for this block try (OutputStream outputStream = blockStore.getOutStream(blockId, -1, localNetAddress, outOptions)) { try (InputStream inputStream = blockStore.getInStream(blockId, inOptions)) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable t) { try { ((Cancelable) outputStream).cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } }
java
public static void loadBlock(FileSystem fs, FileSystemContext context, String path, long blockId) throws AlluxioException, IOException { AlluxioBlockStore blockStore = AlluxioBlockStore.create(context); String localHostName = NetworkAddressUtils.getConnectHost(ServiceType.WORKER_RPC, ServerConfiguration.global()); List<BlockWorkerInfo> workerInfoList = blockStore.getAllWorkers(); WorkerNetAddress localNetAddress = null; for (BlockWorkerInfo workerInfo : workerInfoList) { if (workerInfo.getNetAddress().getHost().equals(localHostName)) { localNetAddress = workerInfo.getNetAddress(); break; } } if (localNetAddress == null) { throw new NotFoundException(ExceptionMessage.NO_LOCAL_BLOCK_WORKER_REPLICATE_TASK .getMessage(blockId)); } // TODO(jiri): Replace with internal client that uses file ID once the internal client is // factored out of the core server module. The reason to prefer using file ID for this job is // to avoid the the race between "replicate" and "rename", so that even a file to replicate is // renamed, the job is still working on the correct file. URIStatus status = fs.getStatus(new AlluxioURI(path)); OpenFilePOptions openOptions = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build(); AlluxioConfiguration conf = ServerConfiguration.global(); InStreamOptions inOptions = new InStreamOptions(status, openOptions, conf); // Set read location policy always to loca first for loading blocks for job tasks inOptions.setUfsReadLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); OutStreamOptions outOptions = OutStreamOptions.defaults(conf); // Set write location policy always to local first for loading blocks for job tasks outOptions.setLocationPolicy(BlockLocationPolicy.Factory.create( LocalFirstPolicy.class.getCanonicalName(), conf)); // use -1 to reuse the existing block size for this block try (OutputStream outputStream = blockStore.getOutStream(blockId, -1, localNetAddress, outOptions)) { try (InputStream inputStream = blockStore.getInStream(blockId, inOptions)) { ByteStreams.copy(inputStream, outputStream); } catch (Throwable t) { try { ((Cancelable) outputStream).cancel(); } catch (Throwable t2) { t.addSuppressed(t2); } throw t; } } }
[ "public", "static", "void", "loadBlock", "(", "FileSystem", "fs", ",", "FileSystemContext", "context", ",", "String", "path", ",", "long", "blockId", ")", "throws", "AlluxioException", ",", "IOException", "{", "AlluxioBlockStore", "blockStore", "=", "AlluxioBlockSto...
Loads a block into the local worker. If the block doesn't exist in Alluxio, it will be read from the UFS. @param fs the filesystem @param context filesystem context @param path the file path of the block to load @param blockId the id of the block to load
[ "Loads", "a", "block", "into", "the", "local", "worker", ".", "If", "the", "block", "doesn", "t", "exist", "in", "Alluxio", "it", "will", "be", "read", "from", "the", "UFS", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/job/server/src/main/java/alluxio/job/util/JobUtils.java#L107-L161
kiegroup/jbpm
jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/RuntimeEnvironmentBuilder.java
RuntimeEnvironmentBuilder.getDefault
public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version) { return getDefault(groupId, artifactId, version, null, null); }
java
public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version) { return getDefault(groupId, artifactId, version, null, null); }
[ "public", "static", "RuntimeEnvironmentBuilder", "getDefault", "(", "String", "groupId", ",", "String", "artifactId", ",", "String", "version", ")", "{", "return", "getDefault", "(", "groupId", ",", "artifactId", ",", "version", ",", "null", ",", "null", ")", ...
Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on: <ul> <li>DefaultRuntimeEnvironment</li> </ul> This one is tailored to works smoothly with kjars as the notion of kbase and ksessions @param groupId group id of kjar @param artifactId artifact id of kjar @param version version number of kjar @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults @see DefaultRuntimeEnvironment
[ "Provides", "default", "configuration", "of", "<code", ">", "RuntimeEnvironmentBuilder<", "/", "code", ">", "that", "is", "based", "on", ":", "<ul", ">", "<li", ">", "DefaultRuntimeEnvironment<", "/", "li", ">", "<", "/", "ul", ">", "This", "one", "is", "t...
train
https://github.com/kiegroup/jbpm/blob/c3473c728aa382ebbea01e380c5e754a96647b82/jbpm-runtime-manager/src/main/java/org/jbpm/runtime/manager/impl/RuntimeEnvironmentBuilder.java#L144-L146
SeaCloudsEU/SeaCloudsPlatform
discoverer/src/main/java/eu/seaclouds/platform/discoverer/crawler/CloudHarmonySPECint.java
CloudHarmonySPECint.getSPECint
public static Integer getSPECint(String providerName, String instanceType) { String key = providerName + "." + instanceType; return SPECint.get(key); }
java
public static Integer getSPECint(String providerName, String instanceType) { String key = providerName + "." + instanceType; return SPECint.get(key); }
[ "public", "static", "Integer", "getSPECint", "(", "String", "providerName", ",", "String", "instanceType", ")", "{", "String", "key", "=", "providerName", "+", "\".\"", "+", "instanceType", ";", "return", "SPECint", ".", "get", "(", "key", ")", ";", "}" ]
Gets the SPECint of the specified instance of the specified offerings provider @param providerName the name of the offerings provider @param instanceType istance type as specified in the CloudHarmony API @return SPECint of the specified instance
[ "Gets", "the", "SPECint", "of", "the", "specified", "instance", "of", "the", "specified", "offerings", "provider" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/discoverer/src/main/java/eu/seaclouds/platform/discoverer/crawler/CloudHarmonySPECint.java#L79-L82
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java
LazyList.toXml
public String toXml(boolean pretty, boolean declaration, String... attrs) { String topNode = Inflector.pluralize(Inflector.underscore(metaModel.getModelClass().getSimpleName())); hydrate(); StringBuilder sb = new StringBuilder(); if(declaration) { sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (pretty) sb.append('\n'); } sb.append('<').append(topNode).append('>'); if (pretty) { sb.append('\n'); } for (T t : delegate) { t.toXmlP(sb, pretty, pretty ? " " : "", attrs); } sb.append("</").append(topNode).append('>'); if (pretty) { sb.append('\n'); } return sb.toString(); }
java
public String toXml(boolean pretty, boolean declaration, String... attrs) { String topNode = Inflector.pluralize(Inflector.underscore(metaModel.getModelClass().getSimpleName())); hydrate(); StringBuilder sb = new StringBuilder(); if(declaration) { sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (pretty) sb.append('\n'); } sb.append('<').append(topNode).append('>'); if (pretty) { sb.append('\n'); } for (T t : delegate) { t.toXmlP(sb, pretty, pretty ? " " : "", attrs); } sb.append("</").append(topNode).append('>'); if (pretty) { sb.append('\n'); } return sb.toString(); }
[ "public", "String", "toXml", "(", "boolean", "pretty", ",", "boolean", "declaration", ",", "String", "...", "attrs", ")", "{", "String", "topNode", "=", "Inflector", ".", "pluralize", "(", "Inflector", ".", "underscore", "(", "metaModel", ".", "getModelClass",...
Generates a XML document from content of this list. @param pretty pretty format (human readable), or one line text. @param declaration true to include XML declaration at the top @param attrs list of attributes to include. No arguments == include all attributes. @return generated XML.
[ "Generates", "a", "XML", "document", "from", "content", "of", "this", "list", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/LazyList.java#L203-L221
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/MultimapJoiner.java
MultimapJoiner.appendTo
public StringBuilder appendTo(StringBuilder builder, Multimap<?, ?> map) { return appendTo(builder, map.asMap().entrySet()); }
java
public StringBuilder appendTo(StringBuilder builder, Multimap<?, ?> map) { return appendTo(builder, map.asMap().entrySet()); }
[ "public", "StringBuilder", "appendTo", "(", "StringBuilder", "builder", ",", "Multimap", "<", "?", ",", "?", ">", "map", ")", "{", "return", "appendTo", "(", "builder", ",", "map", ".", "asMap", "(", ")", ".", "entrySet", "(", ")", ")", ";", "}" ]
Appends the string representation of each entry of {@code map}, using the previously configured separator and key-value separator, to {@code builder}. Identical to {@link #appendTo(Appendable, Multimap)}, except that it does not throw {@link IOException}.
[ "Appends", "the", "string", "representation", "of", "each", "entry", "of", "{" ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/util/MultimapJoiner.java#L62-L64
VoltDB/voltdb
src/frontend/org/voltdb/SnapshotDaemon.java
SnapshotDaemon.processScanResponse
private void processScanResponse(ClientResponse response) { setState(State.WAITING); if (response.getStatus() != ClientResponse.SUCCESS) { logFailureResponse("Initial snapshot scan failed", response); return; } final VoltTable results[] = response.getResults(); if (results.length == 1) { final VoltTable result = results[0]; boolean advanced = result.advanceRow(); assert(advanced); assert(result.getColumnCount() == 1); assert(result.getColumnType(0) == VoltType.STRING); SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG")); return; } assert(results.length == 3); final VoltTable snapshots = results[0]; assert(snapshots.getColumnCount() == 10); final File myPath = new File(m_path); while (snapshots.advanceRow()) { final String path = snapshots.getString("PATH"); final File pathFile = new File(path); if (pathFile.equals(myPath)) { final String nonce = snapshots.getString("NONCE"); if (nonce.startsWith(m_prefixAndSeparator)) { final Long txnId = snapshots.getLong("TXNID"); m_snapshots.add(new Snapshot(path, SnapshotPathType.SNAP_AUTO, nonce, txnId)); } } } java.util.Collections.sort(m_snapshots); deleteExtraSnapshots(); }
java
private void processScanResponse(ClientResponse response) { setState(State.WAITING); if (response.getStatus() != ClientResponse.SUCCESS) { logFailureResponse("Initial snapshot scan failed", response); return; } final VoltTable results[] = response.getResults(); if (results.length == 1) { final VoltTable result = results[0]; boolean advanced = result.advanceRow(); assert(advanced); assert(result.getColumnCount() == 1); assert(result.getColumnType(0) == VoltType.STRING); SNAP_LOG.warn("Initial snapshot scan failed with failure response: " + result.getString("ERR_MSG")); return; } assert(results.length == 3); final VoltTable snapshots = results[0]; assert(snapshots.getColumnCount() == 10); final File myPath = new File(m_path); while (snapshots.advanceRow()) { final String path = snapshots.getString("PATH"); final File pathFile = new File(path); if (pathFile.equals(myPath)) { final String nonce = snapshots.getString("NONCE"); if (nonce.startsWith(m_prefixAndSeparator)) { final Long txnId = snapshots.getLong("TXNID"); m_snapshots.add(new Snapshot(path, SnapshotPathType.SNAP_AUTO, nonce, txnId)); } } } java.util.Collections.sort(m_snapshots); deleteExtraSnapshots(); }
[ "private", "void", "processScanResponse", "(", "ClientResponse", "response", ")", "{", "setState", "(", "State", ".", "WAITING", ")", ";", "if", "(", "response", ".", "getStatus", "(", ")", "!=", "ClientResponse", ".", "SUCCESS", ")", "{", "logFailureResponse"...
Process the response to a snapshot scan. Find the snapshots that are managed by this daemon by path and nonce and add it the list. Initiate a delete of any that should not be retained @param response @return
[ "Process", "the", "response", "to", "a", "snapshot", "scan", ".", "Find", "the", "snapshots", "that", "are", "managed", "by", "this", "daemon", "by", "path", "and", "nonce", "and", "add", "it", "the", "list", ".", "Initiate", "a", "delete", "of", "any", ...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/SnapshotDaemon.java#L1536-L1574
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/threading/Deadline.java
Deadline.waitFor
public void waitFor(final Object monitor, final boolean ignoreInterrupts) { synchronized (monitor) { try { monitor.wait(this.getTimeLeft(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { if (!ignoreInterrupts) return; } } return; }
java
public void waitFor(final Object monitor, final boolean ignoreInterrupts) { synchronized (monitor) { try { monitor.wait(this.getTimeLeft(TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { if (!ignoreInterrupts) return; } } return; }
[ "public", "void", "waitFor", "(", "final", "Object", "monitor", ",", "final", "boolean", "ignoreInterrupts", ")", "{", "synchronized", "(", "monitor", ")", "{", "try", "{", "monitor", ".", "wait", "(", "this", ".", "getTimeLeft", "(", "TimeUnit", ".", "MIL...
Waits on the listed monitor until it returns or until this deadline has expired; if <code>mayInterrupt</code> is true then an interrupt will cause this method to return true @param ignoreInterrupts false if the code should return early in the event of an interrupt, otherwise true if InterruptedExceptions should be ignored
[ "Waits", "on", "the", "listed", "monitor", "until", "it", "returns", "or", "until", "this", "deadline", "has", "expired", ";", "if", "<code", ">", "mayInterrupt<", "/", "code", ">", "is", "true", "then", "an", "interrupt", "will", "cause", "this", "method"...
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/threading/Deadline.java#L239-L255
infinispan/infinispan
server/hotrod/src/main/java/org/infinispan/server/hotrod/transport/ExtendedByteBuf.java
ExtendedByteBuf.readMaybeVInt
public static Optional<Integer> readMaybeVInt(ByteBuf bf) { if (bf.readableBytes() >= 1) { byte b = bf.readByte(); return read(bf, b, 7, b & 0x7F, 1); } else { bf.resetReaderIndex(); return Optional.empty(); } }
java
public static Optional<Integer> readMaybeVInt(ByteBuf bf) { if (bf.readableBytes() >= 1) { byte b = bf.readByte(); return read(bf, b, 7, b & 0x7F, 1); } else { bf.resetReaderIndex(); return Optional.empty(); } }
[ "public", "static", "Optional", "<", "Integer", ">", "readMaybeVInt", "(", "ByteBuf", "bf", ")", "{", "if", "(", "bf", ".", "readableBytes", "(", ")", ">=", "1", ")", "{", "byte", "b", "=", "bf", ".", "readByte", "(", ")", ";", "return", "read", "(...
Reads a variable size int if possible. If not present the reader index is reset to the last mark. @param bf @return
[ "Reads", "a", "variable", "size", "int", "if", "possible", ".", "If", "not", "present", "the", "reader", "index", "is", "reset", "to", "the", "last", "mark", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/transport/ExtendedByteBuf.java#L145-L153
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/release/maven/PomTransformer.java
PomTransformer.invoke
public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException { org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName( currentModule.groupId, currentModule.artifactId); Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap(); for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) { modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName( entry.getKey().groupId, entry.getKey().artifactId), entry.getValue()); } org.jfrog.build.extractor.maven.transformer.PomTransformer transformer = new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl, failOnSnapshot); return transformer.transform(pomFile); }
java
public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException { org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName( currentModule.groupId, currentModule.artifactId); Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap(); for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) { modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName( entry.getKey().groupId, entry.getKey().artifactId), entry.getValue()); } org.jfrog.build.extractor.maven.transformer.PomTransformer transformer = new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl, failOnSnapshot); return transformer.transform(pomFile); }
[ "public", "Boolean", "invoke", "(", "File", "pomFile", ",", "VirtualChannel", "channel", ")", "throws", "IOException", ",", "InterruptedException", "{", "org", ".", "jfrog", ".", "build", ".", "extractor", ".", "maven", ".", "reader", ".", "ModuleName", "curre...
Performs the transformation. @return True if the file was modified.
[ "Performs", "the", "transformation", "." ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/release/maven/PomTransformer.java#L61-L77
eBay/parallec
src/main/java/io/parallec/core/task/ParallelTaskManager.java
ParallelTaskManager.removeTaskFromWaitQ
public synchronized boolean removeTaskFromWaitQ(ParallelTask taskTobeRemoved) { boolean removed = false; for (ParallelTask task : waitQ) { if (task.getTaskId() == taskTobeRemoved.getTaskId()) { task.setState(ParallelTaskState.COMPLETED_WITH_ERROR); task.getTaskErrorMetas().add( new TaskErrorMeta(TaskErrorType.USER_CANCELED, "NA")); logger.info( "task {} removed from wait q. This task has been marked as USER CANCELED.", task.getTaskId()); removed = true; } } return removed; }
java
public synchronized boolean removeTaskFromWaitQ(ParallelTask taskTobeRemoved) { boolean removed = false; for (ParallelTask task : waitQ) { if (task.getTaskId() == taskTobeRemoved.getTaskId()) { task.setState(ParallelTaskState.COMPLETED_WITH_ERROR); task.getTaskErrorMetas().add( new TaskErrorMeta(TaskErrorType.USER_CANCELED, "NA")); logger.info( "task {} removed from wait q. This task has been marked as USER CANCELED.", task.getTaskId()); removed = true; } } return removed; }
[ "public", "synchronized", "boolean", "removeTaskFromWaitQ", "(", "ParallelTask", "taskTobeRemoved", ")", "{", "boolean", "removed", "=", "false", ";", "for", "(", "ParallelTask", "task", ":", "waitQ", ")", "{", "if", "(", "task", ".", "getTaskId", "(", ")", ...
Removes the task from wait q. @param taskTobeRemoved the task tobe removed @return true, if successful
[ "Removes", "the", "task", "from", "wait", "q", "." ]
train
https://github.com/eBay/parallec/blob/1b4f1628f34fedfb06b24c33a5372d64d3df0952/src/main/java/io/parallec/core/task/ParallelTaskManager.java#L228-L244
NLPchina/elasticsearch-sql
src/main/java/org/nlpcn/es4sql/query/DefaultQueryAction.java
DefaultQueryAction.handleScriptField
private void handleScriptField(MethodField method) throws SqlParseException { List<KVValue> params = method.getParams(); if (params.size() == 2) { String f = params.get(0).value.toString(); fieldNames.add(f); request.addScriptField(f, new Script(params.get(1).value.toString())); } else if (params.size() == 3) { String f = params.get(0).value.toString(); fieldNames.add(f); request.addScriptField(f, new Script( ScriptType.INLINE, params.get(1).value.toString(), params.get(2).value.toString(), Collections.emptyMap() ) ); } else { throw new SqlParseException("scripted_field only allows script(name,script) or script(name,lang,script)"); } }
java
private void handleScriptField(MethodField method) throws SqlParseException { List<KVValue> params = method.getParams(); if (params.size() == 2) { String f = params.get(0).value.toString(); fieldNames.add(f); request.addScriptField(f, new Script(params.get(1).value.toString())); } else if (params.size() == 3) { String f = params.get(0).value.toString(); fieldNames.add(f); request.addScriptField(f, new Script( ScriptType.INLINE, params.get(1).value.toString(), params.get(2).value.toString(), Collections.emptyMap() ) ); } else { throw new SqlParseException("scripted_field only allows script(name,script) or script(name,lang,script)"); } }
[ "private", "void", "handleScriptField", "(", "MethodField", "method", ")", "throws", "SqlParseException", "{", "List", "<", "KVValue", ">", "params", "=", "method", ".", "getParams", "(", ")", ";", "if", "(", "params", ".", "size", "(", ")", "==", "2", "...
zhongshu-comment scripted_field only allows script(name,script) or script(name,lang,script) @param method @throws SqlParseException
[ "zhongshu", "-", "comment", "scripted_field", "only", "allows", "script", "(", "name", "script", ")", "or", "script", "(", "name", "lang", "script", ")" ]
train
https://github.com/NLPchina/elasticsearch-sql/blob/eaab70b4bf1729978911b83eb96e816ebcfe6e7f/src/main/java/org/nlpcn/es4sql/query/DefaultQueryAction.java#L166-L186
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/AsyncTableEntryReader.java
AsyncTableEntryReader.readEntryComponents
static DeserializedEntry readEntryComponents(InputStream input, long segmentOffset, EntrySerializer serializer) throws IOException { val h = serializer.readHeader(input); long version = getKeyVersion(h, segmentOffset); byte[] key = StreamHelpers.readAll(input, h.getKeyLength()); byte[] value = h.isDeletion() ? null : (h.getValueLength() == 0 ? new byte[0] : StreamHelpers.readAll(input, h.getValueLength())); return new DeserializedEntry(h, version, key, value); }
java
static DeserializedEntry readEntryComponents(InputStream input, long segmentOffset, EntrySerializer serializer) throws IOException { val h = serializer.readHeader(input); long version = getKeyVersion(h, segmentOffset); byte[] key = StreamHelpers.readAll(input, h.getKeyLength()); byte[] value = h.isDeletion() ? null : (h.getValueLength() == 0 ? new byte[0] : StreamHelpers.readAll(input, h.getValueLength())); return new DeserializedEntry(h, version, key, value); }
[ "static", "DeserializedEntry", "readEntryComponents", "(", "InputStream", "input", ",", "long", "segmentOffset", ",", "EntrySerializer", "serializer", ")", "throws", "IOException", "{", "val", "h", "=", "serializer", ".", "readHeader", "(", "input", ")", ";", "lon...
Reads a single {@link TableEntry} from the given InputStream. The {@link TableEntry} itself is not constructed, rather all of its components are returned individually. @param input An InputStream to read from. @param segmentOffset The Segment Offset that the first byte of the InputStream maps to. This wll be used as a Version, unless the deserialized segment's Header contains an explicit version. @param serializer The {@link EntrySerializer} to use for deserializing entries. @return A {@link DeserializedEntry} that contains all the components of the {@link TableEntry}. @throws IOException If an Exception occurred while reading from the given InputStream.
[ "Reads", "a", "single", "{", "@link", "TableEntry", "}", "from", "the", "given", "InputStream", ".", "The", "{", "@link", "TableEntry", "}", "itself", "is", "not", "constructed", "rather", "all", "of", "its", "components", "are", "returned", "individually", ...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/AsyncTableEntryReader.java#L120-L126
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/util/configuration/impl/ConfigurationAbstractImpl.java
ConfigurationAbstractImpl.getStrings
public String[] getStrings(String key, String defaultValue, String seperators) { StringTokenizer st = new StringTokenizer(getString(key, defaultValue), seperators); String[] ret = new String[st.countTokens()]; for (int i = 0; i < ret.length; i++) { ret[i] = st.nextToken(); } return ret; }
java
public String[] getStrings(String key, String defaultValue, String seperators) { StringTokenizer st = new StringTokenizer(getString(key, defaultValue), seperators); String[] ret = new String[st.countTokens()]; for (int i = 0; i < ret.length; i++) { ret[i] = st.nextToken(); } return ret; }
[ "public", "String", "[", "]", "getStrings", "(", "String", "key", ",", "String", "defaultValue", ",", "String", "seperators", ")", "{", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "getString", "(", "key", ",", "defaultValue", ")", ",", "sepe...
Gets an array of Strings from the value of the specified key, seperated by any key from <code>seperators</code>. If no value for this key is found the array contained in <code>defaultValue</code> is returned. @param key the key @param defaultValue the default Value @param seperators the seprators to be used @return the strings for the key, or the strings contained in <code>defaultValue</code> @see StringTokenizer
[ "Gets", "an", "array", "of", "Strings", "from", "the", "value", "of", "the", "specified", "key", "seperated", "by", "any", "key", "from", "<code", ">", "seperators<", "/", "code", ">", ".", "If", "no", "value", "for", "this", "key", "is", "found", "the...
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/configuration/impl/ConfigurationAbstractImpl.java#L112-L121
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updateRegexEntityRole
public OperationStatus updateRegexEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateRegexEntityRoleOptionalParameter updateRegexEntityRoleOptionalParameter) { return updateRegexEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateRegexEntityRoleOptionalParameter).toBlocking().single().body(); }
java
public OperationStatus updateRegexEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId, UpdateRegexEntityRoleOptionalParameter updateRegexEntityRoleOptionalParameter) { return updateRegexEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updateRegexEntityRoleOptionalParameter).toBlocking().single().body(); }
[ "public", "OperationStatus", "updateRegexEntityRole", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ",", "UpdateRegexEntityRoleOptionalParameter", "updateRegexEntityRoleOptionalParameter", ")", "{", "return", "updateRegexE...
Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updateRegexEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful.
[ "Update", "an", "entity", "role", "for", "a", "given", "entity", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L12051-L12053
alkacon/opencms-core
src-modules/org/opencms/workplace/explorer/CmsExplorer.java
CmsExplorer.folderExists
private boolean folderExists(CmsObject cms, String folder) { try { CmsFolder test = cms.readFolder(folder, CmsResourceFilter.IGNORE_EXPIRATION); if (test.isFile()) { return false; } return true; } catch (Exception e) { return false; } }
java
private boolean folderExists(CmsObject cms, String folder) { try { CmsFolder test = cms.readFolder(folder, CmsResourceFilter.IGNORE_EXPIRATION); if (test.isFile()) { return false; } return true; } catch (Exception e) { return false; } }
[ "private", "boolean", "folderExists", "(", "CmsObject", "cms", ",", "String", "folder", ")", "{", "try", "{", "CmsFolder", "test", "=", "cms", ".", "readFolder", "(", "folder", ",", "CmsResourceFilter", ".", "IGNORE_EXPIRATION", ")", ";", "if", "(", "test", ...
Checks if a folder with a given name exits in the VFS.<p> @param cms the current cms context @param folder the folder to check for @return true if the folder exists in the VFS
[ "Checks", "if", "a", "folder", "with", "a", "given", "name", "exits", "in", "the", "VFS", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/explorer/CmsExplorer.java#L805-L816
zaproxy/zaproxy
src/org/zaproxy/zap/extension/users/ExtensionUserManagement.java
ExtensionUserManagement.getContextPanel
private ContextUsersPanel getContextPanel(int contextId) { ContextUsersPanel panel = this.userPanelsMap.get(contextId); if (panel == null) { panel = new ContextUsersPanel(this, contextId); this.userPanelsMap.put(contextId, panel); } return panel; }
java
private ContextUsersPanel getContextPanel(int contextId) { ContextUsersPanel panel = this.userPanelsMap.get(contextId); if (panel == null) { panel = new ContextUsersPanel(this, contextId); this.userPanelsMap.put(contextId, panel); } return panel; }
[ "private", "ContextUsersPanel", "getContextPanel", "(", "int", "contextId", ")", "{", "ContextUsersPanel", "panel", "=", "this", ".", "userPanelsMap", ".", "get", "(", "contextId", ")", ";", "if", "(", "panel", "==", "null", ")", "{", "panel", "=", "new", ...
Gets the context panel for a given context. @param contextId the context id @return the context panel
[ "Gets", "the", "context", "panel", "for", "a", "given", "context", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/users/ExtensionUserManagement.java#L184-L191
brutusin/commons
src/main/java/org/brutusin/commons/utils/Miscellaneous.java
Miscellaneous.isSymlink
public static boolean isSymlink(File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); } if (File.separatorChar == '\\') { return false; } File fileInCanonicalDir; if (file.getParent() == null) { fileInCanonicalDir = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); fileInCanonicalDir = new File(canonicalDir, file.getName()); } return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile()); }
java
public static boolean isSymlink(File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); } if (File.separatorChar == '\\') { return false; } File fileInCanonicalDir; if (file.getParent() == null) { fileInCanonicalDir = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); fileInCanonicalDir = new File(canonicalDir, file.getName()); } return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile()); }
[ "public", "static", "boolean", "isSymlink", "(", "File", "file", ")", "throws", "IOException", "{", "if", "(", "file", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"File must not be null\"", ")", ";", "}", "if", "(", "File", ".", ...
Determines whether the specified file is a Symbolic Link rather than an actual file. <p> Will not return true if there is a Symbolic Link anywhere in the path, only if the specific file is. <p> <b>Note:</b> the current implementation always returns {@code false} if the system is detected as Windows. Copied from org.apache.commons.io.FileuUils @param file the file to check @return true if the file is a Symbolic Link @throws IOException if an IO error occurs while checking the file
[ "Determines", "whether", "the", "specified", "file", "is", "a", "Symbolic", "Link", "rather", "than", "an", "actual", "file", ".", "<p", ">", "Will", "not", "return", "true", "if", "there", "is", "a", "Symbolic", "Link", "anywhere", "in", "the", "path", ...
train
https://github.com/brutusin/commons/blob/70685df2b2456d0bf1e6a4754d72c87bba4949df/src/main/java/org/brutusin/commons/utils/Miscellaneous.java#L327-L343
samskivert/samskivert
src/main/java/com/samskivert/velocity/FormTool.java
FormTool.imageSubmit
public String imageSubmit (String name, String value, String imagePath) { return fixedInput("image", name, value, "src=\"" + imagePath + "\""); }
java
public String imageSubmit (String name, String value, String imagePath) { return fixedInput("image", name, value, "src=\"" + imagePath + "\""); }
[ "public", "String", "imageSubmit", "(", "String", "name", ",", "String", "value", ",", "String", "imagePath", ")", "{", "return", "fixedInput", "(", "\"image\"", ",", "name", ",", "value", ",", "\"src=\\\"\"", "+", "imagePath", "+", "\"\\\"\"", ")", ";", "...
Constructs a image submit element with the specified parameter name and image path.
[ "Constructs", "a", "image", "submit", "element", "with", "the", "specified", "parameter", "name", "and", "image", "path", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/FormTool.java#L194-L197
xwiki/xwiki-rendering
xwiki-rendering-macros/xwiki-rendering-macro-html/src/main/java/org/xwiki/rendering/internal/macro/html/HTMLMacro.java
HTMLMacro.renderWikiSyntax
private String renderWikiSyntax(String content, Transformation transformation, MacroTransformationContext context) throws MacroExecutionException { String xhtml; try { // Parse the wiki syntax XDOM xdom = this.contentParser.parse(content, context, false, false); // Force clean=false for sub HTML macro: // - at this point we don't know the context of the macro, it can be some <div> directly followed by the // html macro, it this case the macro will be parsed as inline block // - by forcing clean=false, we also make the html macro merge the whole html before cleaning so the cleaner // have the chole context and can clean better List<MacroBlock> macros = xdom.getBlocks(MACROBLOCKMATCHER, Axes.DESCENDANT); for (MacroBlock macro : macros) { if ("html".equals(macro.getId())) { macro.setParameter("clean", "false"); } } MacroBlock htmlMacroBlock = context.getCurrentMacroBlock(); MacroMarkerBlock htmlMacroMarker = new MacroMarkerBlock(htmlMacroBlock.getId(), htmlMacroBlock.getParameters(), htmlMacroBlock.getContent(), xdom.getChildren(), htmlMacroBlock.isInline()); // Make sure the context XDOM contains the html macro content htmlMacroBlock.getParent().replaceChild(htmlMacroMarker, htmlMacroBlock); try { // Execute the Macro transformation ((MutableRenderingContext) this.renderingContext).transformInContext(transformation, context.getTransformationContext(), htmlMacroMarker); } finally { // Restore context XDOM to its previous state htmlMacroMarker.getParent().replaceChild(htmlMacroBlock, htmlMacroMarker); } // Render the whole parsed content as a XHTML string WikiPrinter printer = new DefaultWikiPrinter(); PrintRenderer renderer = this.xhtmlRendererFactory.createRenderer(printer); for (Block block : htmlMacroMarker.getChildren()) { block.traverse(renderer); } xhtml = printer.toString(); } catch (Exception e) { throw new MacroExecutionException("Failed to parse content [" + content + "].", e); } return xhtml; }
java
private String renderWikiSyntax(String content, Transformation transformation, MacroTransformationContext context) throws MacroExecutionException { String xhtml; try { // Parse the wiki syntax XDOM xdom = this.contentParser.parse(content, context, false, false); // Force clean=false for sub HTML macro: // - at this point we don't know the context of the macro, it can be some <div> directly followed by the // html macro, it this case the macro will be parsed as inline block // - by forcing clean=false, we also make the html macro merge the whole html before cleaning so the cleaner // have the chole context and can clean better List<MacroBlock> macros = xdom.getBlocks(MACROBLOCKMATCHER, Axes.DESCENDANT); for (MacroBlock macro : macros) { if ("html".equals(macro.getId())) { macro.setParameter("clean", "false"); } } MacroBlock htmlMacroBlock = context.getCurrentMacroBlock(); MacroMarkerBlock htmlMacroMarker = new MacroMarkerBlock(htmlMacroBlock.getId(), htmlMacroBlock.getParameters(), htmlMacroBlock.getContent(), xdom.getChildren(), htmlMacroBlock.isInline()); // Make sure the context XDOM contains the html macro content htmlMacroBlock.getParent().replaceChild(htmlMacroMarker, htmlMacroBlock); try { // Execute the Macro transformation ((MutableRenderingContext) this.renderingContext).transformInContext(transformation, context.getTransformationContext(), htmlMacroMarker); } finally { // Restore context XDOM to its previous state htmlMacroMarker.getParent().replaceChild(htmlMacroBlock, htmlMacroMarker); } // Render the whole parsed content as a XHTML string WikiPrinter printer = new DefaultWikiPrinter(); PrintRenderer renderer = this.xhtmlRendererFactory.createRenderer(printer); for (Block block : htmlMacroMarker.getChildren()) { block.traverse(renderer); } xhtml = printer.toString(); } catch (Exception e) { throw new MacroExecutionException("Failed to parse content [" + content + "].", e); } return xhtml; }
[ "private", "String", "renderWikiSyntax", "(", "String", "content", ",", "Transformation", "transformation", ",", "MacroTransformationContext", "context", ")", "throws", "MacroExecutionException", "{", "String", "xhtml", ";", "try", "{", "// Parse the wiki syntax", "XDOM",...
Parse the passed context using a wiki syntax parser and render the result as an XHTML string. @param content the content to parse @param transformation the macro transformation to execute macros when wiki is set to true @param context the context of the macros transformation process @return the output XHTML as a string containing the XWiki Syntax resolved as XHTML @throws MacroExecutionException in case there's a parsing problem
[ "Parse", "the", "passed", "context", "using", "a", "wiki", "syntax", "parser", "and", "render", "the", "result", "as", "an", "XHTML", "string", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-macros/xwiki-rendering-macro-html/src/main/java/org/xwiki/rendering/internal/macro/html/HTMLMacro.java#L242-L295
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/TaskTracker.java
TaskTracker.getMaxActualSlots
int getMaxActualSlots(JobConf conf, int numCpuOnTT, TaskType type) { return getMaxSlots(conf, numCpuOnTT, type); }
java
int getMaxActualSlots(JobConf conf, int numCpuOnTT, TaskType type) { return getMaxSlots(conf, numCpuOnTT, type); }
[ "int", "getMaxActualSlots", "(", "JobConf", "conf", ",", "int", "numCpuOnTT", ",", "TaskType", "type", ")", "{", "return", "getMaxSlots", "(", "conf", ",", "numCpuOnTT", ",", "type", ")", ";", "}" ]
Get the actual max number of tasks. This may be different than get(Max|Reduce)CurrentMapTasks() since that is the number used for scheduling. This allows the CoronaTaskTracker to return the real number of resources available. @param conf Configuration to look for slots @param numCpuOnTT Number of cpus on TaskTracker @param type Type of slot @return Actual number of map tasks, not what the TaskLauncher thinks.
[ "Get", "the", "actual", "max", "number", "of", "tasks", ".", "This", "may", "be", "different", "than", "get", "(", "Max|Reduce", ")", "CurrentMapTasks", "()", "since", "that", "is", "the", "number", "used", "for", "scheduling", ".", "This", "allows", "the"...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskTracker.java#L4282-L4284
google/closure-compiler
src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java
DestructuringGlobalNameExtractor.replaceDestructuringAssignment
private static void replaceDestructuringAssignment(Node pattern, Node newLvalue, Node newRvalue) { Node parent = pattern.getParent(); if (parent.isAssign()) { Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent); parent.replaceWith(newAssign); } else if (newLvalue.isName()) { checkState(parent.isDestructuringLhs()); parent.replaceWith(newLvalue); newLvalue.addChildToBack(newRvalue); } else { pattern.getNext().detach(); pattern.detach(); parent.addChildToBack(newLvalue); parent.addChildToBack(newRvalue); } }
java
private static void replaceDestructuringAssignment(Node pattern, Node newLvalue, Node newRvalue) { Node parent = pattern.getParent(); if (parent.isAssign()) { Node newAssign = IR.assign(newLvalue, newRvalue).srcref(parent); parent.replaceWith(newAssign); } else if (newLvalue.isName()) { checkState(parent.isDestructuringLhs()); parent.replaceWith(newLvalue); newLvalue.addChildToBack(newRvalue); } else { pattern.getNext().detach(); pattern.detach(); parent.addChildToBack(newLvalue); parent.addChildToBack(newRvalue); } }
[ "private", "static", "void", "replaceDestructuringAssignment", "(", "Node", "pattern", ",", "Node", "newLvalue", ",", "Node", "newRvalue", ")", "{", "Node", "parent", "=", "pattern", ".", "getParent", "(", ")", ";", "if", "(", "parent", ".", "isAssign", "(",...
Replaces the given assignment or declaration with the new lvalue/rvalue @param pattern a destructuring pattern in an ASSIGN or VAR/LET/CONST
[ "Replaces", "the", "given", "assignment", "or", "declaration", "with", "the", "new", "lvalue", "/", "rvalue" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuringGlobalNameExtractor.java#L153-L168
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/sampling/ReservoirLongsSketch.java
ReservoirLongsSketch.estimateSubsetSum
public SampleSubsetSummary estimateSubsetSum(final Predicate<Long> predicate) { if (itemsSeen_ == 0) { return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0); } final long numSamples = getNumSamples(); final double samplingRate = numSamples / (double) itemsSeen_; assert samplingRate >= 0.0; assert samplingRate <= 1.0; int predTrueCount = 0; for (int i = 0; i < numSamples; ++i) { if (predicate.test(data_[i])) { ++predTrueCount; } } // if in exact mode, we can return an exact answer if (itemsSeen_ <= reservoirSize_) { return new SampleSubsetSummary(predTrueCount, predTrueCount, predTrueCount, numSamples); } final double lbTrueFraction = pseudoHypergeometricLBonP(numSamples, predTrueCount, samplingRate); final double estimatedTrueFraction = (1.0 * predTrueCount) / numSamples; final double ubTrueFraction = pseudoHypergeometricUBonP(numSamples, predTrueCount, samplingRate); return new SampleSubsetSummary( itemsSeen_ * lbTrueFraction, itemsSeen_ * estimatedTrueFraction, itemsSeen_ * ubTrueFraction, itemsSeen_); }
java
public SampleSubsetSummary estimateSubsetSum(final Predicate<Long> predicate) { if (itemsSeen_ == 0) { return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0); } final long numSamples = getNumSamples(); final double samplingRate = numSamples / (double) itemsSeen_; assert samplingRate >= 0.0; assert samplingRate <= 1.0; int predTrueCount = 0; for (int i = 0; i < numSamples; ++i) { if (predicate.test(data_[i])) { ++predTrueCount; } } // if in exact mode, we can return an exact answer if (itemsSeen_ <= reservoirSize_) { return new SampleSubsetSummary(predTrueCount, predTrueCount, predTrueCount, numSamples); } final double lbTrueFraction = pseudoHypergeometricLBonP(numSamples, predTrueCount, samplingRate); final double estimatedTrueFraction = (1.0 * predTrueCount) / numSamples; final double ubTrueFraction = pseudoHypergeometricUBonP(numSamples, predTrueCount, samplingRate); return new SampleSubsetSummary( itemsSeen_ * lbTrueFraction, itemsSeen_ * estimatedTrueFraction, itemsSeen_ * ubTrueFraction, itemsSeen_); }
[ "public", "SampleSubsetSummary", "estimateSubsetSum", "(", "final", "Predicate", "<", "Long", ">", "predicate", ")", "{", "if", "(", "itemsSeen_", "==", "0", ")", "{", "return", "new", "SampleSubsetSummary", "(", "0.0", ",", "0.0", ",", "0.0", ",", "0.0", ...
Computes an estimated subset sum from the entire stream for objects matching a given predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard deviations. <p>This is technically a heuristic method, and tries to err on the conservative side.</p> @param predicate A predicate to use when identifying items. @return A summary object containing the estimate, upper and lower bounds, and the total sketch weight.
[ "Computes", "an", "estimated", "subset", "sum", "from", "the", "entire", "stream", "for", "objects", "matching", "a", "given", "predicate", ".", "Provides", "a", "lower", "bound", "estimate", "and", "upper", "bound", "using", "a", "target", "of", "2", "stand...
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/ReservoirLongsSketch.java#L428-L458
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/VariablesInner.java
VariablesInner.get
public VariableInner get(String resourceGroupName, String automationAccountName, String variableName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, variableName).toBlocking().single().body(); }
java
public VariableInner get(String resourceGroupName, String automationAccountName, String variableName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, variableName).toBlocking().single().body(); }
[ "public", "VariableInner", "get", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "variableName", ")", "{", "return", "getWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "variableName", ")"...
Retrieve the variable identified by variable name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param variableName The name of variable. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VariableInner object if successful.
[ "Retrieve", "the", "variable", "identified", "by", "variable", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/VariablesInner.java#L393-L395
googleapis/google-cloud-java
google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java
ExternalTableDefinition.newBuilder
public static Builder newBuilder(String sourceUri, Schema schema, FormatOptions format) { return newBuilder(ImmutableList.of(sourceUri), schema, format); }
java
public static Builder newBuilder(String sourceUri, Schema schema, FormatOptions format) { return newBuilder(ImmutableList.of(sourceUri), schema, format); }
[ "public", "static", "Builder", "newBuilder", "(", "String", "sourceUri", ",", "Schema", "schema", ",", "FormatOptions", "format", ")", "{", "return", "newBuilder", "(", "ImmutableList", ".", "of", "(", "sourceUri", ")", ",", "schema", ",", "format", ")", ";"...
Creates a builder for an ExternalTableDefinition object. @param sourceUri a fully-qualified URI that points to your data in Google Cloud Storage. The URI can contain one '*' wildcard character that must come after the bucket's name. Size limits related to load jobs apply to external data sources. @param schema the schema for the external data @param format the source format of the external data @return a builder for an ExternalTableDefinition object given source URI, schema and format @see <a href="https://cloud.google.com/bigquery/loading-data-into-bigquery#quota">Quota</a> @see <a href="https://cloud.google.com/bigquery/docs/reference/v2/tables#externalDataConfiguration.sourceFormat"> Source Format</a>
[ "Creates", "a", "builder", "for", "an", "ExternalTableDefinition", "object", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java#L297-L299
WileyLabs/teasy
src/main/java/com/wiley/elements/conditions/TeasyExpectedConditions.java
TeasyExpectedConditions.visibilityOfFirstElements
public static ExpectedCondition<List<WebElement>> visibilityOfFirstElements(final By locator) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(final WebDriver driver) { return getFirstVisibleWebElements(driver, null, locator); } @Override public String toString() { return String.format("visibility of element located by %s", locator); } }; }
java
public static ExpectedCondition<List<WebElement>> visibilityOfFirstElements(final By locator) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(final WebDriver driver) { return getFirstVisibleWebElements(driver, null, locator); } @Override public String toString() { return String.format("visibility of element located by %s", locator); } }; }
[ "public", "static", "ExpectedCondition", "<", "List", "<", "WebElement", ">", ">", "visibilityOfFirstElements", "(", "final", "By", "locator", ")", "{", "return", "new", "ExpectedCondition", "<", "List", "<", "WebElement", ">", ">", "(", ")", "{", "@", "Over...
Expected condition to look for elements in frames that will return as soon as elements are found in any frame @param locator @return
[ "Expected", "condition", "to", "look", "for", "elements", "in", "frames", "that", "will", "return", "as", "soon", "as", "elements", "are", "found", "in", "any", "frame" ]
train
https://github.com/WileyLabs/teasy/blob/94489ac8e6a6680b52dfa6cdbc9d8535333bef42/src/main/java/com/wiley/elements/conditions/TeasyExpectedConditions.java#L145-L157
pressgang-ccms/PressGangCCMSContentSpec
src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java
EntityUtilities.getTopicRevisionsById
public static RevisionList getTopicRevisionsById(final TopicProvider topicProvider, final Integer csId) { final List<Revision> results = new ArrayList<Revision>(); CollectionWrapper<TopicWrapper> topicRevisions = topicProvider.getTopic(csId).getRevisions(); // Create the unique array from the revisions if (topicRevisions != null && topicRevisions.getItems() != null) { final List<TopicWrapper> topicRevs = topicRevisions.getItems(); for (final TopicWrapper topicRev : topicRevs) { Revision revision = new Revision(); revision.setRevision(topicRev.getRevision()); revision.setDate(topicRev.getLastModified()); results.add(revision); } Collections.sort(results, new EnversRevisionSort()); return new RevisionList(csId, "Topic", results); } else { return null; } }
java
public static RevisionList getTopicRevisionsById(final TopicProvider topicProvider, final Integer csId) { final List<Revision> results = new ArrayList<Revision>(); CollectionWrapper<TopicWrapper> topicRevisions = topicProvider.getTopic(csId).getRevisions(); // Create the unique array from the revisions if (topicRevisions != null && topicRevisions.getItems() != null) { final List<TopicWrapper> topicRevs = topicRevisions.getItems(); for (final TopicWrapper topicRev : topicRevs) { Revision revision = new Revision(); revision.setRevision(topicRev.getRevision()); revision.setDate(topicRev.getLastModified()); results.add(revision); } Collections.sort(results, new EnversRevisionSort()); return new RevisionList(csId, "Topic", results); } else { return null; } }
[ "public", "static", "RevisionList", "getTopicRevisionsById", "(", "final", "TopicProvider", "topicProvider", ",", "final", "Integer", "csId", ")", "{", "final", "List", "<", "Revision", ">", "results", "=", "new", "ArrayList", "<", "Revision", ">", "(", ")", "...
/* Gets a list of Revision's from the CSProcessor database for a specific content spec
[ "/", "*", "Gets", "a", "list", "of", "Revision", "s", "from", "the", "CSProcessor", "database", "for", "a", "specific", "content", "spec" ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/EntityUtilities.java#L319-L339
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java
SparkUtils.readStringFromFile
public static String readStringFromFile(String path, SparkContext sc) throws IOException { FileSystem fileSystem = FileSystem.get(sc.hadoopConfiguration()); try (BufferedInputStream bis = new BufferedInputStream(fileSystem.open(new Path(path)))) { byte[] asBytes = IOUtils.toByteArray(bis); return new String(asBytes, "UTF-8"); } }
java
public static String readStringFromFile(String path, SparkContext sc) throws IOException { FileSystem fileSystem = FileSystem.get(sc.hadoopConfiguration()); try (BufferedInputStream bis = new BufferedInputStream(fileSystem.open(new Path(path)))) { byte[] asBytes = IOUtils.toByteArray(bis); return new String(asBytes, "UTF-8"); } }
[ "public", "static", "String", "readStringFromFile", "(", "String", "path", ",", "SparkContext", "sc", ")", "throws", "IOException", "{", "FileSystem", "fileSystem", "=", "FileSystem", ".", "get", "(", "sc", ".", "hadoopConfiguration", "(", ")", ")", ";", "try"...
Read a UTF-8 format String from HDFS (or local) @param path Path to write the string @param sc Spark context
[ "Read", "a", "UTF", "-", "8", "format", "String", "from", "HDFS", "(", "or", "local", ")" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/util/SparkUtils.java#L180-L186
akarnokd/akarnokd-xml
src/main/java/hu/akarnokd/xml/XNElement.java
XNElement.getLong
public long getLong(String attribute, String namespace, long defaultValue) { String value = get(attribute, namespace); if (value == null) { return defaultValue; } return Long.parseLong(value); }
java
public long getLong(String attribute, String namespace, long defaultValue) { String value = get(attribute, namespace); if (value == null) { return defaultValue; } return Long.parseLong(value); }
[ "public", "long", "getLong", "(", "String", "attribute", ",", "String", "namespace", ",", "long", "defaultValue", ")", "{", "String", "value", "=", "get", "(", "attribute", ",", "namespace", ")", ";", "if", "(", "value", "==", "null", ")", "{", "return",...
Retrieve an integer attribute or the default value if not exists. @param attribute the attribute name @param namespace the attribute namespace URI @param defaultValue the default value to return @return the value
[ "Retrieve", "an", "integer", "attribute", "or", "the", "default", "value", "if", "not", "exists", "." ]
train
https://github.com/akarnokd/akarnokd-xml/blob/57466a5a9cb455a13d7121557c165287b31ee870/src/main/java/hu/akarnokd/xml/XNElement.java#L882-L888
dhemery/hartley
src/main/java/com/dhemery/expressing/ImmediateExpressions.java
ImmediateExpressions.assertThat
public static <S> void assertThat(S subject, Feature<? super S,Boolean> feature) { assertThat(subject, feature, isQuietlyTrue()); }
java
public static <S> void assertThat(S subject, Feature<? super S,Boolean> feature) { assertThat(subject, feature, isQuietlyTrue()); }
[ "public", "static", "<", "S", ">", "void", "assertThat", "(", "S", "subject", ",", "Feature", "<", "?", "super", "S", ",", "Boolean", ">", "feature", ")", "{", "assertThat", "(", "subject", ",", "feature", ",", "isQuietlyTrue", "(", ")", ")", ";", "}...
Assert that a sample of the feature is {@code true}. <p>Example:</p> <pre> {@code Page settingsPage = ...; Feature<Page,Boolean> displayed() { ... } ... assertThat(settingsPage, is(displayed())); }
[ "Assert", "that", "a", "sample", "of", "the", "feature", "is", "{", "@code", "true", "}", ".", "<p", ">", "Example", ":", "<", "/", "p", ">", "<pre", ">", "{", "@code" ]
train
https://github.com/dhemery/hartley/blob/7754bd6bc12695f2249601b8890da530a61fcf33/src/main/java/com/dhemery/expressing/ImmediateExpressions.java#L96-L98
jayantk/jklol
src/com/jayantkrish/jklol/inference/JunctionTree.java
JunctionTree.cliqueTreeToMaxMarginalSet
private static MaxMarginalSet cliqueTreeToMaxMarginalSet(CliqueTree cliqueTree, FactorGraph originalFactorGraph) { for (int i = 0; i < cliqueTree.numFactors(); i++) { computeMarginal(cliqueTree, i, false); } return new FactorMaxMarginalSet(cliqueTree, originalFactorGraph.getConditionedValues()); }
java
private static MaxMarginalSet cliqueTreeToMaxMarginalSet(CliqueTree cliqueTree, FactorGraph originalFactorGraph) { for (int i = 0; i < cliqueTree.numFactors(); i++) { computeMarginal(cliqueTree, i, false); } return new FactorMaxMarginalSet(cliqueTree, originalFactorGraph.getConditionedValues()); }
[ "private", "static", "MaxMarginalSet", "cliqueTreeToMaxMarginalSet", "(", "CliqueTree", "cliqueTree", ",", "FactorGraph", "originalFactorGraph", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cliqueTree", ".", "numFactors", "(", ")", ";", "i", "++...
Retrieves max marginals from the given clique tree. @param cliqueTree @param rootFactorNum @return
[ "Retrieves", "max", "marginals", "from", "the", "given", "clique", "tree", "." ]
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/inference/JunctionTree.java#L309-L315
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemTemplateElement.java
ElemTemplateElement.excludeResultNSDecl
private boolean excludeResultNSDecl(String prefix, String uri) throws TransformerException { if (uri != null) { if (uri.equals(Constants.S_XSLNAMESPACEURL) || getStylesheet().containsExtensionElementURI(uri)) return true; if (containsExcludeResultPrefix(prefix, uri)) return true; } return false; }
java
private boolean excludeResultNSDecl(String prefix, String uri) throws TransformerException { if (uri != null) { if (uri.equals(Constants.S_XSLNAMESPACEURL) || getStylesheet().containsExtensionElementURI(uri)) return true; if (containsExcludeResultPrefix(prefix, uri)) return true; } return false; }
[ "private", "boolean", "excludeResultNSDecl", "(", "String", "prefix", ",", "String", "uri", ")", "throws", "TransformerException", "{", "if", "(", "uri", "!=", "null", ")", "{", "if", "(", "uri", ".", "equals", "(", "Constants", ".", "S_XSLNAMESPACEURL", ")"...
Tell if the result namespace decl should be excluded. Should be called before namespace aliasing (I think). @param prefix non-null reference to prefix. @param uri reference to namespace that prefix maps to, which is protected for null, but should really never be passed as null. @return true if the given namespace should be excluded. @throws TransformerException
[ "Tell", "if", "the", "result", "namespace", "decl", "should", "be", "excluded", ".", "Should", "be", "called", "before", "namespace", "aliasing", "(", "I", "think", ")", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/ElemTemplateElement.java#L1001-L1016
FINRAOS/DataGenerator
dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java
SocialNetworkUtilities.getDistanceBetweenCoordinates
public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1._1() - point2._1(); Double yDiff = point1._2() - point2._2(); return Math.sqrt(xDiff * xDiff + yDiff * yDiff); }
java
public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1._1() - point2._1(); Double yDiff = point1._2() - point2._2(); return Math.sqrt(xDiff * xDiff + yDiff * yDiff); }
[ "public", "static", "Double", "getDistanceBetweenCoordinates", "(", "Tuple2", "<", "Double", ",", "Double", ">", "point1", ",", "Tuple2", "<", "Double", ",", "Double", ">", "point2", ")", "{", "// sqrt( (x2-x1)^2 + (y2-y2)^2 )\r", "Double", "xDiff", "=", "point1",...
Get distance between geographical coordinates @param point1 Point1 @param point2 Point2 @return Distance (double)
[ "Get", "distance", "between", "geographical", "coordinates" ]
train
https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-common/src/main/java/org/finra/datagenerator/common/SocialNetwork_Example_Java/SocialNetworkUtilities.java#L60-L65
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java
AbstractFlagEncoder.setSpeed
protected void setSpeed(boolean reverse, IntsRef edgeFlags, double speed) { if (speed < 0 || Double.isNaN(speed)) throw new IllegalArgumentException("Speed cannot be negative or NaN: " + speed + ", flags:" + BitUtil.LITTLE.toBitString(edgeFlags)); if (speed < speedFactor / 2) { speedEncoder.setDecimal(reverse, edgeFlags, 0); accessEnc.setBool(reverse, edgeFlags, false); return; } if (speed > getMaxSpeed()) speed = getMaxSpeed(); speedEncoder.setDecimal(reverse, edgeFlags, speed); }
java
protected void setSpeed(boolean reverse, IntsRef edgeFlags, double speed) { if (speed < 0 || Double.isNaN(speed)) throw new IllegalArgumentException("Speed cannot be negative or NaN: " + speed + ", flags:" + BitUtil.LITTLE.toBitString(edgeFlags)); if (speed < speedFactor / 2) { speedEncoder.setDecimal(reverse, edgeFlags, 0); accessEnc.setBool(reverse, edgeFlags, false); return; } if (speed > getMaxSpeed()) speed = getMaxSpeed(); speedEncoder.setDecimal(reverse, edgeFlags, speed); }
[ "protected", "void", "setSpeed", "(", "boolean", "reverse", ",", "IntsRef", "edgeFlags", ",", "double", "speed", ")", "{", "if", "(", "speed", "<", "0", "||", "Double", ".", "isNaN", "(", "speed", ")", ")", "throw", "new", "IllegalArgumentException", "(", ...
Most use cases do not require this method. Will still keep it accessible so that one can disable it until the averageSpeedEncodedValue is moved out of the FlagEncoder. @Deprecated
[ "Most", "use", "cases", "do", "not", "require", "this", "method", ".", "Will", "still", "keep", "it", "accessible", "so", "that", "one", "can", "disable", "it", "until", "the", "averageSpeedEncodedValue", "is", "moved", "out", "of", "the", "FlagEncoder", "."...
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/routing/util/AbstractFlagEncoder.java#L540-L554
lucee/Lucee
core/src/main/java/lucee/commons/io/compress/CompressUtil.java
CompressUtil._compressBZip2
private static void _compressBZip2(InputStream source, OutputStream target) throws IOException { InputStream is = IOUtil.toBufferedInputStream(source); OutputStream os = new BZip2CompressorOutputStream(IOUtil.toBufferedOutputStream(target)); IOUtil.copy(is, os, true, true); }
java
private static void _compressBZip2(InputStream source, OutputStream target) throws IOException { InputStream is = IOUtil.toBufferedInputStream(source); OutputStream os = new BZip2CompressorOutputStream(IOUtil.toBufferedOutputStream(target)); IOUtil.copy(is, os, true, true); }
[ "private", "static", "void", "_compressBZip2", "(", "InputStream", "source", ",", "OutputStream", "target", ")", "throws", "IOException", "{", "InputStream", "is", "=", "IOUtil", ".", "toBufferedInputStream", "(", "source", ")", ";", "OutputStream", "os", "=", "...
compress a source file to a bzip2 file @param source @param target @throws IOException
[ "compress", "a", "source", "file", "to", "a", "bzip2", "file" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/io/compress/CompressUtil.java#L468-L473
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Uris.java
Uris.createUri
public static URI createUri(final String url, final boolean strict) { try { return newUri(url, strict); } catch (URISyntaxException e) { throw new AssertionError("Error creating URI: " + e.getMessage()); } }
java
public static URI createUri(final String url, final boolean strict) { try { return newUri(url, strict); } catch (URISyntaxException e) { throw new AssertionError("Error creating URI: " + e.getMessage()); } }
[ "public", "static", "URI", "createUri", "(", "final", "String", "url", ",", "final", "boolean", "strict", ")", "{", "try", "{", "return", "newUri", "(", "url", ",", "strict", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "n...
Creates a new URI based off the given string. This function differs from newUri in that it throws an AssertionError instead of a URISyntaxException - so it is suitable for use in static locations as long as you can be sure it is a valid string that is being parsed. @param url the string to parse @param strict whether or not to perform strict escaping. (defaults to false) @return the parsed, normalized URI
[ "Creates", "a", "new", "URI", "based", "off", "the", "given", "string", ".", "This", "function", "differs", "from", "newUri", "in", "that", "it", "throws", "an", "AssertionError", "instead", "of", "a", "URISyntaxException", "-", "so", "it", "is", "suitable",...
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/thirdparty/Uris.java#L514-L520
codelibs/jcifs
src/main/java/jcifs/smb1/smb1/SmbFile.java
SmbFile.getShareSecurity
public ACE[] getShareSecurity(boolean resolveSids) throws IOException { String p = url.getPath(); MsrpcShareGetInfo rpc; DcerpcHandle handle; ACE[] aces; resolveDfs(null); String server = getServerWithDfs(); rpc = new MsrpcShareGetInfo(server, tree.share); handle = DcerpcHandle.getHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", auth); try { handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); aces = rpc.getSecurity(); if (aces != null) processAces(aces, resolveSids); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 1) ioe.printStackTrace(log); } } return aces; }
java
public ACE[] getShareSecurity(boolean resolveSids) throws IOException { String p = url.getPath(); MsrpcShareGetInfo rpc; DcerpcHandle handle; ACE[] aces; resolveDfs(null); String server = getServerWithDfs(); rpc = new MsrpcShareGetInfo(server, tree.share); handle = DcerpcHandle.getHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", auth); try { handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); aces = rpc.getSecurity(); if (aces != null) processAces(aces, resolveSids); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 1) ioe.printStackTrace(log); } } return aces; }
[ "public", "ACE", "[", "]", "getShareSecurity", "(", "boolean", "resolveSids", ")", "throws", "IOException", "{", "String", "p", "=", "url", ".", "getPath", "(", ")", ";", "MsrpcShareGetInfo", "rpc", ";", "DcerpcHandle", "handle", ";", "ACE", "[", "]", "ace...
Return an array of Access Control Entry (ACE) objects representing the share permissions on the share exporting this file or directory. If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. <p> Note that this is different from calling <tt>getSecurity</tt> on a share. There are actually two different ACLs for shares - the ACL on the share and the ACL on the folder being shared. Go to <i>Computer Management</i> &gt; <i>System Tools</i> &gt; <i>Shared Folders</i> &gt <i>Shares</i> and look at the <i>Properties</i> for a share. You will see two tabs - one for "Share Permissions" and another for "Security". These correspond to the ACLs returned by <tt>getShareSecurity</tt> and <tt>getSecurity</tt> respectively. @param resolveSids Attempt to resolve the SIDs within each ACE form their numeric representation to their corresponding account names.
[ "Return", "an", "array", "of", "Access", "Control", "Entry", "(", "ACE", ")", "objects", "representing", "the", "share", "permissions", "on", "the", "share", "exporting", "this", "file", "or", "directory", ".", "If", "no", "DACL", "is", "present", "null", ...
train
https://github.com/codelibs/jcifs/blob/ac6a8ba2925648ae003ca2508aec32316065dc34/src/main/java/jcifs/smb1/smb1/SmbFile.java#L2938-L2967
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/proxy/ObjectProxy.java
ObjectProxy.executeMethod
public static Object executeMethod(Object object, MethodCallFact methodCallFact) throws Exception { if (object == null) throw new RequiredException("object"); if (methodCallFact == null) throw new RequiredException("methodCallFact"); return executeMethod(object, methodCallFact.getMethodName(),methodCallFact.getArguments()); }
java
public static Object executeMethod(Object object, MethodCallFact methodCallFact) throws Exception { if (object == null) throw new RequiredException("object"); if (methodCallFact == null) throw new RequiredException("methodCallFact"); return executeMethod(object, methodCallFact.getMethodName(),methodCallFact.getArguments()); }
[ "public", "static", "Object", "executeMethod", "(", "Object", "object", ",", "MethodCallFact", "methodCallFact", ")", "throws", "Exception", "{", "if", "(", "object", "==", "null", ")", "throw", "new", "RequiredException", "(", "\"object\"", ")", ";", "if", "(...
Execute the method call on a object @param object the target object that contains the method @param methodCallFact the method call information @return the return object of the method call @throws Exception
[ "Execute", "the", "method", "call", "on", "a", "object" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/proxy/ObjectProxy.java#L23-L33
voldemort/voldemort
src/java/voldemort/server/VoldemortConfig.java
VoldemortConfig.getDynamicDefaults
private Props getDynamicDefaults(Props userSuppliedConfig) { // Combined set of configs made up of user supplied configs first, while falling back // on statically defined defaults when the value is missing from the user supplied ones. Props combinedConfigs = new Props(userSuppliedConfig, defaultConfig); // Set of dynamic configs which depend on the combined configs in order to be determined. Props dynamicDefaults = new Props(); initializeNodeId(combinedConfigs, dynamicDefaults); // Define various paths String defaultDataDirectory = combinedConfigs.getString(VOLDEMORT_HOME) + File.separator + "data"; String dataDirectory = combinedConfigs.getString(DATA_DIRECTORY, defaultDataDirectory); dynamicDefaults.put(DATA_DIRECTORY, dataDirectory); dynamicDefaults.put(BDB_DATA_DIRECTORY, dataDirectory + File.separator + "bdb"); dynamicDefaults.put(READONLY_DATA_DIRECTORY, dataDirectory + File.separator + "read-only"); dynamicDefaults.put(ROCKSDB_DATA_DIR, dataDirectory + File.separator + "rocksdb"); String metadataDirectory = combinedConfigs.getString(VOLDEMORT_HOME) + File.separator + "config"; dynamicDefaults.put(METADATA_DIRECTORY, metadataDirectory); dynamicDefaults.put(READONLY_KEYTAB_PATH, metadataDirectory + File.separator + "voldemrt.headless.keytab"); dynamicDefaults.put(READONLY_HADOOP_CONFIG_PATH, metadataDirectory + File.separator + "hadoop-conf"); // Other "transitive" config values. dynamicDefaults.put(CORE_THREADS, Math.max(1, combinedConfigs.getInt(MAX_THREADS) / 2)); dynamicDefaults.put(ADMIN_CORE_THREADS, Math.max(1, combinedConfigs.getInt(ADMIN_MAX_THREADS) / 2)); dynamicDefaults.put(CLIENT_ROUTING_GET_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS)); dynamicDefaults.put(CLIENT_ROUTING_GETALL_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS)); int clientRoutingPutTimeoutMs = combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS); dynamicDefaults.put(CLIENT_ROUTING_PUT_TIMEOUT_MS, clientRoutingPutTimeoutMs); dynamicDefaults.put(CLIENT_ROUTING_GETVERSIONS_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_PUT_TIMEOUT_MS, clientRoutingPutTimeoutMs)); dynamicDefaults.put(CLIENT_ROUTING_DELETE_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS)); dynamicDefaults.put(FAILUREDETECTOR_REQUEST_LENGTH_THRESHOLD, combinedConfigs.getInt(SOCKET_TIMEOUT_MS)); dynamicDefaults.put(REST_SERVICE_STORAGE_THREAD_POOL_QUEUE_SIZE, combinedConfigs.getInt(NUM_REST_SERVICE_STORAGE_THREADS)); // We're changing the property from "client.node.bannage.ms" to // "failuredetector.bannage.period" so if we have the old one, migrate it over. if(userSuppliedConfig.containsKey(CLIENT_NODE_BANNAGE_MS) && !userSuppliedConfig.containsKey(FAILUREDETECTOR_BANNAGE_PERIOD)) { dynamicDefaults.put(FAILUREDETECTOR_BANNAGE_PERIOD, userSuppliedConfig.getInt(CLIENT_NODE_BANNAGE_MS)); } return dynamicDefaults; }
java
private Props getDynamicDefaults(Props userSuppliedConfig) { // Combined set of configs made up of user supplied configs first, while falling back // on statically defined defaults when the value is missing from the user supplied ones. Props combinedConfigs = new Props(userSuppliedConfig, defaultConfig); // Set of dynamic configs which depend on the combined configs in order to be determined. Props dynamicDefaults = new Props(); initializeNodeId(combinedConfigs, dynamicDefaults); // Define various paths String defaultDataDirectory = combinedConfigs.getString(VOLDEMORT_HOME) + File.separator + "data"; String dataDirectory = combinedConfigs.getString(DATA_DIRECTORY, defaultDataDirectory); dynamicDefaults.put(DATA_DIRECTORY, dataDirectory); dynamicDefaults.put(BDB_DATA_DIRECTORY, dataDirectory + File.separator + "bdb"); dynamicDefaults.put(READONLY_DATA_DIRECTORY, dataDirectory + File.separator + "read-only"); dynamicDefaults.put(ROCKSDB_DATA_DIR, dataDirectory + File.separator + "rocksdb"); String metadataDirectory = combinedConfigs.getString(VOLDEMORT_HOME) + File.separator + "config"; dynamicDefaults.put(METADATA_DIRECTORY, metadataDirectory); dynamicDefaults.put(READONLY_KEYTAB_PATH, metadataDirectory + File.separator + "voldemrt.headless.keytab"); dynamicDefaults.put(READONLY_HADOOP_CONFIG_PATH, metadataDirectory + File.separator + "hadoop-conf"); // Other "transitive" config values. dynamicDefaults.put(CORE_THREADS, Math.max(1, combinedConfigs.getInt(MAX_THREADS) / 2)); dynamicDefaults.put(ADMIN_CORE_THREADS, Math.max(1, combinedConfigs.getInt(ADMIN_MAX_THREADS) / 2)); dynamicDefaults.put(CLIENT_ROUTING_GET_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS)); dynamicDefaults.put(CLIENT_ROUTING_GETALL_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS)); int clientRoutingPutTimeoutMs = combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS); dynamicDefaults.put(CLIENT_ROUTING_PUT_TIMEOUT_MS, clientRoutingPutTimeoutMs); dynamicDefaults.put(CLIENT_ROUTING_GETVERSIONS_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_PUT_TIMEOUT_MS, clientRoutingPutTimeoutMs)); dynamicDefaults.put(CLIENT_ROUTING_DELETE_TIMEOUT_MS, combinedConfigs.getInt(CLIENT_ROUTING_TIMEOUT_MS)); dynamicDefaults.put(FAILUREDETECTOR_REQUEST_LENGTH_THRESHOLD, combinedConfigs.getInt(SOCKET_TIMEOUT_MS)); dynamicDefaults.put(REST_SERVICE_STORAGE_THREAD_POOL_QUEUE_SIZE, combinedConfigs.getInt(NUM_REST_SERVICE_STORAGE_THREADS)); // We're changing the property from "client.node.bannage.ms" to // "failuredetector.bannage.period" so if we have the old one, migrate it over. if(userSuppliedConfig.containsKey(CLIENT_NODE_BANNAGE_MS) && !userSuppliedConfig.containsKey(FAILUREDETECTOR_BANNAGE_PERIOD)) { dynamicDefaults.put(FAILUREDETECTOR_BANNAGE_PERIOD, userSuppliedConfig.getInt(CLIENT_NODE_BANNAGE_MS)); } return dynamicDefaults; }
[ "private", "Props", "getDynamicDefaults", "(", "Props", "userSuppliedConfig", ")", "{", "// Combined set of configs made up of user supplied configs first, while falling back", "// on statically defined defaults when the value is missing from the user supplied ones.", "Props", "combinedConfigs...
This function returns a set of default configs which cannot be defined statically, because they (at least potentially) depend on the config values provided by the user.
[ "This", "function", "returns", "a", "set", "of", "default", "configs", "which", "cannot", "be", "defined", "statically", "because", "they", "(", "at", "least", "potentially", ")", "depend", "on", "the", "config", "values", "provided", "by", "the", "user", "....
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/server/VoldemortConfig.java#L761-L803
molgenis/molgenis
molgenis-js/src/main/java/org/molgenis/js/magma/JsMagmaScriptEvaluator.java
JsMagmaScriptEvaluator.toScriptEngineValueMap
private Object toScriptEngineValueMap(Entity entity, int depth) { if (entity != null) { Object idValue = toScriptEngineValue(entity, entity.getEntityType().getIdAttribute(), 0); if (depth == 0) { return idValue; } else { Map<String, Object> map = Maps.newHashMap(); entity .getEntityType() .getAtomicAttributes() .forEach(attr -> map.put(attr.getName(), toScriptEngineValue(entity, attr, depth))); map.put(KEY_ID_VALUE, idValue); return map; } } else { return null; } }
java
private Object toScriptEngineValueMap(Entity entity, int depth) { if (entity != null) { Object idValue = toScriptEngineValue(entity, entity.getEntityType().getIdAttribute(), 0); if (depth == 0) { return idValue; } else { Map<String, Object> map = Maps.newHashMap(); entity .getEntityType() .getAtomicAttributes() .forEach(attr -> map.put(attr.getName(), toScriptEngineValue(entity, attr, depth))); map.put(KEY_ID_VALUE, idValue); return map; } } else { return null; } }
[ "private", "Object", "toScriptEngineValueMap", "(", "Entity", "entity", ",", "int", "depth", ")", "{", "if", "(", "entity", "!=", "null", ")", "{", "Object", "idValue", "=", "toScriptEngineValue", "(", "entity", ",", "entity", ".", "getEntityType", "(", ")",...
Convert entity to a JavaScript object. Adds "_idValue" as a special key to every level for quick access to the id value of an entity. @param entity The entity to be flattened, should start with non null entity @param depth Represents the number of reference levels being added to the JavaScript object @return A JavaScript object in Tree form, containing entities and there references
[ "Convert", "entity", "to", "a", "JavaScript", "object", ".", "Adds", "_idValue", "as", "a", "special", "key", "to", "every", "level", "for", "quick", "access", "to", "the", "id", "value", "of", "an", "entity", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-js/src/main/java/org/molgenis/js/magma/JsMagmaScriptEvaluator.java#L149-L166
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/ZookeeperBasedJobLock.java
ZookeeperBasedJobLock.tryLock
@Override public boolean tryLock() throws JobLockException { try { return this.lock.acquire(lockAcquireTimeoutMilliseconds, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new JobLockException("Failed to acquire lock " + this.lockPath, e); } }
java
@Override public boolean tryLock() throws JobLockException { try { return this.lock.acquire(lockAcquireTimeoutMilliseconds, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new JobLockException("Failed to acquire lock " + this.lockPath, e); } }
[ "@", "Override", "public", "boolean", "tryLock", "(", ")", "throws", "JobLockException", "{", "try", "{", "return", "this", ".", "lock", ".", "acquire", "(", "lockAcquireTimeoutMilliseconds", ",", "TimeUnit", ".", "MILLISECONDS", ")", ";", "}", "catch", "(", ...
Try locking the lock. @return <em>true</em> if the lock is successfully locked, <em>false</em> if otherwise. @throws IOException
[ "Try", "locking", "the", "lock", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/ZookeeperBasedJobLock.java#L128-L135
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/function/Actions.java
Actions.toFunc
public static <T1, T2, T3, T4, T5> Func5<T1, T2, T3, T4, T5, Void> toFunc( final Action5<T1, T2, T3, T4, T5> action) { return toFunc(action, (Void) null); }
java
public static <T1, T2, T3, T4, T5> Func5<T1, T2, T3, T4, T5, Void> toFunc( final Action5<T1, T2, T3, T4, T5> action) { return toFunc(action, (Void) null); }
[ "public", "static", "<", "T1", ",", "T2", ",", "T3", ",", "T4", ",", "T5", ">", "Func5", "<", "T1", ",", "T2", ",", "T3", ",", "T4", ",", "T5", ",", "Void", ">", "toFunc", "(", "final", "Action5", "<", "T1", ",", "T2", ",", "T3", ",", "T4",...
Converts an {@link Action5} to a function that calls the action and returns {@code null}. @param action the {@link Action5} to convert @return a {@link Func5} that calls {@code action} and returns {@code null}
[ "Converts", "an", "{", "@link", "Action5", "}", "to", "a", "function", "that", "calls", "the", "action", "and", "returns", "{", "@code", "null", "}", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/function/Actions.java#L135-L138
k3po/k3po
specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java
Functions.createServerGSSContext
@Function public static GSSContext createServerGSSContext() { System.out.println("createServerGSSContext()..."); try { final GSSManager manager = GSSManager.getInstance(); // // Create server credentials to accept kerberos tokens. This should // make use of the sun.security.krb5.principal system property to // authenticate with the KDC. // GSSCredential serverCreds; try { serverCreds = Subject.doAs(new Subject(), new PrivilegedExceptionAction<GSSCredential>() { public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, krb5Oid, GSSCredential.ACCEPT_ONLY); } }); } catch (PrivilegedActionException e) { throw new RuntimeException("Exception creating server credentials", e); } // // Create the GSSContext used to process requests from clients. The client // requets should use Kerberos since the server credentials are Kerberos // based. // GSSContext retVal = manager.createContext(serverCreds); System.out.println("createServerGSSContext(), context: " + retVal); return retVal; } catch (GSSException ex) { System.out.println("createServerGSSContext(), finished with exception"); throw new RuntimeException("Exception creating server GSSContext", ex); } }
java
@Function public static GSSContext createServerGSSContext() { System.out.println("createServerGSSContext()..."); try { final GSSManager manager = GSSManager.getInstance(); // // Create server credentials to accept kerberos tokens. This should // make use of the sun.security.krb5.principal system property to // authenticate with the KDC. // GSSCredential serverCreds; try { serverCreds = Subject.doAs(new Subject(), new PrivilegedExceptionAction<GSSCredential>() { public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, krb5Oid, GSSCredential.ACCEPT_ONLY); } }); } catch (PrivilegedActionException e) { throw new RuntimeException("Exception creating server credentials", e); } // // Create the GSSContext used to process requests from clients. The client // requets should use Kerberos since the server credentials are Kerberos // based. // GSSContext retVal = manager.createContext(serverCreds); System.out.println("createServerGSSContext(), context: " + retVal); return retVal; } catch (GSSException ex) { System.out.println("createServerGSSContext(), finished with exception"); throw new RuntimeException("Exception creating server GSSContext", ex); } }
[ "@", "Function", "public", "static", "GSSContext", "createServerGSSContext", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"createServerGSSContext()...\"", ")", ";", "try", "{", "final", "GSSManager", "manager", "=", "GSSManager", ".", "getInstance",...
Create a GSS Context not tied to any server name. Peers acting as a server create their context this way. @return the newly created GSS Context
[ "Create", "a", "GSS", "Context", "not", "tied", "to", "any", "server", "name", ".", "Peers", "acting", "as", "a", "server", "create", "their", "context", "this", "way", "." ]
train
https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/specification/socks5/src/main/java/org/kaazing/specification/socks5/internal/Functions.java#L175-L210
Coveros/selenified
src/main/java/com/coveros/selenified/application/WaitFor.java
WaitFor.cookieMatches
@Override public void cookieMatches(String cookieName, String expectedCookiePattern) { cookieMatches(defaultWait, cookieName, expectedCookiePattern); }
java
@Override public void cookieMatches(String cookieName, String expectedCookiePattern) { cookieMatches(defaultWait, cookieName, expectedCookiePattern); }
[ "@", "Override", "public", "void", "cookieMatches", "(", "String", "cookieName", ",", "String", "expectedCookiePattern", ")", "{", "cookieMatches", "(", "defaultWait", ",", "cookieName", ",", "expectedCookiePattern", ")", ";", "}" ]
Waits up to the default wait time (5 seconds unless changed) for a cookies with the provided name has a value matching the expected pattern. This information will be logged and recorded, with a screenshot for traceability and added debugging support. @param cookieName the name of the cookie @param expectedCookiePattern the expected value of the cookie
[ "Waits", "up", "to", "the", "default", "wait", "time", "(", "5", "seconds", "unless", "changed", ")", "for", "a", "cookies", "with", "the", "provided", "name", "has", "a", "value", "matching", "the", "expected", "pattern", ".", "This", "information", "will...
train
https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/application/WaitFor.java#L331-L334
google/closure-templates
java/src/com/google/template/soy/data/SoyValueConverter.java
SoyValueConverter.newSoyMapFromJavaMap
private SoyMap newSoyMapFromJavaMap(Map<?, ?> javaMap) { Map<SoyValue, SoyValueProvider> map = Maps.newHashMapWithExpectedSize(javaMap.size()); for (Map.Entry<?, ?> entry : javaMap.entrySet()) { map.put(convert(entry.getKey()).resolve(), convertLazy(entry.getValue())); } return SoyMapImpl.forProviderMap(map); }
java
private SoyMap newSoyMapFromJavaMap(Map<?, ?> javaMap) { Map<SoyValue, SoyValueProvider> map = Maps.newHashMapWithExpectedSize(javaMap.size()); for (Map.Entry<?, ?> entry : javaMap.entrySet()) { map.put(convert(entry.getKey()).resolve(), convertLazy(entry.getValue())); } return SoyMapImpl.forProviderMap(map); }
[ "private", "SoyMap", "newSoyMapFromJavaMap", "(", "Map", "<", "?", ",", "?", ">", "javaMap", ")", "{", "Map", "<", "SoyValue", ",", "SoyValueProvider", ">", "map", "=", "Maps", ".", "newHashMapWithExpectedSize", "(", "javaMap", ".", "size", "(", ")", ")", ...
Creates a Soy map from a Java map. While this is O(n) in the map's shallow size, the Java values are converted into Soy values lazily and only once. The keys are converted eagerly.
[ "Creates", "a", "Soy", "map", "from", "a", "Java", "map", ".", "While", "this", "is", "O", "(", "n", ")", "in", "the", "map", "s", "shallow", "size", "the", "Java", "values", "are", "converted", "into", "Soy", "values", "lazily", "and", "only", "once...
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/data/SoyValueConverter.java#L370-L376
OpenLiberty/open-liberty
dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/MonitoringProxyActivator.java
MonitoringProxyActivator.createBootProxyJar
JarFile createBootProxyJar() throws IOException { File dataFile = bundleContext.getDataFile("boot-proxy.jar"); // Create the file if it doesn't already exist if (!dataFile.exists()) { dataFile.createNewFile(); } // Generate a manifest Manifest manifest = createBootJarManifest(); // Create the file FileOutputStream fileOutputStream = new FileOutputStream(dataFile, false); JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream, manifest); // Add the jar path entries to reduce class load times createDirectoryEntries(jarOutputStream, BOOT_DELEGATED_PACKAGE); // Map the template classes into the delegation package and add to the jar Bundle bundle = bundleContext.getBundle(); Enumeration<?> entryPaths = bundle.getEntryPaths(TEMPLATE_CLASSES_PATH); if (entryPaths != null) { while (entryPaths.hasMoreElements()) { URL sourceClassResource = bundle.getEntry((String) entryPaths.nextElement()); if (sourceClassResource != null) writeRemappedClass(sourceClassResource, jarOutputStream, BOOT_DELEGATED_PACKAGE); } } jarOutputStream.close(); fileOutputStream.close(); return new JarFile(dataFile); }
java
JarFile createBootProxyJar() throws IOException { File dataFile = bundleContext.getDataFile("boot-proxy.jar"); // Create the file if it doesn't already exist if (!dataFile.exists()) { dataFile.createNewFile(); } // Generate a manifest Manifest manifest = createBootJarManifest(); // Create the file FileOutputStream fileOutputStream = new FileOutputStream(dataFile, false); JarOutputStream jarOutputStream = new JarOutputStream(fileOutputStream, manifest); // Add the jar path entries to reduce class load times createDirectoryEntries(jarOutputStream, BOOT_DELEGATED_PACKAGE); // Map the template classes into the delegation package and add to the jar Bundle bundle = bundleContext.getBundle(); Enumeration<?> entryPaths = bundle.getEntryPaths(TEMPLATE_CLASSES_PATH); if (entryPaths != null) { while (entryPaths.hasMoreElements()) { URL sourceClassResource = bundle.getEntry((String) entryPaths.nextElement()); if (sourceClassResource != null) writeRemappedClass(sourceClassResource, jarOutputStream, BOOT_DELEGATED_PACKAGE); } } jarOutputStream.close(); fileOutputStream.close(); return new JarFile(dataFile); }
[ "JarFile", "createBootProxyJar", "(", ")", "throws", "IOException", "{", "File", "dataFile", "=", "bundleContext", ".", "getDataFile", "(", "\"boot-proxy.jar\"", ")", ";", "// Create the file if it doesn't already exist", "if", "(", "!", "dataFile", ".", "exists", "("...
Create a jar file that contains the proxy code that will live in the boot delegation package. @return the jar file containing the proxy code to append to the boot class path @throws IOException if a file I/O error occurs
[ "Create", "a", "jar", "file", "that", "contains", "the", "proxy", "code", "that", "will", "live", "in", "the", "boot", "delegation", "package", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/MonitoringProxyActivator.java#L228-L261
joniles/mpxj
src/main/java/net/sf/mpxj/planner/PlannerWriter.java
PlannerWriter.processWorkingHours
private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList) { if (isWorkingDay(mpxjCalendar, day)) { ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day); if (mpxjHours != null) { OverriddenDayType odt = m_factory.createOverriddenDayType(); typeList.add(odt); odt.setId(getIntegerString(uniqueID.next())); List<Interval> intervalList = odt.getInterval(); for (DateRange mpxjRange : mpxjHours) { Date rangeStart = mpxjRange.getStart(); Date rangeEnd = mpxjRange.getEnd(); if (rangeStart != null && rangeEnd != null) { Interval interval = m_factory.createInterval(); intervalList.add(interval); interval.setStart(getTimeString(rangeStart)); interval.setEnd(getTimeString(rangeEnd)); } } } } }
java
private void processWorkingHours(ProjectCalendar mpxjCalendar, Sequence uniqueID, Day day, List<OverriddenDayType> typeList) { if (isWorkingDay(mpxjCalendar, day)) { ProjectCalendarHours mpxjHours = mpxjCalendar.getCalendarHours(day); if (mpxjHours != null) { OverriddenDayType odt = m_factory.createOverriddenDayType(); typeList.add(odt); odt.setId(getIntegerString(uniqueID.next())); List<Interval> intervalList = odt.getInterval(); for (DateRange mpxjRange : mpxjHours) { Date rangeStart = mpxjRange.getStart(); Date rangeEnd = mpxjRange.getEnd(); if (rangeStart != null && rangeEnd != null) { Interval interval = m_factory.createInterval(); intervalList.add(interval); interval.setStart(getTimeString(rangeStart)); interval.setEnd(getTimeString(rangeEnd)); } } } } }
[ "private", "void", "processWorkingHours", "(", "ProjectCalendar", "mpxjCalendar", ",", "Sequence", "uniqueID", ",", "Day", "day", ",", "List", "<", "OverriddenDayType", ">", "typeList", ")", "{", "if", "(", "isWorkingDay", "(", "mpxjCalendar", ",", "day", ")", ...
Process the standard working hours for a given day. @param mpxjCalendar MPXJ Calendar instance @param uniqueID unique ID sequence generation @param day Day instance @param typeList Planner list of days
[ "Process", "the", "standard", "working", "hours", "for", "a", "given", "day", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/planner/PlannerWriter.java#L295-L321
micronaut-projects/micronaut-core
http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java
CorsFilter.handleResponse
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) { HttpHeaders headers = request.getHeaders(); Optional<String> originHeader = headers.getOrigin(); originHeader.ifPresent(requestOrigin -> { Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin); if (optionalConfig.isPresent()) { CorsOriginConfiguration config = optionalConfig.get(); if (CorsUtil.isPreflightRequest(request)) { Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class); setAllowMethods(result.get(), response); Argument<List> type = Argument.of(List.class, String.class); Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, type); allowedHeaders.ifPresent(val -> setAllowHeaders(val, response) ); setMaxAge(config.getMaxAge(), response); } setOrigin(requestOrigin, response); setVary(response); setExposeHeaders(config.getExposedHeaders(), response); setAllowCredentials(config, response); } }); }
java
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) { HttpHeaders headers = request.getHeaders(); Optional<String> originHeader = headers.getOrigin(); originHeader.ifPresent(requestOrigin -> { Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin); if (optionalConfig.isPresent()) { CorsOriginConfiguration config = optionalConfig.get(); if (CorsUtil.isPreflightRequest(request)) { Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class); setAllowMethods(result.get(), response); Argument<List> type = Argument.of(List.class, String.class); Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, type); allowedHeaders.ifPresent(val -> setAllowHeaders(val, response) ); setMaxAge(config.getMaxAge(), response); } setOrigin(requestOrigin, response); setVary(response); setExposeHeaders(config.getExposedHeaders(), response); setAllowCredentials(config, response); } }); }
[ "protected", "void", "handleResponse", "(", "HttpRequest", "<", "?", ">", "request", ",", "MutableHttpResponse", "<", "?", ">", "response", ")", "{", "HttpHeaders", "headers", "=", "request", ".", "getHeaders", "(", ")", ";", "Optional", "<", "String", ">", ...
Handles a CORS response. @param request The {@link HttpRequest} object @param response The {@link MutableHttpResponse} object
[ "Handles", "a", "CORS", "response", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http-server/src/main/java/io/micronaut/http/server/cors/CorsFilter.java#L98-L126
STIXProject/java-stix
src/main/java/org/mitre/stix/DocumentUtilities.java
DocumentUtilities.toXMLString
public static String toXMLString(JAXBElement<?> jaxbElement, boolean prettyPrint) { Document document = toDocument(jaxbElement); return toXMLString(document, prettyPrint); }
java
public static String toXMLString(JAXBElement<?> jaxbElement, boolean prettyPrint) { Document document = toDocument(jaxbElement); return toXMLString(document, prettyPrint); }
[ "public", "static", "String", "toXMLString", "(", "JAXBElement", "<", "?", ">", "jaxbElement", ",", "boolean", "prettyPrint", ")", "{", "Document", "document", "=", "toDocument", "(", "jaxbElement", ")", ";", "return", "toXMLString", "(", "document", ",", "pre...
Returns a String for a JAXBElement @param jaxbElement JAXB representation of an XML Element to be printed. @param prettyPrint True for pretty print, otherwise false @return String containing the XML mark-up.
[ "Returns", "a", "String", "for", "a", "JAXBElement" ]
train
https://github.com/STIXProject/java-stix/blob/796b1314253fac3ebafca347f6eeb2c51ba4b009/src/main/java/org/mitre/stix/DocumentUtilities.java#L177-L184
joniles/mpxj
src/main/java/net/sf/mpxj/json/JsonWriter.java
JsonWriter.writeStringField
private void writeStringField(String fieldName, Object value) throws IOException { String val = value.toString(); if (!val.isEmpty()) { m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeStringField(String fieldName, Object value) throws IOException { String val = value.toString(); if (!val.isEmpty()) { m_writer.writeNameValuePair(fieldName, val); } }
[ "private", "void", "writeStringField", "(", "String", "fieldName", ",", "Object", "value", ")", "throws", "IOException", "{", "String", "val", "=", "value", ".", "toString", "(", ")", ";", "if", "(", "!", "val", ".", "isEmpty", "(", ")", ")", "{", "m_w...
Write a string field to the JSON file. @param fieldName field name @param value field value
[ "Write", "a", "string", "field", "to", "the", "JSON", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/json/JsonWriter.java#L512-L519
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/cache/CacheEntry.java
CacheEntry.setValue
public void setValue(Object value, long timeout) { _value = value; _expiration = System.currentTimeMillis() + timeout; }
java
public void setValue(Object value, long timeout) { _value = value; _expiration = System.currentTimeMillis() + timeout; }
[ "public", "void", "setValue", "(", "Object", "value", ",", "long", "timeout", ")", "{", "_value", "=", "value", ";", "_expiration", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "timeout", ";", "}" ]
Sets a new value and extends its expiration. @param value a new cached value. @param timeout a expiration timeout in milliseconds.
[ "Sets", "a", "new", "value", "and", "extends", "its", "expiration", "." ]
train
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/cache/CacheEntry.java#L48-L51
knowm/Yank
src/main/java/org/knowm/yank/Yank.java
Yank.insertSQLKey
public static Long insertSQLKey(String poolName, String sqlKey, Object[] params) throws SQLStatementNotFoundException, YankSQLException { String sql = YANK_POOL_MANAGER.getMergedSqlProperties().getProperty(sqlKey); if (sql == null || sql.equalsIgnoreCase("")) { throw new SQLStatementNotFoundException(); } else { return insert(poolName, sql, params); } }
java
public static Long insertSQLKey(String poolName, String sqlKey, Object[] params) throws SQLStatementNotFoundException, YankSQLException { String sql = YANK_POOL_MANAGER.getMergedSqlProperties().getProperty(sqlKey); if (sql == null || sql.equalsIgnoreCase("")) { throw new SQLStatementNotFoundException(); } else { return insert(poolName, sql, params); } }
[ "public", "static", "Long", "insertSQLKey", "(", "String", "poolName", ",", "String", "sqlKey", ",", "Object", "[", "]", "params", ")", "throws", "SQLStatementNotFoundException", ",", "YankSQLException", "{", "String", "sql", "=", "YANK_POOL_MANAGER", ".", "getMer...
Executes a given INSERT SQL prepared statement matching the sqlKey String in a properties file loaded via Yank.addSQLStatements(...). Returns the auto-increment id of the inserted row. @param poolName The name of the connection pool to query against @param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement value @param params The replacement parameters @return the auto-increment id of the inserted row, or null if no id is available @throws SQLStatementNotFoundException if an SQL statement could not be found for the given sqlKey String
[ "Executes", "a", "given", "INSERT", "SQL", "prepared", "statement", "matching", "the", "sqlKey", "String", "in", "a", "properties", "file", "loaded", "via", "Yank", ".", "addSQLStatements", "(", "...", ")", ".", "Returns", "the", "auto", "-", "increment", "i...
train
https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L84-L93
JadiraOrg/jadira
cdt/src/main/java/org/jadira/cdt/phonenumber/impl/E164PhoneNumberWithExtension.java
E164PhoneNumberWithExtension.ofPhoneNumberStringAndExtension
public static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode) { return new E164PhoneNumberWithExtension(phoneNumber, extension, defaultCountryCode); }
java
public static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension(String phoneNumber, String extension, CountryCode defaultCountryCode) { return new E164PhoneNumberWithExtension(phoneNumber, extension, defaultCountryCode); }
[ "public", "static", "E164PhoneNumberWithExtension", "ofPhoneNumberStringAndExtension", "(", "String", "phoneNumber", ",", "String", "extension", ",", "CountryCode", "defaultCountryCode", ")", "{", "return", "new", "E164PhoneNumberWithExtension", "(", "phoneNumber", ",", "ex...
Creates a new E164 Phone Number with the given extension. @param phoneNumber The phone number in arbitrary parseable format (may be a national format) @param extension The extension, or null for no extension @param defaultCountryCode The Country to apply if no country is indicated by the phone number @return A new instance of E164PhoneNumberWithExtension
[ "Creates", "a", "new", "E164", "Phone", "Number", "with", "the", "given", "extension", "." ]
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/cdt/src/main/java/org/jadira/cdt/phonenumber/impl/E164PhoneNumberWithExtension.java#L212-L214
alkacon/opencms-core
src/org/opencms/jsp/CmsJspNavBuilder.java
CmsJspNavBuilder.getSiteNavigation
public List<CmsJspNavElement> getSiteNavigation(String folder, int endLevel) { return getSiteNavigation(folder, Visibility.navigation, endLevel); }
java
public List<CmsJspNavElement> getSiteNavigation(String folder, int endLevel) { return getSiteNavigation(folder, Visibility.navigation, endLevel); }
[ "public", "List", "<", "CmsJspNavElement", ">", "getSiteNavigation", "(", "String", "folder", ",", "int", "endLevel", ")", "{", "return", "getSiteNavigation", "(", "folder", ",", "Visibility", ".", "navigation", ",", "endLevel", ")", ";", "}" ]
This method builds a complete navigation tree with entries of all branches from the specified folder.<p> @param folder folder the root folder of the navigation tree @param endLevel the end level of the navigation @return list of navigation elements, in depth first order
[ "This", "method", "builds", "a", "complete", "navigation", "tree", "with", "entries", "of", "all", "branches", "from", "the", "specified", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspNavBuilder.java#L706-L709
RestComm/sip-servlets
sip-servlets-examples/alerting-app/sip-servlets/src/main/java/org/mobicents/servlet/sip/alerting/JainSleeSmsAlertServlet.java
JainSleeSmsAlertServlet.doPost
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String alertId = request.getParameter("alertId"); String tel = request.getParameter("tel"); String alertText = request.getParameter("alertText"); if(alertText == null || alertText.length() < 1) { // Get the content of the request as the text to parse byte[] content = new byte[request.getContentLength()]; request.getInputStream().read(content,0, request.getContentLength()); alertText = new String(content); } if(logger.isInfoEnabled()) { logger.info("Got an alert : \n alertID : " + alertId + " \n tel : " + tel + " \n text : " +alertText); } // try { Properties jndiProps = new Properties(); Context initCtx = new InitialContext(jndiProps); // Commented out since the preferred way is through SMS Servlets // SleeConnectionFactory factory = (SleeConnectionFactory) initCtx.lookup("java:/MobicentsConnectionFactory"); // // SleeConnection conn1 = factory.getConnection(); // ExternalActivityHandle handle = conn1.createActivityHandle(); // // EventTypeID requestType = conn1.getEventTypeID( // EVENT_TYPE, // "org.mobicents", "1.0"); // SmsAlertingCustomEvent smsAlertingCustomEvent = new SmsAlertingCustomEvent(alertId, tel, alertText); // // conn1.fireEvent(smsAlertingCustomEvent, requestType, handle, null); // conn1.close(); } catch (Exception e) { logger.error("unexpected exception while firing the event " + EVENT_TYPE + " into jslee", e); } sendHttpResponse(response, OK_BODY); }
java
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String alertId = request.getParameter("alertId"); String tel = request.getParameter("tel"); String alertText = request.getParameter("alertText"); if(alertText == null || alertText.length() < 1) { // Get the content of the request as the text to parse byte[] content = new byte[request.getContentLength()]; request.getInputStream().read(content,0, request.getContentLength()); alertText = new String(content); } if(logger.isInfoEnabled()) { logger.info("Got an alert : \n alertID : " + alertId + " \n tel : " + tel + " \n text : " +alertText); } // try { Properties jndiProps = new Properties(); Context initCtx = new InitialContext(jndiProps); // Commented out since the preferred way is through SMS Servlets // SleeConnectionFactory factory = (SleeConnectionFactory) initCtx.lookup("java:/MobicentsConnectionFactory"); // // SleeConnection conn1 = factory.getConnection(); // ExternalActivityHandle handle = conn1.createActivityHandle(); // // EventTypeID requestType = conn1.getEventTypeID( // EVENT_TYPE, // "org.mobicents", "1.0"); // SmsAlertingCustomEvent smsAlertingCustomEvent = new SmsAlertingCustomEvent(alertId, tel, alertText); // // conn1.fireEvent(smsAlertingCustomEvent, requestType, handle, null); // conn1.close(); } catch (Exception e) { logger.error("unexpected exception while firing the event " + EVENT_TYPE + " into jslee", e); } sendHttpResponse(response, OK_BODY); }
[ "public", "void", "doPost", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "ServletException", ",", "IOException", "{", "String", "alertId", "=", "request", ".", "getParameter", "(", "\"alertId\"", ")", ";", "String", ...
Handle the HTTP POST method on which alert can be sent so that the app sends an sms based on that
[ "Handle", "the", "HTTP", "POST", "method", "on", "which", "alert", "can", "be", "sent", "so", "that", "the", "app", "sends", "an", "sms", "based", "on", "that" ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/alerting-app/sip-servlets/src/main/java/org/mobicents/servlet/sip/alerting/JainSleeSmsAlertServlet.java#L60-L96
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/ds/LDAP.java
LDAP.authenicate
public Principal authenicate(String uid, char[] password) throws SecurityException { String rootDN = Config.getProperty(ROOT_DN_PROP); int timeout = Config.getPropertyInteger(TIMEOUT_SECS_PROP).intValue(); Debugger.println(LDAP.class,"timeout="+timeout); String uidAttributeName = Config.getProperty(UID_ATTRIB_NM_PROP); String groupAttributeName = Config.getProperty(GROUP_ATTRIB_NM_PROP,""); String memberOfAttributeName = Config.getProperty(MEMBEROF_ATTRIB_NM_PROP,""); return authenicate(uid, password,rootDN,uidAttributeName,memberOfAttributeName,groupAttributeName,timeout); }
java
public Principal authenicate(String uid, char[] password) throws SecurityException { String rootDN = Config.getProperty(ROOT_DN_PROP); int timeout = Config.getPropertyInteger(TIMEOUT_SECS_PROP).intValue(); Debugger.println(LDAP.class,"timeout="+timeout); String uidAttributeName = Config.getProperty(UID_ATTRIB_NM_PROP); String groupAttributeName = Config.getProperty(GROUP_ATTRIB_NM_PROP,""); String memberOfAttributeName = Config.getProperty(MEMBEROF_ATTRIB_NM_PROP,""); return authenicate(uid, password,rootDN,uidAttributeName,memberOfAttributeName,groupAttributeName,timeout); }
[ "public", "Principal", "authenicate", "(", "String", "uid", ",", "char", "[", "]", "password", ")", "throws", "SecurityException", "{", "String", "rootDN", "=", "Config", ".", "getProperty", "(", "ROOT_DN_PROP", ")", ";", "int", "timeout", "=", "Config", "."...
Authenticate user ID and password against the LDAP server @param uid i.e. greeng @param password the user password @return the user principal details @throws SecurityException when security error occurs
[ "Authenticate", "user", "ID", "and", "password", "against", "the", "LDAP", "server" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/ds/LDAP.java#L270-L284
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldTracker.java
TldTracker.initialize
public void initialize( T image , int x0 , int y0 , int x1 , int y1 ) { if( imagePyramid == null || imagePyramid.getInputWidth() != image.width || imagePyramid.getInputHeight() != image.height ) { int minSize = (config.trackerFeatureRadius*2+1)*5; int scales[] = selectPyramidScale(image.width,image.height,minSize); imagePyramid = FactoryPyramid.discreteGaussian(scales,-1,1,true,image.getImageType()); } imagePyramid.process(image); reacquiring = false; targetRegion.set(x0, y0, x1, y1); createCascadeRegion(image.width,image.height); template.reset(); fern.reset(); tracking.initialize(imagePyramid); variance.setImage(image); template.setImage(image); fern.setImage(image); adjustRegion.init(image.width,image.height); learning.initialLearning(targetRegion, cascadeRegions); strongMatch = true; previousTrackArea = targetRegion.area(); }
java
public void initialize( T image , int x0 , int y0 , int x1 , int y1 ) { if( imagePyramid == null || imagePyramid.getInputWidth() != image.width || imagePyramid.getInputHeight() != image.height ) { int minSize = (config.trackerFeatureRadius*2+1)*5; int scales[] = selectPyramidScale(image.width,image.height,minSize); imagePyramid = FactoryPyramid.discreteGaussian(scales,-1,1,true,image.getImageType()); } imagePyramid.process(image); reacquiring = false; targetRegion.set(x0, y0, x1, y1); createCascadeRegion(image.width,image.height); template.reset(); fern.reset(); tracking.initialize(imagePyramid); variance.setImage(image); template.setImage(image); fern.setImage(image); adjustRegion.init(image.width,image.height); learning.initialLearning(targetRegion, cascadeRegions); strongMatch = true; previousTrackArea = targetRegion.area(); }
[ "public", "void", "initialize", "(", "T", "image", ",", "int", "x0", ",", "int", "y0", ",", "int", "x1", ",", "int", "y1", ")", "{", "if", "(", "imagePyramid", "==", "null", "||", "imagePyramid", ".", "getInputWidth", "(", ")", "!=", "image", ".", ...
Starts tracking the rectangular region. @param image First image in the sequence. @param x0 Top-left corner of rectangle. x-axis @param y0 Top-left corner of rectangle. y-axis @param x1 Bottom-right corner of rectangle. x-axis @param y1 Bottom-right corner of rectangle. y-axis
[ "Starts", "tracking", "the", "rectangular", "region", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/tld/TldTracker.java#L148-L175
wuman/orientdb-android
core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/stream/OStreamSerializerAnyRuntime.java
OStreamSerializerAnyRuntime.fromStream
public Object fromStream(final byte[] iStream) throws IOException { if (iStream == null || iStream.length == 0) // NULL VALUE return null; final ByteArrayInputStream is = new ByteArrayInputStream(iStream); final ObjectInputStream in = new ObjectInputStream(is); try { return in.readObject(); } catch (ClassNotFoundException e) { throw new OSerializationException("Cannot unmarshall Java serialized object", e); } finally { in.close(); is.close(); } }
java
public Object fromStream(final byte[] iStream) throws IOException { if (iStream == null || iStream.length == 0) // NULL VALUE return null; final ByteArrayInputStream is = new ByteArrayInputStream(iStream); final ObjectInputStream in = new ObjectInputStream(is); try { return in.readObject(); } catch (ClassNotFoundException e) { throw new OSerializationException("Cannot unmarshall Java serialized object", e); } finally { in.close(); is.close(); } }
[ "public", "Object", "fromStream", "(", "final", "byte", "[", "]", "iStream", ")", "throws", "IOException", "{", "if", "(", "iStream", "==", "null", "||", "iStream", ".", "length", "==", "0", ")", "// NULL VALUE\r", "return", "null", ";", "final", "ByteArra...
Re-Create any object if the class has a public constructor that accepts a String as unique parameter.
[ "Re", "-", "Create", "any", "object", "if", "the", "class", "has", "a", "public", "constructor", "that", "accepts", "a", "String", "as", "unique", "parameter", "." ]
train
https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/stream/OStreamSerializerAnyRuntime.java#L45-L60