repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
thorntail/thorntail
tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java
DeclaredDependencies.createSpec
public static ArtifactSpec createSpec(String gav, String scope) { try { MavenArtifactDescriptor maven = ArtifactSpec.fromMavenGav(gav); return new ArtifactSpec( scope, maven.groupId(), maven.artifactId(), maven.version(), maven.type(), maven.classifier(), null ); } catch (IOException e) { throw new RuntimeException(e); } }
java
public static ArtifactSpec createSpec(String gav, String scope) { try { MavenArtifactDescriptor maven = ArtifactSpec.fromMavenGav(gav); return new ArtifactSpec( scope, maven.groupId(), maven.artifactId(), maven.version(), maven.type(), maven.classifier(), null ); } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "static", "ArtifactSpec", "createSpec", "(", "String", "gav", ",", "String", "scope", ")", "{", "try", "{", "MavenArtifactDescriptor", "maven", "=", "ArtifactSpec", ".", "fromMavenGav", "(", "gav", ")", ";", "return", "new", "ArtifactSpec", "(", "sco...
Create an instance of {@link ArtifactSpec} from the given GAV coordinates. @param gav the GAV coordinates for the artifact. @param scope the scope to be set on the returned instance. @return an instance of {@link ArtifactSpec} from the given GAV coordinates.
[ "Create", "an", "instance", "of", "{", "@link", "ArtifactSpec", "}", "from", "the", "given", "GAV", "coordinates", "." ]
train
https://github.com/thorntail/thorntail/blob/4a391b68ffae98c6e66d30a3bfb99dadc9509f14/tools/src/main/java/org/wildfly/swarm/tools/DeclaredDependencies.java#L211-L228
ops4j/org.ops4j.base
ops4j-base-util-xml/src/main/java/org/ops4j/util/xml/ElementHelper.java
ElementHelper.getRootElement
public static Element getRootElement( InputStream input ) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating( false ); factory.setNamespaceAware( false ); try { factory.setFeature( "http://xml.org/sax/features/namespaces", false ); factory.setFeature( "http://xml.org/sax/features/validation", false ); factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false ); factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false ); } catch( Throwable ignore ) { // ignore. we did our best. } DocumentBuilder builder = factory.newDocumentBuilder(); try { // return an empty entity resolver if parser will ask for it, such disabling any validation builder.setEntityResolver( new EntityResolver() { public InputSource resolveEntity( java.lang.String publicId, java.lang.String systemId ) throws SAXException, java.io.IOException { return new InputSource( new ByteArrayInputStream( "<?xml version='1.0' encoding='UTF-8'?>".getBytes() ) ); } } ); } catch( Throwable ignore ) { // ignore. we did our best. } Document document = builder.parse( input ); return document.getDocumentElement(); }
java
public static Element getRootElement( InputStream input ) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating( false ); factory.setNamespaceAware( false ); try { factory.setFeature( "http://xml.org/sax/features/namespaces", false ); factory.setFeature( "http://xml.org/sax/features/validation", false ); factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false ); factory.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false ); } catch( Throwable ignore ) { // ignore. we did our best. } DocumentBuilder builder = factory.newDocumentBuilder(); try { // return an empty entity resolver if parser will ask for it, such disabling any validation builder.setEntityResolver( new EntityResolver() { public InputSource resolveEntity( java.lang.String publicId, java.lang.String systemId ) throws SAXException, java.io.IOException { return new InputSource( new ByteArrayInputStream( "<?xml version='1.0' encoding='UTF-8'?>".getBytes() ) ); } } ); } catch( Throwable ignore ) { // ignore. we did our best. } Document document = builder.parse( input ); return document.getDocumentElement(); }
[ "public", "static", "Element", "getRootElement", "(", "InputStream", "input", ")", "throws", "ParserConfigurationException", ",", "IOException", ",", "SAXException", "{", "DocumentBuilderFactory", "factory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", "...
Return the root element of the supplied input stream. @param input the input stream containing a XML definition @return the root element @throws IOException If an underlying I/O problem occurred. @throws ParserConfigurationException if there is a severe problem in the XML parsing subsystem. @throws SAXException If the XML is malformed in some way.
[ "Return", "the", "root", "element", "of", "the", "supplied", "input", "stream", "." ]
train
https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-util-xml/src/main/java/org/ops4j/util/xml/ElementHelper.java#L65-L105
phax/ph-web
ph-web/src/main/java/com/helger/web/multipart/MultipartStream.java
MultipartStream.readHeaders
public String readHeaders () throws MultipartMalformedStreamException { // to support multi-byte characters try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ()) { int nHeaderSepIndex = 0; int nSize = 0; while (nHeaderSepIndex < HEADER_SEPARATOR.length) { byte b; try { b = readByte (); } catch (final IOException e) { throw new MultipartMalformedStreamException ("Stream ended unexpectedly after " + nSize + " bytes", e); } if (++nSize > HEADER_PART_SIZE_MAX) { throw new MultipartMalformedStreamException ("Header section has more than " + HEADER_PART_SIZE_MAX + " bytes (maybe it is not properly terminated)"); } if (b == HEADER_SEPARATOR[nHeaderSepIndex]) nHeaderSepIndex++; else nHeaderSepIndex = 0; aBAOS.write (b); } final Charset aCharsetToUse = CharsetHelper.getCharsetFromNameOrDefault (m_sHeaderEncoding, SystemHelper.getSystemCharset ()); return aBAOS.getAsString (aCharsetToUse); } }
java
public String readHeaders () throws MultipartMalformedStreamException { // to support multi-byte characters try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ()) { int nHeaderSepIndex = 0; int nSize = 0; while (nHeaderSepIndex < HEADER_SEPARATOR.length) { byte b; try { b = readByte (); } catch (final IOException e) { throw new MultipartMalformedStreamException ("Stream ended unexpectedly after " + nSize + " bytes", e); } if (++nSize > HEADER_PART_SIZE_MAX) { throw new MultipartMalformedStreamException ("Header section has more than " + HEADER_PART_SIZE_MAX + " bytes (maybe it is not properly terminated)"); } if (b == HEADER_SEPARATOR[nHeaderSepIndex]) nHeaderSepIndex++; else nHeaderSepIndex = 0; aBAOS.write (b); } final Charset aCharsetToUse = CharsetHelper.getCharsetFromNameOrDefault (m_sHeaderEncoding, SystemHelper.getSystemCharset ()); return aBAOS.getAsString (aCharsetToUse); } }
[ "public", "String", "readHeaders", "(", ")", "throws", "MultipartMalformedStreamException", "{", "// to support multi-byte characters", "try", "(", "final", "NonBlockingByteArrayOutputStream", "aBAOS", "=", "new", "NonBlockingByteArrayOutputStream", "(", ")", ")", "{", "int...
<p> Reads the <code>header-part</code> of the current <code>encapsulation</code>. <p> Headers are returned verbatim to the input stream, including the trailing <code>CRLF</code> marker. Parsing is left to the application. @return The <code>header-part</code> of the current encapsulation. @throws MultipartMalformedStreamException if the stream ends unexpectedly.
[ "<p", ">", "Reads", "the", "<code", ">", "header", "-", "part<", "/", "code", ">", "of", "the", "current", "<code", ">", "encapsulation<", "/", "code", ">", ".", "<p", ">", "Headers", "are", "returned", "verbatim", "to", "the", "input", "stream", "incl...
train
https://github.com/phax/ph-web/blob/d445fd25184605b62682c93c9782409acf0ae813/ph-web/src/main/java/com/helger/web/multipart/MultipartStream.java#L401-L436
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WColumnLayout.java
WColumnLayout.setLeftColumn
public void setLeftColumn(final String heading, final WComponent content) { setLeftColumn(new WHeading(WHeading.MINOR, heading), content); }
java
public void setLeftColumn(final String heading, final WComponent content) { setLeftColumn(new WHeading(WHeading.MINOR, heading), content); }
[ "public", "void", "setLeftColumn", "(", "final", "String", "heading", ",", "final", "WComponent", "content", ")", "{", "setLeftColumn", "(", "new", "WHeading", "(", "WHeading", ".", "MINOR", ",", "heading", ")", ",", "content", ")", ";", "}" ]
Sets the left column content. @param heading the column heading text. @param content the content.
[ "Sets", "the", "left", "column", "content", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WColumnLayout.java#L82-L84
forge/core
javaee/scaffold-faces/src/main/java/org/jboss/forge/addon/scaffold/faces/freemarker/FreemarkerTemplateProcessor.java
FreemarkerTemplateProcessor.processTemplate
public static String processTemplate(Map<Object, Object> map, String templateLocation) { Writer output = new StringWriter(); try { Template templateFile = getFreemarkerConfig().getTemplate(templateLocation); templateFile.process(map, output); output.flush(); } catch (IOException ioEx) { throw new RuntimeException(ioEx); } catch (TemplateException templateEx) { throw new RuntimeException(templateEx); } return output.toString(); }
java
public static String processTemplate(Map<Object, Object> map, String templateLocation) { Writer output = new StringWriter(); try { Template templateFile = getFreemarkerConfig().getTemplate(templateLocation); templateFile.process(map, output); output.flush(); } catch (IOException ioEx) { throw new RuntimeException(ioEx); } catch (TemplateException templateEx) { throw new RuntimeException(templateEx); } return output.toString(); }
[ "public", "static", "String", "processTemplate", "(", "Map", "<", "Object", ",", "Object", ">", "map", ",", "String", "templateLocation", ")", "{", "Writer", "output", "=", "new", "StringWriter", "(", ")", ";", "try", "{", "Template", "templateFile", "=", ...
Processes the provided data model with the specified Freemarker template @param map the data model to use for template processing. @param templateLocation The location of the template relative to the classpath @return The text output after successfully processing the template
[ "Processes", "the", "provided", "data", "model", "with", "the", "specified", "Freemarker", "template" ]
train
https://github.com/forge/core/blob/e140eb03bbe2b3409478ad70c86c3edbef6d9a0c/javaee/scaffold-faces/src/main/java/org/jboss/forge/addon/scaffold/faces/freemarker/FreemarkerTemplateProcessor.java#L53-L71
febit/wit
wit-core/src/main/java/org/febit/wit/InternalContext.java
InternalContext.createSubContext
public InternalContext createSubContext(VariantIndexer[] indexers, InternalContext localContext, int varSize) { Object[][] myParentScopes = this.parentScopes; //cal the new-context's parent-scopes Object[][] scopes; if (myParentScopes == null) { scopes = new Object[][]{this.vars}; } else { scopes = new Object[myParentScopes.length + 1][]; scopes[0] = this.vars; System.arraycopy(myParentScopes, 0, scopes, 1, myParentScopes.length); } InternalContext newContext = new InternalContext(template, localContext.out, Vars.EMPTY, indexers, varSize, scopes); newContext.localContext = localContext; return newContext; }
java
public InternalContext createSubContext(VariantIndexer[] indexers, InternalContext localContext, int varSize) { Object[][] myParentScopes = this.parentScopes; //cal the new-context's parent-scopes Object[][] scopes; if (myParentScopes == null) { scopes = new Object[][]{this.vars}; } else { scopes = new Object[myParentScopes.length + 1][]; scopes[0] = this.vars; System.arraycopy(myParentScopes, 0, scopes, 1, myParentScopes.length); } InternalContext newContext = new InternalContext(template, localContext.out, Vars.EMPTY, indexers, varSize, scopes); newContext.localContext = localContext; return newContext; }
[ "public", "InternalContext", "createSubContext", "(", "VariantIndexer", "[", "]", "indexers", ",", "InternalContext", "localContext", ",", "int", "varSize", ")", "{", "Object", "[", "]", "[", "]", "myParentScopes", "=", "this", ".", "parentScopes", ";", "//cal t...
Create a sub context. @param indexers indexers @param localContext local context @param varSize var size @return a new sub context
[ "Create", "a", "sub", "context", "." ]
train
https://github.com/febit/wit/blob/89ee29efbc5633b79c30c3c7b953c9f4130575af/wit-core/src/main/java/org/febit/wit/InternalContext.java#L129-L145
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java
EmoSerDe.deserializePrimitive
private Object deserializePrimitive(PrimitiveTypeInfo type, Object value) throws SerDeException { switch (type.getPrimitiveCategory()) { case VOID: return null; case STRING: return deserializeString(value); case BOOLEAN: return deserializeBoolean(value); case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: return deserializeNumber(value, type); case DATE: case TIMESTAMP: return deserializeDate(value, type); default: throw new SerDeException("Unsupported type: " + type.getPrimitiveCategory()); } }
java
private Object deserializePrimitive(PrimitiveTypeInfo type, Object value) throws SerDeException { switch (type.getPrimitiveCategory()) { case VOID: return null; case STRING: return deserializeString(value); case BOOLEAN: return deserializeBoolean(value); case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: return deserializeNumber(value, type); case DATE: case TIMESTAMP: return deserializeDate(value, type); default: throw new SerDeException("Unsupported type: " + type.getPrimitiveCategory()); } }
[ "private", "Object", "deserializePrimitive", "(", "PrimitiveTypeInfo", "type", ",", "Object", "value", ")", "throws", "SerDeException", "{", "switch", "(", "type", ".", "getPrimitiveCategory", "(", ")", ")", "{", "case", "VOID", ":", "return", "null", ";", "ca...
Deserializes a primitive to its corresponding Java type, doing a best-effort conversion when necessary.
[ "Deserializes", "a", "primitive", "to", "its", "corresponding", "Java", "type", "doing", "a", "best", "-", "effort", "conversion", "when", "necessary", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L343-L365
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
SecondaryNameNode.doMerge
private void doMerge(CheckpointSignature sig, RemoteEditLogManifest manifest, boolean loadImage, FSImage dstImage) throws IOException { if (loadImage) { // create an empty namespace if new image namesystem = new FSNamesystem(checkpointImage, conf); checkpointImage.setFSNamesystem(namesystem); } assert namesystem.dir.fsImage == checkpointImage; checkpointImage.doMerge(sig, manifest, loadImage); }
java
private void doMerge(CheckpointSignature sig, RemoteEditLogManifest manifest, boolean loadImage, FSImage dstImage) throws IOException { if (loadImage) { // create an empty namespace if new image namesystem = new FSNamesystem(checkpointImage, conf); checkpointImage.setFSNamesystem(namesystem); } assert namesystem.dir.fsImage == checkpointImage; checkpointImage.doMerge(sig, manifest, loadImage); }
[ "private", "void", "doMerge", "(", "CheckpointSignature", "sig", ",", "RemoteEditLogManifest", "manifest", ",", "boolean", "loadImage", ",", "FSImage", "dstImage", ")", "throws", "IOException", "{", "if", "(", "loadImage", ")", "{", "// create an empty namespace if ne...
Merge downloaded image and edits and write the new image into current storage directory.
[ "Merge", "downloaded", "image", "and", "edits", "and", "write", "the", "new", "image", "into", "current", "storage", "directory", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java#L367-L375
w3c/epubcheck
src/main/java/com/adobe/epubcheck/messages/LocalizedMessages.java
LocalizedMessages.getSuggestion
public String getSuggestion(MessageId id, String key) { String messageKey = id.name() + "_SUG." + key; String messageDefaultKey = id.name() + "_SUG.default"; return bundle.containsKey(messageKey) ? getStringFromBundle(messageKey) : (bundle.containsKey(messageDefaultKey) ? getStringFromBundle(messageDefaultKey) : getSuggestion(id)); }
java
public String getSuggestion(MessageId id, String key) { String messageKey = id.name() + "_SUG." + key; String messageDefaultKey = id.name() + "_SUG.default"; return bundle.containsKey(messageKey) ? getStringFromBundle(messageKey) : (bundle.containsKey(messageDefaultKey) ? getStringFromBundle(messageDefaultKey) : getSuggestion(id)); }
[ "public", "String", "getSuggestion", "(", "MessageId", "id", ",", "String", "key", ")", "{", "String", "messageKey", "=", "id", ".", "name", "(", ")", "+", "\"_SUG.\"", "+", "key", ";", "String", "messageDefaultKey", "=", "id", ".", "name", "(", ")", "...
Returns the suggestion message for the given message ID and key. In other words, for a message ID of `XXX_NNN`, and a key `key`, returns the bundle message named `XXX_NNN_SUG.key`. If the suggestion key is not found, returns the bundle message named `XXX_NNN_SUG.default`. If this latter is not found, returns the bundle message nameed `XXX_NNN_SUG`. @param id a message ID @param key the key of a specific suggestion string @return the associated suggestion string
[ "Returns", "the", "suggestion", "message", "for", "the", "given", "message", "ID", "and", "key", ".", "In", "other", "words", "for", "a", "message", "ID", "of", "XXX_NNN", "and", "a", "key", "key", "returns", "the", "bundle", "message", "named", "XXX_NNN_S...
train
https://github.com/w3c/epubcheck/blob/4d5a24d9f2878a2a5497eb11c036cc18fe2c0a78/src/main/java/com/adobe/epubcheck/messages/LocalizedMessages.java#L164-L171
VoltDB/voltdb
third_party/java/src/org/apache/commons_voltpatches/cli/CommandLine.java
CommandLine.getOptionValue
public String getOptionValue(char opt, String defaultValue) { return getOptionValue(String.valueOf(opt), defaultValue); }
java
public String getOptionValue(char opt, String defaultValue) { return getOptionValue(String.valueOf(opt), defaultValue); }
[ "public", "String", "getOptionValue", "(", "char", "opt", ",", "String", "defaultValue", ")", "{", "return", "getOptionValue", "(", "String", ".", "valueOf", "(", "opt", ")", ",", "defaultValue", ")", ";", "}" ]
Retrieve the argument, if any, of an option. @param opt character name of the option @param defaultValue is the default value to be returned if the option is not specified @return Value of the argument if option is set, and has an argument, otherwise <code>defaultValue</code>.
[ "Retrieve", "the", "argument", "if", "any", "of", "an", "option", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/commons_voltpatches/cli/CommandLine.java#L245-L248
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/text/TokenStream.java
TokenStream.consumeBoolean
public boolean consumeBoolean() throws ParsingException, IllegalStateException { if (completed) throwNoMoreContent(); // Get the value from the current token ... String value = currentToken().value(); try { boolean result = Boolean.parseBoolean(value); moveToNextToken(); return result; } catch (NumberFormatException e) { Position position = currentToken().position(); String msg = CommonI18n.expectingValidBooleanAtLineAndColumn.text(value, position.getLine(), position.getColumn()); throw new ParsingException(position, msg); } }
java
public boolean consumeBoolean() throws ParsingException, IllegalStateException { if (completed) throwNoMoreContent(); // Get the value from the current token ... String value = currentToken().value(); try { boolean result = Boolean.parseBoolean(value); moveToNextToken(); return result; } catch (NumberFormatException e) { Position position = currentToken().position(); String msg = CommonI18n.expectingValidBooleanAtLineAndColumn.text(value, position.getLine(), position.getColumn()); throw new ParsingException(position, msg); } }
[ "public", "boolean", "consumeBoolean", "(", ")", "throws", "ParsingException", ",", "IllegalStateException", "{", "if", "(", "completed", ")", "throwNoMoreContent", "(", ")", ";", "// Get the value from the current token ...", "String", "value", "=", "currentToken", "("...
Convert the value of this token to an integer, return it, and move to the next token. @return the current token's value, converted to an integer @throws ParsingException if there is no such token to consume, or if the token cannot be converted to an integer @throws IllegalStateException if this method was called before the stream was {@link #start() started}
[ "Convert", "the", "value", "of", "this", "token", "to", "an", "integer", "return", "it", "and", "move", "to", "the", "next", "token", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/text/TokenStream.java#L524-L537
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java
TypesafeConfigUtils.loadConfig
public static Config loadConfig(File configFile, boolean useSystemEnvironment) { return loadConfig(ConfigParseOptions.defaults(), ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment), configFile); }
java
public static Config loadConfig(File configFile, boolean useSystemEnvironment) { return loadConfig(ConfigParseOptions.defaults(), ConfigResolveOptions.defaults().setUseSystemEnvironment(useSystemEnvironment), configFile); }
[ "public", "static", "Config", "loadConfig", "(", "File", "configFile", ",", "boolean", "useSystemEnvironment", ")", "{", "return", "loadConfig", "(", "ConfigParseOptions", ".", "defaults", "(", ")", ",", "ConfigResolveOptions", ".", "defaults", "(", ")", ".", "s...
Load, Parse & Resolve configurations from a file, with default parse & resolve options. @param configFile @param useSystemEnvironment {@code true} to resolve substitutions falling back to environment variables @return
[ "Load", "Parse", "&", "Resolve", "configurations", "from", "a", "file", "with", "default", "parse", "&", "resolve", "options", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/TypesafeConfigUtils.java#L56-L60
kite-sdk/kite
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/StorageKey.java
StorageKey.reuseFor
@SuppressWarnings("unchecked") public <E> StorageKey reuseFor(E entity, EntityAccessor<E> accessor) { accessor.keyFor(entity, null, this); return this; }
java
@SuppressWarnings("unchecked") public <E> StorageKey reuseFor(E entity, EntityAccessor<E> accessor) { accessor.keyFor(entity, null, this); return this; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "E", ">", "StorageKey", "reuseFor", "(", "E", "entity", ",", "EntityAccessor", "<", "E", ">", "accessor", ")", "{", "accessor", ".", "keyFor", "(", "entity", ",", "null", ",", "this", ")"...
Replaces all of the values in this {@link StorageKey} with values from the given {@code entity}. @param entity an entity to reuse this {@code StorageKey} for @return this updated {@code StorageKey} @throws IllegalStateException If the {@code entity} cannot be used to produce a value for each field in the {@code PartitionStrategy} @since 0.9.0
[ "Replaces", "all", "of", "the", "values", "in", "this", "{", "@link", "StorageKey", "}", "with", "values", "from", "the", "given", "{", "@code", "entity", "}", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/StorageKey.java#L154-L158
knowm/XChange
xchange-paribu/src/main/java/org/knowm/xchange/paribu/ParibuAdapters.java
ParibuAdapters.adaptTicker
public static Ticker adaptTicker(ParibuTicker paribuTicker, CurrencyPair currencyPair) { if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) { throw new NotAvailableFromExchangeException(); } BTC_TL btcTL = paribuTicker.getBtcTL(); if (btcTL != null) { BigDecimal last = btcTL.getLast(); BigDecimal lowestAsk = btcTL.getLowestAsk(); BigDecimal highestBid = btcTL.getHighestBid(); BigDecimal volume = btcTL.getVolume(); BigDecimal high24hr = btcTL.getHigh24hr(); BigDecimal low24hr = btcTL.getLow24hr(); return new Ticker.Builder() .currencyPair(new CurrencyPair(BTC, Currency.TRY)) .last(last) .bid(highestBid) .ask(lowestAsk) .high(high24hr) .low(low24hr) .volume(volume) .build(); } return null; }
java
public static Ticker adaptTicker(ParibuTicker paribuTicker, CurrencyPair currencyPair) { if (!currencyPair.equals(new CurrencyPair(BTC, TRY))) { throw new NotAvailableFromExchangeException(); } BTC_TL btcTL = paribuTicker.getBtcTL(); if (btcTL != null) { BigDecimal last = btcTL.getLast(); BigDecimal lowestAsk = btcTL.getLowestAsk(); BigDecimal highestBid = btcTL.getHighestBid(); BigDecimal volume = btcTL.getVolume(); BigDecimal high24hr = btcTL.getHigh24hr(); BigDecimal low24hr = btcTL.getLow24hr(); return new Ticker.Builder() .currencyPair(new CurrencyPair(BTC, Currency.TRY)) .last(last) .bid(highestBid) .ask(lowestAsk) .high(high24hr) .low(low24hr) .volume(volume) .build(); } return null; }
[ "public", "static", "Ticker", "adaptTicker", "(", "ParibuTicker", "paribuTicker", ",", "CurrencyPair", "currencyPair", ")", "{", "if", "(", "!", "currencyPair", ".", "equals", "(", "new", "CurrencyPair", "(", "BTC", ",", "TRY", ")", ")", ")", "{", "throw", ...
Adapts a ParibuTicker to a Ticker Object @param paribuTicker The exchange specific ticker @param currencyPair @return The ticker
[ "Adapts", "a", "ParibuTicker", "to", "a", "Ticker", "Object" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-paribu/src/main/java/org/knowm/xchange/paribu/ParibuAdapters.java#L26-L49
sstrickx/yahoofinance-api
src/main/java/yahoofinance/YahooFinance.java
YahooFinance.getFx
public static Map<String, FxQuote> getFx(String[] symbols) throws IOException { List<FxQuote> quotes; if(YahooFinance.QUOTES_QUERY1V7_ENABLED.equalsIgnoreCase("true")) { FxQuotesQuery1V7Request request = new FxQuotesQuery1V7Request(Utils.join(symbols, ",")); quotes = request.getResult(); } else { FxQuotesRequest request = new FxQuotesRequest(Utils.join(symbols, ",")); quotes = request.getResult(); } Map<String, FxQuote> result = new HashMap<String, FxQuote>(); for(FxQuote quote : quotes) { result.put(quote.getSymbol(), quote); } return result; }
java
public static Map<String, FxQuote> getFx(String[] symbols) throws IOException { List<FxQuote> quotes; if(YahooFinance.QUOTES_QUERY1V7_ENABLED.equalsIgnoreCase("true")) { FxQuotesQuery1V7Request request = new FxQuotesQuery1V7Request(Utils.join(symbols, ",")); quotes = request.getResult(); } else { FxQuotesRequest request = new FxQuotesRequest(Utils.join(symbols, ",")); quotes = request.getResult(); } Map<String, FxQuote> result = new HashMap<String, FxQuote>(); for(FxQuote quote : quotes) { result.put(quote.getSymbol(), quote); } return result; }
[ "public", "static", "Map", "<", "String", ",", "FxQuote", ">", "getFx", "(", "String", "[", "]", "symbols", ")", "throws", "IOException", "{", "List", "<", "FxQuote", ">", "quotes", ";", "if", "(", "YahooFinance", ".", "QUOTES_QUERY1V7_ENABLED", ".", "equa...
Sends a single request to Yahoo Finance to retrieve a quote for all the requested FX symbols. See <code>getFx(String)</code> for more information on the accepted FX symbols. @param symbols an array of FX symbols @return the requested FX symbols mapped to their respective quotes @throws java.io.IOException when there's a connection problem or the request is incorrect @see #getFx(java.lang.String)
[ "Sends", "a", "single", "request", "to", "Yahoo", "Finance", "to", "retrieve", "a", "quote", "for", "all", "the", "requested", "FX", "symbols", ".", "See", "<code", ">", "getFx", "(", "String", ")", "<", "/", "code", ">", "for", "more", "information", ...
train
https://github.com/sstrickx/yahoofinance-api/blob/2766ba52fc5cccf9b4da5c06423d68059cf0a6e6/src/main/java/yahoofinance/YahooFinance.java#L361-L375
UrielCh/ovh-java-sdk
ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java
ApiOvhHostingprivateDatabase.serviceName_PUT
public void serviceName_PUT(String serviceName, net.minidev.ovh.api.hosting.privatedatabase.OvhService body) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}"; StringBuilder sb = path(qPath, serviceName); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_PUT(String serviceName, net.minidev.ovh.api.hosting.privatedatabase.OvhService body) throws IOException { String qPath = "/hosting/privateDatabase/{serviceName}"; StringBuilder sb = path(qPath, serviceName); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_PUT", "(", "String", "serviceName", ",", "net", ".", "minidev", ".", "ovh", ".", "api", ".", "hosting", ".", "privatedatabase", ".", "OvhService", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/hosting/pri...
Alter this object properties REST: PUT /hosting/privateDatabase/{serviceName} @param body [required] New object properties @param serviceName [required] The internal name of your private database
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-hostingprivateDatabase/src/main/java/net/minidev/ovh/api/ApiOvhHostingprivateDatabase.java#L771-L775
b3log/latke
latke-core/src/main/java/org/b3log/latke/Latkes.java
Latkes.setLocalProperty
public static void setLocalProperty(final String key, final String value) { if (null == key) { LOGGER.log(Level.WARN, "local.props can not set null key"); return; } if (null == value) { LOGGER.log(Level.WARN, "local.props can not set null value"); return; } localProps.setProperty(key, value); }
java
public static void setLocalProperty(final String key, final String value) { if (null == key) { LOGGER.log(Level.WARN, "local.props can not set null key"); return; } if (null == value) { LOGGER.log(Level.WARN, "local.props can not set null value"); return; } localProps.setProperty(key, value); }
[ "public", "static", "void", "setLocalProperty", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "if", "(", "null", "==", "key", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "WARN", ",", "\"local.props can not set null key\"", ...
Sets local.props with the specified key and value. @param key the specified key @param value the specified value
[ "Sets", "local", ".", "props", "with", "the", "specified", "key", "and", "value", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L148-L161
Azure/azure-sdk-for-java
dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/RecordSetsInner.java
RecordSetsInner.listAllByDnsZoneWithServiceResponseAsync
public Observable<ServiceResponse<Page<RecordSetInner>>> listAllByDnsZoneWithServiceResponseAsync(final String resourceGroupName, final String zoneName, final Integer top, final String recordSetNameSuffix) { return listAllByDnsZoneSinglePageAsync(resourceGroupName, zoneName, top, recordSetNameSuffix) .concatMap(new Func1<ServiceResponse<Page<RecordSetInner>>, Observable<ServiceResponse<Page<RecordSetInner>>>>() { @Override public Observable<ServiceResponse<Page<RecordSetInner>>> call(ServiceResponse<Page<RecordSetInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listAllByDnsZoneNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<RecordSetInner>>> listAllByDnsZoneWithServiceResponseAsync(final String resourceGroupName, final String zoneName, final Integer top, final String recordSetNameSuffix) { return listAllByDnsZoneSinglePageAsync(resourceGroupName, zoneName, top, recordSetNameSuffix) .concatMap(new Func1<ServiceResponse<Page<RecordSetInner>>, Observable<ServiceResponse<Page<RecordSetInner>>>>() { @Override public Observable<ServiceResponse<Page<RecordSetInner>>> call(ServiceResponse<Page<RecordSetInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listAllByDnsZoneNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "RecordSetInner", ">", ">", ">", "listAllByDnsZoneWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "zoneName", ",", "final", "Integer", "top", ",", "fina...
Lists all record sets in a DNS zone. @param resourceGroupName The name of the resource group. @param zoneName The name of the DNS zone (without a terminating dot). @param top The maximum number of record sets to return. If not specified, returns up to 100 record sets. @param recordSetNameSuffix The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt; @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;RecordSetInner&gt; object
[ "Lists", "all", "record", "sets", "in", "a", "DNS", "zone", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/dns/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/dns/v2017_10_01/implementation/RecordSetsInner.java#L1550-L1562
groovy/groovy-core
src/main/org/codehaus/groovy/transform/trait/TraitComposer.java
TraitComposer.findDefaultMethodFromInterface
private static MethodNode findDefaultMethodFromInterface(final ClassNode cNode, final String name, final Parameter[] params) { if (cNode == null) { return null; } if (cNode.isInterface()) { MethodNode method = cNode.getMethod(name, params); if (method!=null && !method.isAbstract()) { // this is a Java 8 only behavior! return method; } } ClassNode[] interfaces = cNode.getInterfaces(); for (ClassNode anInterface : interfaces) { MethodNode res = findDefaultMethodFromInterface(anInterface, name, params); if (res!=null) { return res; } } return findDefaultMethodFromInterface(cNode.getSuperClass(), name, params); }
java
private static MethodNode findDefaultMethodFromInterface(final ClassNode cNode, final String name, final Parameter[] params) { if (cNode == null) { return null; } if (cNode.isInterface()) { MethodNode method = cNode.getMethod(name, params); if (method!=null && !method.isAbstract()) { // this is a Java 8 only behavior! return method; } } ClassNode[] interfaces = cNode.getInterfaces(); for (ClassNode anInterface : interfaces) { MethodNode res = findDefaultMethodFromInterface(anInterface, name, params); if (res!=null) { return res; } } return findDefaultMethodFromInterface(cNode.getSuperClass(), name, params); }
[ "private", "static", "MethodNode", "findDefaultMethodFromInterface", "(", "final", "ClassNode", "cNode", ",", "final", "String", "name", ",", "final", "Parameter", "[", "]", "params", ")", "{", "if", "(", "cNode", "==", "null", ")", "{", "return", "null", ";...
An utility method which tries to find a method with default implementation (in the Java 8 semantics). @param cNode a class node @param name the name of the method @param params the parameters of the method @return a method node corresponding to a default method if it exists
[ "An", "utility", "method", "which", "tries", "to", "find", "a", "method", "with", "default", "implementation", "(", "in", "the", "Java", "8", "semantics", ")", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/trait/TraitComposer.java#L500-L519
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/Script.java
Script.addExportable
public void addExportable(String name, BtrpOperand e, Set<String> scopes) { this.exported.put(name, e); this.exportScopes.put(name, scopes); }
java
public void addExportable(String name, BtrpOperand e, Set<String> scopes) { this.exported.put(name, e); this.exportScopes.put(name, scopes); }
[ "public", "void", "addExportable", "(", "String", "name", ",", "BtrpOperand", "e", ",", "Set", "<", "String", ">", "scopes", ")", "{", "this", ".", "exported", ".", "put", "(", "name", ",", "e", ")", ";", "this", ".", "exportScopes", ".", "put", "(",...
Add an external operand that can be accessed from several given scopes. A scope is a namespace that can ends with a wildcard ('*'). In this situation. The beginning of the scope is considered @param name the name of the exported operand @param e the operand to add @param scopes the namespaces of the scripts that can use this variable. {@code null} to allow anyone
[ "Add", "an", "external", "operand", "that", "can", "be", "accessed", "from", "several", "given", "scopes", ".", "A", "scope", "is", "a", "namespace", "that", "can", "ends", "with", "a", "wildcard", "(", "*", ")", ".", "In", "this", "situation", ".", "T...
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/Script.java#L276-L279
apptik/jus
android/jus-android/src/main/java/io/apptik/comm/jus/util/DefaultBitmapLruCache.java
DefaultBitmapLruCache.sizeOf
@Override protected int sizeOf(String key, Bitmap value) { final int bitmapSize = BitmapLruPool.getBitmapSize(value); return bitmapSize == 0 ? 1 : bitmapSize; }
java
@Override protected int sizeOf(String key, Bitmap value) { final int bitmapSize = BitmapLruPool.getBitmapSize(value); return bitmapSize == 0 ? 1 : bitmapSize; }
[ "@", "Override", "protected", "int", "sizeOf", "(", "String", "key", ",", "Bitmap", "value", ")", "{", "final", "int", "bitmapSize", "=", "BitmapLruPool", ".", "getBitmapSize", "(", "value", ")", ";", "return", "bitmapSize", "==", "0", "?", "1", ":", "bi...
Measure item size in kilobytes rather than units which is more practical for a bitmap cache
[ "Measure", "item", "size", "in", "kilobytes", "rather", "than", "units", "which", "is", "more", "practical", "for", "a", "bitmap", "cache" ]
train
https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/android/jus-android/src/main/java/io/apptik/comm/jus/util/DefaultBitmapLruCache.java#L80-L84
infinispan/infinispan
server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java
HotRodServer.toMillis
private static long toMillis(long duration, TimeUnitValue unit) { if (duration > 0) { long milliseconds = unit.toTimeUnit().toMillis(duration); if (milliseconds > MILLISECONDS_IN_30_DAYS) { long unixTimeExpiry = milliseconds - System.currentTimeMillis(); return unixTimeExpiry < 0 ? 0 : unixTimeExpiry; } else { return milliseconds; } } else { return duration; } }
java
private static long toMillis(long duration, TimeUnitValue unit) { if (duration > 0) { long milliseconds = unit.toTimeUnit().toMillis(duration); if (milliseconds > MILLISECONDS_IN_30_DAYS) { long unixTimeExpiry = milliseconds - System.currentTimeMillis(); return unixTimeExpiry < 0 ? 0 : unixTimeExpiry; } else { return milliseconds; } } else { return duration; } }
[ "private", "static", "long", "toMillis", "(", "long", "duration", ",", "TimeUnitValue", "unit", ")", "{", "if", "(", "duration", ">", "0", ")", "{", "long", "milliseconds", "=", "unit", ".", "toTimeUnit", "(", ")", ".", "toMillis", "(", "duration", ")", ...
Transforms lifespan pass as seconds into milliseconds following this rule (inspired by Memcached): <p> If lifespan is bigger than number of seconds in 30 days, then it is considered unix time. After converting it to milliseconds, we subtract the current time in and the result is returned. <p> Otherwise it's just considered number of seconds from now and it's returned in milliseconds unit.
[ "Transforms", "lifespan", "pass", "as", "seconds", "into", "milliseconds", "following", "this", "rule", "(", "inspired", "by", "Memcached", ")", ":", "<p", ">", "If", "lifespan", "is", "bigger", "than", "number", "of", "seconds", "in", "30", "days", "then", ...
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/server/hotrod/src/main/java/org/infinispan/server/hotrod/HotRodServer.java#L607-L619
nyla-solutions/nyla
nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java
Organizer.makeCopies
@SuppressWarnings( { "unchecked", "rawtypes" }) public static void makeCopies(Collection<Copier> aFrom, Collection<Copier> aTo) { if (aFrom == null || aTo == null) return; List<Copier> fromList = new ArrayList<Copier>(aFrom); List<Copier> toList = new ArrayList<Copier>(aTo); Collections.sort((List) fromList); Collections.sort((List) toList); Copier from = null; Copier to = null; Iterator<Copier> toIter = toList.iterator(); for (Iterator<Copier> i = fromList.iterator(); i.hasNext() && toIter.hasNext();) { from = (Copier) i.next(); to = (Copier) toIter.next(); // copy data to.copy(from); } }
java
@SuppressWarnings( { "unchecked", "rawtypes" }) public static void makeCopies(Collection<Copier> aFrom, Collection<Copier> aTo) { if (aFrom == null || aTo == null) return; List<Copier> fromList = new ArrayList<Copier>(aFrom); List<Copier> toList = new ArrayList<Copier>(aTo); Collections.sort((List) fromList); Collections.sort((List) toList); Copier from = null; Copier to = null; Iterator<Copier> toIter = toList.iterator(); for (Iterator<Copier> i = fromList.iterator(); i.hasNext() && toIter.hasNext();) { from = (Copier) i.next(); to = (Copier) toIter.next(); // copy data to.copy(from); } }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "static", "void", "makeCopies", "(", "Collection", "<", "Copier", ">", "aFrom", ",", "Collection", "<", "Copier", ">", "aTo", ")", "{", "if", "(", "aFrom", "==", ...
Copy data from object to object @param aFrom the object to copy from @param aTo the object to copy to
[ "Copy", "data", "from", "object", "to", "object" ]
train
https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java#L845-L868
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/JobScheduler.java
JobScheduler.scheduleJob
public void scheduleJob(Properties jobProps, JobListener jobListener, Map<String, Object> additionalJobData, Class<? extends Job> jobClass) throws JobException { Preconditions.checkArgument(jobProps.containsKey(ConfigurationKeys.JOB_NAME_KEY), "A job must have a job name specified by job.name"); String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY); if (this.scheduledJobs.containsKey(jobName)) { LOG.info("Job " + jobName + " was already scheduled, un-scheduling it now."); unscheduleJob(jobName); } // Check if the job has been disabled boolean disabled = Boolean.valueOf(jobProps.getProperty(ConfigurationKeys.JOB_DISABLED_KEY, "false")); if (disabled) { LOG.info("Skipping disabled job " + jobName); return; } if (!jobProps.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) { // Submit the job to run this.jobExecutor.execute(new NonScheduledJobRunner(jobProps, jobListener)); return; } if (jobListener != null) { this.jobListenerMap.put(jobName, jobListener); } // Build a data map that gets passed to the job JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(JOB_SCHEDULER_KEY, this); jobDataMap.put(PROPERTIES_KEY, jobProps); jobDataMap.put(JOB_LISTENER_KEY, jobListener); jobDataMap.putAll(additionalJobData); // Build a Quartz job JobDetail job = JobBuilder.newJob(jobClass) .withIdentity(jobName, Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY))) .withDescription(Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_DESCRIPTION_KEY))) .usingJobData(jobDataMap) .build(); try { // Schedule the Quartz job with a trigger built from the job configuration Trigger trigger = getTrigger(job.getKey(), jobProps); this.scheduler.getScheduler().scheduleJob(job, trigger); LOG.info(String.format("Scheduled job %s. Next run: %s.", job.getKey(), trigger.getNextFireTime())); } catch (SchedulerException se) { LOG.error("Failed to schedule job " + jobName, se); throw new JobException("Failed to schedule job " + jobName, se); } this.scheduledJobs.put(jobName, job.getKey()); }
java
public void scheduleJob(Properties jobProps, JobListener jobListener, Map<String, Object> additionalJobData, Class<? extends Job> jobClass) throws JobException { Preconditions.checkArgument(jobProps.containsKey(ConfigurationKeys.JOB_NAME_KEY), "A job must have a job name specified by job.name"); String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY); if (this.scheduledJobs.containsKey(jobName)) { LOG.info("Job " + jobName + " was already scheduled, un-scheduling it now."); unscheduleJob(jobName); } // Check if the job has been disabled boolean disabled = Boolean.valueOf(jobProps.getProperty(ConfigurationKeys.JOB_DISABLED_KEY, "false")); if (disabled) { LOG.info("Skipping disabled job " + jobName); return; } if (!jobProps.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) { // Submit the job to run this.jobExecutor.execute(new NonScheduledJobRunner(jobProps, jobListener)); return; } if (jobListener != null) { this.jobListenerMap.put(jobName, jobListener); } // Build a data map that gets passed to the job JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(JOB_SCHEDULER_KEY, this); jobDataMap.put(PROPERTIES_KEY, jobProps); jobDataMap.put(JOB_LISTENER_KEY, jobListener); jobDataMap.putAll(additionalJobData); // Build a Quartz job JobDetail job = JobBuilder.newJob(jobClass) .withIdentity(jobName, Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_GROUP_KEY))) .withDescription(Strings.nullToEmpty(jobProps.getProperty(ConfigurationKeys.JOB_DESCRIPTION_KEY))) .usingJobData(jobDataMap) .build(); try { // Schedule the Quartz job with a trigger built from the job configuration Trigger trigger = getTrigger(job.getKey(), jobProps); this.scheduler.getScheduler().scheduleJob(job, trigger); LOG.info(String.format("Scheduled job %s. Next run: %s.", job.getKey(), trigger.getNextFireTime())); } catch (SchedulerException se) { LOG.error("Failed to schedule job " + jobName, se); throw new JobException("Failed to schedule job " + jobName, se); } this.scheduledJobs.put(jobName, job.getKey()); }
[ "public", "void", "scheduleJob", "(", "Properties", "jobProps", ",", "JobListener", "jobListener", ",", "Map", "<", "String", ",", "Object", ">", "additionalJobData", ",", "Class", "<", "?", "extends", "Job", ">", "jobClass", ")", "throws", "JobException", "{"...
Schedule a job. <p> This method does what {@link #scheduleJob(Properties, JobListener)} does, and additionally it allows the caller to pass in additional job data and the {@link Job} implementation class. </p> @param jobProps Job configuration properties @param jobListener {@link JobListener} used for callback, can be <em>null</em> if no callback is needed. @param additionalJobData additional job data in a {@link Map} @param jobClass Quartz job class @throws JobException when there is anything wrong with scheduling the job
[ "Schedule", "a", "job", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/JobScheduler.java#L346-L400
mgormley/agiga
src/main/java/edu/jhu/agiga/AgigaSentenceReader.java
AgigaSentenceReader.getElementFragmentAsString
public static String getElementFragmentAsString(byte[] b, VTDNav vn) throws NavException { long l = vn.getElementFragment(); int offset = (int) l; int len = (int) (l >> 32); String elementFragment = new String(Arrays.copyOfRange(b, offset, offset + len)); return elementFragment; }
java
public static String getElementFragmentAsString(byte[] b, VTDNav vn) throws NavException { long l = vn.getElementFragment(); int offset = (int) l; int len = (int) (l >> 32); String elementFragment = new String(Arrays.copyOfRange(b, offset, offset + len)); return elementFragment; }
[ "public", "static", "String", "getElementFragmentAsString", "(", "byte", "[", "]", "b", ",", "VTDNav", "vn", ")", "throws", "NavException", "{", "long", "l", "=", "vn", ".", "getElementFragment", "(", ")", ";", "int", "offset", "=", "(", "int", ")", "l",...
This method will print out the XML from the current position of <code>vn</code>. Very useful for debugging.
[ "This", "method", "will", "print", "out", "the", "XML", "from", "the", "current", "position", "of", "<code", ">", "vn<", "/", "code", ">", ".", "Very", "useful", "for", "debugging", "." ]
train
https://github.com/mgormley/agiga/blob/d61db78e3fa9d2470122d869a9ab798cb07eea3b/src/main/java/edu/jhu/agiga/AgigaSentenceReader.java#L348-L354
baratine/baratine
core/src/main/java/com/caucho/v5/ramp/pipe/PipeNode.java
PipeNode.send
@Override public void send(T value, Result<Void> result) { /* if (! init() && pendingSend(value, result)) { return; } */ send(value); result.ok(null); }
java
@Override public void send(T value, Result<Void> result) { /* if (! init() && pendingSend(value, result)) { return; } */ send(value); result.ok(null); }
[ "@", "Override", "public", "void", "send", "(", "T", "value", ",", "Result", "<", "Void", ">", "result", ")", "{", "/*\n if (! init() && pendingSend(value, result)) {\n return;\n }\n */", "send", "(", "value", ")", ";", "result", ".", "ok", "(", "nul...
/* private boolean pendingPublish(ResultPipeOut<T> result) { if (_init == StateInit.INIT) { return false; } _pendingInit.add(()->publish(result)); return true; }
[ "/", "*", "private", "boolean", "pendingPublish", "(", "ResultPipeOut<T", ">", "result", ")", "{", "if", "(", "_init", "==", "StateInit", ".", "INIT", ")", "{", "return", "false", ";", "}" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/core/src/main/java/com/caucho/v5/ramp/pipe/PipeNode.java#L129-L141
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/ReflectionUtils.java
ReflectionUtils.invokeMethod
public static Object invokeMethod(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (InvocationTargetException | IllegalAccessException e) { throw new IllegalStateException("Could not access method: " + method, ExceptionUtils.getRootCause(e)); } }
java
public static Object invokeMethod(Method method, Object target, Object... args) { try { return method.invoke(target, args); } catch (InvocationTargetException | IllegalAccessException e) { throw new IllegalStateException("Could not access method: " + method, ExceptionUtils.getRootCause(e)); } }
[ "public", "static", "Object", "invokeMethod", "(", "Method", "method", ",", "Object", "target", ",", "Object", "...", "args", ")", "{", "try", "{", "return", "method", ".", "invoke", "(", "target", ",", "args", ")", ";", "}", "catch", "(", "InvocationTar...
Invoke the specified {@link Method} against the supplied target object with the supplied arguments. The target object can be {@code null} when invoking a static {@link Method}. @param method the method to invoke @param target the target object to invoke the method on @param args the invocation arguments (may be {@code null}) @return the invocation result, if any
[ "Invoke", "the", "specified", "{", "@link", "Method", "}", "against", "the", "supplied", "target", "object", "with", "the", "supplied", "arguments", ".", "The", "target", "object", "can", "be", "{", "@code", "null", "}", "when", "invoking", "a", "static", ...
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ReflectionUtils.java#L76-L82
jayantk/jklol
src/com/jayantkrish/jklol/lisp/LispUtil.java
LispUtil.checkNotNull
public static void checkNotNull(Object ref, String message, Object ... values) { if (ref == null) { throw new EvalError(String.format(message, values)); } }
java
public static void checkNotNull(Object ref, String message, Object ... values) { if (ref == null) { throw new EvalError(String.format(message, values)); } }
[ "public", "static", "void", "checkNotNull", "(", "Object", "ref", ",", "String", "message", ",", "Object", "...", "values", ")", "{", "if", "(", "ref", "==", "null", ")", "{", "throw", "new", "EvalError", "(", "String", ".", "format", "(", "message", "...
Identical to Preconditions.checkNotNull but throws an {@code EvalError} instead of an IllegalArgumentException. Use this check to verify properties of a Lisp program execution, i.e., whenever the raised exception should be catchable by the evaluator of the program. @param condition @param message @param values
[ "Identical", "to", "Preconditions", ".", "checkNotNull", "but", "throws", "an", "{", "@code", "EvalError", "}", "instead", "of", "an", "IllegalArgumentException", ".", "Use", "this", "check", "to", "verify", "properties", "of", "a", "Lisp", "program", "execution...
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/lisp/LispUtil.java#L77-L81
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/process/LinearInterpolatedTimeDiscreteProcess.java
LinearInterpolatedTimeDiscreteProcess.add
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException { Map<Double, RandomVariable> sum = new HashMap<>(); for(double time: timeDiscretization) { sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0))); } return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum); }
java
public LinearInterpolatedTimeDiscreteProcess add(LinearInterpolatedTimeDiscreteProcess process) throws CalculationException { Map<Double, RandomVariable> sum = new HashMap<>(); for(double time: timeDiscretization) { sum.put(time, realizations.get(time).add(process.getProcessValue(time, 0))); } return new LinearInterpolatedTimeDiscreteProcess(timeDiscretization, sum); }
[ "public", "LinearInterpolatedTimeDiscreteProcess", "add", "(", "LinearInterpolatedTimeDiscreteProcess", "process", ")", "throws", "CalculationException", "{", "Map", "<", "Double", ",", "RandomVariable", ">", "sum", "=", "new", "HashMap", "<>", "(", ")", ";", "for", ...
Create a new linear interpolated time discrete process by using the time discretization of this process and the sum of this process and the given one as its values. @param process A given process. @return A new process representing the of this and the given process. @throws CalculationException Thrown if the given process fails to evaluate at a certain time point.
[ "Create", "a", "new", "linear", "interpolated", "time", "discrete", "process", "by", "using", "the", "time", "discretization", "of", "this", "process", "and", "the", "sum", "of", "this", "process", "and", "the", "given", "one", "as", "its", "values", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/process/LinearInterpolatedTimeDiscreteProcess.java#L70-L78
FedericoPecora/meta-csp-framework
src/main/java/org/metacsp/multi/activity/ActivityNetworkSolver.java
ActivityNetworkSolver.drawAsGantt
public void drawAsGantt( String varsMatchingThis ) { Vector<String> selectedVariables = new Vector<String>(); for ( Variable v : this.getVariables() ) { if ( v.getComponent().contains(varsMatchingThis)) { selectedVariables.add(v.getComponent()); } } new PlotActivityNetworkGantt(this, selectedVariables, "Activity Network Gantt"); }
java
public void drawAsGantt( String varsMatchingThis ) { Vector<String> selectedVariables = new Vector<String>(); for ( Variable v : this.getVariables() ) { if ( v.getComponent().contains(varsMatchingThis)) { selectedVariables.add(v.getComponent()); } } new PlotActivityNetworkGantt(this, selectedVariables, "Activity Network Gantt"); }
[ "public", "void", "drawAsGantt", "(", "String", "varsMatchingThis", ")", "{", "Vector", "<", "String", ">", "selectedVariables", "=", "new", "Vector", "<", "String", ">", "(", ")", ";", "for", "(", "Variable", "v", ":", "this", ".", "getVariables", "(", ...
Draw variables matching this {@link String} on Gantt chart @param varsMatchingThis {@link String} that must be contained in a variable to be plotted
[ "Draw", "variables", "matching", "this", "{" ]
train
https://github.com/FedericoPecora/meta-csp-framework/blob/42aaef2e2b76d0f738427f0dd9653c4f62b40517/src/main/java/org/metacsp/multi/activity/ActivityNetworkSolver.java#L143-L151
mcxiaoke/Android-Next
recycler/src/main/java/com/mcxiaoke/next/recycler/AdvancedRecyclerArrayAdapter.java
AdvancedRecyclerArrayAdapter.isItemTheSame
public boolean isItemTheSame(@Nullable final T oldItem, @Nullable final T newItem) { if (oldItem == null && newItem == null) { return true; } if (oldItem == null || newItem == null) { return false; } final Object oldId = getItemId(oldItem); final Object newId = getItemId(newItem); return (oldId == newId) || (oldId != null && oldId.equals(newId)); }
java
public boolean isItemTheSame(@Nullable final T oldItem, @Nullable final T newItem) { if (oldItem == null && newItem == null) { return true; } if (oldItem == null || newItem == null) { return false; } final Object oldId = getItemId(oldItem); final Object newId = getItemId(newItem); return (oldId == newId) || (oldId != null && oldId.equals(newId)); }
[ "public", "boolean", "isItemTheSame", "(", "@", "Nullable", "final", "T", "oldItem", ",", "@", "Nullable", "final", "T", "newItem", ")", "{", "if", "(", "oldItem", "==", "null", "&&", "newItem", "==", "null", ")", "{", "return", "true", ";", "}", "if",...
Called by the DiffUtil to decide whether two object represent the same Item. <p> For example, if your items have unique ids, this method should check their id equality. @param oldItem The position of the item in the old list @param newItem The position of the item in the new list @return True if the two items represent the same object or false if they are different. @see #getItemId(Object)
[ "Called", "by", "the", "DiffUtil", "to", "decide", "whether", "two", "object", "represent", "the", "same", "Item", ".", "<p", ">", "For", "example", "if", "your", "items", "have", "unique", "ids", "this", "method", "should", "check", "their", "id", "equali...
train
https://github.com/mcxiaoke/Android-Next/blob/1bfdf99d0b81a849aa0fa6697c53ed673151ca39/recycler/src/main/java/com/mcxiaoke/next/recycler/AdvancedRecyclerArrayAdapter.java#L245-L258
OpenLiberty/open-liberty
dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/impl/BatchKernelImpl.java
BatchKernelImpl.publishEvent
private void publishEvent(WSJobExecution objectToPublish, String eventToPublishTo, String correlationId) { if (eventsPublisher != null) { eventsPublisher.publishJobExecutionEvent(objectToPublish, eventToPublishTo, correlationId); } }
java
private void publishEvent(WSJobExecution objectToPublish, String eventToPublishTo, String correlationId) { if (eventsPublisher != null) { eventsPublisher.publishJobExecutionEvent(objectToPublish, eventToPublishTo, correlationId); } }
[ "private", "void", "publishEvent", "(", "WSJobExecution", "objectToPublish", ",", "String", "eventToPublishTo", ",", "String", "correlationId", ")", "{", "if", "(", "eventsPublisher", "!=", "null", ")", "{", "eventsPublisher", ".", "publishJobExecutionEvent", "(", "...
Publish jms topic if batch jms event is available @param objectToPublish WSJobInstance @param eventToPublish
[ "Publish", "jms", "topic", "if", "batch", "jms", "event", "is", "available" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.jbatch.container/src/com/ibm/jbatch/container/impl/BatchKernelImpl.java#L294-L298
kohsuke/com4j
runtime/src/main/java/com4j/Variant.java
Variant.toDate
static Date toDate(double d) { GregorianCalendar ret = new GregorianCalendar(1899,11,30); int days = (int)d; d -= days; ret.add(Calendar.DATE,days); d *= 24; int hours = (int)d; ret.add(Calendar.HOUR,hours); d -= hours; d *= 60; // d += 0.5; // round int min = (int)d; ret.add(Calendar.MINUTE,min); d -= min; d *= 60; int secs = (int) d; ret.add(Calendar.SECOND, secs); return ret.getTime(); }
java
static Date toDate(double d) { GregorianCalendar ret = new GregorianCalendar(1899,11,30); int days = (int)d; d -= days; ret.add(Calendar.DATE,days); d *= 24; int hours = (int)d; ret.add(Calendar.HOUR,hours); d -= hours; d *= 60; // d += 0.5; // round int min = (int)d; ret.add(Calendar.MINUTE,min); d -= min; d *= 60; int secs = (int) d; ret.add(Calendar.SECOND, secs); return ret.getTime(); }
[ "static", "Date", "toDate", "(", "double", "d", ")", "{", "GregorianCalendar", "ret", "=", "new", "GregorianCalendar", "(", "1899", ",", "11", ",", "30", ")", ";", "int", "days", "=", "(", "int", ")", "d", ";", "d", "-=", "days", ";", "ret", ".", ...
Called from the native code to assist VT_DATE -> Date conversion.
[ "Called", "from", "the", "native", "code", "to", "assist", "VT_DATE", "-", ">", "Date", "conversion", "." ]
train
https://github.com/kohsuke/com4j/blob/1e690b805fb0e4e9ef61560e20a56335aecb0b24/runtime/src/main/java/com4j/Variant.java#L800-L820
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.putShapeForVarName
@Deprecated public void putShapeForVarName(String varName, long[] shape) { if (shape == null) { throw new ND4JIllegalStateException("Shape must not be null!"); } if (variableNameToShape.containsKey(varName)) { throw new ND4JIllegalStateException("Shape for " + varName + " already exists!"); } variableNameToShape.put(varName, shape); }
java
@Deprecated public void putShapeForVarName(String varName, long[] shape) { if (shape == null) { throw new ND4JIllegalStateException("Shape must not be null!"); } if (variableNameToShape.containsKey(varName)) { throw new ND4JIllegalStateException("Shape for " + varName + " already exists!"); } variableNameToShape.put(varName, shape); }
[ "@", "Deprecated", "public", "void", "putShapeForVarName", "(", "String", "varName", ",", "long", "[", "]", "shape", ")", "{", "if", "(", "shape", "==", "null", ")", "{", "throw", "new", "ND4JIllegalStateException", "(", "\"Shape must not be null!\"", ")", ";"...
Associate a vertex id with the given shape. @param varName the vertex id to associate @param shape the shape to associate with @see #putShapeForVarName(String, long[]) @see #putOrUpdateShapeForVarName(String, long[], boolean)
[ "Associate", "a", "vertex", "id", "with", "the", "given", "shape", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L661-L672
jayantk/jklol
src/com/jayantkrish/jklol/ccg/HeadedSyntacticCategory.java
HeadedSyntacticCategory.getCanonicalForm
public HeadedSyntacticCategory getCanonicalForm(Map<Integer, Integer> relabeling) { Preconditions.checkArgument(relabeling.size() == 0); int[] relabeledVariables = canonicalizeVariableArray(semanticVariables, relabeling); return new HeadedSyntacticCategory(syntacticCategory.getCanonicalForm(), relabeledVariables, rootIndex); }
java
public HeadedSyntacticCategory getCanonicalForm(Map<Integer, Integer> relabeling) { Preconditions.checkArgument(relabeling.size() == 0); int[] relabeledVariables = canonicalizeVariableArray(semanticVariables, relabeling); return new HeadedSyntacticCategory(syntacticCategory.getCanonicalForm(), relabeledVariables, rootIndex); }
[ "public", "HeadedSyntacticCategory", "getCanonicalForm", "(", "Map", "<", "Integer", ",", "Integer", ">", "relabeling", ")", "{", "Preconditions", ".", "checkArgument", "(", "relabeling", ".", "size", "(", ")", "==", "0", ")", ";", "int", "[", "]", "relabele...
Gets a canonical representation of this category that treats each variable number as an equivalence class. The canonical form relabels variables in the category such that all categories with the same variable equivalence relations have the same canonical form. @param relabeling the relabeling applied to variables in this to produce the relabeled category. @return
[ "Gets", "a", "canonical", "representation", "of", "this", "category", "that", "treats", "each", "variable", "number", "as", "an", "equivalence", "class", ".", "The", "canonical", "form", "relabels", "variables", "in", "the", "category", "such", "that", "all", ...
train
https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/HeadedSyntacticCategory.java#L217-L221
canoo/dolphin-platform
platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/gc/GarbageCollector.java
GarbageCollector.onAddedToList
public synchronized void onAddedToList(ObservableList list, Object value) { if (!configuration.isUseGc()) { return; } if (value != null && DolphinUtils.isDolphinBean(value.getClass())) { Instance instance = getInstance(value); Reference reference = new ListReference(listToParent.get(list), list, instance); if (reference.hasCircularReference()) { throw new CircularDependencyException("Circular dependency detected!"); } instance.getReferences().add(reference); removeFromGC(instance); } }
java
public synchronized void onAddedToList(ObservableList list, Object value) { if (!configuration.isUseGc()) { return; } if (value != null && DolphinUtils.isDolphinBean(value.getClass())) { Instance instance = getInstance(value); Reference reference = new ListReference(listToParent.get(list), list, instance); if (reference.hasCircularReference()) { throw new CircularDependencyException("Circular dependency detected!"); } instance.getReferences().add(reference); removeFromGC(instance); } }
[ "public", "synchronized", "void", "onAddedToList", "(", "ObservableList", "list", ",", "Object", "value", ")", "{", "if", "(", "!", "configuration", ".", "isUseGc", "(", ")", ")", "{", "return", ";", "}", "if", "(", "value", "!=", "null", "&&", "DolphinU...
This method must be called for each item that is added to a {@link ObservableList} that is part of a Dolphin bean (see {@link RemotingBean}) @param list the list @param value the added item
[ "This", "method", "must", "be", "called", "for", "each", "item", "that", "is", "added", "to", "a", "{", "@link", "ObservableList", "}", "that", "is", "part", "of", "a", "Dolphin", "bean", "(", "see", "{", "@link", "RemotingBean", "}", ")" ]
train
https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-remoting-server/src/main/java/com/canoo/dp/impl/server/gc/GarbageCollector.java#L172-L185
eclipse/xtext-core
org.eclipse.xtext/xtend-gen/org/eclipse/xtext/resource/persistence/ResourceStorageLoadable.java
ResourceStorageLoadable.loadEntries
protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException { zipIn.getNextEntry(); BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn); this.readContents(resource, _bufferedInputStream); zipIn.getNextEntry(); BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn); this.readResourceDescription(resource, _bufferedInputStream_1); if (this.storeNodeModel) { zipIn.getNextEntry(); BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn); this.readNodeModel(resource, _bufferedInputStream_2); } }
java
protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException { zipIn.getNextEntry(); BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn); this.readContents(resource, _bufferedInputStream); zipIn.getNextEntry(); BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn); this.readResourceDescription(resource, _bufferedInputStream_1); if (this.storeNodeModel) { zipIn.getNextEntry(); BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn); this.readNodeModel(resource, _bufferedInputStream_2); } }
[ "protected", "void", "loadEntries", "(", "final", "StorageAwareResource", "resource", ",", "final", "ZipInputStream", "zipIn", ")", "throws", "IOException", "{", "zipIn", ".", "getNextEntry", "(", ")", ";", "BufferedInputStream", "_bufferedInputStream", "=", "new", ...
Load entries from the storage. Overriding methods should first delegate to super before adding their own entries.
[ "Load", "entries", "from", "the", "storage", ".", "Overriding", "methods", "should", "first", "delegate", "to", "super", "before", "adding", "their", "own", "entries", "." ]
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/resource/persistence/ResourceStorageLoadable.java#L64-L76
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/ProxiedTrash.java
ProxiedTrash.moveToTrashAsUser
@Override public boolean moveToTrashAsUser(Path path, final String user) throws IOException { return getUserTrash(user).moveToTrash(path); }
java
@Override public boolean moveToTrashAsUser(Path path, final String user) throws IOException { return getUserTrash(user).moveToTrash(path); }
[ "@", "Override", "public", "boolean", "moveToTrashAsUser", "(", "Path", "path", ",", "final", "String", "user", ")", "throws", "IOException", "{", "return", "getUserTrash", "(", "user", ")", ".", "moveToTrash", "(", "path", ")", ";", "}" ]
Move the path to trash as specified user. @param path {@link org.apache.hadoop.fs.Path} to move. @param user User to move the path as. @return true if the move succeeded. @throws IOException
[ "Move", "the", "path", "to", "trash", "as", "specified", "user", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/ProxiedTrash.java#L61-L64
vst/commons-math-extensions
src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java
EMatrixUtils.colSubtract
public static RealMatrix colSubtract (RealMatrix matrix, double[] vector) { // Declare and initialize the new matrix: double[][] retval = new double[matrix.getRowDimension()][matrix.getColumnDimension()]; // Iterate over rows: for (int col = 0; col < retval.length; col++) { // Iterate over columns: for (int row = 0; row < retval[0].length; row++) { retval[row][col] = matrix.getEntry(row, col) - vector[row]; } } // Done, return a new matrix: return MatrixUtils.createRealMatrix(retval); }
java
public static RealMatrix colSubtract (RealMatrix matrix, double[] vector) { // Declare and initialize the new matrix: double[][] retval = new double[matrix.getRowDimension()][matrix.getColumnDimension()]; // Iterate over rows: for (int col = 0; col < retval.length; col++) { // Iterate over columns: for (int row = 0; row < retval[0].length; row++) { retval[row][col] = matrix.getEntry(row, col) - vector[row]; } } // Done, return a new matrix: return MatrixUtils.createRealMatrix(retval); }
[ "public", "static", "RealMatrix", "colSubtract", "(", "RealMatrix", "matrix", ",", "double", "[", "]", "vector", ")", "{", "// Declare and initialize the new matrix:", "double", "[", "]", "[", "]", "retval", "=", "new", "double", "[", "matrix", ".", "getRowDimen...
Returns a new matrix by subtracting elements column by column. @param matrix The input matrix @param vector The vector to be subtracted from columns @return A new matrix of which the vector is subtracted column by column
[ "Returns", "a", "new", "matrix", "by", "subtracting", "elements", "column", "by", "column", "." ]
train
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/EMatrixUtils.java#L145-L159
jenkinsci/jenkins
core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java
HudsonPrivateSecurityRealm.createAccount
public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); user.addProperty(Details.fromPlainPassword(password)); SecurityListener.fireUserCreated(user.getId()); return user; }
java
public User createAccount(String userName, String password) throws IOException { User user = User.getById(userName, true); user.addProperty(Details.fromPlainPassword(password)); SecurityListener.fireUserCreated(user.getId()); return user; }
[ "public", "User", "createAccount", "(", "String", "userName", ",", "String", "password", ")", "throws", "IOException", "{", "User", "user", "=", "User", ".", "getById", "(", "userName", ",", "true", ")", ";", "user", ".", "addProperty", "(", "Details", "."...
Creates a new user account by registering a password to the user.
[ "Creates", "a", "new", "user", "account", "by", "registering", "a", "password", "to", "the", "user", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/HudsonPrivateSecurityRealm.java#L507-L512
boncey/Flickr4Java
src/main/java/com/flickr4java/flickr/util/UrlUtilities.java
UrlUtilities.buildPostUrl
public static URL buildPostUrl(String host, int port, String path) throws MalformedURLException { return buildPostUrl("http", host, port, path); }
java
public static URL buildPostUrl(String host, int port, String path) throws MalformedURLException { return buildPostUrl("http", host, port, path); }
[ "public", "static", "URL", "buildPostUrl", "(", "String", "host", ",", "int", "port", ",", "String", "path", ")", "throws", "MalformedURLException", "{", "return", "buildPostUrl", "(", "\"http\"", ",", "host", ",", "port", ",", "path", ")", ";", "}" ]
Build a POST URL with {@code http} scheme. @param host the host @param port the port @param path the path @return @throws MalformedURLException
[ "Build", "a", "POST", "URL", "with", "{" ]
train
https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/util/UrlUtilities.java#L150-L152
riversun/d6
src/main/java/org/riversun/d6/core/D6DateUtil.java
D6DateUtil.getSqlTime
public static java.sql.Time getSqlTime(int hour, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date(0)); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, second); cal.set(Calendar.MILLISECOND, 0); return getSqlTime(cal.getTime()); }
java
public static java.sql.Time getSqlTime(int hour, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date(0)); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, second); cal.set(Calendar.MILLISECOND, 0); return getSqlTime(cal.getTime()); }
[ "public", "static", "java", ".", "sql", ".", "Time", "getSqlTime", "(", "int", "hour", ",", "int", "minute", ",", "int", "second", ")", "{", "Calendar", "cal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "cal", ".", "setTime", "(", "new", "ja...
Get SQL Time(java.sql.Time) from supplied parameters @param hour @param minute @param second @return
[ "Get", "SQL", "Time", "(", "java", ".", "sql", ".", "Time", ")", "from", "supplied", "parameters" ]
train
https://github.com/riversun/d6/blob/2798bd876b9380dbfea8182d11ad306cb1b0e114/src/main/java/org/riversun/d6/core/D6DateUtil.java#L77-L86
infinispan/infinispan
commons/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java
UnsignedNumeric.readUnsignedLong
public static long readUnsignedLong(byte[] bytes, int offset) { byte b = bytes[offset++]; long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = bytes[offset++]; i |= (b & 0x7FL) << shift; } return i; }
java
public static long readUnsignedLong(byte[] bytes, int offset) { byte b = bytes[offset++]; long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = bytes[offset++]; i |= (b & 0x7FL) << shift; } return i; }
[ "public", "static", "long", "readUnsignedLong", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ")", "{", "byte", "b", "=", "bytes", "[", "offset", "++", "]", ";", "long", "i", "=", "b", "&", "0x7F", ";", "for", "(", "int", "shift", "=", "7...
Reads an int stored in variable-length format. Reads between one and nine bytes. Smaller values take fewer bytes. Negative numbers are not supported.
[ "Reads", "an", "int", "stored", "in", "variable", "-", "length", "format", ".", "Reads", "between", "one", "and", "nine", "bytes", ".", "Smaller", "values", "take", "fewer", "bytes", ".", "Negative", "numbers", "are", "not", "supported", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java#L188-L196
couchbase/java-dcp-client
src/main/java/com/couchbase/client/dcp/Client.java
Client.rollbackAndRestartStream
public Completable rollbackAndRestartStream(final short partition, final long seqno) { return stopStreaming(partition) .andThen(Completable.create(new Completable.OnSubscribe() { @Override public void call(CompletableSubscriber subscriber) { sessionState().rollbackToPosition(partition, seqno); subscriber.onCompleted(); } })) .andThen(startStreaming(partition)); }
java
public Completable rollbackAndRestartStream(final short partition, final long seqno) { return stopStreaming(partition) .andThen(Completable.create(new Completable.OnSubscribe() { @Override public void call(CompletableSubscriber subscriber) { sessionState().rollbackToPosition(partition, seqno); subscriber.onCompleted(); } })) .andThen(startStreaming(partition)); }
[ "public", "Completable", "rollbackAndRestartStream", "(", "final", "short", "partition", ",", "final", "long", "seqno", ")", "{", "return", "stopStreaming", "(", "partition", ")", ".", "andThen", "(", "Completable", ".", "create", "(", "new", "Completable", ".",...
Helper method to rollback the partition state and stop/restart the stream. <p> The stream is stopped (if not already done). Then: <p> The rollback seqno state is applied. Note that this will also remove all the failover logs for the partition that are higher than the given seqno, since the server told us we are ahead of it. <p> Finally, the stream is restarted again. @param partition the partition id @param seqno the sequence number to rollback to
[ "Helper", "method", "to", "rollback", "the", "partition", "state", "and", "stop", "/", "restart", "the", "stream", ".", "<p", ">", "The", "stream", "is", "stopped", "(", "if", "not", "already", "done", ")", ".", "Then", ":", "<p", ">", "The", "rollback...
train
https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/Client.java#L522-L532
netty/netty
codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyStreamStatus.java
SpdyStreamStatus.valueOf
public static SpdyStreamStatus valueOf(int code) { if (code == 0) { throw new IllegalArgumentException( "0 is not a valid status code for a RST_STREAM"); } switch (code) { case 1: return PROTOCOL_ERROR; case 2: return INVALID_STREAM; case 3: return REFUSED_STREAM; case 4: return UNSUPPORTED_VERSION; case 5: return CANCEL; case 6: return INTERNAL_ERROR; case 7: return FLOW_CONTROL_ERROR; case 8: return STREAM_IN_USE; case 9: return STREAM_ALREADY_CLOSED; case 10: return INVALID_CREDENTIALS; case 11: return FRAME_TOO_LARGE; } return new SpdyStreamStatus(code, "UNKNOWN (" + code + ')'); }
java
public static SpdyStreamStatus valueOf(int code) { if (code == 0) { throw new IllegalArgumentException( "0 is not a valid status code for a RST_STREAM"); } switch (code) { case 1: return PROTOCOL_ERROR; case 2: return INVALID_STREAM; case 3: return REFUSED_STREAM; case 4: return UNSUPPORTED_VERSION; case 5: return CANCEL; case 6: return INTERNAL_ERROR; case 7: return FLOW_CONTROL_ERROR; case 8: return STREAM_IN_USE; case 9: return STREAM_ALREADY_CLOSED; case 10: return INVALID_CREDENTIALS; case 11: return FRAME_TOO_LARGE; } return new SpdyStreamStatus(code, "UNKNOWN (" + code + ')'); }
[ "public", "static", "SpdyStreamStatus", "valueOf", "(", "int", "code", ")", "{", "if", "(", "code", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"0 is not a valid status code for a RST_STREAM\"", ")", ";", "}", "switch", "(", "code", "...
Returns the {@link SpdyStreamStatus} represented by the specified code. If the specified code is a defined SPDY status code, a cached instance will be returned. Otherwise, a new instance will be returned.
[ "Returns", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/spdy/SpdyStreamStatus.java#L94-L126
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/auth/OAuthActivity.java
OAuthActivity.onReceivedAuthCode
public void onReceivedAuthCode(String code, String baseDomain) { if (authType == AUTH_TYPE_WEBVIEW) { oauthView.setVisibility(View.INVISIBLE); } startMakingOAuthAPICall(code, baseDomain); }
java
public void onReceivedAuthCode(String code, String baseDomain) { if (authType == AUTH_TYPE_WEBVIEW) { oauthView.setVisibility(View.INVISIBLE); } startMakingOAuthAPICall(code, baseDomain); }
[ "public", "void", "onReceivedAuthCode", "(", "String", "code", ",", "String", "baseDomain", ")", "{", "if", "(", "authType", "==", "AUTH_TYPE_WEBVIEW", ")", "{", "oauthView", ".", "setVisibility", "(", "View", ".", "INVISIBLE", ")", ";", "}", "startMakingOAuth...
Callback method to be called when authentication code is received along with a base domain. The code will then be used to make an API call to create OAuth tokens.
[ "Callback", "method", "to", "be", "called", "when", "authentication", "code", "is", "received", "along", "with", "a", "base", "domain", ".", "The", "code", "will", "then", "be", "used", "to", "make", "an", "API", "call", "to", "create", "OAuth", "tokens", ...
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/auth/OAuthActivity.java#L172-L177
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java
ObjectArrayList.shuffleFromTo
public void shuffleFromTo(int from, int to) { if (size == 0) return; checkRangeFromTo(from, to, size); //cern.jet.random.Uniform gen = new cern.jet.random.Uniform(new cern.jet.random.engine.DRand(new java.util.Date())); java.util.Random gen = new java.util.Random(); Object tmpElement; Object[] theElements = elements; int random; for (int i = from; i < to; i++) { //random = gen.nextIntFromTo(i, to); int rp = gen.nextInt(to-i); random = rp + i; //swap(i, random) tmpElement = theElements[random]; theElements[random] = theElements[i]; theElements[i] = tmpElement; } }
java
public void shuffleFromTo(int from, int to) { if (size == 0) return; checkRangeFromTo(from, to, size); //cern.jet.random.Uniform gen = new cern.jet.random.Uniform(new cern.jet.random.engine.DRand(new java.util.Date())); java.util.Random gen = new java.util.Random(); Object tmpElement; Object[] theElements = elements; int random; for (int i = from; i < to; i++) { //random = gen.nextIntFromTo(i, to); int rp = gen.nextInt(to-i); random = rp + i; //swap(i, random) tmpElement = theElements[random]; theElements[random] = theElements[i]; theElements[i] = tmpElement; } }
[ "public", "void", "shuffleFromTo", "(", "int", "from", ",", "int", "to", ")", "{", "if", "(", "size", "==", "0", ")", "return", ";", "checkRangeFromTo", "(", "from", ",", "to", ",", "size", ")", ";", "//cern.jet.random.Uniform gen = new cern.jet.random.Uniform...
Randomly permutes the part of the receiver between <code>from</code> (inclusive) and <code>to</code> (inclusive). @param from the index of the first element (inclusive) to be permuted. @param to the index of the last element (inclusive) to be permuted. @exception IndexOutOfBoundsException index is out of range (<tt>size()&gt;0 && (from&lt;0 || from&gt;to || to&gt;=size())</tt>).
[ "Randomly", "permutes", "the", "part", "of", "the", "receiver", "between", "<code", ">", "from<", "/", "code", ">", "(", "inclusive", ")", "and", "<code", ">", "to<", "/", "code", ">", "(", "inclusive", ")", "." ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L863-L881
primefaces/primefaces
src/main/java/org/primefaces/component/repeat/UIRepeat.java
UIRepeat.saveInitialChildState
private void saveInitialChildState(FacesContext facesContext, UIComponent component) { if (component instanceof EditableValueHolder && !component.isTransient()) { String clientId = component.getClientId(facesContext); SavedState state = new SavedState(); initialChildState.put(clientId, state); state.populate((EditableValueHolder) component); } Iterator<UIComponent> iterator = component.getFacetsAndChildren(); while (iterator.hasNext()) { saveChildState(facesContext, iterator.next()); } }
java
private void saveInitialChildState(FacesContext facesContext, UIComponent component) { if (component instanceof EditableValueHolder && !component.isTransient()) { String clientId = component.getClientId(facesContext); SavedState state = new SavedState(); initialChildState.put(clientId, state); state.populate((EditableValueHolder) component); } Iterator<UIComponent> iterator = component.getFacetsAndChildren(); while (iterator.hasNext()) { saveChildState(facesContext, iterator.next()); } }
[ "private", "void", "saveInitialChildState", "(", "FacesContext", "facesContext", ",", "UIComponent", "component", ")", "{", "if", "(", "component", "instanceof", "EditableValueHolder", "&&", "!", "component", ".", "isTransient", "(", ")", ")", "{", "String", "clie...
Recursively create the initial state for the given component. @param facesContext the Faces context. @param component the UI component to save the state for. @see #saveInitialChildState(javax.faces.context.FacesContext)
[ "Recursively", "create", "the", "initial", "state", "for", "the", "given", "component", "." ]
train
https://github.com/primefaces/primefaces/blob/b8cdd5ed395d09826e40e3302d6b14901d3ef4e7/src/main/java/org/primefaces/component/repeat/UIRepeat.java#L470-L482
Harium/keel
src/main/java/com/harium/keel/catalano/statistics/HistogramStatistics.java
HistogramStatistics.StdDev
public static double StdDev( int[] values, double mean ){ double stddev = 0; double diff; int hits; int total = 0; // for all values for ( int i = 0, n = values.length; i < n; i++ ) { hits = values[i]; diff = (double) i - mean; // accumulate std.dev. stddev += diff * diff * hits; // accumalate total total += hits; } return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) ); }
java
public static double StdDev( int[] values, double mean ){ double stddev = 0; double diff; int hits; int total = 0; // for all values for ( int i = 0, n = values.length; i < n; i++ ) { hits = values[i]; diff = (double) i - mean; // accumulate std.dev. stddev += diff * diff * hits; // accumalate total total += hits; } return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) ); }
[ "public", "static", "double", "StdDev", "(", "int", "[", "]", "values", ",", "double", "mean", ")", "{", "double", "stddev", "=", "0", ";", "double", "diff", ";", "int", "hits", ";", "int", "total", "=", "0", ";", "// for all values", "for", "(", "in...
Calculate standart deviation. @param values Values. @param mean Mean. @return Standart deviation.
[ "Calculate", "standart", "deviation", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/statistics/HistogramStatistics.java#L263-L281
apache/incubator-gobblin
gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/SessionHelper.java
SessionHelper.getSessionId
public static String getSessionId(CloseableHttpClient httpClient, String url, String username, String password) throws AzkabanClientException { try { HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(AzkabanClientParams.ACTION, "login")); nvps.add(new BasicNameValuePair(AzkabanClientParams.USERNAME, username)); nvps.add(new BasicNameValuePair(AzkabanClientParams.PASSWORD, password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); // retrieve session id from entity String jsonResponseString = IOUtils.toString(entity.getContent(), "UTF-8"); String sessionId = AzkabanClient.parseResponse(jsonResponseString).get(AzkabanClientParams.SESSION_ID); EntityUtils.consume(entity); return sessionId; } catch (Exception e) { throw new AzkabanClientException("Azkaban client cannot consume session response.", e); } finally { response.close(); } } catch (Exception e) { throw new AzkabanClientException("Azkaban client cannot fetch session.", e); } }
java
public static String getSessionId(CloseableHttpClient httpClient, String url, String username, String password) throws AzkabanClientException { try { HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(AzkabanClientParams.ACTION, "login")); nvps.add(new BasicNameValuePair(AzkabanClientParams.USERNAME, username)); nvps.add(new BasicNameValuePair(AzkabanClientParams.PASSWORD, password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); // retrieve session id from entity String jsonResponseString = IOUtils.toString(entity.getContent(), "UTF-8"); String sessionId = AzkabanClient.parseResponse(jsonResponseString).get(AzkabanClientParams.SESSION_ID); EntityUtils.consume(entity); return sessionId; } catch (Exception e) { throw new AzkabanClientException("Azkaban client cannot consume session response.", e); } finally { response.close(); } } catch (Exception e) { throw new AzkabanClientException("Azkaban client cannot fetch session.", e); } }
[ "public", "static", "String", "getSessionId", "(", "CloseableHttpClient", "httpClient", ",", "String", "url", ",", "String", "username", ",", "String", "password", ")", "throws", "AzkabanClientException", "{", "try", "{", "HttpPost", "httpPost", "=", "new", "HttpP...
<p>Use Azkaban ajax api to fetch the session id. Required http request parameters are: <br>action=login The fixed parameter indicating the login action. <br>username The Azkaban username. <br>password The corresponding password. </pr> @param httpClient An apache http client @param url Azkaban ajax endpoint @param username username for Azkaban login @param password password for Azkaban login @return session id
[ "<p", ">", "Use", "Azkaban", "ajax", "api", "to", "fetch", "the", "session", "id", ".", "Required", "http", "request", "parameters", "are", ":", "<br", ">", "action", "=", "login", "The", "fixed", "parameter", "indicating", "the", "login", "action", ".", ...
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-azkaban/src/main/java/org/apache/gobblin/service/modules/orchestration/SessionHelper.java#L56-L83
dlemmermann/CalendarFX
CalendarFXGoogle/src/main/java/com/calendarfx/google/model/GoogleCalendar.java
GoogleCalendar.createEntry
public final GoogleEntry createEntry(ZonedDateTime start, boolean fullDay) { GoogleEntry entry = new GoogleEntry(); entry.setTitle("New Entry " + generateEntryConsecutive()); entry.setInterval(new Interval(start.toLocalDate(), start.toLocalTime(), start.toLocalDate(), start.toLocalTime().plusHours(1))); entry.setFullDay(fullDay); entry.setAttendeesCanInviteOthers(true); entry.setAttendeesCanSeeOthers(true); return entry; }
java
public final GoogleEntry createEntry(ZonedDateTime start, boolean fullDay) { GoogleEntry entry = new GoogleEntry(); entry.setTitle("New Entry " + generateEntryConsecutive()); entry.setInterval(new Interval(start.toLocalDate(), start.toLocalTime(), start.toLocalDate(), start.toLocalTime().plusHours(1))); entry.setFullDay(fullDay); entry.setAttendeesCanInviteOthers(true); entry.setAttendeesCanSeeOthers(true); return entry; }
[ "public", "final", "GoogleEntry", "createEntry", "(", "ZonedDateTime", "start", ",", "boolean", "fullDay", ")", "{", "GoogleEntry", "entry", "=", "new", "GoogleEntry", "(", ")", ";", "entry", ".", "setTitle", "(", "\"New Entry \"", "+", "generateEntryConsecutive",...
Creates a new google entry by using the given parameters, this assigns a default name by using a consecutive number. The entry is of course associated to this calendar, but it is not sent to google for storing. @param start The start date/time of the new entry. @param fullDay A flag indicating if the new entry is going to be full day. @return The new google entry created, this is not send to server side. @see #generateEntryConsecutive()
[ "Creates", "a", "new", "google", "entry", "by", "using", "the", "given", "parameters", "this", "assigns", "a", "default", "name", "by", "using", "a", "consecutive", "number", ".", "The", "entry", "is", "of", "course", "associated", "to", "this", "calendar", ...
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXGoogle/src/main/java/com/calendarfx/google/model/GoogleCalendar.java#L143-L151
probedock/probedock-java
src/main/java/io/probedock/client/common/utils/Inflector.java
Inflector.forgeName
public static String forgeName(Class cl, String methodName, ProbeTest methodAnnotation) { if (methodAnnotation != null && !"".equalsIgnoreCase(methodAnnotation.name())) { return methodAnnotation.name(); } else { return getHumanName(cl.getSimpleName() + ": " + methodName); } }
java
public static String forgeName(Class cl, String methodName, ProbeTest methodAnnotation) { if (methodAnnotation != null && !"".equalsIgnoreCase(methodAnnotation.name())) { return methodAnnotation.name(); } else { return getHumanName(cl.getSimpleName() + ": " + methodName); } }
[ "public", "static", "String", "forgeName", "(", "Class", "cl", ",", "String", "methodName", ",", "ProbeTest", "methodAnnotation", ")", "{", "if", "(", "methodAnnotation", "!=", "null", "&&", "!", "\"\"", ".", "equalsIgnoreCase", "(", "methodAnnotation", ".", "...
Forge a name from a class and a method. If an annotation is provided, then the method content is used. @param cl Class to get the name @param methodName The method name @param methodAnnotation The method annotation to override the normal forged name @return The name forge and humanize
[ "Forge", "a", "name", "from", "a", "class", "and", "a", "method", ".", "If", "an", "annotation", "is", "provided", "then", "the", "method", "content", "is", "used", "." ]
train
https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/common/utils/Inflector.java#L36-L42
groovyfx-project/groovyfx
src/main/groovy/groovyx/javafx/beans/FXBindableASTTransformation.java
FXBindableASTTransformation.createFieldNodeCopy
private FieldNode createFieldNodeCopy(String newName, ClassNode newType, FieldNode f) { if (newType == null) newType = f.getType(); newType = newType.getPlainNodeReference(); return new FieldNode(newName, f.getModifiers(), newType, f.getOwner(), f.getInitialValueExpression()); }
java
private FieldNode createFieldNodeCopy(String newName, ClassNode newType, FieldNode f) { if (newType == null) newType = f.getType(); newType = newType.getPlainNodeReference(); return new FieldNode(newName, f.getModifiers(), newType, f.getOwner(), f.getInitialValueExpression()); }
[ "private", "FieldNode", "createFieldNodeCopy", "(", "String", "newName", ",", "ClassNode", "newType", ",", "FieldNode", "f", ")", "{", "if", "(", "newType", "==", "null", ")", "newType", "=", "f", ".", "getType", "(", ")", ";", "newType", "=", "newType", ...
Creates a copy of a FieldNode with a new name and, optionally, a new type. @param newName The name for the new field node. @param newType The new type of the field. If null, the old FieldNode's type will be used. @param f The FieldNode to copy. @return The new FieldNode.
[ "Creates", "a", "copy", "of", "a", "FieldNode", "with", "a", "new", "name", "and", "optionally", "a", "new", "type", "." ]
train
https://github.com/groovyfx-project/groovyfx/blob/7067d76793601ce4de9c642d4c0c0e11db7907cb/src/main/groovy/groovyx/javafx/beans/FXBindableASTTransformation.java#L658-L664
molgenis/molgenis
molgenis-data-i18n/src/main/java/org/molgenis/data/i18n/LocalizationService.java
LocalizationService.resolveCodeWithoutArguments
@Override @RunAsSystem public String resolveCodeWithoutArguments(String code, Locale locale) { return Optional.ofNullable( dataService.query(L10N_STRING, L10nString.class).eq(MSGID, code).findOne()) .map(l10nString -> l10nString.getString(locale)) .orElse(null); }
java
@Override @RunAsSystem public String resolveCodeWithoutArguments(String code, Locale locale) { return Optional.ofNullable( dataService.query(L10N_STRING, L10nString.class).eq(MSGID, code).findOne()) .map(l10nString -> l10nString.getString(locale)) .orElse(null); }
[ "@", "Override", "@", "RunAsSystem", "public", "String", "resolveCodeWithoutArguments", "(", "String", "code", ",", "Locale", "locale", ")", "{", "return", "Optional", ".", "ofNullable", "(", "dataService", ".", "query", "(", "L10N_STRING", ",", "L10nString", "....
Looks up a single localized message. @param code messageID @param locale the Locale for the language @return String containing the message or null if not specified
[ "Looks", "up", "a", "single", "localized", "message", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-i18n/src/main/java/org/molgenis/data/i18n/LocalizationService.java#L51-L58
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfContentByte.java
PdfContentByte.addImage
public void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException { addImage(image, a, b, c, d, e, f, false); }
java
public void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException { addImage(image, a, b, c, d, e, f, false); }
[ "public", "void", "addImage", "(", "Image", "image", ",", "float", "a", ",", "float", "b", ",", "float", "c", ",", "float", "d", ",", "float", "e", ",", "float", "f", ")", "throws", "DocumentException", "{", "addImage", "(", "image", ",", "a", ",", ...
Adds an <CODE>Image</CODE> to the page. The positioning of the <CODE>Image</CODE> is done with the transformation matrix. To position an <CODE>image</CODE> at (x,y) use addImage(image, image_width, 0, 0, image_height, x, y). @param image the <CODE>Image</CODE> object @param a an element of the transformation matrix @param b an element of the transformation matrix @param c an element of the transformation matrix @param d an element of the transformation matrix @param e an element of the transformation matrix @param f an element of the transformation matrix @throws DocumentException on error
[ "Adds", "an", "<CODE", ">", "Image<", "/", "CODE", ">", "to", "the", "page", ".", "The", "positioning", "of", "the", "<CODE", ">", "Image<", "/", "CODE", ">", "is", "done", "with", "the", "transformation", "matrix", ".", "To", "position", "an", "<CODE"...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L1133-L1135
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/event/StickyValueHandler.java
StickyValueHandler.fieldChanged
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { int iErrorCode = super.fieldChanged(bDisplayOption, iMoveMode); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; if (iMoveMode == DBConstants.INIT_MOVE) this.retrieveValue(); if (iMoveMode == DBConstants.SCREEN_MOVE) this.saveValue(); return iErrorCode; }
java
public int fieldChanged(boolean bDisplayOption, int iMoveMode) { int iErrorCode = super.fieldChanged(bDisplayOption, iMoveMode); if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; if (iMoveMode == DBConstants.INIT_MOVE) this.retrieveValue(); if (iMoveMode == DBConstants.SCREEN_MOVE) this.saveValue(); return iErrorCode; }
[ "public", "int", "fieldChanged", "(", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "int", "iErrorCode", "=", "super", ".", "fieldChanged", "(", "bDisplayOption", ",", "iMoveMode", ")", ";", "if", "(", "iErrorCode", "!=", "DBConstants", ".", ...
The Field has Changed. @param bDisplayOption If true, display the change. @param iMoveMode The type of move being done (init/read/screen). @return The error code (or NORMAL_RETURN if okay).
[ "The", "Field", "has", "Changed", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/event/StickyValueHandler.java#L98-L108
michael-rapp/AndroidPreferenceActivity
library/src/main/java/de/mrapp/android/preference/activity/animation/HideViewOnScrollAnimation.java
HideViewOnScrollAnimation.notifyOnScrollingUp
private void notifyOnScrollingUp(@NonNull final View animatedView, final int scrollPosition) { for (HideViewOnScrollAnimationListener listener : listeners) { listener.onScrollingUp(this, animatedView, scrollPosition); } }
java
private void notifyOnScrollingUp(@NonNull final View animatedView, final int scrollPosition) { for (HideViewOnScrollAnimationListener listener : listeners) { listener.onScrollingUp(this, animatedView, scrollPosition); } }
[ "private", "void", "notifyOnScrollingUp", "(", "@", "NonNull", "final", "View", "animatedView", ",", "final", "int", "scrollPosition", ")", "{", "for", "(", "HideViewOnScrollAnimationListener", "listener", ":", "listeners", ")", "{", "listener", ".", "onScrollingUp"...
Notifies all listeners, which have been registered to be notified about the animation's internal state, when the observed list view is scrolling upwards. @param animatedView The view, which is animated by the observed animation, as an instance of the class {@link View} @param scrollPosition The current scroll position of the list view's first item in pixels as an {@link Integer} value
[ "Notifies", "all", "listeners", "which", "have", "been", "registered", "to", "be", "notified", "about", "the", "animation", "s", "internal", "state", "when", "the", "observed", "list", "view", "is", "scrolling", "upwards", "." ]
train
https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/library/src/main/java/de/mrapp/android/preference/activity/animation/HideViewOnScrollAnimation.java#L124-L128
VoltDB/voltdb
src/frontend/org/voltdb/planner/PlanAssembler.java
PlanAssembler.handleUnionLimitOperator
private AbstractPlanNode handleUnionLimitOperator(AbstractPlanNode root) { // The coordinator's top limit graph fragment for a MP plan. // If planning "order by ... limit", getNextUnionPlan() // will have already added an order by to the coordinator frag. // This is the only limit node in a SP plan LimitPlanNode topLimit = m_parsedUnion.getLimitNodeTop(); assert(topLimit != null); return inlineLimitOperator(root, topLimit); }
java
private AbstractPlanNode handleUnionLimitOperator(AbstractPlanNode root) { // The coordinator's top limit graph fragment for a MP plan. // If planning "order by ... limit", getNextUnionPlan() // will have already added an order by to the coordinator frag. // This is the only limit node in a SP plan LimitPlanNode topLimit = m_parsedUnion.getLimitNodeTop(); assert(topLimit != null); return inlineLimitOperator(root, topLimit); }
[ "private", "AbstractPlanNode", "handleUnionLimitOperator", "(", "AbstractPlanNode", "root", ")", "{", "// The coordinator's top limit graph fragment for a MP plan.", "// If planning \"order by ... limit\", getNextUnionPlan()", "// will have already added an order by to the coordinator frag.", ...
Add a limit, and return the new root. @param root top of the original plan @return new plan's root node
[ "Add", "a", "limit", "and", "return", "the", "new", "root", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/PlanAssembler.java#L2206-L2214
apache/flink
flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBStateDownloader.java
RocksDBStateDownloader.downloadDataForAllStateHandles
private void downloadDataForAllStateHandles( Map<StateHandleID, StreamStateHandle> stateHandleMap, Path restoreInstancePath, CloseableRegistry closeableRegistry) throws Exception { try { List<Runnable> runnables = createDownloadRunnables(stateHandleMap, restoreInstancePath, closeableRegistry); List<CompletableFuture<Void>> futures = new ArrayList<>(runnables.size()); for (Runnable runnable : runnables) { futures.add(CompletableFuture.runAsync(runnable, executorService)); } FutureUtils.waitForAll(futures).get(); } catch (ExecutionException e) { Throwable throwable = ExceptionUtils.stripExecutionException(e); throwable = ExceptionUtils.stripException(throwable, RuntimeException.class); if (throwable instanceof IOException) { throw (IOException) throwable; } else { throw new FlinkRuntimeException("Failed to download data for state handles.", e); } } }
java
private void downloadDataForAllStateHandles( Map<StateHandleID, StreamStateHandle> stateHandleMap, Path restoreInstancePath, CloseableRegistry closeableRegistry) throws Exception { try { List<Runnable> runnables = createDownloadRunnables(stateHandleMap, restoreInstancePath, closeableRegistry); List<CompletableFuture<Void>> futures = new ArrayList<>(runnables.size()); for (Runnable runnable : runnables) { futures.add(CompletableFuture.runAsync(runnable, executorService)); } FutureUtils.waitForAll(futures).get(); } catch (ExecutionException e) { Throwable throwable = ExceptionUtils.stripExecutionException(e); throwable = ExceptionUtils.stripException(throwable, RuntimeException.class); if (throwable instanceof IOException) { throw (IOException) throwable; } else { throw new FlinkRuntimeException("Failed to download data for state handles.", e); } } }
[ "private", "void", "downloadDataForAllStateHandles", "(", "Map", "<", "StateHandleID", ",", "StreamStateHandle", ">", "stateHandleMap", ",", "Path", "restoreInstancePath", ",", "CloseableRegistry", "closeableRegistry", ")", "throws", "Exception", "{", "try", "{", "List"...
Copies all the files from the given stream state handles to the given path, renaming the files w.r.t. their {@link StateHandleID}.
[ "Copies", "all", "the", "files", "from", "the", "given", "stream", "state", "handles", "to", "the", "given", "path", "renaming", "the", "files", "w", ".", "r", ".", "t", ".", "their", "{" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-state-backends/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBStateDownloader.java#L74-L95
deeplearning4j/deeplearning4j
nd4j/nd4j-serde/nd4j-aeron/src/main/java/org/nd4j/aeron/ipc/AeronConnectionInformation.java
AeronConnectionInformation.of
public static AeronConnectionInformation of(String connectionHost, int connectionPort, int streamId) { return AeronConnectionInformation.builder().connectionHost(connectionHost).connectionPort(connectionPort) .streamId(streamId).build(); }
java
public static AeronConnectionInformation of(String connectionHost, int connectionPort, int streamId) { return AeronConnectionInformation.builder().connectionHost(connectionHost).connectionPort(connectionPort) .streamId(streamId).build(); }
[ "public", "static", "AeronConnectionInformation", "of", "(", "String", "connectionHost", ",", "int", "connectionPort", ",", "int", "streamId", ")", "{", "return", "AeronConnectionInformation", ".", "builder", "(", ")", ".", "connectionHost", "(", "connectionHost", "...
Traditional static generator method @param connectionHost @param connectionPort @param streamId @return
[ "Traditional", "static", "generator", "method" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-serde/nd4j-aeron/src/main/java/org/nd4j/aeron/ipc/AeronConnectionInformation.java#L44-L47
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqlquarter
public static void sqlquarter(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "extract(quarter from ", "quarter", parsedArgs); }
java
public static void sqlquarter(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "extract(quarter from ", "quarter", parsedArgs); }
[ "public", "static", "void", "sqlquarter", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "singleArgumentFunctionCall", "(", "buf", ",", "\"extract(quarter from \"", ",", "\"quarte...
quarter translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "quarter", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L453-L455
threerings/nenya
core/src/main/java/com/threerings/chat/ComicChatOverlay.java
ComicChatOverlay.getBubbleSize
protected Rectangle getBubbleSize (int type, Dimension d) { switch (ChatLogic.modeOf(type)) { case ChatLogic.SHOUT: case ChatLogic.THINK: case ChatLogic.EMOTE: // extra room for these two monsters return new Rectangle(d.width + (PAD * 4), d.height + (PAD * 4)); default: return new Rectangle(d.width + (PAD * 2), d.height + (PAD * 2)); } }
java
protected Rectangle getBubbleSize (int type, Dimension d) { switch (ChatLogic.modeOf(type)) { case ChatLogic.SHOUT: case ChatLogic.THINK: case ChatLogic.EMOTE: // extra room for these two monsters return new Rectangle(d.width + (PAD * 4), d.height + (PAD * 4)); default: return new Rectangle(d.width + (PAD * 2), d.height + (PAD * 2)); } }
[ "protected", "Rectangle", "getBubbleSize", "(", "int", "type", ",", "Dimension", "d", ")", "{", "switch", "(", "ChatLogic", ".", "modeOf", "(", "type", ")", ")", "{", "case", "ChatLogic", ".", "SHOUT", ":", "case", "ChatLogic", ".", "THINK", ":", "case",...
Calculate the size of the chat bubble based on the dimensions of the label and the type of chat. It will be turned into a shape later, but we manipulate it for a while as just a rectangle (which are easier to move about and do intersection tests with, and besides the Shape interface has no way to translate).
[ "Calculate", "the", "size", "of", "the", "chat", "bubble", "based", "on", "the", "dimensions", "of", "the", "label", "and", "the", "type", "of", "chat", ".", "It", "will", "be", "turned", "into", "a", "shape", "later", "but", "we", "manipulate", "it", ...
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/chat/ComicChatOverlay.java#L368-L380
soarcn/COCOQuery
query/src/main/java/com/cocosw/query/AbstractViewQuery.java
AbstractViewQuery.imeAction
public T imeAction(int lable, final View associateView) { if (view instanceof EditText) { ((EditText)view).setImeActionLabel(context.getString(lable),view.getId()); ((EditText)view).setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == view.getId() || id == EditorInfo.IME_NULL) { associateView.performClick(); return true; } return false; } }); } return self(); }
java
public T imeAction(int lable, final View associateView) { if (view instanceof EditText) { ((EditText)view).setImeActionLabel(context.getString(lable),view.getId()); ((EditText)view).setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == view.getId() || id == EditorInfo.IME_NULL) { associateView.performClick(); return true; } return false; } }); } return self(); }
[ "public", "T", "imeAction", "(", "int", "lable", ",", "final", "View", "associateView", ")", "{", "if", "(", "view", "instanceof", "EditText", ")", "{", "(", "(", "EditText", ")", "view", ")", ".", "setImeActionLabel", "(", "context", ".", "getString", "...
Change the custom IME action associated with the text view. click the lable will trigger the associateView's onClick method @param lable @param associateView
[ "Change", "the", "custom", "IME", "action", "associated", "with", "the", "text", "view", ".", "click", "the", "lable", "will", "trigger", "the", "associateView", "s", "onClick", "method" ]
train
https://github.com/soarcn/COCOQuery/blob/712eac37ab65ef3dbdf55dbfae28750edfc36608/query/src/main/java/com/cocosw/query/AbstractViewQuery.java#L173-L188
zaproxy/zaproxy
src/org/zaproxy/zap/model/Context.java
Context.fillNodesInContext
private void fillNodesInContext(SiteNode rootNode, List<SiteNode> nodesList) { @SuppressWarnings("unchecked") Enumeration<TreeNode> en = rootNode.children(); while (en.hasMoreElements()) { SiteNode sn = (SiteNode) en.nextElement(); if (isInContext(sn)) { nodesList.add(sn); } fillNodesInContext(sn, nodesList); } }
java
private void fillNodesInContext(SiteNode rootNode, List<SiteNode> nodesList) { @SuppressWarnings("unchecked") Enumeration<TreeNode> en = rootNode.children(); while (en.hasMoreElements()) { SiteNode sn = (SiteNode) en.nextElement(); if (isInContext(sn)) { nodesList.add(sn); } fillNodesInContext(sn, nodesList); } }
[ "private", "void", "fillNodesInContext", "(", "SiteNode", "rootNode", ",", "List", "<", "SiteNode", ">", "nodesList", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Enumeration", "<", "TreeNode", ">", "en", "=", "rootNode", ".", "children", "("...
Fills a given list with nodes in scope, searching recursively. @param rootNode the root node @param nodesList the nodes list
[ "Fills", "a", "given", "list", "with", "nodes", "in", "scope", "searching", "recursively", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/model/Context.java#L289-L299
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.createUser
public CmsUser createUser( CmsDbContext dbc, String name, String password, String description, Map<String, Object> additionalInfos) throws CmsException, CmsIllegalArgumentException { // no space before or after the name name = name.trim(); // check the user name String userName = CmsOrganizationalUnit.getSimpleName(name); OpenCms.getValidationHandler().checkUserName(userName); if (CmsStringUtil.isEmptyOrWhitespaceOnly(userName)) { throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_BAD_USER_1, userName)); } // check the ou CmsOrganizationalUnit ou = readOrganizationalUnit(dbc, CmsOrganizationalUnit.getParentFqn(name)); // check the password validatePassword(password); Map<String, Object> info = new HashMap<String, Object>(); if (additionalInfos != null) { info.putAll(additionalInfos); } if (description != null) { info.put(CmsUserSettings.ADDITIONAL_INFO_DESCRIPTION, description); } int flags = 0; if (ou.hasFlagWebuser()) { flags += I_CmsPrincipal.FLAG_USER_WEBUSER; } CmsUser user = getUserDriver(dbc).createUser( dbc, new CmsUUID(), name, OpenCms.getPasswordHandler().digest(password), " ", " ", " ", 0, I_CmsPrincipal.FLAG_ENABLED + flags, 0, info); if (!dbc.getProjectId().isNullUUID()) { // user modified event is not needed return user; } // fire user modified event Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put(I_CmsEventListener.KEY_USER_ID, user.getId().toString()); eventData.put(I_CmsEventListener.KEY_USER_ACTION, I_CmsEventListener.VALUE_USER_MODIFIED_ACTION_CREATE_USER); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_USER_MODIFIED, eventData)); return user; }
java
public CmsUser createUser( CmsDbContext dbc, String name, String password, String description, Map<String, Object> additionalInfos) throws CmsException, CmsIllegalArgumentException { // no space before or after the name name = name.trim(); // check the user name String userName = CmsOrganizationalUnit.getSimpleName(name); OpenCms.getValidationHandler().checkUserName(userName); if (CmsStringUtil.isEmptyOrWhitespaceOnly(userName)) { throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_BAD_USER_1, userName)); } // check the ou CmsOrganizationalUnit ou = readOrganizationalUnit(dbc, CmsOrganizationalUnit.getParentFqn(name)); // check the password validatePassword(password); Map<String, Object> info = new HashMap<String, Object>(); if (additionalInfos != null) { info.putAll(additionalInfos); } if (description != null) { info.put(CmsUserSettings.ADDITIONAL_INFO_DESCRIPTION, description); } int flags = 0; if (ou.hasFlagWebuser()) { flags += I_CmsPrincipal.FLAG_USER_WEBUSER; } CmsUser user = getUserDriver(dbc).createUser( dbc, new CmsUUID(), name, OpenCms.getPasswordHandler().digest(password), " ", " ", " ", 0, I_CmsPrincipal.FLAG_ENABLED + flags, 0, info); if (!dbc.getProjectId().isNullUUID()) { // user modified event is not needed return user; } // fire user modified event Map<String, Object> eventData = new HashMap<String, Object>(); eventData.put(I_CmsEventListener.KEY_USER_ID, user.getId().toString()); eventData.put(I_CmsEventListener.KEY_USER_ACTION, I_CmsEventListener.VALUE_USER_MODIFIED_ACTION_CREATE_USER); OpenCms.fireCmsEvent(new CmsEvent(I_CmsEventListener.EVENT_USER_MODIFIED, eventData)); return user; }
[ "public", "CmsUser", "createUser", "(", "CmsDbContext", "dbc", ",", "String", "name", ",", "String", "password", ",", "String", "description", ",", "Map", "<", "String", ",", "Object", ">", "additionalInfos", ")", "throws", "CmsException", ",", "CmsIllegalArgume...
Creates a new user.<p> @param dbc the current database context @param name the name for the new user @param password the password for the new user @param description the description for the new user @param additionalInfos the additional infos for the user @return the created user @see CmsObject#createUser(String, String, String, Map) @throws CmsException if something goes wrong @throws CmsIllegalArgumentException if the name for the user is not valid
[ "Creates", "a", "new", "user", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L2167-L2222
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.Manhattan
public static double Manhattan(double[] p, double[] q) { double sum = 0; for (int i = 0; i < p.length; i++) { sum += Math.abs(p[i] - q[i]); } return sum; }
java
public static double Manhattan(double[] p, double[] q) { double sum = 0; for (int i = 0; i < p.length; i++) { sum += Math.abs(p[i] - q[i]); } return sum; }
[ "public", "static", "double", "Manhattan", "(", "double", "[", "]", "p", ",", "double", "[", "]", "q", ")", "{", "double", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "p", ".", "length", ";", "i", "++", ")", "{", ...
Gets the Manhattan distance between two points. @param p A point in space. @param q A point in space. @return The Manhattan distance between x and y.
[ "Gets", "the", "Manhattan", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L686-L692
AltBeacon/android-beacon-library
lib/src/main/java/org/altbeacon/beacon/BeaconManager.java
BeaconManager.logDebug
@Deprecated public static void logDebug(String tag, String message) { LogManager.d(tag, message); }
java
@Deprecated public static void logDebug(String tag, String message) { LogManager.d(tag, message); }
[ "@", "Deprecated", "public", "static", "void", "logDebug", "(", "String", "tag", ",", "String", "message", ")", "{", "LogManager", ".", "d", "(", "tag", ",", "message", ")", ";", "}" ]
Convenience method for logging debug by the library @param tag @param message @deprecated This will be removed in a later release. Use {@link org.altbeacon.beacon.logging.LogManager#d(String, String, Object...)} instead.
[ "Convenience", "method", "for", "logging", "debug", "by", "the", "library" ]
train
https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/BeaconManager.java#L1123-L1126
Stratio/bdt
src/main/java/com/stratio/qa/specs/DcosSpec.java
DcosSpec.destroyService
@Given("^I destroy service '(.+?)' in cluster '(.+?)'") public void destroyService(String service, String cluster) throws Exception { String endPoint = "/service/deploy-api/deploy/uninstall?app=" + service; Future response; this.commonspec.setRestProtocol("https://"); this.commonspec.setRestHost(cluster); this.commonspec.setRestPort(":443"); response = this.commonspec.generateRequest("DELETE", true, null, null, endPoint, null, "json"); this.commonspec.setResponse("DELETE", (Response) response.get()); assertThat(this.commonspec.getResponse().getStatusCode()).as("It hasn't been possible to destroy service: " + service).isIn(Arrays.asList(200, 202)); }
java
@Given("^I destroy service '(.+?)' in cluster '(.+?)'") public void destroyService(String service, String cluster) throws Exception { String endPoint = "/service/deploy-api/deploy/uninstall?app=" + service; Future response; this.commonspec.setRestProtocol("https://"); this.commonspec.setRestHost(cluster); this.commonspec.setRestPort(":443"); response = this.commonspec.generateRequest("DELETE", true, null, null, endPoint, null, "json"); this.commonspec.setResponse("DELETE", (Response) response.get()); assertThat(this.commonspec.getResponse().getStatusCode()).as("It hasn't been possible to destroy service: " + service).isIn(Arrays.asList(200, 202)); }
[ "@", "Given", "(", "\"^I destroy service '(.+?)' in cluster '(.+?)'\"", ")", "public", "void", "destroyService", "(", "String", "service", ",", "String", "cluster", ")", "throws", "Exception", "{", "String", "endPoint", "=", "\"/service/deploy-api/deploy/uninstall?app=\"", ...
Destroy specified service @param service name of the service to be destroyed @param cluster URI of the cluster @throws Exception exception *
[ "Destroy", "specified", "service" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/DcosSpec.java#L365-L378
OpenLiberty/open-liberty
dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java
SSLUtils.resetBuffersAfterJSSE
public static void resetBuffersAfterJSSE(WsByteBuffer[] buffers, int[] limitInfo) { // Handle case where not changes were made in recent call to adjustBuffersForJSSE if (limitInfo == null) { return; } int bufferIndex = limitInfo[0]; int bufferLimit = limitInfo[1]; // Ensure buffer index is within array bounds. if (buffers.length > bufferIndex) { WsByteBuffer buffer = buffers[bufferIndex]; // Ensure the buffer is not null and the limit won't be set beyond the capacity if ((buffer != null) && (buffer.capacity() >= bufferLimit)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "resetBuffersAfterJSSE: buffer [" + bufferIndex + "] from " + buffer.limit() + " to " + bufferLimit); } // Make the adjustment. buffer.limit(bufferLimit); } } }
java
public static void resetBuffersAfterJSSE(WsByteBuffer[] buffers, int[] limitInfo) { // Handle case where not changes were made in recent call to adjustBuffersForJSSE if (limitInfo == null) { return; } int bufferIndex = limitInfo[0]; int bufferLimit = limitInfo[1]; // Ensure buffer index is within array bounds. if (buffers.length > bufferIndex) { WsByteBuffer buffer = buffers[bufferIndex]; // Ensure the buffer is not null and the limit won't be set beyond the capacity if ((buffer != null) && (buffer.capacity() >= bufferLimit)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "resetBuffersAfterJSSE: buffer [" + bufferIndex + "] from " + buffer.limit() + " to " + bufferLimit); } // Make the adjustment. buffer.limit(bufferLimit); } } }
[ "public", "static", "void", "resetBuffersAfterJSSE", "(", "WsByteBuffer", "[", "]", "buffers", ",", "int", "[", "]", "limitInfo", ")", "{", "// Handle case where not changes were made in recent call to adjustBuffersForJSSE", "if", "(", "limitInfo", "==", "null", ")", "{...
This method is called after a call is made to adjustBuffersForJSSE followed by a call to wrap or unwrap in the JSSE. It restores the saved limit in the buffer that was modified. A few extra checks are done here to prevent any problems during odd code paths in the future. @param buffers array of buffers containing the buffer whose limit should be reset. @param limitInfo array of 2. The first entry is the index of the buffer whose limit will be restored in the array. The second entry is the actual limit to be restored.
[ "This", "method", "is", "called", "after", "a", "call", "is", "made", "to", "adjustBuffersForJSSE", "followed", "by", "a", "call", "to", "wrap", "or", "unwrap", "in", "the", "JSSE", ".", "It", "restores", "the", "saved", "limit", "in", "the", "buffer", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channel.ssl/src/com/ibm/ws/channel/ssl/internal/SSLUtils.java#L1341-L1362
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/DefaultCommandManager.java
DefaultCommandManager.createCommandGroup
@Override public CommandGroup createCommandGroup(String groupId, Object[] members, CommandConfigurer configurer) { return createCommandGroup(groupId, members, false, configurer); }
java
@Override public CommandGroup createCommandGroup(String groupId, Object[] members, CommandConfigurer configurer) { return createCommandGroup(groupId, members, false, configurer); }
[ "@", "Override", "public", "CommandGroup", "createCommandGroup", "(", "String", "groupId", ",", "Object", "[", "]", "members", ",", "CommandConfigurer", "configurer", ")", "{", "return", "createCommandGroup", "(", "groupId", ",", "members", ",", "false", ",", "c...
Create a command group which holds all the given members. @param groupId the id to configure the group. @param members members to add to the group. @param configurer the configurer to use. @return a {@link CommandGroup} which contains all the members.
[ "Create", "a", "command", "group", "which", "holds", "all", "the", "given", "members", "." ]
train
https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/DefaultCommandManager.java#L317-L320
future-architect/uroborosql
src/main/java/jp/co/future/uroborosql/config/DefaultSqlConfig.java
DefaultSqlConfig.getConfig
public static SqlConfig getConfig(final String url, final String user, final String password, final String schema, final boolean autoCommit, final boolean readOnly) { return new DefaultSqlConfig(new JdbcConnectionSupplierImpl(url, user, password, schema, autoCommit, readOnly), null); }
java
public static SqlConfig getConfig(final String url, final String user, final String password, final String schema, final boolean autoCommit, final boolean readOnly) { return new DefaultSqlConfig(new JdbcConnectionSupplierImpl(url, user, password, schema, autoCommit, readOnly), null); }
[ "public", "static", "SqlConfig", "getConfig", "(", "final", "String", "url", ",", "final", "String", "user", ",", "final", "String", "password", ",", "final", "String", "schema", ",", "final", "boolean", "autoCommit", ",", "final", "boolean", "readOnly", ")", ...
DB接続情報を指定してSqlConfigを取得する @param url JDBC接続URL @param user JDBC接続ユーザ @param password JDBC接続パスワード @param schema JDBCスキーマ名 @param autoCommit 自動コミットするかどうか. 自動コミットの場合<code>true</code> @param readOnly 参照のみかどうか. 参照のみの場合<code>true</code> @return SqlConfigオブジェクト
[ "DB接続情報を指定してSqlConfigを取得する" ]
train
https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/config/DefaultSqlConfig.java#L152-L156
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java
Calc.getXYZEuler
public static final double[] getXYZEuler(Matrix m){ double heading, attitude, bank; // Assuming the angles are in radians. if (m.get(1,0) > 0.998) { // singularity at north pole heading = Math.atan2(m.get(0,2),m.get(2,2)); attitude = Math.PI/2; bank = 0; } else if (m.get(1,0) < -0.998) { // singularity at south pole heading = Math.atan2(m.get(0,2),m.get(2,2)); attitude = -Math.PI/2; bank = 0; } else { heading = Math.atan2(-m.get(2,0),m.get(0,0)); bank = Math.atan2(-m.get(1,2),m.get(1,1)); attitude = Math.asin(m.get(1,0)); } return new double[] { heading, attitude, bank }; }
java
public static final double[] getXYZEuler(Matrix m){ double heading, attitude, bank; // Assuming the angles are in radians. if (m.get(1,0) > 0.998) { // singularity at north pole heading = Math.atan2(m.get(0,2),m.get(2,2)); attitude = Math.PI/2; bank = 0; } else if (m.get(1,0) < -0.998) { // singularity at south pole heading = Math.atan2(m.get(0,2),m.get(2,2)); attitude = -Math.PI/2; bank = 0; } else { heading = Math.atan2(-m.get(2,0),m.get(0,0)); bank = Math.atan2(-m.get(1,2),m.get(1,1)); attitude = Math.asin(m.get(1,0)); } return new double[] { heading, attitude, bank }; }
[ "public", "static", "final", "double", "[", "]", "getXYZEuler", "(", "Matrix", "m", ")", "{", "double", "heading", ",", "attitude", ",", "bank", ";", "// Assuming the angles are in radians.", "if", "(", "m", ".", "get", "(", "1", ",", "0", ")", ">", "0.9...
Convert a rotation Matrix to Euler angles. This conversion uses conventions as described on page: http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm Coordinate System: right hand Positive angle: right hand Order of euler angles: heading first, then attitude, then bank @param m the rotation matrix @return a array of three doubles containing the three euler angles in radians
[ "Convert", "a", "rotation", "Matrix", "to", "Euler", "angles", ".", "This", "conversion", "uses", "conventions", "as", "described", "on", "page", ":", "http", ":", "//", "www", ".", "euclideanspace", ".", "com", "/", "maths", "/", "geometry", "/", "rotatio...
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java#L1048-L1068
overturetool/overture
core/interpreter/src/main/java/org/overture/interpreter/assistant/definition/ACpuClassDefinitionAssistantInterpreter.java
ACpuClassDefinitionAssistantInterpreter.updateCPUandChildCPUs
private void updateCPUandChildCPUs(ObjectValue obj, CPUValue cpu) { if (cpu != obj.getCPU()) { for (ObjectValue superObj : obj.superobjects) { updateCPUandChildCPUs(superObj, cpu); } obj.setCPU(cpu); } // update all object we have created our self. for (ObjectValue objVal : obj.children) { updateCPUandChildCPUs(objVal, cpu); } }
java
private void updateCPUandChildCPUs(ObjectValue obj, CPUValue cpu) { if (cpu != obj.getCPU()) { for (ObjectValue superObj : obj.superobjects) { updateCPUandChildCPUs(superObj, cpu); } obj.setCPU(cpu); } // update all object we have created our self. for (ObjectValue objVal : obj.children) { updateCPUandChildCPUs(objVal, cpu); } }
[ "private", "void", "updateCPUandChildCPUs", "(", "ObjectValue", "obj", ",", "CPUValue", "cpu", ")", "{", "if", "(", "cpu", "!=", "obj", ".", "getCPU", "(", ")", ")", "{", "for", "(", "ObjectValue", "superObj", ":", "obj", ".", "superobjects", ")", "{", ...
Recursively updates all transitive references with the new CPU, but without removing the parent - child relation, unlike the deploy method. @param the objectvalue to update @param the target CPU of the redeploy
[ "Recursively", "updates", "all", "transitive", "references", "with", "the", "new", "CPU", "but", "without", "removing", "the", "parent", "-", "child", "relation", "unlike", "the", "deploy", "method", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/assistant/definition/ACpuClassDefinitionAssistantInterpreter.java#L111-L127
voldemort/voldemort
src/java/voldemort/rest/RestRequestValidator.java
RestRequestValidator.debugLog
protected void debugLog(String operationType, Long receivedTimeInMs) { long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs); int numVectorClockEntries = (this.parsedVectorClock == null ? 0 : this.parsedVectorClock.getVersionMap() .size()); logger.debug("Received a new request. Operation type: " + operationType + " , Key(s): " + keysHexString(this.parsedKeys) + " , Store: " + this.storeName + " , Origin time (in ms): " + (this.parsedRequestOriginTimeInMs) + " , Request received at time(in ms): " + receivedTimeInMs + " , Num vector clock entries: " + numVectorClockEntries + " , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): " + durationInMs); }
java
protected void debugLog(String operationType, Long receivedTimeInMs) { long durationInMs = receivedTimeInMs - (this.parsedRequestOriginTimeInMs); int numVectorClockEntries = (this.parsedVectorClock == null ? 0 : this.parsedVectorClock.getVersionMap() .size()); logger.debug("Received a new request. Operation type: " + operationType + " , Key(s): " + keysHexString(this.parsedKeys) + " , Store: " + this.storeName + " , Origin time (in ms): " + (this.parsedRequestOriginTimeInMs) + " , Request received at time(in ms): " + receivedTimeInMs + " , Num vector clock entries: " + numVectorClockEntries + " , Duration from RESTClient to CoordinatorRestRequestValidator(in ms): " + durationInMs); }
[ "protected", "void", "debugLog", "(", "String", "operationType", ",", "Long", "receivedTimeInMs", ")", "{", "long", "durationInMs", "=", "receivedTimeInMs", "-", "(", "this", ".", "parsedRequestOriginTimeInMs", ")", ";", "int", "numVectorClockEntries", "=", "(", "...
Prints a debug log message that details the time taken for the Http request to be parsed by the coordinator @param operationType @param receivedTimeInMs
[ "Prints", "a", "debug", "log", "message", "that", "details", "the", "time", "taken", "for", "the", "Http", "request", "to", "be", "parsed", "by", "the", "coordinator" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/rest/RestRequestValidator.java#L321-L334
devnied/Bit-lib4j
src/main/java/fr/devnied/bitlib/BitUtils.java
BitUtils.getNextDate
public Date getNextDate(final int pSize, final String pPattern, final boolean pUseBcd) { Date date = null; // create date formatter SimpleDateFormat sdf = new SimpleDateFormat(pPattern); // get String String dateTxt = null; if (pUseBcd) { dateTxt = getNextHexaString(pSize); } else { dateTxt = getNextString(pSize); } try { date = sdf.parse(dateTxt); } catch (ParseException e) { LOGGER.error("Parsing date error. date:" + dateTxt + " pattern:" + pPattern, e); } return date; }
java
public Date getNextDate(final int pSize, final String pPattern, final boolean pUseBcd) { Date date = null; // create date formatter SimpleDateFormat sdf = new SimpleDateFormat(pPattern); // get String String dateTxt = null; if (pUseBcd) { dateTxt = getNextHexaString(pSize); } else { dateTxt = getNextString(pSize); } try { date = sdf.parse(dateTxt); } catch (ParseException e) { LOGGER.error("Parsing date error. date:" + dateTxt + " pattern:" + pPattern, e); } return date; }
[ "public", "Date", "getNextDate", "(", "final", "int", "pSize", ",", "final", "String", "pPattern", ",", "final", "boolean", "pUseBcd", ")", "{", "Date", "date", "=", "null", ";", "// create date formatter\r", "SimpleDateFormat", "sdf", "=", "new", "SimpleDateFor...
Method to get the next date @param pSize the size of the string date in bit @param pPattern the Date pattern @param pUseBcd get the Date with BCD format (Binary coded decimal) @return a date object or null
[ "Method", "to", "get", "the", "next", "date" ]
train
https://github.com/devnied/Bit-lib4j/blob/bdfa79fd12e7e3d5cf1196291825ef1bb12a1ee0/src/main/java/fr/devnied/bitlib/BitUtils.java#L245-L263
btaz/data-util
src/main/java/com/btaz/util/files/FileDeleter.java
FileDeleter.deleteFilesByRegex
public static void deleteFilesByRegex(File dir, String regex) { if(regex == null) { throw new DataUtilException("Filename regex can not be null"); } FilenameFilter filter = new RegexFilenameFilter(regex); FileDeleter.deleteFiles(dir, filter); }
java
public static void deleteFilesByRegex(File dir, String regex) { if(regex == null) { throw new DataUtilException("Filename regex can not be null"); } FilenameFilter filter = new RegexFilenameFilter(regex); FileDeleter.deleteFiles(dir, filter); }
[ "public", "static", "void", "deleteFilesByRegex", "(", "File", "dir", ",", "String", "regex", ")", "{", "if", "(", "regex", "==", "null", ")", "{", "throw", "new", "DataUtilException", "(", "\"Filename regex can not be null\"", ")", ";", "}", "FilenameFilter", ...
Delete files in a directory matching a regular expression @param dir directory @param regex regular expression
[ "Delete", "files", "in", "a", "directory", "matching", "a", "regular", "expression" ]
train
https://github.com/btaz/data-util/blob/f01de64854c456a88a31ffbe8bac6d605151b496/src/main/java/com/btaz/util/files/FileDeleter.java#L30-L36
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/github/lgooddatepicker/zinternaltools/InternalUtilities.java
InternalUtilities.getConstraints
static public GridBagConstraints getConstraints(int gridx, int gridy) { GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.BOTH; gc.gridx = gridx; gc.gridy = gridy; return gc; }
java
static public GridBagConstraints getConstraints(int gridx, int gridy) { GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.BOTH; gc.gridx = gridx; gc.gridy = gridy; return gc; }
[ "static", "public", "GridBagConstraints", "getConstraints", "(", "int", "gridx", ",", "int", "gridy", ")", "{", "GridBagConstraints", "gc", "=", "new", "GridBagConstraints", "(", ")", ";", "gc", ".", "fill", "=", "GridBagConstraints", ".", "BOTH", ";", "gc", ...
getConstraints, This returns a grid bag constraints object that can be used for placing a component appropriately into a grid bag layout.
[ "getConstraints", "This", "returns", "a", "grid", "bag", "constraints", "object", "that", "can", "be", "used", "for", "placing", "a", "component", "appropriately", "into", "a", "grid", "bag", "layout", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/github/lgooddatepicker/zinternaltools/InternalUtilities.java#L340-L346
datasalt/pangool
core/src/main/java/com/datasalt/pangool/io/Mutator.java
Mutator.jointSchema
public static Schema jointSchema(Schema leftSchema, Schema rightSchema) { return jointSchema("jointSchema" + (COUNTER++), leftSchema, rightSchema); }
java
public static Schema jointSchema(Schema leftSchema, Schema rightSchema) { return jointSchema("jointSchema" + (COUNTER++), leftSchema, rightSchema); }
[ "public", "static", "Schema", "jointSchema", "(", "Schema", "leftSchema", ",", "Schema", "rightSchema", ")", "{", "return", "jointSchema", "(", "\"jointSchema\"", "+", "(", "COUNTER", "++", ")", ",", "leftSchema", ",", "rightSchema", ")", ";", "}" ]
Creates a joint schema between two Schemas. All Fields from both schema are deduplicated and combined into a single Schema. The left Schema has priority so if both Schemas have the same Field with the same name but different Types, the Type from the left Schema will be taken. <p> The name of the schema is auto-generated with a static counter.
[ "Creates", "a", "joint", "schema", "between", "two", "Schemas", ".", "All", "Fields", "from", "both", "schema", "are", "deduplicated", "and", "combined", "into", "a", "single", "Schema", ".", "The", "left", "Schema", "has", "priority", "so", "if", "both", ...
train
https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/io/Mutator.java#L99-L101
looly/hutool
hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelPicUtil.java
ExcelPicUtil.getPicMap
public static Map<String, PictureData> getPicMap(Workbook workbook, int sheetIndex) { Assert.notNull(workbook, "Workbook must be not null !"); if (sheetIndex < 0) { sheetIndex = 0; } if (workbook instanceof HSSFWorkbook) { return getPicMapXls((HSSFWorkbook) workbook, sheetIndex); } else if (workbook instanceof XSSFWorkbook) { return getPicMapXlsx((XSSFWorkbook) workbook, sheetIndex); } else { throw new IllegalArgumentException(StrUtil.format("Workbook type [{}] is not supported!", workbook.getClass())); } }
java
public static Map<String, PictureData> getPicMap(Workbook workbook, int sheetIndex) { Assert.notNull(workbook, "Workbook must be not null !"); if (sheetIndex < 0) { sheetIndex = 0; } if (workbook instanceof HSSFWorkbook) { return getPicMapXls((HSSFWorkbook) workbook, sheetIndex); } else if (workbook instanceof XSSFWorkbook) { return getPicMapXlsx((XSSFWorkbook) workbook, sheetIndex); } else { throw new IllegalArgumentException(StrUtil.format("Workbook type [{}] is not supported!", workbook.getClass())); } }
[ "public", "static", "Map", "<", "String", ",", "PictureData", ">", "getPicMap", "(", "Workbook", "workbook", ",", "int", "sheetIndex", ")", "{", "Assert", ".", "notNull", "(", "workbook", ",", "\"Workbook must be not null !\"", ")", ";", "if", "(", "sheetIndex...
获取工作簿指定sheet中图片列表 @param workbook 工作簿{@link Workbook} @param sheetIndex sheet的索引 @return 图片映射,键格式:行_列,值:{@link PictureData}
[ "获取工作簿指定sheet中图片列表" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelPicUtil.java#L41-L54
hap-java/HAP-Java
src/main/java/io/github/hapjava/HomekitServer.java
HomekitServer.createBridge
public HomekitRoot createBridge( HomekitAuthInfo authInfo, String label, String manufacturer, String model, String serialNumber) throws IOException { HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo); root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer)); return root; }
java
public HomekitRoot createBridge( HomekitAuthInfo authInfo, String label, String manufacturer, String model, String serialNumber) throws IOException { HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo); root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer)); return root; }
[ "public", "HomekitRoot", "createBridge", "(", "HomekitAuthInfo", "authInfo", ",", "String", "label", ",", "String", "manufacturer", ",", "String", "model", ",", "String", "serialNumber", ")", "throws", "IOException", "{", "HomekitRoot", "root", "=", "new", "Homeki...
Creates a bridge accessory, capable of holding multiple child accessories. This has the advantage over multiple standalone accessories of only requiring a single pairing from iOS for the bridge. @param authInfo authentication information for this accessory. These values should be persisted and re-supplied on re-start of your application. @param label label for the bridge. This will show in iOS during pairing. @param manufacturer manufacturer of the bridge. This information is exposed to iOS for unknown purposes. @param model model of the bridge. This is also exposed to iOS for unknown purposes. @param serialNumber serial number of the bridge. Also exposed. Purposes also unknown. @return the bridge, from which you can {@link HomekitRoot#addAccessory add accessories} and then {@link HomekitRoot#start start} handling requests. @throws IOException when mDNS cannot connect to the network
[ "Creates", "a", "bridge", "accessory", "capable", "of", "holding", "multiple", "child", "accessories", ".", "This", "has", "the", "advantage", "over", "multiple", "standalone", "accessories", "of", "only", "requiring", "a", "single", "pairing", "from", "iOS", "f...
train
https://github.com/hap-java/HAP-Java/blob/d2b2f4f1579580a2b5958af3a192128345843db9/src/main/java/io/github/hapjava/HomekitServer.java#L104-L114
rhiot/rhiot
gateway/components/camel-webcam/src/main/java/io/rhiot/gateway/camel/webcam/WebcamComponent.java
WebcamComponent.getWebcam
public Webcam getWebcam(String name, Dimension dimension) { if (name == null) { return getWebcam(dimension); } Webcam webcam = webcams.get(name); openWebcam(webcam, dimension); return webcam; }
java
public Webcam getWebcam(String name, Dimension dimension) { if (name == null) { return getWebcam(dimension); } Webcam webcam = webcams.get(name); openWebcam(webcam, dimension); return webcam; }
[ "public", "Webcam", "getWebcam", "(", "String", "name", ",", "Dimension", "dimension", ")", "{", "if", "(", "name", "==", "null", ")", "{", "return", "getWebcam", "(", "dimension", ")", ";", "}", "Webcam", "webcam", "=", "webcams", ".", "get", "(", "na...
Returns the webcam by name, null if not found. @param name webcam name @return webcam instance
[ "Returns", "the", "webcam", "by", "name", "null", "if", "not", "found", "." ]
train
https://github.com/rhiot/rhiot/blob/82eac10e365f72bab9248b8c3bd0ec9a2fc0a721/gateway/components/camel-webcam/src/main/java/io/rhiot/gateway/camel/webcam/WebcamComponent.java#L234-L242
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/Context.java
Context.getConnection
public static Connection getConnection() throws EFapsException { Connection con = null; try { con = Context.DATASOURCE.getConnection(); con.setAutoCommit(false); } catch (final SQLException e) { throw new EFapsException(Context.class, "getConnection.SQLException", e); } return con; }
java
public static Connection getConnection() throws EFapsException { Connection con = null; try { con = Context.DATASOURCE.getConnection(); con.setAutoCommit(false); } catch (final SQLException e) { throw new EFapsException(Context.class, "getConnection.SQLException", e); } return con; }
[ "public", "static", "Connection", "getConnection", "(", ")", "throws", "EFapsException", "{", "Connection", "con", "=", "null", ";", "try", "{", "con", "=", "Context", ".", "DATASOURCE", ".", "getConnection", "(", ")", ";", "con", ".", "setAutoCommit", "(", ...
Returns a opened connection resource. If a previous close connection resource already exists, this already existing connection resource is returned. @return opened connection resource @throws EFapsException if connection resource cannot be created
[ "Returns", "a", "opened", "connection", "resource", ".", "If", "a", "previous", "close", "connection", "resource", "already", "exists", "this", "already", "existing", "connection", "resource", "is", "returned", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/Context.java#L853-L864
redbox-mint/redbox
plugins/transaction/curation/src/main/java/com/googlecode/fascinator/redbox/plugins/curation/redbox/CurationManager.java
CurationManager.workflowCuration
private void workflowCuration(JsonSimple response, JsonSimple message) { String oid = message.getString(null, "oid"); if (!workflowCompleted(oid)) { return; } // Resolve relationships before we continue try { JSONArray relations = mapRelations(oid); // Unless there was an error, we should be good to go if (relations != null) { JsonObject request = createTask(response, oid, "curation-request"); if (!relations.isEmpty()) { request.put("relationships", relations); } } } catch (Exception ex) { log.error("Error processing relations: ", ex); return; } }
java
private void workflowCuration(JsonSimple response, JsonSimple message) { String oid = message.getString(null, "oid"); if (!workflowCompleted(oid)) { return; } // Resolve relationships before we continue try { JSONArray relations = mapRelations(oid); // Unless there was an error, we should be good to go if (relations != null) { JsonObject request = createTask(response, oid, "curation-request"); if (!relations.isEmpty()) { request.put("relationships", relations); } } } catch (Exception ex) { log.error("Error processing relations: ", ex); return; } }
[ "private", "void", "workflowCuration", "(", "JsonSimple", "response", ",", "JsonSimple", "message", ")", "{", "String", "oid", "=", "message", ".", "getString", "(", "null", ",", "\"oid\"", ")", ";", "if", "(", "!", "workflowCompleted", "(", "oid", ")", ")...
Assess a workflow event to see how it effects curation @param response The response object @param message The incoming message
[ "Assess", "a", "workflow", "event", "to", "see", "how", "it", "effects", "curation" ]
train
https://github.com/redbox-mint/redbox/blob/1db230f218031b85c48c8603cbb04fce7ac6de0c/plugins/transaction/curation/src/main/java/com/googlecode/fascinator/redbox/plugins/curation/redbox/CurationManager.java#L236-L258
LableOrg/java-uniqueid
uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java
ResourceClaim.acquireLock
static String acquireLock(ZooKeeper zookeeper, String lockNode) throws KeeperException, InterruptedException { // Inspired by the queueing algorithm suggested here: // http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_Queues // Acquire a place in the queue by creating an ephemeral, sequential znode. String placeInLine = takeQueueTicket(zookeeper, lockNode); logger.debug("Acquiring lock, waiting in queue: {}.", placeInLine); // Wait in the queue until our turn has come. return waitInLine(zookeeper, lockNode, placeInLine); }
java
static String acquireLock(ZooKeeper zookeeper, String lockNode) throws KeeperException, InterruptedException { // Inspired by the queueing algorithm suggested here: // http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_Queues // Acquire a place in the queue by creating an ephemeral, sequential znode. String placeInLine = takeQueueTicket(zookeeper, lockNode); logger.debug("Acquiring lock, waiting in queue: {}.", placeInLine); // Wait in the queue until our turn has come. return waitInLine(zookeeper, lockNode, placeInLine); }
[ "static", "String", "acquireLock", "(", "ZooKeeper", "zookeeper", ",", "String", "lockNode", ")", "throws", "KeeperException", ",", "InterruptedException", "{", "// Inspired by the queueing algorithm suggested here:", "// http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_...
Try to acquire a lock on for choosing a resource. This method will wait until it has acquired the lock. @param zookeeper ZooKeeper connection to use. @param lockNode Path to the znode representing the locking queue. @return Name of the first node in the queue.
[ "Try", "to", "acquire", "a", "lock", "on", "for", "choosing", "a", "resource", ".", "This", "method", "will", "wait", "until", "it", "has", "acquired", "the", "lock", "." ]
train
https://github.com/LableOrg/java-uniqueid/blob/554e30b2277765f365e7c7f598108de0ab5744f4/uniqueid-zookeeper/src/main/java/org/lable/oss/uniqueid/zookeeper/ResourceClaim.java#L165-L175
stephenc/simple-java-mail
src/main/java/org/codemonkey/simplejavamail/Mailer.java
Mailer.createMailSession
public Session createMailSession(final String host, final int port, final String username, final String password) { Properties props = transportStrategy.generateProperties(); props.put(transportStrategy.propertyNameHost(), host); props.put(transportStrategy.propertyNamePort(), String.valueOf(port)); if (username != null) { props.put(transportStrategy.propertyNameUsername(), username); } if (password != null) { props.put(transportStrategy.propertyNameAuthenticate(), "true"); return Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { return Session.getInstance(props); } }
java
public Session createMailSession(final String host, final int port, final String username, final String password) { Properties props = transportStrategy.generateProperties(); props.put(transportStrategy.propertyNameHost(), host); props.put(transportStrategy.propertyNamePort(), String.valueOf(port)); if (username != null) { props.put(transportStrategy.propertyNameUsername(), username); } if (password != null) { props.put(transportStrategy.propertyNameAuthenticate(), "true"); return Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { return Session.getInstance(props); } }
[ "public", "Session", "createMailSession", "(", "final", "String", "host", ",", "final", "int", "port", ",", "final", "String", "username", ",", "final", "String", "password", ")", "{", "Properties", "props", "=", "transportStrategy", ".", "generateProperties", "...
Actually instantiates and configures the {@link Session} instance. Delegates resolving transport protocol specific properties to the {@link #transportStrategy} in two ways: <ol> <li>request an initial property list which the strategy may pre-populate</li> <li>by requesting the property names according to the respective transport protocol it handles (for the host property name it would be <em>"mail.smtp.host"</em> for SMTP and <em>"mail.smtps.host"</em> for SMTPS)</li> </ol> @param host The address URL of the SMTP server to be used. @param port The port of the SMTP server. @param username An optional username, may be <code>null</code>. @param password An optional password, may be <code>null</code>. @return A fully configured <code>Session</code> instance complete with transport protocol settings. @see TransportStrategy#generateProperties() @see TransportStrategy#propertyNameHost() @see TransportStrategy#propertyNamePort() @see TransportStrategy#propertyNameUsername() @see TransportStrategy#propertyNameAuthenticate()
[ "Actually", "instantiates", "and", "configures", "the", "{", "@link", "Session", "}", "instance", ".", "Delegates", "resolving", "transport", "protocol", "specific", "properties", "to", "the", "{", "@link", "#transportStrategy", "}", "in", "two", "ways", ":", "<...
train
https://github.com/stephenc/simple-java-mail/blob/8c5897e6bbc23c11e7c7eb5064f407625c653923/src/main/java/org/codemonkey/simplejavamail/Mailer.java#L152-L172
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/WriterUtils.java
WriterUtils.getCodecFactory
public static CodecFactory getCodecFactory(Optional<String> codecName, Optional<String> deflateLevel) { if (!codecName.isPresent()) { return CodecFactory.deflateCodec(ConfigurationKeys.DEFAULT_DEFLATE_LEVEL); } else if (codecName.get().equalsIgnoreCase(DataFileConstants.DEFLATE_CODEC)) { if (!deflateLevel.isPresent()) { return CodecFactory.deflateCodec(ConfigurationKeys.DEFAULT_DEFLATE_LEVEL); } return CodecFactory.deflateCodec(Integer.parseInt(deflateLevel.get())); } else { return CodecFactory.fromString(codecName.get().toLowerCase()); } }
java
public static CodecFactory getCodecFactory(Optional<String> codecName, Optional<String> deflateLevel) { if (!codecName.isPresent()) { return CodecFactory.deflateCodec(ConfigurationKeys.DEFAULT_DEFLATE_LEVEL); } else if (codecName.get().equalsIgnoreCase(DataFileConstants.DEFLATE_CODEC)) { if (!deflateLevel.isPresent()) { return CodecFactory.deflateCodec(ConfigurationKeys.DEFAULT_DEFLATE_LEVEL); } return CodecFactory.deflateCodec(Integer.parseInt(deflateLevel.get())); } else { return CodecFactory.fromString(codecName.get().toLowerCase()); } }
[ "public", "static", "CodecFactory", "getCodecFactory", "(", "Optional", "<", "String", ">", "codecName", ",", "Optional", "<", "String", ">", "deflateLevel", ")", "{", "if", "(", "!", "codecName", ".", "isPresent", "(", ")", ")", "{", "return", "CodecFactory...
Creates a {@link CodecFactory} based on the specified codec name and deflate level. If codecName is absent, then a {@link CodecFactory#deflateCodec(int)} is returned. Otherwise the codecName is converted into a {@link CodecFactory} via the {@link CodecFactory#fromString(String)} method. @param codecName the name of the codec to use (e.g. deflate, snappy, xz, etc.). @param deflateLevel must be an integer from [0-9], and is only applicable if the codecName is "deflate". @return a {@link CodecFactory}.
[ "Creates", "a", "{", "@link", "CodecFactory", "}", "based", "on", "the", "specified", "codec", "name", "and", "deflate", "level", ".", "If", "codecName", "is", "absent", "then", "a", "{", "@link", "CodecFactory#deflateCodec", "(", "int", ")", "}", "is", "r...
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/WriterUtils.java#L254-L265
alkacon/opencms-core
src/org/opencms/util/CmsRequestUtil.java
CmsRequestUtil.getJsonParameterMap
public static JSONObject getJsonParameterMap(Map<String, String[]> params) { JSONObject result = new JSONObject(); for (Map.Entry<String, String[]> entry : params.entrySet()) { String paramKey = entry.getKey(); JSONArray paramValue = new JSONArray(); for (int i = 0, l = entry.getValue().length; i < l; i++) { paramValue.put(entry.getValue()[i]); } try { result.putOpt(paramKey, paramValue); } catch (JSONException e) { // should never happen LOG.warn(e.getLocalizedMessage(), e); } } return result; }
java
public static JSONObject getJsonParameterMap(Map<String, String[]> params) { JSONObject result = new JSONObject(); for (Map.Entry<String, String[]> entry : params.entrySet()) { String paramKey = entry.getKey(); JSONArray paramValue = new JSONArray(); for (int i = 0, l = entry.getValue().length; i < l; i++) { paramValue.put(entry.getValue()[i]); } try { result.putOpt(paramKey, paramValue); } catch (JSONException e) { // should never happen LOG.warn(e.getLocalizedMessage(), e); } } return result; }
[ "public", "static", "JSONObject", "getJsonParameterMap", "(", "Map", "<", "String", ",", "String", "[", "]", ">", "params", ")", "{", "JSONObject", "result", "=", "new", "JSONObject", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", ...
Converts the given parameter map into an JSON object.<p> @param params the parameters map to convert @return the JSON representation of the given parameter map
[ "Converts", "the", "given", "parameter", "map", "into", "an", "JSON", "object", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsRequestUtil.java#L577-L594
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/MPP14Reader.java
MPP14Reader.processCustomValueLists
private void processCustomValueLists() throws IOException { DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask"); if (taskDir.hasEntry("Props")) { Props taskProps = new Props14(m_inputStreamFactory.getInstance(taskDir, "Props")); CustomFieldValueReader14 reader = new CustomFieldValueReader14(m_file.getProjectProperties(), m_file.getCustomFields(), m_outlineCodeVarMeta, m_outlineCodeVarData, m_outlineCodeFixedData, m_outlineCodeFixedData2, taskProps); reader.process(); } }
java
private void processCustomValueLists() throws IOException { DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask"); if (taskDir.hasEntry("Props")) { Props taskProps = new Props14(m_inputStreamFactory.getInstance(taskDir, "Props")); CustomFieldValueReader14 reader = new CustomFieldValueReader14(m_file.getProjectProperties(), m_file.getCustomFields(), m_outlineCodeVarMeta, m_outlineCodeVarData, m_outlineCodeFixedData, m_outlineCodeFixedData2, taskProps); reader.process(); } }
[ "private", "void", "processCustomValueLists", "(", ")", "throws", "IOException", "{", "DirectoryEntry", "taskDir", "=", "(", "DirectoryEntry", ")", "m_projectDir", ".", "getEntry", "(", "\"TBkndTask\"", ")", ";", "if", "(", "taskDir", ".", "hasEntry", "(", "\"Pr...
This method extracts and collates the value list information for custom column value lists. @throws IOException
[ "This", "method", "extracts", "and", "collates", "the", "value", "list", "information", "for", "custom", "column", "value", "lists", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPP14Reader.java#L206-L216
operasoftware/operaprestodriver
src/com/opera/core/systems/scope/stp/services/ScopeExec.java
ScopeExec.executeScreenWatcher
private ScreenWatcherResult executeScreenWatcher(ScreenWatcher.Builder builder, long timeout) { if (timeout <= 0) { timeout = 1; } // TODO(andreastt): Unsafe long to int cast builder.setTimeOut((int) timeout); builder.setWindowID(services.getWindowManager().getActiveWindowId()); Response response = executeMessage(ExecMessage.SETUP_SCREEN_WATCHER, builder, OperaIntervals.RESPONSE_TIMEOUT.getMs() + timeout); ScreenWatcherResult.Builder watcherBuilder = ScreenWatcherResult.newBuilder(); buildPayload(response, watcherBuilder); return watcherBuilder.build(); }
java
private ScreenWatcherResult executeScreenWatcher(ScreenWatcher.Builder builder, long timeout) { if (timeout <= 0) { timeout = 1; } // TODO(andreastt): Unsafe long to int cast builder.setTimeOut((int) timeout); builder.setWindowID(services.getWindowManager().getActiveWindowId()); Response response = executeMessage(ExecMessage.SETUP_SCREEN_WATCHER, builder, OperaIntervals.RESPONSE_TIMEOUT.getMs() + timeout); ScreenWatcherResult.Builder watcherBuilder = ScreenWatcherResult.newBuilder(); buildPayload(response, watcherBuilder); return watcherBuilder.build(); }
[ "private", "ScreenWatcherResult", "executeScreenWatcher", "(", "ScreenWatcher", ".", "Builder", "builder", ",", "long", "timeout", ")", "{", "if", "(", "timeout", "<=", "0", ")", "{", "timeout", "=", "1", ";", "}", "// TODO(andreastt): Unsafe long to int cast", "b...
Executes a screenwatcher with the given timeout and returns the result.
[ "Executes", "a", "screenwatcher", "with", "the", "given", "timeout", "and", "returns", "the", "result", "." ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/scope/stp/services/ScopeExec.java#L242-L260
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/actions/SaveXmlAction.java
SaveXmlAction.work
private void work(final IProject project, final String fileName) { FindBugsJob runFindBugs = new FindBugsJob("Saving SpotBugs XML data to " + fileName + "...", project) { @Override protected void runWithProgress(IProgressMonitor monitor) throws CoreException { BugCollection bugCollection = FindbugsPlugin.getBugCollection(project, monitor); try { bugCollection.writeXML(fileName); } catch (IOException e) { CoreException ex = new CoreException(FindbugsPlugin.createErrorStatus( "Can't write SpotBugs bug collection from project " + project + " to file " + fileName, e)); throw ex; } } }; runFindBugs.setRule(project); runFindBugs.scheduleInteractive(); }
java
private void work(final IProject project, final String fileName) { FindBugsJob runFindBugs = new FindBugsJob("Saving SpotBugs XML data to " + fileName + "...", project) { @Override protected void runWithProgress(IProgressMonitor monitor) throws CoreException { BugCollection bugCollection = FindbugsPlugin.getBugCollection(project, monitor); try { bugCollection.writeXML(fileName); } catch (IOException e) { CoreException ex = new CoreException(FindbugsPlugin.createErrorStatus( "Can't write SpotBugs bug collection from project " + project + " to file " + fileName, e)); throw ex; } } }; runFindBugs.setRule(project); runFindBugs.scheduleInteractive(); }
[ "private", "void", "work", "(", "final", "IProject", "project", ",", "final", "String", "fileName", ")", "{", "FindBugsJob", "runFindBugs", "=", "new", "FindBugsJob", "(", "\"Saving SpotBugs XML data to \"", "+", "fileName", "+", "\"...\"", ",", "project", ")", ...
Save the XML result of a FindBugs analysis on the given project, displaying a progress monitor. @param project The selected project. @param fileName The file name to store the XML to.
[ "Save", "the", "XML", "result", "of", "a", "FindBugs", "analysis", "on", "the", "given", "project", "displaying", "a", "progress", "monitor", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/actions/SaveXmlAction.java#L126-L142
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java
AvroUtils.getDirectorySchema
public static Schema getDirectorySchema(Path directory, Configuration conf, boolean latest) throws IOException { return getDirectorySchema(directory, FileSystem.get(conf), latest); }
java
public static Schema getDirectorySchema(Path directory, Configuration conf, boolean latest) throws IOException { return getDirectorySchema(directory, FileSystem.get(conf), latest); }
[ "public", "static", "Schema", "getDirectorySchema", "(", "Path", "directory", ",", "Configuration", "conf", ",", "boolean", "latest", ")", "throws", "IOException", "{", "return", "getDirectorySchema", "(", "directory", ",", "FileSystem", ".", "get", "(", "conf", ...
Get the latest avro schema for a directory @param directory the input dir that contains avro files @param conf configuration @param latest true to return latest schema, false to return oldest schema @return the latest/oldest schema in the directory @throws IOException
[ "Get", "the", "latest", "avro", "schema", "for", "a", "directory" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/AvroUtils.java#L519-L521
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertImpl.java
X509CertImpl.makeAltNames
private static Collection<List<?>> makeAltNames(GeneralNames names) { if (names.isEmpty()) { return Collections.<List<?>>emptySet(); } List<List<?>> newNames = new ArrayList<>(); for (GeneralName gname : names.names()) { GeneralNameInterface name = gname.getName(); List<Object> nameEntry = new ArrayList<>(2); nameEntry.add(Integer.valueOf(name.getType())); switch (name.getType()) { case GeneralNameInterface.NAME_RFC822: nameEntry.add(((RFC822Name) name).getName()); break; case GeneralNameInterface.NAME_DNS: nameEntry.add(((DNSName) name).getName()); break; case GeneralNameInterface.NAME_DIRECTORY: nameEntry.add(((X500Name) name).getRFC2253Name()); break; case GeneralNameInterface.NAME_URI: nameEntry.add(((URIName) name).getName()); break; case GeneralNameInterface.NAME_IP: try { nameEntry.add(((IPAddressName) name).getName()); } catch (IOException ioe) { // IPAddressName in cert is bogus throw new RuntimeException("IPAddress cannot be parsed", ioe); } break; case GeneralNameInterface.NAME_OID: nameEntry.add(((OIDName) name).getOID().toString()); break; default: // add DER encoded form DerOutputStream derOut = new DerOutputStream(); try { name.encode(derOut); } catch (IOException ioe) { // should not occur since name has already been decoded // from cert (this would indicate a bug in our code) throw new RuntimeException("name cannot be encoded", ioe); } nameEntry.add(derOut.toByteArray()); break; } newNames.add(Collections.unmodifiableList(nameEntry)); } return Collections.unmodifiableCollection(newNames); }
java
private static Collection<List<?>> makeAltNames(GeneralNames names) { if (names.isEmpty()) { return Collections.<List<?>>emptySet(); } List<List<?>> newNames = new ArrayList<>(); for (GeneralName gname : names.names()) { GeneralNameInterface name = gname.getName(); List<Object> nameEntry = new ArrayList<>(2); nameEntry.add(Integer.valueOf(name.getType())); switch (name.getType()) { case GeneralNameInterface.NAME_RFC822: nameEntry.add(((RFC822Name) name).getName()); break; case GeneralNameInterface.NAME_DNS: nameEntry.add(((DNSName) name).getName()); break; case GeneralNameInterface.NAME_DIRECTORY: nameEntry.add(((X500Name) name).getRFC2253Name()); break; case GeneralNameInterface.NAME_URI: nameEntry.add(((URIName) name).getName()); break; case GeneralNameInterface.NAME_IP: try { nameEntry.add(((IPAddressName) name).getName()); } catch (IOException ioe) { // IPAddressName in cert is bogus throw new RuntimeException("IPAddress cannot be parsed", ioe); } break; case GeneralNameInterface.NAME_OID: nameEntry.add(((OIDName) name).getOID().toString()); break; default: // add DER encoded form DerOutputStream derOut = new DerOutputStream(); try { name.encode(derOut); } catch (IOException ioe) { // should not occur since name has already been decoded // from cert (this would indicate a bug in our code) throw new RuntimeException("name cannot be encoded", ioe); } nameEntry.add(derOut.toByteArray()); break; } newNames.add(Collections.unmodifiableList(nameEntry)); } return Collections.unmodifiableCollection(newNames); }
[ "private", "static", "Collection", "<", "List", "<", "?", ">", ">", "makeAltNames", "(", "GeneralNames", "names", ")", "{", "if", "(", "names", ".", "isEmpty", "(", ")", ")", "{", "return", "Collections", ".", "<", "List", "<", "?", ">", ">", "emptyS...
Converts a GeneralNames structure into an immutable Collection of alternative names (subject or issuer) in the form required by {@link #getSubjectAlternativeNames} or {@link #getIssuerAlternativeNames}. @param names the GeneralNames to be converted @return an immutable Collection of alternative names
[ "Converts", "a", "GeneralNames", "structure", "into", "an", "immutable", "Collection", "of", "alternative", "names", "(", "subject", "or", "issuer", ")", "in", "the", "form", "required", "by", "{", "@link", "#getSubjectAlternativeNames", "}", "or", "{", "@link",...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/x509/X509CertImpl.java#L1563-L1613
prestodb/presto
presto-main/src/main/java/com/facebook/presto/sql/planner/GroupingOperationRewriter.java
GroupingOperationRewriter.calculateGrouping
static long calculateGrouping(Set<Integer> groupingSet, List<Integer> columns) { long grouping = (1L << columns.size()) - 1; for (int index = 0; index < columns.size(); index++) { int column = columns.get(index); if (groupingSet.contains(column)) { // Leftmost argument to grouping() (i.e. when index = 0) corresponds to // the most significant bit in the result. That is why we shift 1L starting // from the columns.size() - 1 bit index. grouping = grouping & ~(1L << (columns.size() - 1 - index)); } } return grouping; }
java
static long calculateGrouping(Set<Integer> groupingSet, List<Integer> columns) { long grouping = (1L << columns.size()) - 1; for (int index = 0; index < columns.size(); index++) { int column = columns.get(index); if (groupingSet.contains(column)) { // Leftmost argument to grouping() (i.e. when index = 0) corresponds to // the most significant bit in the result. That is why we shift 1L starting // from the columns.size() - 1 bit index. grouping = grouping & ~(1L << (columns.size() - 1 - index)); } } return grouping; }
[ "static", "long", "calculateGrouping", "(", "Set", "<", "Integer", ">", "groupingSet", ",", "List", "<", "Integer", ">", "columns", ")", "{", "long", "grouping", "=", "(", "1L", "<<", "columns", ".", "size", "(", ")", ")", "-", "1", ";", "for", "(", ...
The grouping function is used in conjunction with GROUPING SETS, ROLLUP and CUBE to indicate which columns are present in that grouping. <p>The grouping function must be invoked with arguments that exactly match the columns referenced in the corresponding GROUPING SET, ROLLUP or CUBE clause at the associated query level. Those column arguments are not evaluated and instead the function is re-written with the arguments below. <p>To compute the resulting bit set for a particular row, bits are assigned to the argument columns with the rightmost column being the most significant bit. For a given grouping, a bit is set to 0 if the corresponding column is included in the grouping and 1 otherwise. For an example, see the SQL documentation for the function. @param columns The column arguments with which the function was invoked converted to ordinals with respect to the base table column ordering. @param groupingSet A collection containing the ordinals of the columns present in the grouping. @return A bit set converted to decimal indicating which columns are present in the grouping. If a column is NOT present in the grouping its corresponding bit is set to 1 and to 0 if the column is present in the grouping.
[ "The", "grouping", "function", "is", "used", "in", "conjunction", "with", "GROUPING", "SETS", "ROLLUP", "and", "CUBE", "to", "indicate", "which", "columns", "are", "present", "in", "that", "grouping", "." ]
train
https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-main/src/main/java/com/facebook/presto/sql/planner/GroupingOperationRewriter.java#L107-L123
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/io/FileSupport.java
FileSupport.copyFile
public static void copyFile(String fileName, String newFileName, boolean overwriteExisting) throws IOException { copyFile(new File(fileName), newFileName, overwriteExisting); }
java
public static void copyFile(String fileName, String newFileName, boolean overwriteExisting) throws IOException { copyFile(new File(fileName), newFileName, overwriteExisting); }
[ "public", "static", "void", "copyFile", "(", "String", "fileName", ",", "String", "newFileName", ",", "boolean", "overwriteExisting", ")", "throws", "IOException", "{", "copyFile", "(", "new", "File", "(", "fileName", ")", ",", "newFileName", ",", "overwriteExis...
Copies a file. @param fileName @param newFileName @param overwriteExisting @throws IOException
[ "Copies", "a", "file", "." ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/io/FileSupport.java#L583-L585
Stratio/stratio-cassandra
src/java/org/apache/cassandra/config/Schema.java
Schema.getCFMetaData
public CFMetaData getCFMetaData(String keyspaceName, String cfName) { assert keyspaceName != null; KSMetaData ksm = keyspaces.get(keyspaceName); return (ksm == null) ? null : ksm.cfMetaData().get(cfName); }
java
public CFMetaData getCFMetaData(String keyspaceName, String cfName) { assert keyspaceName != null; KSMetaData ksm = keyspaces.get(keyspaceName); return (ksm == null) ? null : ksm.cfMetaData().get(cfName); }
[ "public", "CFMetaData", "getCFMetaData", "(", "String", "keyspaceName", ",", "String", "cfName", ")", "{", "assert", "keyspaceName", "!=", "null", ";", "KSMetaData", "ksm", "=", "keyspaces", ".", "get", "(", "keyspaceName", ")", ";", "return", "(", "ksm", "=...
Given a keyspace name & column family name, get the column family meta data. If the keyspace name or column family name is not valid this function returns null. @param keyspaceName The keyspace name @param cfName The ColumnFamily name @return ColumnFamily Metadata object or null if it wasn't found
[ "Given", "a", "keyspace", "name", "&", "column", "family", "name", "get", "the", "column", "family", "meta", "data", ".", "If", "the", "keyspace", "name", "or", "column", "family", "name", "is", "not", "valid", "this", "function", "returns", "null", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L190-L195
Impetus/Kundera
src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/GraphEntityMapper.java
GraphEntityMapper.deserializeIdAttributeValue
private Object deserializeIdAttributeValue(final EntityMetadata m, String idValue) { if (idValue == null) { return null; } Class<?> embeddableClass = m.getIdAttribute().getBindableJavaType(); Object embeddedObject = embeddedObject = KunderaCoreUtils.createNewInstance(embeddableClass); List<String> tokens = new ArrayList<String>(); StringTokenizer st = new StringTokenizer((String) idValue, COMPOSITE_KEY_SEPARATOR); while (st.hasMoreTokens()) { tokens.add((String) st.nextElement()); } int count = 0; for (Field embeddedField : embeddableClass.getDeclaredFields()) { if (!ReflectUtils.isTransientOrStatic(embeddedField)) { if (count < tokens.size()) { String value = tokens.get(count++); PropertyAccessorHelper.set(embeddedObject, embeddedField, value); } } } return embeddedObject; }
java
private Object deserializeIdAttributeValue(final EntityMetadata m, String idValue) { if (idValue == null) { return null; } Class<?> embeddableClass = m.getIdAttribute().getBindableJavaType(); Object embeddedObject = embeddedObject = KunderaCoreUtils.createNewInstance(embeddableClass); List<String> tokens = new ArrayList<String>(); StringTokenizer st = new StringTokenizer((String) idValue, COMPOSITE_KEY_SEPARATOR); while (st.hasMoreTokens()) { tokens.add((String) st.nextElement()); } int count = 0; for (Field embeddedField : embeddableClass.getDeclaredFields()) { if (!ReflectUtils.isTransientOrStatic(embeddedField)) { if (count < tokens.size()) { String value = tokens.get(count++); PropertyAccessorHelper.set(embeddedObject, embeddedField, value); } } } return embeddedObject; }
[ "private", "Object", "deserializeIdAttributeValue", "(", "final", "EntityMetadata", "m", ",", "String", "idValue", ")", "{", "if", "(", "idValue", "==", "null", ")", "{", "return", "null", ";", "}", "Class", "<", "?", ">", "embeddableClass", "=", "m", ".",...
Prepares Embedded ID field from value prepared via serializeIdAttributeValue method.
[ "Prepares", "Embedded", "ID", "field", "from", "value", "prepared", "via", "serializeIdAttributeValue", "method", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/GraphEntityMapper.java#L542-L570
micwin/ticino
context/src/main/java/net/micwin/ticino/context/GenericContext.java
GenericContext.lookup
@Override public <TargetContextType extends IModifyableContext<ElementType>> TargetContextType lookup( final Predicate<ElementType> pPredicate, final TargetContextType pTarget) { return lookup(pPredicate, Integer.MAX_VALUE, pTarget); }
java
@Override public <TargetContextType extends IModifyableContext<ElementType>> TargetContextType lookup( final Predicate<ElementType> pPredicate, final TargetContextType pTarget) { return lookup(pPredicate, Integer.MAX_VALUE, pTarget); }
[ "@", "Override", "public", "<", "TargetContextType", "extends", "IModifyableContext", "<", "ElementType", ">", ">", "TargetContextType", "lookup", "(", "final", "Predicate", "<", "ElementType", ">", "pPredicate", ",", "final", "TargetContextType", "pTarget", ")", "{...
Looks up elements that match given predicate and returns them in given {@link IModifyableContext}. @param pPredicate The criteria the elements must match to be found. @param pTarget Where the found elements were put into.
[ "Looks", "up", "elements", "that", "match", "given", "predicate", "and", "returns", "them", "in", "given", "{", "@link", "IModifyableContext", "}", "." ]
train
https://github.com/micwin/ticino/blob/4d143093500cd2fb9767ebe8cd05ddda23e35613/context/src/main/java/net/micwin/ticino/context/GenericContext.java#L80-L85
ehcache/ehcache3
impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java
RobustLoaderWriterResilienceStrategy.putFailure
@Override public void putFailure(K key, V value, StoreAccessException e) { try { loaderWriter.write(key, value); } catch (Exception e1) { throw ExceptionFactory.newCacheWritingException(e1, e); } finally { cleanup(key, e); } }
java
@Override public void putFailure(K key, V value, StoreAccessException e) { try { loaderWriter.write(key, value); } catch (Exception e1) { throw ExceptionFactory.newCacheWritingException(e1, e); } finally { cleanup(key, e); } }
[ "@", "Override", "public", "void", "putFailure", "(", "K", "key", ",", "V", "value", ",", "StoreAccessException", "e", ")", "{", "try", "{", "loaderWriter", ".", "write", "(", "key", ",", "value", ")", ";", "}", "catch", "(", "Exception", "e1", ")", ...
Write the value to the loader-write. @param key the key being put @param value the value being put @param e the triggered failure
[ "Write", "the", "value", "to", "the", "loader", "-", "write", "." ]
train
https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategy.java#L86-L95
Netflix/eureka
eureka-core/src/main/java/com/netflix/eureka/cluster/PeerEurekaNode.java
PeerEurekaNode.deleteStatusOverride
public void deleteStatusOverride(final String appName, final String id, final InstanceInfo info) { long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs; batchingDispatcher.process( taskId("deleteStatusOverride", appName, id), new InstanceReplicationTask(targetHost, Action.DeleteStatusOverride, info, null, false) { @Override public EurekaHttpResponse<Void> execute() { return replicationClient.deleteStatusOverride(appName, id, info); } }, expiryTime); }
java
public void deleteStatusOverride(final String appName, final String id, final InstanceInfo info) { long expiryTime = System.currentTimeMillis() + maxProcessingDelayMs; batchingDispatcher.process( taskId("deleteStatusOverride", appName, id), new InstanceReplicationTask(targetHost, Action.DeleteStatusOverride, info, null, false) { @Override public EurekaHttpResponse<Void> execute() { return replicationClient.deleteStatusOverride(appName, id, info); } }, expiryTime); }
[ "public", "void", "deleteStatusOverride", "(", "final", "String", "appName", ",", "final", "String", "id", ",", "final", "InstanceInfo", "info", ")", "{", "long", "expiryTime", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "maxProcessingDelayMs", ";", ...
Delete instance status override. @param appName the application name of the instance. @param id the unique identifier of the instance. @param info the instance information of the instance.
[ "Delete", "instance", "status", "override", "." ]
train
https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/cluster/PeerEurekaNode.java#L294-L305
synchronoss/cpo-api
cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java
JdbcCpoAdapter.executeObject
@Override public <T> T executeObject(T object) throws CpoException { return processExecuteGroup(null, object, object); }
java
@Override public <T> T executeObject(T object) throws CpoException { return processExecuteGroup(null, object, object); }
[ "@", "Override", "public", "<", "T", ">", "T", "executeObject", "(", "T", "object", ")", "throws", "CpoException", "{", "return", "processExecuteGroup", "(", "null", ",", "object", ",", "object", ")", ";", "}" ]
Executes an Object whose metadata will call an executable within the datasource. It is assumed that the executable object exists in the metadatasource. If the executable does not exist, an exception will be thrown. <p/> <pre>Example: <code> <p/> class SomeObject so = new SomeObject(); class CpoAdapter cpo = null; <p/> try { cpo = new JdbcCpoAdapter(new JdbcDataSourceInfo(driver, url, user, password,1,1,false)); } catch (CpoException ce) { // Handle the error cpo = null; } <p/> if (cpo!=null) { so.setId(1); so.setName("SomeName"); try{ cpo.executeObject(so); } catch (CpoException ce) { // Handle the error } } </code> </pre> @param object This is an Object that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the object does not exist in the datasource, an exception will be thrown. This object is used to populate the IN arguments used to executed the datasource object. <p/> An object of this type will be created and filled with the returned data from the value_object. This newly created object will be returned from this method. @return An object populated with the OUT arguments returned from the executable object @throws CpoException Thrown if there are errors accessing the datasource
[ "Executes", "an", "Object", "whose", "metadata", "will", "call", "an", "executable", "within", "the", "datasource", ".", "It", "is", "assumed", "that", "the", "executable", "object", "exists", "in", "the", "metadatasource", ".", "If", "the", "executable", "doe...
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-jdbc/src/main/java/org/synchronoss/cpo/jdbc/JdbcCpoAdapter.java#L780-L783