repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
sarl/sarl
contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java
PyExpressionGenerator._generate
protected XExpression _generate(XCastedExpression castOperator, IAppendable it, IExtraLanguageGeneratorContext context) { return generate(castOperator.getTarget(), context.getExpectedExpressionType(), it, context); }
java
protected XExpression _generate(XCastedExpression castOperator, IAppendable it, IExtraLanguageGeneratorContext context) { return generate(castOperator.getTarget(), context.getExpectedExpressionType(), it, context); }
[ "protected", "XExpression", "_generate", "(", "XCastedExpression", "castOperator", ",", "IAppendable", "it", ",", "IExtraLanguageGeneratorContext", "context", ")", "{", "return", "generate", "(", "castOperator", ".", "getTarget", "(", ")", ",", "context", ".", "getE...
Generate the given object. @param castOperator the cast operator. @param it the target for the generated content. @param context the context. @return the expression.
[ "Generate", "the", "given", "object", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java#L688-L690
GerdHolz/TOVAL
src/de/invation/code/toval/misc/wd/AbstractComponentContainer.java
AbstractComponentContainer.addComponent
public void addComponent(O component, boolean storeToFile, boolean notifyListeners) throws ProjectComponentException { Validate.notNull(component); Validate.notNull(storeToFile); String componentName = component.getName(); Validate.notNull(componentName); if (containsComponent(componentName)) { throw new ProjectComponentException("Container already contains component with name \"" + componentName + "\""); } File componentFile = null; try { File pathFile = getComponentDirectory(componentName); pathFile.mkdir(); componentFile = getComponentFile(pathFile, componentName); } catch (Exception e) { ExceptionDialog.showException(null, "", e, true); throw new ProjectComponentException("Cannot create component file.", e); } components.put(componentName, component); componentFiles.put(componentName, componentFile); if (storeToFile) { try { storeComponent(component.getName()); } catch (Exception e) { throw new ProjectComponentException("Cannot store created component " + component.getName() + " to disk: " + e.getMessage(), e); } } if (notifyListeners) { listenerSupport.notifyComponentAdded(component); } }
java
public void addComponent(O component, boolean storeToFile, boolean notifyListeners) throws ProjectComponentException { Validate.notNull(component); Validate.notNull(storeToFile); String componentName = component.getName(); Validate.notNull(componentName); if (containsComponent(componentName)) { throw new ProjectComponentException("Container already contains component with name \"" + componentName + "\""); } File componentFile = null; try { File pathFile = getComponentDirectory(componentName); pathFile.mkdir(); componentFile = getComponentFile(pathFile, componentName); } catch (Exception e) { ExceptionDialog.showException(null, "", e, true); throw new ProjectComponentException("Cannot create component file.", e); } components.put(componentName, component); componentFiles.put(componentName, componentFile); if (storeToFile) { try { storeComponent(component.getName()); } catch (Exception e) { throw new ProjectComponentException("Cannot store created component " + component.getName() + " to disk: " + e.getMessage(), e); } } if (notifyListeners) { listenerSupport.notifyComponentAdded(component); } }
[ "public", "void", "addComponent", "(", "O", "component", ",", "boolean", "storeToFile", ",", "boolean", "notifyListeners", ")", "throws", "ProjectComponentException", "{", "Validate", ".", "notNull", "(", "component", ")", ";", "Validate", ".", "notNull", "(", "...
Adds a new component.<br> Depending on the value of the store-parameter, the component is also stored in the serialization directory. @param component The new component to add. @param storeToFile Indicates if the net should be stored to disk. @param notifyListeners @throws de.invation.code.toval.misc.wd.ProjectComponentException
[ "Adds", "a", "new", "component", ".", "<br", ">", "Depending", "on", "the", "value", "of", "the", "store", "-", "parameter", "the", "component", "is", "also", "stored", "in", "the", "serialization", "directory", "." ]
train
https://github.com/GerdHolz/TOVAL/blob/036922cdfd710fa53b18e5dbe1e07f226f731fde/src/de/invation/code/toval/misc/wd/AbstractComponentContainer.java#L353-L386
lecousin/java-framework-core
net.lecousin.core/src/main/java/net/lecousin/framework/adapter/AdapterRegistry.java
AdapterRegistry.canAdapt
public boolean canAdapt(Object input, Class<?> outputType) { Class<?> inputType = input.getClass(); Adapter a = findAdapter(input, inputType, outputType); return a != null; }
java
public boolean canAdapt(Object input, Class<?> outputType) { Class<?> inputType = input.getClass(); Adapter a = findAdapter(input, inputType, outputType); return a != null; }
[ "public", "boolean", "canAdapt", "(", "Object", "input", ",", "Class", "<", "?", ">", "outputType", ")", "{", "Class", "<", "?", ">", "inputType", "=", "input", ".", "getClass", "(", ")", ";", "Adapter", "a", "=", "findAdapter", "(", "input", ",", "i...
Return true if an adapter can be found to adapt the given input into the given output type.
[ "Return", "true", "if", "an", "adapter", "can", "be", "found", "to", "adapt", "the", "given", "input", "into", "the", "given", "output", "type", "." ]
train
https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/adapter/AdapterRegistry.java#L65-L69
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/MapTileCollisionComputer.java
MapTileCollisionComputer.getCollisionX
private static Double getCollisionX(CollisionCategory category, TileCollision tileCollision, double x, double y) { if (Axis.X == category.getAxis()) { return tileCollision.getCollisionX(category, x, y); } return null; }
java
private static Double getCollisionX(CollisionCategory category, TileCollision tileCollision, double x, double y) { if (Axis.X == category.getAxis()) { return tileCollision.getCollisionX(category, x, y); } return null; }
[ "private", "static", "Double", "getCollisionX", "(", "CollisionCategory", "category", ",", "TileCollision", "tileCollision", ",", "double", "x", ",", "double", "y", ")", "{", "if", "(", "Axis", ".", "X", "==", "category", ".", "getAxis", "(", ")", ")", "{"...
Get the horizontal collision from current location. @param category The collision category. @param tileCollision The current tile collision. @param x The current horizontal location. @param y The current vertical location. @return The computed horizontal collision.
[ "Get", "the", "horizontal", "collision", "from", "current", "location", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/collision/MapTileCollisionComputer.java#L60-L67
alkacon/opencms-core
src/org/opencms/ui/apps/user/CmsGroupTable.java
CmsGroupTable.fillGroupItem
public void fillGroupItem(Item item, CmsGroup group, List<CmsGroup> indirects) { item.getItemProperty(TableProperty.Name).setValue(group.getName()); item.getItemProperty(TableProperty.Description).setValue(group.getDescription(A_CmsUI.get().getLocale())); item.getItemProperty(TableProperty.OU).setValue(group.getOuFqn()); if (indirects.contains(group)) { item.getItemProperty(TableProperty.INDIRECT).setValue(Boolean.TRUE); } }
java
public void fillGroupItem(Item item, CmsGroup group, List<CmsGroup> indirects) { item.getItemProperty(TableProperty.Name).setValue(group.getName()); item.getItemProperty(TableProperty.Description).setValue(group.getDescription(A_CmsUI.get().getLocale())); item.getItemProperty(TableProperty.OU).setValue(group.getOuFqn()); if (indirects.contains(group)) { item.getItemProperty(TableProperty.INDIRECT).setValue(Boolean.TRUE); } }
[ "public", "void", "fillGroupItem", "(", "Item", "item", ",", "CmsGroup", "group", ",", "List", "<", "CmsGroup", ">", "indirects", ")", "{", "item", ".", "getItemProperty", "(", "TableProperty", ".", "Name", ")", ".", "setValue", "(", "group", ".", "getName...
Fills the container item representing a group.<p> @param item the item @param group the group @param indirects the indirect groups
[ "Fills", "the", "container", "item", "representing", "a", "group", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/user/CmsGroupTable.java#L438-L446
aws/aws-sdk-java
aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateSimulationJobResult.java
CreateSimulationJobResult.withTags
public CreateSimulationJobResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public CreateSimulationJobResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "CreateSimulationJobResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
<p> The list of all tags added to the simulation job. </p> @param tags The list of all tags added to the simulation job. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "list", "of", "all", "tags", "added", "to", "the", "simulation", "job", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-robomaker/src/main/java/com/amazonaws/services/robomaker/model/CreateSimulationJobResult.java#L1520-L1523
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_user_POST
public OvhUserDetail project_serviceName_user_POST(String serviceName, String description, OvhRoleEnum role) throws IOException { String qPath = "/cloud/project/{serviceName}/user"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "role", role); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhUserDetail.class); }
java
public OvhUserDetail project_serviceName_user_POST(String serviceName, String description, OvhRoleEnum role) throws IOException { String qPath = "/cloud/project/{serviceName}/user"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "role", role); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhUserDetail.class); }
[ "public", "OvhUserDetail", "project_serviceName_user_POST", "(", "String", "serviceName", ",", "String", "description", ",", "OvhRoleEnum", "role", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/user\"", ";", "StringBuilder", "s...
Create user REST: POST /cloud/project/{serviceName}/user @param description [required] User description @param role [required] Openstack keystone role name @param serviceName [required] Service name
[ "Create", "user" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L509-L517
carewebframework/carewebframework-core
org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/viewer/HelpViewerProxy.java
HelpViewerProxy.sendRequest
private void sendRequest(InvocationRequest helpRequest, boolean startRemoteViewer) { this.helpRequest = helpRequest; if (helpRequest != null) { if (remoteViewerActive()) { remoteQueue.sendRequest(helpRequest); this.helpRequest = null; } else if (startRemoteViewer) { startRemoteViewer(); } else { this.helpRequest = null; } } }
java
private void sendRequest(InvocationRequest helpRequest, boolean startRemoteViewer) { this.helpRequest = helpRequest; if (helpRequest != null) { if (remoteViewerActive()) { remoteQueue.sendRequest(helpRequest); this.helpRequest = null; } else if (startRemoteViewer) { startRemoteViewer(); } else { this.helpRequest = null; } } }
[ "private", "void", "sendRequest", "(", "InvocationRequest", "helpRequest", ",", "boolean", "startRemoteViewer", ")", "{", "this", ".", "helpRequest", "=", "helpRequest", ";", "if", "(", "helpRequest", "!=", "null", ")", "{", "if", "(", "remoteViewerActive", "(",...
Sends a request to the remote viewer. @param helpRequest The request to send. @param startRemoteViewer If true and the remote viewer is not running, start it.
[ "Sends", "a", "request", "to", "the", "remote", "viewer", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/viewer/HelpViewerProxy.java#L107-L120
elastic/elasticsearch-hadoop
mr/src/main/java/org/elasticsearch/hadoop/rest/commonshttp/auth/spnego/SpnegoAuthScheme.java
SpnegoAuthScheme.ensureMutualAuth
public void ensureMutualAuth(String returnChallenge) throws AuthenticationException { try { processChallenge(returnChallenge); } catch (MalformedChallengeException mce) { throw new AuthenticationException("Received invalid response header for mutual authentication", mce); } try { String token = getNegotiateToken(); if (!spnegoNegotiator.established() || token != null) { throw new AuthenticationException("Could not complete SPNEGO Authentication, Mutual Authentication Failed"); } } catch (GSSException gsse) { throw new AuthenticationException("Could not complete SPNEGO Authentication", gsse); } }
java
public void ensureMutualAuth(String returnChallenge) throws AuthenticationException { try { processChallenge(returnChallenge); } catch (MalformedChallengeException mce) { throw new AuthenticationException("Received invalid response header for mutual authentication", mce); } try { String token = getNegotiateToken(); if (!spnegoNegotiator.established() || token != null) { throw new AuthenticationException("Could not complete SPNEGO Authentication, Mutual Authentication Failed"); } } catch (GSSException gsse) { throw new AuthenticationException("Could not complete SPNEGO Authentication", gsse); } }
[ "public", "void", "ensureMutualAuth", "(", "String", "returnChallenge", ")", "throws", "AuthenticationException", "{", "try", "{", "processChallenge", "(", "returnChallenge", ")", ";", "}", "catch", "(", "MalformedChallengeException", "mce", ")", "{", "throw", "new"...
Authenticating requests with SPNEGO means that a request will execute before the client is sure that the server is mutually authenticated. This means that, at best, if mutual auth is requested, the client cannot trust that the server is giving accurate information, or in the case that the client has already sent data, further communication with the server should not happen. @param returnChallenge The Negotiate challenge from the response headers of a successful executed request @throws AuthenticationException If the response header does not allow for mutual authentication to be established.
[ "Authenticating", "requests", "with", "SPNEGO", "means", "that", "a", "request", "will", "execute", "before", "the", "client", "is", "sure", "that", "the", "server", "is", "mutually", "authenticated", ".", "This", "means", "that", "at", "best", "if", "mutual",...
train
https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/rest/commonshttp/auth/spnego/SpnegoAuthScheme.java#L196-L210
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/slim/StringFixture.java
StringFixture.extractIntFromUsingGroup
public Integer extractIntFromUsingGroup(String value, String regEx, int groupIndex) { Integer result = null; if (value != null) { Matcher matcher = getMatcher(regEx, value); if (matcher.matches()) { String intStr = matcher.group(groupIndex); result = convertToInt(intStr); } } return result; }
java
public Integer extractIntFromUsingGroup(String value, String regEx, int groupIndex) { Integer result = null; if (value != null) { Matcher matcher = getMatcher(regEx, value); if (matcher.matches()) { String intStr = matcher.group(groupIndex); result = convertToInt(intStr); } } return result; }
[ "public", "Integer", "extractIntFromUsingGroup", "(", "String", "value", ",", "String", "regEx", ",", "int", "groupIndex", ")", "{", "Integer", "result", "=", "null", ";", "if", "(", "value", "!=", "null", ")", "{", "Matcher", "matcher", "=", "getMatcher", ...
Extracts a whole number for a string using a regular expression. @param value input string. @param regEx regular expression to match against value. @param groupIndex index of group in regular expression containing the number. @return extracted number.
[ "Extracts", "a", "whole", "number", "for", "a", "string", "using", "a", "regular", "expression", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/StringFixture.java#L185-L195
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/AbstractKMeans.java
AbstractKMeans.minusEquals
public static void minusEquals(double[] sum, NumberVector vec) { for(int d = 0; d < sum.length; d++) { sum[d] -= vec.doubleValue(d); } }
java
public static void minusEquals(double[] sum, NumberVector vec) { for(int d = 0; d < sum.length; d++) { sum[d] -= vec.doubleValue(d); } }
[ "public", "static", "void", "minusEquals", "(", "double", "[", "]", "sum", ",", "NumberVector", "vec", ")", "{", "for", "(", "int", "d", "=", "0", ";", "d", "<", "sum", ".", "length", ";", "d", "++", ")", "{", "sum", "[", "d", "]", "-=", "vec",...
Similar to VMath.minusEquals, but accepts a number vector. @param sum Aggregation array @param vec Vector to subtract
[ "Similar", "to", "VMath", ".", "minusEquals", "but", "accepts", "a", "number", "vector", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/kmeans/AbstractKMeans.java#L195-L199
grails/gorm-hibernate5
grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java
GrailsDomainBinder.bindRoot
public void bindRoot(HibernatePersistentEntity entity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { if (mappings.getEntityBinding(entity.getName()) != null) { LOG.info("[GrailsDomainBinder] Class [" + entity.getName() + "] is already mapped, skipping.. "); return; } RootClass root = new RootClass(this.metadataBuildingContext); root.setAbstract(entity.isAbstract()); final MappingContext mappingContext = entity.getMappingContext(); final java.util.Collection<PersistentEntity> children = mappingContext.getDirectChildEntities(entity); if (children.isEmpty()) { root.setPolymorphic(false); } bindClass(entity, root, mappings); Mapping m = getMapping(entity); bindRootPersistentClassCommonValues(entity, root, mappings, sessionFactoryBeanName); if (!children.isEmpty()) { boolean tablePerSubclass = m != null && !m.getTablePerHierarchy(); if (!tablePerSubclass) { // if the root class has children create a discriminator property bindDiscriminatorProperty(root.getTable(), root, mappings); } // bind the sub classes bindSubClasses(entity, root, mappings, sessionFactoryBeanName); } addMultiTenantFilterIfNecessary(entity, root, mappings, sessionFactoryBeanName); mappings.addEntityBinding(root); }
java
public void bindRoot(HibernatePersistentEntity entity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { if (mappings.getEntityBinding(entity.getName()) != null) { LOG.info("[GrailsDomainBinder] Class [" + entity.getName() + "] is already mapped, skipping.. "); return; } RootClass root = new RootClass(this.metadataBuildingContext); root.setAbstract(entity.isAbstract()); final MappingContext mappingContext = entity.getMappingContext(); final java.util.Collection<PersistentEntity> children = mappingContext.getDirectChildEntities(entity); if (children.isEmpty()) { root.setPolymorphic(false); } bindClass(entity, root, mappings); Mapping m = getMapping(entity); bindRootPersistentClassCommonValues(entity, root, mappings, sessionFactoryBeanName); if (!children.isEmpty()) { boolean tablePerSubclass = m != null && !m.getTablePerHierarchy(); if (!tablePerSubclass) { // if the root class has children create a discriminator property bindDiscriminatorProperty(root.getTable(), root, mappings); } // bind the sub classes bindSubClasses(entity, root, mappings, sessionFactoryBeanName); } addMultiTenantFilterIfNecessary(entity, root, mappings, sessionFactoryBeanName); mappings.addEntityBinding(root); }
[ "public", "void", "bindRoot", "(", "HibernatePersistentEntity", "entity", ",", "InFlightMetadataCollector", "mappings", ",", "String", "sessionFactoryBeanName", ")", "{", "if", "(", "mappings", ".", "getEntityBinding", "(", "entity", ".", "getName", "(", ")", ")", ...
Binds a root class (one with no super classes) to the runtime meta model based on the supplied Grails domain class @param entity The Grails domain class @param mappings The Hibernate Mappings object @param sessionFactoryBeanName the session factory bean name
[ "Binds", "a", "root", "class", "(", "one", "with", "no", "super", "classes", ")", "to", "the", "runtime", "meta", "model", "based", "on", "the", "supplied", "Grails", "domain", "class" ]
train
https://github.com/grails/gorm-hibernate5/blob/0ebb80cd769ef2bea955723d4543828a3e9542ef/grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/cfg/GrailsDomainBinder.java#L1374-L1409
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/storage/AuthRundeckStorageTree.java
AuthRundeckStorageTree.authorizedPath
private boolean authorizedPath(AuthContext context, Path path, String action) { Decision evaluate = context.evaluate( resourceForPath(path), action, environmentForPath(path) ); return evaluate.isAuthorized(); }
java
private boolean authorizedPath(AuthContext context, Path path, String action) { Decision evaluate = context.evaluate( resourceForPath(path), action, environmentForPath(path) ); return evaluate.isAuthorized(); }
[ "private", "boolean", "authorizedPath", "(", "AuthContext", "context", ",", "Path", "path", ",", "String", "action", ")", "{", "Decision", "evaluate", "=", "context", ".", "evaluate", "(", "resourceForPath", "(", "path", ")", ",", "action", ",", "environmentFo...
Evaluate access based on path @param context auth context @param path path @param action action @return true if authorized
[ "Evaluate", "access", "based", "on", "path" ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/storage/AuthRundeckStorageTree.java#L58-L65
HubSpot/Singularity
SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java
SingularityClient.readSandBoxFile
public Optional<MesosFileChunkObject> readSandBoxFile(String taskId, String path, Optional<String> grep, Optional<Long> offset, Optional<Long> length) { final Function<String, String> requestUrl = (host) -> String.format(SANDBOX_READ_FILE_FORMAT, getApiBase(host), taskId); Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("path", path); if (grep.isPresent()) { queryParamBuider.put("grep", grep.get()); } if (offset.isPresent()) { queryParamBuider.put("offset", offset.get()); } if (length.isPresent()) { queryParamBuider.put("length", length.get()); } return getSingleWithParams(requestUrl, "Read sandbox file for task", taskId, Optional.of(queryParamBuider.build()), MesosFileChunkObject.class); }
java
public Optional<MesosFileChunkObject> readSandBoxFile(String taskId, String path, Optional<String> grep, Optional<Long> offset, Optional<Long> length) { final Function<String, String> requestUrl = (host) -> String.format(SANDBOX_READ_FILE_FORMAT, getApiBase(host), taskId); Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("path", path); if (grep.isPresent()) { queryParamBuider.put("grep", grep.get()); } if (offset.isPresent()) { queryParamBuider.put("offset", offset.get()); } if (length.isPresent()) { queryParamBuider.put("length", length.get()); } return getSingleWithParams(requestUrl, "Read sandbox file for task", taskId, Optional.of(queryParamBuider.build()), MesosFileChunkObject.class); }
[ "public", "Optional", "<", "MesosFileChunkObject", ">", "readSandBoxFile", "(", "String", "taskId", ",", "String", "path", ",", "Optional", "<", "String", ">", "grep", ",", "Optional", "<", "Long", ">", "offset", ",", "Optional", "<", "Long", ">", "length", ...
Retrieve part of the contents of a file in a specific task's sandbox. @param taskId The task ID of the sandbox to read from @param path The path to the file to be read. Relative to the sandbox root (without a leading slash) @param grep Optional string to grep for @param offset Byte offset to start reading from @param length Maximum number of bytes to read @return A {@link MesosFileChunkObject} that contains the requested partial file contents
[ "Retrieve", "part", "of", "the", "contents", "of", "a", "file", "in", "a", "specific", "task", "s", "sandbox", "." ]
train
https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java#L1307-L1323
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/business/oauth/AuthRequestHelper.java
AuthRequestHelper.validateTokenRequest
public static boolean validateTokenRequest(TokenRequestDto tokenRequestDto, OAuthApplicationDto oAuthApplicationDto) { // basic check try { String decodedRedirectUri = java.net.URLDecoder.decode(tokenRequestDto.getRedirectUri(), "UTF-8"); if (StringUtils.isNotBlank(oAuthApplicationDto.getRedirectUri()) && oAuthApplicationDto.getRedirectUri().equals(decodedRedirectUri)) { if (StringUtils.isNotBlank(tokenRequestDto.getGrantType())) { if (OAuthFields.AUTHORIZATION_CODE.equals(tokenRequestDto.getGrantType())) { return true; } else { _logger.info("Grant Type '" + tokenRequestDto.getGrantType() + "' is not supported"); throw new OAuthException(ResponseCodes.GRANT_TYPE_NOT_SUPPORTED, HttpResponseStatus.BAD_REQUEST); } } else { _logger.info("Grant Type '" + tokenRequestDto.getGrantType() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_GRANT_TYPE, HttpResponseStatus.BAD_REQUEST); } } else { _logger.info("Request Redirect URI '" + tokenRequestDto.getRedirectUri() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST); } } catch (UnsupportedEncodingException e) { _logger.info("Request Redirect URI '" + tokenRequestDto.getRedirectUri() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST); } }
java
public static boolean validateTokenRequest(TokenRequestDto tokenRequestDto, OAuthApplicationDto oAuthApplicationDto) { // basic check try { String decodedRedirectUri = java.net.URLDecoder.decode(tokenRequestDto.getRedirectUri(), "UTF-8"); if (StringUtils.isNotBlank(oAuthApplicationDto.getRedirectUri()) && oAuthApplicationDto.getRedirectUri().equals(decodedRedirectUri)) { if (StringUtils.isNotBlank(tokenRequestDto.getGrantType())) { if (OAuthFields.AUTHORIZATION_CODE.equals(tokenRequestDto.getGrantType())) { return true; } else { _logger.info("Grant Type '" + tokenRequestDto.getGrantType() + "' is not supported"); throw new OAuthException(ResponseCodes.GRANT_TYPE_NOT_SUPPORTED, HttpResponseStatus.BAD_REQUEST); } } else { _logger.info("Grant Type '" + tokenRequestDto.getGrantType() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_GRANT_TYPE, HttpResponseStatus.BAD_REQUEST); } } else { _logger.info("Request Redirect URI '" + tokenRequestDto.getRedirectUri() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST); } } catch (UnsupportedEncodingException e) { _logger.info("Request Redirect URI '" + tokenRequestDto.getRedirectUri() + "' mismatch"); throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST); } }
[ "public", "static", "boolean", "validateTokenRequest", "(", "TokenRequestDto", "tokenRequestDto", ",", "OAuthApplicationDto", "oAuthApplicationDto", ")", "{", "// basic check", "try", "{", "String", "decodedRedirectUri", "=", "java", ".", "net", ".", "URLDecoder", ".", ...
Validates Token Request @param tokenRequestDto Given Application DTO properties @param oAuthApplicationDto Expected Application DTO properties @return Returns boolean or OAuth Exception
[ "Validates", "Token", "Request" ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/business/oauth/AuthRequestHelper.java#L109-L134
op4j/op4j
src/main/java/org/op4j/Op.java
Op.onArrayFor
public static <T> Level0ArrayOperator<Boolean[],Boolean> onArrayFor(final Boolean... elements) { return onArrayOf(Types.BOOLEAN, VarArgsUtil.asRequiredObjectArray(elements)); }
java
public static <T> Level0ArrayOperator<Boolean[],Boolean> onArrayFor(final Boolean... elements) { return onArrayOf(Types.BOOLEAN, VarArgsUtil.asRequiredObjectArray(elements)); }
[ "public", "static", "<", "T", ">", "Level0ArrayOperator", "<", "Boolean", "[", "]", ",", "Boolean", ">", "onArrayFor", "(", "final", "Boolean", "...", "elements", ")", "{", "return", "onArrayOf", "(", "Types", ".", "BOOLEAN", ",", "VarArgsUtil", ".", "asRe...
<p> Creates an array with the specified elements and an <i>operation expression</i> on it. </p> @param elements the elements of the array being created @return an operator, ready for chaining
[ "<p", ">", "Creates", "an", "array", "with", "the", "specified", "elements", "and", "an", "<i", ">", "operation", "expression<", "/", "i", ">", "on", "it", ".", "<", "/", "p", ">" ]
train
https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/Op.java#L971-L973
infinispan/infinispan
server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/PrepareCoordinator.java
PrepareCoordinator.forgetTransaction
private void forgetTransaction(GlobalTransaction gtx, RpcManager rpcManager, CommandsFactory factory) { TxCompletionNotificationCommand cmd = factory.buildTxCompletionNotificationCommand(xid, gtx); rpcManager.sendToAll(cmd, DeliverOrder.NONE); perCacheTxTable.removeLocalTx(xid); globalTxTable.remove(cacheXid); }
java
private void forgetTransaction(GlobalTransaction gtx, RpcManager rpcManager, CommandsFactory factory) { TxCompletionNotificationCommand cmd = factory.buildTxCompletionNotificationCommand(xid, gtx); rpcManager.sendToAll(cmd, DeliverOrder.NONE); perCacheTxTable.removeLocalTx(xid); globalTxTable.remove(cacheXid); }
[ "private", "void", "forgetTransaction", "(", "GlobalTransaction", "gtx", ",", "RpcManager", "rpcManager", ",", "CommandsFactory", "factory", ")", "{", "TxCompletionNotificationCommand", "cmd", "=", "factory", ".", "buildTxCompletionNotificationCommand", "(", "xid", ",", ...
Forgets the transaction cluster-wise and from global and local transaction tables.
[ "Forgets", "the", "transaction", "cluster", "-", "wise", "and", "from", "global", "and", "local", "transaction", "tables", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/tx/PrepareCoordinator.java#L240-L245
fuwjax/ev-oss
funco/src/main/java/org/fuwjax/oss/util/io/Files2.java
Files2.copy
public static void copy(final Path source, final Path dest) throws IOException { if(Files.exists(source)) { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, resolve(dest, relativize(source, file))); return super.visitFile(file, attrs); } @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(resolve(dest, relativize(source, dir))); return super.preVisitDirectory(dir, attrs); } }); } }
java
public static void copy(final Path source, final Path dest) throws IOException { if(Files.exists(source)) { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, resolve(dest, relativize(source, file))); return super.visitFile(file, attrs); } @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(resolve(dest, relativize(source, dir))); return super.preVisitDirectory(dir, attrs); } }); } }
[ "public", "static", "void", "copy", "(", "final", "Path", "source", ",", "final", "Path", "dest", ")", "throws", "IOException", "{", "if", "(", "Files", ".", "exists", "(", "source", ")", ")", "{", "Files", ".", "walkFileTree", "(", "source", ",", "new...
Copies a source to a destination, works recursively on directories. @param source the source path @param dest the destination path @throws IOException if the source cannot be copied to the destination
[ "Copies", "a", "source", "to", "a", "destination", "works", "recursively", "on", "directories", "." ]
train
https://github.com/fuwjax/ev-oss/blob/cbd88592e9b2fa9547c3bdd41e52e790061a2253/funco/src/main/java/org/fuwjax/oss/util/io/Files2.java#L36-L52
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/pathfinding/PathfindableModel.java
PathfindableModel.checkArrivedX
private boolean checkArrivedX(double extrp, double sx, double dx) { final double x = transformable.getX(); if (sx < 0 && x <= dx || sx >= 0 && x >= dx) { transformable.moveLocation(extrp, dx - x, 0); return true; } return false; }
java
private boolean checkArrivedX(double extrp, double sx, double dx) { final double x = transformable.getX(); if (sx < 0 && x <= dx || sx >= 0 && x >= dx) { transformable.moveLocation(extrp, dx - x, 0); return true; } return false; }
[ "private", "boolean", "checkArrivedX", "(", "double", "extrp", ",", "double", "sx", ",", "double", "dx", ")", "{", "final", "double", "x", "=", "transformable", ".", "getX", "(", ")", ";", "if", "(", "sx", "<", "0", "&&", "x", "<=", "dx", "||", "sx...
Check if the pathfindable is horizontally arrived. @param extrp The extrapolation value. @param sx The horizontal speed. @param dx The horizontal tile destination. @return <code>true</code> if arrived, <code>false</code> else.
[ "Check", "if", "the", "pathfindable", "is", "horizontally", "arrived", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/pathfinding/PathfindableModel.java#L363-L372
avianey/facebook-api-android-maven
facebook/src/main/java/com/facebook/android/Facebook.java
Facebook.setTokenFromCache
@Deprecated public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) { checkUserSession("setTokenFromCache"); synchronized (this.lock) { this.accessToken = accessToken; accessExpiresMillisecondsAfterEpoch = accessExpires; lastAccessUpdateMillisecondsAfterEpoch = lastAccessUpdate; } }
java
@Deprecated public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) { checkUserSession("setTokenFromCache"); synchronized (this.lock) { this.accessToken = accessToken; accessExpiresMillisecondsAfterEpoch = accessExpires; lastAccessUpdateMillisecondsAfterEpoch = lastAccessUpdate; } }
[ "@", "Deprecated", "public", "void", "setTokenFromCache", "(", "String", "accessToken", ",", "long", "accessExpires", ",", "long", "lastAccessUpdate", ")", "{", "checkUserSession", "(", "\"setTokenFromCache\"", ")", ";", "synchronized", "(", "this", ".", "lock", "...
Restore the token, expiration time, and last update time from cached values. These should be values obtained from getAccessToken(), getAccessExpires, and getLastAccessUpdate() respectively. <p/> This method is deprecated. See {@link Facebook} and {@link Session} for more info. @param accessToken - access token @param accessExpires - access token expiration time @param lastAccessUpdate - timestamp of the last token update
[ "Restore", "the", "token", "expiration", "time", "and", "last", "update", "time", "from", "cached", "values", ".", "These", "should", "be", "values", "obtained", "from", "getAccessToken", "()", "getAccessExpires", "and", "getLastAccessUpdate", "()", "respectively", ...
train
https://github.com/avianey/facebook-api-android-maven/blob/ae6c7aa7ae45739ee19f18c1983e05f7e35b9ede/facebook/src/main/java/com/facebook/android/Facebook.java#L1035-L1043
looly/hutool
hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java
MapUtil.reverse
public static <T> Map<T, T> reverse(Map<T, T> map) { return filter(map, new Editor<Map.Entry<T, T>>() { @Override public Entry<T, T> edit(final Entry<T, T> t) { return new Entry<T, T>() { @Override public T getKey() { return t.getValue(); } @Override public T getValue() { return t.getKey(); } @Override public T setValue(T value) { throw new UnsupportedOperationException("Unsupported setValue method !"); } }; } }); }
java
public static <T> Map<T, T> reverse(Map<T, T> map) { return filter(map, new Editor<Map.Entry<T, T>>() { @Override public Entry<T, T> edit(final Entry<T, T> t) { return new Entry<T, T>() { @Override public T getKey() { return t.getValue(); } @Override public T getValue() { return t.getKey(); } @Override public T setValue(T value) { throw new UnsupportedOperationException("Unsupported setValue method !"); } }; } }); }
[ "public", "static", "<", "T", ">", "Map", "<", "T", ",", "T", ">", "reverse", "(", "Map", "<", "T", ",", "T", ">", "map", ")", "{", "return", "filter", "(", "map", ",", "new", "Editor", "<", "Map", ".", "Entry", "<", "T", ",", "T", ">", ">"...
Map的键和值互换 @param <T> 键和值类型 @param map Map对象,键值类型必须一致 @return 互换后的Map @since 3.2.2
[ "Map的键和值互换" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L579-L602
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-graph/src/main/java/org/deeplearning4j/graph/data/GraphLoader.java
GraphLoader.loadWeightedEdgeListFile
public static Graph<String, Double> loadWeightedEdgeListFile(String path, int numVertices, String delim, boolean directed, boolean allowMultipleEdges, String... ignoreLinesStartingWith) throws IOException { Graph<String, Double> graph = new Graph<>(numVertices, allowMultipleEdges, new StringVertexFactory()); EdgeLineProcessor<Double> lineProcessor = new WeightedEdgeLineProcessor(delim, directed, ignoreLinesStartingWith); try (BufferedReader br = new BufferedReader(new FileReader(new File(path)))) { String line; while ((line = br.readLine()) != null) { Edge<Double> edge = lineProcessor.processLine(line); if (edge != null) { graph.addEdge(edge); } } } return graph; }
java
public static Graph<String, Double> loadWeightedEdgeListFile(String path, int numVertices, String delim, boolean directed, boolean allowMultipleEdges, String... ignoreLinesStartingWith) throws IOException { Graph<String, Double> graph = new Graph<>(numVertices, allowMultipleEdges, new StringVertexFactory()); EdgeLineProcessor<Double> lineProcessor = new WeightedEdgeLineProcessor(delim, directed, ignoreLinesStartingWith); try (BufferedReader br = new BufferedReader(new FileReader(new File(path)))) { String line; while ((line = br.readLine()) != null) { Edge<Double> edge = lineProcessor.processLine(line); if (edge != null) { graph.addEdge(edge); } } } return graph; }
[ "public", "static", "Graph", "<", "String", ",", "Double", ">", "loadWeightedEdgeListFile", "(", "String", "path", ",", "int", "numVertices", ",", "String", "delim", ",", "boolean", "directed", ",", "boolean", "allowMultipleEdges", ",", "String", "...", "ignoreL...
Method for loading a weighted graph from an edge list file, where each edge (inc. weight) is represented by a single line. Graph may be directed or undirected<br> This method assumes that edges are of the format: {@code fromIndex<delim>toIndex<delim>edgeWeight} where {@code <delim>} is the delimiter. @param path Path to the edge list file @param numVertices The number of vertices in the graph @param delim The delimiter used in the file (typically: "," or " " etc) @param directed whether the edges should be treated as directed (true) or undirected (false) @param allowMultipleEdges If set to false, the graph will not allow multiple edges between any two vertices to exist. However, checking for duplicates during graph loading can be costly, so use allowMultipleEdges=true when possible. @param ignoreLinesStartingWith Starting characters for comment lines. May be null. For example: "//" or "#" @return The graph @throws IOException
[ "Method", "for", "loading", "a", "weighted", "graph", "from", "an", "edge", "list", "file", "where", "each", "edge", "(", "inc", ".", "weight", ")", "is", "represented", "by", "a", "single", "line", ".", "Graph", "may", "be", "directed", "or", "undirecte...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-graph/src/main/java/org/deeplearning4j/graph/data/GraphLoader.java#L117-L134
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WProgressBarRenderer.java
WProgressBarRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WProgressBar progressBar = (WProgressBar) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("html:progress"); xml.appendAttribute("id", component.getId()); xml.appendAttribute("class", getHtmlClass(progressBar)); xml.appendOptionalAttribute("hidden", progressBar.isHidden(), "hidden"); xml.appendOptionalAttribute("title", progressBar.getToolTip()); xml.appendOptionalAttribute("aria-label", progressBar.getAccessibleText()); xml.appendAttribute("value", progressBar.getValue()); xml.appendOptionalAttribute("max", progressBar.getMax() > 0, progressBar.getMax()); xml.appendClose(); xml.appendEndTag("html:progress"); }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WProgressBar progressBar = (WProgressBar) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("html:progress"); xml.appendAttribute("id", component.getId()); xml.appendAttribute("class", getHtmlClass(progressBar)); xml.appendOptionalAttribute("hidden", progressBar.isHidden(), "hidden"); xml.appendOptionalAttribute("title", progressBar.getToolTip()); xml.appendOptionalAttribute("aria-label", progressBar.getAccessibleText()); xml.appendAttribute("value", progressBar.getValue()); xml.appendOptionalAttribute("max", progressBar.getMax() > 0, progressBar.getMax()); xml.appendClose(); xml.appendEndTag("html:progress"); }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WProgressBar", "progressBar", "=", "(", "WProgressBar", ")", "component", ";", "XmlStringBuilder", "xml", "=", ...
Paints the given WProgressBar. @param component the WProgressBar to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "WProgressBar", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WProgressBarRenderer.java#L23-L38
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/AnimationConfig.java
AnimationConfig.exports
public static void exports(Xml root, Animation animation) { Check.notNull(root); Check.notNull(animation); final Xml node = root.createChild(ANIMATION); node.writeString(ANIMATION_NAME, animation.getName()); node.writeInteger(ANIMATION_START, animation.getFirst()); node.writeInteger(ANIMATION_END, animation.getLast()); node.writeDouble(ANIMATION_SPEED, animation.getSpeed()); node.writeBoolean(ANIMATION_REVERSED, animation.hasReverse()); node.writeBoolean(ANIMATION_REPEAT, animation.hasRepeat()); }
java
public static void exports(Xml root, Animation animation) { Check.notNull(root); Check.notNull(animation); final Xml node = root.createChild(ANIMATION); node.writeString(ANIMATION_NAME, animation.getName()); node.writeInteger(ANIMATION_START, animation.getFirst()); node.writeInteger(ANIMATION_END, animation.getLast()); node.writeDouble(ANIMATION_SPEED, animation.getSpeed()); node.writeBoolean(ANIMATION_REVERSED, animation.hasReverse()); node.writeBoolean(ANIMATION_REPEAT, animation.hasRepeat()); }
[ "public", "static", "void", "exports", "(", "Xml", "root", ",", "Animation", "animation", ")", "{", "Check", ".", "notNull", "(", "root", ")", ";", "Check", ".", "notNull", "(", "animation", ")", ";", "final", "Xml", "node", "=", "root", ".", "createCh...
Create an XML node from an animation. @param root The node root (must not be <code>null</code>). @param animation The animation reference (must not be <code>null</code>). @throws LionEngineException If error on writing.
[ "Create", "an", "XML", "node", "from", "an", "animation", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/AnimationConfig.java#L124-L136
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/widgets/CmsDependentSelectWidget.java
CmsDependentSelectWidget.replaceOptions
private void replaceOptions(LinkedHashMap<String, String> options) { String oldValue = m_selectBox.getFormValueAsString(); for (String additionalValue : new String[] {oldValue, m_externalValue}) { if (!options.containsKey(additionalValue)) { options.put(additionalValue, additionalValue); } } if (options.containsKey("")) { options.put( "", org.opencms.gwt.client.Messages.get().key( org.opencms.gwt.client.Messages.GUI_SELECTBOX_EMPTY_SELECTION_0)); } m_selectBox.setItems(options); m_selectBox.setFormValueAsString(oldValue); }
java
private void replaceOptions(LinkedHashMap<String, String> options) { String oldValue = m_selectBox.getFormValueAsString(); for (String additionalValue : new String[] {oldValue, m_externalValue}) { if (!options.containsKey(additionalValue)) { options.put(additionalValue, additionalValue); } } if (options.containsKey("")) { options.put( "", org.opencms.gwt.client.Messages.get().key( org.opencms.gwt.client.Messages.GUI_SELECTBOX_EMPTY_SELECTION_0)); } m_selectBox.setItems(options); m_selectBox.setFormValueAsString(oldValue); }
[ "private", "void", "replaceOptions", "(", "LinkedHashMap", "<", "String", ",", "String", ">", "options", ")", "{", "String", "oldValue", "=", "m_selectBox", ".", "getFormValueAsString", "(", ")", ";", "for", "(", "String", "additionalValue", ":", "new", "Strin...
Replaces the select options with the given options.<p> @param options the map of select options (keys are option values, values are option descriptions)
[ "Replaces", "the", "select", "options", "with", "the", "given", "options", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/widgets/CmsDependentSelectWidget.java#L289-L305
kiswanij/jk-util
src/main/java/com/jk/util/JKHttpUtil.java
JKHttpUtil.readUrlAsObject
public static <T> T readUrlAsObject(String url, Class<T> type) { String contents = getUrlContents(url); ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); try { return mapper.readValue(contents, type); } catch (IOException e) { JK.throww(e); return null; } }
java
public static <T> T readUrlAsObject(String url, Class<T> type) { String contents = getUrlContents(url); ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(); try { return mapper.readValue(contents, type); } catch (IOException e) { JK.throww(e); return null; } }
[ "public", "static", "<", "T", ">", "T", "readUrlAsObject", "(", "String", "url", ",", "Class", "<", "T", ">", "type", ")", "{", "String", "contents", "=", "getUrlContents", "(", "url", ")", ";", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ...
Read the given url contents, and try to create an object from the given type. @param <T> the generic type @param url the url @param type the type @return the t
[ "Read", "the", "given", "url", "contents", "and", "try", "to", "create", "an", "object", "from", "the", "given", "type", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKHttpUtil.java#L221-L232
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/SchemaManager.java
SchemaManager.getSchemaHsqlNameNoThrow
public HsqlName getSchemaHsqlNameNoThrow(String name, HsqlName defaultName) { if (name == null) { return defaultSchemaHsqlName; } if (SqlInvariants.INFORMATION_SCHEMA.equals(name)) { return SqlInvariants.INFORMATION_SCHEMA_HSQLNAME; } Schema schema = ((Schema) schemaMap.get(name)); if (schema == null) { return defaultName; } return schema.name; }
java
public HsqlName getSchemaHsqlNameNoThrow(String name, HsqlName defaultName) { if (name == null) { return defaultSchemaHsqlName; } if (SqlInvariants.INFORMATION_SCHEMA.equals(name)) { return SqlInvariants.INFORMATION_SCHEMA_HSQLNAME; } Schema schema = ((Schema) schemaMap.get(name)); if (schema == null) { return defaultName; } return schema.name; }
[ "public", "HsqlName", "getSchemaHsqlNameNoThrow", "(", "String", "name", ",", "HsqlName", "defaultName", ")", "{", "if", "(", "name", "==", "null", ")", "{", "return", "defaultSchemaHsqlName", ";", "}", "if", "(", "SqlInvariants", ".", "INFORMATION_SCHEMA", ".",...
If schemaName is null, return the default schema name, else return the HsqlName object for the schema. If schemaName does not exist, return the defaultName provided. Not throwing the usual exception saves some throw-then-catch nonsense in the usual session setup.
[ "If", "schemaName", "is", "null", "return", "the", "default", "schema", "name", "else", "return", "the", "HsqlName", "object", "for", "the", "schema", ".", "If", "schemaName", "does", "not", "exist", "return", "the", "defaultName", "provided", ".", "Not", "t...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/SchemaManager.java#L1638-L1654
fuinorg/units4j
src/main/java/org/fuin/units4j/Units4JUtils.java
Units4JUtils.setPrivateField
public static void setPrivateField(final Object obj, final String name, final Object value) { try { final Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); field.set(obj, value); } catch (final Exception ex) { throw new RuntimeException("Couldn't set field '" + name + "' in class '" + obj.getClass() + "'", ex); } }
java
public static void setPrivateField(final Object obj, final String name, final Object value) { try { final Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); field.set(obj, value); } catch (final Exception ex) { throw new RuntimeException("Couldn't set field '" + name + "' in class '" + obj.getClass() + "'", ex); } }
[ "public", "static", "void", "setPrivateField", "(", "final", "Object", "obj", ",", "final", "String", "name", ",", "final", "Object", "value", ")", "{", "try", "{", "final", "Field", "field", "=", "obj", ".", "getClass", "(", ")", ".", "getDeclaredField", ...
Sets a private field in an object by using reflection. @param obj Object with the attribute to set. @param name Name of the attribute to set. @param value Value to set for the attribute.
[ "Sets", "a", "private", "field", "in", "an", "object", "by", "using", "reflection", "." ]
train
https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/Units4JUtils.java#L255-L263
blacklocus/metrics-cloudwatch
src/main/java/com/blacklocus/metrics/MetricNameBuilder.java
MetricNameBuilder.addDimension
public MetricNameBuilder addDimension(Dimension dimension, boolean permute) throws MetricsNameSyntaxException { return addDimension(dimension.getName(), dimension.getValue(), false); }
java
public MetricNameBuilder addDimension(Dimension dimension, boolean permute) throws MetricsNameSyntaxException { return addDimension(dimension.getName(), dimension.getValue(), false); }
[ "public", "MetricNameBuilder", "addDimension", "(", "Dimension", "dimension", ",", "boolean", "permute", ")", "throws", "MetricsNameSyntaxException", "{", "return", "addDimension", "(", "dimension", ".", "getName", "(", ")", ",", "dimension", ".", "getValue", "(", ...
Passes into {@link #addDimension(String, String, boolean)} @return this for chaining @throws MetricsNameSyntaxException on validation failure
[ "Passes", "into", "{", "@link", "#addDimension", "(", "String", "String", "boolean", ")", "}" ]
train
https://github.com/blacklocus/metrics-cloudwatch/blob/0554929b5729621c3d3ffd925284af174ab1dd32/src/main/java/com/blacklocus/metrics/MetricNameBuilder.java#L124-L126
tvesalainen/util
util/src/main/java/org/vesalainen/nio/file/attribute/PosixHelp.java
PosixHelp.setOwner
public static final void setOwner(String name, Path... files) throws IOException { if (supports("posix")) { for (Path file : files) { FileSystem fs = file.getFileSystem(); UserPrincipalLookupService upls = fs.getUserPrincipalLookupService(); UserPrincipal user = upls.lookupPrincipalByName(name); Files.setOwner(file, user); } } else { JavaLogging.getLogger(PosixHelp.class).warning("no owner support. setOwner(%s)", name); } }
java
public static final void setOwner(String name, Path... files) throws IOException { if (supports("posix")) { for (Path file : files) { FileSystem fs = file.getFileSystem(); UserPrincipalLookupService upls = fs.getUserPrincipalLookupService(); UserPrincipal user = upls.lookupPrincipalByName(name); Files.setOwner(file, user); } } else { JavaLogging.getLogger(PosixHelp.class).warning("no owner support. setOwner(%s)", name); } }
[ "public", "static", "final", "void", "setOwner", "(", "String", "name", ",", "Path", "...", "files", ")", "throws", "IOException", "{", "if", "(", "supports", "(", "\"posix\"", ")", ")", "{", "for", "(", "Path", "file", ":", "files", ")", "{", "FileSys...
Change user of given files. Works only in linux. @param name @param files @throws IOException @see java.nio.file.Files#setOwner(java.nio.file.Path, java.nio.file.attribute.UserPrincipal)
[ "Change", "user", "of", "given", "files", ".", "Works", "only", "in", "linux", "." ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/file/attribute/PosixHelp.java#L200-L216
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaStringGenerator.java
SibRaStringGenerator.addField
void addField(final String name, final Object value) throws IllegalStateException { checkNotCompleted(); _buffer.append(" <"); _buffer.append(name); _buffer.append("="); _buffer.append(value); _buffer.append(">"); }
java
void addField(final String name, final Object value) throws IllegalStateException { checkNotCompleted(); _buffer.append(" <"); _buffer.append(name); _buffer.append("="); _buffer.append(value); _buffer.append(">"); }
[ "void", "addField", "(", "final", "String", "name", ",", "final", "Object", "value", ")", "throws", "IllegalStateException", "{", "checkNotCompleted", "(", ")", ";", "_buffer", ".", "append", "(", "\" <\"", ")", ";", "_buffer", ".", "append", "(", "name", ...
Adds a string representation of the given object field. @param name the name of the field @param value the value of the field @throws IllegalStateException if the string representation has already been completed
[ "Adds", "a", "string", "representation", "of", "the", "given", "object", "field", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaStringGenerator.java#L75-L85
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java
HtmlTree.UL
public static HtmlTree UL(HtmlStyle styleClass, Content first, Content... more) { HtmlTree htmlTree = new HtmlTree(HtmlTag.UL); htmlTree.addContent(nullCheck(first)); for (Content c : more) { htmlTree.addContent(nullCheck(c)); } htmlTree.addStyle(nullCheck(styleClass)); return htmlTree; }
java
public static HtmlTree UL(HtmlStyle styleClass, Content first, Content... more) { HtmlTree htmlTree = new HtmlTree(HtmlTag.UL); htmlTree.addContent(nullCheck(first)); for (Content c : more) { htmlTree.addContent(nullCheck(c)); } htmlTree.addStyle(nullCheck(styleClass)); return htmlTree; }
[ "public", "static", "HtmlTree", "UL", "(", "HtmlStyle", "styleClass", ",", "Content", "first", ",", "Content", "...", "more", ")", "{", "HtmlTree", "htmlTree", "=", "new", "HtmlTree", "(", "HtmlTag", ".", "UL", ")", ";", "htmlTree", ".", "addContent", "(",...
Generates a UL tag with the style class attribute and some content. @param styleClass style for the tag @param first initial content to be added @param more a series of additional content nodes to be added @return an HtmlTree object for the UL tag
[ "Generates", "a", "UL", "tag", "with", "the", "style", "class", "attribute", "and", "some", "content", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/markup/HtmlTree.java#L866-L874
assertthat/selenium-shutterbug
src/main/java/com/assertthat/selenium_shutterbug/core/Shutterbug.java
Shutterbug.shootPage
public static PageSnapshot shootPage(WebDriver driver, ScrollStrategy scroll, boolean useDevicePixelRatio) { return shootPage(driver,scroll,0,useDevicePixelRatio); }
java
public static PageSnapshot shootPage(WebDriver driver, ScrollStrategy scroll, boolean useDevicePixelRatio) { return shootPage(driver,scroll,0,useDevicePixelRatio); }
[ "public", "static", "PageSnapshot", "shootPage", "(", "WebDriver", "driver", ",", "ScrollStrategy", "scroll", ",", "boolean", "useDevicePixelRatio", ")", "{", "return", "shootPage", "(", "driver", ",", "scroll", ",", "0", ",", "useDevicePixelRatio", ")", ";", "}...
To be used when screen shooting the page and need to scroll while making screen shots, either vertically or horizontally or both directions (Chrome). @param driver WebDriver instance @param scroll ScrollStrategy How you need to scroll @param useDevicePixelRatio whether or not take into account device pixel ratio @return PageSnapshot instance
[ "To", "be", "used", "when", "screen", "shooting", "the", "page", "and", "need", "to", "scroll", "while", "making", "screen", "shots", "either", "vertically", "or", "horizontally", "or", "both", "directions", "(", "Chrome", ")", "." ]
train
https://github.com/assertthat/selenium-shutterbug/blob/770d9b92423200d262c9ab70e40405921d81e262/src/main/java/com/assertthat/selenium_shutterbug/core/Shutterbug.java#L85-L87
looly/hutool
hutool-core/src/main/java/cn/hutool/core/builder/HashCodeBuilder.java
HashCodeBuilder.reflectionHashCode
public static <T> int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final T object, final boolean testTransients, final Class<? super T> reflectUpToClass, final String... excludeFields) { if (object == null) { throw new IllegalArgumentException("The object to build a hash code for must not be null"); } final HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber); Class<?> clazz = object.getClass(); reflectionAppend(object, clazz, builder, testTransients, excludeFields); while (clazz.getSuperclass() != null && clazz != reflectUpToClass) { clazz = clazz.getSuperclass(); reflectionAppend(object, clazz, builder, testTransients, excludeFields); } return builder.toHashCode(); }
java
public static <T> int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final T object, final boolean testTransients, final Class<? super T> reflectUpToClass, final String... excludeFields) { if (object == null) { throw new IllegalArgumentException("The object to build a hash code for must not be null"); } final HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber); Class<?> clazz = object.getClass(); reflectionAppend(object, clazz, builder, testTransients, excludeFields); while (clazz.getSuperclass() != null && clazz != reflectUpToClass) { clazz = clazz.getSuperclass(); reflectionAppend(object, clazz, builder, testTransients, excludeFields); } return builder.toHashCode(); }
[ "public", "static", "<", "T", ">", "int", "reflectionHashCode", "(", "final", "int", "initialNonZeroOddNumber", ",", "final", "int", "multiplierNonZeroOddNumber", ",", "final", "T", "object", ",", "final", "boolean", "testTransients", ",", "final", "Class", "<", ...
<p> Uses reflection to build a valid hash code from the fields of {@code object}. </p> <p> It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. </p> <p> If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>. </p> <p> Static fields will not be included. Superclass fields will be included up to and including the specified superclass. A null superclass is treated as java.lang.Object. </p> <p> Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, however this is not vital. Prime numbers are preferred, especially for the multiplier. </p> @param <T> the type of the object involved @param initialNonZeroOddNumber a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code @param multiplierNonZeroOddNumber a non-zero, odd number used as the multiplier @param object the Object to create a <code>hashCode</code> for @param testTransients whether to include transient fields @param reflectUpToClass the superclass to reflect up to (inclusive), may be <code>null</code> @param excludeFields array of field names to exclude from use in calculation of hash code @return int hash code @throws IllegalArgumentException if the Object is <code>null</code> @throws IllegalArgumentException if the number is zero or even @since 2.0
[ "<p", ">", "Uses", "reflection", "to", "build", "a", "valid", "hash", "code", "from", "the", "fields", "of", "{", "@code", "object", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/builder/HashCodeBuilder.java#L331-L345
line/armeria
core/src/main/java/com/linecorp/armeria/common/stream/AbstractStreamMessage.java
AbstractStreamMessage.cleanupQueue
void cleanupQueue(SubscriptionImpl subscription, Queue<Object> queue) { final Throwable cause = ClosedPublisherException.get(); for (;;) { final Object e = queue.poll(); if (e == null) { break; } try { if (e instanceof CloseEvent) { notifySubscriberOfCloseEvent(subscription, (CloseEvent) e); continue; } if (e instanceof CompletableFuture) { ((CompletableFuture<?>) e).completeExceptionally(cause); } @SuppressWarnings("unchecked") final T obj = (T) e; onRemoval(obj); } finally { ReferenceCountUtil.safeRelease(e); } } }
java
void cleanupQueue(SubscriptionImpl subscription, Queue<Object> queue) { final Throwable cause = ClosedPublisherException.get(); for (;;) { final Object e = queue.poll(); if (e == null) { break; } try { if (e instanceof CloseEvent) { notifySubscriberOfCloseEvent(subscription, (CloseEvent) e); continue; } if (e instanceof CompletableFuture) { ((CompletableFuture<?>) e).completeExceptionally(cause); } @SuppressWarnings("unchecked") final T obj = (T) e; onRemoval(obj); } finally { ReferenceCountUtil.safeRelease(e); } } }
[ "void", "cleanupQueue", "(", "SubscriptionImpl", "subscription", ",", "Queue", "<", "Object", ">", "queue", ")", "{", "final", "Throwable", "cause", "=", "ClosedPublisherException", ".", "get", "(", ")", ";", "for", "(", ";", ";", ")", "{", "final", "Objec...
Helper method for the common case of cleaning up all elements in a queue when shutting down the stream.
[ "Helper", "method", "for", "the", "common", "case", "of", "cleaning", "up", "all", "elements", "in", "a", "queue", "when", "shutting", "down", "the", "stream", "." ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/common/stream/AbstractStreamMessage.java#L190-L215
vipshop/vjtools
vjmap/src/main/java/com/vip/vjtools/vjmap/VJMap.java
VJMap.triggerGc
private static void triggerGc(Integer pid) { VirtualMachine vm = null; try { vm = VirtualMachine.attach(String.valueOf(pid)); HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm; try (InputStream in = hvm.executeJCmd("GC.run");) { byte b[] = new byte[256]; int n; do { n = in.read(b); if (n > 0) { String s = new String(b, 0, n, "UTF-8"); tty.print(s); } } while (n > 0); tty.println(); } } catch (Exception e) { tty.println(e.getMessage()); } finally { if (vm != null) { try { vm.detach(); } catch (IOException e) { tty.println(e.getMessage()); } } } }
java
private static void triggerGc(Integer pid) { VirtualMachine vm = null; try { vm = VirtualMachine.attach(String.valueOf(pid)); HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm; try (InputStream in = hvm.executeJCmd("GC.run");) { byte b[] = new byte[256]; int n; do { n = in.read(b); if (n > 0) { String s = new String(b, 0, n, "UTF-8"); tty.print(s); } } while (n > 0); tty.println(); } } catch (Exception e) { tty.println(e.getMessage()); } finally { if (vm != null) { try { vm.detach(); } catch (IOException e) { tty.println(e.getMessage()); } } } }
[ "private", "static", "void", "triggerGc", "(", "Integer", "pid", ")", "{", "VirtualMachine", "vm", "=", "null", ";", "try", "{", "vm", "=", "VirtualMachine", ".", "attach", "(", "String", ".", "valueOf", "(", "pid", ")", ")", ";", "HotSpotVirtualMachine", ...
Trigger a remote gc using HotSpotVirtualMachine, inspired by jcmd's source code. @param pid
[ "Trigger", "a", "remote", "gc", "using", "HotSpotVirtualMachine", "inspired", "by", "jcmd", "s", "source", "code", "." ]
train
https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjmap/src/main/java/com/vip/vjtools/vjmap/VJMap.java#L243-L271
lessthanoptimal/BoofCV
integration/boofcv-swing/src/main/java/boofcv/gui/binary/VisualizeBinaryData.java
VisualizeBinaryData.renderContours
public static BufferedImage renderContours(List<Contour> contours , int colorExternal, int colorInternal , int width , int height , BufferedImage out) { if( out == null ) { out = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); } else { Graphics2D g2 = out.createGraphics(); g2.setColor(Color.BLACK); g2.fillRect(0,0,width,height); } for( Contour c : contours ) { for(Point2D_I32 p : c.external ) { out.setRGB(p.x,p.y,colorExternal); } for( List<Point2D_I32> l : c.internal ) { for( Point2D_I32 p : l ) { out.setRGB(p.x,p.y,colorInternal); } } } return out; }
java
public static BufferedImage renderContours(List<Contour> contours , int colorExternal, int colorInternal , int width , int height , BufferedImage out) { if( out == null ) { out = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); } else { Graphics2D g2 = out.createGraphics(); g2.setColor(Color.BLACK); g2.fillRect(0,0,width,height); } for( Contour c : contours ) { for(Point2D_I32 p : c.external ) { out.setRGB(p.x,p.y,colorExternal); } for( List<Point2D_I32> l : c.internal ) { for( Point2D_I32 p : l ) { out.setRGB(p.x,p.y,colorInternal); } } } return out; }
[ "public", "static", "BufferedImage", "renderContours", "(", "List", "<", "Contour", ">", "contours", ",", "int", "colorExternal", ",", "int", "colorInternal", ",", "int", "width", ",", "int", "height", ",", "BufferedImage", "out", ")", "{", "if", "(", "out",...
Draws contours. Internal and external contours are different user specified colors. @param contours List of contours @param colorExternal RGB color @param colorInternal RGB color @param width Image width @param height Image height @param out (Optional) storage for output image @return Rendered contours
[ "Draws", "contours", ".", "Internal", "and", "external", "contours", "are", "different", "user", "specified", "colors", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-swing/src/main/java/boofcv/gui/binary/VisualizeBinaryData.java#L77-L100
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/Category.java
Category.l7dlog
public void l7dlog(Priority priority, String key, Object[] params, Throwable t) { if (repository.isDisabled(priority.level)) { return; } if (priority.isGreaterOrEqual(this.getEffectiveLevel())) { String pattern = getResourceBundleString(key); String msg; if (pattern == null) msg = key; else msg = java.text.MessageFormat.format(pattern, params); forcedLog(FQCN, priority, msg, t); } }
java
public void l7dlog(Priority priority, String key, Object[] params, Throwable t) { if (repository.isDisabled(priority.level)) { return; } if (priority.isGreaterOrEqual(this.getEffectiveLevel())) { String pattern = getResourceBundleString(key); String msg; if (pattern == null) msg = key; else msg = java.text.MessageFormat.format(pattern, params); forcedLog(FQCN, priority, msg, t); } }
[ "public", "void", "l7dlog", "(", "Priority", "priority", ",", "String", "key", ",", "Object", "[", "]", "params", ",", "Throwable", "t", ")", "{", "if", "(", "repository", ".", "isDisabled", "(", "priority", ".", "level", ")", ")", "{", "return", ";", ...
Log a localized and parameterized message. First, the user supplied <code>key</code> is searched in the resource bundle. Next, the resulting pattern is formatted using {@link java.text.MessageFormat#format(String,Object[])} method with the user supplied object array <code>params</code>. @since 0.8.4
[ "Log", "a", "localized", "and", "parameterized", "message", ".", "First", "the", "user", "supplied", "<code", ">", "key<", "/", "code", ">", "is", "searched", "in", "the", "resource", "bundle", ".", "Next", "the", "resulting", "pattern", "is", "formatted", ...
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/Category.java#L674-L687
michael-rapp/AndroidMaterialDialog
library/src/main/java/de/mrapp/android/dialog/AbstractMaterialDialog.java
AbstractMaterialDialog.createCanceledOnTouchListener
private View.OnTouchListener createCanceledOnTouchListener() { return new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(final View v, final MotionEvent event) { return isCanceledOnTouchOutside() && !isFullscreen() && onCanceledOnTouchOutside(); } }; }
java
private View.OnTouchListener createCanceledOnTouchListener() { return new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(final View v, final MotionEvent event) { return isCanceledOnTouchOutside() && !isFullscreen() && onCanceledOnTouchOutside(); } }; }
[ "private", "View", ".", "OnTouchListener", "createCanceledOnTouchListener", "(", ")", "{", "return", "new", "View", ".", "OnTouchListener", "(", ")", "{", "@", "SuppressLint", "(", "\"ClickableViewAccessibility\"", ")", "@", "Override", "public", "boolean", "onTouch...
Creates and returns a listener, which allows to cancel the dialog, when touched outside the window. @return The listener, which has been created, as an instance of the type {@link View.OnTouchListener}
[ "Creates", "and", "returns", "a", "listener", "which", "allows", "to", "cancel", "the", "dialog", "when", "touched", "outside", "the", "window", "." ]
train
https://github.com/michael-rapp/AndroidMaterialDialog/blob/8990eed72ee5f5a9720836ee708f71ac0d43053b/library/src/main/java/de/mrapp/android/dialog/AbstractMaterialDialog.java#L94-L104
petergeneric/stdlib
guice/webapp/src/main/java/com/peterphi/std/guice/web/HttpCallContext.java
HttpCallContext.set
public static HttpCallContext set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) { final HttpCallContext ctx = new HttpCallContext(generateTraceId(request), request, response, servletContext); contexts.set(ctx); return ctx; }
java
public static HttpCallContext set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) { final HttpCallContext ctx = new HttpCallContext(generateTraceId(request), request, response, servletContext); contexts.set(ctx); return ctx; }
[ "public", "static", "HttpCallContext", "set", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "ServletContext", "servletContext", ")", "{", "final", "HttpCallContext", "ctx", "=", "new", "HttpCallContext", "(", "generateTraceId", "(", ...
Creates and associates an HttpCallContext with the current Thread @param request @param response @return
[ "Creates", "and", "associates", "an", "HttpCallContext", "with", "the", "current", "Thread" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/guice/webapp/src/main/java/com/peterphi/std/guice/web/HttpCallContext.java#L70-L77
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/result/EvaluationResult.java
EvaluationResult.findOrCreate
public static EvaluationResult findOrCreate(ResultHierarchy hierarchy, Result parent, String name, String shortname) { ArrayList<EvaluationResult> ers = ResultUtil.filterResults(hierarchy, parent, EvaluationResult.class); EvaluationResult ev = null; for(EvaluationResult e : ers) { if(shortname.equals(e.getShortName())) { ev = e; break; } } if(ev == null) { ev = new EvaluationResult(name, shortname); hierarchy.add(parent, ev); } return ev; }
java
public static EvaluationResult findOrCreate(ResultHierarchy hierarchy, Result parent, String name, String shortname) { ArrayList<EvaluationResult> ers = ResultUtil.filterResults(hierarchy, parent, EvaluationResult.class); EvaluationResult ev = null; for(EvaluationResult e : ers) { if(shortname.equals(e.getShortName())) { ev = e; break; } } if(ev == null) { ev = new EvaluationResult(name, shortname); hierarchy.add(parent, ev); } return ev; }
[ "public", "static", "EvaluationResult", "findOrCreate", "(", "ResultHierarchy", "hierarchy", ",", "Result", "parent", ",", "String", "name", ",", "String", "shortname", ")", "{", "ArrayList", "<", "EvaluationResult", ">", "ers", "=", "ResultUtil", ".", "filterResu...
Find or create an evaluation result. @param hierarchy Result hierarchy. @param parent Parent result @param name Long name @param shortname Short name @return Evaluation result
[ "Find", "or", "create", "an", "evaluation", "result", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/result/EvaluationResult.java#L143-L157
hugegraph/hugegraph-common
src/main/java/com/baidu/hugegraph/util/VersionUtil.java
VersionUtil.gte
public static boolean gte(String version, String other) { E.checkArgumentNotNull(version, "The version to match is null"); return new Version(version).compareTo(new Version(other)) >= 0; }
java
public static boolean gte(String version, String other) { E.checkArgumentNotNull(version, "The version to match is null"); return new Version(version).compareTo(new Version(other)) >= 0; }
[ "public", "static", "boolean", "gte", "(", "String", "version", ",", "String", "other", ")", "{", "E", ".", "checkArgumentNotNull", "(", "version", ",", "\"The version to match is null\"", ")", ";", "return", "new", "Version", "(", "version", ")", ".", "compar...
Compare if a version is greater than the other one (inclusive) @param version The version to be compared @param other The lower bound of the range @return true if it's greater than the other, otherwise false
[ "Compare", "if", "a", "version", "is", "greater", "than", "the", "other", "one", "(", "inclusive", ")" ]
train
https://github.com/hugegraph/hugegraph-common/blob/1eb2414134b639a13f68ca352c1b3eb2d956e7b2/src/main/java/com/baidu/hugegraph/util/VersionUtil.java#L50-L53
pravega/pravega
segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/LogMetadata.java
LogMetadata.addLedger
LogMetadata addLedger(long ledgerId) { Preconditions.checkState(this.enabled, "Log is not enabled. Cannot perform any modifications on it."); // Copy existing ledgers. List<LedgerMetadata> newLedgers = new ArrayList<>(this.ledgers.size() + 1); newLedgers.addAll(this.ledgers); // Create and add metadata for the new ledger. int sequence = this.ledgers.size() == 0 ? INITIAL_LEDGER_SEQUENCE : this.ledgers.get(this.ledgers.size() - 1).getSequence() + 1; newLedgers.add(new LedgerMetadata(ledgerId, sequence)); return new LogMetadata(this.epoch + 1, this.enabled, Collections.unmodifiableList(newLedgers), this.truncationAddress, this.updateVersion.get()); }
java
LogMetadata addLedger(long ledgerId) { Preconditions.checkState(this.enabled, "Log is not enabled. Cannot perform any modifications on it."); // Copy existing ledgers. List<LedgerMetadata> newLedgers = new ArrayList<>(this.ledgers.size() + 1); newLedgers.addAll(this.ledgers); // Create and add metadata for the new ledger. int sequence = this.ledgers.size() == 0 ? INITIAL_LEDGER_SEQUENCE : this.ledgers.get(this.ledgers.size() - 1).getSequence() + 1; newLedgers.add(new LedgerMetadata(ledgerId, sequence)); return new LogMetadata(this.epoch + 1, this.enabled, Collections.unmodifiableList(newLedgers), this.truncationAddress, this.updateVersion.get()); }
[ "LogMetadata", "addLedger", "(", "long", "ledgerId", ")", "{", "Preconditions", ".", "checkState", "(", "this", ".", "enabled", ",", "\"Log is not enabled. Cannot perform any modifications on it.\"", ")", ";", "// Copy existing ledgers.", "List", "<", "LedgerMetadata", ">...
Creates a new instance of the LogMetadata class which contains an additional ledger. @param ledgerId The Id of the Ledger to add. @return A new instance of the LogMetadata class.
[ "Creates", "a", "new", "instance", "of", "the", "LogMetadata", "class", "which", "contains", "an", "additional", "ledger", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/LogMetadata.java#L130-L141
FrodeRanders/java-vopn
src/main/java/org/gautelis/vopn/lang/DynamicLoader.java
DynamicLoader.createObject
public C createObject(String className, Class clazz) throws ClassNotFoundException { return createObject(className, clazz, /* no dynamic init */ null); }
java
public C createObject(String className, Class clazz) throws ClassNotFoundException { return createObject(className, clazz, /* no dynamic init */ null); }
[ "public", "C", "createObject", "(", "String", "className", ",", "Class", "clazz", ")", "throws", "ClassNotFoundException", "{", "return", "createObject", "(", "className", ",", "clazz", ",", "/* no dynamic init */", "null", ")", ";", "}" ]
Creates an instance from a Class. @param className name of class -- used for logging purposes and nothing else. @param clazz the class template from which an object is wrought. @throws ClassNotFoundException if class could not be found.
[ "Creates", "an", "instance", "from", "a", "Class", "." ]
train
https://github.com/FrodeRanders/java-vopn/blob/4c7b2f90201327af4eaa3cd46b3fee68f864e5cc/src/main/java/org/gautelis/vopn/lang/DynamicLoader.java#L329-L331
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/postprocess/impl/CSSURLPathRewriterPostProcessor.java
CSSURLPathRewriterPostProcessor.getBundlePrefix
protected String getBundlePrefix(BundleProcessingStatus status, JawrConfig jawrConfig, String bundleName) { // Generation the bundle prefix String bundlePrefix = status.getCurrentBundle().getBundlePrefix(); if (bundlePrefix == null) { bundlePrefix = ""; } else { bundlePrefix = PathNormalizer.asPath(bundlePrefix); } if (!bundleName.equals(ResourceGenerator.CSS_DEBUGPATH)) { bundlePrefix += FAKE_BUNDLE_PREFIX; } // Add path reference for the servlet mapping if it exists if (!"".equals(jawrConfig.getServletMapping())) { bundlePrefix = PathNormalizer.asPath(jawrConfig.getServletMapping() + bundlePrefix) + "/"; } return bundlePrefix; }
java
protected String getBundlePrefix(BundleProcessingStatus status, JawrConfig jawrConfig, String bundleName) { // Generation the bundle prefix String bundlePrefix = status.getCurrentBundle().getBundlePrefix(); if (bundlePrefix == null) { bundlePrefix = ""; } else { bundlePrefix = PathNormalizer.asPath(bundlePrefix); } if (!bundleName.equals(ResourceGenerator.CSS_DEBUGPATH)) { bundlePrefix += FAKE_BUNDLE_PREFIX; } // Add path reference for the servlet mapping if it exists if (!"".equals(jawrConfig.getServletMapping())) { bundlePrefix = PathNormalizer.asPath(jawrConfig.getServletMapping() + bundlePrefix) + "/"; } return bundlePrefix; }
[ "protected", "String", "getBundlePrefix", "(", "BundleProcessingStatus", "status", ",", "JawrConfig", "jawrConfig", ",", "String", "bundleName", ")", "{", "// Generation the bundle prefix", "String", "bundlePrefix", "=", "status", ".", "getCurrentBundle", "(", ")", ".",...
Returns the bundle prefix @param status the bundle processing status @param jawrConfig the jawr config @param bundleName the bundle name @return the bundle prefix
[ "Returns", "the", "bundle", "prefix" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/postprocess/impl/CSSURLPathRewriterPostProcessor.java#L124-L142
xvik/guice-validator
src/main/java/ru/vyarus/guice/validator/group/ValidationContext.java
ValidationContext.doWithGroups
public <T> T doWithGroups(final GroupAction<T> action, final Class<?>... groups) { pushContext(groups); try { return action.call(); } catch (Throwable ex) { throw Throwables.propagate(ex); } finally { popContext(); } }
java
public <T> T doWithGroups(final GroupAction<T> action, final Class<?>... groups) { pushContext(groups); try { return action.call(); } catch (Throwable ex) { throw Throwables.propagate(ex); } finally { popContext(); } }
[ "public", "<", "T", ">", "T", "doWithGroups", "(", "final", "GroupAction", "<", "T", ">", "action", ",", "final", "Class", "<", "?", ">", "...", "groups", ")", "{", "pushContext", "(", "groups", ")", ";", "try", "{", "return", "action", ".", "call", ...
Defines context validation groups. Context is defined for all logic inside action callback (in current thread). Note: does not override current context groups. @param action action callback to be executed with validation groups @param groups validation groups to use @param <T> action return type @return object produced by action callback
[ "Defines", "context", "validation", "groups", ".", "Context", "is", "defined", "for", "all", "logic", "inside", "action", "callback", "(", "in", "current", "thread", ")", ".", "Note", ":", "does", "not", "override", "current", "context", "groups", "." ]
train
https://github.com/xvik/guice-validator/blob/e69d6722bbe653036bf1469393dddfa47a6491a6/src/main/java/ru/vyarus/guice/validator/group/ValidationContext.java#L55-L64
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/RedundentExprEliminator.java
RedundentExprEliminator.visitPredicate
public boolean visitPredicate(ExpressionOwner owner, Expression pred) { boolean savedIsSame = m_isSameContext; m_isSameContext = false; // Any further down, just collect the absolute paths. pred.callVisitors(owner, this); m_isSameContext = savedIsSame; // We've already gone down the subtree, so don't go have the caller // go any further. return false; }
java
public boolean visitPredicate(ExpressionOwner owner, Expression pred) { boolean savedIsSame = m_isSameContext; m_isSameContext = false; // Any further down, just collect the absolute paths. pred.callVisitors(owner, this); m_isSameContext = savedIsSame; // We've already gone down the subtree, so don't go have the caller // go any further. return false; }
[ "public", "boolean", "visitPredicate", "(", "ExpressionOwner", "owner", ",", "Expression", "pred", ")", "{", "boolean", "savedIsSame", "=", "m_isSameContext", ";", "m_isSameContext", "=", "false", ";", "// Any further down, just collect the absolute paths.", "pred", ".", ...
Visit a predicate within a location path. Note that there isn't a proper unique component for predicates, and that the expression will be called also for whatever type Expression is. @param owner The owner of the expression, to which the expression can be reset if rewriting takes place. @param pred The predicate object. @return true if the sub expressions should be traversed.
[ "Visit", "a", "predicate", "within", "a", "location", "path", ".", "Note", "that", "there", "isn", "t", "a", "proper", "unique", "component", "for", "predicates", "and", "that", "the", "expression", "will", "be", "called", "also", "for", "whatever", "type", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/RedundentExprEliminator.java#L1122-L1135
voldemort/voldemort
src/java/voldemort/tools/admin/command/AdminCommandAsyncJob.java
AdminCommandAsyncJob.executeHelp
public static void executeHelp(String[] args, PrintStream stream) throws IOException { String subCmd = (args.length > 0) ? args[0] : ""; if(subCmd.equals("list")) { SubCommandAsyncJobList.printHelp(stream); } else if(subCmd.equals("stop")) { SubCommandAsyncJobStop.printHelp(stream); } else { printHelp(stream); } }
java
public static void executeHelp(String[] args, PrintStream stream) throws IOException { String subCmd = (args.length > 0) ? args[0] : ""; if(subCmd.equals("list")) { SubCommandAsyncJobList.printHelp(stream); } else if(subCmd.equals("stop")) { SubCommandAsyncJobStop.printHelp(stream); } else { printHelp(stream); } }
[ "public", "static", "void", "executeHelp", "(", "String", "[", "]", "args", ",", "PrintStream", "stream", ")", "throws", "IOException", "{", "String", "subCmd", "=", "(", "args", ".", "length", ">", "0", ")", "?", "args", "[", "0", "]", ":", "\"\"", ...
Parses command-line input and prints help menu. @throws IOException
[ "Parses", "command", "-", "line", "input", "and", "prints", "help", "menu", "." ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/command/AdminCommandAsyncJob.java#L76-L85
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/Table.java
Table.setRowsSpanned
public void setRowsSpanned(final int rowIndex, final int colIndex, final int n) throws IOException { this.builder.setRowsSpanned(this, this.appender, rowIndex, colIndex, n); }
java
public void setRowsSpanned(final int rowIndex, final int colIndex, final int n) throws IOException { this.builder.setRowsSpanned(this, this.appender, rowIndex, colIndex, n); }
[ "public", "void", "setRowsSpanned", "(", "final", "int", "rowIndex", ",", "final", "int", "colIndex", ",", "final", "int", "n", ")", "throws", "IOException", "{", "this", ".", "builder", ".", "setRowsSpanned", "(", "this", ",", "this", ".", "appender", ","...
Set a span over rows @param rowIndex the row index @param colIndex the col index @param n the number of rows @throws IOException if an error occurs
[ "Set", "a", "span", "over", "rows" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/Table.java#L325-L328
quattor/pan
panc/src/main/java/org/quattor/pan/ttemplate/BuildContext.java
BuildContext.setGlobalVariable
public void setGlobalVariable(String name, GlobalVariable variable) { assert (name != null); if (variable != null) { globalVariables.put(name, variable); } else { globalVariables.remove(name); } }
java
public void setGlobalVariable(String name, GlobalVariable variable) { assert (name != null); if (variable != null) { globalVariables.put(name, variable); } else { globalVariables.remove(name); } }
[ "public", "void", "setGlobalVariable", "(", "String", "name", ",", "GlobalVariable", "variable", ")", "{", "assert", "(", "name", "!=", "null", ")", ";", "if", "(", "variable", "!=", "null", ")", "{", "globalVariables", ".", "put", "(", "name", ",", "var...
Set the variable to the given GlobalVariable. If variable is null, then the global variable definition is removed. @param name global variable name @param variable GlobalVariable to associate with name
[ "Set", "the", "variable", "to", "the", "given", "GlobalVariable", ".", "If", "variable", "is", "null", "then", "the", "global", "variable", "definition", "is", "removed", "." ]
train
https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/ttemplate/BuildContext.java#L615-L624
hltcoe/annotated-nyt
src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java
NYTCorpusDocumentParser.parseNYTCorpusDocumentFromFile
public NYTCorpusDocument parseNYTCorpusDocumentFromFile(File file, boolean validating) { Document document = null; if (validating) { document = loadValidating(file); } else { document = loadNonValidating(file); } return parseNYTCorpusDocumentFromDOMDocument(file, document); }
java
public NYTCorpusDocument parseNYTCorpusDocumentFromFile(File file, boolean validating) { Document document = null; if (validating) { document = loadValidating(file); } else { document = loadNonValidating(file); } return parseNYTCorpusDocumentFromDOMDocument(file, document); }
[ "public", "NYTCorpusDocument", "parseNYTCorpusDocumentFromFile", "(", "File", "file", ",", "boolean", "validating", ")", "{", "Document", "document", "=", "null", ";", "if", "(", "validating", ")", "{", "document", "=", "loadValidating", "(", "file", ")", ";", ...
Parse an New York Times Document from a file. @param file The file from which to parse the document. @param validating True if the file is to be validated against the nitf DTD and false if it is not. It is recommended that validation be disabled, as all documents in the corpus have previously been validated against the NITF DTD. @return The parsed document, or null if an error occurs.
[ "Parse", "an", "New", "York", "Times", "Document", "from", "a", "file", "." ]
train
https://github.com/hltcoe/annotated-nyt/blob/0a4daa97705591cefea9de61614770ae2665a48e/src/main/java/com/nytlabs/corpus/NYTCorpusDocumentParser.java#L289-L299
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/indexing/BranchUniversalObject.java
BranchUniversalObject.getShortUrl
public String getShortUrl(@NonNull Context context, @NonNull LinkProperties linkProperties) { return getLinkBuilder(context, linkProperties).getShortUrl(); }
java
public String getShortUrl(@NonNull Context context, @NonNull LinkProperties linkProperties) { return getLinkBuilder(context, linkProperties).getShortUrl(); }
[ "public", "String", "getShortUrl", "(", "@", "NonNull", "Context", "context", ",", "@", "NonNull", "LinkProperties", "linkProperties", ")", "{", "return", "getLinkBuilder", "(", "context", ",", "linkProperties", ")", ".", "getShortUrl", "(", ")", ";", "}" ]
Creates a short url for the BUO synchronously. @param context {@link Context} instance @param linkProperties An object of {@link LinkProperties} specifying the properties of this link @return A {@link String} with value of the short url created for this BUO. A long url for the BUO is returned in case link creation fails
[ "Creates", "a", "short", "url", "for", "the", "BUO", "synchronously", "." ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/indexing/BranchUniversalObject.java#L597-L599
pwheel/spring-security-oauth2-client
src/main/java/com/racquettrack/security/oauth/OAuth2AuthenticationFilter.java
OAuth2AuthenticationFilter.checkForErrors
protected void checkForErrors(Map<String, String[]> parameters) throws AuthenticationException { final String errorValues[] = parameters.get("error"); final String errorReasonValues[] = parameters.get("error_reason"); final String errorDescriptionValues[] = parameters.get("error_description"); if (errorValues != null && errorValues.length > 0) { final String error = errorValues[0]; final String errorReason = errorReasonValues != null && errorReasonValues.length > 0 ? errorReasonValues[0] : null; final String errorDescription = errorDescriptionValues != null && errorDescriptionValues.length > 0 ? errorDescriptionValues[0] : null; final String errorText = String.format("An error was returned by the OAuth Provider: error=%s, " + "error_reason=%s, error_description=%s", error, errorReason, errorDescription); LOG.info(errorText); throw new AuthenticationServiceException(errorText); } }
java
protected void checkForErrors(Map<String, String[]> parameters) throws AuthenticationException { final String errorValues[] = parameters.get("error"); final String errorReasonValues[] = parameters.get("error_reason"); final String errorDescriptionValues[] = parameters.get("error_description"); if (errorValues != null && errorValues.length > 0) { final String error = errorValues[0]; final String errorReason = errorReasonValues != null && errorReasonValues.length > 0 ? errorReasonValues[0] : null; final String errorDescription = errorDescriptionValues != null && errorDescriptionValues.length > 0 ? errorDescriptionValues[0] : null; final String errorText = String.format("An error was returned by the OAuth Provider: error=%s, " + "error_reason=%s, error_description=%s", error, errorReason, errorDescription); LOG.info(errorText); throw new AuthenticationServiceException(errorText); } }
[ "protected", "void", "checkForErrors", "(", "Map", "<", "String", ",", "String", "[", "]", ">", "parameters", ")", "throws", "AuthenticationException", "{", "final", "String", "errorValues", "[", "]", "=", "parameters", ".", "get", "(", "\"error\"", ")", ";"...
Checks to see if an error was returned by the OAuth Provider and throws an {@link AuthenticationException} if it was. @param parameters Parameters received from the OAuth Provider. @throws AuthenticationException If an error was returned by the OAuth Provider.
[ "Checks", "to", "see", "if", "an", "error", "was", "returned", "by", "the", "OAuth", "Provider", "and", "throws", "an", "{" ]
train
https://github.com/pwheel/spring-security-oauth2-client/blob/c0258823493e268495c9752c5d752f74c6809c6b/src/main/java/com/racquettrack/security/oauth/OAuth2AuthenticationFilter.java#L129-L145
alkacon/opencms-core
src/org/opencms/acacia/shared/CmsEntity.java
CmsEntity.insertAttributeValue
public void insertAttributeValue(String attributeName, CmsEntity value, int index) { if (m_entityAttributes.containsKey(attributeName)) { m_entityAttributes.get(attributeName).add(index, value); } else { setAttributeValue(attributeName, value); } registerChangeHandler(value); fireChange(); }
java
public void insertAttributeValue(String attributeName, CmsEntity value, int index) { if (m_entityAttributes.containsKey(attributeName)) { m_entityAttributes.get(attributeName).add(index, value); } else { setAttributeValue(attributeName, value); } registerChangeHandler(value); fireChange(); }
[ "public", "void", "insertAttributeValue", "(", "String", "attributeName", ",", "CmsEntity", "value", ",", "int", "index", ")", "{", "if", "(", "m_entityAttributes", ".", "containsKey", "(", "attributeName", ")", ")", "{", "m_entityAttributes", ".", "get", "(", ...
Inserts a new attribute value at the given index.<p> @param attributeName the attribute name @param value the attribute value @param index the value index
[ "Inserts", "a", "new", "attribute", "value", "at", "the", "given", "index", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/acacia/shared/CmsEntity.java#L491-L500
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java
OSchemaHelper.oDocument
public OSchemaHelper oDocument(String pkField, Object pkValue) { checkOClass(); List<ODocument> docs = db.query(new OSQLSynchQuery<ODocument>("select from "+lastClass.getName()+" where "+pkField+" = ?", 1), pkValue); if(docs!=null && !docs.isEmpty()) { lastDocument = docs.get(0); } else { lastDocument = new ODocument(lastClass); lastDocument.field(pkField, pkValue); } return this; }
java
public OSchemaHelper oDocument(String pkField, Object pkValue) { checkOClass(); List<ODocument> docs = db.query(new OSQLSynchQuery<ODocument>("select from "+lastClass.getName()+" where "+pkField+" = ?", 1), pkValue); if(docs!=null && !docs.isEmpty()) { lastDocument = docs.get(0); } else { lastDocument = new ODocument(lastClass); lastDocument.field(pkField, pkValue); } return this; }
[ "public", "OSchemaHelper", "oDocument", "(", "String", "pkField", ",", "Object", "pkValue", ")", "{", "checkOClass", "(", ")", ";", "List", "<", "ODocument", ">", "docs", "=", "db", ".", "query", "(", "new", "OSQLSynchQuery", "<", "ODocument", ">", "(", ...
Create an {@link ODocument} if required of an current class. Existance of an document checked by specified primary key field name and required value @param pkField primary key field name @param pkValue required primary key value @return this helper
[ "Create", "an", "{" ]
train
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java#L323-L337
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcConnections.java
JdbcConnections.getDb
synchronized public Connection getDb(String db) throws Exception { Connection con = null; if (nameToConnection.containsKey(db)) { con = nameToConnection.get(db); } else { ConnectionInfo info = nameToInfo.get(db); if( null == info ) { throw new Exception("No information provided for database named: "+db); } try { Class.forName(info.getJdbcClass()); //load the driver con = DriverManager.getConnection(info.getConnectionString(), info.getUserName(), info.getPassword()); //connect to the db DatabaseMetaData dbmd = con.getMetaData(); //get MetaData to confirm connection logger.info("Connection to "+dbmd.getDatabaseProductName()+" "+ dbmd.getDatabaseProductVersion()+" successful.\n"); nameToConnection.put(db, con); } catch(Exception e) { throw new Exception("Couldn't get db connection: "+db,e); } } return(con); }
java
synchronized public Connection getDb(String db) throws Exception { Connection con = null; if (nameToConnection.containsKey(db)) { con = nameToConnection.get(db); } else { ConnectionInfo info = nameToInfo.get(db); if( null == info ) { throw new Exception("No information provided for database named: "+db); } try { Class.forName(info.getJdbcClass()); //load the driver con = DriverManager.getConnection(info.getConnectionString(), info.getUserName(), info.getPassword()); //connect to the db DatabaseMetaData dbmd = con.getMetaData(); //get MetaData to confirm connection logger.info("Connection to "+dbmd.getDatabaseProductName()+" "+ dbmd.getDatabaseProductVersion()+" successful.\n"); nameToConnection.put(db, con); } catch(Exception e) { throw new Exception("Couldn't get db connection: "+db,e); } } return(con); }
[ "synchronized", "public", "Connection", "getDb", "(", "String", "db", ")", "throws", "Exception", "{", "Connection", "con", "=", "null", ";", "if", "(", "nameToConnection", ".", "containsKey", "(", "db", ")", ")", "{", "con", "=", "nameToConnection", ".", ...
This method checks for the presence of a Connection associated with the input db parameter. It attempts to create the Connection and adds it to the connection map if it does not already exist. If the Connection exists or is created, it is returned. @param db database name. @return Returns the desired Connection instance, or null.
[ "This", "method", "checks", "for", "the", "presence", "of", "a", "Connection", "associated", "with", "the", "input", "db", "parameter", ".", "It", "attempts", "to", "create", "the", "Connection", "and", "adds", "it", "to", "the", "connection", "map", "if", ...
train
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcConnections.java#L149-L175
gallandarakhneorg/afc
core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java
MeasureUnitUtil.toRadiansPerSecond
@Pure public static double toRadiansPerSecond(double value, AngularUnit inputUnit) { switch (inputUnit) { case TURNS_PER_SECOND: return value * (2. * MathConstants.PI); case DEGREES_PER_SECOND: return Math.toRadians(value); case RADIANS_PER_SECOND: default: } return value; }
java
@Pure public static double toRadiansPerSecond(double value, AngularUnit inputUnit) { switch (inputUnit) { case TURNS_PER_SECOND: return value * (2. * MathConstants.PI); case DEGREES_PER_SECOND: return Math.toRadians(value); case RADIANS_PER_SECOND: default: } return value; }
[ "@", "Pure", "public", "static", "double", "toRadiansPerSecond", "(", "double", "value", ",", "AngularUnit", "inputUnit", ")", "{", "switch", "(", "inputUnit", ")", "{", "case", "TURNS_PER_SECOND", ":", "return", "value", "*", "(", "2.", "*", "MathConstants", ...
Convert the given value expressed in the given unit to radians per second. @param value is the value to convert @param inputUnit is the unit of the {@code value} @return the result of the convertion.
[ "Convert", "the", "given", "value", "expressed", "in", "the", "given", "unit", "to", "radians", "per", "second", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathphysics/src/main/java/org/arakhne/afc/math/physics/MeasureUnitUtil.java#L639-L650
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java
PresentsConnectionManager.handleDatagram
protected int handleDatagram (DatagramChannel listener, long when) { InetSocketAddress source; _databuf.clear(); try { source = (InetSocketAddress)listener.receive(_databuf); } catch (IOException ioe) { log.warning("Failure receiving datagram.", ioe); return 0; } // make sure we actually read a packet if (source == null) { log.info("Psych! Got READ_READY, but no datagram."); return 0; } // flip the buffer and record the size (which must be at least 14 to contain the connection // id, authentication hash, and a class reference) int size = _databuf.flip().remaining(); if (size < 14) { log.warning("Received undersized datagram", "source", source, "size", size); return 0; } // the first four bytes are the connection id int connectionId = _databuf.getInt(); Connection conn = _connections.get(connectionId); if (conn != null) { ((PresentsConnection)conn).handleDatagram(source, listener, _databuf, when); } else { log.debug("Received datagram for unknown connection", "id", connectionId, "source", source); } return size; }
java
protected int handleDatagram (DatagramChannel listener, long when) { InetSocketAddress source; _databuf.clear(); try { source = (InetSocketAddress)listener.receive(_databuf); } catch (IOException ioe) { log.warning("Failure receiving datagram.", ioe); return 0; } // make sure we actually read a packet if (source == null) { log.info("Psych! Got READ_READY, but no datagram."); return 0; } // flip the buffer and record the size (which must be at least 14 to contain the connection // id, authentication hash, and a class reference) int size = _databuf.flip().remaining(); if (size < 14) { log.warning("Received undersized datagram", "source", source, "size", size); return 0; } // the first four bytes are the connection id int connectionId = _databuf.getInt(); Connection conn = _connections.get(connectionId); if (conn != null) { ((PresentsConnection)conn).handleDatagram(source, listener, _databuf, when); } else { log.debug("Received datagram for unknown connection", "id", connectionId, "source", source); } return size; }
[ "protected", "int", "handleDatagram", "(", "DatagramChannel", "listener", ",", "long", "when", ")", "{", "InetSocketAddress", "source", ";", "_databuf", ".", "clear", "(", ")", ";", "try", "{", "source", "=", "(", "InetSocketAddress", ")", "listener", ".", "...
Called when a datagram message is ready to be read off its channel.
[ "Called", "when", "a", "datagram", "message", "is", "ready", "to", "be", "read", "off", "its", "channel", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnectionManager.java#L215-L251
Azure/azure-sdk-for-java
privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/VirtualNetworkLinksInner.java
VirtualNetworkLinksInner.beginUpdateAsync
public Observable<VirtualNetworkLinkInner> beginUpdateAsync(String resourceGroupName, String privateZoneName, String virtualNetworkLinkName, VirtualNetworkLinkInner parameters, String ifMatch) { return beginUpdateWithServiceResponseAsync(resourceGroupName, privateZoneName, virtualNetworkLinkName, parameters, ifMatch).map(new Func1<ServiceResponse<VirtualNetworkLinkInner>, VirtualNetworkLinkInner>() { @Override public VirtualNetworkLinkInner call(ServiceResponse<VirtualNetworkLinkInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkLinkInner> beginUpdateAsync(String resourceGroupName, String privateZoneName, String virtualNetworkLinkName, VirtualNetworkLinkInner parameters, String ifMatch) { return beginUpdateWithServiceResponseAsync(resourceGroupName, privateZoneName, virtualNetworkLinkName, parameters, ifMatch).map(new Func1<ServiceResponse<VirtualNetworkLinkInner>, VirtualNetworkLinkInner>() { @Override public VirtualNetworkLinkInner call(ServiceResponse<VirtualNetworkLinkInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkLinkInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "privateZoneName", ",", "String", "virtualNetworkLinkName", ",", "VirtualNetworkLinkInner", "parameters", ",", "String", "ifMatch", ")", "{"...
Updates a virtual network link to the specified Private DNS zone. @param resourceGroupName The name of the resource group. @param privateZoneName The name of the Private DNS zone (without a terminating dot). @param virtualNetworkLinkName The name of the virtual network link. @param parameters Parameters supplied to the Update operation. @param ifMatch The ETag of the virtual network link to the Private DNS zone. Omit this value to always overwrite the current virtual network link. Specify the last-seen ETag value to prevent accidentally overwriting any concurrent changes. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkLinkInner object
[ "Updates", "a", "virtual", "network", "link", "to", "the", "specified", "Private", "DNS", "zone", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/VirtualNetworkLinksInner.java#L798-L805
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Assert.java
Assert.isNull
public static void isNull(Object object, String errorMsgTemplate, Object... params) throws IllegalArgumentException { if (object != null) { throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params)); } }
java
public static void isNull(Object object, String errorMsgTemplate, Object... params) throws IllegalArgumentException { if (object != null) { throw new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params)); } }
[ "public", "static", "void", "isNull", "(", "Object", "object", ",", "String", "errorMsgTemplate", ",", "Object", "...", "params", ")", "throws", "IllegalArgumentException", "{", "if", "(", "object", "!=", "null", ")", "{", "throw", "new", "IllegalArgumentExcepti...
断言对象是否为{@code null} ,如果不为{@code null} 抛出{@link IllegalArgumentException} 异常 <pre class="code"> Assert.isNull(value, "The value must be null"); </pre> @param object 被检查的对象 @param errorMsgTemplate 消息模板,变量使用{}表示 @param params 参数列表 @throws IllegalArgumentException if the object is not {@code null}
[ "断言对象是否为", "{", "@code", "null", "}", ",如果不为", "{", "@code", "null", "}", "抛出", "{", "@link", "IllegalArgumentException", "}", "异常" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Assert.java#L95-L99
aequologica/geppaequo
geppaequo-core/src/main/java/net/aequologica/neo/geppaequo/auth/MethodUtils.java
MethodUtils.getTotalTransformationCost
private static float getTotalTransformationCost(Class<?>[] srcArgs, Class<?>[] destArgs) { float totalCost = 0.0f; for (int i = 0; i < srcArgs.length; i++) { Class<?> srcClass, destClass; srcClass = srcArgs[i]; destClass = destArgs[i]; totalCost += getObjectTransformationCost(srcClass, destClass); } return totalCost; }
java
private static float getTotalTransformationCost(Class<?>[] srcArgs, Class<?>[] destArgs) { float totalCost = 0.0f; for (int i = 0; i < srcArgs.length; i++) { Class<?> srcClass, destClass; srcClass = srcArgs[i]; destClass = destArgs[i]; totalCost += getObjectTransformationCost(srcClass, destClass); } return totalCost; }
[ "private", "static", "float", "getTotalTransformationCost", "(", "Class", "<", "?", ">", "[", "]", "srcArgs", ",", "Class", "<", "?", ">", "[", "]", "destArgs", ")", "{", "float", "totalCost", "=", "0.0f", ";", "for", "(", "int", "i", "=", "0", ";", ...
Returns the sum of the object transformation cost for each class in the source argument list. @param srcArgs The source arguments @param destArgs The destination arguments @return The total transformation cost
[ "Returns", "the", "sum", "of", "the", "object", "transformation", "cost", "for", "each", "class", "in", "the", "source", "argument", "list", "." ]
train
https://github.com/aequologica/geppaequo/blob/b72e5f6356535fd045a931f8c544d4a8ea6e35a2/geppaequo-core/src/main/java/net/aequologica/neo/geppaequo/auth/MethodUtils.java#L1103-L1114
noboomu/proteus
core/src/main/java/io/sinistral/proteus/ProteusApplication.java
ProteusApplication.setServerConfigurationFunction
public ProteusApplication setServerConfigurationFunction(Function<Undertow.Builder, Undertow.Builder> serverConfigurationFunction) { this.serverConfigurationFunction = serverConfigurationFunction; return this; }
java
public ProteusApplication setServerConfigurationFunction(Function<Undertow.Builder, Undertow.Builder> serverConfigurationFunction) { this.serverConfigurationFunction = serverConfigurationFunction; return this; }
[ "public", "ProteusApplication", "setServerConfigurationFunction", "(", "Function", "<", "Undertow", ".", "Builder", ",", "Undertow", ".", "Builder", ">", "serverConfigurationFunction", ")", "{", "this", ".", "serverConfigurationFunction", "=", "serverConfigurationFunction",...
Allows direct access to the Undertow.Builder for custom configuration @param serverConfigurationFunction the serverConfigurationFunction
[ "Allows", "direct", "access", "to", "the", "Undertow", ".", "Builder", "for", "custom", "configuration" ]
train
https://github.com/noboomu/proteus/blob/9bf999e19e9b491b13912f3ee0e3fbefdbacc509/core/src/main/java/io/sinistral/proteus/ProteusApplication.java#L465-L469
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java
BeanUtil.copyProperties
public static void copyProperties(Object source, Object target, CopyOptions copyOptions) { if (null == copyOptions) { copyOptions = new CopyOptions(); } BeanCopier.create(source, target, copyOptions).copy(); }
java
public static void copyProperties(Object source, Object target, CopyOptions copyOptions) { if (null == copyOptions) { copyOptions = new CopyOptions(); } BeanCopier.create(source, target, copyOptions).copy(); }
[ "public", "static", "void", "copyProperties", "(", "Object", "source", ",", "Object", "target", ",", "CopyOptions", "copyOptions", ")", "{", "if", "(", "null", "==", "copyOptions", ")", "{", "copyOptions", "=", "new", "CopyOptions", "(", ")", ";", "}", "Be...
复制Bean对象属性<br> 限制类用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类 @param source 源Bean对象 @param target 目标Bean对象 @param copyOptions 拷贝选项,见 {@link CopyOptions}
[ "复制Bean对象属性<br", ">", "限制类用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java#L617-L622
googleapis/google-cloud-java
google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/BigtableDataClient.java
BigtableDataClient.readRow
public Row readRow(String tableId, String rowKey, @Nullable Filter filter) { return ApiExceptions.callAndTranslateApiException( readRowAsync(tableId, ByteString.copyFromUtf8(rowKey), filter)); }
java
public Row readRow(String tableId, String rowKey, @Nullable Filter filter) { return ApiExceptions.callAndTranslateApiException( readRowAsync(tableId, ByteString.copyFromUtf8(rowKey), filter)); }
[ "public", "Row", "readRow", "(", "String", "tableId", ",", "String", "rowKey", ",", "@", "Nullable", "Filter", "filter", ")", "{", "return", "ApiExceptions", ".", "callAndTranslateApiException", "(", "readRowAsync", "(", "tableId", ",", "ByteString", ".", "copyF...
Convenience method for synchronously reading a single row. If the row does not exist, the value will be null. <p>Sample code: <pre>{@code try (BigtableDataClient bigtableDataClient = BigtableDataClient.create("[PROJECT]", "[INSTANCE]")) { String tableId = "[TABLE]"; // Build the filter expression Filter filter = FILTERS.chain() .filter(FILTERS.qualifier().regex("prefix.*")) .filter(FILTERS.limit().cellsPerRow(10)); Row row = bigtableDataClient.readRow(tableId, "key", filter); // Do something with row, for example, display all cells if(row != null) { System.out.println(row.getKey().toStringUtf8()); for(RowCell cell : row.getCells()) { System.out.printf("Family: %s Qualifier: %s Value: %s", cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8()); } } } catch(ApiException e) { e.printStackTrace(); } }</pre> @throws com.google.api.gax.rpc.ApiException when a serverside error occurs
[ "Convenience", "method", "for", "synchronously", "reading", "a", "single", "row", ".", "If", "the", "row", "does", "not", "exist", "the", "value", "will", "be", "null", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/BigtableDataClient.java#L235-L238
spring-projects/spring-boot
spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityService.java
CloudFoundrySecurityService.getAccessLevel
public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { try { URI uri = getPermissionsUri(applicationId); RequestEntity<?> request = RequestEntity.get(uri) .header("Authorization", "bearer " + token).build(); Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody(); if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) { return AccessLevel.FULL; } return AccessLevel.RESTRICTED; } catch (HttpClientErrorException ex) { if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) { throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex); } catch (HttpServerErrorException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable"); } }
java
public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { try { URI uri = getPermissionsUri(applicationId); RequestEntity<?> request = RequestEntity.get(uri) .header("Authorization", "bearer " + token).build(); Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody(); if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) { return AccessLevel.FULL; } return AccessLevel.RESTRICTED; } catch (HttpClientErrorException ex) { if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) { throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex); } catch (HttpServerErrorException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable"); } }
[ "public", "AccessLevel", "getAccessLevel", "(", "String", "token", ",", "String", "applicationId", ")", "throws", "CloudFoundryAuthorizationException", "{", "try", "{", "URI", "uri", "=", "getPermissionsUri", "(", "applicationId", ")", ";", "RequestEntity", "<", "?"...
Return the access level that should be granted to the given token. @param token the token @param applicationId the cloud foundry application ID @return the access level that should be granted @throws CloudFoundryAuthorizationException if the token is not authorized
[ "Return", "the", "access", "level", "that", "should", "be", "granted", "to", "the", "given", "token", "." ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/cloudfoundry/servlet/CloudFoundrySecurityService.java#L69-L93
cdk/cdk
legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java
MassToFormulaTool.getFormula
private IMolecularFormula getFormula(List<IIsotope> isoToCond_new, int[] value_In) { IMolecularFormula mf = builder.newInstance(IMolecularFormula.class); for (int i = 0; i < isoToCond_new.size(); i++) { if (value_In[i] != 0) { for (int j = 0; j < value_In[i]; j++) mf.addIsotope(isoToCond_new.get(i)); } } mf = putInOrder(mf); return mf; }
java
private IMolecularFormula getFormula(List<IIsotope> isoToCond_new, int[] value_In) { IMolecularFormula mf = builder.newInstance(IMolecularFormula.class); for (int i = 0; i < isoToCond_new.size(); i++) { if (value_In[i] != 0) { for (int j = 0; j < value_In[i]; j++) mf.addIsotope(isoToCond_new.get(i)); } } mf = putInOrder(mf); return mf; }
[ "private", "IMolecularFormula", "getFormula", "(", "List", "<", "IIsotope", ">", "isoToCond_new", ",", "int", "[", "]", "value_In", ")", "{", "IMolecularFormula", "mf", "=", "builder", ".", "newInstance", "(", "IMolecularFormula", ".", "class", ")", ";", "for"...
Set the formula molecular as IMolecularFormula object. @param elemToCond_new List with IIsotope @param value_In Array matrix with occurrences @return The IMolecularFormula
[ "Set", "the", "formula", "molecular", "as", "IMolecularFormula", "object", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/formula/MassToFormulaTool.java#L486-L497
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/RandomUtil.java
RandomUtil.randomString
public String randomString(String permitted, int length) { StringBuilder result = new StringBuilder(length); int maxIndex = permitted.length(); for (int i = 0; i < length; i++) { int index = random(maxIndex); char value = permitted.charAt(index); result.append(value); } return result.toString(); }
java
public String randomString(String permitted, int length) { StringBuilder result = new StringBuilder(length); int maxIndex = permitted.length(); for (int i = 0; i < length; i++) { int index = random(maxIndex); char value = permitted.charAt(index); result.append(value); } return result.toString(); }
[ "public", "String", "randomString", "(", "String", "permitted", ",", "int", "length", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "length", ")", ";", "int", "maxIndex", "=", "permitted", ".", "length", "(", ")", ";", "for", "(", ...
Creates a random string consisting only of supplied characters. @param permitted string consisting of permitted characters. @param length length of string to create. @return random string.
[ "Creates", "a", "random", "string", "consisting", "only", "of", "supplied", "characters", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/RandomUtil.java#L50-L59
google/error-prone-javac
src/java.compiler/share/classes/javax/lang/model/util/TypeKindVisitor6.java
TypeKindVisitor6.visitPrimitive
@Override public R visitPrimitive(PrimitiveType t, P p) { TypeKind k = t.getKind(); switch (k) { case BOOLEAN: return visitPrimitiveAsBoolean(t, p); case BYTE: return visitPrimitiveAsByte(t, p); case SHORT: return visitPrimitiveAsShort(t, p); case INT: return visitPrimitiveAsInt(t, p); case LONG: return visitPrimitiveAsLong(t, p); case CHAR: return visitPrimitiveAsChar(t, p); case FLOAT: return visitPrimitiveAsFloat(t, p); case DOUBLE: return visitPrimitiveAsDouble(t, p); default: throw new AssertionError("Bad kind " + k + " for PrimitiveType" + t); } }
java
@Override public R visitPrimitive(PrimitiveType t, P p) { TypeKind k = t.getKind(); switch (k) { case BOOLEAN: return visitPrimitiveAsBoolean(t, p); case BYTE: return visitPrimitiveAsByte(t, p); case SHORT: return visitPrimitiveAsShort(t, p); case INT: return visitPrimitiveAsInt(t, p); case LONG: return visitPrimitiveAsLong(t, p); case CHAR: return visitPrimitiveAsChar(t, p); case FLOAT: return visitPrimitiveAsFloat(t, p); case DOUBLE: return visitPrimitiveAsDouble(t, p); default: throw new AssertionError("Bad kind " + k + " for PrimitiveType" + t); } }
[ "@", "Override", "public", "R", "visitPrimitive", "(", "PrimitiveType", "t", ",", "P", "p", ")", "{", "TypeKind", "k", "=", "t", ".", "getKind", "(", ")", ";", "switch", "(", "k", ")", "{", "case", "BOOLEAN", ":", "return", "visitPrimitiveAsBoolean", "...
Visits a primitive type, dispatching to the visit method for the specific {@linkplain TypeKind kind} of primitive type: {@code BOOLEAN}, {@code BYTE}, etc. @param t {@inheritDoc} @param p {@inheritDoc} @return the result of the kind-specific visit method
[ "Visits", "a", "primitive", "type", "dispatching", "to", "the", "visit", "method", "for", "the", "specific", "{", "@linkplain", "TypeKind", "kind", "}", "of", "primitive", "type", ":", "{", "@code", "BOOLEAN", "}", "{", "@code", "BYTE", "}", "etc", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/TypeKindVisitor6.java#L116-L147
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/PrincipalUserDto.java
PrincipalUserDto.transformToDto
public static List<PrincipalUserDto> transformToDto(List<PrincipalUser> users) { if (users == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<PrincipalUserDto> result = new ArrayList<>(); for (PrincipalUser user : users) { result.add(transformToDto(user)); } return result; }
java
public static List<PrincipalUserDto> transformToDto(List<PrincipalUser> users) { if (users == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<PrincipalUserDto> result = new ArrayList<>(); for (PrincipalUser user : users) { result.add(transformToDto(user)); } return result; }
[ "public", "static", "List", "<", "PrincipalUserDto", ">", "transformToDto", "(", "List", "<", "PrincipalUser", ">", "users", ")", "{", "if", "(", "users", "==", "null", ")", "{", "throw", "new", "WebApplicationException", "(", "\"Null entity object cannot be conve...
Converts list of alert entity objects to list of alertDto objects. @param users alerts List of alert entities. Cannot be null. @return List of alertDto objects. @throws WebApplicationException If an error occurs.
[ "Converts", "list", "of", "alert", "entity", "objects", "to", "list", "of", "alertDto", "objects", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/dto/PrincipalUserDto.java#L96-L107
mockito/mockito
src/main/java/org/mockito/AdditionalMatchers.java
AdditionalMatchers.and
public static <T> T and(T first, T second) { mockingProgress().getArgumentMatcherStorage().reportAnd(); return null; }
java
public static <T> T and(T first, T second) { mockingProgress().getArgumentMatcherStorage().reportAnd(); return null; }
[ "public", "static", "<", "T", ">", "T", "and", "(", "T", "first", ",", "T", "second", ")", "{", "mockingProgress", "(", ")", ".", "getArgumentMatcherStorage", "(", ")", ".", "reportAnd", "(", ")", ";", "return", "null", ";", "}" ]
Object argument that matches both given argument matchers. <p> See examples in javadoc for {@link AdditionalMatchers} class @param <T> the type of the object, it is passed through to prevent casts. @param first placeholder for the first argument matcher. @param second placeholder for the second argument matcher. @return <code>null</code>.
[ "Object", "argument", "that", "matches", "both", "given", "argument", "matchers", ".", "<p", ">", "See", "examples", "in", "javadoc", "for", "{", "@link", "AdditionalMatchers", "}", "class" ]
train
https://github.com/mockito/mockito/blob/c5e2b80af76e3192cae7c9550b70c4d1ab312034/src/main/java/org/mockito/AdditionalMatchers.java#L742-L745
salesforce/Argus
ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java
UserResources.removeAccess
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/revoke_oauth_access/{appName}") @Description("Revokes Oauth access of app from argus for a particular user") public Response removeAccess(@Context HttpServletRequest req,@PathParam("appName") String appName) { String userName=findUserByToken(req); if(appName.equalsIgnoreCase(applicationName)) { authService.deleteByUserId(userName); return Response.status(Status.OK).build(); } else { throw new OAuthException(ResponseCodes.ERR_DELETING_APP, HttpResponseStatus.BAD_REQUEST); } }
java
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/revoke_oauth_access/{appName}") @Description("Revokes Oauth access of app from argus for a particular user") public Response removeAccess(@Context HttpServletRequest req,@PathParam("appName") String appName) { String userName=findUserByToken(req); if(appName.equalsIgnoreCase(applicationName)) { authService.deleteByUserId(userName); return Response.status(Status.OK).build(); } else { throw new OAuthException(ResponseCodes.ERR_DELETING_APP, HttpResponseStatus.BAD_REQUEST); } }
[ "@", "DELETE", "@", "Produces", "(", "MediaType", ".", "APPLICATION_JSON", ")", "@", "Path", "(", "\"/revoke_oauth_access/{appName}\"", ")", "@", "Description", "(", "\"Revokes Oauth access of app from argus for a particular user\"", ")", "public", "Response", "removeAccess...
Revokes Oauth access of app from argus for a particular user @param req The Http Request with authorization header @param appName Application Name which is recognized by Argus Oauth @return Returns either Success or OAuthException
[ "Revokes", "Oauth", "access", "of", "app", "from", "argus", "for", "a", "particular", "user" ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusWebServices/src/main/java/com/salesforce/dva/argus/ws/resources/UserResources.java#L437-L454
RestComm/Restcomm-Connect
restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/NumberSelectorServiceImpl.java
NumberSelectorServiceImpl.findByNumber
private NumberSelectionResult findByNumber(List<String> numberQueries, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers) { Boolean orgFiltered = false; NumberSelectionResult matchedNumber = new NumberSelectionResult(null, orgFiltered, null); int i = 0; while (matchedNumber.getNumber() == null && i < numberQueries.size()) { matchedNumber = findSingleNumber(numberQueries.get(i), sourceOrganizationSid, destinationOrganizationSid, modifiers); //preserve the orgFiltered flag along the queries if (matchedNumber.getOrganizationFiltered()) { orgFiltered = true; } i = i + 1; } matchedNumber.setOrganizationFiltered(orgFiltered); return matchedNumber; }
java
private NumberSelectionResult findByNumber(List<String> numberQueries, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers) { Boolean orgFiltered = false; NumberSelectionResult matchedNumber = new NumberSelectionResult(null, orgFiltered, null); int i = 0; while (matchedNumber.getNumber() == null && i < numberQueries.size()) { matchedNumber = findSingleNumber(numberQueries.get(i), sourceOrganizationSid, destinationOrganizationSid, modifiers); //preserve the orgFiltered flag along the queries if (matchedNumber.getOrganizationFiltered()) { orgFiltered = true; } i = i + 1; } matchedNumber.setOrganizationFiltered(orgFiltered); return matchedNumber; }
[ "private", "NumberSelectionResult", "findByNumber", "(", "List", "<", "String", ">", "numberQueries", ",", "Sid", "sourceOrganizationSid", ",", "Sid", "destinationOrganizationSid", ",", "Set", "<", "SearchModifier", ">", "modifiers", ")", "{", "Boolean", "orgFiltered"...
Iterates over the list of given numbers, and returns the first matching. @param numberQueries the list of numbers to attempt @param sourceOrganizationSid @param destinationOrganizationSid @return the matched number, null if not matched.
[ "Iterates", "over", "the", "list", "of", "given", "numbers", "and", "returns", "the", "first", "matching", "." ]
train
https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/NumberSelectorServiceImpl.java#L184-L200
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/FileListUtils.java
FileListUtils.listFilesRecursively
public static List<FileStatus> listFilesRecursively(FileSystem fs, Path path, PathFilter fileFilter, boolean applyFilterToDirectories) throws IOException { return listFilesRecursivelyHelper(fs, Lists.newArrayList(), fs.getFileStatus(path), fileFilter, applyFilterToDirectories, false); }
java
public static List<FileStatus> listFilesRecursively(FileSystem fs, Path path, PathFilter fileFilter, boolean applyFilterToDirectories) throws IOException { return listFilesRecursivelyHelper(fs, Lists.newArrayList(), fs.getFileStatus(path), fileFilter, applyFilterToDirectories, false); }
[ "public", "static", "List", "<", "FileStatus", ">", "listFilesRecursively", "(", "FileSystem", "fs", ",", "Path", "path", ",", "PathFilter", "fileFilter", ",", "boolean", "applyFilterToDirectories", ")", "throws", "IOException", "{", "return", "listFilesRecursivelyHel...
Helper method to list out all files under a specified path. If applyFilterToDirectories is false, the supplied {@link PathFilter} will only be applied to files.
[ "Helper", "method", "to", "list", "out", "all", "files", "under", "a", "specified", "path", ".", "If", "applyFilterToDirectories", "is", "false", "the", "supplied", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/FileListUtils.java#L125-L130
sevensource/html-email-service
src/main/java/org/sevensource/commons/email/model/DefaultEmailModel.java
DefaultEmailModel.setReplyTo
public void setReplyTo(String address, String personal) throws AddressException { replyTo = toInternetAddress(address, personal); }
java
public void setReplyTo(String address, String personal) throws AddressException { replyTo = toInternetAddress(address, personal); }
[ "public", "void", "setReplyTo", "(", "String", "address", ",", "String", "personal", ")", "throws", "AddressException", "{", "replyTo", "=", "toInternetAddress", "(", "address", ",", "personal", ")", ";", "}" ]
sets the reply to address @param address a valid email address @param personal the real world name of the sender (can be null) @throws AddressException in case of an invalid email address
[ "sets", "the", "reply", "to", "address" ]
train
https://github.com/sevensource/html-email-service/blob/a55d9ef1a2173917cb5f870854bc24e5aaebd182/src/main/java/org/sevensource/commons/email/model/DefaultEmailModel.java#L82-L84
jmrozanec/cron-utils
src/main/java/com/cronutils/mapper/CronMapper.java
CronMapper.returnOnZeroExpression
@VisibleForTesting static Function<CronField, CronField> returnOnZeroExpression(final CronFieldName name) { return field -> { final FieldConstraints constraints = FieldConstraintsBuilder.instance().forField(name).createConstraintsInstance(); return new CronField(name, new On(new IntegerFieldValue(0)), constraints); }; }
java
@VisibleForTesting static Function<CronField, CronField> returnOnZeroExpression(final CronFieldName name) { return field -> { final FieldConstraints constraints = FieldConstraintsBuilder.instance().forField(name).createConstraintsInstance(); return new CronField(name, new On(new IntegerFieldValue(0)), constraints); }; }
[ "@", "VisibleForTesting", "static", "Function", "<", "CronField", ",", "CronField", ">", "returnOnZeroExpression", "(", "final", "CronFieldName", "name", ")", "{", "return", "field", "->", "{", "final", "FieldConstraints", "constraints", "=", "FieldConstraintsBuilder"...
Creates a Function that returns a On instance with zero value. @param name - Cron field name @return new CronField -> CronField instance, never null
[ "Creates", "a", "Function", "that", "returns", "a", "On", "instance", "with", "zero", "value", "." ]
train
https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/mapper/CronMapper.java#L226-L232
pressgang-ccms/PressGangCCMSBuilder
src/main/java/org/jboss/pressgang/ccms/contentspec/builder/PublicanPODocBookBuilder.java
PublicanPODocBookBuilder.checkAndAddListInjections
protected void checkAndAddListInjections(final BuildData buildData, final Document doc, final ITopicNode topicNode, final Map<String, TranslationDetails> translations) { final DocBookXMLPreProcessor preProcessor = buildData.getXMLPreProcessor(); final List<Integer> types = Arrays.asList(DocBookXMLPreProcessor.ORDEREDLIST_INJECTION_POINT, DocBookXMLPreProcessor.ITEMIZEDLIST_INJECTION_POINT, DocBookXMLPreProcessor.LIST_INJECTION_POINT); final HashMap<org.w3c.dom.Node, InjectionListData> customInjections = new HashMap<org.w3c.dom.Node, InjectionListData>(); preProcessor.collectInjectionData(buildData.getContentSpec(), topicNode, new ArrayList<String>(), doc, buildData.getBuildDatabase(), new ArrayList<String>(), customInjections, buildData.isUseFixedUrls(), types); // Now convert the custom injection points for (final org.w3c.dom.Node customInjectionCommentNode : customInjections.keySet()) { final InjectionListData injectionListData = customInjections.get(customInjectionCommentNode); /* * this may not be true if we are not building all related topics */ if (injectionListData.listItems.size() != 0) { for (final List<Element> elements : injectionListData.listItems) { final Element para = doc.createElement("para"); for (final Element element : elements) { para.appendChild(element); } final String translationString = XMLUtilities.convertNodeToString(para, false); translations.put(translationString, new TranslationDetails(translationString, false, "para")); } } } }
java
protected void checkAndAddListInjections(final BuildData buildData, final Document doc, final ITopicNode topicNode, final Map<String, TranslationDetails> translations) { final DocBookXMLPreProcessor preProcessor = buildData.getXMLPreProcessor(); final List<Integer> types = Arrays.asList(DocBookXMLPreProcessor.ORDEREDLIST_INJECTION_POINT, DocBookXMLPreProcessor.ITEMIZEDLIST_INJECTION_POINT, DocBookXMLPreProcessor.LIST_INJECTION_POINT); final HashMap<org.w3c.dom.Node, InjectionListData> customInjections = new HashMap<org.w3c.dom.Node, InjectionListData>(); preProcessor.collectInjectionData(buildData.getContentSpec(), topicNode, new ArrayList<String>(), doc, buildData.getBuildDatabase(), new ArrayList<String>(), customInjections, buildData.isUseFixedUrls(), types); // Now convert the custom injection points for (final org.w3c.dom.Node customInjectionCommentNode : customInjections.keySet()) { final InjectionListData injectionListData = customInjections.get(customInjectionCommentNode); /* * this may not be true if we are not building all related topics */ if (injectionListData.listItems.size() != 0) { for (final List<Element> elements : injectionListData.listItems) { final Element para = doc.createElement("para"); for (final Element element : elements) { para.appendChild(element); } final String translationString = XMLUtilities.convertNodeToString(para, false); translations.put(translationString, new TranslationDetails(translationString, false, "para")); } } } }
[ "protected", "void", "checkAndAddListInjections", "(", "final", "BuildData", "buildData", ",", "final", "Document", "doc", ",", "final", "ITopicNode", "topicNode", ",", "final", "Map", "<", "String", ",", "TranslationDetails", ">", "translations", ")", "{", "final...
Checks to see if any list injections have been used and if so adds the translation xrefs. @param buildData Information and data structures for the build. @param doc The DOM Document to look for list injections in. @param topicNode The topic to get the injections for. @param translations The mapping of original strings to translation strings, that will be used to build the po/pot files.
[ "Checks", "to", "see", "if", "any", "list", "injections", "have", "been", "used", "and", "if", "so", "adds", "the", "translation", "xrefs", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/PublicanPODocBookBuilder.java#L447-L477
OpenLiberty/open-liberty
dev/com.ibm.json4j/src/com/ibm/json/xml/internal/JSONObject.java
JSONObject.writeIndention
private void writeIndention(Writer writer, int indentDepth) throws IOException { if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeIndention(Writer, int)"); try { for (int i = 0; i < indentDepth; i++) { writer.write(indent); } } catch (Exception ex) { IOException iox = new IOException("Error occurred on serialization of JSON text."); iox.initCause(ex); throw iox; } if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeIndention(Writer, int)"); }
java
private void writeIndention(Writer writer, int indentDepth) throws IOException { if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeIndention(Writer, int)"); try { for (int i = 0; i < indentDepth; i++) { writer.write(indent); } } catch (Exception ex) { IOException iox = new IOException("Error occurred on serialization of JSON text."); iox.initCause(ex); throw iox; } if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeIndention(Writer, int)"); }
[ "private", "void", "writeIndention", "(", "Writer", "writer", ",", "int", "indentDepth", ")", "throws", "IOException", "{", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINER", ")", ")", "logger", ".", "entering", "(", "className", ",", "\"w...
Internal method for doing a simple indention write. @param writer The writer to use while writing the JSON text. @param indentDepth How deep to indent the text. @throws IOException Trhown if an error occurs on write.
[ "Internal", "method", "for", "doing", "a", "simple", "indention", "write", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.json4j/src/com/ibm/json/xml/internal/JSONObject.java#L242-L262
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/server/core/DummyInvocationUtils.java
DummyInvocationUtils.methodOn
public static <T> T methodOn(Class<T> type, Object... parameters) { Assert.notNull(type, "Given type must not be null!"); InvocationRecordingMethodInterceptor interceptor = new InvocationRecordingMethodInterceptor(type, parameters); return getProxyWithInterceptor(type, interceptor, type.getClassLoader()); }
java
public static <T> T methodOn(Class<T> type, Object... parameters) { Assert.notNull(type, "Given type must not be null!"); InvocationRecordingMethodInterceptor interceptor = new InvocationRecordingMethodInterceptor(type, parameters); return getProxyWithInterceptor(type, interceptor, type.getClassLoader()); }
[ "public", "static", "<", "T", ">", "T", "methodOn", "(", "Class", "<", "T", ">", "type", ",", "Object", "...", "parameters", ")", "{", "Assert", ".", "notNull", "(", "type", ",", "\"Given type must not be null!\"", ")", ";", "InvocationRecordingMethodIntercept...
Returns a proxy of the given type, backed by an {@link EmptyTargetSource} to simply drop method invocations but equips it with an {@link InvocationRecordingMethodInterceptor}. The interceptor records the last invocation and returns a proxy of the return type that also implements {@link LastInvocationAware} so that the last method invocation can be inspected. Parameters passed to the subsequent method invocation are generally neglected except the ones that might be mapped into the URI translation eventually, e.g. {@link org.springframework.web.bind.annotation.PathVariable} in the case of Spring MVC. Note, that the return types of the methods have to be capable to be proxied. @param type must not be {@literal null}. @param parameters parameters to extend template variables in the type level mapping. @return
[ "Returns", "a", "proxy", "of", "the", "given", "type", "backed", "by", "an", "{", "@link", "EmptyTargetSource", "}", "to", "simply", "drop", "method", "invocations", "but", "equips", "it", "with", "an", "{", "@link", "InvocationRecordingMethodInterceptor", "}", ...
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/core/DummyInvocationUtils.java#L134-L140
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/GCMMessage.java
GCMMessage.withData
public GCMMessage withData(java.util.Map<String, String> data) { setData(data); return this; }
java
public GCMMessage withData(java.util.Map<String, String> data) { setData(data); return this; }
[ "public", "GCMMessage", "withData", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "data", ")", "{", "setData", "(", "data", ")", ";", "return", "this", ";", "}" ]
The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' object @param data The data payload used for a silent push. This payload is added to the notifications' data.pinpoint.jsonBody' object @return Returns a reference to this object so that method calls can be chained together.
[ "The", "data", "payload", "used", "for", "a", "silent", "push", ".", "This", "payload", "is", "added", "to", "the", "notifications", "data", ".", "pinpoint", ".", "jsonBody", "object" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/GCMMessage.java#L324-L327
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java
ApiOvhDedicatedCloud.serviceName_orderableIpCountries_GET
public ArrayList<OvhIpCountriesEnum> serviceName_orderableIpCountries_GET(String serviceName) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/orderableIpCountries"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
java
public ArrayList<OvhIpCountriesEnum> serviceName_orderableIpCountries_GET(String serviceName) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/orderableIpCountries"; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t4); }
[ "public", "ArrayList", "<", "OvhIpCountriesEnum", ">", "serviceName_orderableIpCountries_GET", "(", "String", "serviceName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicatedCloud/{serviceName}/orderableIpCountries\"", ";", "StringBuilder", "sb", "=", ...
Get the countries you can select in /order/dedicatedCloud/{serviceName}/ip REST: GET /dedicatedCloud/{serviceName}/orderableIpCountries @param serviceName [required] Domain of the service
[ "Get", "the", "countries", "you", "can", "select", "in", "/", "order", "/", "dedicatedCloud", "/", "{", "serviceName", "}", "/", "ip" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedCloud.java#L1467-L1472
sebastiangraf/jSCSI
bundles/target/src/main/java/org/jscsi/target/settings/TextParameter.java
TextParameter.toKeyValuePair
public static String toKeyValuePair (final String key, final String value) { return key + TextKeyword.EQUALS + value; }
java
public static String toKeyValuePair (final String key, final String value) { return key + TextKeyword.EQUALS + value; }
[ "public", "static", "String", "toKeyValuePair", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "return", "key", "+", "TextKeyword", ".", "EQUALS", "+", "value", ";", "}" ]
Joins a <i>key</i> and a <i>value</i> {@link String} to a <i>key=value</i> pair as required by iSCSI text parameter negotiation and returns the result. @param key the <i>key</i> part @param value the <i>value</i> part @return the concatenated <i>key=value</i> pair
[ "Joins", "a", "<i", ">", "key<", "/", "i", ">", "and", "a", "<i", ">", "value<", "/", "i", ">", "{", "@link", "String", "}", "to", "a", "<i", ">", "key", "=", "value<", "/", "i", ">", "pair", "as", "required", "by", "iSCSI", "text", "parameter"...
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/target/src/main/java/org/jscsi/target/settings/TextParameter.java#L175-L177
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/file/FileHelper.java
FileHelper.getOutputStream
@Nullable public static FileOutputStream getOutputStream (@Nonnull final File aFile, @Nonnull final EAppend eAppend) { ValueEnforcer.notNull (aFile, "File"); ValueEnforcer.notNull (eAppend, "Append"); if (internalCheckParentDirectoryExistanceAndAccess (aFile).isInvalid ()) return null; // OK, parent is present and writable try { return new CountingFileOutputStream (aFile, eAppend); } catch (final FileNotFoundException ex) { if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Failed to create output stream for '" + aFile + "'; append: " + eAppend + ": " + ex.getClass ().getName () + " - " + ex.getMessage ()); return null; } }
java
@Nullable public static FileOutputStream getOutputStream (@Nonnull final File aFile, @Nonnull final EAppend eAppend) { ValueEnforcer.notNull (aFile, "File"); ValueEnforcer.notNull (eAppend, "Append"); if (internalCheckParentDirectoryExistanceAndAccess (aFile).isInvalid ()) return null; // OK, parent is present and writable try { return new CountingFileOutputStream (aFile, eAppend); } catch (final FileNotFoundException ex) { if (LOGGER.isWarnEnabled ()) LOGGER.warn ("Failed to create output stream for '" + aFile + "'; append: " + eAppend + ": " + ex.getClass ().getName () + " - " + ex.getMessage ()); return null; } }
[ "@", "Nullable", "public", "static", "FileOutputStream", "getOutputStream", "(", "@", "Nonnull", "final", "File", "aFile", ",", "@", "Nonnull", "final", "EAppend", "eAppend", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aFile", ",", "\"File\"", ")", ";", ...
Get an output stream for writing to a file. @param aFile The file to write to. May not be <code>null</code>. @param eAppend Appending mode. May not be <code>null</code>. @return <code>null</code> if the file could not be opened
[ "Get", "an", "output", "stream", "for", "writing", "to", "a", "file", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/file/FileHelper.java#L363-L390
reactor/reactor-netty
src/main/java/reactor/netty/http/client/HttpClient.java
HttpClient.doOnError
public final HttpClient doOnError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequest, BiConsumer<? super HttpClientResponse, ? super Throwable> doOnResponse) { Objects.requireNonNull(doOnRequest, "doOnRequest"); Objects.requireNonNull(doOnResponse, "doOnResponse"); return new HttpClientDoOnError(this, doOnRequest, doOnResponse); }
java
public final HttpClient doOnError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequest, BiConsumer<? super HttpClientResponse, ? super Throwable> doOnResponse) { Objects.requireNonNull(doOnRequest, "doOnRequest"); Objects.requireNonNull(doOnResponse, "doOnResponse"); return new HttpClientDoOnError(this, doOnRequest, doOnResponse); }
[ "public", "final", "HttpClient", "doOnError", "(", "BiConsumer", "<", "?", "super", "HttpClientRequest", ",", "?", "super", "Throwable", ">", "doOnRequest", ",", "BiConsumer", "<", "?", "super", "HttpClientResponse", ",", "?", "super", "Throwable", ">", "doOnRes...
Setup a callback called when {@link HttpClientRequest} has not been sent and when {@link HttpClientResponse} has not been fully received. <p> Note that some mutation of {@link HttpClientRequest} performed late in lifecycle {@link #doOnRequest(BiConsumer)} or {@link RequestSender#send(BiFunction)} might not be visible if the error results from a connection failure. @param doOnRequest a consumer observing connected events @param doOnResponse a consumer observing response failures @return a new {@link HttpClient}
[ "Setup", "a", "callback", "called", "when", "{", "@link", "HttpClientRequest", "}", "has", "not", "been", "sent", "and", "when", "{", "@link", "HttpClientResponse", "}", "has", "not", "been", "fully", "received", ".", "<p", ">", "Note", "that", "some", "mu...
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/client/HttpClient.java#L501-L506
alkacon/opencms-core
src/org/opencms/ade/sitemap/CmsVfsSitemapService.java
CmsVfsSitemapService.isInSubsite
private boolean isInSubsite(List<String> subSitePaths, String path) { boolean result = false; for (String subSite : subSitePaths) { if (path.startsWith(subSite)) { result = true; break; } } return result; }
java
private boolean isInSubsite(List<String> subSitePaths, String path) { boolean result = false; for (String subSite : subSitePaths) { if (path.startsWith(subSite)) { result = true; break; } } return result; }
[ "private", "boolean", "isInSubsite", "(", "List", "<", "String", ">", "subSitePaths", ",", "String", "path", ")", "{", "boolean", "result", "=", "false", ";", "for", "(", "String", "subSite", ":", "subSitePaths", ")", "{", "if", "(", "path", ".", "starts...
Returns if the given path is located below one of the given sub site paths.<p> @param subSitePaths the sub site root paths @param path the root path to check @return <code>true</code> if the given path is located below one of the given sub site paths
[ "Returns", "if", "the", "given", "path", "is", "located", "below", "one", "of", "the", "given", "sub", "site", "paths", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/sitemap/CmsVfsSitemapService.java#L2764-L2774
mlhartme/sushi
src/main/java/net/oneandone/sushi/fs/filter/Filter.java
Filter.invoke
public void invoke(Node root, Action result) throws IOException { doInvoke(0, root, root.isLink(), new ArrayList<>(includes), new ArrayList<>(excludes), result); }
java
public void invoke(Node root, Action result) throws IOException { doInvoke(0, root, root.isLink(), new ArrayList<>(includes), new ArrayList<>(excludes), result); }
[ "public", "void", "invoke", "(", "Node", "root", ",", "Action", "result", ")", "throws", "IOException", "{", "doInvoke", "(", "0", ",", "root", ",", "root", ".", "isLink", "(", ")", ",", "new", "ArrayList", "<>", "(", "includes", ")", ",", "new", "Ar...
Main methods of this class. @throws IOException as thrown by the specified FileTask
[ "Main", "methods", "of", "this", "class", "." ]
train
https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/fs/filter/Filter.java#L274-L276
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/tm/tmsessionpolicy.java
tmsessionpolicy.get
public static tmsessionpolicy get(nitro_service service, String name) throws Exception{ tmsessionpolicy obj = new tmsessionpolicy(); obj.set_name(name); tmsessionpolicy response = (tmsessionpolicy) obj.get_resource(service); return response; }
java
public static tmsessionpolicy get(nitro_service service, String name) throws Exception{ tmsessionpolicy obj = new tmsessionpolicy(); obj.set_name(name); tmsessionpolicy response = (tmsessionpolicy) obj.get_resource(service); return response; }
[ "public", "static", "tmsessionpolicy", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "tmsessionpolicy", "obj", "=", "new", "tmsessionpolicy", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "tms...
Use this API to fetch tmsessionpolicy resource of given name .
[ "Use", "this", "API", "to", "fetch", "tmsessionpolicy", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/tm/tmsessionpolicy.java#L330-L335
apereo/cas
support/cas-server-support-saml-mdui-core/src/main/java/org/apereo/cas/support/saml/mdui/SamlMetadataUIInfo.java
SamlMetadataUIInfo.getLocalizedValues
private static String getLocalizedValues(final String locale, final List<?> items) { val foundLocale = findLocale(StringUtils.defaultString(locale, "en"), items); if (foundLocale.isPresent()) { return foundLocale.get(); } if (!items.isEmpty()) { val item = items.get(0); var value = StringUtils.EMPTY; if (item instanceof LocalizedName) { value = ((LocalizedName) item).getValue(); } if (item instanceof LocalizedURI) { value = ((LocalizedURI) item).getValue(); } if (item instanceof XSString) { value = ((XSString) item).getValue(); } LOGGER.trace("Loading first available locale [{}]", value); return value; } return null; }
java
private static String getLocalizedValues(final String locale, final List<?> items) { val foundLocale = findLocale(StringUtils.defaultString(locale, "en"), items); if (foundLocale.isPresent()) { return foundLocale.get(); } if (!items.isEmpty()) { val item = items.get(0); var value = StringUtils.EMPTY; if (item instanceof LocalizedName) { value = ((LocalizedName) item).getValue(); } if (item instanceof LocalizedURI) { value = ((LocalizedURI) item).getValue(); } if (item instanceof XSString) { value = ((XSString) item).getValue(); } LOGGER.trace("Loading first available locale [{}]", value); return value; } return null; }
[ "private", "static", "String", "getLocalizedValues", "(", "final", "String", "locale", ",", "final", "List", "<", "?", ">", "items", ")", "{", "val", "foundLocale", "=", "findLocale", "(", "StringUtils", ".", "defaultString", "(", "locale", ",", "\"en\"", ")...
Gets localized values. @param locale browser preferred language @param items the items @return the string value
[ "Gets", "localized", "values", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-saml-mdui-core/src/main/java/org/apereo/cas/support/saml/mdui/SamlMetadataUIInfo.java#L211-L233
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-pkix/src/main/java/org/xwiki/crypto/pkix/internal/extension/AbstractBcX509ExtensionBuilder.java
AbstractBcX509ExtensionBuilder.addExtension
public X509ExtensionBuilder addExtension(ASN1ObjectIdentifier oid, boolean critical, ASN1Encodable value) { try { this.extensions.addExtension(oid, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); } catch (IOException e) { // Very unlikely throw new IllegalArgumentException("Invalid extension value, it could not be properly DER encoded."); } return this; }
java
public X509ExtensionBuilder addExtension(ASN1ObjectIdentifier oid, boolean critical, ASN1Encodable value) { try { this.extensions.addExtension(oid, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); } catch (IOException e) { // Very unlikely throw new IllegalArgumentException("Invalid extension value, it could not be properly DER encoded."); } return this; }
[ "public", "X509ExtensionBuilder", "addExtension", "(", "ASN1ObjectIdentifier", "oid", ",", "boolean", "critical", ",", "ASN1Encodable", "value", ")", "{", "try", "{", "this", ".", "extensions", ".", "addExtension", "(", "oid", ",", "critical", ",", "value", ".",...
Add an extension. @param oid the extension oid. @param critical true if the extension is critical. @param value the value of the extension. @return this extensions builder to allow chaining.
[ "Add", "an", "extension", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-crypto/xwiki-commons-crypto-pkix/src/main/java/org/xwiki/crypto/pkix/internal/extension/AbstractBcX509ExtensionBuilder.java#L86-L95
apache/groovy
subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
NioGroovyMethods.withCloseable
@Deprecated public static <T> T withCloseable(Closeable self, @ClosureParams(value = SimpleType.class, options = "java.io.Closeable") Closure<T> action) throws IOException { return IOGroovyMethods.withCloseable(self, action); }
java
@Deprecated public static <T> T withCloseable(Closeable self, @ClosureParams(value = SimpleType.class, options = "java.io.Closeable") Closure<T> action) throws IOException { return IOGroovyMethods.withCloseable(self, action); }
[ "@", "Deprecated", "public", "static", "<", "T", ">", "T", "withCloseable", "(", "Closeable", "self", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.Closeable\"", ")", "Closure", "<", "T", ">", "ac...
#deprecated use the variant in IOGroovyMethods @see org.codehaus.groovy.runtime.IOGroovyMethods#withCloseable(java.io.Closeable, groovy.lang.Closure) @since 2.3.0
[ "#deprecated", "use", "the", "variant", "in", "IOGroovyMethods" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java#L1919-L1922
geomajas/geomajas-project-server
plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/impl/PrintComponentImpl.java
PrintComponentImpl.calculateSize
public void calculateSize(PdfContext context) { float width = 0; float height = 0; for (PrintComponent<?> child : children) { child.calculateSize(context); float cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX(); float ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY(); switch (getConstraint().getFlowDirection()) { case LayoutConstraint.FLOW_NONE: width = Math.max(width, cw); height = Math.max(height, ch); break; case LayoutConstraint.FLOW_X: width += cw; height = Math.max(height, ch); break; case LayoutConstraint.FLOW_Y: width = Math.max(width, cw); height += ch; break; default: throw new IllegalStateException("Unknown flow direction " + getConstraint().getFlowDirection()); } } if (getConstraint().getWidth() != 0) { width = getConstraint().getWidth(); } if (getConstraint().getHeight() != 0) { height = getConstraint().getHeight(); } setBounds(new Rectangle(0, 0, width, height)); }
java
public void calculateSize(PdfContext context) { float width = 0; float height = 0; for (PrintComponent<?> child : children) { child.calculateSize(context); float cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX(); float ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY(); switch (getConstraint().getFlowDirection()) { case LayoutConstraint.FLOW_NONE: width = Math.max(width, cw); height = Math.max(height, ch); break; case LayoutConstraint.FLOW_X: width += cw; height = Math.max(height, ch); break; case LayoutConstraint.FLOW_Y: width = Math.max(width, cw); height += ch; break; default: throw new IllegalStateException("Unknown flow direction " + getConstraint().getFlowDirection()); } } if (getConstraint().getWidth() != 0) { width = getConstraint().getWidth(); } if (getConstraint().getHeight() != 0) { height = getConstraint().getHeight(); } setBounds(new Rectangle(0, 0, width, height)); }
[ "public", "void", "calculateSize", "(", "PdfContext", "context", ")", "{", "float", "width", "=", "0", ";", "float", "height", "=", "0", ";", "for", "(", "PrintComponent", "<", "?", ">", "child", ":", "children", ")", "{", "child", ".", "calculateSize", ...
Calculates the size based constraint width and height if present, otherwise from children sizes.
[ "Calculates", "the", "size", "based", "constraint", "width", "and", "height", "if", "present", "otherwise", "from", "children", "sizes", "." ]
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/plugin/print/print/src/main/java/org/geomajas/plugin/printing/component/impl/PrintComponentImpl.java#L139-L170
Twitter4J/Twitter4J
twitter4j-core/src/main/java/twitter4j/conf/PropertyConfiguration.java
PropertyConfiguration.setFieldsWithTreePath
private void setFieldsWithTreePath(Properties props, String treePath) { setFieldsWithPrefix(props, ""); String[] splitArray = treePath.split("/"); String prefix = null; for (String split : splitArray) { if (!"".equals(split)) { if (null == prefix) { prefix = split + "."; } else { prefix += split + "."; } setFieldsWithPrefix(props, prefix); } } }
java
private void setFieldsWithTreePath(Properties props, String treePath) { setFieldsWithPrefix(props, ""); String[] splitArray = treePath.split("/"); String prefix = null; for (String split : splitArray) { if (!"".equals(split)) { if (null == prefix) { prefix = split + "."; } else { prefix += split + "."; } setFieldsWithPrefix(props, prefix); } } }
[ "private", "void", "setFieldsWithTreePath", "(", "Properties", "props", ",", "String", "treePath", ")", "{", "setFieldsWithPrefix", "(", "props", ",", "\"\"", ")", ";", "String", "[", "]", "splitArray", "=", "treePath", ".", "split", "(", "\"/\"", ")", ";", ...
passing "/foo/bar" as treePath will result:<br> 1. load [twitter4j.]restBaseURL<br> 2. override the value with foo.[twitter4j.]restBaseURL<br> 3. override the value with foo.bar.[twitter4j.]restBaseURL<br> @param props properties to be loaded @param treePath the path
[ "passing", "/", "foo", "/", "bar", "as", "treePath", "will", "result", ":", "<br", ">", "1", ".", "load", "[", "twitter4j", ".", "]", "restBaseURL<br", ">", "2", ".", "override", "the", "value", "with", "foo", ".", "[", "twitter4j", ".", "]", "restBa...
train
https://github.com/Twitter4J/Twitter4J/blob/8376fade8d557896bb9319fb46e39a55b134b166/twitter4j-core/src/main/java/twitter4j/conf/PropertyConfiguration.java#L215-L229
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/query/impl/Indexes.java
Indexes.putEntry
public void putEntry(QueryableEntry queryableEntry, Object oldValue, Index.OperationSource operationSource) { InternalIndex[] indexes = getIndexes(); for (InternalIndex index : indexes) { index.putEntry(queryableEntry, oldValue, operationSource); } }
java
public void putEntry(QueryableEntry queryableEntry, Object oldValue, Index.OperationSource operationSource) { InternalIndex[] indexes = getIndexes(); for (InternalIndex index : indexes) { index.putEntry(queryableEntry, oldValue, operationSource); } }
[ "public", "void", "putEntry", "(", "QueryableEntry", "queryableEntry", ",", "Object", "oldValue", ",", "Index", ".", "OperationSource", "operationSource", ")", "{", "InternalIndex", "[", "]", "indexes", "=", "getIndexes", "(", ")", ";", "for", "(", "InternalInde...
Inserts a new queryable entry into this indexes instance or updates the existing one. @param queryableEntry the queryable entry to insert or update. @param oldValue the old entry value to update, {@code null} if inserting the new entry. @param operationSource the operation source.
[ "Inserts", "a", "new", "queryable", "entry", "into", "this", "indexes", "instance", "or", "updates", "the", "existing", "one", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/query/impl/Indexes.java#L217-L222
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/input/A_CmsSelectCell.java
A_CmsSelectCell.registerDomHandler
public <H extends EventHandler> HandlerRegistration registerDomHandler(final H handler, DomEvent.Type<H> type) { return addDomHandler(handler, type); }
java
public <H extends EventHandler> HandlerRegistration registerDomHandler(final H handler, DomEvent.Type<H> type) { return addDomHandler(handler, type); }
[ "public", "<", "H", "extends", "EventHandler", ">", "HandlerRegistration", "registerDomHandler", "(", "final", "H", "handler", ",", "DomEvent", ".", "Type", "<", "H", ">", "type", ")", "{", "return", "addDomHandler", "(", "handler", ",", "type", ")", ";", ...
Adds a new event handler to the widget.<p> This method is used because we want the select box to register some event handlers on this widget, but we can't use {@link com.google.gwt.user.client.ui.Widget#addDomHandler} directly, since it's both protected and final. @param <H> the event type @param handler the new event handler @param type the event type object @return the HandlerRegistration for removing the event handler
[ "Adds", "a", "new", "event", "handler", "to", "the", "widget", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/A_CmsSelectCell.java#L83-L86
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java
FileWriter.writeMap
public File writeMap(Map<?, ?> map, LineSeparator lineSeparator, String kvSeparator, boolean isAppend) throws IORuntimeException { if(null == kvSeparator) { kvSeparator = " = "; } try(PrintWriter writer = getPrintWriter(isAppend)) { for (Entry<?, ?> entry : map.entrySet()) { if (null != entry) { writer.print(StrUtil.format("{}{}{}", entry.getKey(), kvSeparator, entry.getValue())); printNewLine(writer, lineSeparator); writer.flush(); } } } return this.file; }
java
public File writeMap(Map<?, ?> map, LineSeparator lineSeparator, String kvSeparator, boolean isAppend) throws IORuntimeException { if(null == kvSeparator) { kvSeparator = " = "; } try(PrintWriter writer = getPrintWriter(isAppend)) { for (Entry<?, ?> entry : map.entrySet()) { if (null != entry) { writer.print(StrUtil.format("{}{}{}", entry.getKey(), kvSeparator, entry.getValue())); printNewLine(writer, lineSeparator); writer.flush(); } } } return this.file; }
[ "public", "File", "writeMap", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "LineSeparator", "lineSeparator", ",", "String", "kvSeparator", ",", "boolean", "isAppend", ")", "throws", "IORuntimeException", "{", "if", "(", "null", "==", "kvSeparator", ")", ...
将Map写入文件,每个键值对为一行,一行中键与值之间使用kvSeparator分隔 @param map Map @param lineSeparator 换行符枚举(Windows、Mac或Linux换行符) @param kvSeparator 键和值之间的分隔符,如果传入null使用默认分隔符" = " @param isAppend 是否追加 @return 目标文件 @throws IORuntimeException IO异常 @since 4.0.5
[ "将Map写入文件,每个键值对为一行,一行中键与值之间使用kvSeparator分隔" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java#L235-L249
Omertron/api-themoviedb
src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java
TheMovieDbApi.getTVAccountState
public MediaState getTVAccountState(int tvID, String sessionID) throws MovieDbException { return tmdbTv.getTVAccountState(tvID, sessionID); }
java
public MediaState getTVAccountState(int tvID, String sessionID) throws MovieDbException { return tmdbTv.getTVAccountState(tvID, sessionID); }
[ "public", "MediaState", "getTVAccountState", "(", "int", "tvID", ",", "String", "sessionID", ")", "throws", "MovieDbException", "{", "return", "tmdbTv", ".", "getTVAccountState", "(", "tvID", ",", "sessionID", ")", ";", "}" ]
This method lets users get the status of whether or not the TV show has been rated or added to their favourite or watch lists. A valid session id is required. @param tvID tvID @param sessionID sessionID @return @throws com.omertron.themoviedbapi.MovieDbException
[ "This", "method", "lets", "users", "get", "the", "status", "of", "whether", "or", "not", "the", "TV", "show", "has", "been", "rated", "or", "added", "to", "their", "favourite", "or", "watch", "lists", "." ]
train
https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L1450-L1452
BioPAX/Paxtools
pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ConBox.java
ConBox.inSamePathway
public static Constraint inSamePathway() { String s1 = "Interaction/stepProcessOf/pathwayOrderOf"; String s2 = "Interaction/pathwayComponentOf"; return new OR(new MappedConst(new Field(s1, s1, Field.Operation.INTERSECT), 0, 1), new MappedConst(new Field(s2, s2, Field.Operation.INTERSECT), 0, 1)); }
java
public static Constraint inSamePathway() { String s1 = "Interaction/stepProcessOf/pathwayOrderOf"; String s2 = "Interaction/pathwayComponentOf"; return new OR(new MappedConst(new Field(s1, s1, Field.Operation.INTERSECT), 0, 1), new MappedConst(new Field(s2, s2, Field.Operation.INTERSECT), 0, 1)); }
[ "public", "static", "Constraint", "inSamePathway", "(", ")", "{", "String", "s1", "=", "\"Interaction/stepProcessOf/pathwayOrderOf\"", ";", "String", "s2", "=", "\"Interaction/pathwayComponentOf\"", ";", "return", "new", "OR", "(", "new", "MappedConst", "(", "new", ...
Makes sure that the two interactions are members of the same pathway. @return non-generative constraint
[ "Makes", "sure", "that", "the", "two", "interactions", "are", "members", "of", "the", "same", "pathway", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/constraint/ConBox.java#L606-L612
jboss/jboss-jstl-api_spec
src/main/java/javax/servlet/jsp/jstl/fmt/JakartaInline.java
JakartaInline.setResponseLocale
static void setResponseLocale(PageContext pc, Locale locale) { // set response locale ServletResponse response = pc.getResponse(); response.setLocale(locale); // get response character encoding and store it in session attribute if (pc.getSession() != null) { try { pc.setAttribute(REQUEST_CHAR_SET, response.getCharacterEncoding(), PageContext.SESSION_SCOPE); } catch (IllegalStateException ex) { } // invalidated session ignored } }
java
static void setResponseLocale(PageContext pc, Locale locale) { // set response locale ServletResponse response = pc.getResponse(); response.setLocale(locale); // get response character encoding and store it in session attribute if (pc.getSession() != null) { try { pc.setAttribute(REQUEST_CHAR_SET, response.getCharacterEncoding(), PageContext.SESSION_SCOPE); } catch (IllegalStateException ex) { } // invalidated session ignored } }
[ "static", "void", "setResponseLocale", "(", "PageContext", "pc", ",", "Locale", "locale", ")", "{", "// set response locale", "ServletResponse", "response", "=", "pc", ".", "getResponse", "(", ")", ";", "response", ".", "setLocale", "(", "locale", ")", ";", "/...
/* Stores the given locale in the response object of the given page context, and stores the locale's associated charset in the javax.servlet.jsp.jstl.fmt.request.charset session attribute, which may be used by the <requestEncoding> action in a page invoked by a form included in the response to set the request charset to the same as the response charset (this makes it possible for the container to decode the form parameter values properly, since browsers typically encode form field values using the response's charset). @param pageContext the page context whose response object is assigned the given locale @param locale the response locale
[ "/", "*", "Stores", "the", "given", "locale", "in", "the", "response", "object", "of", "the", "given", "page", "context", "and", "stores", "the", "locale", "s", "associated", "charset", "in", "the", "javax", ".", "servlet", ".", "jsp", ".", "jstl", ".", ...
train
https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/javax/servlet/jsp/jstl/fmt/JakartaInline.java#L332-L345
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/databases/AbstractDatabase.java
AbstractDatabase.defineTableParent
public T defineTableParent(final Connection _con, final String _table, final String _parentTable) throws InstallationException { return addForeignKey(_con, _table, _table + "_FK_ID", "ID", _parentTable + "(ID)", false); }
java
public T defineTableParent(final Connection _con, final String _table, final String _parentTable) throws InstallationException { return addForeignKey(_con, _table, _table + "_FK_ID", "ID", _parentTable + "(ID)", false); }
[ "public", "T", "defineTableParent", "(", "final", "Connection", "_con", ",", "final", "String", "_table", ",", "final", "String", "_parentTable", ")", "throws", "InstallationException", "{", "return", "addForeignKey", "(", "_con", ",", "_table", ",", "_table", "...
For a new created SQL table the column <code>ID</code> is update with a foreign key to a parent table. @param _con SQL connection @param _table name of the SQL table to update @param _parentTable name of the parent table @return this instance @throws InstallationException if the update of the table failed
[ "For", "a", "new", "created", "SQL", "table", "the", "column", "<code", ">", "ID<", "/", "code", ">", "is", "update", "with", "a", "foreign", "key", "to", "a", "parent", "table", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/databases/AbstractDatabase.java#L646-L652
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeDiffComputer.java
TypeDiffComputer.computeAnyFieldDifferences
@SuppressWarnings("unchecked") private static void computeAnyFieldDifferences(FieldNode oField, FieldNode nField, TypeDelta td) { // Want to record things that are different between these two fields... FieldDelta fd = new FieldDelta(oField.name); if (oField.access != nField.access) { // access changed fd.setAccessChanged(oField.access, nField.access); } if (!oField.desc.equals(nField.desc)) { // type changed fd.setTypeChanged(oField.desc, nField.desc); } String annotationChange = compareAnnotations(oField.invisibleAnnotations, nField.invisibleAnnotations); annotationChange = annotationChange + compareAnnotations(oField.visibleAnnotations, nField.visibleAnnotations); if (annotationChange.length() != 0) { fd.setAnnotationsChanged(annotationChange); } if (fd.hasAnyChanges()) { // it needs recording td.addChangedField(fd); } }
java
@SuppressWarnings("unchecked") private static void computeAnyFieldDifferences(FieldNode oField, FieldNode nField, TypeDelta td) { // Want to record things that are different between these two fields... FieldDelta fd = new FieldDelta(oField.name); if (oField.access != nField.access) { // access changed fd.setAccessChanged(oField.access, nField.access); } if (!oField.desc.equals(nField.desc)) { // type changed fd.setTypeChanged(oField.desc, nField.desc); } String annotationChange = compareAnnotations(oField.invisibleAnnotations, nField.invisibleAnnotations); annotationChange = annotationChange + compareAnnotations(oField.visibleAnnotations, nField.visibleAnnotations); if (annotationChange.length() != 0) { fd.setAnnotationsChanged(annotationChange); } if (fd.hasAnyChanges()) { // it needs recording td.addChangedField(fd); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "void", "computeAnyFieldDifferences", "(", "FieldNode", "oField", ",", "FieldNode", "nField", ",", "TypeDelta", "td", ")", "{", "// Want to record things that are different between these two fields...", ...
Check the properties of the field - if they have changed at all then record what kind of change for the field. Thinking the type delta should have a map from names to a delta describing (capturing) the change.
[ "Check", "the", "properties", "of", "the", "field", "-", "if", "they", "have", "changed", "at", "all", "then", "record", "what", "kind", "of", "change", "for", "the", "field", ".", "Thinking", "the", "type", "delta", "should", "have", "a", "map", "from",...
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeDiffComputer.java#L153-L174
HeidelTime/heideltime
src/jmaxent/Feature.java
Feature.FeatureInit
public void FeatureInit(String str, Map cpStr2Int, Map lbStr2Int) { StringTokenizer strTok = new StringTokenizer(str, " \t\r\n"); // <label> <cp> <idx> <wgt> int len = strTok.countTokens(); if (len != 4) { return; } String labelStr = strTok.nextToken(); String cpStr = strTok.nextToken(); int idx = Integer.parseInt(strTok.nextToken()); float val = 1; double wgt = Double.parseDouble(strTok.nextToken()); Integer labelInt = (Integer)lbStr2Int.get(labelStr); Integer cpInt = (Integer)cpStr2Int.get(cpStr); FeatureInit(labelInt.intValue(), cpInt.intValue()); this.idx = idx; this.val = val; this.wgt = wgt; }
java
public void FeatureInit(String str, Map cpStr2Int, Map lbStr2Int) { StringTokenizer strTok = new StringTokenizer(str, " \t\r\n"); // <label> <cp> <idx> <wgt> int len = strTok.countTokens(); if (len != 4) { return; } String labelStr = strTok.nextToken(); String cpStr = strTok.nextToken(); int idx = Integer.parseInt(strTok.nextToken()); float val = 1; double wgt = Double.parseDouble(strTok.nextToken()); Integer labelInt = (Integer)lbStr2Int.get(labelStr); Integer cpInt = (Integer)cpStr2Int.get(cpStr); FeatureInit(labelInt.intValue(), cpInt.intValue()); this.idx = idx; this.val = val; this.wgt = wgt; }
[ "public", "void", "FeatureInit", "(", "String", "str", ",", "Map", "cpStr2Int", ",", "Map", "lbStr2Int", ")", "{", "StringTokenizer", "strTok", "=", "new", "StringTokenizer", "(", "str", ",", "\" \\t\\r\\n\"", ")", ";", "// <label> <cp> <idx> <wgt>", "int", "len...
Feature init. @param str the str @param cpStr2Int the cp str2 int @param lbStr2Int the lb str2 int
[ "Feature", "init", "." ]
train
https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/jmaxent/Feature.java#L129-L151