repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/util/dbhandling/TorqueDBHandling.java
TorqueDBHandling.createDB
public void createDB() throws PlatformException { """ Creates the database. @throws PlatformException If some error occurred """ if (_creationScript == null) { createCreationScript(); } Project project = new Project(); TorqueDataModelTask modelTask = new TorqueDataModelTask(); File tmpDir = null; File scriptFile = null; try { tmpDir = new File(getWorkDir(), "schemas"); tmpDir.mkdir(); scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME); writeCompressedText(scriptFile, _creationScript); project.setBasedir(tmpDir.getAbsolutePath()); // we use the ant task 'sql' to perform the creation script SQLExec sqlTask = new SQLExec(); SQLExec.OnError onError = new SQLExec.OnError(); onError.setValue("continue"); sqlTask.setProject(project); sqlTask.setAutocommit(true); sqlTask.setDriver(_jcd.getDriver()); sqlTask.setOnerror(onError); sqlTask.setUserid(_jcd.getUserName()); sqlTask.setPassword(_jcd.getPassWord() == null ? "" : _jcd.getPassWord()); sqlTask.setUrl(getDBCreationUrl()); sqlTask.setSrc(scriptFile); sqlTask.execute(); deleteDir(tmpDir); } catch (Exception ex) { // clean-up if ((tmpDir != null) && tmpDir.exists()) { try { scriptFile.delete(); } catch (NullPointerException e) { LoggerFactory.getLogger(this.getClass()).error("NPE While deleting scriptFile [" + scriptFile.getName() + "]", e); } } throw new PlatformException(ex); } }
java
public void createDB() throws PlatformException { if (_creationScript == null) { createCreationScript(); } Project project = new Project(); TorqueDataModelTask modelTask = new TorqueDataModelTask(); File tmpDir = null; File scriptFile = null; try { tmpDir = new File(getWorkDir(), "schemas"); tmpDir.mkdir(); scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME); writeCompressedText(scriptFile, _creationScript); project.setBasedir(tmpDir.getAbsolutePath()); // we use the ant task 'sql' to perform the creation script SQLExec sqlTask = new SQLExec(); SQLExec.OnError onError = new SQLExec.OnError(); onError.setValue("continue"); sqlTask.setProject(project); sqlTask.setAutocommit(true); sqlTask.setDriver(_jcd.getDriver()); sqlTask.setOnerror(onError); sqlTask.setUserid(_jcd.getUserName()); sqlTask.setPassword(_jcd.getPassWord() == null ? "" : _jcd.getPassWord()); sqlTask.setUrl(getDBCreationUrl()); sqlTask.setSrc(scriptFile); sqlTask.execute(); deleteDir(tmpDir); } catch (Exception ex) { // clean-up if ((tmpDir != null) && tmpDir.exists()) { try { scriptFile.delete(); } catch (NullPointerException e) { LoggerFactory.getLogger(this.getClass()).error("NPE While deleting scriptFile [" + scriptFile.getName() + "]", e); } } throw new PlatformException(ex); } }
[ "public", "void", "createDB", "(", ")", "throws", "PlatformException", "{", "if", "(", "_creationScript", "==", "null", ")", "{", "createCreationScript", "(", ")", ";", "}", "Project", "project", "=", "new", "Project", "(", ")", ";", "TorqueDataModelTask", "...
Creates the database. @throws PlatformException If some error occurred
[ "Creates", "the", "database", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/dbhandling/TorqueDBHandling.java#L258-L314
javagl/Common
src/main/java/de/javagl/common/beans/XmlBeanUtil.java
XmlBeanUtil.writeFullBeanXml
public static void writeFullBeanXml( Object object, OutputStream outputStream) { """ Write the XML describing the given bean to the given output stream, as it is done by an <code>XMLEncoder</code>, but including all properties, even if they still have their default values. The caller is responsible for closing the given stream. @param object The bean object @param outputStream The stream to write to @throws XmlException If there is an error while encoding the object """ XMLEncoder encoder = XmlEncoders.createVerbose(outputStream); encoder.setExceptionListener(new ExceptionListener() { @Override public void exceptionThrown(Exception e) { throw new XmlException("Could not encode object", e); } }); encoder.writeObject(object); encoder.flush(); encoder.close(); }
java
public static void writeFullBeanXml( Object object, OutputStream outputStream) { XMLEncoder encoder = XmlEncoders.createVerbose(outputStream); encoder.setExceptionListener(new ExceptionListener() { @Override public void exceptionThrown(Exception e) { throw new XmlException("Could not encode object", e); } }); encoder.writeObject(object); encoder.flush(); encoder.close(); }
[ "public", "static", "void", "writeFullBeanXml", "(", "Object", "object", ",", "OutputStream", "outputStream", ")", "{", "XMLEncoder", "encoder", "=", "XmlEncoders", ".", "createVerbose", "(", "outputStream", ")", ";", "encoder", ".", "setExceptionListener", "(", "...
Write the XML describing the given bean to the given output stream, as it is done by an <code>XMLEncoder</code>, but including all properties, even if they still have their default values. The caller is responsible for closing the given stream. @param object The bean object @param outputStream The stream to write to @throws XmlException If there is an error while encoding the object
[ "Write", "the", "XML", "describing", "the", "given", "bean", "to", "the", "given", "output", "stream", "as", "it", "is", "done", "by", "an", "<code", ">", "XMLEncoder<", "/", "code", ">", "but", "including", "all", "properties", "even", "if", "they", "st...
train
https://github.com/javagl/Common/blob/5a4876b48c3a2dc61d21324733cf37512d721c33/src/main/java/de/javagl/common/beans/XmlBeanUtil.java#L52-L67
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-cache/xwiki-commons-cache-infinispan/src/main/java/org/xwiki/cache/infinispan/internal/InfinispanConfigurationLoader.java
InfinispanConfigurationLoader.completeFilesystem
private void completeFilesystem(ConfigurationBuilder builder, Configuration configuration) { """ Add missing location for filesystem based cache. @param currentBuilder the configuration builder @param configuration the configuration @return the configuration builder """ PersistenceConfigurationBuilder persistence = builder.persistence(); if (containsIncompleteFileLoader(configuration)) { for (StoreConfigurationBuilder<?, ?> store : persistence.stores()) { if (store instanceof SingleFileStoreConfigurationBuilder) { SingleFileStoreConfigurationBuilder singleFileStore = (SingleFileStoreConfigurationBuilder) store; singleFileStore.location(createTempDir()); } } } }
java
private void completeFilesystem(ConfigurationBuilder builder, Configuration configuration) { PersistenceConfigurationBuilder persistence = builder.persistence(); if (containsIncompleteFileLoader(configuration)) { for (StoreConfigurationBuilder<?, ?> store : persistence.stores()) { if (store instanceof SingleFileStoreConfigurationBuilder) { SingleFileStoreConfigurationBuilder singleFileStore = (SingleFileStoreConfigurationBuilder) store; singleFileStore.location(createTempDir()); } } } }
[ "private", "void", "completeFilesystem", "(", "ConfigurationBuilder", "builder", ",", "Configuration", "configuration", ")", "{", "PersistenceConfigurationBuilder", "persistence", "=", "builder", ".", "persistence", "(", ")", ";", "if", "(", "containsIncompleteFileLoader"...
Add missing location for filesystem based cache. @param currentBuilder the configuration builder @param configuration the configuration @return the configuration builder
[ "Add", "missing", "location", "for", "filesystem", "based", "cache", "." ]
train
https://github.com/xwiki/xwiki-commons/blob/5374d8c6d966588c1eac7392c83da610dfb9f129/xwiki-commons-core/xwiki-commons-cache/xwiki-commons-cache-infinispan/src/main/java/org/xwiki/cache/infinispan/internal/InfinispanConfigurationLoader.java#L162-L175
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java
Item.withNumber
public Item withNumber(String attrName, BigDecimal val) { """ Sets the value of the specified attribute in the current item to the given value. """ checkInvalidAttribute(attrName, val); attributes.put(attrName, val); return this; }
java
public Item withNumber(String attrName, BigDecimal val) { checkInvalidAttribute(attrName, val); attributes.put(attrName, val); return this; }
[ "public", "Item", "withNumber", "(", "String", "attrName", ",", "BigDecimal", "val", ")", "{", "checkInvalidAttribute", "(", "attrName", ",", "val", ")", ";", "attributes", ".", "put", "(", "attrName", ",", "val", ")", ";", "return", "this", ";", "}" ]
Sets the value of the specified attribute in the current item to the given value.
[ "Sets", "the", "value", "of", "the", "specified", "attribute", "in", "the", "current", "item", "to", "the", "given", "value", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/Item.java#L267-L271
WiQuery/wiquery
wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/sortable/SortableBehavior.java
SortableBehavior.setGrid
public SortableBehavior setGrid(int x, int y) { """ Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y] @param x @param y @return instance of the current behavior """ ArrayItemOptions<IntegerItemOptions> grids = new ArrayItemOptions<IntegerItemOptions>(); grids.add(new IntegerItemOptions(x)); grids.add(new IntegerItemOptions(y)); this.options.put("grid", grids); return this; }
java
public SortableBehavior setGrid(int x, int y) { ArrayItemOptions<IntegerItemOptions> grids = new ArrayItemOptions<IntegerItemOptions>(); grids.add(new IntegerItemOptions(x)); grids.add(new IntegerItemOptions(y)); this.options.put("grid", grids); return this; }
[ "public", "SortableBehavior", "setGrid", "(", "int", "x", ",", "int", "y", ")", "{", "ArrayItemOptions", "<", "IntegerItemOptions", ">", "grids", "=", "new", "ArrayItemOptions", "<", "IntegerItemOptions", ">", "(", ")", ";", "grids", ".", "add", "(", "new", ...
Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y] @param x @param y @return instance of the current behavior
[ "Snaps", "the", "sorting", "element", "or", "helper", "to", "a", "grid", "every", "x", "and", "y", "pixels", ".", "Array", "values", ":", "[", "x", "y", "]" ]
train
https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/sortable/SortableBehavior.java#L825-L832
Erudika/para
para-core/src/main/java/com/erudika/para/core/App.java
App.addDatatype
public void addDatatype(String pluralDatatype, String datatype) { """ Adds a user-defined data type to the types map. @param pluralDatatype the plural form of the type @param datatype a datatype, must not be null or empty """ pluralDatatype = Utils.noSpaces(Utils.stripAndTrim(pluralDatatype, " "), "-"); datatype = Utils.noSpaces(Utils.stripAndTrim(datatype, " "), "-"); if (StringUtils.isBlank(pluralDatatype) || StringUtils.isBlank(datatype)) { return; } if (getDatatypes().size() >= Config.MAX_DATATYPES_PER_APP) { LoggerFactory.getLogger(App.class).warn("Maximum number of types per app reached - {}.", Config.MAX_DATATYPES_PER_APP); return; } if (!getDatatypes().containsKey(pluralDatatype) && !getDatatypes().containsValue(datatype) && !ParaObjectUtils.getCoreTypes().containsKey(pluralDatatype)) { getDatatypes().put(pluralDatatype, datatype); } }
java
public void addDatatype(String pluralDatatype, String datatype) { pluralDatatype = Utils.noSpaces(Utils.stripAndTrim(pluralDatatype, " "), "-"); datatype = Utils.noSpaces(Utils.stripAndTrim(datatype, " "), "-"); if (StringUtils.isBlank(pluralDatatype) || StringUtils.isBlank(datatype)) { return; } if (getDatatypes().size() >= Config.MAX_DATATYPES_PER_APP) { LoggerFactory.getLogger(App.class).warn("Maximum number of types per app reached - {}.", Config.MAX_DATATYPES_PER_APP); return; } if (!getDatatypes().containsKey(pluralDatatype) && !getDatatypes().containsValue(datatype) && !ParaObjectUtils.getCoreTypes().containsKey(pluralDatatype)) { getDatatypes().put(pluralDatatype, datatype); } }
[ "public", "void", "addDatatype", "(", "String", "pluralDatatype", ",", "String", "datatype", ")", "{", "pluralDatatype", "=", "Utils", ".", "noSpaces", "(", "Utils", ".", "stripAndTrim", "(", "pluralDatatype", ",", "\" \"", ")", ",", "\"-\"", ")", ";", "data...
Adds a user-defined data type to the types map. @param pluralDatatype the plural form of the type @param datatype a datatype, must not be null or empty
[ "Adds", "a", "user", "-", "defined", "data", "type", "to", "the", "types", "map", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-core/src/main/java/com/erudika/para/core/App.java#L878-L893
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/refer/Referencer.java
Referencer.setReferences
public static void setReferences(IReferences references, Iterable<Object> components) throws ReferenceException, ConfigException { """ Sets references to multiple components. To set references components must implement IReferenceable interface. If they don't the call to this method has no effect. @param references the references to be set. @param components a list of components to set the references to. @throws ReferenceException when no references found. @throws ConfigException when configuration is wrong. @see IReferenceable """ for (Object component : components) setReferencesForOne(references, component); } /** * Unsets references in specific component. * * To unset references components must implement IUnreferenceable interface. If * they don't the call to this method has no effect. * * @param component the component to unset references. * * @see IUnreferenceable */ public static void unsetReferencesForOne(Object component) { if (component instanceof IUnreferenceable) ((IUnreferenceable) component).unsetReferences(); } /** * Unsets references in multiple components. * * To unset references components must implement IUnreferenceable interface. If * they don't the call to this method has no effect. * * @param components the list of components, whose references must be cleared. * * @see IUnreferenceable */ public static void unsetReferences(Iterable<Object> components) { for (Object component : components) unsetReferencesForOne(component); } }
java
public static void setReferences(IReferences references, Iterable<Object> components) throws ReferenceException, ConfigException { for (Object component : components) setReferencesForOne(references, component); } /** * Unsets references in specific component. * * To unset references components must implement IUnreferenceable interface. If * they don't the call to this method has no effect. * * @param component the component to unset references. * * @see IUnreferenceable */ public static void unsetReferencesForOne(Object component) { if (component instanceof IUnreferenceable) ((IUnreferenceable) component).unsetReferences(); } /** * Unsets references in multiple components. * * To unset references components must implement IUnreferenceable interface. If * they don't the call to this method has no effect. * * @param components the list of components, whose references must be cleared. * * @see IUnreferenceable */ public static void unsetReferences(Iterable<Object> components) { for (Object component : components) unsetReferencesForOne(component); } }
[ "public", "static", "void", "setReferences", "(", "IReferences", "references", ",", "Iterable", "<", "Object", ">", "components", ")", "throws", "ReferenceException", ",", "ConfigException", "{", "for", "(", "Object", "component", ":", "components", ")", "setRefer...
Sets references to multiple components. To set references components must implement IReferenceable interface. If they don't the call to this method has no effect. @param references the references to be set. @param components a list of components to set the references to. @throws ReferenceException when no references found. @throws ConfigException when configuration is wrong. @see IReferenceable
[ "Sets", "references", "to", "multiple", "components", "." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/Referencer.java#L45-L81
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.createConnector
public Connector createConnector(Long chargingStationTypeId, Long evseId, Connector connector) { """ Creates a connector in a charging station type evse. @param chargingStationTypeId charging station identifier. @param evseId evse id. @param connector connector to be created. @return created connector. """ ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); Evse evse = getEvseById(chargingStationType, evseId); Set<Connector> originalConnectors = ImmutableSet.copyOf(evse.getConnectors()); evse.getConnectors().add(connector); chargingStationType = chargingStationTypeRepository.createOrUpdate(chargingStationType); Set<Connector> newConnectors = getEvseById(chargingStationType, evseId).getConnectors(); Set<Connector> diffConnectors = Sets.difference(newConnectors, originalConnectors); if (diffConnectors.size() == 1) { return Iterables.get(diffConnectors, 0); } else { return null; } }
java
public Connector createConnector(Long chargingStationTypeId, Long evseId, Connector connector) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); Evse evse = getEvseById(chargingStationType, evseId); Set<Connector> originalConnectors = ImmutableSet.copyOf(evse.getConnectors()); evse.getConnectors().add(connector); chargingStationType = chargingStationTypeRepository.createOrUpdate(chargingStationType); Set<Connector> newConnectors = getEvseById(chargingStationType, evseId).getConnectors(); Set<Connector> diffConnectors = Sets.difference(newConnectors, originalConnectors); if (diffConnectors.size() == 1) { return Iterables.get(diffConnectors, 0); } else { return null; } }
[ "public", "Connector", "createConnector", "(", "Long", "chargingStationTypeId", ",", "Long", "evseId", ",", "Connector", "connector", ")", "{", "ChargingStationType", "chargingStationType", "=", "chargingStationTypeRepository", ".", "findOne", "(", "chargingStationTypeId", ...
Creates a connector in a charging station type evse. @param chargingStationTypeId charging station identifier. @param evseId evse id. @param connector connector to be created. @return created connector.
[ "Creates", "a", "connector", "in", "a", "charging", "station", "type", "evse", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L195-L212
mebigfatguy/fb-contrib
src/main/java/com/mebigfatguy/fbcontrib/detect/Section508Compliance.java
Section508Compliance.visitClassContext
@Override public void visitClassContext(ClassContext classContext) { """ implements the visitor to create and clear the stack @param classContext the context object of the currently visited class """ try { if ((jcomponentClass != null) && (accessibleClass != null)) { JavaClass cls = classContext.getJavaClass(); if (cls.instanceOf(jcomponentClass) && !cls.implementationOf(accessibleClass)) { bugReporter.reportBug(new BugInstance(this, BugType.S508C_NON_ACCESSIBLE_JCOMPONENT.name(), NORMAL_PRIORITY).addClass(cls)); } } stack = new OpcodeStack(); fieldLabels = new HashSet<>(); localLabels = new HashMap<>(); super.visitClassContext(classContext); for (XField fa : fieldLabels) { bugReporter.reportBug(new BugInstance(this, BugType.S508C_NO_SETLABELFOR.name(), NORMAL_PRIORITY).addClass(this).addField(fa)); } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { stack = null; fieldLabels = null; localLabels = null; } }
java
@Override public void visitClassContext(ClassContext classContext) { try { if ((jcomponentClass != null) && (accessibleClass != null)) { JavaClass cls = classContext.getJavaClass(); if (cls.instanceOf(jcomponentClass) && !cls.implementationOf(accessibleClass)) { bugReporter.reportBug(new BugInstance(this, BugType.S508C_NON_ACCESSIBLE_JCOMPONENT.name(), NORMAL_PRIORITY).addClass(cls)); } } stack = new OpcodeStack(); fieldLabels = new HashSet<>(); localLabels = new HashMap<>(); super.visitClassContext(classContext); for (XField fa : fieldLabels) { bugReporter.reportBug(new BugInstance(this, BugType.S508C_NO_SETLABELFOR.name(), NORMAL_PRIORITY).addClass(this).addField(fa)); } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { stack = null; fieldLabels = null; localLabels = null; } }
[ "@", "Override", "public", "void", "visitClassContext", "(", "ClassContext", "classContext", ")", "{", "try", "{", "if", "(", "(", "jcomponentClass", "!=", "null", ")", "&&", "(", "accessibleClass", "!=", "null", ")", ")", "{", "JavaClass", "cls", "=", "cl...
implements the visitor to create and clear the stack @param classContext the context object of the currently visited class
[ "implements", "the", "visitor", "to", "create", "and", "clear", "the", "stack" ]
train
https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/Section508Compliance.java#L166-L190
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/api/ApiModule.java
ApiModule.performPersistCursorRequest
public void performPersistCursorRequest(String name, long key, Request request) { """ Perform cursor persist request. Request is performed only if key is bigger than previous request with same name @param name name of cursor @param key sorting key @param request request for performing """ persistentRequests.send(new PersistentRequestsActor.PerformCursorRequest(name, key, request)); }
java
public void performPersistCursorRequest(String name, long key, Request request) { persistentRequests.send(new PersistentRequestsActor.PerformCursorRequest(name, key, request)); }
[ "public", "void", "performPersistCursorRequest", "(", "String", "name", ",", "long", "key", ",", "Request", "request", ")", "{", "persistentRequests", ".", "send", "(", "new", "PersistentRequestsActor", ".", "PerformCursorRequest", "(", "name", ",", "key", ",", ...
Perform cursor persist request. Request is performed only if key is bigger than previous request with same name @param name name of cursor @param key sorting key @param request request for performing
[ "Perform", "cursor", "persist", "request", ".", "Request", "is", "performed", "only", "if", "key", "is", "bigger", "than", "previous", "request", "with", "same", "name" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/modules/api/ApiModule.java#L100-L102
jtrfp/javamod
src/main/java/de/quippy/javamod/multimedia/mod/loader/tracker/ScreamTrackerOldMod.java
ScreamTrackerOldMod.createNewPatternElement
private PatternElement createNewPatternElement(int pattNum, int row, int channel, int note) { """ Read the STM pattern data @param pattNum @param row @param channel @param note @return """ PatternElement pe = new PatternElement(pattNum, row, channel); pe.setInstrument((note&0xF80000)>>19); int oktave = (note&0xF0000000)>>28; if (oktave!=-1) { int ton = (note&0x0F000000)>>24; int index = (oktave+3)*12+ton; // fit to it octaves pe.setPeriod((index<Helpers.noteValues.length) ? Helpers.noteValues[index] : 0); pe.setNoteIndex(index+1); } else { pe.setPeriod(0); pe.setNoteIndex(0); } pe.setEffekt((note&0xF00)>>8); pe.setEffektOp(note&0xFF); if (pe.getEffekt()==0x01) // set Tempo needs correction. Do not ask why! { int effektOp = pe.getEffektOp(); pe.setEffektOp(((effektOp&0x0F)<<4) | ((effektOp&0xF0)>>4)); } int volume =((note&0x70000)>>16) | ((note&0xF000)>>9); if (volume<=64) { pe.setVolumeEffekt(1); pe.setVolumeEffektOp(volume); } return pe; }
java
private PatternElement createNewPatternElement(int pattNum, int row, int channel, int note) { PatternElement pe = new PatternElement(pattNum, row, channel); pe.setInstrument((note&0xF80000)>>19); int oktave = (note&0xF0000000)>>28; if (oktave!=-1) { int ton = (note&0x0F000000)>>24; int index = (oktave+3)*12+ton; // fit to it octaves pe.setPeriod((index<Helpers.noteValues.length) ? Helpers.noteValues[index] : 0); pe.setNoteIndex(index+1); } else { pe.setPeriod(0); pe.setNoteIndex(0); } pe.setEffekt((note&0xF00)>>8); pe.setEffektOp(note&0xFF); if (pe.getEffekt()==0x01) // set Tempo needs correction. Do not ask why! { int effektOp = pe.getEffektOp(); pe.setEffektOp(((effektOp&0x0F)<<4) | ((effektOp&0xF0)>>4)); } int volume =((note&0x70000)>>16) | ((note&0xF000)>>9); if (volume<=64) { pe.setVolumeEffekt(1); pe.setVolumeEffektOp(volume); } return pe; }
[ "private", "PatternElement", "createNewPatternElement", "(", "int", "pattNum", ",", "int", "row", ",", "int", "channel", ",", "int", "note", ")", "{", "PatternElement", "pe", "=", "new", "PatternElement", "(", "pattNum", ",", "row", ",", "channel", ")", ";",...
Read the STM pattern data @param pattNum @param row @param channel @param note @return
[ "Read", "the", "STM", "pattern", "data" ]
train
https://github.com/jtrfp/javamod/blob/cda4fe943a589dc49415f4413453e2eece72076a/src/main/java/de/quippy/javamod/multimedia/mod/loader/tracker/ScreamTrackerOldMod.java#L164-L200
sgroschupf/zkclient
src/main/java/org/I0Itec/zkclient/ZkClient.java
ZkClient.createPersistent
public void createPersistent(String path, Object data, List<ACL> acl) { """ Create a persistent node. @param path @param data @param acl @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted @throws IllegalArgumentException if called from anything except the ZooKeeper event thread @throws ZkException if any ZooKeeper exception occurred @throws RuntimeException if any other exception occurs """ create(path, data, acl, CreateMode.PERSISTENT); }
java
public void createPersistent(String path, Object data, List<ACL> acl) { create(path, data, acl, CreateMode.PERSISTENT); }
[ "public", "void", "createPersistent", "(", "String", "path", ",", "Object", "data", ",", "List", "<", "ACL", ">", "acl", ")", "{", "create", "(", "path", ",", "data", ",", "acl", ",", "CreateMode", ".", "PERSISTENT", ")", ";", "}" ]
Create a persistent node. @param path @param data @param acl @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted @throws IllegalArgumentException if called from anything except the ZooKeeper event thread @throws ZkException if any ZooKeeper exception occurred @throws RuntimeException if any other exception occurs
[ "Create", "a", "persistent", "node", "." ]
train
https://github.com/sgroschupf/zkclient/blob/03ccf12c70aca2f771bfcd94d44dc7c4d4a1495e/src/main/java/org/I0Itec/zkclient/ZkClient.java#L404-L406
buschmais/jqa-rdbms-plugin
src/main/java/com/buschmais/jqassistant/plugin/rdbms/impl/scanner/AbstractSchemaScannerPlugin.java
AbstractSchemaScannerPlugin.createRoutines
private void createRoutines(Collection<Routine> routines, SchemaDescriptor schemaDescriptor, Map<String, ColumnTypeDescriptor> columnTypes, Store store) throws IOException { """ Create routines, i.e. functions and procedures. @param routines The routines. @param schemaDescriptor The schema descriptor. @param columnTypes The column types. @param store The store. @throws java.io.IOException If an unsupported routine type has been found. """ for (Routine routine : routines) { RoutineDescriptor routineDescriptor; String returnType; switch (routine.getRoutineType()) { case procedure: routineDescriptor = store.create(ProcedureDescriptor.class); returnType = ((ProcedureReturnType) routine.getReturnType()).name(); schemaDescriptor.getProcedures().add((ProcedureDescriptor) routineDescriptor); break; case function: routineDescriptor = store.create(FunctionDescriptor.class); returnType = ((FunctionReturnType) routine.getReturnType()).name(); schemaDescriptor.getFunctions().add((FunctionDescriptor) routineDescriptor); break; case unknown: routineDescriptor = store.create(RoutineDescriptor.class); returnType = null; schemaDescriptor.getUnknownRoutines().add(routineDescriptor); break; default: throw new IOException("Unsupported routine type " + routine.getRoutineType()); } routineDescriptor.setName(routine.getName()); routineDescriptor.setReturnType(returnType); routineDescriptor.setBodyType(routine.getRoutineBodyType().name()); routineDescriptor.setDefinition(routine.getDefinition()); for (RoutineColumn<? extends Routine> routineColumn : routine.getColumns()) { RoutineColumnDescriptor columnDescriptor = createColumnDescriptor(routineColumn, RoutineColumnDescriptor.class, columnTypes, store); routineDescriptor.getColumns().add(columnDescriptor); RoutineColumnType columnType = routineColumn.getColumnType(); if (columnType instanceof ProcedureColumnType) { ProcedureColumnType procedureColumnType = (ProcedureColumnType) columnType; columnDescriptor.setType(procedureColumnType.name()); } else if (columnType instanceof FunctionColumnType) { FunctionColumnType functionColumnType = (FunctionColumnType) columnType; columnDescriptor.setType(functionColumnType.name()); } else { throw new IOException("Unsupported routine column type " + columnType.getClass().getName()); } } } }
java
private void createRoutines(Collection<Routine> routines, SchemaDescriptor schemaDescriptor, Map<String, ColumnTypeDescriptor> columnTypes, Store store) throws IOException { for (Routine routine : routines) { RoutineDescriptor routineDescriptor; String returnType; switch (routine.getRoutineType()) { case procedure: routineDescriptor = store.create(ProcedureDescriptor.class); returnType = ((ProcedureReturnType) routine.getReturnType()).name(); schemaDescriptor.getProcedures().add((ProcedureDescriptor) routineDescriptor); break; case function: routineDescriptor = store.create(FunctionDescriptor.class); returnType = ((FunctionReturnType) routine.getReturnType()).name(); schemaDescriptor.getFunctions().add((FunctionDescriptor) routineDescriptor); break; case unknown: routineDescriptor = store.create(RoutineDescriptor.class); returnType = null; schemaDescriptor.getUnknownRoutines().add(routineDescriptor); break; default: throw new IOException("Unsupported routine type " + routine.getRoutineType()); } routineDescriptor.setName(routine.getName()); routineDescriptor.setReturnType(returnType); routineDescriptor.setBodyType(routine.getRoutineBodyType().name()); routineDescriptor.setDefinition(routine.getDefinition()); for (RoutineColumn<? extends Routine> routineColumn : routine.getColumns()) { RoutineColumnDescriptor columnDescriptor = createColumnDescriptor(routineColumn, RoutineColumnDescriptor.class, columnTypes, store); routineDescriptor.getColumns().add(columnDescriptor); RoutineColumnType columnType = routineColumn.getColumnType(); if (columnType instanceof ProcedureColumnType) { ProcedureColumnType procedureColumnType = (ProcedureColumnType) columnType; columnDescriptor.setType(procedureColumnType.name()); } else if (columnType instanceof FunctionColumnType) { FunctionColumnType functionColumnType = (FunctionColumnType) columnType; columnDescriptor.setType(functionColumnType.name()); } else { throw new IOException("Unsupported routine column type " + columnType.getClass().getName()); } } } }
[ "private", "void", "createRoutines", "(", "Collection", "<", "Routine", ">", "routines", ",", "SchemaDescriptor", "schemaDescriptor", ",", "Map", "<", "String", ",", "ColumnTypeDescriptor", ">", "columnTypes", ",", "Store", "store", ")", "throws", "IOException", "...
Create routines, i.e. functions and procedures. @param routines The routines. @param schemaDescriptor The schema descriptor. @param columnTypes The column types. @param store The store. @throws java.io.IOException If an unsupported routine type has been found.
[ "Create", "routines", "i", ".", "e", ".", "functions", "and", "procedures", "." ]
train
https://github.com/buschmais/jqa-rdbms-plugin/blob/96c3919907deee00175cf5ab005867d76e01ba62/src/main/java/com/buschmais/jqassistant/plugin/rdbms/impl/scanner/AbstractSchemaScannerPlugin.java#L265-L308
js-lib-com/template.xhtml
src/main/java/js/template/xhtml/OMapOperator.java
OMapOperator.doExec
@Override protected Object doExec(Element element, Object scope, String propertyPath, Object... arguments) throws IOException, TemplateException { """ Execute OMAP operator. Behaves like {@link MapOperator#doExec(Element, Object, String, Object...)} counterpart but takes care to create index and increment it before every key / value pair processing. @param element context element, @param scope scope object, @param propertyPath property path, @param arguments optional arguments, not used. @return always returns null to signal full processing. @throws IOException if underlying writer fails to write. @throws TemplateException if element has not at least two children or content map is undefined. """ if (!propertyPath.equals(".") && ConverterRegistry.hasType(scope.getClass())) { throw new TemplateException("Operand is property path but scope is not an object."); } Element keyTemplate = element.getFirstChild(); if (keyTemplate == null) { throw new TemplateException("Invalid map element |%s|. Missing key template.", element); } Element valueTemplate = keyTemplate.getNextSibling(); if (valueTemplate == null) { throw new TemplateException("Invalid map element |%s|. Missing value template.", element); } Stack<Index> indexes = serializer.getIndexes(); Index index = new Index(); indexes.push(index); Map<?, ?> map = content.getMap(scope, propertyPath); for (Object key : map.keySet()) { index.increment(); serializer.writeItem(keyTemplate, key); serializer.writeItem(valueTemplate, map.get(key)); } indexes.pop(); return null; }
java
@Override protected Object doExec(Element element, Object scope, String propertyPath, Object... arguments) throws IOException, TemplateException { if (!propertyPath.equals(".") && ConverterRegistry.hasType(scope.getClass())) { throw new TemplateException("Operand is property path but scope is not an object."); } Element keyTemplate = element.getFirstChild(); if (keyTemplate == null) { throw new TemplateException("Invalid map element |%s|. Missing key template.", element); } Element valueTemplate = keyTemplate.getNextSibling(); if (valueTemplate == null) { throw new TemplateException("Invalid map element |%s|. Missing value template.", element); } Stack<Index> indexes = serializer.getIndexes(); Index index = new Index(); indexes.push(index); Map<?, ?> map = content.getMap(scope, propertyPath); for (Object key : map.keySet()) { index.increment(); serializer.writeItem(keyTemplate, key); serializer.writeItem(valueTemplate, map.get(key)); } indexes.pop(); return null; }
[ "@", "Override", "protected", "Object", "doExec", "(", "Element", "element", ",", "Object", "scope", ",", "String", "propertyPath", ",", "Object", "...", "arguments", ")", "throws", "IOException", ",", "TemplateException", "{", "if", "(", "!", "propertyPath", ...
Execute OMAP operator. Behaves like {@link MapOperator#doExec(Element, Object, String, Object...)} counterpart but takes care to create index and increment it before every key / value pair processing. @param element context element, @param scope scope object, @param propertyPath property path, @param arguments optional arguments, not used. @return always returns null to signal full processing. @throws IOException if underlying writer fails to write. @throws TemplateException if element has not at least two children or content map is undefined.
[ "Execute", "OMAP", "operator", ".", "Behaves", "like", "{", "@link", "MapOperator#doExec", "(", "Element", "Object", "String", "Object", "...", ")", "}", "counterpart", "but", "takes", "care", "to", "create", "index", "and", "increment", "it", "before", "every...
train
https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/OMapOperator.java#L60-L84
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_Reverse3DLine.java
ST_Reverse3DLine.reverse3D
public static MultiLineString reverse3D(MultiLineString multiLineString, String order) { """ Reverses a multilinestring according to z value. If asc : the z first point must be lower than the z end point if desc : the z first point must be greater than the z end point @param multiLineString @return """ int num = multiLineString.getNumGeometries(); LineString[] lineStrings = new LineString[num]; for (int i = 0; i < multiLineString.getNumGeometries(); i++) { lineStrings[i] = reverse3D((LineString) multiLineString.getGeometryN(i), order); } return FACTORY.createMultiLineString(lineStrings); }
java
public static MultiLineString reverse3D(MultiLineString multiLineString, String order) { int num = multiLineString.getNumGeometries(); LineString[] lineStrings = new LineString[num]; for (int i = 0; i < multiLineString.getNumGeometries(); i++) { lineStrings[i] = reverse3D((LineString) multiLineString.getGeometryN(i), order); } return FACTORY.createMultiLineString(lineStrings); }
[ "public", "static", "MultiLineString", "reverse3D", "(", "MultiLineString", "multiLineString", ",", "String", "order", ")", "{", "int", "num", "=", "multiLineString", ".", "getNumGeometries", "(", ")", ";", "LineString", "[", "]", "lineStrings", "=", "new", "Lin...
Reverses a multilinestring according to z value. If asc : the z first point must be lower than the z end point if desc : the z first point must be greater than the z end point @param multiLineString @return
[ "Reverses", "a", "multilinestring", "according", "to", "z", "value", ".", "If", "asc", ":", "the", "z", "first", "point", "must", "be", "lower", "than", "the", "z", "end", "point", "if", "desc", ":", "the", "z", "first", "point", "must", "be", "greater...
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/ST_Reverse3DLine.java#L116-L124
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/BaseTable.java
BaseTable.unlockIfLocked
public boolean unlockIfLocked(Record record, Object bookmark) throws DBException { """ Unlock this record if it is locked. @param record The record to unlock. @param The bookmark to unlock (all if null). @return true if successful (it is usually okay to ignore this return). """ if (record != null) { // unlock record BaseApplication app = null; org.jbundle.model.Task task = null; if (record.getRecordOwner() != null) task = record.getRecordOwner().getTask(); if (task != null) app = (BaseApplication)record.getRecordOwner().getTask().getApplication(); Environment env = null; if (app != null) env = app.getEnvironment(); else env = Environment.getEnvironment(null); return env.getLockManager().unlockThisRecord(task, record.getDatabaseName(), record.getTableNames(false), bookmark); } return true; }
java
public boolean unlockIfLocked(Record record, Object bookmark) throws DBException { if (record != null) { // unlock record BaseApplication app = null; org.jbundle.model.Task task = null; if (record.getRecordOwner() != null) task = record.getRecordOwner().getTask(); if (task != null) app = (BaseApplication)record.getRecordOwner().getTask().getApplication(); Environment env = null; if (app != null) env = app.getEnvironment(); else env = Environment.getEnvironment(null); return env.getLockManager().unlockThisRecord(task, record.getDatabaseName(), record.getTableNames(false), bookmark); } return true; }
[ "public", "boolean", "unlockIfLocked", "(", "Record", "record", ",", "Object", "bookmark", ")", "throws", "DBException", "{", "if", "(", "record", "!=", "null", ")", "{", "// unlock record", "BaseApplication", "app", "=", "null", ";", "org", ".", "jbundle", ...
Unlock this record if it is locked. @param record The record to unlock. @param The bookmark to unlock (all if null). @return true if successful (it is usually okay to ignore this return).
[ "Unlock", "this", "record", "if", "it", "is", "locked", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/BaseTable.java#L1561-L1579
jeremylong/DependencyCheck
cli/src/main/java/org/owasp/dependencycheck/CliParser.java
CliParser.isNodeAuditDisabled
public boolean isNodeAuditDisabled() { """ Returns true if the disableNodeAudit command line argument was specified. @return true if the disableNodeAudit command line argument was specified; otherwise false """ if (hasDisableOption("disableNSP", Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) { LOGGER.error("The disableNSP argument has been deprecated and replaced by disableNodeAudit"); LOGGER.error("The disableNSP argument will be removed in the next version"); return true; } return hasDisableOption(ARGUMENT.DISABLE_NODE_AUDIT, Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED); }
java
public boolean isNodeAuditDisabled() { if (hasDisableOption("disableNSP", Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) { LOGGER.error("The disableNSP argument has been deprecated and replaced by disableNodeAudit"); LOGGER.error("The disableNSP argument will be removed in the next version"); return true; } return hasDisableOption(ARGUMENT.DISABLE_NODE_AUDIT, Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED); }
[ "public", "boolean", "isNodeAuditDisabled", "(", ")", "{", "if", "(", "hasDisableOption", "(", "\"disableNSP\"", ",", "Settings", ".", "KEYS", ".", "ANALYZER_NODE_AUDIT_ENABLED", ")", ")", "{", "LOGGER", ".", "error", "(", "\"The disableNSP argument has been deprecate...
Returns true if the disableNodeAudit command line argument was specified. @return true if the disableNodeAudit command line argument was specified; otherwise false
[ "Returns", "true", "if", "the", "disableNodeAudit", "command", "line", "argument", "was", "specified", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/cli/src/main/java/org/owasp/dependencycheck/CliParser.java#L766-L773
algolia/instantsearch-android
core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java
Searcher.getUpdatedFacetStats
@SuppressWarnings( { """ Updates the facet stats, calling {@link Index#search(Query, RequestOptions)} without notifying listeners of the result. """"WeakerAccess", "unused"}) // For library users public void getUpdatedFacetStats() { searchable.searchAsync(query, new CompletionHandler() { @Override public void requestCompleted(JSONObject content, AlgoliaException error) { if (error == null) { updateFacetStats(content); } else { Log.e("Algolia|Searcher", "Error while getting updated facet stats:" + error.getMessage()); } } }); }
java
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public void getUpdatedFacetStats() { searchable.searchAsync(query, new CompletionHandler() { @Override public void requestCompleted(JSONObject content, AlgoliaException error) { if (error == null) { updateFacetStats(content); } else { Log.e("Algolia|Searcher", "Error while getting updated facet stats:" + error.getMessage()); } } }); }
[ "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "// For library users", "public", "void", "getUpdatedFacetStats", "(", ")", "{", "searchable", ".", "searchAsync", "(", "query", ",", "new", "CompletionHandler", "(", ")", "{", "...
Updates the facet stats, calling {@link Index#search(Query, RequestOptions)} without notifying listeners of the result.
[ "Updates", "the", "facet", "stats", "calling", "{" ]
train
https://github.com/algolia/instantsearch-android/blob/12092ec30140df9ffc2bf916339b433372034616/core/src/main/java/com/algolia/instantsearch/core/helpers/Searcher.java#L1089-L1101
Virtlink/commons-configuration2-jackson
src/main/java/com/virtlink/commons/configuration2/jackson/JacksonConfiguration.java
JacksonConfiguration.valueToNode
private ImmutableNode valueToNode(final Builder builder, final Object value) { """ Creates a node for the specified value. @param builder The node builder. @param value The value. @return The created node. """ // Set the value of the node being built. return builder.value(value).create(); }
java
private ImmutableNode valueToNode(final Builder builder, final Object value) { // Set the value of the node being built. return builder.value(value).create(); }
[ "private", "ImmutableNode", "valueToNode", "(", "final", "Builder", "builder", ",", "final", "Object", "value", ")", "{", "// Set the value of the node being built.", "return", "builder", ".", "value", "(", "value", ")", ".", "create", "(", ")", ";", "}" ]
Creates a node for the specified value. @param builder The node builder. @param value The value. @return The created node.
[ "Creates", "a", "node", "for", "the", "specified", "value", "." ]
train
https://github.com/Virtlink/commons-configuration2-jackson/blob/40474ab3c641fbbb4ccd9c97d4f7075c1644ef69/src/main/java/com/virtlink/commons/configuration2/jackson/JacksonConfiguration.java#L204-L207
Hygieia/Hygieia
collectors/feature/versionone/src/main/java/com/capitalone/dashboard/collector/BaseClient.java
BaseClient.sanitizeResponse
public static String sanitizeResponse(String nativeRs) { """ Utility method used to sanitize / canonicalize a String-based response artifact from a source system. This will return a valid UTF-8 strings, or a "" (blank) response for any of the following cases: "NULL";"Null";"null";null;"" @param nativeRs The string response artifact retrieved from the source system to be sanitized @return A UTF-8 sanitized response """ if (StringUtils.isEmpty(nativeRs)) return ""; byte[] utf8Bytes; CharsetDecoder cs = StandardCharsets.UTF_8.newDecoder(); if ("null".equalsIgnoreCase(nativeRs)) return ""; utf8Bytes = nativeRs.getBytes(StandardCharsets.UTF_8); try { cs.decode(ByteBuffer.wrap(utf8Bytes)); return new String(utf8Bytes, StandardCharsets.UTF_8); } catch (CharacterCodingException e) { return "[INVALID NON UTF-8 ENCODING]"; } }
java
public static String sanitizeResponse(String nativeRs) { if (StringUtils.isEmpty(nativeRs)) return ""; byte[] utf8Bytes; CharsetDecoder cs = StandardCharsets.UTF_8.newDecoder(); if ("null".equalsIgnoreCase(nativeRs)) return ""; utf8Bytes = nativeRs.getBytes(StandardCharsets.UTF_8); try { cs.decode(ByteBuffer.wrap(utf8Bytes)); return new String(utf8Bytes, StandardCharsets.UTF_8); } catch (CharacterCodingException e) { return "[INVALID NON UTF-8 ENCODING]"; } }
[ "public", "static", "String", "sanitizeResponse", "(", "String", "nativeRs", ")", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "nativeRs", ")", ")", "return", "\"\"", ";", "byte", "[", "]", "utf8Bytes", ";", "CharsetDecoder", "cs", "=", "StandardChars...
Utility method used to sanitize / canonicalize a String-based response artifact from a source system. This will return a valid UTF-8 strings, or a "" (blank) response for any of the following cases: "NULL";"Null";"null";null;"" @param nativeRs The string response artifact retrieved from the source system to be sanitized @return A UTF-8 sanitized response
[ "Utility", "method", "used", "to", "sanitize", "/", "canonicalize", "a", "String", "-", "based", "response", "artifact", "from", "a", "source", "system", ".", "This", "will", "return", "a", "valid", "UTF", "-", "8", "strings", "or", "a", "(", "blank", ")...
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/collectors/feature/versionone/src/main/java/com/capitalone/dashboard/collector/BaseClient.java#L91-L105
unbescape/unbescape
src/main/java/org/unbescape/json/JsonEscape.java
JsonEscape.escapeJsonMinimal
public static void escapeJsonMinimal(final Reader reader, final Writer writer) throws IOException { """ <p> Perform a JSON level 1 (only basic set) <strong>escape</strong> operation on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 1</em> means this method will only escape the JSON basic escape set: </p> <ul> <li>The <em>Single Escape Characters</em>: <tt>&#92;b</tt> (<tt>U+0008</tt>), <tt>&#92;t</tt> (<tt>U+0009</tt>), <tt>&#92;n</tt> (<tt>U+000A</tt>), <tt>&#92;f</tt> (<tt>U+000C</tt>), <tt>&#92;r</tt> (<tt>U+000D</tt>), <tt>&#92;&quot;</tt> (<tt>U+0022</tt>), <tt>&#92;&#92;</tt> (<tt>U+005C</tt>) and <tt>&#92;&#47;</tt> (<tt>U+002F</tt>). Note that <tt>&#92;&#47;</tt> is optional, and will only be used when the <tt>&#47;</tt> symbol appears after <tt>&lt;</tt>, as in <tt>&lt;&#47;</tt>. This is to avoid accidentally closing <tt>&lt;script&gt;</tt> tags in HTML. </li> <li> Two ranges of non-displayable, control characters (some of which are already part of the <em>single escape characters</em> list): <tt>U+0000</tt> to <tt>U+001F</tt> (required by the JSON spec) and <tt>U+007F</tt> to <tt>U+009F</tt> (additional). </li> </ul> <p> This method calls {@link #escapeJson(Reader, Writer, JsonEscapeType, JsonEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link JsonEscapeType#SINGLE_ESCAPE_CHARS_DEFAULT_TO_UHEXA}</li> <li><tt>level</tt>: {@link JsonEscapeLevel#LEVEL_1_BASIC_ESCAPE_SET}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.2 """ escapeJson(reader, writer, JsonEscapeType.SINGLE_ESCAPE_CHARS_DEFAULT_TO_UHEXA, JsonEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET); }
java
public static void escapeJsonMinimal(final Reader reader, final Writer writer) throws IOException { escapeJson(reader, writer, JsonEscapeType.SINGLE_ESCAPE_CHARS_DEFAULT_TO_UHEXA, JsonEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET); }
[ "public", "static", "void", "escapeJsonMinimal", "(", "final", "Reader", "reader", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "escapeJson", "(", "reader", ",", "writer", ",", "JsonEscapeType", ".", "SINGLE_ESCAPE_CHARS_DEFAULT_TO_UHEXA", ",...
<p> Perform a JSON level 1 (only basic set) <strong>escape</strong> operation on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>. </p> <p> <em>Level 1</em> means this method will only escape the JSON basic escape set: </p> <ul> <li>The <em>Single Escape Characters</em>: <tt>&#92;b</tt> (<tt>U+0008</tt>), <tt>&#92;t</tt> (<tt>U+0009</tt>), <tt>&#92;n</tt> (<tt>U+000A</tt>), <tt>&#92;f</tt> (<tt>U+000C</tt>), <tt>&#92;r</tt> (<tt>U+000D</tt>), <tt>&#92;&quot;</tt> (<tt>U+0022</tt>), <tt>&#92;&#92;</tt> (<tt>U+005C</tt>) and <tt>&#92;&#47;</tt> (<tt>U+002F</tt>). Note that <tt>&#92;&#47;</tt> is optional, and will only be used when the <tt>&#47;</tt> symbol appears after <tt>&lt;</tt>, as in <tt>&lt;&#47;</tt>. This is to avoid accidentally closing <tt>&lt;script&gt;</tt> tags in HTML. </li> <li> Two ranges of non-displayable, control characters (some of which are already part of the <em>single escape characters</em> list): <tt>U+0000</tt> to <tt>U+001F</tt> (required by the JSON spec) and <tt>U+007F</tt> to <tt>U+009F</tt> (additional). </li> </ul> <p> This method calls {@link #escapeJson(Reader, Writer, JsonEscapeType, JsonEscapeLevel)} with the following preconfigured values: </p> <ul> <li><tt>type</tt>: {@link JsonEscapeType#SINGLE_ESCAPE_CHARS_DEFAULT_TO_UHEXA}</li> <li><tt>level</tt>: {@link JsonEscapeLevel#LEVEL_1_BASIC_ESCAPE_SET}</li> </ul> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "a", "JSON", "level", "1", "(", "only", "basic", "set", ")", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "Reader<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", "...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/json/JsonEscape.java#L549-L554
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/ExpressionResolverImpl.java
ExpressionResolverImpl.resolveExpressionStringRecursively
private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure, final boolean initial) throws OperationFailedException { """ Attempt to resolve the given expression string, recursing if resolution of one string produces another expression. @param expressionString the expression string from a node of {@link ModelType#EXPRESSION} @param ignoreDMRResolutionFailure {@code false} if {@link org.jboss.dmr.ModelNode#resolve() basic DMR resolution} failures should be ignored, and {@code new ModelNode(expressionType.asString())} returned @param initial {@code true} if this call originated outside this method; {@code false} if it is a recursive call @return a node of {@link ModelType#STRING} where the encapsulated string is the resolved expression, or a node of {@link ModelType#EXPRESSION} if {@code ignoreDMRResolutionFailure} and {@code initial} are {@code true} and the string could not be resolved. @throws OperationFailedException if the expression cannot be resolved """ ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure); if (resolved.recursive) { // Some part of expressionString resolved into a different expression. // So, start over, ignoring failures. Ignore failures because we don't require // that expressions must not resolve to something that *looks like* an expression but isn't return resolveExpressionStringRecursively(resolved.result, true, false); } else if (resolved.modified) { // Typical case return new ModelNode(resolved.result); } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) { // We should only get an unmodified expression string back if there was a resolution // failure that we ignored. assert ignoreDMRResolutionFailure; // expressionString came from a node of type expression, so since we did nothing send it back in the same type return new ModelNode(new ValueExpression(expressionString)); } else { // The string wasn't really an expression. Two possible cases: // 1) if initial == true, someone created a expression node with a non-expression string, which is legal // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an // expression but can't be resolved. We don't require that expressions must not resolve to something that // *looks like* an expression but isn't, so we'll just treat this as a string return new ModelNode(expressionString); } }
java
private ModelNode resolveExpressionStringRecursively(final String expressionString, final boolean ignoreDMRResolutionFailure, final boolean initial) throws OperationFailedException { ParseAndResolveResult resolved = parseAndResolve(expressionString, ignoreDMRResolutionFailure); if (resolved.recursive) { // Some part of expressionString resolved into a different expression. // So, start over, ignoring failures. Ignore failures because we don't require // that expressions must not resolve to something that *looks like* an expression but isn't return resolveExpressionStringRecursively(resolved.result, true, false); } else if (resolved.modified) { // Typical case return new ModelNode(resolved.result); } else if (initial && EXPRESSION_PATTERN.matcher(expressionString).matches()) { // We should only get an unmodified expression string back if there was a resolution // failure that we ignored. assert ignoreDMRResolutionFailure; // expressionString came from a node of type expression, so since we did nothing send it back in the same type return new ModelNode(new ValueExpression(expressionString)); } else { // The string wasn't really an expression. Two possible cases: // 1) if initial == true, someone created a expression node with a non-expression string, which is legal // 2) if initial == false, we resolved from an ModelType.EXPRESSION to a string that looked like an // expression but can't be resolved. We don't require that expressions must not resolve to something that // *looks like* an expression but isn't, so we'll just treat this as a string return new ModelNode(expressionString); } }
[ "private", "ModelNode", "resolveExpressionStringRecursively", "(", "final", "String", "expressionString", ",", "final", "boolean", "ignoreDMRResolutionFailure", ",", "final", "boolean", "initial", ")", "throws", "OperationFailedException", "{", "ParseAndResolveResult", "resol...
Attempt to resolve the given expression string, recursing if resolution of one string produces another expression. @param expressionString the expression string from a node of {@link ModelType#EXPRESSION} @param ignoreDMRResolutionFailure {@code false} if {@link org.jboss.dmr.ModelNode#resolve() basic DMR resolution} failures should be ignored, and {@code new ModelNode(expressionType.asString())} returned @param initial {@code true} if this call originated outside this method; {@code false} if it is a recursive call @return a node of {@link ModelType#STRING} where the encapsulated string is the resolved expression, or a node of {@link ModelType#EXPRESSION} if {@code ignoreDMRResolutionFailure} and {@code initial} are {@code true} and the string could not be resolved. @throws OperationFailedException if the expression cannot be resolved
[ "Attempt", "to", "resolve", "the", "given", "expression", "string", "recursing", "if", "resolution", "of", "one", "string", "produces", "another", "expression", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/ExpressionResolverImpl.java#L141-L166
alkacon/opencms-core
src/org/opencms/main/CmsShellCommands.java
CmsShellCommands.replaceModule
public void replaceModule(String moduleName, String importFile) throws Exception { """ Replaces a module with another revision.<p> @param moduleName the name of the module to delete @param importFile the name of the import file @throws Exception if something goes wrong """ CmsModule module = CmsModuleImportExportHandler.readModuleFromImport(importFile); if (moduleName.equals(module.getName())) { replaceModule(importFile); } else { if (OpenCms.getModuleManager().getModule(moduleName) != null) { OpenCms.getModuleManager().deleteModule( m_cms, moduleName, true, new CmsShellReport(m_cms.getRequestContext().getLocale())); } importModule(importFile); } }
java
public void replaceModule(String moduleName, String importFile) throws Exception { CmsModule module = CmsModuleImportExportHandler.readModuleFromImport(importFile); if (moduleName.equals(module.getName())) { replaceModule(importFile); } else { if (OpenCms.getModuleManager().getModule(moduleName) != null) { OpenCms.getModuleManager().deleteModule( m_cms, moduleName, true, new CmsShellReport(m_cms.getRequestContext().getLocale())); } importModule(importFile); } }
[ "public", "void", "replaceModule", "(", "String", "moduleName", ",", "String", "importFile", ")", "throws", "Exception", "{", "CmsModule", "module", "=", "CmsModuleImportExportHandler", ".", "readModuleFromImport", "(", "importFile", ")", ";", "if", "(", "moduleName...
Replaces a module with another revision.<p> @param moduleName the name of the module to delete @param importFile the name of the import file @throws Exception if something goes wrong
[ "Replaces", "a", "module", "with", "another", "revision", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L1412-L1427
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/source/FunctionalType.java
FunctionalType.functionalTypeAcceptedByMethod
public static FunctionalType functionalTypeAcceptedByMethod( DeclaredType type, String methodName, FunctionalType prototype, Elements elements, Types types) { """ Returns the functional type accepted by {@code methodName} on {@code type}, assignable to {@code prototype}, or {@code prototype} itself if no such method has been declared. <p>Used to allow the user to override the functional interface used on builder methods, e.g. to force boxing, or to use Guava types. """ return functionalTypesAcceptedByMethod(type, methodName, elements, types) .stream() .filter(functionalType -> isAssignable(functionalType, prototype, types)) .findAny() .orElse(prototype); }
java
public static FunctionalType functionalTypeAcceptedByMethod( DeclaredType type, String methodName, FunctionalType prototype, Elements elements, Types types) { return functionalTypesAcceptedByMethod(type, methodName, elements, types) .stream() .filter(functionalType -> isAssignable(functionalType, prototype, types)) .findAny() .orElse(prototype); }
[ "public", "static", "FunctionalType", "functionalTypeAcceptedByMethod", "(", "DeclaredType", "type", ",", "String", "methodName", ",", "FunctionalType", "prototype", ",", "Elements", "elements", ",", "Types", "types", ")", "{", "return", "functionalTypesAcceptedByMethod",...
Returns the functional type accepted by {@code methodName} on {@code type}, assignable to {@code prototype}, or {@code prototype} itself if no such method has been declared. <p>Used to allow the user to override the functional interface used on builder methods, e.g. to force boxing, or to use Guava types.
[ "Returns", "the", "functional", "type", "accepted", "by", "{", "@code", "methodName", "}", "on", "{", "@code", "type", "}", "assignable", "to", "{", "@code", "prototype", "}", "or", "{", "@code", "prototype", "}", "itself", "if", "no", "such", "method", ...
train
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/source/FunctionalType.java#L135-L146
jenkinsci/jenkins
core/src/main/java/hudson/model/queue/Timeline.java
Timeline.insert
int insert(long start, long end, int n) { """ increases q(t) by n for t in [start,end). @return peak value of q(t) in this range as a result of addition. """ splitAt(start); splitAt(end); int peak = 0; for (Map.Entry<Long, int[]> e : data.tailMap(start).headMap(end).entrySet()) { peak = max(peak, e.getValue()[0] += n); } return peak; }
java
int insert(long start, long end, int n) { splitAt(start); splitAt(end); int peak = 0; for (Map.Entry<Long, int[]> e : data.tailMap(start).headMap(end).entrySet()) { peak = max(peak, e.getValue()[0] += n); } return peak; }
[ "int", "insert", "(", "long", "start", ",", "long", "end", ",", "int", "n", ")", "{", "splitAt", "(", "start", ")", ";", "splitAt", "(", "end", ")", ";", "int", "peak", "=", "0", ";", "for", "(", "Map", ".", "Entry", "<", "Long", ",", "int", ...
increases q(t) by n for t in [start,end). @return peak value of q(t) in this range as a result of addition.
[ "increases", "q", "(", "t", ")", "by", "n", "for", "t", "in", "[", "start", "end", ")", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/queue/Timeline.java#L79-L88
Netflix/conductor
core/src/main/java/com/netflix/conductor/core/execution/DeciderService.java
DeciderService.updateWorkflowOutput
void updateWorkflowOutput(final Workflow workflow, @Nullable Task task) { """ Updates the workflow output. @param workflow the workflow instance @param task if not null, the output of this task will be copied to workflow output if no output parameters are specified in the workflow defintion if null, the output of the last task in the workflow will be copied to workflow output of no output parameters are specified in the workflow definition """ List<Task> allTasks = workflow.getTasks(); if (allTasks.isEmpty()) { return; } Task last = Optional.ofNullable(task).orElse(allTasks.get(allTasks.size() - 1)); WorkflowDef workflowDef = workflow.getWorkflowDefinition(); Map<String, Object> output; if (workflowDef.getOutputParameters() != null && !workflowDef.getOutputParameters().isEmpty()) { Workflow workflowInstance = populateWorkflowAndTaskData(workflow); output = parametersUtils.getTaskInput(workflowDef.getOutputParameters(), workflowInstance, null, null); } else if (StringUtils.isNotBlank(last.getExternalOutputPayloadStoragePath())) { output = externalPayloadStorageUtils.downloadPayload(last.getExternalOutputPayloadStoragePath()); Monitors.recordExternalPayloadStorageUsage(last.getTaskDefName(), ExternalPayloadStorage.Operation.READ.toString(), ExternalPayloadStorage.PayloadType.TASK_OUTPUT.toString()); } else { output = last.getOutputData(); } workflow.setOutput(output); externalPayloadStorageUtils.verifyAndUpload(workflow, ExternalPayloadStorage.PayloadType.WORKFLOW_OUTPUT); }
java
void updateWorkflowOutput(final Workflow workflow, @Nullable Task task) { List<Task> allTasks = workflow.getTasks(); if (allTasks.isEmpty()) { return; } Task last = Optional.ofNullable(task).orElse(allTasks.get(allTasks.size() - 1)); WorkflowDef workflowDef = workflow.getWorkflowDefinition(); Map<String, Object> output; if (workflowDef.getOutputParameters() != null && !workflowDef.getOutputParameters().isEmpty()) { Workflow workflowInstance = populateWorkflowAndTaskData(workflow); output = parametersUtils.getTaskInput(workflowDef.getOutputParameters(), workflowInstance, null, null); } else if (StringUtils.isNotBlank(last.getExternalOutputPayloadStoragePath())) { output = externalPayloadStorageUtils.downloadPayload(last.getExternalOutputPayloadStoragePath()); Monitors.recordExternalPayloadStorageUsage(last.getTaskDefName(), ExternalPayloadStorage.Operation.READ.toString(), ExternalPayloadStorage.PayloadType.TASK_OUTPUT.toString()); } else { output = last.getOutputData(); } workflow.setOutput(output); externalPayloadStorageUtils.verifyAndUpload(workflow, ExternalPayloadStorage.PayloadType.WORKFLOW_OUTPUT); }
[ "void", "updateWorkflowOutput", "(", "final", "Workflow", "workflow", ",", "@", "Nullable", "Task", "task", ")", "{", "List", "<", "Task", ">", "allTasks", "=", "workflow", ".", "getTasks", "(", ")", ";", "if", "(", "allTasks", ".", "isEmpty", "(", ")", ...
Updates the workflow output. @param workflow the workflow instance @param task if not null, the output of this task will be copied to workflow output if no output parameters are specified in the workflow defintion if null, the output of the last task in the workflow will be copied to workflow output of no output parameters are specified in the workflow definition
[ "Updates", "the", "workflow", "output", "." ]
train
https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/core/src/main/java/com/netflix/conductor/core/execution/DeciderService.java#L269-L291
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/jdbc/DBInitializerHelper.java
DBInitializerHelper.prepareScripts
public static String prepareScripts(WorkspaceEntry wsEntry, String dialect) throws IOException, RepositoryConfigurationException { """ Returns SQL scripts for initialization database for defined {@link WorkspaceEntry}. @param wsEntry workspace configuration @param dialect database dialect which is used, since {@link JDBCWorkspaceDataContainer#DB_DIALECT} parameter can contain {@link DialectConstants#DB_DIALECT_AUTO} value it is necessary to resolve dialect before based on database connection. """ String itemTableSuffix = getItemTableSuffix(wsEntry); String valueTableSuffix = getValueTableSuffix(wsEntry); String refTableSuffix = getRefTableSuffix(wsEntry); DatabaseStructureType dbType = DBInitializerHelper.getDatabaseType(wsEntry); boolean isolatedDB = dbType == DatabaseStructureType.ISOLATED; String initScriptPath = DBInitializerHelper.scriptPath(dialect, dbType.isMultiDatabase()); return prepareScripts(initScriptPath, itemTableSuffix, valueTableSuffix, refTableSuffix, isolatedDB); }
java
public static String prepareScripts(WorkspaceEntry wsEntry, String dialect) throws IOException, RepositoryConfigurationException { String itemTableSuffix = getItemTableSuffix(wsEntry); String valueTableSuffix = getValueTableSuffix(wsEntry); String refTableSuffix = getRefTableSuffix(wsEntry); DatabaseStructureType dbType = DBInitializerHelper.getDatabaseType(wsEntry); boolean isolatedDB = dbType == DatabaseStructureType.ISOLATED; String initScriptPath = DBInitializerHelper.scriptPath(dialect, dbType.isMultiDatabase()); return prepareScripts(initScriptPath, itemTableSuffix, valueTableSuffix, refTableSuffix, isolatedDB); }
[ "public", "static", "String", "prepareScripts", "(", "WorkspaceEntry", "wsEntry", ",", "String", "dialect", ")", "throws", "IOException", ",", "RepositoryConfigurationException", "{", "String", "itemTableSuffix", "=", "getItemTableSuffix", "(", "wsEntry", ")", ";", "S...
Returns SQL scripts for initialization database for defined {@link WorkspaceEntry}. @param wsEntry workspace configuration @param dialect database dialect which is used, since {@link JDBCWorkspaceDataContainer#DB_DIALECT} parameter can contain {@link DialectConstants#DB_DIALECT_AUTO} value it is necessary to resolve dialect before based on database connection.
[ "Returns", "SQL", "scripts", "for", "initialization", "database", "for", "defined", "{", "@link", "WorkspaceEntry", "}", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/jdbc/DBInitializerHelper.java#L79-L92
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java
FieldRef.putInstanceField
public Statement putInstanceField(final Expression instance, final Expression value) { """ Returns a {@link Statement} that stores the {@code value} in this field on the given {@code instance}. @throws IllegalStateException if this is a static field """ checkState(!isStatic(), "This field is static!"); instance.checkAssignableTo(owner().type()); value.checkAssignableTo(type()); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { instance.gen(adapter); value.gen(adapter); putUnchecked(adapter); } }; }
java
public Statement putInstanceField(final Expression instance, final Expression value) { checkState(!isStatic(), "This field is static!"); instance.checkAssignableTo(owner().type()); value.checkAssignableTo(type()); return new Statement() { @Override protected void doGen(CodeBuilder adapter) { instance.gen(adapter); value.gen(adapter); putUnchecked(adapter); } }; }
[ "public", "Statement", "putInstanceField", "(", "final", "Expression", "instance", ",", "final", "Expression", "value", ")", "{", "checkState", "(", "!", "isStatic", "(", ")", ",", "\"This field is static!\"", ")", ";", "instance", ".", "checkAssignableTo", "(", ...
Returns a {@link Statement} that stores the {@code value} in this field on the given {@code instance}. @throws IllegalStateException if this is a static field
[ "Returns", "a", "{", "@link", "Statement", "}", "that", "stores", "the", "{", "@code", "value", "}", "in", "this", "field", "on", "the", "given", "{", "@code", "instance", "}", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/FieldRef.java#L203-L215
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/QuerySpecification.java
QuerySpecification.getResult
@Override Result getResult(Session session, int maxrows) { """ Returns the result of executing this Select. @param maxrows may be 0 to indicate no limit on the number of rows. Positive values limit the size of the result set. @return the result of executing this Select """ Result r; r = getSingleResult(session, maxrows); // fredt - now there is no need for the sort and group columns // r.setColumnCount(indexLimitVisible); r.getNavigator().reset(); return r; }
java
@Override Result getResult(Session session, int maxrows) { Result r; r = getSingleResult(session, maxrows); // fredt - now there is no need for the sort and group columns // r.setColumnCount(indexLimitVisible); r.getNavigator().reset(); return r; }
[ "@", "Override", "Result", "getResult", "(", "Session", "session", ",", "int", "maxrows", ")", "{", "Result", "r", ";", "r", "=", "getSingleResult", "(", "session", ",", "maxrows", ")", ";", "// fredt - now there is no need for the sort and group columns", "// ...
Returns the result of executing this Select. @param maxrows may be 0 to indicate no limit on the number of rows. Positive values limit the size of the result set. @return the result of executing this Select
[ "Returns", "the", "result", "of", "executing", "this", "Select", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/QuerySpecification.java#L1255-L1267
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/TimeZone.java
TimeZone.getOffsets
int getOffsets(long date, int[] offsets) { """ Gets the raw GMT offset and the amount of daylight saving of this time zone at the given time. @param date the milliseconds (since January 1, 1970, 00:00:00.000 GMT) at which the time zone offset and daylight saving amount are found @param offsets an array of int where the raw GMT offset (offset[0]) and daylight saving amount (offset[1]) are stored, or null if those values are not needed. The method assumes that the length of the given array is two or larger. @return the total amount of the raw GMT offset and daylight saving at the specified date. @see Calendar#ZONE_OFFSET @see Calendar#DST_OFFSET """ int rawoffset = getRawOffset(); int dstoffset = 0; if (inDaylightTime(new Date(date))) { dstoffset = getDSTSavings(); } if (offsets != null) { offsets[0] = rawoffset; offsets[1] = dstoffset; } return rawoffset + dstoffset; }
java
int getOffsets(long date, int[] offsets) { int rawoffset = getRawOffset(); int dstoffset = 0; if (inDaylightTime(new Date(date))) { dstoffset = getDSTSavings(); } if (offsets != null) { offsets[0] = rawoffset; offsets[1] = dstoffset; } return rawoffset + dstoffset; }
[ "int", "getOffsets", "(", "long", "date", ",", "int", "[", "]", "offsets", ")", "{", "int", "rawoffset", "=", "getRawOffset", "(", ")", ";", "int", "dstoffset", "=", "0", ";", "if", "(", "inDaylightTime", "(", "new", "Date", "(", "date", ")", ")", ...
Gets the raw GMT offset and the amount of daylight saving of this time zone at the given time. @param date the milliseconds (since January 1, 1970, 00:00:00.000 GMT) at which the time zone offset and daylight saving amount are found @param offsets an array of int where the raw GMT offset (offset[0]) and daylight saving amount (offset[1]) are stored, or null if those values are not needed. The method assumes that the length of the given array is two or larger. @return the total amount of the raw GMT offset and daylight saving at the specified date. @see Calendar#ZONE_OFFSET @see Calendar#DST_OFFSET
[ "Gets", "the", "raw", "GMT", "offset", "and", "the", "amount", "of", "daylight", "saving", "of", "this", "time", "zone", "at", "the", "given", "time", ".", "@param", "date", "the", "milliseconds", "(", "since", "January", "1", "1970", "00", ":", "00", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/TimeZone.java#L238-L249
netty/netty
common/src/main/java/io/netty/util/internal/StringUtil.java
StringUtil.toHexString
public static <T extends Appendable> T toHexString(T dst, byte[] src) { """ Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. """ return toHexString(dst, src, 0, src.length); }
java
public static <T extends Appendable> T toHexString(T dst, byte[] src) { return toHexString(dst, src, 0, src.length); }
[ "public", "static", "<", "T", "extends", "Appendable", ">", "T", "toHexString", "(", "T", "dst", ",", "byte", "[", "]", "src", ")", "{", "return", "toHexString", "(", "dst", ",", "src", ",", "0", ",", "src", ".", "length", ")", ";", "}" ]
Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
[ "Converts", "the", "specified", "byte", "array", "into", "a", "hexadecimal", "value", "and", "appends", "it", "to", "the", "specified", "buffer", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/StringUtil.java#L174-L176
moleculer-java/moleculer-java
src/main/java/services/moleculer/ServiceBroker.java
ServiceBroker.waitForServices
public Promise waitForServices(long timeoutMillis, String... services) { """ Waits for one (or an array of) service(s). Sample code:<br> <br> broker.waitForServices(5000, "logger").then(in -&gt; {<br> broker.getLogger().info("Logger started successfully");<br> }.catchError(error -&gt; {<br> broker.getLogger().info("Logger did not start");<br> } @param timeoutMillis timeout in milliseconds @param services array of service names @return listenable Promise """ return waitForServices(timeoutMillis, Arrays.asList(services)); }
java
public Promise waitForServices(long timeoutMillis, String... services) { return waitForServices(timeoutMillis, Arrays.asList(services)); }
[ "public", "Promise", "waitForServices", "(", "long", "timeoutMillis", ",", "String", "...", "services", ")", "{", "return", "waitForServices", "(", "timeoutMillis", ",", "Arrays", ".", "asList", "(", "services", ")", ")", ";", "}" ]
Waits for one (or an array of) service(s). Sample code:<br> <br> broker.waitForServices(5000, "logger").then(in -&gt; {<br> broker.getLogger().info("Logger started successfully");<br> }.catchError(error -&gt; {<br> broker.getLogger().info("Logger did not start");<br> } @param timeoutMillis timeout in milliseconds @param services array of service names @return listenable Promise
[ "Waits", "for", "one", "(", "or", "an", "array", "of", ")", "service", "(", "s", ")", ".", "Sample", "code", ":", "<br", ">", "<br", ">", "broker", ".", "waitForServices", "(", "5000", "logger", ")", ".", "then", "(", "in", "-", "&gt", ";", "{", ...
train
https://github.com/moleculer-java/moleculer-java/blob/27575c44b9ecacc17c4456ceacf5d1851abf1cc4/src/main/java/services/moleculer/ServiceBroker.java#L805-L807
mangstadt/biweekly
src/main/java/biweekly/property/ICalProperty.java
ICalProperty.setParameter
public void setParameter(String name, Collection<String> values) { """ Replaces all existing values of a parameter with the given values. @param name the parameter name (case insensitive, e.g. "LANGUAGE") @param values the parameter values """ parameters.replace(name, values); }
java
public void setParameter(String name, Collection<String> values) { parameters.replace(name, values); }
[ "public", "void", "setParameter", "(", "String", "name", ",", "Collection", "<", "String", ">", "values", ")", "{", "parameters", ".", "replace", "(", "name", ",", "values", ")", ";", "}" ]
Replaces all existing values of a parameter with the given values. @param name the parameter name (case insensitive, e.g. "LANGUAGE") @param values the parameter values
[ "Replaces", "all", "existing", "values", "of", "a", "parameter", "with", "the", "given", "values", "." ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/property/ICalProperty.java#L124-L126
geomajas/geomajas-project-graphics
graphics/src/main/java/org/geomajas/graphics/client/util/CopyUtil.java
CopyUtil.copyStrokableProperties
public static void copyStrokableProperties(HasStroke strokableOriginal, HasStroke strokableCopy) { """ Copy all {@link HasStroke} properties from original to copy. @param strokableOriginal @param strokableCopy """ strokableCopy.setStrokeOpacity(strokableOriginal.getStrokeOpacity()); strokableCopy.setStrokeColor(strokableOriginal.getStrokeColor()); strokableCopy.setStrokeWidth(strokableOriginal.getStrokeWidth()); }
java
public static void copyStrokableProperties(HasStroke strokableOriginal, HasStroke strokableCopy) { strokableCopy.setStrokeOpacity(strokableOriginal.getStrokeOpacity()); strokableCopy.setStrokeColor(strokableOriginal.getStrokeColor()); strokableCopy.setStrokeWidth(strokableOriginal.getStrokeWidth()); }
[ "public", "static", "void", "copyStrokableProperties", "(", "HasStroke", "strokableOriginal", ",", "HasStroke", "strokableCopy", ")", "{", "strokableCopy", ".", "setStrokeOpacity", "(", "strokableOriginal", ".", "getStrokeOpacity", "(", ")", ")", ";", "strokableCopy", ...
Copy all {@link HasStroke} properties from original to copy. @param strokableOriginal @param strokableCopy
[ "Copy", "all", "{", "@link", "HasStroke", "}", "properties", "from", "original", "to", "copy", "." ]
train
https://github.com/geomajas/geomajas-project-graphics/blob/1104196640e0ba455b8a619e774352a8e1e319ba/graphics/src/main/java/org/geomajas/graphics/client/util/CopyUtil.java#L55-L59
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/DatatypeConverter.java
DatatypeConverter.printExtendedAttribute
public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type) { """ Print an extended attribute value. @param writer parent MSPDIWriter instance @param value attribute value @param type type of the value being passed @return string representation """ String result; if (type == DataType.DATE) { result = printExtendedAttributeDate((Date) value); } else { if (value instanceof Boolean) { result = printExtendedAttributeBoolean((Boolean) value); } else { if (value instanceof Duration) { result = printDuration(writer, (Duration) value); } else { if (type == DataType.CURRENCY) { result = printExtendedAttributeCurrency((Number) value); } else { if (value instanceof Number) { result = printExtendedAttributeNumber((Number) value); } else { result = value.toString(); } } } } } return (result); }
java
public static final String printExtendedAttribute(MSPDIWriter writer, Object value, DataType type) { String result; if (type == DataType.DATE) { result = printExtendedAttributeDate((Date) value); } else { if (value instanceof Boolean) { result = printExtendedAttributeBoolean((Boolean) value); } else { if (value instanceof Duration) { result = printDuration(writer, (Duration) value); } else { if (type == DataType.CURRENCY) { result = printExtendedAttributeCurrency((Number) value); } else { if (value instanceof Number) { result = printExtendedAttributeNumber((Number) value); } else { result = value.toString(); } } } } } return (result); }
[ "public", "static", "final", "String", "printExtendedAttribute", "(", "MSPDIWriter", "writer", ",", "Object", "value", ",", "DataType", "type", ")", "{", "String", "result", ";", "if", "(", "type", "==", "DataType", ".", "DATE", ")", "{", "result", "=", "p...
Print an extended attribute value. @param writer parent MSPDIWriter instance @param value attribute value @param type type of the value being passed @return string representation
[ "Print", "an", "extended", "attribute", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/DatatypeConverter.java#L186-L228
alibaba/jstorm
jstorm-core/src/main/java/backtype/storm/scheduler/multitenant/IsolatedPool.java
IsolatedPool.getNodesForIsolatedTop
private int getNodesForIsolatedTop(TopologyDetails td, Set<Node> allNodes, NodePool[] lesserPools, int nodesRequested) { """ Get the nodes needed to schedule an isolated topology. @param td the topology to be scheduled @param allNodes the nodes already scheduled for this topology. This will be updated to include new nodes if needed. @param lesserPools node pools we can steal nodes from @return the number of additional slots that should be used for scheduling. """ String topId = td.getId(); LOG.debug("Topology {} is isolated", topId); int nodesFromUsAvailable = nodesAvailable(); int nodesFromOthersAvailable = NodePool.nodesAvailable(lesserPools); int nodesUsed = _topologyIdToNodes.get(topId).size(); int nodesNeeded = nodesRequested - nodesUsed; LOG.debug("Nodes... requested {} used {} available from us {} " + "avail from other {} needed {}", new Object[]{nodesRequested, nodesUsed, nodesFromUsAvailable, nodesFromOthersAvailable, nodesNeeded}); if ((nodesNeeded - nodesFromUsAvailable) > (_maxNodes - _usedNodes)) { _cluster.setStatus(topId, "Max Nodes(" + _maxNodes + ") for this user would be exceeded. " + ((nodesNeeded - nodesFromUsAvailable) - (_maxNodes - _usedNodes)) + " more nodes needed to run topology."); return 0; } // In order to avoid going over _maxNodes I may need to steal from // myself even though other pools have free nodes. so figure out how // much each group should provide int nodesNeededFromOthers = Math.min(Math.min(_maxNodes - _usedNodes, nodesFromOthersAvailable), nodesNeeded); int nodesNeededFromUs = nodesNeeded - nodesNeededFromOthers; LOG.debug("Nodes... needed from us {} needed from others {}", nodesNeededFromUs, nodesNeededFromOthers); if (nodesNeededFromUs > nodesFromUsAvailable) { _cluster.setStatus(topId, "Not Enough Nodes Available to Schedule Topology"); return 0; } // Get the nodes Collection<Node> found = NodePool.takeNodes(nodesNeededFromOthers, lesserPools); _usedNodes += found.size(); allNodes.addAll(found); Collection<Node> foundMore = takeNodes(nodesNeededFromUs); _usedNodes += foundMore.size(); allNodes.addAll(foundMore); int totalTasks = td.getExecutors().size(); int origRequest = td.getNumWorkers(); int slotsRequested = Math.min(totalTasks, origRequest); int slotsUsed = Node.countSlotsUsed(allNodes); int slotsFree = Node.countFreeSlotsAlive(allNodes); int slotsToUse = Math.min(slotsRequested - slotsUsed, slotsFree); if (slotsToUse <= 0) { _cluster.setStatus(topId, "Node has partially crashed, if this situation persists rebalance the topology."); } return slotsToUse; }
java
private int getNodesForIsolatedTop(TopologyDetails td, Set<Node> allNodes, NodePool[] lesserPools, int nodesRequested) { String topId = td.getId(); LOG.debug("Topology {} is isolated", topId); int nodesFromUsAvailable = nodesAvailable(); int nodesFromOthersAvailable = NodePool.nodesAvailable(lesserPools); int nodesUsed = _topologyIdToNodes.get(topId).size(); int nodesNeeded = nodesRequested - nodesUsed; LOG.debug("Nodes... requested {} used {} available from us {} " + "avail from other {} needed {}", new Object[]{nodesRequested, nodesUsed, nodesFromUsAvailable, nodesFromOthersAvailable, nodesNeeded}); if ((nodesNeeded - nodesFromUsAvailable) > (_maxNodes - _usedNodes)) { _cluster.setStatus(topId, "Max Nodes(" + _maxNodes + ") for this user would be exceeded. " + ((nodesNeeded - nodesFromUsAvailable) - (_maxNodes - _usedNodes)) + " more nodes needed to run topology."); return 0; } // In order to avoid going over _maxNodes I may need to steal from // myself even though other pools have free nodes. so figure out how // much each group should provide int nodesNeededFromOthers = Math.min(Math.min(_maxNodes - _usedNodes, nodesFromOthersAvailable), nodesNeeded); int nodesNeededFromUs = nodesNeeded - nodesNeededFromOthers; LOG.debug("Nodes... needed from us {} needed from others {}", nodesNeededFromUs, nodesNeededFromOthers); if (nodesNeededFromUs > nodesFromUsAvailable) { _cluster.setStatus(topId, "Not Enough Nodes Available to Schedule Topology"); return 0; } // Get the nodes Collection<Node> found = NodePool.takeNodes(nodesNeededFromOthers, lesserPools); _usedNodes += found.size(); allNodes.addAll(found); Collection<Node> foundMore = takeNodes(nodesNeededFromUs); _usedNodes += foundMore.size(); allNodes.addAll(foundMore); int totalTasks = td.getExecutors().size(); int origRequest = td.getNumWorkers(); int slotsRequested = Math.min(totalTasks, origRequest); int slotsUsed = Node.countSlotsUsed(allNodes); int slotsFree = Node.countFreeSlotsAlive(allNodes); int slotsToUse = Math.min(slotsRequested - slotsUsed, slotsFree); if (slotsToUse <= 0) { _cluster.setStatus(topId, "Node has partially crashed, if this situation persists rebalance the topology."); } return slotsToUse; }
[ "private", "int", "getNodesForIsolatedTop", "(", "TopologyDetails", "td", ",", "Set", "<", "Node", ">", "allNodes", ",", "NodePool", "[", "]", "lesserPools", ",", "int", "nodesRequested", ")", "{", "String", "topId", "=", "td", ".", "getId", "(", ")", ";",...
Get the nodes needed to schedule an isolated topology. @param td the topology to be scheduled @param allNodes the nodes already scheduled for this topology. This will be updated to include new nodes if needed. @param lesserPools node pools we can steal nodes from @return the number of additional slots that should be used for scheduling.
[ "Get", "the", "nodes", "needed", "to", "schedule", "an", "isolated", "topology", "." ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/backtype/storm/scheduler/multitenant/IsolatedPool.java#L146-L192
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/user/UserCoreDao.java
UserCoreDao.queryForValueFieldValues
public TResult queryForValueFieldValues(Map<String, ColumnValue> fieldValues) { """ Query for the row where all fields match their values @param fieldValues field values @return result """ String where = buildValueWhere(fieldValues.entrySet()); String[] whereArgs = buildValueWhereArgs(fieldValues.values()); TResult result = userDb.query(getTableName(), table.getColumnNames(), where, whereArgs, null, null, null); prepareResult(result); return result; }
java
public TResult queryForValueFieldValues(Map<String, ColumnValue> fieldValues) { String where = buildValueWhere(fieldValues.entrySet()); String[] whereArgs = buildValueWhereArgs(fieldValues.values()); TResult result = userDb.query(getTableName(), table.getColumnNames(), where, whereArgs, null, null, null); prepareResult(result); return result; }
[ "public", "TResult", "queryForValueFieldValues", "(", "Map", "<", "String", ",", "ColumnValue", ">", "fieldValues", ")", "{", "String", "where", "=", "buildValueWhere", "(", "fieldValues", ".", "entrySet", "(", ")", ")", ";", "String", "[", "]", "whereArgs", ...
Query for the row where all fields match their values @param fieldValues field values @return result
[ "Query", "for", "the", "row", "where", "all", "fields", "match", "their", "values" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/user/UserCoreDao.java#L370-L377
maxirosson/jdroid-android
jdroid-android-core/src/main/java/com/jdroid/android/permission/PermissionHelper.java
PermissionHelper.onRequestPermissionsResult
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { """ This method must be called from the respective method of the fragment/activity. """ if (requestCode == permissionRequestCode) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (onRequestPermissionsResultListener != null) { onRequestPermissionsResultListener.onRequestPermissionsGranted(); } } else { if (onRequestPermissionsResultListener != null) { onRequestPermissionsResultListener.onRequestPermissionsDenied(); } if (previouslyShouldShowRequestPermissionRationale != null && !previouslyShouldShowRequestPermissionRationale && !permissionDelegate.shouldShowRequestPermissionRationale(permission)) { //Note: onRequestPermissionsResult(...) is called immediately before onResume() (like onActivityResult(...)), // if the dialog is show immediately in this case an exception occurs ("java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState"). pendingAppInfoDialog = true; } } } }
java
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == permissionRequestCode) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (onRequestPermissionsResultListener != null) { onRequestPermissionsResultListener.onRequestPermissionsGranted(); } } else { if (onRequestPermissionsResultListener != null) { onRequestPermissionsResultListener.onRequestPermissionsDenied(); } if (previouslyShouldShowRequestPermissionRationale != null && !previouslyShouldShowRequestPermissionRationale && !permissionDelegate.shouldShowRequestPermissionRationale(permission)) { //Note: onRequestPermissionsResult(...) is called immediately before onResume() (like onActivityResult(...)), // if the dialog is show immediately in this case an exception occurs ("java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState"). pendingAppInfoDialog = true; } } } }
[ "public", "void", "onRequestPermissionsResult", "(", "int", "requestCode", ",", "@", "NonNull", "String", "[", "]", "permissions", ",", "@", "NonNull", "int", "[", "]", "grantResults", ")", "{", "if", "(", "requestCode", "==", "permissionRequestCode", ")", "{"...
This method must be called from the respective method of the fragment/activity.
[ "This", "method", "must", "be", "called", "from", "the", "respective", "method", "of", "the", "fragment", "/", "activity", "." ]
train
https://github.com/maxirosson/jdroid-android/blob/1ba9cae56a16fa36bdb2c9c04379853f0300707f/jdroid-android-core/src/main/java/com/jdroid/android/permission/PermissionHelper.java#L289-L307
looly/hutool
hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java
NumberUtil.roundHalfEven
public static BigDecimal roundHalfEven(BigDecimal value, int scale) { """ 四舍六入五成双计算法 <p> 四舍六入五成双是一种比较精确比较科学的计数保留法,是一种数字修约规则。 </p> <pre> 算法规则: 四舍六入五考虑, 五后非零就进一, 五后皆零看奇偶, 五前为偶应舍去, 五前为奇要进一。 </pre> @param value 需要科学计算的数据 @param scale 保留的小数位 @return 结果 @since 4.1.0 """ return round(value, scale, RoundingMode.HALF_EVEN); }
java
public static BigDecimal roundHalfEven(BigDecimal value, int scale) { return round(value, scale, RoundingMode.HALF_EVEN); }
[ "public", "static", "BigDecimal", "roundHalfEven", "(", "BigDecimal", "value", ",", "int", "scale", ")", "{", "return", "round", "(", "value", ",", "scale", ",", "RoundingMode", ".", "HALF_EVEN", ")", ";", "}" ]
四舍六入五成双计算法 <p> 四舍六入五成双是一种比较精确比较科学的计数保留法,是一种数字修约规则。 </p> <pre> 算法规则: 四舍六入五考虑, 五后非零就进一, 五后皆零看奇偶, 五前为偶应舍去, 五前为奇要进一。 </pre> @param value 需要科学计算的数据 @param scale 保留的小数位 @return 结果 @since 4.1.0
[ "四舍六入五成双计算法", "<p", ">", "四舍六入五成双是一种比较精确比较科学的计数保留法,是一种数字修约规则。", "<", "/", "p", ">" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/NumberUtil.java#L945-L947
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/Iterate.java
Iterate.sumOfBigInteger
public static <T> BigInteger sumOfBigInteger(Iterable<T> iterable, Function<? super T, BigInteger> function) { """ Returns the BigInteger sum of the result of applying the function to each element of the iterable. @since 6.0 """ if (iterable instanceof List) { return ListIterate.sumOfBigInteger((List<T>) iterable, function); } if (iterable != null) { return IterableIterate.sumOfBigInteger(iterable, function); } throw new IllegalArgumentException("Cannot perform an sumOfBigDecimal on null"); }
java
public static <T> BigInteger sumOfBigInteger(Iterable<T> iterable, Function<? super T, BigInteger> function) { if (iterable instanceof List) { return ListIterate.sumOfBigInteger((List<T>) iterable, function); } if (iterable != null) { return IterableIterate.sumOfBigInteger(iterable, function); } throw new IllegalArgumentException("Cannot perform an sumOfBigDecimal on null"); }
[ "public", "static", "<", "T", ">", "BigInteger", "sumOfBigInteger", "(", "Iterable", "<", "T", ">", "iterable", ",", "Function", "<", "?", "super", "T", ",", "BigInteger", ">", "function", ")", "{", "if", "(", "iterable", "instanceof", "List", ")", "{", ...
Returns the BigInteger sum of the result of applying the function to each element of the iterable. @since 6.0
[ "Returns", "the", "BigInteger", "sum", "of", "the", "result", "of", "applying", "the", "function", "to", "each", "element", "of", "the", "iterable", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/Iterate.java#L2635-L2646
FXMisc/RichTextFX
richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java
MultiChangeBuilder.insertText
public MultiChangeBuilder<PS, SEG, S> insertText(int paragraphIndex, int columnPosition, String text) { """ Inserts the given text at the position returned from {@code getAbsolutePosition(paragraphIndex, columnPosition)}. <p><b>Caution:</b> see {@link StyledDocument#getAbsolutePosition(int, int)} to know how the column index argument can affect the returned position.</p> @param text The text to insert """ int index = area.getAbsolutePosition(paragraphIndex, columnPosition); return replaceText(index, index, text); }
java
public MultiChangeBuilder<PS, SEG, S> insertText(int paragraphIndex, int columnPosition, String text) { int index = area.getAbsolutePosition(paragraphIndex, columnPosition); return replaceText(index, index, text); }
[ "public", "MultiChangeBuilder", "<", "PS", ",", "SEG", ",", "S", ">", "insertText", "(", "int", "paragraphIndex", ",", "int", "columnPosition", ",", "String", "text", ")", "{", "int", "index", "=", "area", ".", "getAbsolutePosition", "(", "paragraphIndex", "...
Inserts the given text at the position returned from {@code getAbsolutePosition(paragraphIndex, columnPosition)}. <p><b>Caution:</b> see {@link StyledDocument#getAbsolutePosition(int, int)} to know how the column index argument can affect the returned position.</p> @param text The text to insert
[ "Inserts", "the", "given", "text", "at", "the", "position", "returned", "from", "{", "@code", "getAbsolutePosition", "(", "paragraphIndex", "columnPosition", ")", "}", "." ]
train
https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java#L163-L166
imsweb/naaccr-xml
src/main/java/com/imsweb/naaccrxml/sas/SasUtils.java
SasUtils.createWriter
public static BufferedWriter createWriter(File file) throws IOException { """ Creates a writer from the given file. Supports GZIP compressed files. @param file file to write @return writer """ OutputStream os = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) os = new GZIPOutputStream(os); return new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)); }
java
public static BufferedWriter createWriter(File file) throws IOException { OutputStream os = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) os = new GZIPOutputStream(os); return new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)); }
[ "public", "static", "BufferedWriter", "createWriter", "(", "File", "file", ")", "throws", "IOException", "{", "OutputStream", "os", "=", "new", "FileOutputStream", "(", "file", ")", ";", "if", "(", "file", ".", "getName", "(", ")", ".", "toLowerCase", "(", ...
Creates a writer from the given file. Supports GZIP compressed files. @param file file to write @return writer
[ "Creates", "a", "writer", "from", "the", "given", "file", ".", "Supports", "GZIP", "compressed", "files", "." ]
train
https://github.com/imsweb/naaccr-xml/blob/a3a501faa2a0c3411dd5248b2c1379f279131696/src/main/java/com/imsweb/naaccrxml/sas/SasUtils.java#L50-L55
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/user/UserClient.java
UserClient.updateFriendsNote
public ResponseWrapper updateFriendsNote(String username, FriendNote[] array) throws APIConnectionException, APIRequestException { """ Update friends' note information. The size is limit to 500. @param username Necessary @param array FriendNote array @return No content @throws APIConnectionException connect exception @throws APIRequestException request exception """ StringUtils.checkUsername(username); FriendNotePayload payload = new FriendNotePayload.Builder() .setFriendNotes(array) .build(); Preconditions.checkArgument(null != payload, "FriendNotePayload should not be null"); return _httpClient.sendPut(_baseUrl + userPath + "/" + username + "/friends", payload.toString()); }
java
public ResponseWrapper updateFriendsNote(String username, FriendNote[] array) throws APIConnectionException, APIRequestException { StringUtils.checkUsername(username); FriendNotePayload payload = new FriendNotePayload.Builder() .setFriendNotes(array) .build(); Preconditions.checkArgument(null != payload, "FriendNotePayload should not be null"); return _httpClient.sendPut(_baseUrl + userPath + "/" + username + "/friends", payload.toString()); }
[ "public", "ResponseWrapper", "updateFriendsNote", "(", "String", "username", ",", "FriendNote", "[", "]", "array", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "StringUtils", ".", "checkUsername", "(", "username", ")", ";", "FriendNotePayl...
Update friends' note information. The size is limit to 500. @param username Necessary @param array FriendNote array @return No content @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Update", "friends", "note", "information", ".", "The", "size", "is", "limit", "to", "500", "." ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/user/UserClient.java#L326-L334
OpenTSDB/opentsdb
src/meta/Annotation.java
Annotation.getAnnotation
public static Deferred<Annotation> getAnnotation(final TSDB tsdb, final long start_time) { """ Attempts to fetch a global annotation from storage @param tsdb The TSDB to use for storage access @param start_time The start time as a Unix epoch timestamp @return A valid annotation object if found, null if not """ return getAnnotation(tsdb, (byte[])null, start_time); }
java
public static Deferred<Annotation> getAnnotation(final TSDB tsdb, final long start_time) { return getAnnotation(tsdb, (byte[])null, start_time); }
[ "public", "static", "Deferred", "<", "Annotation", ">", "getAnnotation", "(", "final", "TSDB", "tsdb", ",", "final", "long", "start_time", ")", "{", "return", "getAnnotation", "(", "tsdb", ",", "(", "byte", "[", "]", ")", "null", ",", "start_time", ")", ...
Attempts to fetch a global annotation from storage @param tsdb The TSDB to use for storage access @param start_time The start time as a Unix epoch timestamp @return A valid annotation object if found, null if not
[ "Attempts", "to", "fetch", "a", "global", "annotation", "from", "storage" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/meta/Annotation.java#L231-L234
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java
FileUtil.getWriter
public static BufferedWriter getWriter(File file, String charsetName, boolean isAppend) throws IORuntimeException { """ 获得一个带缓存的写入对象 @param file 输出文件 @param charsetName 字符集 @param isAppend 是否追加 @return BufferedReader对象 @throws IORuntimeException IO异常 """ return getWriter(file, Charset.forName(charsetName), isAppend); }
java
public static BufferedWriter getWriter(File file, String charsetName, boolean isAppend) throws IORuntimeException { return getWriter(file, Charset.forName(charsetName), isAppend); }
[ "public", "static", "BufferedWriter", "getWriter", "(", "File", "file", ",", "String", "charsetName", ",", "boolean", "isAppend", ")", "throws", "IORuntimeException", "{", "return", "getWriter", "(", "file", ",", "Charset", ".", "forName", "(", "charsetName", ")...
获得一个带缓存的写入对象 @param file 输出文件 @param charsetName 字符集 @param isAppend 是否追加 @return BufferedReader对象 @throws IORuntimeException IO异常
[ "获得一个带缓存的写入对象" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L2611-L2613
google/error-prone-javac
src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java
ElementFilter.requiresIn
public static List<RequiresDirective> requiresIn(Iterable<? extends Directive> directives) { """ Returns a list of {@code requires} directives in {@code directives}. @return a list of {@code requires} directives in {@code directives} @param directives the directives to filter @since 9 @spec JPMS """ return listFilter(directives, DirectiveKind.REQUIRES, RequiresDirective.class); }
java
public static List<RequiresDirective> requiresIn(Iterable<? extends Directive> directives) { return listFilter(directives, DirectiveKind.REQUIRES, RequiresDirective.class); }
[ "public", "static", "List", "<", "RequiresDirective", ">", "requiresIn", "(", "Iterable", "<", "?", "extends", "Directive", ">", "directives", ")", "{", "return", "listFilter", "(", "directives", ",", "DirectiveKind", ".", "REQUIRES", ",", "RequiresDirective", "...
Returns a list of {@code requires} directives in {@code directives}. @return a list of {@code requires} directives in {@code directives} @param directives the directives to filter @since 9 @spec JPMS
[ "Returns", "a", "list", "of", "{" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java#L278-L281
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/utils/LoadConf.java
LoadConf.dumpYaml
public static void dumpYaml(Map conf, String file) { """ dumps a conf map into a file, note that the output yaml file uses a compact format e.g., for a list, it uses key: [xx, xx] instead of multiple lines. """ Yaml yaml = new Yaml(); try { Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); yaml.dump(conf, writer); } catch (Exception ex) { LOG.error("Error:", ex); } }
java
public static void dumpYaml(Map conf, String file) { Yaml yaml = new Yaml(); try { Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); yaml.dump(conf, writer); } catch (Exception ex) { LOG.error("Error:", ex); } }
[ "public", "static", "void", "dumpYaml", "(", "Map", "conf", ",", "String", "file", ")", "{", "Yaml", "yaml", "=", "new", "Yaml", "(", ")", ";", "try", "{", "Writer", "writer", "=", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "file",...
dumps a conf map into a file, note that the output yaml file uses a compact format e.g., for a list, it uses key: [xx, xx] instead of multiple lines.
[ "dumps", "a", "conf", "map", "into", "a", "file", "note", "that", "the", "output", "yaml", "file", "uses", "a", "compact", "format", "e", ".", "g", ".", "for", "a", "list", "it", "uses", "key", ":", "[", "xx", "xx", "]", "instead", "of", "multiple"...
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/utils/LoadConf.java#L174-L182
apache/flink
flink-core/src/main/java/org/apache/flink/types/Record.java
Record.setField
public void setField(int fieldNum, Value value) { """ Sets the field at the given position to the given value. If the field position is larger or equal than the current number of fields in the record, than the record is expanded to host as many columns. <p> The value is kept as a reference in the record until the binary representation is synchronized. Until that point, all modifications to the value's object will change the value inside the record. <p> The binary representation is synchronized the latest when the record is emitted. It may be triggered manually at an earlier point, but it is generally not necessary and advisable. Because the synchronization triggers the serialization on all modified values, it may be an expensive operation. @param fieldNum The position of the field, starting at zero. @param value The new value. """ // range check if (fieldNum < 0) { throw new IndexOutOfBoundsException(); } // if the field number is beyond the size, the tuple is expanded if (fieldNum >= this.numFields) { setNumFields(fieldNum + 1); } internallySetField(fieldNum, value); }
java
public void setField(int fieldNum, Value value) { // range check if (fieldNum < 0) { throw new IndexOutOfBoundsException(); } // if the field number is beyond the size, the tuple is expanded if (fieldNum >= this.numFields) { setNumFields(fieldNum + 1); } internallySetField(fieldNum, value); }
[ "public", "void", "setField", "(", "int", "fieldNum", ",", "Value", "value", ")", "{", "// range check", "if", "(", "fieldNum", "<", "0", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "// if the field number is beyond the size, the tup...
Sets the field at the given position to the given value. If the field position is larger or equal than the current number of fields in the record, than the record is expanded to host as many columns. <p> The value is kept as a reference in the record until the binary representation is synchronized. Until that point, all modifications to the value's object will change the value inside the record. <p> The binary representation is synchronized the latest when the record is emitted. It may be triggered manually at an earlier point, but it is generally not necessary and advisable. Because the synchronization triggers the serialization on all modified values, it may be an expensive operation. @param fieldNum The position of the field, starting at zero. @param value The new value.
[ "Sets", "the", "field", "at", "the", "given", "position", "to", "the", "given", "value", ".", "If", "the", "field", "position", "is", "larger", "or", "equal", "than", "the", "current", "number", "of", "fields", "in", "the", "record", "than", "the", "reco...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/Record.java#L402-L413
javactic/javactic
src/main/java/com/github/javactic/Accumulation.java
Accumulation.validatedBy
public static <F, G, ERR> Or<Vector<G>, Every<ERR>> validatedBy(Iterable<? extends F> iterable, Function<? super F, ? extends Or<? extends G, ? extends Every<? extends ERR>>> f) { """ Maps an iterable of Fs into an Ors of type Or&lt;G, EVERY&lt;ERR&gt;&gt; (where EVERY is some subtype of Every) using the passed function f, then combines the resulting Ors into a single Or of type Or&lt;Vector&lt;G&gt;, Every&lt;ERR&gt;&gt;. <p> Note: the process implemented by this method is sometimes called a &quot;traverse&quot;. </p> @param <F> the type of the original iterable to validate @param <G> the Good type of the resulting Or @param <ERR> the Bad type of the resulting Or @param iterable the iterable to validate @param f the validation function @return an Or of all the success values or of all the errors """ return validatedBy(iterable, f, Vector.collector()); }
java
public static <F, G, ERR> Or<Vector<G>, Every<ERR>> validatedBy(Iterable<? extends F> iterable, Function<? super F, ? extends Or<? extends G, ? extends Every<? extends ERR>>> f) { return validatedBy(iterable, f, Vector.collector()); }
[ "public", "static", "<", "F", ",", "G", ",", "ERR", ">", "Or", "<", "Vector", "<", "G", ">", ",", "Every", "<", "ERR", ">", ">", "validatedBy", "(", "Iterable", "<", "?", "extends", "F", ">", "iterable", ",", "Function", "<", "?", "super", "F", ...
Maps an iterable of Fs into an Ors of type Or&lt;G, EVERY&lt;ERR&gt;&gt; (where EVERY is some subtype of Every) using the passed function f, then combines the resulting Ors into a single Or of type Or&lt;Vector&lt;G&gt;, Every&lt;ERR&gt;&gt;. <p> Note: the process implemented by this method is sometimes called a &quot;traverse&quot;. </p> @param <F> the type of the original iterable to validate @param <G> the Good type of the resulting Or @param <ERR> the Bad type of the resulting Or @param iterable the iterable to validate @param f the validation function @return an Or of all the success values or of all the errors
[ "Maps", "an", "iterable", "of", "Fs", "into", "an", "Ors", "of", "type", "Or&lt", ";", "G", "EVERY&lt", ";", "ERR&gt", ";", "&gt", ";", "(", "where", "EVERY", "is", "some", "subtype", "of", "Every", ")", "using", "the", "passed", "function", "f", "th...
train
https://github.com/javactic/javactic/blob/dfa040062178c259c3067fd9b59cb4498022d8bc/src/main/java/com/github/javactic/Accumulation.java#L111-L115
mikepenz/Android-Iconics
library-core/src/main/java/com/mikepenz/iconics/Iconics.java
Iconics.iconExists
public static boolean iconExists(@NonNull Context context, @NonNull String icon) { """ Test if the icon exists in the currently loaded fonts @param context A context to access application resources @param icon The icon to verify @return true if the icon is available """ try { ITypeface font = findFont(context, icon.substring(0, 3)); icon = icon.replace("-", "_"); font.getIcon(icon); return true; } catch (Exception ignore) { return false; } }
java
public static boolean iconExists(@NonNull Context context, @NonNull String icon) { try { ITypeface font = findFont(context, icon.substring(0, 3)); icon = icon.replace("-", "_"); font.getIcon(icon); return true; } catch (Exception ignore) { return false; } }
[ "public", "static", "boolean", "iconExists", "(", "@", "NonNull", "Context", "context", ",", "@", "NonNull", "String", "icon", ")", "{", "try", "{", "ITypeface", "font", "=", "findFont", "(", "context", ",", "icon", ".", "substring", "(", "0", ",", "3", ...
Test if the icon exists in the currently loaded fonts @param context A context to access application resources @param icon The icon to verify @return true if the icon is available
[ "Test", "if", "the", "icon", "exists", "in", "the", "currently", "loaded", "fonts" ]
train
https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/Iconics.java#L114-L123
forge/javaee-descriptors
impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/validationConfiguration11/ValidationConfigurationDescriptorImpl.java
ValidationConfigurationDescriptorImpl.addNamespace
public ValidationConfigurationDescriptor addNamespace(String name, String value) { """ Adds a new namespace @return the current instance of <code>ValidationConfigurationDescriptor</code> """ model.attribute(name, value); return this; }
java
public ValidationConfigurationDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
[ "public", "ValidationConfigurationDescriptor", "addNamespace", "(", "String", "name", ",", "String", "value", ")", "{", "model", ".", "attribute", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a new namespace @return the current instance of <code>ValidationConfigurationDescriptor</code>
[ "Adds", "a", "new", "namespace" ]
train
https://github.com/forge/javaee-descriptors/blob/cb914330a1a0b04bfc1d0f199bd9cde3bbf0b3ed/impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/validationConfiguration11/ValidationConfigurationDescriptorImpl.java#L84-L88
morimekta/utils
io-util/src/main/java/net/morimekta/util/io/IndentedPrintWriter.java
IndentedPrintWriter.printf
@Override public IndentedPrintWriter printf(String format, Object... args) { """ --- Override PrintWriter methods to return IndentedPrintWriter. """ super.format(format, args); return this; }
java
@Override public IndentedPrintWriter printf(String format, Object... args) { super.format(format, args); return this; }
[ "@", "Override", "public", "IndentedPrintWriter", "printf", "(", "String", "format", ",", "Object", "...", "args", ")", "{", "super", ".", "format", "(", "format", ",", "args", ")", ";", "return", "this", ";", "}" ]
--- Override PrintWriter methods to return IndentedPrintWriter.
[ "---", "Override", "PrintWriter", "methods", "to", "return", "IndentedPrintWriter", "." ]
train
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/io/IndentedPrintWriter.java#L132-L136
synchronoss/cpo-api
cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java
CassandraCpoAdapter.insertObjects
@Override public <T> long insertObjects(String name, Collection<T> coll, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { """ Iterates through a collection of Objects, creates and stores them in the datasource. The assumption is that the objects contained in the collection do not exist in the datasource. <p/> This method creates and stores the objects in the datasource. The objects in the collection will be treated as one transaction, assuming the datasource supports transactions. <p/> This means that if one of the objects fail being created in the datasource then the CpoAdapter should stop processing the remainder of the collection, and if supported, rollback all the objects created thus far. <p/> <pre>Example: <code> <p/> class SomeObject so = null; class CpoAdapter cpo = null; <p/> try { cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false)); } catch (CpoException ce) { // Handle the error cpo = null; } if (cpo!=null) { ArrayList al = new ArrayList(); for (int i=0; i<3; i++){ so = new SomeObject(); so.setId(1); so.setName("SomeName"); al.add(so); } try{ cpo.insertObjects("IdNameInsert",al); } catch (CpoException ce) { // Handle the error } } </code> </pre> @param name The String name of the CREATE Function Group that will be used to create the object in the datasource. null signifies that the default rules will be used. @param coll This is a collection of objects that have been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return The number of objects created in the datasource @throws CpoException Thrown if there are errors accessing the datasource """ return processUpdateGroup(coll, CpoAdapter.CREATE_GROUP, name, wheres, orderBy, nativeExpressions); }
java
@Override public <T> long insertObjects(String name, Collection<T> coll, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { return processUpdateGroup(coll, CpoAdapter.CREATE_GROUP, name, wheres, orderBy, nativeExpressions); }
[ "@", "Override", "public", "<", "T", ">", "long", "insertObjects", "(", "String", "name", ",", "Collection", "<", "T", ">", "coll", ",", "Collection", "<", "CpoWhere", ">", "wheres", ",", "Collection", "<", "CpoOrderBy", ">", "orderBy", ",", "Collection", ...
Iterates through a collection of Objects, creates and stores them in the datasource. The assumption is that the objects contained in the collection do not exist in the datasource. <p/> This method creates and stores the objects in the datasource. The objects in the collection will be treated as one transaction, assuming the datasource supports transactions. <p/> This means that if one of the objects fail being created in the datasource then the CpoAdapter should stop processing the remainder of the collection, and if supported, rollback all the objects created thus far. <p/> <pre>Example: <code> <p/> class SomeObject so = null; class CpoAdapter cpo = null; <p/> try { cpo = new CpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false)); } catch (CpoException ce) { // Handle the error cpo = null; } if (cpo!=null) { ArrayList al = new ArrayList(); for (int i=0; i<3; i++){ so = new SomeObject(); so.setId(1); so.setName("SomeName"); al.add(so); } try{ cpo.insertObjects("IdNameInsert",al); } catch (CpoException ce) { // Handle the error } } </code> </pre> @param name The String name of the CREATE Function Group that will be used to create the object in the datasource. null signifies that the default rules will be used. @param coll This is a collection of objects that have been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return The number of objects created in the datasource @throws CpoException Thrown if there are errors accessing the datasource
[ "Iterates", "through", "a", "collection", "of", "Objects", "creates", "and", "stores", "them", "in", "the", "datasource", ".", "The", "assumption", "is", "that", "the", "objects", "contained", "in", "the", "collection", "do", "not", "exist", "in", "the", "da...
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L400-L403
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.writeWordVectors
public static void writeWordVectors(@NonNull Glove vectors, @NonNull String path) { """ This method saves GloVe model to the given output stream. @param vectors GloVe model to be saved @param path path where model should be saved to """ try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path))) { writeWordVectors(vectors, fos); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static void writeWordVectors(@NonNull Glove vectors, @NonNull String path) { try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path))) { writeWordVectors(vectors, fos); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "void", "writeWordVectors", "(", "@", "NonNull", "Glove", "vectors", ",", "@", "NonNull", "String", "path", ")", "{", "try", "(", "BufferedOutputStream", "fos", "=", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "path", ...
This method saves GloVe model to the given output stream. @param vectors GloVe model to be saved @param path path where model should be saved to
[ "This", "method", "saves", "GloVe", "model", "to", "the", "given", "output", "stream", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L1127-L1133
drewnoakes/metadata-extractor
Source/com/drew/metadata/Directory.java
Directory.setObject
@java.lang.SuppressWarnings( { """ Sets a <code>Object</code> for the specified tag. @param tagType the tag's value as an int @param value the value for the specified tag @throws NullPointerException if value is <code>null</code> """ "ConstantConditions", "UnnecessaryBoxing" }) public void setObject(int tagType, @NotNull Object value) { if (value == null) throw new NullPointerException("cannot set a null object"); if (!_tagMap.containsKey(Integer.valueOf(tagType))) { _definedTagList.add(new Tag(tagType, this)); } // else { // final Object oldValue = _tagMap.get(tagType); // if (!oldValue.equals(value)) // addError(String.format("Overwritten tag 0x%s (%s). Old=%s, New=%s", Integer.toHexString(tagType), getTagName(tagType), oldValue, value)); // } _tagMap.put(tagType, value); }
java
@java.lang.SuppressWarnings( { "ConstantConditions", "UnnecessaryBoxing" }) public void setObject(int tagType, @NotNull Object value) { if (value == null) throw new NullPointerException("cannot set a null object"); if (!_tagMap.containsKey(Integer.valueOf(tagType))) { _definedTagList.add(new Tag(tagType, this)); } // else { // final Object oldValue = _tagMap.get(tagType); // if (!oldValue.equals(value)) // addError(String.format("Overwritten tag 0x%s (%s). Old=%s, New=%s", Integer.toHexString(tagType), getTagName(tagType), oldValue, value)); // } _tagMap.put(tagType, value); }
[ "@", "java", ".", "lang", ".", "SuppressWarnings", "(", "{", "\"ConstantConditions\"", ",", "\"UnnecessaryBoxing\"", "}", ")", "public", "void", "setObject", "(", "int", "tagType", ",", "@", "NotNull", "Object", "value", ")", "{", "if", "(", "value", "==", ...
Sets a <code>Object</code> for the specified tag. @param tagType the tag's value as an int @param value the value for the specified tag @throws NullPointerException if value is <code>null</code>
[ "Sets", "a", "<code", ">", "Object<", "/", "code", ">", "for", "the", "specified", "tag", "." ]
train
https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/metadata/Directory.java#L386-L401
opentable/otj-jaxrs
client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java
JaxRsClientFactory.addFeatureToGroup
public synchronized JaxRsClientFactory addFeatureToGroup(JaxRsFeatureGroup group, Feature... features) { """ Register a list of features to all clients marked with the given group. """ Preconditions.checkState(!started, "Already started building clients"); featureMap.putAll(group, Arrays.asList(features)); LOG.trace("Group {} registers features {}", group, features); return this; }
java
public synchronized JaxRsClientFactory addFeatureToGroup(JaxRsFeatureGroup group, Feature... features) { Preconditions.checkState(!started, "Already started building clients"); featureMap.putAll(group, Arrays.asList(features)); LOG.trace("Group {} registers features {}", group, features); return this; }
[ "public", "synchronized", "JaxRsClientFactory", "addFeatureToGroup", "(", "JaxRsFeatureGroup", "group", ",", "Feature", "...", "features", ")", "{", "Preconditions", ".", "checkState", "(", "!", "started", ",", "\"Already started building clients\"", ")", ";", "featureM...
Register a list of features to all clients marked with the given group.
[ "Register", "a", "list", "of", "features", "to", "all", "clients", "marked", "with", "the", "given", "group", "." ]
train
https://github.com/opentable/otj-jaxrs/blob/384e7094fe5a56d41b2a9970bfd783fa85cbbcb8/client/src/main/java/com/opentable/jaxrs/JaxRsClientFactory.java#L141-L146
Mangopay/mangopay2-java-sdk
src/main/java/com/mangopay/core/UrlTool.java
UrlTool.getRestUrl
public String getRestUrl(String urlKey) throws UnsupportedEncodingException { """ Gets REST url. @param urlKey Url key. @return Final REST url. @throws UnsupportedEncodingException """ return getRestUrl(urlKey, true, null, null); }
java
public String getRestUrl(String urlKey) throws UnsupportedEncodingException { return getRestUrl(urlKey, true, null, null); }
[ "public", "String", "getRestUrl", "(", "String", "urlKey", ")", "throws", "UnsupportedEncodingException", "{", "return", "getRestUrl", "(", "urlKey", ",", "true", ",", "null", ",", "null", ")", ";", "}" ]
Gets REST url. @param urlKey Url key. @return Final REST url. @throws UnsupportedEncodingException
[ "Gets", "REST", "url", "." ]
train
https://github.com/Mangopay/mangopay2-java-sdk/blob/037cecb44ea62def63b507817fd9961649151157/src/main/java/com/mangopay/core/UrlTool.java#L46-L48
mygreen/excel-cellformatter
src/main/java/com/github/mygreen/cellformatter/JXLCellFormatter.java
JXLCellFormatter.formatAsString
public String formatAsString(final Cell cell, final Locale locale, final boolean isStartDate1904) { """ ロケールを指定してセルの値をフォーマットし、文字列として取得する @param cell フォーマット対象のセル @param locale フォーマットしたロケール。nullでも可能。 ロケールに依存する場合、指定したロケールにより自動的に切り替わります。 @param isStartDate1904 ファイルの設定が1904年始まりかどうか。 {@link JXLUtils#isDateStart1904(jxl.Sheet)}で値を調べます。 @return フォーマットしたセルの値。 @throws IllegalArgumentException cell is null. """ ArgUtils.notNull(cell, "cell"); return format(cell, locale, isStartDate1904).getText(); }
java
public String formatAsString(final Cell cell, final Locale locale, final boolean isStartDate1904) { ArgUtils.notNull(cell, "cell"); return format(cell, locale, isStartDate1904).getText(); }
[ "public", "String", "formatAsString", "(", "final", "Cell", "cell", ",", "final", "Locale", "locale", ",", "final", "boolean", "isStartDate1904", ")", "{", "ArgUtils", ".", "notNull", "(", "cell", ",", "\"cell\"", ")", ";", "return", "format", "(", "cell", ...
ロケールを指定してセルの値をフォーマットし、文字列として取得する @param cell フォーマット対象のセル @param locale フォーマットしたロケール。nullでも可能。 ロケールに依存する場合、指定したロケールにより自動的に切り替わります。 @param isStartDate1904 ファイルの設定が1904年始まりかどうか。 {@link JXLUtils#isDateStart1904(jxl.Sheet)}で値を調べます。 @return フォーマットしたセルの値。 @throws IllegalArgumentException cell is null.
[ "ロケールを指定してセルの値をフォーマットし、文字列として取得する" ]
train
https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/JXLCellFormatter.java#L108-L113
nmorel/gwt-jackson
gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/AbstractBeanJsonCreator.java
AbstractBeanJsonCreator.buildCommonPropertyParameters
protected final void buildCommonPropertyParameters( CodeBlock.Builder paramBuilder, PropertyInfo property ) { """ Add the common property parameters to the code builder. @param paramBuilder the code builder @param property the information about the property """ if ( property.getFormat().isPresent() ) { JsonFormat format = property.getFormat().get(); if ( !Strings.isNullOrEmpty( format.pattern() ) ) { paramBuilder.add( "\n.setPattern($S)", format.pattern() ); } paramBuilder.add( "\n.setShape($T.$L)", Shape.class, format.shape().name() ); if ( !Strings.isNullOrEmpty( format.locale() ) && !JsonFormat.DEFAULT_LOCALE.equals( format.locale() ) ) { logger.log( Type.WARN, "JsonFormat.locale is not supported by default" ); paramBuilder.add( "\n.setLocale($S)", format.locale() ); } } if ( property.getIgnoredProperties().isPresent() ) { for ( String ignoredProperty : property.getIgnoredProperties().get() ) { paramBuilder.add( "\n.addIgnoredProperty($S)", ignoredProperty ); } } }
java
protected final void buildCommonPropertyParameters( CodeBlock.Builder paramBuilder, PropertyInfo property ) { if ( property.getFormat().isPresent() ) { JsonFormat format = property.getFormat().get(); if ( !Strings.isNullOrEmpty( format.pattern() ) ) { paramBuilder.add( "\n.setPattern($S)", format.pattern() ); } paramBuilder.add( "\n.setShape($T.$L)", Shape.class, format.shape().name() ); if ( !Strings.isNullOrEmpty( format.locale() ) && !JsonFormat.DEFAULT_LOCALE.equals( format.locale() ) ) { logger.log( Type.WARN, "JsonFormat.locale is not supported by default" ); paramBuilder.add( "\n.setLocale($S)", format.locale() ); } } if ( property.getIgnoredProperties().isPresent() ) { for ( String ignoredProperty : property.getIgnoredProperties().get() ) { paramBuilder.add( "\n.addIgnoredProperty($S)", ignoredProperty ); } } }
[ "protected", "final", "void", "buildCommonPropertyParameters", "(", "CodeBlock", ".", "Builder", "paramBuilder", ",", "PropertyInfo", "property", ")", "{", "if", "(", "property", ".", "getFormat", "(", ")", ".", "isPresent", "(", ")", ")", "{", "JsonFormat", "...
Add the common property parameters to the code builder. @param paramBuilder the code builder @param property the information about the property
[ "Add", "the", "common", "property", "parameters", "to", "the", "code", "builder", "." ]
train
https://github.com/nmorel/gwt-jackson/blob/3fdc4350a27a9b64fc437d5fe516bf9191b74824/gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/rebind/AbstractBeanJsonCreator.java#L284-L305
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_network_private_POST
public OvhNetwork project_serviceName_network_private_POST(String serviceName, String name, String[] regions, Long vlanId) throws IOException { """ Create a new network REST: POST /cloud/project/{serviceName}/network/private @param name [required] Network name @param regions [required] Region where to activate private network. No parameters means all region @param serviceName [required] Project name @param vlanId [required] Vland id, between 0 and 4000. 0 value means no vlan. """ String qPath = "/cloud/project/{serviceName}/network/private"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "name", name); addBody(o, "regions", regions); addBody(o, "vlanId", vlanId); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhNetwork.class); }
java
public OvhNetwork project_serviceName_network_private_POST(String serviceName, String name, String[] regions, Long vlanId) throws IOException { String qPath = "/cloud/project/{serviceName}/network/private"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "name", name); addBody(o, "regions", regions); addBody(o, "vlanId", vlanId); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhNetwork.class); }
[ "public", "OvhNetwork", "project_serviceName_network_private_POST", "(", "String", "serviceName", ",", "String", "name", ",", "String", "[", "]", "regions", ",", "Long", "vlanId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceNam...
Create a new network REST: POST /cloud/project/{serviceName}/network/private @param name [required] Network name @param regions [required] Region where to activate private network. No parameters means all region @param serviceName [required] Project name @param vlanId [required] Vland id, between 0 and 4000. 0 value means no vlan.
[ "Create", "a", "new", "network" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L844-L853
joniles/mpxj
src/main/java/net/sf/mpxj/Task.java
Task.setDate
public void setDate(int index, Date value) { """ Set a date value. @param index date index (1-10) @param value date value """ set(selectField(TaskFieldLists.CUSTOM_DATE, index), value); }
java
public void setDate(int index, Date value) { set(selectField(TaskFieldLists.CUSTOM_DATE, index), value); }
[ "public", "void", "setDate", "(", "int", "index", ",", "Date", "value", ")", "{", "set", "(", "selectField", "(", "TaskFieldLists", ".", "CUSTOM_DATE", ",", "index", ")", ",", "value", ")", ";", "}" ]
Set a date value. @param index date index (1-10) @param value date value
[ "Set", "a", "date", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L3301-L3304
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/FileUtils.java
FileUtils.toElement
public static Element toElement(final String aFilePath, final String aPattern) throws FileNotFoundException, ParserConfigurationException { """ Returns an XML Element representing the file structure found at the supplied file system path. Files included in the representation will match the supplied regular expression pattern. This method doesn't descend through the directory structure. @param aFilePath The directory from which the structural representation should be built @param aPattern A regular expression pattern which files included in the Element should match @return An XML Element representation of the directory structure @throws FileNotFoundException If the supplied directory isn't found @throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly """ return toElement(aFilePath, aPattern, false); }
java
public static Element toElement(final String aFilePath, final String aPattern) throws FileNotFoundException, ParserConfigurationException { return toElement(aFilePath, aPattern, false); }
[ "public", "static", "Element", "toElement", "(", "final", "String", "aFilePath", ",", "final", "String", "aPattern", ")", "throws", "FileNotFoundException", ",", "ParserConfigurationException", "{", "return", "toElement", "(", "aFilePath", ",", "aPattern", ",", "fal...
Returns an XML Element representing the file structure found at the supplied file system path. Files included in the representation will match the supplied regular expression pattern. This method doesn't descend through the directory structure. @param aFilePath The directory from which the structural representation should be built @param aPattern A regular expression pattern which files included in the Element should match @return An XML Element representation of the directory structure @throws FileNotFoundException If the supplied directory isn't found @throws ParserConfigurationException If the default XML parser for the JRE isn't configured correctly
[ "Returns", "an", "XML", "Element", "representing", "the", "file", "structure", "found", "at", "the", "supplied", "file", "system", "path", ".", "Files", "included", "in", "the", "representation", "will", "match", "the", "supplied", "regular", "expression", "patt...
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/FileUtils.java#L254-L257
apache/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java
SqlDateTimeUtils.unixTimestamp
public static long unixTimestamp(String dateStr, String format, TimeZone tz) { """ Returns the value of the argument as an unsigned integer in seconds since '1970-01-01 00:00:00' UTC. """ long ts = parseToTimeMillis(dateStr, format, tz); if (ts == Long.MIN_VALUE) { return Long.MIN_VALUE; } else { // return the seconds return ts / 1000; } }
java
public static long unixTimestamp(String dateStr, String format, TimeZone tz) { long ts = parseToTimeMillis(dateStr, format, tz); if (ts == Long.MIN_VALUE) { return Long.MIN_VALUE; } else { // return the seconds return ts / 1000; } }
[ "public", "static", "long", "unixTimestamp", "(", "String", "dateStr", ",", "String", "format", ",", "TimeZone", "tz", ")", "{", "long", "ts", "=", "parseToTimeMillis", "(", "dateStr", ",", "format", ",", "tz", ")", ";", "if", "(", "ts", "==", "Long", ...
Returns the value of the argument as an unsigned integer in seconds since '1970-01-01 00:00:00' UTC.
[ "Returns", "the", "value", "of", "the", "argument", "as", "an", "unsigned", "integer", "in", "seconds", "since", "1970", "-", "01", "-", "01", "00", ":", "00", ":", "00", "UTC", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlDateTimeUtils.java#L889-L897
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java
DefaultImageFormatChecker.isJpegHeader
private static boolean isJpegHeader(final byte[] imageHeaderBytes, final int headerSize) { """ Checks if imageHeaderBytes starts with SOI (start of image) marker, followed by 0xFF. If headerSize is lower than 3 false is returned. Description of jpeg format can be found here: <a href="http://www.w3.org/Graphics/JPEG/itu-t81.pdf"> http://www.w3.org/Graphics/JPEG/itu-t81.pdf</a> Annex B deals with compressed data format @param imageHeaderBytes @param headerSize @return true if imageHeaderBytes starts with SOI_BYTES and headerSize >= 3 """ return headerSize >= JPEG_HEADER.length && ImageFormatCheckerUtils.startsWithPattern(imageHeaderBytes, JPEG_HEADER); }
java
private static boolean isJpegHeader(final byte[] imageHeaderBytes, final int headerSize) { return headerSize >= JPEG_HEADER.length && ImageFormatCheckerUtils.startsWithPattern(imageHeaderBytes, JPEG_HEADER); }
[ "private", "static", "boolean", "isJpegHeader", "(", "final", "byte", "[", "]", "imageHeaderBytes", ",", "final", "int", "headerSize", ")", "{", "return", "headerSize", ">=", "JPEG_HEADER", ".", "length", "&&", "ImageFormatCheckerUtils", ".", "startsWithPattern", ...
Checks if imageHeaderBytes starts with SOI (start of image) marker, followed by 0xFF. If headerSize is lower than 3 false is returned. Description of jpeg format can be found here: <a href="http://www.w3.org/Graphics/JPEG/itu-t81.pdf"> http://www.w3.org/Graphics/JPEG/itu-t81.pdf</a> Annex B deals with compressed data format @param imageHeaderBytes @param headerSize @return true if imageHeaderBytes starts with SOI_BYTES and headerSize >= 3
[ "Checks", "if", "imageHeaderBytes", "starts", "with", "SOI", "(", "start", "of", "image", ")", "marker", "followed", "by", "0xFF", ".", "If", "headerSize", "is", "lower", "than", "3", "false", "is", "returned", ".", "Description", "of", "jpeg", "format", "...
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imageformat/DefaultImageFormatChecker.java#L145-L148
jbossws/jbossws-cxf
modules/server/src/main/java/org/jboss/wsf/stack/cxf/addressRewrite/SoapAddressRewriteHelper.java
SoapAddressRewriteHelper.rewriteSoapAddress
private static String rewriteSoapAddress(SOAPAddressRewriteMetadata sarm, String origAddress, String newAddress, String uriScheme) { """ Rewrite the provided address according to the current server configuration and always using the specified uriScheme. @param sarm The deployment SOAPAddressRewriteMetadata @param origAddress The source address @param newAddress The new (candidate) address @param uriScheme The uriScheme to use for rewrite @return The obtained address """ try { URL url = new URL(newAddress); String path = url.getPath(); String host = sarm.getWebServiceHost(); String port = getDotPortNumber(uriScheme, sarm); StringBuilder sb = new StringBuilder(uriScheme); sb.append("://"); sb.append(host); sb.append(port); if (isPathRewriteRequired(sarm)) { sb.append(SEDProcessor.newInstance(sarm.getWebServicePathRewriteRule()).processLine(path)); } else { sb.append(path); } final String urlStr = sb.toString(); ADDRESS_REWRITE_LOGGER.addressRewritten(origAddress, urlStr); return urlStr; } catch (MalformedURLException e) { ADDRESS_REWRITE_LOGGER.invalidAddressProvidedUseItWithoutRewriting(newAddress, origAddress); return origAddress; } }
java
private static String rewriteSoapAddress(SOAPAddressRewriteMetadata sarm, String origAddress, String newAddress, String uriScheme) { try { URL url = new URL(newAddress); String path = url.getPath(); String host = sarm.getWebServiceHost(); String port = getDotPortNumber(uriScheme, sarm); StringBuilder sb = new StringBuilder(uriScheme); sb.append("://"); sb.append(host); sb.append(port); if (isPathRewriteRequired(sarm)) { sb.append(SEDProcessor.newInstance(sarm.getWebServicePathRewriteRule()).processLine(path)); } else { sb.append(path); } final String urlStr = sb.toString(); ADDRESS_REWRITE_LOGGER.addressRewritten(origAddress, urlStr); return urlStr; } catch (MalformedURLException e) { ADDRESS_REWRITE_LOGGER.invalidAddressProvidedUseItWithoutRewriting(newAddress, origAddress); return origAddress; } }
[ "private", "static", "String", "rewriteSoapAddress", "(", "SOAPAddressRewriteMetadata", "sarm", ",", "String", "origAddress", ",", "String", "newAddress", ",", "String", "uriScheme", ")", "{", "try", "{", "URL", "url", "=", "new", "URL", "(", "newAddress", ")", ...
Rewrite the provided address according to the current server configuration and always using the specified uriScheme. @param sarm The deployment SOAPAddressRewriteMetadata @param origAddress The source address @param newAddress The new (candidate) address @param uriScheme The uriScheme to use for rewrite @return The obtained address
[ "Rewrite", "the", "provided", "address", "according", "to", "the", "current", "server", "configuration", "and", "always", "using", "the", "specified", "uriScheme", "." ]
train
https://github.com/jbossws/jbossws-cxf/blob/e1d5df3664cbc2482ebc83cafd355a4d60d12150/modules/server/src/main/java/org/jboss/wsf/stack/cxf/addressRewrite/SoapAddressRewriteHelper.java#L173-L204
paymill/paymill-java
src/main/java/com/paymill/services/SubscriptionService.java
SubscriptionService.changeAmount
public Subscription changeAmount( Subscription subscription, Integer amount, String currency, Interval.PeriodWithChargeDay interval ) { """ Changes the amount of a subscription.<br> <br> The new amount is valid until the end of the subscription. If you want to set a temporary one-time amount use {@link SubscriptionService#changeAmountTemporary(String, Integer)} @param subscription the subscription. @param amount the new amount. @param currency optionally, a new currency or <code>null</code>. @param interval optionally, a new interval or <code>null</code>. @return the updated subscription. """ return changeAmount( subscription, amount, 1, currency, interval ); }
java
public Subscription changeAmount( Subscription subscription, Integer amount, String currency, Interval.PeriodWithChargeDay interval ) { return changeAmount( subscription, amount, 1, currency, interval ); }
[ "public", "Subscription", "changeAmount", "(", "Subscription", "subscription", ",", "Integer", "amount", ",", "String", "currency", ",", "Interval", ".", "PeriodWithChargeDay", "interval", ")", "{", "return", "changeAmount", "(", "subscription", ",", "amount", ",", ...
Changes the amount of a subscription.<br> <br> The new amount is valid until the end of the subscription. If you want to set a temporary one-time amount use {@link SubscriptionService#changeAmountTemporary(String, Integer)} @param subscription the subscription. @param amount the new amount. @param currency optionally, a new currency or <code>null</code>. @param interval optionally, a new interval or <code>null</code>. @return the updated subscription.
[ "Changes", "the", "amount", "of", "a", "subscription", ".", "<br", ">", "<br", ">", "The", "new", "amount", "is", "valid", "until", "the", "end", "of", "the", "subscription", ".", "If", "you", "want", "to", "set", "a", "temporary", "one", "-", "time", ...
train
https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/SubscriptionService.java#L339-L341
apereo/cas
support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/authenticator/OAuth20CasAuthenticationBuilder.java
OAuth20CasAuthenticationBuilder.build
public Authentication build(final UserProfile profile, final OAuthRegisteredService registeredService, final J2EContext context, final Service service) { """ Create an authentication from a user profile. @param profile the given user profile @param registeredService the registered service @param context the context @param service the service @return the built authentication """ val profileAttributes = CoreAuthenticationUtils.convertAttributeValuesToMultiValuedObjects(profile.getAttributes()); val newPrincipal = this.principalFactory.createPrincipal(profile.getId(), profileAttributes); LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService); val authenticator = profile.getClass().getCanonicalName(); val metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId())); val handlerResult = new DefaultAuthenticationHandlerExecutionResult(authenticator, metadata, newPrincipal, new ArrayList<>()); val scopes = CollectionUtils.toCollection(context.getRequest().getParameterValues(OAuth20Constants.SCOPE)); val state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.STATE), StringUtils.EMPTY); val nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.NONCE), StringUtils.EMPTY); LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuth20Constants.STATE, state, OAuth20Constants.NONCE, nonce); /* * pac4j UserProfile.getPermissions() and getRoles() returns UnmodifiableSet which Jackson Serializer * happily serializes to json but is unable to deserialize. * We have to transform those to HashSet to avoid such a problem */ return DefaultAuthenticationBuilder.newInstance() .addAttribute("permissions", new LinkedHashSet<>(profile.getPermissions())) .addAttribute("roles", new LinkedHashSet<>(profile.getRoles())) .addAttribute("scopes", scopes) .addAttribute(OAuth20Constants.STATE, state) .addAttribute(OAuth20Constants.NONCE, nonce) .addAttribute(OAuth20Constants.CLIENT_ID, registeredService.getClientId()) .addCredential(metadata) .setPrincipal(newPrincipal) .setAuthenticationDate(ZonedDateTime.now(ZoneOffset.UTC)) .addSuccess(profile.getClass().getCanonicalName(), handlerResult) .build(); }
java
public Authentication build(final UserProfile profile, final OAuthRegisteredService registeredService, final J2EContext context, final Service service) { val profileAttributes = CoreAuthenticationUtils.convertAttributeValuesToMultiValuedObjects(profile.getAttributes()); val newPrincipal = this.principalFactory.createPrincipal(profile.getId(), profileAttributes); LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService); val authenticator = profile.getClass().getCanonicalName(); val metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId())); val handlerResult = new DefaultAuthenticationHandlerExecutionResult(authenticator, metadata, newPrincipal, new ArrayList<>()); val scopes = CollectionUtils.toCollection(context.getRequest().getParameterValues(OAuth20Constants.SCOPE)); val state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.STATE), StringUtils.EMPTY); val nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.NONCE), StringUtils.EMPTY); LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuth20Constants.STATE, state, OAuth20Constants.NONCE, nonce); /* * pac4j UserProfile.getPermissions() and getRoles() returns UnmodifiableSet which Jackson Serializer * happily serializes to json but is unable to deserialize. * We have to transform those to HashSet to avoid such a problem */ return DefaultAuthenticationBuilder.newInstance() .addAttribute("permissions", new LinkedHashSet<>(profile.getPermissions())) .addAttribute("roles", new LinkedHashSet<>(profile.getRoles())) .addAttribute("scopes", scopes) .addAttribute(OAuth20Constants.STATE, state) .addAttribute(OAuth20Constants.NONCE, nonce) .addAttribute(OAuth20Constants.CLIENT_ID, registeredService.getClientId()) .addCredential(metadata) .setPrincipal(newPrincipal) .setAuthenticationDate(ZonedDateTime.now(ZoneOffset.UTC)) .addSuccess(profile.getClass().getCanonicalName(), handlerResult) .build(); }
[ "public", "Authentication", "build", "(", "final", "UserProfile", "profile", ",", "final", "OAuthRegisteredService", "registeredService", ",", "final", "J2EContext", "context", ",", "final", "Service", "service", ")", "{", "val", "profileAttributes", "=", "CoreAuthent...
Create an authentication from a user profile. @param profile the given user profile @param registeredService the registered service @param context the context @param service the service @return the built authentication
[ "Create", "an", "authentication", "from", "a", "user", "profile", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/authenticator/OAuth20CasAuthenticationBuilder.java#L91-L126
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java
TaskOperations.getTask
public CloudTask getTask(String jobId, String taskId, DetailLevel detailLevel) throws BatchErrorException, IOException { """ Gets the specified {@link CloudTask}. @param jobId The ID of the job containing the task. @param taskId The ID of the task. @param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service. @return A {@link CloudTask} containing information about the specified Azure Batch task. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service. """ return getTask(jobId, taskId, detailLevel, null); }
java
public CloudTask getTask(String jobId, String taskId, DetailLevel detailLevel) throws BatchErrorException, IOException { return getTask(jobId, taskId, detailLevel, null); }
[ "public", "CloudTask", "getTask", "(", "String", "jobId", ",", "String", "taskId", ",", "DetailLevel", "detailLevel", ")", "throws", "BatchErrorException", ",", "IOException", "{", "return", "getTask", "(", "jobId", ",", "taskId", ",", "detailLevel", ",", "null"...
Gets the specified {@link CloudTask}. @param jobId The ID of the job containing the task. @param taskId The ID of the task. @param detailLevel A {@link DetailLevel} used for controlling which properties are retrieved from the service. @return A {@link CloudTask} containing information about the specified Azure Batch task. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Gets", "the", "specified", "{", "@link", "CloudTask", "}", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/TaskOperations.java#L623-L626
VoltDB/voltdb
src/frontend/org/voltdb/utils/MiscUtils.java
MiscUtils.writeDeferredSerialization
public static int writeDeferredSerialization(ByteBuffer mbuf, DeferredSerialization ds) throws IOException { """ Serialize the deferred serializer data into byte buffer @param mbuf ByteBuffer the buffer is written to @param ds DeferredSerialization data writes to the byte buffer @return size of data @throws IOException """ int written = 0; try { final int objStartPosition = mbuf.position(); ds.serialize(mbuf); written = mbuf.position() - objStartPosition; } finally { ds.cancel(); } return written; }
java
public static int writeDeferredSerialization(ByteBuffer mbuf, DeferredSerialization ds) throws IOException { int written = 0; try { final int objStartPosition = mbuf.position(); ds.serialize(mbuf); written = mbuf.position() - objStartPosition; } finally { ds.cancel(); } return written; }
[ "public", "static", "int", "writeDeferredSerialization", "(", "ByteBuffer", "mbuf", ",", "DeferredSerialization", "ds", ")", "throws", "IOException", "{", "int", "written", "=", "0", ";", "try", "{", "final", "int", "objStartPosition", "=", "mbuf", ".", "positio...
Serialize the deferred serializer data into byte buffer @param mbuf ByteBuffer the buffer is written to @param ds DeferredSerialization data writes to the byte buffer @return size of data @throws IOException
[ "Serialize", "the", "deferred", "serializer", "data", "into", "byte", "buffer" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/MiscUtils.java#L1055-L1066
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/util/ClassLoaderUtils.java
ClassLoaderUtils.isKnownClassLoaderAccessibleFrom
private static boolean isKnownClassLoaderAccessibleFrom(final ClassLoader accessibleCL, final ClassLoader fromCL) { """ /* This method determines whether it is known that a this class loader is a a child of another one, or equal to it. The "known" part is because SecurityManager could be preventing us from knowing such information. """ if (fromCL == null) { return false; } ClassLoader parent = fromCL; try { while (parent != null && parent != accessibleCL) { parent = parent.getParent(); } return (parent != null && parent == accessibleCL); } catch (final SecurityException se) { // The SecurityManager prevents us from accessing, so just ignore it return false; } }
java
private static boolean isKnownClassLoaderAccessibleFrom(final ClassLoader accessibleCL, final ClassLoader fromCL) { if (fromCL == null) { return false; } ClassLoader parent = fromCL; try { while (parent != null && parent != accessibleCL) { parent = parent.getParent(); } return (parent != null && parent == accessibleCL); } catch (final SecurityException se) { // The SecurityManager prevents us from accessing, so just ignore it return false; } }
[ "private", "static", "boolean", "isKnownClassLoaderAccessibleFrom", "(", "final", "ClassLoader", "accessibleCL", ",", "final", "ClassLoader", "fromCL", ")", "{", "if", "(", "fromCL", "==", "null", ")", "{", "return", "false", ";", "}", "ClassLoader", "parent", "...
/* This method determines whether it is known that a this class loader is a a child of another one, or equal to it. The "known" part is because SecurityManager could be preventing us from knowing such information.
[ "/", "*", "This", "method", "determines", "whether", "it", "is", "known", "that", "a", "this", "class", "loader", "is", "a", "a", "child", "of", "another", "one", "or", "equal", "to", "it", ".", "The", "known", "part", "is", "because", "SecurityManager",...
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/util/ClassLoaderUtils.java#L446-L467
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.getAttributeIntWithDefault
@Pure public static Integer getAttributeIntWithDefault(Node document, boolean caseSensitive, Integer defaultValue, String... path) { """ Replies the integer value that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. @param document is the XML document to explore. @param caseSensitive indicates of the {@code path}'s components are case sensitive. @param defaultValue is the default value to reply. @param path is the list of and ended by the attribute's name. @return the integer value of the specified attribute or <code>null</code> if it was node found in the document """ assert document != null : AssertMessages.notNullParameter(0); final String v = getAttributeValue(document, caseSensitive, 0, path); if (v != null) { try { return Integer.parseInt(v); } catch (NumberFormatException e) { // } } return defaultValue; }
java
@Pure public static Integer getAttributeIntWithDefault(Node document, boolean caseSensitive, Integer defaultValue, String... path) { assert document != null : AssertMessages.notNullParameter(0); final String v = getAttributeValue(document, caseSensitive, 0, path); if (v != null) { try { return Integer.parseInt(v); } catch (NumberFormatException e) { // } } return defaultValue; }
[ "@", "Pure", "public", "static", "Integer", "getAttributeIntWithDefault", "(", "Node", "document", ",", "boolean", "caseSensitive", ",", "Integer", "defaultValue", ",", "String", "...", "path", ")", "{", "assert", "document", "!=", "null", ":", "AssertMessages", ...
Replies the integer value that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. @param document is the XML document to explore. @param caseSensitive indicates of the {@code path}'s components are case sensitive. @param defaultValue is the default value to reply. @param path is the list of and ended by the attribute's name. @return the integer value of the specified attribute or <code>null</code> if it was node found in the document
[ "Replies", "the", "integer", "value", "that", "corresponds", "to", "the", "specified", "attribute", "s", "path", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L845-L857
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java
ICUBinary.compareKeys
static int compareKeys(CharSequence key, ByteBuffer bytes, int offset) { """ Compares the length-specified input key with the NUL-terminated table key. (ASCII) """ for (int i = 0;; ++i, ++offset) { int c2 = bytes.get(offset); if (c2 == 0) { if (i == key.length()) { return 0; } else { return 1; // key > table key because key is longer. } } else if (i == key.length()) { return -1; // key < table key because key is shorter. } int diff = key.charAt(i) - c2; if (diff != 0) { return diff; } } }
java
static int compareKeys(CharSequence key, ByteBuffer bytes, int offset) { for (int i = 0;; ++i, ++offset) { int c2 = bytes.get(offset); if (c2 == 0) { if (i == key.length()) { return 0; } else { return 1; // key > table key because key is longer. } } else if (i == key.length()) { return -1; // key < table key because key is shorter. } int diff = key.charAt(i) - c2; if (diff != 0) { return diff; } } }
[ "static", "int", "compareKeys", "(", "CharSequence", "key", ",", "ByteBuffer", "bytes", ",", "int", "offset", ")", "{", "for", "(", "int", "i", "=", "0", ";", ";", "++", "i", ",", "++", "offset", ")", "{", "int", "c2", "=", "bytes", ".", "get", "...
Compares the length-specified input key with the NUL-terminated table key. (ASCII)
[ "Compares", "the", "length", "-", "specified", "input", "key", "with", "the", "NUL", "-", "terminated", "table", "key", ".", "(", "ASCII", ")" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUBinary.java#L362-L379
alkacon/opencms-core
src/org/opencms/db/generic/CmsProjectDriver.java
CmsProjectDriver.internalResetResourceState
protected void internalResetResourceState(CmsDbContext dbc, CmsResource resource) throws CmsDataAccessException { """ Resets the state to UNCHANGED for a specified resource.<p> @param dbc the current database context @param resource the Cms resource @throws CmsDataAccessException if something goes wrong """ try { // reset the resource state resource.setState(CmsResource.STATE_UNCHANGED); m_driverManager.getVfsDriver(dbc).writeResourceState( dbc, dbc.currentProject(), resource, CmsDriverManager.UPDATE_ALL, true); } catch (CmsDataAccessException e) { if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.LOG_ERROR_RESETTING_RESOURCE_STATE_1, resource.getRootPath()), e); } throw e; } }
java
protected void internalResetResourceState(CmsDbContext dbc, CmsResource resource) throws CmsDataAccessException { try { // reset the resource state resource.setState(CmsResource.STATE_UNCHANGED); m_driverManager.getVfsDriver(dbc).writeResourceState( dbc, dbc.currentProject(), resource, CmsDriverManager.UPDATE_ALL, true); } catch (CmsDataAccessException e) { if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.LOG_ERROR_RESETTING_RESOURCE_STATE_1, resource.getRootPath()), e); } throw e; } }
[ "protected", "void", "internalResetResourceState", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ")", "throws", "CmsDataAccessException", "{", "try", "{", "// reset the resource state", "resource", ".", "setState", "(", "CmsResource", ".", "STATE_UNCHANGED",...
Resets the state to UNCHANGED for a specified resource.<p> @param dbc the current database context @param resource the Cms resource @throws CmsDataAccessException if something goes wrong
[ "Resets", "the", "state", "to", "UNCHANGED", "for", "a", "specified", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsProjectDriver.java#L3182-L3203
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/GraphitePickleWriter.java
GraphitePickleWriter.start
@Override public void start() { """ Load settings, initialize the {@link SocketWriter} pool and test the connection to the graphite server. a {@link Logger#warn(String)} message is emitted if the connection to the graphite server fails. """ int port = getIntSetting(SETTING_PORT, DEFAULT_GRAPHITE_SERVER_PORT); String host = getStringSetting(SETTING_HOST); graphiteServerHostAndPort = new HostAndPort(host, port); logger.info("Start Graphite Pickle writer connected to '{}'...", graphiteServerHostAndPort); metricPathPrefix = getStringSetting(SETTING_NAME_PREFIX, DEFAULT_NAME_PREFIX); metricPathPrefix = getStrategy().resolveExpression(metricPathPrefix); if (!metricPathPrefix.isEmpty() && !metricPathPrefix.endsWith(".")) { metricPathPrefix = metricPathPrefix + "."; } GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); config.setTestOnBorrow(getBooleanSetting("pool.testOnBorrow", true)); config.setTestWhileIdle(getBooleanSetting("pool.testWhileIdle", true)); config.setMaxTotal(getIntSetting("pool.maxActive", -1)); config.setMaxIdlePerKey(getIntSetting("pool.maxIdle", -1)); config.setMinEvictableIdleTimeMillis(getLongSetting("pool.minEvictableIdleTimeMillis", TimeUnit.MINUTES.toMillis(5))); config.setTimeBetweenEvictionRunsMillis(getLongSetting("pool.timeBetweenEvictionRunsMillis", TimeUnit.MINUTES.toMillis(5))); config.setJmxNameBase("org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=GraphitePickleWriter,name="); config.setJmxNamePrefix(graphiteServerHostAndPort.getHost() + "_" + graphiteServerHostAndPort.getPort()); int socketConnectTimeoutInMillis = getIntSetting("graphite.socketConnectTimeoutInMillis", SocketOutputStreamPoolFactory.DEFAULT_SOCKET_CONNECT_TIMEOUT_IN_MILLIS); socketOutputStreamPool = new GenericKeyedObjectPool<HostAndPort, SocketOutputStream>(new SocketOutputStreamPoolFactory(socketConnectTimeoutInMillis), config); if (isEnabled()) { try { SocketOutputStream socketOutputStream = socketOutputStreamPool.borrowObject(graphiteServerHostAndPort); socketOutputStreamPool.returnObject(graphiteServerHostAndPort, socketOutputStream); } catch (Exception e) { logger.warn("Test Connection: FAILURE to connect to Graphite server '{}'", graphiteServerHostAndPort, e); } } try { Class.forName("org.python.modules.cPickle"); } catch (ClassNotFoundException e) { throw new EmbeddedJmxTransException("jython librarie is required by the " + getClass().getSimpleName() + " but is not found in the classpath. Please add org.python:jython:2.5.3+ to the classpath."); } }
java
@Override public void start() { int port = getIntSetting(SETTING_PORT, DEFAULT_GRAPHITE_SERVER_PORT); String host = getStringSetting(SETTING_HOST); graphiteServerHostAndPort = new HostAndPort(host, port); logger.info("Start Graphite Pickle writer connected to '{}'...", graphiteServerHostAndPort); metricPathPrefix = getStringSetting(SETTING_NAME_PREFIX, DEFAULT_NAME_PREFIX); metricPathPrefix = getStrategy().resolveExpression(metricPathPrefix); if (!metricPathPrefix.isEmpty() && !metricPathPrefix.endsWith(".")) { metricPathPrefix = metricPathPrefix + "."; } GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig(); config.setTestOnBorrow(getBooleanSetting("pool.testOnBorrow", true)); config.setTestWhileIdle(getBooleanSetting("pool.testWhileIdle", true)); config.setMaxTotal(getIntSetting("pool.maxActive", -1)); config.setMaxIdlePerKey(getIntSetting("pool.maxIdle", -1)); config.setMinEvictableIdleTimeMillis(getLongSetting("pool.minEvictableIdleTimeMillis", TimeUnit.MINUTES.toMillis(5))); config.setTimeBetweenEvictionRunsMillis(getLongSetting("pool.timeBetweenEvictionRunsMillis", TimeUnit.MINUTES.toMillis(5))); config.setJmxNameBase("org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=GraphitePickleWriter,name="); config.setJmxNamePrefix(graphiteServerHostAndPort.getHost() + "_" + graphiteServerHostAndPort.getPort()); int socketConnectTimeoutInMillis = getIntSetting("graphite.socketConnectTimeoutInMillis", SocketOutputStreamPoolFactory.DEFAULT_SOCKET_CONNECT_TIMEOUT_IN_MILLIS); socketOutputStreamPool = new GenericKeyedObjectPool<HostAndPort, SocketOutputStream>(new SocketOutputStreamPoolFactory(socketConnectTimeoutInMillis), config); if (isEnabled()) { try { SocketOutputStream socketOutputStream = socketOutputStreamPool.borrowObject(graphiteServerHostAndPort); socketOutputStreamPool.returnObject(graphiteServerHostAndPort, socketOutputStream); } catch (Exception e) { logger.warn("Test Connection: FAILURE to connect to Graphite server '{}'", graphiteServerHostAndPort, e); } } try { Class.forName("org.python.modules.cPickle"); } catch (ClassNotFoundException e) { throw new EmbeddedJmxTransException("jython librarie is required by the " + getClass().getSimpleName() + " but is not found in the classpath. Please add org.python:jython:2.5.3+ to the classpath."); } }
[ "@", "Override", "public", "void", "start", "(", ")", "{", "int", "port", "=", "getIntSetting", "(", "SETTING_PORT", ",", "DEFAULT_GRAPHITE_SERVER_PORT", ")", ";", "String", "host", "=", "getStringSetting", "(", "SETTING_HOST", ")", ";", "graphiteServerHostAndPort...
Load settings, initialize the {@link SocketWriter} pool and test the connection to the graphite server. a {@link Logger#warn(String)} message is emitted if the connection to the graphite server fails.
[ "Load", "settings", "initialize", "the", "{", "@link", "SocketWriter", "}", "pool", "and", "test", "the", "connection", "to", "the", "graphite", "server", "." ]
train
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/GraphitePickleWriter.java#L81-L123
alkacon/opencms-core
src/org/opencms/search/CmsSearchIndex.java
CmsSearchIndex.hasReadPermission
protected boolean hasReadPermission(CmsObject cms, I_CmsSearchDocument doc) { """ Checks if the OpenCms resource referenced by the result document can be read be the user of the given OpenCms context.<p> @param cms the OpenCms user context to use for permission testing @param doc the search result document to check @return <code>true</code> if the user has read permissions to the resource """ // If no permission check is needed: the document can be read // Else try to read the resource if this is not possible the user does not have enough permissions return !needsPermissionCheck(doc) ? true : (null != getResource(cms, doc)); }
java
protected boolean hasReadPermission(CmsObject cms, I_CmsSearchDocument doc) { // If no permission check is needed: the document can be read // Else try to read the resource if this is not possible the user does not have enough permissions return !needsPermissionCheck(doc) ? true : (null != getResource(cms, doc)); }
[ "protected", "boolean", "hasReadPermission", "(", "CmsObject", "cms", ",", "I_CmsSearchDocument", "doc", ")", "{", "// If no permission check is needed: the document can be read", "// Else try to read the resource if this is not possible the user does not have enough permissions", "return"...
Checks if the OpenCms resource referenced by the result document can be read be the user of the given OpenCms context.<p> @param cms the OpenCms user context to use for permission testing @param doc the search result document to check @return <code>true</code> if the user has read permissions to the resource
[ "Checks", "if", "the", "OpenCms", "resource", "referenced", "by", "the", "result", "document", "can", "be", "read", "be", "the", "user", "of", "the", "given", "OpenCms", "context", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchIndex.java#L1758-L1763
dadoonet/elasticsearch-beyonder
src/main/java/fr/pilato/elasticsearch/tools/index/IndexElasticsearchUpdater.java
IndexElasticsearchUpdater.updateIndexWithSettingsInElasticsearch
private static void updateIndexWithSettingsInElasticsearch(RestClient client, String index, String settings) throws Exception { """ Update settings in Elasticsearch @param client Elasticsearch client @param index Index name @param settings Settings if any, null if no update settings @throws Exception if the elasticsearch API call is failing """ logger.trace("updateIndex([{}])", index); assert client != null; assert index != null; if (settings != null) { logger.trace("Found update settings for index [{}]: [{}]", index, settings); logger.debug("updating settings for index [{}]", index); Request request = new Request("PUT", "/" + index + "/_settings"); request.setJsonEntity(settings); client.performRequest(request); } logger.trace("/updateIndex([{}])", index); }
java
private static void updateIndexWithSettingsInElasticsearch(RestClient client, String index, String settings) throws Exception { logger.trace("updateIndex([{}])", index); assert client != null; assert index != null; if (settings != null) { logger.trace("Found update settings for index [{}]: [{}]", index, settings); logger.debug("updating settings for index [{}]", index); Request request = new Request("PUT", "/" + index + "/_settings"); request.setJsonEntity(settings); client.performRequest(request); } logger.trace("/updateIndex([{}])", index); }
[ "private", "static", "void", "updateIndexWithSettingsInElasticsearch", "(", "RestClient", "client", ",", "String", "index", ",", "String", "settings", ")", "throws", "Exception", "{", "logger", ".", "trace", "(", "\"updateIndex([{}])\"", ",", "index", ")", ";", "a...
Update settings in Elasticsearch @param client Elasticsearch client @param index Index name @param settings Settings if any, null if no update settings @throws Exception if the elasticsearch API call is failing
[ "Update", "settings", "in", "Elasticsearch" ]
train
https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/index/IndexElasticsearchUpdater.java#L306-L322
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/parser/lexparser/Options.java
Options.setOptionsOrWarn
public void setOptionsOrWarn(final String[] flags, final int startIndex, final int endIndexPlusOne) { """ Set options based on a String array in the style of commandline flags. This method goes through the array until it ends, processing options, as for {@link #setOption}. @param flags Array of options. The options passed in should be specified like command-line arguments, including with an initial minus sign for example, {"-outputFormat", "typedDependencies", "-maxLength", "70"} @param startIndex The index in the array to begin processing options at @param endIndexPlusOne A number one greater than the last array index at which options should be processed @throws IllegalArgumentException If an unknown flag is passed in """ for (int i = startIndex; i < endIndexPlusOne;) { i = setOptionOrWarn(flags, i); } }
java
public void setOptionsOrWarn(final String[] flags, final int startIndex, final int endIndexPlusOne) { for (int i = startIndex; i < endIndexPlusOne;) { i = setOptionOrWarn(flags, i); } }
[ "public", "void", "setOptionsOrWarn", "(", "final", "String", "[", "]", "flags", ",", "final", "int", "startIndex", ",", "final", "int", "endIndexPlusOne", ")", "{", "for", "(", "int", "i", "=", "startIndex", ";", "i", "<", "endIndexPlusOne", ";", ")", "...
Set options based on a String array in the style of commandline flags. This method goes through the array until it ends, processing options, as for {@link #setOption}. @param flags Array of options. The options passed in should be specified like command-line arguments, including with an initial minus sign for example, {"-outputFormat", "typedDependencies", "-maxLength", "70"} @param startIndex The index in the array to begin processing options at @param endIndexPlusOne A number one greater than the last array index at which options should be processed @throws IllegalArgumentException If an unknown flag is passed in
[ "Set", "options", "based", "on", "a", "String", "array", "in", "the", "style", "of", "commandline", "flags", ".", "This", "method", "goes", "through", "the", "array", "until", "it", "ends", "processing", "options", "as", "for", "{", "@link", "#setOption", ...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/parser/lexparser/Options.java#L100-L104
alkacon/opencms-core
src/org/opencms/util/CmsStringUtil.java
CmsStringUtil.substitutePerl
public static String substitutePerl(String content, String searchString, String replaceItem, String occurences) { """ Substitutes searchString in content with replaceItem.<p> @param content the content which is scanned @param searchString the String which is searched in content @param replaceItem the new String which replaces searchString @param occurences must be a "g" if all occurrences of searchString shall be replaced @return String the substituted String """ String translationRule = "s#" + searchString + "#" + replaceItem + "#" + occurences; Perl5Util perlUtil = new Perl5Util(); try { return perlUtil.substitute(translationRule, content); } catch (MalformedPerl5PatternException e) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_MALFORMED_TRANSLATION_RULE_1, translationRule), e); } } return content; }
java
public static String substitutePerl(String content, String searchString, String replaceItem, String occurences) { String translationRule = "s#" + searchString + "#" + replaceItem + "#" + occurences; Perl5Util perlUtil = new Perl5Util(); try { return perlUtil.substitute(translationRule, content); } catch (MalformedPerl5PatternException e) { if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key(Messages.LOG_MALFORMED_TRANSLATION_RULE_1, translationRule), e); } } return content; }
[ "public", "static", "String", "substitutePerl", "(", "String", "content", ",", "String", "searchString", ",", "String", "replaceItem", ",", "String", "occurences", ")", "{", "String", "translationRule", "=", "\"s#\"", "+", "searchString", "+", "\"#\"", "+", "rep...
Substitutes searchString in content with replaceItem.<p> @param content the content which is scanned @param searchString the String which is searched in content @param replaceItem the new String which replaces searchString @param occurences must be a "g" if all occurrences of searchString shall be replaced @return String the substituted String
[ "Substitutes", "searchString", "in", "content", "with", "replaceItem", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L1750-L1764
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/constraint/DefaultSatConstraintBuilder.java
DefaultSatConstraintBuilder.checkConformance
public boolean checkConformance(BtrPlaceTree t, List<BtrpOperand> ops) { """ Check if the provided parameters match the constraint signature @param t the constraint token @param ops the constraint arguments @return {@code true} iff the arguments match the constraint signature """ //Arity error if (ops.size() != getParameters().length) { t.ignoreError("'" + pretty(ops) + "' cannot be casted to '" + getSignature() + "'"); return false; } //Type checking for (int i = 0; i < ops.size(); i++) { BtrpOperand o = ops.get(i); ConstraintParam<?> p = params[i]; if (o == IgnorableOperand.getInstance()) { return false; } if (!p.isCompatibleWith(t, o)) { t.ignoreError("'" + pretty(ops) + "' cannot be casted to '" + getSignature() + "'"); return false; } } return true; }
java
public boolean checkConformance(BtrPlaceTree t, List<BtrpOperand> ops) { //Arity error if (ops.size() != getParameters().length) { t.ignoreError("'" + pretty(ops) + "' cannot be casted to '" + getSignature() + "'"); return false; } //Type checking for (int i = 0; i < ops.size(); i++) { BtrpOperand o = ops.get(i); ConstraintParam<?> p = params[i]; if (o == IgnorableOperand.getInstance()) { return false; } if (!p.isCompatibleWith(t, o)) { t.ignoreError("'" + pretty(ops) + "' cannot be casted to '" + getSignature() + "'"); return false; } } return true; }
[ "public", "boolean", "checkConformance", "(", "BtrPlaceTree", "t", ",", "List", "<", "BtrpOperand", ">", "ops", ")", "{", "//Arity error", "if", "(", "ops", ".", "size", "(", ")", "!=", "getParameters", "(", ")", ".", "length", ")", "{", "t", ".", "ign...
Check if the provided parameters match the constraint signature @param t the constraint token @param ops the constraint arguments @return {@code true} iff the arguments match the constraint signature
[ "Check", "if", "the", "provided", "parameters", "match", "the", "constraint", "signature" ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/constraint/DefaultSatConstraintBuilder.java#L98-L118
intendia-oss/rxjava-gwt
src/main/modified/io/reactivex/super/io/reactivex/Flowable.java
Flowable.skipUntil
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> skipUntil(Publisher<U> other) { """ Returns a Flowable that skips items emitted by the source Publisher until a second Publisher emits an item. <p> <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipUntil.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure behavior.</dd> <dt><b>Scheduler:</b></dt> <dd>{@code skipUntil} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param <U> the element type of the other Publisher @param other the second Publisher that has to emit an item before the source Publisher's elements begin to be mirrored by the resulting Publisher @return a Flowable that skips items from the source Publisher until the second Publisher emits an item, then emits the remaining items @see <a href="http://reactivex.io/documentation/operators/skipuntil.html">ReactiveX operators documentation: SkipUntil</a> """ ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableSkipUntil<T, U>(this, other)); }
java
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U> Flowable<T> skipUntil(Publisher<U> other) { ObjectHelper.requireNonNull(other, "other is null"); return RxJavaPlugins.onAssembly(new FlowableSkipUntil<T, U>(this, other)); }
[ "@", "CheckReturnValue", "@", "BackpressureSupport", "(", "BackpressureKind", ".", "FULL", ")", "@", "SchedulerSupport", "(", "SchedulerSupport", ".", "NONE", ")", "public", "final", "<", "U", ">", "Flowable", "<", "T", ">", "skipUntil", "(", "Publisher", "<",...
Returns a Flowable that skips items emitted by the source Publisher until a second Publisher emits an item. <p> <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/skipUntil.png" alt=""> <dl> <dt><b>Backpressure:</b></dt> <dd>The operator doesn't interfere with backpressure which is determined by the source {@code Publisher}'s backpressure behavior.</dd> <dt><b>Scheduler:</b></dt> <dd>{@code skipUntil} does not operate by default on a particular {@link Scheduler}.</dd> </dl> @param <U> the element type of the other Publisher @param other the second Publisher that has to emit an item before the source Publisher's elements begin to be mirrored by the resulting Publisher @return a Flowable that skips items from the source Publisher until the second Publisher emits an item, then emits the remaining items @see <a href="http://reactivex.io/documentation/operators/skipuntil.html">ReactiveX operators documentation: SkipUntil</a>
[ "Returns", "a", "Flowable", "that", "skips", "items", "emitted", "by", "the", "source", "Publisher", "until", "a", "second", "Publisher", "emits", "an", "item", ".", "<p", ">", "<img", "width", "=", "640", "height", "=", "375", "src", "=", "https", ":", ...
train
https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Flowable.java#L14048-L14054
thymeleaf/thymeleaf
src/main/java/org/thymeleaf/expression/Uris.java
Uris.escapePath
public String escapePath(final String text, final String encoding) { """ <p> Perform am URI path <strong>escape</strong> operation on a {@code String} input. </p> <p> This method simply calls the equivalent method in the {@code UriEscape} class from the <a href="http://www.unbescape.org">Unbescape</a> library. </p> <p> The following are the only allowed chars in an URI path (will not be escaped): </p> <ul> <li>{@code A-Z a-z 0-9}</li> <li>{@code - . _ ~}</li> <li>{@code ! $ & ' ( ) * + , ; =}</li> <li>{@code : @}</li> <li>{@code /}</li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the specified <em>encoding</em> and then representing each byte in {@code %HH} syntax, being {@code HH} the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the {@code String} to be escaped. @param encoding the encoding to be used for unescaping. @return The escaped result {@code String}. As a memory-performance improvement, will return the exact same object as the {@code text} input argument if no escaping modifications were required (and no additional {@code String} objects will be created during processing). Will return {@code null} if {@code text} is {@code null}. """ return UriEscape.escapeUriPath(text, encoding); }
java
public String escapePath(final String text, final String encoding) { return UriEscape.escapeUriPath(text, encoding); }
[ "public", "String", "escapePath", "(", "final", "String", "text", ",", "final", "String", "encoding", ")", "{", "return", "UriEscape", ".", "escapeUriPath", "(", "text", ",", "encoding", ")", ";", "}" ]
<p> Perform am URI path <strong>escape</strong> operation on a {@code String} input. </p> <p> This method simply calls the equivalent method in the {@code UriEscape} class from the <a href="http://www.unbescape.org">Unbescape</a> library. </p> <p> The following are the only allowed chars in an URI path (will not be escaped): </p> <ul> <li>{@code A-Z a-z 0-9}</li> <li>{@code - . _ ~}</li> <li>{@code ! $ & ' ( ) * + , ; =}</li> <li>{@code : @}</li> <li>{@code /}</li> </ul> <p> All other chars will be escaped by converting them to the sequence of bytes that represents them in the specified <em>encoding</em> and then representing each byte in {@code %HH} syntax, being {@code HH} the hexadecimal representation of the byte. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the {@code String} to be escaped. @param encoding the encoding to be used for unescaping. @return The escaped result {@code String}. As a memory-performance improvement, will return the exact same object as the {@code text} input argument if no escaping modifications were required (and no additional {@code String} objects will be created during processing). Will return {@code null} if {@code text} is {@code null}.
[ "<p", ">", "Perform", "am", "URI", "path", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "{", "@code", "String", "}", "input", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "simply", "calls", "the", "equivalent", "met...
train
https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/expression/Uris.java#L153-L155
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WButtonRenderer.java
WButtonRenderer.paintAjax
private void paintAjax(final WButton button, final XmlStringBuilder xml) { """ Paints the AJAX information for the given WButton. @param button the WButton to paint. @param xml the XmlStringBuilder to paint to. """ // Start tag xml.appendTagOpen("ui:ajaxtrigger"); xml.appendAttribute("triggerId", button.getId()); xml.appendClose(); // Target xml.appendTagOpen("ui:ajaxtargetid"); xml.appendAttribute("targetId", button.getAjaxTarget().getId()); xml.appendEnd(); // End tag xml.appendEndTag("ui:ajaxtrigger"); }
java
private void paintAjax(final WButton button, final XmlStringBuilder xml) { // Start tag xml.appendTagOpen("ui:ajaxtrigger"); xml.appendAttribute("triggerId", button.getId()); xml.appendClose(); // Target xml.appendTagOpen("ui:ajaxtargetid"); xml.appendAttribute("targetId", button.getAjaxTarget().getId()); xml.appendEnd(); // End tag xml.appendEndTag("ui:ajaxtrigger"); }
[ "private", "void", "paintAjax", "(", "final", "WButton", "button", ",", "final", "XmlStringBuilder", "xml", ")", "{", "// Start tag", "xml", ".", "appendTagOpen", "(", "\"ui:ajaxtrigger\"", ")", ";", "xml", ".", "appendAttribute", "(", "\"triggerId\"", ",", "but...
Paints the AJAX information for the given WButton. @param button the WButton to paint. @param xml the XmlStringBuilder to paint to.
[ "Paints", "the", "AJAX", "information", "for", "the", "given", "WButton", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WButtonRenderer.java#L134-L147
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPoliciesInner.java
ServiceEndpointPoliciesInner.beginUpdate
public ServiceEndpointPolicyInner beginUpdate(String resourceGroupName, String serviceEndpointPolicyName, Map<String, String> tags) { """ Updates service Endpoint Policies. @param resourceGroupName The name of the resource group. @param serviceEndpointPolicyName The name of the service endpoint policy. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ServiceEndpointPolicyInner object if successful. """ return beginUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, tags).toBlocking().single().body(); }
java
public ServiceEndpointPolicyInner beginUpdate(String resourceGroupName, String serviceEndpointPolicyName, Map<String, String> tags) { return beginUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, tags).toBlocking().single().body(); }
[ "public", "ServiceEndpointPolicyInner", "beginUpdate", "(", "String", "resourceGroupName", ",", "String", "serviceEndpointPolicyName", ",", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName...
Updates service Endpoint Policies. @param resourceGroupName The name of the resource group. @param serviceEndpointPolicyName The name of the service endpoint policy. @param tags Resource tags. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ServiceEndpointPolicyInner object if successful.
[ "Updates", "service", "Endpoint", "Policies", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ServiceEndpointPoliciesInner.java#L835-L837
Impetus/Kundera
src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java
ESQuery.buildWhereAggregations
private FilterAggregationBuilder buildWhereAggregations(EntityMetadata entityMetadata, QueryBuilder filter) { """ Builds the where aggregations. @param entityMetadata the entity metadata @param filter the filter @return the filter aggregation builder """ filter = filter != null ? filter : QueryBuilders.matchAllQuery(); FilterAggregationBuilder filteragg = AggregationBuilders.filter(ESConstants.AGGREGATION_NAME).filter(filter); return filteragg; }
java
private FilterAggregationBuilder buildWhereAggregations(EntityMetadata entityMetadata, QueryBuilder filter) { filter = filter != null ? filter : QueryBuilders.matchAllQuery(); FilterAggregationBuilder filteragg = AggregationBuilders.filter(ESConstants.AGGREGATION_NAME).filter(filter); return filteragg; }
[ "private", "FilterAggregationBuilder", "buildWhereAggregations", "(", "EntityMetadata", "entityMetadata", ",", "QueryBuilder", "filter", ")", "{", "filter", "=", "filter", "!=", "null", "?", "filter", ":", "QueryBuilders", ".", "matchAllQuery", "(", ")", ";", "Filte...
Builds the where aggregations. @param entityMetadata the entity metadata @param filter the filter @return the filter aggregation builder
[ "Builds", "the", "where", "aggregations", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java#L410-L416
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java
ImageModerationsImpl.evaluateUrlInput
public Evaluate evaluateUrlInput(String contentType, BodyModelModel imageUrl, EvaluateUrlInputOptionalParameter evaluateUrlInputOptionalParameter) { """ Returns probabilities of the image containing racy or adult content. @param contentType The content type. @param imageUrl The image url. @param evaluateUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the Evaluate object if successful. """ return evaluateUrlInputWithServiceResponseAsync(contentType, imageUrl, evaluateUrlInputOptionalParameter).toBlocking().single().body(); }
java
public Evaluate evaluateUrlInput(String contentType, BodyModelModel imageUrl, EvaluateUrlInputOptionalParameter evaluateUrlInputOptionalParameter) { return evaluateUrlInputWithServiceResponseAsync(contentType, imageUrl, evaluateUrlInputOptionalParameter).toBlocking().single().body(); }
[ "public", "Evaluate", "evaluateUrlInput", "(", "String", "contentType", ",", "BodyModelModel", "imageUrl", ",", "EvaluateUrlInputOptionalParameter", "evaluateUrlInputOptionalParameter", ")", "{", "return", "evaluateUrlInputWithServiceResponseAsync", "(", "contentType", ",", "im...
Returns probabilities of the image containing racy or adult content. @param contentType The content type. @param imageUrl The image url. @param evaluateUrlInputOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the Evaluate object if successful.
[ "Returns", "probabilities", "of", "the", "image", "containing", "racy", "or", "adult", "content", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java#L1579-L1581
JOML-CI/JOML
src/org/joml/Matrix3d.java
Matrix3d.lookAlong
public Matrix3d lookAlong(double dirX, double dirY, double dirZ, double upX, double upY, double upZ) { """ Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookalong rotation transformation will be applied first! <p> In order to set the matrix to a lookalong transformation without post-multiplying it, use {@link #setLookAlong(double, double, double, double, double, double) setLookAlong()} @see #setLookAlong(double, double, double, double, double, double) @param dirX the x-coordinate of the direction to look along @param dirY the y-coordinate of the direction to look along @param dirZ the z-coordinate of the direction to look along @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @return this """ return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); }
java
public Matrix3d lookAlong(double dirX, double dirY, double dirZ, double upX, double upY, double upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); }
[ "public", "Matrix3d", "lookAlong", "(", "double", "dirX", ",", "double", "dirY", ",", "double", "dirZ", ",", "double", "upX", ",", "double", "upY", ",", "double", "upZ", ")", "{", "return", "lookAlong", "(", "dirX", ",", "dirY", ",", "dirZ", ",", "upX"...
Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookalong rotation transformation will be applied first! <p> In order to set the matrix to a lookalong transformation without post-multiplying it, use {@link #setLookAlong(double, double, double, double, double, double) setLookAlong()} @see #setLookAlong(double, double, double, double, double, double) @param dirX the x-coordinate of the direction to look along @param dirY the y-coordinate of the direction to look along @param dirZ the z-coordinate of the direction to look along @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @return this
[ "Apply", "a", "rotation", "transformation", "to", "this", "matrix", "to", "make", "<code", ">", "-", "z<", "/", "code", ">", "point", "along", "<code", ">", "dir<", "/", "code", ">", ".", "<p", ">", "If", "<code", ">", "M<", "/", "code", ">", "is",...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3d.java#L3964-L3967
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ExtendedServerBlobAuditingPoliciesInner.java
ExtendedServerBlobAuditingPoliciesInner.beginCreateOrUpdateAsync
public Observable<ExtendedServerBlobAuditingPolicyInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, ExtendedServerBlobAuditingPolicyInner parameters) { """ Creates or updates an extended server's blob auditing policy. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters Properties of extended blob auditing policy @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExtendedServerBlobAuditingPolicyInner object """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ExtendedServerBlobAuditingPolicyInner>, ExtendedServerBlobAuditingPolicyInner>() { @Override public ExtendedServerBlobAuditingPolicyInner call(ServiceResponse<ExtendedServerBlobAuditingPolicyInner> response) { return response.body(); } }); }
java
public Observable<ExtendedServerBlobAuditingPolicyInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, ExtendedServerBlobAuditingPolicyInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ExtendedServerBlobAuditingPolicyInner>, ExtendedServerBlobAuditingPolicyInner>() { @Override public ExtendedServerBlobAuditingPolicyInner call(ServiceResponse<ExtendedServerBlobAuditingPolicyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ExtendedServerBlobAuditingPolicyInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ExtendedServerBlobAuditingPolicyInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceR...
Creates or updates an extended server's blob auditing policy. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param parameters Properties of extended blob auditing policy @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ExtendedServerBlobAuditingPolicyInner object
[ "Creates", "or", "updates", "an", "extended", "server", "s", "blob", "auditing", "policy", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ExtendedServerBlobAuditingPoliciesInner.java#L274-L281
spockframework/spock
spock-core/src/main/java/org/spockframework/compiler/SpecRewriter.java
SpecRewriter.moveVariableDeclarations
private void moveVariableDeclarations(List<Statement> from, List<Statement> to) { """ /* Moves variable declarations from one statement list to another. Initializer expressions are kept at their former place. """ for (Statement stat : from) { DeclarationExpression declExpr = AstUtil.getExpression(stat, DeclarationExpression.class); if (declExpr == null) continue; ((ExpressionStatement) stat).setExpression( new BinaryExpression( copyLhsVariableExpressions(declExpr), Token.newSymbol(Types.ASSIGN, -1, -1), declExpr.getRightExpression())); declExpr.setRightExpression(createDefaultValueInitializer(declExpr)); to.add(new ExpressionStatement(declExpr)); } }
java
private void moveVariableDeclarations(List<Statement> from, List<Statement> to) { for (Statement stat : from) { DeclarationExpression declExpr = AstUtil.getExpression(stat, DeclarationExpression.class); if (declExpr == null) continue; ((ExpressionStatement) stat).setExpression( new BinaryExpression( copyLhsVariableExpressions(declExpr), Token.newSymbol(Types.ASSIGN, -1, -1), declExpr.getRightExpression())); declExpr.setRightExpression(createDefaultValueInitializer(declExpr)); to.add(new ExpressionStatement(declExpr)); } }
[ "private", "void", "moveVariableDeclarations", "(", "List", "<", "Statement", ">", "from", ",", "List", "<", "Statement", ">", "to", ")", "{", "for", "(", "Statement", "stat", ":", "from", ")", "{", "DeclarationExpression", "declExpr", "=", "AstUtil", ".", ...
/* Moves variable declarations from one statement list to another. Initializer expressions are kept at their former place.
[ "/", "*", "Moves", "variable", "declarations", "from", "one", "statement", "list", "to", "another", ".", "Initializer", "expressions", "are", "kept", "at", "their", "former", "place", "." ]
train
https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/org/spockframework/compiler/SpecRewriter.java#L667-L681
tvesalainen/lpg
src/main/java/org/vesalainen/grammar/Grammar.java
Grammar.addSyntheticRule
public void addSyntheticRule(ExecutableElement reducer, String nonterminal, String... rhs) { """ Adds new rule if the same rule doesn't exist already. Rhs is added as-is. Sequences, choices or quantifiers are not parsed. @param nonterminal Left hand side of the rule. @param rhs @see BnfGrammarFactory """ addRule(reducer, nonterminal, "", true, Arrays.asList(rhs)); }
java
public void addSyntheticRule(ExecutableElement reducer, String nonterminal, String... rhs) { addRule(reducer, nonterminal, "", true, Arrays.asList(rhs)); }
[ "public", "void", "addSyntheticRule", "(", "ExecutableElement", "reducer", ",", "String", "nonterminal", ",", "String", "...", "rhs", ")", "{", "addRule", "(", "reducer", ",", "nonterminal", ",", "\"\"", ",", "true", ",", "Arrays", ".", "asList", "(", "rhs",...
Adds new rule if the same rule doesn't exist already. Rhs is added as-is. Sequences, choices or quantifiers are not parsed. @param nonterminal Left hand side of the rule. @param rhs @see BnfGrammarFactory
[ "Adds", "new", "rule", "if", "the", "same", "rule", "doesn", "t", "exist", "already", ".", "Rhs", "is", "added", "as", "-", "is", ".", "Sequences", "choices", "or", "quantifiers", "are", "not", "parsed", "." ]
train
https://github.com/tvesalainen/lpg/blob/0917b8d295e9772b9f8a0affc258a08530cd567a/src/main/java/org/vesalainen/grammar/Grammar.java#L251-L254
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessorHelper.java
PropertyAccessorHelper.setId
public static void setId(Object entity, EntityMetadata metadata, Object rowKey) { """ Sets Primary Key (Row key) into entity field that was annotated with @Id. @param entity the entity @param metadata the metadata @param rowKey the row key @throws PropertyAccessException the property access exception """ try { Field idField = (Field) metadata.getIdAttribute().getJavaMember(); set(entity, idField, rowKey); } catch (IllegalArgumentException iarg) { throw new PropertyAccessException(iarg); } }
java
public static void setId(Object entity, EntityMetadata metadata, Object rowKey) { try { Field idField = (Field) metadata.getIdAttribute().getJavaMember(); set(entity, idField, rowKey); } catch (IllegalArgumentException iarg) { throw new PropertyAccessException(iarg); } }
[ "public", "static", "void", "setId", "(", "Object", "entity", ",", "EntityMetadata", "metadata", ",", "Object", "rowKey", ")", "{", "try", "{", "Field", "idField", "=", "(", "Field", ")", "metadata", ".", "getIdAttribute", "(", ")", ".", "getJavaMember", "...
Sets Primary Key (Row key) into entity field that was annotated with @Id. @param entity the entity @param metadata the metadata @param rowKey the row key @throws PropertyAccessException the property access exception
[ "Sets", "Primary", "Key", "(", "Row", "key", ")", "into", "entity", "field", "that", "was", "annotated", "with", "@Id", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessorHelper.java#L260-L271
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/runtime/StandardSREInstall.java
StandardSREInstall.parsePath
private static IPath parsePath(String path, IPath defaultPath, IPath rootPath) { """ Path the given string for extracting a path. @param path the string representation of the path to parse. @param defaultPath the default path. @param rootPath the root path to use is the given path is not absolute. @return the absolute path. """ if (!Strings.isNullOrEmpty(path)) { try { final IPath pathObject = Path.fromPortableString(path); if (pathObject != null) { if (rootPath != null && !pathObject.isAbsolute()) { return rootPath.append(pathObject); } return pathObject; } } catch (Throwable exception) { // } } return defaultPath; }
java
private static IPath parsePath(String path, IPath defaultPath, IPath rootPath) { if (!Strings.isNullOrEmpty(path)) { try { final IPath pathObject = Path.fromPortableString(path); if (pathObject != null) { if (rootPath != null && !pathObject.isAbsolute()) { return rootPath.append(pathObject); } return pathObject; } } catch (Throwable exception) { // } } return defaultPath; }
[ "private", "static", "IPath", "parsePath", "(", "String", "path", ",", "IPath", "defaultPath", ",", "IPath", "rootPath", ")", "{", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "path", ")", ")", "{", "try", "{", "final", "IPath", "pathObject", "=...
Path the given string for extracting a path. @param path the string representation of the path to parse. @param defaultPath the default path. @param rootPath the root path to use is the given path is not absolute. @return the absolute path.
[ "Path", "the", "given", "string", "for", "extracting", "a", "path", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/runtime/StandardSREInstall.java#L515-L530
cloudant/java-cloudant
cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java
HttpConnection.setRequestBody
public HttpConnection setRequestBody(final InputStream input, final long inputLength) { """ Set the InputStream of request body data, of known length, to be sent to the server. @param input InputStream of request body data to be sent to the server @param inputLength Length of request body data to be sent to the server, in bytes @return an {@link HttpConnection} for method chaining @deprecated Use {@link #setRequestBody(InputStreamGenerator, long)} """ try { return setRequestBody(new InputStreamWrappingGenerator(input, inputLength), inputLength); } catch (IOException e) { logger.log(Level.SEVERE, "Error copying input stream for request body", e); throw new RuntimeException(e); } }
java
public HttpConnection setRequestBody(final InputStream input, final long inputLength) { try { return setRequestBody(new InputStreamWrappingGenerator(input, inputLength), inputLength); } catch (IOException e) { logger.log(Level.SEVERE, "Error copying input stream for request body", e); throw new RuntimeException(e); } }
[ "public", "HttpConnection", "setRequestBody", "(", "final", "InputStream", "input", ",", "final", "long", "inputLength", ")", "{", "try", "{", "return", "setRequestBody", "(", "new", "InputStreamWrappingGenerator", "(", "input", ",", "inputLength", ")", ",", "inpu...
Set the InputStream of request body data, of known length, to be sent to the server. @param input InputStream of request body data to be sent to the server @param inputLength Length of request body data to be sent to the server, in bytes @return an {@link HttpConnection} for method chaining @deprecated Use {@link #setRequestBody(InputStreamGenerator, long)}
[ "Set", "the", "InputStream", "of", "request", "body", "data", "of", "known", "length", "to", "be", "sent", "to", "the", "server", "." ]
train
https://github.com/cloudant/java-cloudant/blob/42c438654945361bded2cc0827afc046d535b31b/cloudant-http/src/main/java/com/cloudant/http/HttpConnection.java#L197-L205
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/Feature.java
Feature.fromJson
public static Feature fromJson(@NonNull String json) { """ Create a new instance of this class by passing in a formatted valid JSON String. If you are creating a Feature object from scratch it is better to use one of the other provided static factory methods such as {@link #fromGeometry(Geometry)}. @param json a formatted valid JSON string defining a GeoJson Feature @return a new instance of this class defined by the values passed inside this static factory method @since 1.0.0 """ GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create()); gson.registerTypeAdapterFactory(GeometryAdapterFactory.create()); Feature feature = gson.create().fromJson(json, Feature.class); // Even thought properties are Nullable, // Feature object will be created with properties set to an empty object, // so that addProperties() would work if (feature.properties() != null) { return feature; } return new Feature(TYPE, feature.bbox(), feature.id(), feature.geometry(), new JsonObject()); }
java
public static Feature fromJson(@NonNull String json) { GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapterFactory(GeoJsonAdapterFactory.create()); gson.registerTypeAdapterFactory(GeometryAdapterFactory.create()); Feature feature = gson.create().fromJson(json, Feature.class); // Even thought properties are Nullable, // Feature object will be created with properties set to an empty object, // so that addProperties() would work if (feature.properties() != null) { return feature; } return new Feature(TYPE, feature.bbox(), feature.id(), feature.geometry(), new JsonObject()); }
[ "public", "static", "Feature", "fromJson", "(", "@", "NonNull", "String", "json", ")", "{", "GsonBuilder", "gson", "=", "new", "GsonBuilder", "(", ")", ";", "gson", ".", "registerTypeAdapterFactory", "(", "GeoJsonAdapterFactory", ".", "create", "(", ")", ")", ...
Create a new instance of this class by passing in a formatted valid JSON String. If you are creating a Feature object from scratch it is better to use one of the other provided static factory methods such as {@link #fromGeometry(Geometry)}. @param json a formatted valid JSON string defining a GeoJson Feature @return a new instance of this class defined by the values passed inside this static factory method @since 1.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "by", "passing", "in", "a", "formatted", "valid", "JSON", "String", ".", "If", "you", "are", "creating", "a", "Feature", "object", "from", "scratch", "it", "is", "better", "to", "use", "one", "of",...
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/Feature.java#L76-L92
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/cache/TagTrackingCacheEventListener.java
TagTrackingCacheEventListener.putElement
protected void putElement(Ehcache cache, Element element) { """ If the element has a TaggedCacheKey record the tag associations """ final Set<CacheEntryTag> tags = this.getTags(element); // Check if the key is tagged if (tags != null && !tags.isEmpty()) { final String cacheName = cache.getName(); final Object key = element.getObjectKey(); final LoadingCache<CacheEntryTag, Set<Object>> cacheKeys = taggedCacheKeys.getUnchecked(cacheName); logger.debug("Tracking {} tags in cache {} for key {}", tags.size(), cacheName, key); // Add all the tags to the tracking map for (final CacheEntryTag tag : tags) { // Record that this tag type is stored in this cache final String tagType = tag.getTagType(); final Set<Ehcache> caches = taggedCaches.getUnchecked(tagType); caches.add(cache); // Record the tag->key association final Set<Object> taggedKeys = cacheKeys.getUnchecked(tag); taggedKeys.add(key); } } }
java
protected void putElement(Ehcache cache, Element element) { final Set<CacheEntryTag> tags = this.getTags(element); // Check if the key is tagged if (tags != null && !tags.isEmpty()) { final String cacheName = cache.getName(); final Object key = element.getObjectKey(); final LoadingCache<CacheEntryTag, Set<Object>> cacheKeys = taggedCacheKeys.getUnchecked(cacheName); logger.debug("Tracking {} tags in cache {} for key {}", tags.size(), cacheName, key); // Add all the tags to the tracking map for (final CacheEntryTag tag : tags) { // Record that this tag type is stored in this cache final String tagType = tag.getTagType(); final Set<Ehcache> caches = taggedCaches.getUnchecked(tagType); caches.add(cache); // Record the tag->key association final Set<Object> taggedKeys = cacheKeys.getUnchecked(tag); taggedKeys.add(key); } } }
[ "protected", "void", "putElement", "(", "Ehcache", "cache", ",", "Element", "element", ")", "{", "final", "Set", "<", "CacheEntryTag", ">", "tags", "=", "this", ".", "getTags", "(", "element", ")", ";", "// Check if the key is tagged", "if", "(", "tags", "!=...
If the element has a TaggedCacheKey record the tag associations
[ "If", "the", "element", "has", "a", "TaggedCacheKey", "record", "the", "tag", "associations" ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/cache/TagTrackingCacheEventListener.java#L134-L158
3pillarlabs/spring-data-simpledb
spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/ReflectionUtils.java
ReflectionUtils.hasDeclaredGetterAndSetter
public static <T> boolean hasDeclaredGetterAndSetter(final Field field, Class<T> entityClazz) { """ This method checks if the declared Field is accessible through getters and setters methods Fields which have only setters OR getters and NOT both are discarded from serialization process """ boolean hasDeclaredAccessorsMutators = true; Method getter = retrieveGetterFrom(entityClazz, field.getName()); Method setter = retrieveSetterFrom(entityClazz, field.getName()); if(getter == null || setter == null) { hasDeclaredAccessorsMutators = false; } return hasDeclaredAccessorsMutators; }
java
public static <T> boolean hasDeclaredGetterAndSetter(final Field field, Class<T> entityClazz) { boolean hasDeclaredAccessorsMutators = true; Method getter = retrieveGetterFrom(entityClazz, field.getName()); Method setter = retrieveSetterFrom(entityClazz, field.getName()); if(getter == null || setter == null) { hasDeclaredAccessorsMutators = false; } return hasDeclaredAccessorsMutators; }
[ "public", "static", "<", "T", ">", "boolean", "hasDeclaredGetterAndSetter", "(", "final", "Field", "field", ",", "Class", "<", "T", ">", "entityClazz", ")", "{", "boolean", "hasDeclaredAccessorsMutators", "=", "true", ";", "Method", "getter", "=", "retrieveGette...
This method checks if the declared Field is accessible through getters and setters methods Fields which have only setters OR getters and NOT both are discarded from serialization process
[ "This", "method", "checks", "if", "the", "declared", "Field", "is", "accessible", "through", "getters", "and", "setters", "methods", "Fields", "which", "have", "only", "setters", "OR", "getters", "and", "NOT", "both", "are", "discarded", "from", "serialization",...
train
https://github.com/3pillarlabs/spring-data-simpledb/blob/f1e0eb4e48ec4674d3966e8f5bc04c95031f93ae/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/reflection/ReflectionUtils.java#L107-L118
TheHortonMachine/hortonmachine
apps/src/main/java/org/hortonmachine/nww/gui/NwwPanel.java
NwwPanel.goTo
public void goTo( Sector sector, boolean animate ) { """ Move to see a given sector. @param sector the sector to go to. @param animate if <code>true</code>, it animates to the position. """ View view = getWwd().getView(); view.stopAnimations(); view.stopMovement(); if (sector == null) { return; } // Create a bounding box for the specified sector in order to estimate // its size in model coordinates. Box extent = Sector.computeBoundingBox(getWwd().getModel().getGlobe(), getWwd().getSceneController().getVerticalExaggeration(), sector); // Estimate the distance between the center position and the eye // position that is necessary to cause the sector to // fill a viewport with the specified field of view. Note that we change // the distance between the center and eye // position here, and leave the field of view constant. Angle fov = view.getFieldOfView(); double zoom = extent.getRadius() / fov.cosHalfAngle() / fov.tanHalfAngle(); // Configure OrbitView to look at the center of the sector from our // estimated distance. This causes OrbitView to // animate to the specified position over several seconds. To affect // this change immediately use the following: if (animate) { view.goTo(new Position(sector.getCentroid(), 0d), zoom); } else { ((OrbitView) wwd.getView()).setCenterPosition(new Position(sector.getCentroid(), 0d)); ((OrbitView) wwd.getView()).setZoom(zoom); } }
java
public void goTo( Sector sector, boolean animate ) { View view = getWwd().getView(); view.stopAnimations(); view.stopMovement(); if (sector == null) { return; } // Create a bounding box for the specified sector in order to estimate // its size in model coordinates. Box extent = Sector.computeBoundingBox(getWwd().getModel().getGlobe(), getWwd().getSceneController().getVerticalExaggeration(), sector); // Estimate the distance between the center position and the eye // position that is necessary to cause the sector to // fill a viewport with the specified field of view. Note that we change // the distance between the center and eye // position here, and leave the field of view constant. Angle fov = view.getFieldOfView(); double zoom = extent.getRadius() / fov.cosHalfAngle() / fov.tanHalfAngle(); // Configure OrbitView to look at the center of the sector from our // estimated distance. This causes OrbitView to // animate to the specified position over several seconds. To affect // this change immediately use the following: if (animate) { view.goTo(new Position(sector.getCentroid(), 0d), zoom); } else { ((OrbitView) wwd.getView()).setCenterPosition(new Position(sector.getCentroid(), 0d)); ((OrbitView) wwd.getView()).setZoom(zoom); } }
[ "public", "void", "goTo", "(", "Sector", "sector", ",", "boolean", "animate", ")", "{", "View", "view", "=", "getWwd", "(", ")", ".", "getView", "(", ")", ";", "view", ".", "stopAnimations", "(", ")", ";", "view", ".", "stopMovement", "(", ")", ";", ...
Move to see a given sector. @param sector the sector to go to. @param animate if <code>true</code>, it animates to the position.
[ "Move", "to", "see", "a", "given", "sector", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/apps/src/main/java/org/hortonmachine/nww/gui/NwwPanel.java#L257-L288
aws/aws-sdk-java
aws-java-sdk-cloudformation/src/main/java/com/amazonaws/services/cloudformation/model/DescribeStackResourceDriftsResult.java
DescribeStackResourceDriftsResult.getStackResourceDrifts
public java.util.List<StackResourceDrift> getStackResourceDrifts() { """ <p> Drift information for the resources that have been checked for drift in the specified stack. This includes actual and expected configuration values for resources where AWS CloudFormation detects drift. </p> <p> For a given stack, there will be one <code>StackResourceDrift</code> for each stack resource that has been checked for drift. Resources that have not yet been checked for drift are not included. Resources that do not currently support drift detection are not checked, and so not included. For a list of resources that support drift detection, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift-resource-list.html" >Resources that Support Drift Detection</a>. </p> @return Drift information for the resources that have been checked for drift in the specified stack. This includes actual and expected configuration values for resources where AWS CloudFormation detects drift.</p> <p> For a given stack, there will be one <code>StackResourceDrift</code> for each stack resource that has been checked for drift. Resources that have not yet been checked for drift are not included. Resources that do not currently support drift detection are not checked, and so not included. For a list of resources that support drift detection, see <a href= "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift-resource-list.html" >Resources that Support Drift Detection</a>. """ if (stackResourceDrifts == null) { stackResourceDrifts = new com.amazonaws.internal.SdkInternalList<StackResourceDrift>(); } return stackResourceDrifts; }
java
public java.util.List<StackResourceDrift> getStackResourceDrifts() { if (stackResourceDrifts == null) { stackResourceDrifts = new com.amazonaws.internal.SdkInternalList<StackResourceDrift>(); } return stackResourceDrifts; }
[ "public", "java", ".", "util", ".", "List", "<", "StackResourceDrift", ">", "getStackResourceDrifts", "(", ")", "{", "if", "(", "stackResourceDrifts", "==", "null", ")", "{", "stackResourceDrifts", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "...
<p> Drift information for the resources that have been checked for drift in the specified stack. This includes actual and expected configuration values for resources where AWS CloudFormation detects drift. </p> <p> For a given stack, there will be one <code>StackResourceDrift</code> for each stack resource that has been checked for drift. Resources that have not yet been checked for drift are not included. Resources that do not currently support drift detection are not checked, and so not included. For a list of resources that support drift detection, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift-resource-list.html" >Resources that Support Drift Detection</a>. </p> @return Drift information for the resources that have been checked for drift in the specified stack. This includes actual and expected configuration values for resources where AWS CloudFormation detects drift.</p> <p> For a given stack, there will be one <code>StackResourceDrift</code> for each stack resource that has been checked for drift. Resources that have not yet been checked for drift are not included. Resources that do not currently support drift detection are not checked, and so not included. For a list of resources that support drift detection, see <a href= "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift-resource-list.html" >Resources that Support Drift Detection</a>.
[ "<p", ">", "Drift", "information", "for", "the", "resources", "that", "have", "been", "checked", "for", "drift", "in", "the", "specified", "stack", ".", "This", "includes", "actual", "and", "expected", "configuration", "values", "for", "resources", "where", "A...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cloudformation/src/main/java/com/amazonaws/services/cloudformation/model/DescribeStackResourceDriftsResult.java#L77-L82
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.writeWordVectors
public static void writeWordVectors(@NonNull Glove vectors, @NonNull OutputStream stream) { """ This method saves GloVe model to the given OutputStream @param vectors GloVe model to be saved @param stream OutputStream where model should be saved to """ try { writeWordVectors(vectors.lookupTable(), stream); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static void writeWordVectors(@NonNull Glove vectors, @NonNull OutputStream stream) { try { writeWordVectors(vectors.lookupTable(), stream); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "void", "writeWordVectors", "(", "@", "NonNull", "Glove", "vectors", ",", "@", "NonNull", "OutputStream", "stream", ")", "{", "try", "{", "writeWordVectors", "(", "vectors", ".", "lookupTable", "(", ")", ",", "stream", ")", ";", "}", "c...
This method saves GloVe model to the given OutputStream @param vectors GloVe model to be saved @param stream OutputStream where model should be saved to
[ "This", "method", "saves", "GloVe", "model", "to", "the", "given", "OutputStream" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L1141-L1147
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.setVpnclientIpsecParameters
public VpnClientIPsecParametersInner setVpnclientIpsecParameters(String resourceGroupName, String virtualNetworkGatewayName, VpnClientIPsecParametersInner vpnclientIpsecParams) { """ The Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy for P2S client of virtual network gateway in the specified resource group through Network resource provider. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param vpnclientIpsecParams Parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual Network Gateway P2S client operation through Network resource provider. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VpnClientIPsecParametersInner object if successful. """ return setVpnclientIpsecParametersWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams).toBlocking().last().body(); }
java
public VpnClientIPsecParametersInner setVpnclientIpsecParameters(String resourceGroupName, String virtualNetworkGatewayName, VpnClientIPsecParametersInner vpnclientIpsecParams) { return setVpnclientIpsecParametersWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, vpnclientIpsecParams).toBlocking().last().body(); }
[ "public", "VpnClientIPsecParametersInner", "setVpnclientIpsecParameters", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "VpnClientIPsecParametersInner", "vpnclientIpsecParams", ")", "{", "return", "setVpnclientIpsecParametersWithServiceResponseAsy...
The Set VpnclientIpsecParameters operation sets the vpnclient ipsec policy for P2S client of virtual network gateway in the specified resource group through Network resource provider. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param vpnclientIpsecParams Parameters supplied to the Begin Set vpnclient ipsec parameters of Virtual Network Gateway P2S client operation through Network resource provider. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VpnClientIPsecParametersInner object if successful.
[ "The", "Set", "VpnclientIpsecParameters", "operation", "sets", "the", "vpnclient", "ipsec", "policy", "for", "P2S", "client", "of", "virtual", "network", "gateway", "in", "the", "specified", "resource", "group", "through", "Network", "resource", "provider", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2659-L2661
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/shapes/edge/SnapToLineEdge.java
SnapToLineEdge.refine
public boolean refine(Point2D_F64 a, Point2D_F64 b, LineGeneral2D_F64 found) { """ Fits a line defined by the two points. When fitting the line the weight of the edge is used to determine. how influential the point is. Multiple calls might be required to get a perfect fit. @param a Start of line @param b End of line.. @param found (output) Fitted line to the edge @return true if successful or false if it failed """ // determine the local coordinate system center.x = (a.x + b.x)/2.0; center.y = (a.y + b.y)/2.0; localScale = a.distance(center); // define the line which points are going to be sampled along double slopeX = (b.x - a.x); double slopeY = (b.y - a.y); double r = Math.sqrt(slopeX*slopeX + slopeY*slopeY); // tangent of unit length that radial sample samples are going to be along // Two choices for tangent here. Select the one which points to the "right" of the line, // which is inside of the edge double tanX = slopeY/r; double tanY = -slopeX/r; // set up inputs into line fitting computePointsAndWeights(slopeX, slopeY, a.x, a.y, tanX, tanY); if( samplePts.size() >= 4 ) { // fit line and convert into generalized format if( null == FitLine_F64.polar(samplePts.toList(), weights.data, polar) ) { throw new RuntimeException("All weights were zero, bug some place"); } UtilLine2D_F64.convert(polar, found); // Convert line from local to global coordinates localToGlobal(found); return true; } else { return false; } }
java
public boolean refine(Point2D_F64 a, Point2D_F64 b, LineGeneral2D_F64 found) { // determine the local coordinate system center.x = (a.x + b.x)/2.0; center.y = (a.y + b.y)/2.0; localScale = a.distance(center); // define the line which points are going to be sampled along double slopeX = (b.x - a.x); double slopeY = (b.y - a.y); double r = Math.sqrt(slopeX*slopeX + slopeY*slopeY); // tangent of unit length that radial sample samples are going to be along // Two choices for tangent here. Select the one which points to the "right" of the line, // which is inside of the edge double tanX = slopeY/r; double tanY = -slopeX/r; // set up inputs into line fitting computePointsAndWeights(slopeX, slopeY, a.x, a.y, tanX, tanY); if( samplePts.size() >= 4 ) { // fit line and convert into generalized format if( null == FitLine_F64.polar(samplePts.toList(), weights.data, polar) ) { throw new RuntimeException("All weights were zero, bug some place"); } UtilLine2D_F64.convert(polar, found); // Convert line from local to global coordinates localToGlobal(found); return true; } else { return false; } }
[ "public", "boolean", "refine", "(", "Point2D_F64", "a", ",", "Point2D_F64", "b", ",", "LineGeneral2D_F64", "found", ")", "{", "// determine the local coordinate system", "center", ".", "x", "=", "(", "a", ".", "x", "+", "b", ".", "x", ")", "/", "2.0", ";",...
Fits a line defined by the two points. When fitting the line the weight of the edge is used to determine. how influential the point is. Multiple calls might be required to get a perfect fit. @param a Start of line @param b End of line.. @param found (output) Fitted line to the edge @return true if successful or false if it failed
[ "Fits", "a", "line", "defined", "by", "the", "two", "points", ".", "When", "fitting", "the", "line", "the", "weight", "of", "the", "edge", "is", "used", "to", "determine", ".", "how", "influential", "the", "point", "is", ".", "Multiple", "calls", "might"...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/edge/SnapToLineEdge.java#L103-L138