repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
192
func_name
stringlengths
5
108
whole_func_string
stringlengths
75
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.91k
func_code_tokens
listlengths
21
629
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
111
306
knowm/Yank
src/main/java/org/knowm/yank/Yank.java
Yank.queryBeanSQLKey
public static <T> T queryBeanSQLKey(String sqlKey, Class<T> beanType, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return queryBeanSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, beanType, params); }
java
public static <T> T queryBeanSQLKey(String sqlKey, Class<T> beanType, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return queryBeanSQLKey(YankPoolManager.DEFAULT_POOL_NAME, sqlKey, beanType, params); }
[ "public", "static", "<", "T", ">", "T", "queryBeanSQLKey", "(", "String", "sqlKey", ",", "Class", "<", "T", ">", "beanType", ",", "Object", "[", "]", "params", ")", "throws", "SQLStatementNotFoundException", ",", "YankSQLException", "{", "return", "queryBeanSQ...
Return just one Bean given a SQL Key using an SQL statement matching the sqlKey String in a properties file loaded via Yank.addSQLStatements(...). If more than one row match the query, only the first row is returned using the default connection pool. @param sqlKey The SQL Key found in a properties file corresponding to the desired SQL statement value @param params The replacement parameters @param beanType The Class of the desired return Object matching the table @return The Object @throws SQLStatementNotFoundException if an SQL statement could not be found for the given sqlKey String
[ "Return", "just", "one", "Bean", "given", "a", "SQL", "Key", "using", "an", "SQL", "statement", "matching", "the", "sqlKey", "String", "in", "a", "properties", "file", "loaded", "via", "Yank", ".", "addSQLStatements", "(", "...", ")", ".", "If", "more", ...
train
https://github.com/knowm/Yank/blob/b2071dcd94da99db6904355f9557456b8b292a6b/src/main/java/org/knowm/yank/Yank.java#L338-L342
Jasig/uPortal
uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/GroupService.java
GroupService.igetGroupMember
private IGroupMember igetGroupMember(String key, Class<?> type) throws GroupsException { return compositeGroupService.getGroupMember(key, type); }
java
private IGroupMember igetGroupMember(String key, Class<?> type) throws GroupsException { return compositeGroupService.getGroupMember(key, type); }
[ "private", "IGroupMember", "igetGroupMember", "(", "String", "key", ",", "Class", "<", "?", ">", "type", ")", "throws", "GroupsException", "{", "return", "compositeGroupService", ".", "getGroupMember", "(", "key", ",", "type", ")", ";", "}" ]
Returns an <code>IGroupMember</code> representing either a group or a portal entity. If the parm <code>type</code> is the group type, the <code>IGroupMember</code> is an <code> IEntityGroup</code> else it is an <code>IEntity</code>.
[ "Returns", "an", "<code", ">", "IGroupMember<", "/", "code", ">", "representing", "either", "a", "group", "or", "a", "portal", "entity", ".", "If", "the", "parm", "<code", ">", "type<", "/", "code", ">", "is", "the", "group", "type", "the", "<code", ">...
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-groups/uPortal-groups-core/src/main/java/org/apereo/portal/services/GroupService.java#L295-L297
finmath/finmath-lib
src/main/java6/net/finmath/functions/AnalyticFormulas.java
AnalyticFormulas.blackScholesGeneralizedOptionValue
public static double blackScholesGeneralizedOptionValue( double forward, double volatility, double optionMaturity, double optionStrike, double payoffUnit) { if(optionMaturity < 0) { return 0; } else if(forward < 0) { // We use max(X,0) = X + max(-X,0) return (forward - optionStrike) * payoffUnit + blackScholesGeneralizedOptionValue(-forward, volatility, optionMaturity, -optionStrike, payoffUnit); } else if((forward == 0) || (optionStrike <= 0.0) || (volatility <= 0.0) || (optionMaturity <= 0.0)) { // Limit case (where dPlus = +/- infty) return Math.max(forward - optionStrike,0) * payoffUnit; } else { // Calculate analytic value double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit; return valueAnalytic; } }
java
public static double blackScholesGeneralizedOptionValue( double forward, double volatility, double optionMaturity, double optionStrike, double payoffUnit) { if(optionMaturity < 0) { return 0; } else if(forward < 0) { // We use max(X,0) = X + max(-X,0) return (forward - optionStrike) * payoffUnit + blackScholesGeneralizedOptionValue(-forward, volatility, optionMaturity, -optionStrike, payoffUnit); } else if((forward == 0) || (optionStrike <= 0.0) || (volatility <= 0.0) || (optionMaturity <= 0.0)) { // Limit case (where dPlus = +/- infty) return Math.max(forward - optionStrike,0) * payoffUnit; } else { // Calculate analytic value double dPlus = (Math.log(forward / optionStrike) + 0.5 * volatility * volatility * optionMaturity) / (volatility * Math.sqrt(optionMaturity)); double dMinus = dPlus - volatility * Math.sqrt(optionMaturity); double valueAnalytic = (forward * NormalDistribution.cumulativeDistribution(dPlus) - optionStrike * NormalDistribution.cumulativeDistribution(dMinus)) * payoffUnit; return valueAnalytic; } }
[ "public", "static", "double", "blackScholesGeneralizedOptionValue", "(", "double", "forward", ",", "double", "volatility", ",", "double", "optionMaturity", ",", "double", "optionStrike", ",", "double", "payoffUnit", ")", "{", "if", "(", "optionMaturity", "<", "0", ...
Calculates the Black-Scholes option value of a call, i.e., the payoff max(S(T)-K,0) P, where S follows a log-normal process with constant log-volatility. The method also handles cases where the forward and/or option strike is negative and some limit cases where the forward and/or the option strike is zero. @param forward The forward of the underlying. @param volatility The Black-Scholes volatility. @param optionMaturity The option maturity T. @param optionStrike The option strike. If the option strike is &le; 0.0 the method returns the value of the forward contract paying S(T)-K in T. @param payoffUnit The payoff unit (e.g., the discount factor) @return Returns the value of a European call option under the Black-Scholes model.
[ "Calculates", "the", "Black", "-", "Scholes", "option", "value", "of", "a", "call", "i", ".", "e", ".", "the", "payoff", "max", "(", "S", "(", "T", ")", "-", "K", "0", ")", "P", "where", "S", "follows", "a", "log", "-", "normal", "process", "with...
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java6/net/finmath/functions/AnalyticFormulas.java#L54-L83
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java
CanBeStaticAnalyzer.memberOfEnclosing
private static boolean memberOfEnclosing(Symbol owner, VisitorState state, Symbol sym) { if (sym == null || !sym.hasOuterInstance()) { return false; } for (ClassSymbol encl = owner.owner.enclClass(); encl != null; encl = encl.owner != null ? encl.owner.enclClass() : null) { if (sym.isMemberOf(encl, state.getTypes())) { return true; } } return false; }
java
private static boolean memberOfEnclosing(Symbol owner, VisitorState state, Symbol sym) { if (sym == null || !sym.hasOuterInstance()) { return false; } for (ClassSymbol encl = owner.owner.enclClass(); encl != null; encl = encl.owner != null ? encl.owner.enclClass() : null) { if (sym.isMemberOf(encl, state.getTypes())) { return true; } } return false; }
[ "private", "static", "boolean", "memberOfEnclosing", "(", "Symbol", "owner", ",", "VisitorState", "state", ",", "Symbol", "sym", ")", "{", "if", "(", "sym", "==", "null", "||", "!", "sym", ".", "hasOuterInstance", "(", ")", ")", "{", "return", "false", "...
Is sym a non-static member of an enclosing class of currentClass?
[ "Is", "sym", "a", "non", "-", "static", "member", "of", "an", "enclosing", "class", "of", "currentClass?" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java#L180-L192
jenetics/jenetics
jenetics/src/main/java/io/jenetics/engine/Limits.java
Limits.byExecutionTime
public static Predicate<Object> byExecutionTime(final Duration duration, final Clock clock) { return new ExecutionTimeLimit(duration, clock); }
java
public static Predicate<Object> byExecutionTime(final Duration duration, final Clock clock) { return new ExecutionTimeLimit(duration, clock); }
[ "public", "static", "Predicate", "<", "Object", ">", "byExecutionTime", "(", "final", "Duration", "duration", ",", "final", "Clock", "clock", ")", "{", "return", "new", "ExecutionTimeLimit", "(", "duration", ",", "clock", ")", ";", "}" ]
Return a predicate, which will truncate the evolution stream if the GA execution exceeds a given time duration. This predicate is (normally) used as safety net, for guaranteed stream truncation. <pre>{@code final Phenotype<DoubleGene, Double> result = engine.stream() // Truncate the evolution stream after 5 "steady" generations. .limit(bySteadyFitness(5)) // The evolution will stop after maximal 500 ms. .limit(byExecutionTime(Duration.ofMillis(500), Clock.systemUTC()) .collect(toBestPhenotype()); }</pre> @since 3.1 @param duration the duration after the evolution stream will be truncated @param clock the clock used for measure the execution time @return a predicate, which will truncate the evolution stream, based on the exceeded execution time @throws NullPointerException if one of the arguments is {@code null}
[ "Return", "a", "predicate", "which", "will", "truncate", "the", "evolution", "stream", "if", "the", "GA", "execution", "exceeds", "a", "given", "time", "duration", ".", "This", "predicate", "is", "(", "normally", ")", "used", "as", "safety", "net", "for", ...
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics/src/main/java/io/jenetics/engine/Limits.java#L143-L146
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/cp/internal/datastructures/lock/RaftLock.java
RaftLock.onSessionClose
@Override protected void onSessionClose(long sessionId, Map<Long, Object> responses) { removeInvocationRefUids(sessionId); if (owner != null && owner.sessionId() == sessionId) { ReleaseResult result = doRelease(owner.endpoint(), newUnsecureUUID(), lockCount); for (LockInvocationKey key : result.completedWaitKeys()) { responses.put(key.commitIndex(), result.ownership().getFence()); } } }
java
@Override protected void onSessionClose(long sessionId, Map<Long, Object> responses) { removeInvocationRefUids(sessionId); if (owner != null && owner.sessionId() == sessionId) { ReleaseResult result = doRelease(owner.endpoint(), newUnsecureUUID(), lockCount); for (LockInvocationKey key : result.completedWaitKeys()) { responses.put(key.commitIndex(), result.ownership().getFence()); } } }
[ "@", "Override", "protected", "void", "onSessionClose", "(", "long", "sessionId", ",", "Map", "<", "Long", ",", "Object", ">", "responses", ")", "{", "removeInvocationRefUids", "(", "sessionId", ")", ";", "if", "(", "owner", "!=", "null", "&&", "owner", "....
Releases the lock if the current lock holder's session is closed.
[ "Releases", "the", "lock", "if", "the", "current", "lock", "holder", "s", "session", "is", "closed", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/cp/internal/datastructures/lock/RaftLock.java#L234-L244
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/query/dsl/path/index/IndexReference.java
IndexReference.indexRef
public static final IndexReference indexRef(String indexName, IndexType type) { if (type == null) { return new IndexReference("`" + indexName + "`"); } return new IndexReference("`" + indexName + "` USING " + type.toString()); }
java
public static final IndexReference indexRef(String indexName, IndexType type) { if (type == null) { return new IndexReference("`" + indexName + "`"); } return new IndexReference("`" + indexName + "` USING " + type.toString()); }
[ "public", "static", "final", "IndexReference", "indexRef", "(", "String", "indexName", ",", "IndexType", "type", ")", "{", "if", "(", "type", "==", "null", ")", "{", "return", "new", "IndexReference", "(", "\"`\"", "+", "indexName", "+", "\"`\"", ")", ";",...
Constructs an {@link IndexReference} given an index name (which will be escaped) and an explicit {@link IndexType} to use in a USING clause.
[ "Constructs", "an", "{" ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/path/index/IndexReference.java#L57-L62
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/css/sass/ruby/JawrSassResolver.java
JawrSassResolver.getPath
public String getPath(String base, String uri) throws ResourceNotFoundException, IOException { String fileName = uri; if (!fileName.endsWith(".scss")) { fileName += ".scss"; } String parentPath = base.replace('\\', '/'); fileName = fileName.replace('\\', '/'); return PathNormalizer.concatWebPath(parentPath, fileName); }
java
public String getPath(String base, String uri) throws ResourceNotFoundException, IOException { String fileName = uri; if (!fileName.endsWith(".scss")) { fileName += ".scss"; } String parentPath = base.replace('\\', '/'); fileName = fileName.replace('\\', '/'); return PathNormalizer.concatWebPath(parentPath, fileName); }
[ "public", "String", "getPath", "(", "String", "base", ",", "String", "uri", ")", "throws", "ResourceNotFoundException", ",", "IOException", "{", "String", "fileName", "=", "uri", ";", "if", "(", "!", "fileName", ".", "endsWith", "(", "\".scss\"", ")", ")", ...
Returns the path of the resource @param base the base path @param uri the relative URI @return the resource path @throws ResourceNotFoundException if the resource is not found @throws IOException if an IOException occurs
[ "Returns", "the", "path", "of", "the", "resource" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/generator/css/sass/ruby/JawrSassResolver.java#L97-L108
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.notifications_sendEmailPlain
public String notifications_sendEmailPlain(Collection<Integer> recipientIds, CharSequence subject, CharSequence text) throws FacebookException, IOException { return notifications_sendEmail(recipientIds, subject, /*fbml*/null, text); }
java
public String notifications_sendEmailPlain(Collection<Integer> recipientIds, CharSequence subject, CharSequence text) throws FacebookException, IOException { return notifications_sendEmail(recipientIds, subject, /*fbml*/null, text); }
[ "public", "String", "notifications_sendEmailPlain", "(", "Collection", "<", "Integer", ">", "recipientIds", ",", "CharSequence", "subject", ",", "CharSequence", "text", ")", "throws", "FacebookException", ",", "IOException", "{", "return", "notifications_sendEmail", "("...
Sends a notification email to the specified users, who must have added your application. You can send five (5) emails to a user per day. Requires a session key for desktop applications, which may only send email to the person whose session it is. This method does not require a session for Web applications. @param recipientIds up to 100 user ids to which the message is to be sent @param subject the subject of the notification email (optional) @param text the plain text to send to the specified users via email @return a comma-separated list of the IDs of the users to whom the email was successfully sent @see <a href="http://wiki.developers.facebook.com/index.php/Notifications.sendEmail"> Developers Wiki: notifications.sendEmail</a>
[ "Sends", "a", "notification", "email", "to", "the", "specified", "users", "who", "must", "have", "added", "your", "application", ".", "You", "can", "send", "five", "(", "5", ")", "emails", "to", "a", "user", "per", "day", ".", "Requires", "a", "session",...
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1252-L1255
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java
DomHelper.setController
public void setController(Object parent, String name, GraphicsController controller) { // set them all doSetController(getElement(parent, name), controller, Event.TOUCHEVENTS | Event.MOUSEEVENTS | Event.ONDBLCLICK | Event.ONMOUSEWHEEL); }
java
public void setController(Object parent, String name, GraphicsController controller) { // set them all doSetController(getElement(parent, name), controller, Event.TOUCHEVENTS | Event.MOUSEEVENTS | Event.ONDBLCLICK | Event.ONMOUSEWHEEL); }
[ "public", "void", "setController", "(", "Object", "parent", ",", "String", "name", ",", "GraphicsController", "controller", ")", "{", "// set them all", "doSetController", "(", "getElement", "(", "parent", ",", "name", ")", ",", "controller", ",", "Event", ".", ...
Set the controller on an element of this <code>GraphicsContext</code> so it can react to events. @param parent the parent of the element on which the controller should be set. @param name the name of the child element on which the controller should be set @param controller The new <code>GraphicsController</code>
[ "Set", "the", "controller", "on", "an", "element", "of", "this", "<code", ">", "GraphicsContext<", "/", "code", ">", "so", "it", "can", "react", "to", "events", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L567-L571
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java
Configuration.getEnum
public <T extends Enum<T>> T getEnum(String name, T defaultValue) { final String val = get(name); return null == val ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), val); }
java
public <T extends Enum<T>> T getEnum(String name, T defaultValue) { final String val = get(name); return null == val ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), val); }
[ "public", "<", "T", "extends", "Enum", "<", "T", ">", ">", "T", "getEnum", "(", "String", "name", ",", "T", "defaultValue", ")", "{", "final", "String", "val", "=", "get", "(", "name", ")", ";", "return", "null", "==", "val", "?", "defaultValue", "...
Return value matching this enumerated type. @param name Property name @param defaultValue Value returned if no mapping exists @throws IllegalArgumentException If mapping is illegal for the type provided
[ "Return", "value", "matching", "this", "enumerated", "type", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/conf/Configuration.java#L923-L928
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java
SparseFlowObjectTracker.update
public boolean update( Image input , RectangleRotate_F64 output ) { if( trackLost ) return false; trackFeatures(input, region); // See if there are enough points remaining. use of config.numberOfSamples is some what arbitrary if( pairs.size() < config.numberOfSamples ) { System.out.println("Lack of sample pairs"); trackLost = true; return false; } // find the motion using tracked features if( !estimateMotion.process(pairs.toList()) ) { System.out.println("estimate motion failed"); trackLost = true; return false; } if( estimateMotion.getFitQuality() > config.robustMaxError ) { System.out.println("exceeded Max estimation error"); trackLost = true; return false; } // update the target's location using the found motion ScaleTranslateRotate2D model = estimateMotion.getModelParameters(); region.width *= model.scale; region.height *= model.scale; double c = Math.cos(model.theta); double s = Math.sin(model.theta); double x = region.cx; double y = region.cy; region.cx = (x*c - y*s)*model.scale + model.transX; region.cy = (x*s + y*c)*model.scale + model.transY; region.theta += model.theta; output.set(region); // make the current image into the previous image swapImages(); return true; }
java
public boolean update( Image input , RectangleRotate_F64 output ) { if( trackLost ) return false; trackFeatures(input, region); // See if there are enough points remaining. use of config.numberOfSamples is some what arbitrary if( pairs.size() < config.numberOfSamples ) { System.out.println("Lack of sample pairs"); trackLost = true; return false; } // find the motion using tracked features if( !estimateMotion.process(pairs.toList()) ) { System.out.println("estimate motion failed"); trackLost = true; return false; } if( estimateMotion.getFitQuality() > config.robustMaxError ) { System.out.println("exceeded Max estimation error"); trackLost = true; return false; } // update the target's location using the found motion ScaleTranslateRotate2D model = estimateMotion.getModelParameters(); region.width *= model.scale; region.height *= model.scale; double c = Math.cos(model.theta); double s = Math.sin(model.theta); double x = region.cx; double y = region.cy; region.cx = (x*c - y*s)*model.scale + model.transX; region.cy = (x*s + y*c)*model.scale + model.transY; region.theta += model.theta; output.set(region); // make the current image into the previous image swapImages(); return true; }
[ "public", "boolean", "update", "(", "Image", "input", ",", "RectangleRotate_F64", "output", ")", "{", "if", "(", "trackLost", ")", "return", "false", ";", "trackFeatures", "(", "input", ",", "region", ")", ";", "// See if there are enough points remaining. use of c...
Given the input image compute the new location of the target region and store the results in output. @param input next image in the sequence. @param output Storage for the output. @return true if tracking is successful
[ "Given", "the", "input", "image", "compute", "the", "new", "location", "of", "the", "target", "region", "and", "store", "the", "results", "in", "output", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/tracker/sfot/SparseFlowObjectTracker.java#L136-L186
igniterealtime/Smack
smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoMessageBuilder.java
OmemoMessageBuilder.setMessage
private void setMessage(String message) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException { if (message == null) { return; } // Encrypt message body SecretKey secretKey = new SecretKeySpec(messageKey, KEYTYPE); IvParameterSpec ivSpec = new IvParameterSpec(initializationVector); Cipher cipher = Cipher.getInstance(CIPHERMODE); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); byte[] body; byte[] ciphertext; body = message.getBytes(StringUtils.UTF8); ciphertext = cipher.doFinal(body); byte[] clearKeyWithAuthTag = new byte[messageKey.length + 16]; byte[] cipherTextWithoutAuthTag = new byte[ciphertext.length - 16]; moveAuthTag(messageKey, ciphertext, clearKeyWithAuthTag, cipherTextWithoutAuthTag); ciphertextMessage = cipherTextWithoutAuthTag; messageKey = clearKeyWithAuthTag; }
java
private void setMessage(String message) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException { if (message == null) { return; } // Encrypt message body SecretKey secretKey = new SecretKeySpec(messageKey, KEYTYPE); IvParameterSpec ivSpec = new IvParameterSpec(initializationVector); Cipher cipher = Cipher.getInstance(CIPHERMODE); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); byte[] body; byte[] ciphertext; body = message.getBytes(StringUtils.UTF8); ciphertext = cipher.doFinal(body); byte[] clearKeyWithAuthTag = new byte[messageKey.length + 16]; byte[] cipherTextWithoutAuthTag = new byte[ciphertext.length - 16]; moveAuthTag(messageKey, ciphertext, clearKeyWithAuthTag, cipherTextWithoutAuthTag); ciphertextMessage = cipherTextWithoutAuthTag; messageKey = clearKeyWithAuthTag; }
[ "private", "void", "setMessage", "(", "String", "message", ")", "throws", "NoSuchPaddingException", ",", "NoSuchAlgorithmException", ",", "InvalidAlgorithmParameterException", ",", "InvalidKeyException", ",", "UnsupportedEncodingException", ",", "BadPaddingException", ",", "I...
Encrypt the message with the aes key. Move the AuthTag from the end of the cipherText to the end of the messageKey afterwards. This prevents an attacker which compromised one recipient device to switch out the cipherText for other recipients. @see <a href="https://conversations.im/omemo/audit.pdf">OMEMO security audit</a>. @param message plaintext message @throws NoSuchPaddingException @throws NoSuchProviderException @throws InvalidAlgorithmParameterException @throws InvalidKeyException @throws UnsupportedEncodingException @throws BadPaddingException @throws IllegalBlockSizeException
[ "Encrypt", "the", "message", "with", "the", "aes", "key", ".", "Move", "the", "AuthTag", "from", "the", "end", "of", "the", "cipherText", "to", "the", "end", "of", "the", "messageKey", "afterwards", ".", "This", "prevents", "an", "attacker", "which", "comp...
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/util/OmemoMessageBuilder.java#L157-L181
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.setCertificateIssuer
public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) { return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).toBlocking().single().body(); }
java
public IssuerBundle setCertificateIssuer(String vaultBaseUrl, String issuerName, String provider) { return setCertificateIssuerWithServiceResponseAsync(vaultBaseUrl, issuerName, provider).toBlocking().single().body(); }
[ "public", "IssuerBundle", "setCertificateIssuer", "(", "String", "vaultBaseUrl", ",", "String", "issuerName", ",", "String", "provider", ")", "{", "return", "setCertificateIssuerWithServiceResponseAsync", "(", "vaultBaseUrl", ",", "issuerName", ",", "provider", ")", "."...
Sets the specified certificate issuer. The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param issuerName The name of the issuer. @param provider The issuer provider. @throws IllegalArgumentException thrown if parameters fail the validation @throws KeyVaultErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the IssuerBundle object if successful.
[ "Sets", "the", "specified", "certificate", "issuer", ".", "The", "SetCertificateIssuer", "operation", "adds", "or", "updates", "the", "specified", "certificate", "issuer", ".", "This", "operation", "requires", "the", "certificates", "/", "setissuers", "permission", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5900-L5902
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Model.java
Model.beforeClosingBrace
public void beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { StringWriter writer = new StringWriter(); beforeClosingBrace(pretty, indent, writer); sb.append(writer.toString()); }
java
public void beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { StringWriter writer = new StringWriter(); beforeClosingBrace(pretty, indent, writer); sb.append(writer.toString()); }
[ "public", "void", "beforeClosingBrace", "(", "StringBuilder", "sb", ",", "boolean", "pretty", ",", "String", "indent", ",", "String", "...", "attributeNames", ")", "{", "StringWriter", "writer", "=", "new", "StringWriter", "(", ")", ";", "beforeClosingBrace", "(...
Override in subclasses in order to inject custom content into Json just before the closing brace. <p>To keep the formatting, it is recommended to implement this method as the example below. <blockquote><pre> sb.append(','); if (pretty) { sb.append('\n').append(indent); } sb.append("\"test\":\"...\""); </pre></blockquote> @param sb to write custom content to @param pretty pretty format (human readable), or one line text. @param indent indent at current level @param attributeNames list of attributes to include
[ "Override", "in", "subclasses", "in", "order", "to", "inject", "custom", "content", "into", "Json", "just", "before", "the", "closing", "brace", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Model.java#L1178-L1182
lessthanoptimal/ddogleg
src/org/ddogleg/clustering/gmm/GaussianGmm_F64.java
GaussianGmm_F64.addCovariance
public void addCovariance( double[] difference , double responsibility ) { int N = mean.numRows; for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { covariance.data[i*N+j] += responsibility*difference[i]*difference[j]; } } for (int i = 0; i < N; i++) { for (int j = 0; j < i; j++) { covariance.data[i*N+j] = covariance.data[j*N+i]; } } }
java
public void addCovariance( double[] difference , double responsibility ) { int N = mean.numRows; for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { covariance.data[i*N+j] += responsibility*difference[i]*difference[j]; } } for (int i = 0; i < N; i++) { for (int j = 0; j < i; j++) { covariance.data[i*N+j] = covariance.data[j*N+i]; } } }
[ "public", "void", "addCovariance", "(", "double", "[", "]", "difference", ",", "double", "responsibility", ")", "{", "int", "N", "=", "mean", ".", "numRows", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "fo...
Helper function for computing Gaussian parameters. Adds the difference between point and mean to covariance, adjusted by the weight.
[ "Helper", "function", "for", "computing", "Gaussian", "parameters", ".", "Adds", "the", "difference", "between", "point", "and", "mean", "to", "covariance", "adjusted", "by", "the", "weight", "." ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/clustering/gmm/GaussianGmm_F64.java#L73-L86
protegeproject/jpaul
src/main/java/jpaul/Constraints/SetConstraints/SetConstraints.java
SetConstraints.addCtSource
public void addCtSource(Collection<T> ct, SVar<T> s) { this.add(new CtConstraint<SVar<T>,Set<T>>(new LinkedHashSet<T>(ct), s)); }
java
public void addCtSource(Collection<T> ct, SVar<T> s) { this.add(new CtConstraint<SVar<T>,Set<T>>(new LinkedHashSet<T>(ct), s)); }
[ "public", "void", "addCtSource", "(", "Collection", "<", "T", ">", "ct", ",", "SVar", "<", "T", ">", "s", ")", "{", "this", ".", "add", "(", "new", "CtConstraint", "<", "SVar", "<", "T", ">", ",", "Set", "<", "T", ">", ">", "(", "new", "LinkedH...
Adds an constraint of the form &quot;constant set <code>ct</code> is included in the set <code>s</code>&quot;.
[ "Adds", "an", "constraint", "of", "the", "form", "&quot", ";", "constant", "set", "<code", ">", "ct<", "/", "code", ">", "is", "included", "in", "the", "set", "<code", ">", "s<", "/", "code", ">", "&quot", ";", "." ]
train
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/Constraints/SetConstraints/SetConstraints.java#L32-L34
knowm/XChange
xchange-wex/src/main/java/org/knowm/xchange/wex/v3/service/WexMarketDataServiceRaw.java
WexMarketDataServiceRaw.getBTCEDepth
public WexDepthWrapper getBTCEDepth(String pairs, int size) throws IOException { if (size < 1) { size = 1; } if (size > FULL_SIZE) { size = FULL_SIZE; } return btce.getDepth(pairs.toLowerCase(), size, 1); }
java
public WexDepthWrapper getBTCEDepth(String pairs, int size) throws IOException { if (size < 1) { size = 1; } if (size > FULL_SIZE) { size = FULL_SIZE; } return btce.getDepth(pairs.toLowerCase(), size, 1); }
[ "public", "WexDepthWrapper", "getBTCEDepth", "(", "String", "pairs", ",", "int", "size", ")", "throws", "IOException", "{", "if", "(", "size", "<", "1", ")", "{", "size", "=", "1", ";", "}", "if", "(", "size", ">", "FULL_SIZE", ")", "{", "size", "=",...
Get market depth from exchange @param pairs Dash-delimited string of currency pairs to retrieve (e.g. "btc_usd-ltc_btc") @param size Integer value from 1 to 2000 -> get corresponding number of items @return WexDepthWrapper object @throws IOException
[ "Get", "market", "depth", "from", "exchange" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-wex/src/main/java/org/knowm/xchange/wex/v3/service/WexMarketDataServiceRaw.java#L43-L54
nutzam/nutzboot
nutzboot-starter/nutzboot-starter-fastdfs/src/main/java/org/nutz/boot/starter/fastdfs/FastdfsService.java
FastdfsService.uploadImage
public String uploadImage(byte[] image, byte[] watermark, String ext, Map<String, String> metaInfo, float opacity, int pos, int margin) { String path = ""; TrackerServer trackerServer = null; StorageClient1 storageClient1 = null; ByteArrayOutputStream thumbOs = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { trackerServer = fastDfsClientPool.borrowObject(); storageClient1 = new StorageClient1(trackerServer, null); NameValuePair data[] = null; if (Lang.isNotEmpty(metaInfo)) { data = new NameValuePair[metaInfo.size()]; int index = 0; for (Map.Entry<String, String> entry : metaInfo.entrySet()) { data[index] = new NameValuePair(entry.getKey(), entry.getValue()); index++; } } //保存原图 path = storageClient1.uploadFile1(image, ext, data); //保存水印图 作为原图的salve file BufferedImage bufferedImage = Images.addWatermark(image, watermark, opacity, pos, margin); Images.write(bufferedImage, ext, os); storageClient1.uploadFile1(path, IMAGE_WATERMARK_SUFFIX, os.toByteArray(), ext, data); //保存缩略图 BufferedImage read = Images.read(image); BufferedImage bufferedImageThumb = Images.zoomScale(read, IMAGE_THUMB_WIDTH, IMAGE_THUMB_HEIGHT); Images.write(bufferedImageThumb, ext, thumbOs); storageClient1.uploadFile1(path, IMAGE_THUMB_SUFFIX, thumbOs.toByteArray(), ext, data); } catch (Exception e) { throw Lang.makeThrow("[FastdfsService] upload images error : %s", e.getMessage()); } finally { Streams.safeClose(os); Streams.safeClose(thumbOs); try { if (trackerServer != null) fastDfsClientPool.returnObject(trackerServer); storageClient1 = null; } catch (Exception e) { log.error(e); } } return path; }
java
public String uploadImage(byte[] image, byte[] watermark, String ext, Map<String, String> metaInfo, float opacity, int pos, int margin) { String path = ""; TrackerServer trackerServer = null; StorageClient1 storageClient1 = null; ByteArrayOutputStream thumbOs = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { trackerServer = fastDfsClientPool.borrowObject(); storageClient1 = new StorageClient1(trackerServer, null); NameValuePair data[] = null; if (Lang.isNotEmpty(metaInfo)) { data = new NameValuePair[metaInfo.size()]; int index = 0; for (Map.Entry<String, String> entry : metaInfo.entrySet()) { data[index] = new NameValuePair(entry.getKey(), entry.getValue()); index++; } } //保存原图 path = storageClient1.uploadFile1(image, ext, data); //保存水印图 作为原图的salve file BufferedImage bufferedImage = Images.addWatermark(image, watermark, opacity, pos, margin); Images.write(bufferedImage, ext, os); storageClient1.uploadFile1(path, IMAGE_WATERMARK_SUFFIX, os.toByteArray(), ext, data); //保存缩略图 BufferedImage read = Images.read(image); BufferedImage bufferedImageThumb = Images.zoomScale(read, IMAGE_THUMB_WIDTH, IMAGE_THUMB_HEIGHT); Images.write(bufferedImageThumb, ext, thumbOs); storageClient1.uploadFile1(path, IMAGE_THUMB_SUFFIX, thumbOs.toByteArray(), ext, data); } catch (Exception e) { throw Lang.makeThrow("[FastdfsService] upload images error : %s", e.getMessage()); } finally { Streams.safeClose(os); Streams.safeClose(thumbOs); try { if (trackerServer != null) fastDfsClientPool.returnObject(trackerServer); storageClient1 = null; } catch (Exception e) { log.error(e); } } return path; }
[ "public", "String", "uploadImage", "(", "byte", "[", "]", "image", ",", "byte", "[", "]", "watermark", ",", "String", "ext", ",", "Map", "<", "String", ",", "String", ">", "metaInfo", ",", "float", "opacity", ",", "int", "pos", ",", "int", "margin", ...
上传图片并生成缩略图、水印图 @param image 原图 @param watermark 水印图 @param ext 后缀名 @param metaInfo 元信息 @param opacity 透明度 @param pos 位置 @param margin 水印距离四周的边距 默认为0 @return
[ "上传图片并生成缩略图、水印图" ]
train
https://github.com/nutzam/nutzboot/blob/fd33fd4fdce058eab594f28e4d3202f997e3c66a/nutzboot-starter/nutzboot-starter-fastdfs/src/main/java/org/nutz/boot/starter/fastdfs/FastdfsService.java#L436-L480
VoltDB/voltdb
src/frontend/org/voltdb/ClientAppBase.java
ClientAppBase.printLogStatic
protected static void printLogStatic(String className, String msg, Object...args) { if (args != null) { msg = String.format(msg, args); } String header = String.format("%s [%s] ", ZonedDateTime.now().format(TIME_FORMAT), className); System.out.println(String.format("%s%s", header, msg.replaceAll("\n", "\n" + header))); }
java
protected static void printLogStatic(String className, String msg, Object...args) { if (args != null) { msg = String.format(msg, args); } String header = String.format("%s [%s] ", ZonedDateTime.now().format(TIME_FORMAT), className); System.out.println(String.format("%s%s", header, msg.replaceAll("\n", "\n" + header))); }
[ "protected", "static", "void", "printLogStatic", "(", "String", "className", ",", "String", "msg", ",", "Object", "...", "args", ")", "{", "if", "(", "args", "!=", "null", ")", "{", "msg", "=", "String", ".", "format", "(", "msg", ",", "args", ")", "...
The static method to print a log message to the console. @param className Name of the class that prints this message. @param msg The log message that needs to be printed. @param args The arguments that may be needed for formatting the message.
[ "The", "static", "method", "to", "print", "a", "log", "message", "to", "the", "console", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/ClientAppBase.java#L53-L63
axibase/atsd-api-java
src/main/java/com/axibase/tsd/model/data/series/Sample.java
Sample.ofIsoDoubleText
public static Sample ofIsoDoubleText(String isoDate, double numericValue, String textValue) { return new Sample(null, isoDate, null, textValue) .setNumericValueFromDouble(numericValue); }
java
public static Sample ofIsoDoubleText(String isoDate, double numericValue, String textValue) { return new Sample(null, isoDate, null, textValue) .setNumericValueFromDouble(numericValue); }
[ "public", "static", "Sample", "ofIsoDoubleText", "(", "String", "isoDate", ",", "double", "numericValue", ",", "String", "textValue", ")", "{", "return", "new", "Sample", "(", "null", ",", "isoDate", ",", "null", ",", "textValue", ")", ".", "setNumericValueFro...
Creates a new {@link Sample} with date in ISO 8061 format, double and text value specified @param isoDate date in ISO 8061 format according to <a href="https://www.ietf.org/rfc/rfc3339.txt">RFC3339</a> @param numericValue the numeric value of the sample @param textValue the text value of the sample @return the Sample with specified fields
[ "Creates", "a", "new", "{", "@link", "Sample", "}", "with", "date", "in", "ISO", "8061", "format", "double", "and", "text", "value", "specified" ]
train
https://github.com/axibase/atsd-api-java/blob/63a0767d08b202dad2ebef4372ff947d6fba0246/src/main/java/com/axibase/tsd/model/data/series/Sample.java#L106-L109
usc/wechat-mp-sdk
wechat-mp-sdk/src/main/java/org/usc/wechat/mp/sdk/util/ReplyUtil.java
ReplyUtil.getDummyTextReplyDetailWarpper
public static ReplyDetailWarpper getDummyTextReplyDetailWarpper() { ReplyDetail replyDetail = new ReplyDetail(); replyDetail.setDescription("欢迎订阅javatech,这是微信公众平台开发模式的一个尝试,更多详情请见 https://github.com/usc/wechat-mp-sdk \n" + "Welcome subscribe javatech, this is an attempt to development model of wechat management platform, please via https://github.com/usc/wechat-mp-sdk to see more details"); return new ReplyDetailWarpper("text", Arrays.asList(replyDetail)); }
java
public static ReplyDetailWarpper getDummyTextReplyDetailWarpper() { ReplyDetail replyDetail = new ReplyDetail(); replyDetail.setDescription("欢迎订阅javatech,这是微信公众平台开发模式的一个尝试,更多详情请见 https://github.com/usc/wechat-mp-sdk \n" + "Welcome subscribe javatech, this is an attempt to development model of wechat management platform, please via https://github.com/usc/wechat-mp-sdk to see more details"); return new ReplyDetailWarpper("text", Arrays.asList(replyDetail)); }
[ "public", "static", "ReplyDetailWarpper", "getDummyTextReplyDetailWarpper", "(", ")", "{", "ReplyDetail", "replyDetail", "=", "new", "ReplyDetail", "(", ")", ";", "replyDetail", ".", "setDescription", "(", "\"欢迎订阅javatech,这是微信公众平台开发模式的一个尝试,更多详情请见 https://github.com/usc/wechat-m...
dummy reply. please according to your own situation to build ReplyDetailWarpper, and remove those code in production.
[ "dummy", "reply", ".", "please", "according", "to", "your", "own", "situation", "to", "build", "ReplyDetailWarpper", "and", "remove", "those", "code", "in", "production", "." ]
train
https://github.com/usc/wechat-mp-sdk/blob/39d9574a8e3ffa3b61f88b4bef534d93645a825f/wechat-mp-sdk/src/main/java/org/usc/wechat/mp/sdk/util/ReplyUtil.java#L65-L71
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java
MapConverter.getDateTime
public Date getDateTime(Map<String, Object> data, String name) { return get(data, name, Date.class); }
java
public Date getDateTime(Map<String, Object> data, String name) { return get(data, name, Date.class); }
[ "public", "Date", "getDateTime", "(", "Map", "<", "String", ",", "Object", ">", "data", ",", "String", "name", ")", "{", "return", "get", "(", "data", ",", "name", ",", "Date", ".", "class", ")", ";", "}" ]
<p> getDateTime. </p> @param data a {@link java.util.Map} object. @param name a {@link java.lang.String} object. @return a {@link java.util.Date} object.
[ "<p", ">", "getDateTime", ".", "<", "/", "p", ">" ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/collection/MapConverter.java#L231-L233
zxing/zxing
core/src/main/java/com/google/zxing/pdf417/encoder/PDF417.java
PDF417.getNumberOfPadCodewords
private static int getNumberOfPadCodewords(int m, int k, int c, int r) { int n = c * r - k; return n > m + 1 ? n - m - 1 : 0; }
java
private static int getNumberOfPadCodewords(int m, int k, int c, int r) { int n = c * r - k; return n > m + 1 ? n - m - 1 : 0; }
[ "private", "static", "int", "getNumberOfPadCodewords", "(", "int", "m", ",", "int", "k", ",", "int", "c", ",", "int", "r", ")", "{", "int", "n", "=", "c", "*", "r", "-", "k", ";", "return", "n", ">", "m", "+", "1", "?", "n", "-", "m", "-", ...
Calculates the number of pad codewords as described in 4.9.2 of ISO/IEC 15438:2001(E). @param m the number of source codewords prior to the additional of the Symbol Length Descriptor and any pad codewords @param k the number of error correction codewords @param c the number of columns in the symbol in the data region (excluding start, stop and row indicator codewords) @param r the number of rows in the symbol @return the number of pad codewords
[ "Calculates", "the", "number", "of", "pad", "codewords", "as", "described", "in", "4", ".", "9", ".", "2", "of", "ISO", "/", "IEC", "15438", ":", "2001", "(", "E", ")", "." ]
train
https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/pdf417/encoder/PDF417.java#L571-L574
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/util/ValidationObjUtil.java
ValidationObjUtil.getMethodName
public static String getMethodName(String name, String prefix) { return prefix + name.substring(0, 1).toUpperCase() + name.substring(1); }
java
public static String getMethodName(String name, String prefix) { return prefix + name.substring(0, 1).toUpperCase() + name.substring(1); }
[ "public", "static", "String", "getMethodName", "(", "String", "name", ",", "String", "prefix", ")", "{", "return", "prefix", "+", "name", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "name", ".", "substring", "(", "1", ...
Gets method name. @param name the name @param prefix the prefix @return the method name
[ "Gets", "method", "name", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/util/ValidationObjUtil.java#L184-L186
alkacon/opencms-core
src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java
CmsDefaultXmlContentHandler.addSimpleSearchSetting
protected void addSimpleSearchSetting(CmsXmlContentDefinition contentDef, String name, String value) throws CmsXmlException { if ("false".equalsIgnoreCase(value)) { addSearchSetting(contentDef, name, Boolean.FALSE); } else if ("true".equalsIgnoreCase(value)) { addSearchSetting(contentDef, name, Boolean.TRUE); } else { StringTemplate template = m_searchTemplateGroup.getInstanceOf(value); if ((template != null) && (template.getFormalArgument("name") != null)) { template.setAttribute("name", CmsEncoder.escapeXml(name)); String xml = template.toString(); try { Document doc = DocumentHelper.parseText(xml); initSearchSettings(doc.getRootElement(), contentDef); } catch (DocumentException e) { LOG.error(e.getLocalizedMessage(), e); } } } }
java
protected void addSimpleSearchSetting(CmsXmlContentDefinition contentDef, String name, String value) throws CmsXmlException { if ("false".equalsIgnoreCase(value)) { addSearchSetting(contentDef, name, Boolean.FALSE); } else if ("true".equalsIgnoreCase(value)) { addSearchSetting(contentDef, name, Boolean.TRUE); } else { StringTemplate template = m_searchTemplateGroup.getInstanceOf(value); if ((template != null) && (template.getFormalArgument("name") != null)) { template.setAttribute("name", CmsEncoder.escapeXml(name)); String xml = template.toString(); try { Document doc = DocumentHelper.parseText(xml); initSearchSettings(doc.getRootElement(), contentDef); } catch (DocumentException e) { LOG.error(e.getLocalizedMessage(), e); } } } }
[ "protected", "void", "addSimpleSearchSetting", "(", "CmsXmlContentDefinition", "contentDef", ",", "String", "name", ",", "String", "value", ")", "throws", "CmsXmlException", "{", "if", "(", "\"false\"", ".", "equalsIgnoreCase", "(", "value", ")", ")", "{", "addSea...
Adds search settings as defined by 'simple' syntax in fields.<p> @param contentDef the content definition @param name the element name @param value the search setting value @throws CmsXmlException if something goes wrong
[ "Adds", "search", "settings", "as", "defined", "by", "simple", "syntax", "in", "fields", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/content/CmsDefaultXmlContentHandler.java#L2120-L2140
samskivert/samskivert
src/main/java/com/samskivert/jdbc/JDBCUtil.java
JDBCUtil.checkedUpdate
public static void checkedUpdate (PreparedStatement stmt, int expectedCount) throws SQLException, PersistenceException { int modified = stmt.executeUpdate(); if (modified != expectedCount) { String err = "Statement did not modify expected number of rows [stmt=" + stmt + ", expected=" + expectedCount + ", modified=" + modified + "]"; throw new PersistenceException(err); } }
java
public static void checkedUpdate (PreparedStatement stmt, int expectedCount) throws SQLException, PersistenceException { int modified = stmt.executeUpdate(); if (modified != expectedCount) { String err = "Statement did not modify expected number of rows [stmt=" + stmt + ", expected=" + expectedCount + ", modified=" + modified + "]"; throw new PersistenceException(err); } }
[ "public", "static", "void", "checkedUpdate", "(", "PreparedStatement", "stmt", ",", "int", "expectedCount", ")", "throws", "SQLException", ",", "PersistenceException", "{", "int", "modified", "=", "stmt", ".", "executeUpdate", "(", ")", ";", "if", "(", "modified...
Calls <code>stmt.executeUpdate()</code> on the supplied statement, checking to see that it returns the expected update count and throwing a persistence exception if it does not.
[ "Calls", "<code", ">", "stmt", ".", "executeUpdate", "()", "<", "/", "code", ">", "on", "the", "supplied", "statement", "checking", "to", "see", "that", "it", "returns", "the", "expected", "update", "count", "and", "throwing", "a", "persistence", "exception"...
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/jdbc/JDBCUtil.java#L93-L102
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.getAttributeUUIDs
@Pure public static List<UUID> getAttributeUUIDs(Node document, String... path) { assert document != null : AssertMessages.notNullParameter(0); return getAttributeUUIDs(document, true, path); }
java
@Pure public static List<UUID> getAttributeUUIDs(Node document, String... path) { assert document != null : AssertMessages.notNullParameter(0); return getAttributeUUIDs(document, true, path); }
[ "@", "Pure", "public", "static", "List", "<", "UUID", ">", "getAttributeUUIDs", "(", "Node", "document", ",", "String", "...", "path", ")", "{", "assert", "document", "!=", "null", ":", "AssertMessages", ".", "notNullParameter", "(", "0", ")", ";", "return...
Replies the UUIDs that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. Be careful about the fact that the names are case sensitives. @param document is the XML document to explore. @param path is the list of and ended by the attribute's name. @return the UUIDs in the specified attribute, never <code>null</code>
[ "Replies", "the", "UUIDs", "that", "corresponds", "to", "the", "specified", "attribute", "s", "path", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L1099-L1103
netty/netty
buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java
CompositeByteBuf.addComponents
public CompositeByteBuf addComponents(int cIndex, Iterable<ByteBuf> buffers) { return addComponents(false, cIndex, buffers); }
java
public CompositeByteBuf addComponents(int cIndex, Iterable<ByteBuf> buffers) { return addComponents(false, cIndex, buffers); }
[ "public", "CompositeByteBuf", "addComponents", "(", "int", "cIndex", ",", "Iterable", "<", "ByteBuf", ">", "buffers", ")", "{", "return", "addComponents", "(", "false", ",", "cIndex", ",", "buffers", ")", ";", "}" ]
Add the given {@link ByteBuf}s on the specific index Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. If you need to have it increased you need to handle it by your own. <p> {@link ByteBuf#release()} ownership of all {@link ByteBuf} objects in {@code buffers} is transferred to this {@link CompositeByteBuf}. @param cIndex the index on which the {@link ByteBuf} will be added. @param buffers the {@link ByteBuf}s to add. {@link ByteBuf#release()} ownership of all {@link ByteBuf#release()} ownership of all {@link ByteBuf} objects is transferred to this {@link CompositeByteBuf}.
[ "Add", "the", "given", "{", "@link", "ByteBuf", "}", "s", "on", "the", "specific", "index" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java#L413-L415
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/EllipseClustersIntoGrid.java
EllipseClustersIntoGrid.findClosestEdge
protected static NodeInfo findClosestEdge( NodeInfo n , Point2D_F64 p ) { double bestDistance = Double.MAX_VALUE; NodeInfo best = null; for (int i = 0; i < n.edges.size(); i++) { Edge e = n.edges.get(i); if( e.target.marked ) continue; double d = e.target.ellipse.center.distance2(p); if( d < bestDistance ) { bestDistance = d; best = e.target; } } return best; }
java
protected static NodeInfo findClosestEdge( NodeInfo n , Point2D_F64 p ) { double bestDistance = Double.MAX_VALUE; NodeInfo best = null; for (int i = 0; i < n.edges.size(); i++) { Edge e = n.edges.get(i); if( e.target.marked ) continue; double d = e.target.ellipse.center.distance2(p); if( d < bestDistance ) { bestDistance = d; best = e.target; } } return best; }
[ "protected", "static", "NodeInfo", "findClosestEdge", "(", "NodeInfo", "n", ",", "Point2D_F64", "p", ")", "{", "double", "bestDistance", "=", "Double", ".", "MAX_VALUE", ";", "NodeInfo", "best", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i...
Finds the node which is an edge of 'n' that is closest to point 'p'
[ "Finds", "the", "node", "which", "is", "an", "edge", "of", "n", "that", "is", "closest", "to", "point", "p" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/alg/fiducial/calib/circle/EllipseClustersIntoGrid.java#L217-L234
openbase/jul
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/TimestampProcessor.java
TimestampProcessor.copyTimestamp
public static <M extends MessageOrBuilder> M copyTimestamp(final M sourceMessageOrBuilder, final M targetMessageOrBuilder) throws CouldNotPerformException { return TimestampProcessor.updateTimestamp(TimestampProcessor.getTimestamp(sourceMessageOrBuilder, TimeUnit.MICROSECONDS), targetMessageOrBuilder , TimeUnit.MICROSECONDS); }
java
public static <M extends MessageOrBuilder> M copyTimestamp(final M sourceMessageOrBuilder, final M targetMessageOrBuilder) throws CouldNotPerformException { return TimestampProcessor.updateTimestamp(TimestampProcessor.getTimestamp(sourceMessageOrBuilder, TimeUnit.MICROSECONDS), targetMessageOrBuilder , TimeUnit.MICROSECONDS); }
[ "public", "static", "<", "M", "extends", "MessageOrBuilder", ">", "M", "copyTimestamp", "(", "final", "M", "sourceMessageOrBuilder", ",", "final", "M", "targetMessageOrBuilder", ")", "throws", "CouldNotPerformException", "{", "return", "TimestampProcessor", ".", "upda...
Method copies the timestamp field of the source message into the target message. In case of an error the original message is returned. @param <M> the message type of the message to update. @param sourceMessageOrBuilder the message providing a timestamp. @param targetMessageOrBuilder the message offering a timestamp field to update. @return the updated message or the original one in case of errors. @throws CouldNotPerformException is thrown in case the copy could not be performed e.g. because of a missing timestamp field.
[ "Method", "copies", "the", "timestamp", "field", "of", "the", "source", "message", "into", "the", "target", "message", ".", "In", "case", "of", "an", "error", "the", "original", "message", "is", "returned", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/TimestampProcessor.java#L218-L220
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/UserResourcesImpl.java
UserResourcesImpl.promoteAlternateEmail
public AlternateEmail promoteAlternateEmail(long userId, long altEmailId) throws SmartsheetException { HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve( "users/" + userId + "/alternateemails/" + altEmailId + "/makeprimary"), HttpMethod.POST); Object obj = null; try { HttpResponse response = this.smartsheet.getHttpClient().request(request); switch (response.getStatusCode()) { case 200: obj = this.smartsheet.getJsonSerializer().deserializeResult(AlternateEmail.class, response.getEntity().getContent()); break; default: handleError(response); } } finally { smartsheet.getHttpClient().releaseConnection(); } return (AlternateEmail)obj; }
java
public AlternateEmail promoteAlternateEmail(long userId, long altEmailId) throws SmartsheetException { HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve( "users/" + userId + "/alternateemails/" + altEmailId + "/makeprimary"), HttpMethod.POST); Object obj = null; try { HttpResponse response = this.smartsheet.getHttpClient().request(request); switch (response.getStatusCode()) { case 200: obj = this.smartsheet.getJsonSerializer().deserializeResult(AlternateEmail.class, response.getEntity().getContent()); break; default: handleError(response); } } finally { smartsheet.getHttpClient().releaseConnection(); } return (AlternateEmail)obj; }
[ "public", "AlternateEmail", "promoteAlternateEmail", "(", "long", "userId", ",", "long", "altEmailId", ")", "throws", "SmartsheetException", "{", "HttpRequest", "request", "=", "createHttpRequest", "(", "smartsheet", ".", "getBaseURI", "(", ")", ".", "resolve", "(",...
Promote and alternate email to primary. @param userId id of the user @param altEmailId alternate email id @return alternateEmail of the primary @throws IllegalArgumentException if any argument is null or empty string @throws InvalidRequestException if there is any problem with the REST API request @throws AuthorizationException if there is any problem with the REST API authorization (access token) @throws ResourceNotFoundException if the resource cannot be found @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting) @throws SmartsheetException f there is any other error during the operation
[ "Promote", "and", "alternate", "email", "to", "primary", "." ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/UserResourcesImpl.java#L346-L367
Stratio/bdt
src/main/java/com/stratio/qa/utils/ElasticSearchUtils.java
ElasticSearchUtils.existsMapping
public boolean existsMapping(String indexName, String mappingName) { ClusterStateResponse resp = this.client.admin().cluster().prepareState().execute().actionGet(); if (resp.getState().getMetaData().index(indexName) == null) { return false; } ImmutableOpenMap<String, MappingMetaData> mappings = resp.getState().getMetaData().index(indexName).getMappings(); if (mappings.get(mappingName) != null) { return true; } return false; }
java
public boolean existsMapping(String indexName, String mappingName) { ClusterStateResponse resp = this.client.admin().cluster().prepareState().execute().actionGet(); if (resp.getState().getMetaData().index(indexName) == null) { return false; } ImmutableOpenMap<String, MappingMetaData> mappings = resp.getState().getMetaData().index(indexName).getMappings(); if (mappings.get(mappingName) != null) { return true; } return false; }
[ "public", "boolean", "existsMapping", "(", "String", "indexName", ",", "String", "mappingName", ")", "{", "ClusterStateResponse", "resp", "=", "this", ".", "client", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareState", "(", ")", ".", "exe...
Check if a mapping exists in an expecific index. @param indexName @param mappingName @return true if the mapping exists and false in other case
[ "Check", "if", "a", "mapping", "exists", "in", "an", "expecific", "index", "." ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/utils/ElasticSearchUtils.java#L200-L212
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/rest/DatastreamFilenameHelper.java
DatastreamFilenameHelper.addContentDispositionHeader
public final void addContentDispositionHeader(Context context, String pid, String dsID, String download, Date asOfDateTime, MIMETypedStream stream) throws Exception { String headerValue = null; String filename = null; // is downloading requested? if (download != null && download.equals("true")) { // generate an "attachment" content disposition header with the filename filename = getFilename(context, pid, dsID, asOfDateTime, stream.getMIMEType()); headerValue= attachmentHeader(filename); } else { // is the content disposition header enabled in the case of not downloading? if (m_datastreamContentDispositionInlineEnabled.equals("true")) { // it is... generate the header with "inline" filename = getFilename(context, pid, dsID, asOfDateTime, stream.getMIMEType()); headerValue= inlineHeader(filename); } } // create content disposition header to add Property[] header = { new Property ("content-disposition", headerValue) }; // add header to existing headers if present, or set this as the new header if not if (stream.header != null) { Property headers[] = new Property[stream.header.length + 1]; System.arraycopy(stream.header, 0, headers, 0, stream.header.length); headers[headers.length - 1] = header[0]; stream.header = headers; } else { stream.header = header; } }
java
public final void addContentDispositionHeader(Context context, String pid, String dsID, String download, Date asOfDateTime, MIMETypedStream stream) throws Exception { String headerValue = null; String filename = null; // is downloading requested? if (download != null && download.equals("true")) { // generate an "attachment" content disposition header with the filename filename = getFilename(context, pid, dsID, asOfDateTime, stream.getMIMEType()); headerValue= attachmentHeader(filename); } else { // is the content disposition header enabled in the case of not downloading? if (m_datastreamContentDispositionInlineEnabled.equals("true")) { // it is... generate the header with "inline" filename = getFilename(context, pid, dsID, asOfDateTime, stream.getMIMEType()); headerValue= inlineHeader(filename); } } // create content disposition header to add Property[] header = { new Property ("content-disposition", headerValue) }; // add header to existing headers if present, or set this as the new header if not if (stream.header != null) { Property headers[] = new Property[stream.header.length + 1]; System.arraycopy(stream.header, 0, headers, 0, stream.header.length); headers[headers.length - 1] = header[0]; stream.header = headers; } else { stream.header = header; } }
[ "public", "final", "void", "addContentDispositionHeader", "(", "Context", "context", ",", "String", "pid", ",", "String", "dsID", ",", "String", "download", ",", "Date", "asOfDateTime", ",", "MIMETypedStream", "stream", ")", "throws", "Exception", "{", "String", ...
Add a content disposition header to a MIMETypedStream based on configuration preferences. Header by default specifies "inline"; if download=true then "attachment" is specified. @param context @param pid @param dsID @param download true if file is to be downloaded @param asOfDateTime @param stream @throws Exception
[ "Add", "a", "content", "disposition", "header", "to", "a", "MIMETypedStream", "based", "on", "configuration", "preferences", ".", "Header", "by", "default", "specifies", "inline", ";", "if", "download", "=", "true", "then", "attachment", "is", "specified", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/rest/DatastreamFilenameHelper.java#L181-L210
Azure/azure-sdk-for-java
keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java
KeyVaultClientBaseImpl.signAsync
public Observable<KeyOperationResult> signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { return signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1<ServiceResponse<KeyOperationResult>, KeyOperationResult>() { @Override public KeyOperationResult call(ServiceResponse<KeyOperationResult> response) { return response.body(); } }); }
java
public Observable<KeyOperationResult> signAsync(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeySignatureAlgorithm algorithm, byte[] value) { return signWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).map(new Func1<ServiceResponse<KeyOperationResult>, KeyOperationResult>() { @Override public KeyOperationResult call(ServiceResponse<KeyOperationResult> response) { return response.body(); } }); }
[ "public", "Observable", "<", "KeyOperationResult", ">", "signAsync", "(", "String", "vaultBaseUrl", ",", "String", "keyName", ",", "String", "keyVersion", ",", "JsonWebKeySignatureAlgorithm", "algorithm", ",", "byte", "[", "]", "value", ")", "{", "return", "signWi...
Creates a signature from a digest using the specified key. The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation uses the private portion of the key. This operation requires the keys/sign permission. @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. @param keyName The name of the key. @param keyVersion The version of the key. @param algorithm The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'RSNULL', 'ES256', 'ES384', 'ES512', 'ES256K' @param value the Base64Url value @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the KeyOperationResult object
[ "Creates", "a", "signature", "from", "a", "digest", "using", "the", "specified", "key", ".", "The", "SIGN", "operation", "is", "applicable", "to", "asymmetric", "and", "symmetric", "keys", "stored", "in", "Azure", "Key", "Vault", "since", "this", "operation", ...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L2403-L2410
xvik/generics-resolver
src/main/java/ru/vyarus/java/generics/resolver/util/TypeToStringUtils.java
TypeToStringUtils.toStringWithGenerics
public static String toStringWithGenerics(final Class<?> type, final Map<String, Type> generics) { // provided generics may contain outer type generics, but we will render only required generics final Map<String, Type> actual = GenericsUtils.extractTypeGenerics(type, generics); return toStringType(new ParameterizedTypeImpl(type, actual.values().toArray(new Type[0])), actual); }
java
public static String toStringWithGenerics(final Class<?> type, final Map<String, Type> generics) { // provided generics may contain outer type generics, but we will render only required generics final Map<String, Type> actual = GenericsUtils.extractTypeGenerics(type, generics); return toStringType(new ParameterizedTypeImpl(type, actual.values().toArray(new Type[0])), actual); }
[ "public", "static", "String", "toStringWithGenerics", "(", "final", "Class", "<", "?", ">", "type", ",", "final", "Map", "<", "String", ",", "Type", ">", "generics", ")", "{", "// provided generics may contain outer type generics, but we will render only required generics...
Formats class as {@code Class<generics>}. Only actual class generics are rendered. Intended to be used for error reporting. <p> Note: if class is inned class, outer class is not printed! @param type class class to print with generics @param generics known generics map class generics map @return generified class string @see ru.vyarus.java.generics.resolver.util.map.PrintableGenericsMap to print not known generic names @see ru.vyarus.java.generics.resolver.util.map.IgnoreGenericsMap to print Object instead of not known generic
[ "Formats", "class", "as", "{", "@code", "Class<generics", ">", "}", ".", "Only", "actual", "class", "generics", "are", "rendered", ".", "Intended", "to", "be", "used", "for", "error", "reporting", ".", "<p", ">", "Note", ":", "if", "class", "is", "inned"...
train
https://github.com/xvik/generics-resolver/blob/d7d9d2783265df1178230e8f0b7cb6d853b67a7b/src/main/java/ru/vyarus/java/generics/resolver/util/TypeToStringUtils.java#L113-L117
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/CDCQueryResponseDeserializer.java
CDCQueryResponseDeserializer.getQueryResponse
private QueryResponse getQueryResponse(JsonNode jsonNode) throws IOException { ObjectMapper mapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule("QueryResponseDeserializer", new Version(1, 0, 0, null)); simpleModule.addDeserializer(QueryResponse.class, new QueryResponseDeserializer()); mapper.registerModule(simpleModule); return mapper.treeToValue(jsonNode, QueryResponse.class); }
java
private QueryResponse getQueryResponse(JsonNode jsonNode) throws IOException { ObjectMapper mapper = new ObjectMapper(); SimpleModule simpleModule = new SimpleModule("QueryResponseDeserializer", new Version(1, 0, 0, null)); simpleModule.addDeserializer(QueryResponse.class, new QueryResponseDeserializer()); mapper.registerModule(simpleModule); return mapper.treeToValue(jsonNode, QueryResponse.class); }
[ "private", "QueryResponse", "getQueryResponse", "(", "JsonNode", "jsonNode", ")", "throws", "IOException", "{", "ObjectMapper", "mapper", "=", "new", "ObjectMapper", "(", ")", ";", "SimpleModule", "simpleModule", "=", "new", "SimpleModule", "(", "\"QueryResponseDeseri...
Method to deserialize the QueryResponse object @param jsonNode @return QueryResponse
[ "Method", "to", "deserialize", "the", "QueryResponse", "object" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/serialization/CDCQueryResponseDeserializer.java#L125-L134
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/NodeReportsInner.java
NodeReportsInner.getContentAsync
public Observable<Object> getContentAsync(String resourceGroupName, String automationAccountName, String nodeId, String reportId) { return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeId, reportId).map(new Func1<ServiceResponse<Object>, Object>() { @Override public Object call(ServiceResponse<Object> response) { return response.body(); } }); }
java
public Observable<Object> getContentAsync(String resourceGroupName, String automationAccountName, String nodeId, String reportId) { return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeId, reportId).map(new Func1<ServiceResponse<Object>, Object>() { @Override public Object call(ServiceResponse<Object> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Object", ">", "getContentAsync", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "nodeId", ",", "String", "reportId", ")", "{", "return", "getContentWithServiceResponseAsync", "(", "resourceGroupNa...
Retrieve the Dsc node reports by node id and report id. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param nodeId The Dsc node id. @param reportId The report id. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the Object object
[ "Retrieve", "the", "Dsc", "node", "reports", "by", "node", "id", "and", "report", "id", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/NodeReportsInner.java#L474-L481
mikepenz/FastAdapter
library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/ActionModeHelper.java
ActionModeHelper.onLongClick
public ActionMode onLongClick(AppCompatActivity act, int position) { if (mActionMode == null && mFastAdapter.getItem(position).isSelectable()) { //may check if actionMode is already displayed mActionMode = act.startSupportActionMode(mInternalCallback); //we have to select this on our own as we will consume the event mSelectExtension.select(position); // update title checkActionMode(act, 1); //we consume this event so the normal onClick isn't called anymore return mActionMode; } return mActionMode; }
java
public ActionMode onLongClick(AppCompatActivity act, int position) { if (mActionMode == null && mFastAdapter.getItem(position).isSelectable()) { //may check if actionMode is already displayed mActionMode = act.startSupportActionMode(mInternalCallback); //we have to select this on our own as we will consume the event mSelectExtension.select(position); // update title checkActionMode(act, 1); //we consume this event so the normal onClick isn't called anymore return mActionMode; } return mActionMode; }
[ "public", "ActionMode", "onLongClick", "(", "AppCompatActivity", "act", ",", "int", "position", ")", "{", "if", "(", "mActionMode", "==", "null", "&&", "mFastAdapter", ".", "getItem", "(", "position", ")", ".", "isSelectable", "(", ")", ")", "{", "//may chec...
implements the basic behavior of a CAB and multi select behavior onLongClick @param act the current Activity @param position the position of the clicked item @return the initialized ActionMode or null if nothing was done
[ "implements", "the", "basic", "behavior", "of", "a", "CAB", "and", "multi", "select", "behavior", "onLongClick" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-extensions/src/main/java/com/mikepenz/fastadapter_extensions/ActionModeHelper.java#L146-L158
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java
Resolve.resolveMemberReference
Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env, JCMemberReference referenceTree, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes, MethodCheck methodCheck, InferenceContext inferenceContext, ReferenceChooser referenceChooser) { //step 1 - bound lookup ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper( referenceTree, site, name, argtypes, typeargtypes, VARARITY); Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup()); MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext(); boundSearchResolveContext.methodCheck = methodCheck; Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundSearchResolveContext, boundLookupHelper); ReferenceLookupResult boundRes = new ReferenceLookupResult(boundSym, boundSearchResolveContext); //step 2 - unbound lookup Symbol unboundSym = methodNotFound; Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup()); ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext); ReferenceLookupResult unboundRes = referenceNotFound; if (unboundLookupHelper != null) { MethodResolutionContext unboundSearchResolveContext = new MethodResolutionContext(); unboundSearchResolveContext.methodCheck = methodCheck; unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundSearchResolveContext, unboundLookupHelper); unboundRes = new ReferenceLookupResult(unboundSym, unboundSearchResolveContext); } //merge results Pair<Symbol, ReferenceLookupHelper> res; Symbol bestSym = referenceChooser.result(boundRes, unboundRes); res = new Pair<>(bestSym, bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper); env.info.pendingResolutionPhase = bestSym == unboundSym ? unboundEnv.info.pendingResolutionPhase : boundEnv.info.pendingResolutionPhase; return res; }
java
Pair<Symbol, ReferenceLookupHelper> resolveMemberReference(Env<AttrContext> env, JCMemberReference referenceTree, Type site, Name name, List<Type> argtypes, List<Type> typeargtypes, MethodCheck methodCheck, InferenceContext inferenceContext, ReferenceChooser referenceChooser) { //step 1 - bound lookup ReferenceLookupHelper boundLookupHelper = makeReferenceLookupHelper( referenceTree, site, name, argtypes, typeargtypes, VARARITY); Env<AttrContext> boundEnv = env.dup(env.tree, env.info.dup()); MethodResolutionContext boundSearchResolveContext = new MethodResolutionContext(); boundSearchResolveContext.methodCheck = methodCheck; Symbol boundSym = lookupMethod(boundEnv, env.tree.pos(), site.tsym, boundSearchResolveContext, boundLookupHelper); ReferenceLookupResult boundRes = new ReferenceLookupResult(boundSym, boundSearchResolveContext); //step 2 - unbound lookup Symbol unboundSym = methodNotFound; Env<AttrContext> unboundEnv = env.dup(env.tree, env.info.dup()); ReferenceLookupHelper unboundLookupHelper = boundLookupHelper.unboundLookup(inferenceContext); ReferenceLookupResult unboundRes = referenceNotFound; if (unboundLookupHelper != null) { MethodResolutionContext unboundSearchResolveContext = new MethodResolutionContext(); unboundSearchResolveContext.methodCheck = methodCheck; unboundSym = lookupMethod(unboundEnv, env.tree.pos(), site.tsym, unboundSearchResolveContext, unboundLookupHelper); unboundRes = new ReferenceLookupResult(unboundSym, unboundSearchResolveContext); } //merge results Pair<Symbol, ReferenceLookupHelper> res; Symbol bestSym = referenceChooser.result(boundRes, unboundRes); res = new Pair<>(bestSym, bestSym == unboundSym ? unboundLookupHelper : boundLookupHelper); env.info.pendingResolutionPhase = bestSym == unboundSym ? unboundEnv.info.pendingResolutionPhase : boundEnv.info.pendingResolutionPhase; return res; }
[ "Pair", "<", "Symbol", ",", "ReferenceLookupHelper", ">", "resolveMemberReference", "(", "Env", "<", "AttrContext", ">", "env", ",", "JCMemberReference", "referenceTree", ",", "Type", "site", ",", "Name", "name", ",", "List", "<", "Type", ">", "argtypes", ",",...
Resolution of member references is typically done as a single overload resolution step, where the argument types A are inferred from the target functional descriptor. If the member reference is a method reference with a type qualifier, a two-step lookup process is performed. The first step uses the expected argument list A, while the second step discards the first type from A (which is treated as a receiver type). There are two cases in which inference is performed: (i) if the member reference is a constructor reference and the qualifier type is raw - in which case diamond inference is used to infer a parameterization for the type qualifier; (ii) if the member reference is an unbound reference where the type qualifier is raw - in that case, during the unbound lookup the receiver argument type is used to infer an instantiation for the raw qualifier type. When a multi-step resolution process is exploited, the process of picking the resulting symbol is delegated to an helper class {@link com.sun.tools.javac.comp.Resolve.ReferenceChooser}. This routine returns a pair (T,S), where S is the member reference symbol, and T is the type of the class in which S is defined. This is necessary as the type T might be dynamically inferred (i.e. if constructor reference has a raw qualifier).
[ "Resolution", "of", "member", "references", "is", "typically", "done", "as", "a", "single", "overload", "resolution", "step", "where", "the", "argument", "types", "A", "are", "inferred", "from", "the", "target", "functional", "descriptor", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java#L2920-L2964
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormatSymbols.java
DecimalFormatSymbols.setPatternForCurrencySpacing
public void setPatternForCurrencySpacing(int itemType, boolean beforeCurrency, String pattern) { if (itemType < CURRENCY_SPC_CURRENCY_MATCH || itemType > CURRENCY_SPC_INSERT ) { throw new IllegalArgumentException("unknown currency spacing: " + itemType); } if (beforeCurrency) { currencySpcBeforeSym[itemType] = pattern; } else { currencySpcAfterSym[itemType] = pattern; } }
java
public void setPatternForCurrencySpacing(int itemType, boolean beforeCurrency, String pattern) { if (itemType < CURRENCY_SPC_CURRENCY_MATCH || itemType > CURRENCY_SPC_INSERT ) { throw new IllegalArgumentException("unknown currency spacing: " + itemType); } if (beforeCurrency) { currencySpcBeforeSym[itemType] = pattern; } else { currencySpcAfterSym[itemType] = pattern; } }
[ "public", "void", "setPatternForCurrencySpacing", "(", "int", "itemType", ",", "boolean", "beforeCurrency", ",", "String", "pattern", ")", "{", "if", "(", "itemType", "<", "CURRENCY_SPC_CURRENCY_MATCH", "||", "itemType", ">", "CURRENCY_SPC_INSERT", ")", "{", "throw"...
<strong>[icu]</strong> Sets the indicated currency spacing pattern or value. See {@link #getPatternForCurrencySpacing} for more information. <p>Values for currency match and surrounding match must be {@link android.icu.text.UnicodeSet} patterns. Values for insert can be any string. <p><strong>Note:</strong> ICU4J does not currently use this information. @param itemType one of CURRENCY_SPC_CURRENCY_MATCH, CURRENCY_SPC_SURROUNDING_MATCH or CURRENCY_SPC_INSERT @param beforeCurrency true if the pattern is for before the currency symbol. false if the pattern is for after it. @param pattern string to override current setting; can be null. @see #getPatternForCurrencySpacing(int, boolean)
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Sets", "the", "indicated", "currency", "spacing", "pattern", "or", "value", ".", "See", "{", "@link", "#getPatternForCurrencySpacing", "}", "for", "more", "information", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormatSymbols.java#L1006-L1016
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.sendTransaction
public CompletableFuture<TransactionEvent> sendTransaction(Collection<ProposalResponse> proposalResponses, User userContext) { return sendTransaction(proposalResponses, getOrderers(), userContext); }
java
public CompletableFuture<TransactionEvent> sendTransaction(Collection<ProposalResponse> proposalResponses, User userContext) { return sendTransaction(proposalResponses, getOrderers(), userContext); }
[ "public", "CompletableFuture", "<", "TransactionEvent", ">", "sendTransaction", "(", "Collection", "<", "ProposalResponse", ">", "proposalResponses", ",", "User", "userContext", ")", "{", "return", "sendTransaction", "(", "proposalResponses", ",", "getOrderers", "(", ...
Send transaction to one of the orderers on the channel using a specific user context. @param proposalResponses The proposal responses to be sent to the orderer. @param userContext The usercontext used for signing transaction. @return a future allowing access to the result of the transaction invocation once complete.
[ "Send", "transaction", "to", "one", "of", "the", "orderers", "on", "the", "channel", "using", "a", "specific", "user", "context", "." ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L4631-L4635
ngageoint/geopackage-java
src/main/java/mil/nga/geopackage/extension/style/IconCache.java
IconCache.put
public BufferedImage put(IconRow iconRow, BufferedImage image) { return put(iconRow.getId(), image); }
java
public BufferedImage put(IconRow iconRow, BufferedImage image) { return put(iconRow.getId(), image); }
[ "public", "BufferedImage", "put", "(", "IconRow", "iconRow", ",", "BufferedImage", "image", ")", "{", "return", "put", "(", "iconRow", ".", "getId", "(", ")", ",", "image", ")", ";", "}" ]
Cache the icon image for the icon row @param iconRow icon row @param image icon image @return previous cached icon image or null
[ "Cache", "the", "icon", "image", "for", "the", "icon", "row" ]
train
https://github.com/ngageoint/geopackage-java/blob/889bffb5d18330a3f4bd89443acf7959ebe3a376/src/main/java/mil/nga/geopackage/extension/style/IconCache.java#L94-L96
Erudika/para
para-client/src/main/java/com/erudika/para/client/ParaClient.java
ParaClient.grantResourcePermission
public Map<String, Map<String, List<String>>> grantResourcePermission(String subjectid, String resourcePath, EnumSet<App.AllowedMethods> permission, boolean allowGuestAccess) { if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) || permission == null) { return Collections.emptyMap(); } if (allowGuestAccess && App.ALLOW_ALL.equals(subjectid)) { permission.add(App.AllowedMethods.GUEST); } resourcePath = Utils.urlEncode(resourcePath); return getEntity(invokePut(Utils.formatMessage("_permissions/{0}/{1}", subjectid, resourcePath), Entity.json(permission)), Map.class); }
java
public Map<String, Map<String, List<String>>> grantResourcePermission(String subjectid, String resourcePath, EnumSet<App.AllowedMethods> permission, boolean allowGuestAccess) { if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) || permission == null) { return Collections.emptyMap(); } if (allowGuestAccess && App.ALLOW_ALL.equals(subjectid)) { permission.add(App.AllowedMethods.GUEST); } resourcePath = Utils.urlEncode(resourcePath); return getEntity(invokePut(Utils.formatMessage("_permissions/{0}/{1}", subjectid, resourcePath), Entity.json(permission)), Map.class); }
[ "public", "Map", "<", "String", ",", "Map", "<", "String", ",", "List", "<", "String", ">", ">", ">", "grantResourcePermission", "(", "String", "subjectid", ",", "String", "resourcePath", ",", "EnumSet", "<", "App", ".", "AllowedMethods", ">", "permission", ...
Grants a permission to a subject that allows them to call the specified HTTP methods on a given resource. @param subjectid subject id (user id) @param resourcePath resource path or object type @param permission a set of HTTP methods @param allowGuestAccess if true - all unauthenticated requests will go through, 'false' by default. @return a map of the permissions for this subject id
[ "Grants", "a", "permission", "to", "a", "subject", "that", "allows", "them", "to", "call", "the", "specified", "HTTP", "methods", "on", "a", "given", "resource", "." ]
train
https://github.com/Erudika/para/blob/5ba096c477042ea7b18e9a0e8b5b1ee0f5bd6ce9/para-client/src/main/java/com/erudika/para/client/ParaClient.java#L1444-L1455
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addErrorsNotLoadFromServer
public FessMessages addErrorsNotLoadFromServer(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_not_load_from_server, arg0)); return this; }
java
public FessMessages addErrorsNotLoadFromServer(String property, String arg0) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_not_load_from_server, arg0)); return this; }
[ "public", "FessMessages", "addErrorsNotLoadFromServer", "(", "String", "property", ",", "String", "arg0", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "ERRORS_not_load_from_server", ",", "arg0"...
Add the created action message for the key 'errors.not_load_from_server' with parameters. <pre> message: Could not load from this server: {0} </pre> @param property The property name for the message. (NotNull) @param arg0 The parameter arg0 for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "errors", ".", "not_load_from_server", "with", "parameters", ".", "<pre", ">", "message", ":", "Could", "not", "load", "from", "this", "server", ":", "{", "0", "}", "<", "/", "pre", ">" ]
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L1507-L1511
awslabs/amazon-sqs-java-extended-client-lib
src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClient.java
AmazonSQSExtendedClient.deleteMessageBatch
public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries) { DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest(queueUrl, entries); return deleteMessageBatch(deleteMessageBatchRequest); }
java
public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries) { DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest(queueUrl, entries); return deleteMessageBatch(deleteMessageBatchRequest); }
[ "public", "DeleteMessageBatchResult", "deleteMessageBatch", "(", "String", "queueUrl", ",", "List", "<", "DeleteMessageBatchRequestEntry", ">", "entries", ")", "{", "DeleteMessageBatchRequest", "deleteMessageBatchRequest", "=", "new", "DeleteMessageBatchRequest", "(", "queueU...
<p> Deletes up to ten messages from the specified queue. This is a batch version of DeleteMessage. The result of the delete action on each message is reported individually in the response. Also deletes the message payloads from Amazon S3 when necessary. </p> <p> <b>IMPORTANT:</b> Because the batch request can result in a combination of successful and unsuccessful actions, you should check for batch errors even when the call returns an HTTP status code of 200. </p> <p> <b>NOTE:</b>Some API actions take lists of parameters. These lists are specified using the param.n notation. Values of n are integers starting from 1. For example, a parameter list with two elements looks like this: </p> <p> <code>&Attribute.1=this</code> </p> <p> <code>&Attribute.2=that</code> </p> @param queueUrl The URL of the Amazon SQS queue to take action on. @param entries A list of receipt handles for the messages to be deleted. @return The response from the DeleteMessageBatch service method, as returned by AmazonSQS. @throws BatchEntryIdsNotDistinctException @throws TooManyEntriesInBatchRequestException @throws InvalidBatchEntryIdException @throws EmptyBatchRequestException @throws AmazonClientException If any internal errors are encountered inside the client while attempting to make the request or handle the response. For example if a network connection is not available. @throws AmazonServiceException If an error response is returned by AmazonSQS indicating either a problem with the data in the request, or a server side issue.
[ "<p", ">", "Deletes", "up", "to", "ten", "messages", "from", "the", "specified", "queue", ".", "This", "is", "a", "batch", "version", "of", "DeleteMessage", ".", "The", "result", "of", "the", "delete", "action", "on", "each", "message", "is", "reported", ...
train
https://github.com/awslabs/amazon-sqs-java-extended-client-lib/blob/df0c6251b99e682d6179938fe784590e662b84ea/src/main/java/com/amazon/sqs/javamessaging/AmazonSQSExtendedClient.java#L972-L975
couchbase/CouchbaseMock
src/main/java/com/couchbase/mock/memcached/VBucketStore.java
VBucketStore.forceDeleteMutation
void forceDeleteMutation(Item itm, VBucketCoordinates coords) { forceMutation(itm.getKeySpec().vbId, itm, coords, true); }
java
void forceDeleteMutation(Item itm, VBucketCoordinates coords) { forceMutation(itm.getKeySpec().vbId, itm, coords, true); }
[ "void", "forceDeleteMutation", "(", "Item", "itm", ",", "VBucketCoordinates", "coords", ")", "{", "forceMutation", "(", "itm", ".", "getKeySpec", "(", ")", ".", "vbId", ",", "itm", ",", "coords", ",", "true", ")", ";", "}" ]
Forces the deletion of an item from the case. @see #forceStorageMutation(Item, VBucketCoordinates) @param itm @param coords
[ "Forces", "the", "deletion", "of", "an", "item", "from", "the", "case", "." ]
train
https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/VBucketStore.java#L323-L325
micronaut-projects/micronaut-core
tracing/src/main/java/io/micronaut/tracing/brave/instrument/http/HttpTracingFactory.java
HttpTracingFactory.httpServerHandler
@Singleton HttpServerHandler<HttpRequest<?>, HttpResponse<?>> httpServerHandler(HttpTracing httpTracing) { return HttpServerHandler.create(httpTracing, new HttpServerAdapter<HttpRequest<?>, HttpResponse<?>>() { @Override public String method(HttpRequest<?> request) { return request.getMethod().name(); } @Override public String url(HttpRequest<?> request) { return request.getUri().toString(); } @Override public String requestHeader(HttpRequest<?> request, String name) { return request.getHeaders().get(name); } @Override public Integer statusCode(HttpResponse<?> response) { return response.getStatus().getCode(); } @Override public String route(HttpResponse<?> response) { Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class); return value.orElseGet(() -> super.route(response)); } @Override public String methodFromResponse(HttpResponse<?> httpResponse) { return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class).orElse(null); } @Override public boolean parseClientAddress(HttpRequest<?> httpRequest, Endpoint.Builder builder) { InetSocketAddress remoteAddress = httpRequest.getRemoteAddress(); return builder.parseIp(remoteAddress.getAddress()); } }); }
java
@Singleton HttpServerHandler<HttpRequest<?>, HttpResponse<?>> httpServerHandler(HttpTracing httpTracing) { return HttpServerHandler.create(httpTracing, new HttpServerAdapter<HttpRequest<?>, HttpResponse<?>>() { @Override public String method(HttpRequest<?> request) { return request.getMethod().name(); } @Override public String url(HttpRequest<?> request) { return request.getUri().toString(); } @Override public String requestHeader(HttpRequest<?> request, String name) { return request.getHeaders().get(name); } @Override public Integer statusCode(HttpResponse<?> response) { return response.getStatus().getCode(); } @Override public String route(HttpResponse<?> response) { Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class); return value.orElseGet(() -> super.route(response)); } @Override public String methodFromResponse(HttpResponse<?> httpResponse) { return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class).orElse(null); } @Override public boolean parseClientAddress(HttpRequest<?> httpRequest, Endpoint.Builder builder) { InetSocketAddress remoteAddress = httpRequest.getRemoteAddress(); return builder.parseIp(remoteAddress.getAddress()); } }); }
[ "@", "Singleton", "HttpServerHandler", "<", "HttpRequest", "<", "?", ">", ",", "HttpResponse", "<", "?", ">", ">", "httpServerHandler", "(", "HttpTracing", "httpTracing", ")", "{", "return", "HttpServerHandler", ".", "create", "(", "httpTracing", ",", "new", "...
The {@link HttpServerHandler} bean. @param httpTracing The {@link HttpTracing} bean @return The {@link HttpServerHandler} bean
[ "The", "{", "@link", "HttpServerHandler", "}", "bean", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/tracing/src/main/java/io/micronaut/tracing/brave/instrument/http/HttpTracingFactory.java#L110-L150
diffplug/durian
src/com/diffplug/common/base/StringPrinter.java
StringPrinter.toOutputStream
public OutputStream toOutputStream(Charset charset) { CharsetDecoder decoder = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .replaceWith("?"); ByteBuffer decoderIn = ByteBuffer.allocate(DECODER_BUFFER); CharBuffer decoderOut = CharBuffer.allocate(DECODER_BUFFER); return new OutputStream() { @Override public void write(final int b) throws IOException { write(new byte[]{(byte) b}); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { final int c = Math.min(len, decoderIn.remaining()); decoderIn.put(b, off, c); processInput(false); len -= c; off += c; } flushOutput(); } private void processInput(final boolean endOfInput) throws IOException { // Prepare decoderIn for reading decoderIn.flip(); CoderResult coderResult; while (true) { coderResult = decoder.decode(decoderIn, decoderOut, endOfInput); if (coderResult.isOverflow()) { flushOutput(); } else if (coderResult.isUnderflow()) { break; } else { // The decoder is configured to replace malformed input and unmappable characters, // so we should not get here. throw new IOException("Unexpected coder result"); } } // Discard the bytes that have been read decoderIn.compact(); } private void flushOutput() throws IOException { if (decoderOut.position() > 0) { consumer.accept(new String(decoderOut.array(), 0, decoderOut.position())); decoderOut.rewind(); } } }; }
java
public OutputStream toOutputStream(Charset charset) { CharsetDecoder decoder = charset.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .replaceWith("?"); ByteBuffer decoderIn = ByteBuffer.allocate(DECODER_BUFFER); CharBuffer decoderOut = CharBuffer.allocate(DECODER_BUFFER); return new OutputStream() { @Override public void write(final int b) throws IOException { write(new byte[]{(byte) b}); } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { final int c = Math.min(len, decoderIn.remaining()); decoderIn.put(b, off, c); processInput(false); len -= c; off += c; } flushOutput(); } private void processInput(final boolean endOfInput) throws IOException { // Prepare decoderIn for reading decoderIn.flip(); CoderResult coderResult; while (true) { coderResult = decoder.decode(decoderIn, decoderOut, endOfInput); if (coderResult.isOverflow()) { flushOutput(); } else if (coderResult.isUnderflow()) { break; } else { // The decoder is configured to replace malformed input and unmappable characters, // so we should not get here. throw new IOException("Unexpected coder result"); } } // Discard the bytes that have been read decoderIn.compact(); } private void flushOutput() throws IOException { if (decoderOut.position() > 0) { consumer.accept(new String(decoderOut.array(), 0, decoderOut.position())); decoderOut.rewind(); } } }; }
[ "public", "OutputStream", "toOutputStream", "(", "Charset", "charset", ")", "{", "CharsetDecoder", "decoder", "=", "charset", ".", "newDecoder", "(", ")", ".", "onMalformedInput", "(", "CodingErrorAction", ".", "REPLACE", ")", ".", "onUnmappableCharacter", "(", "C...
Creates an OutputStream which will print its content to the given StringPrinter, encoding bytes according to the given Charset. Doesn't matter if you close the stream or not, because StringPrinter doesn't have a close(). <p> Strings are sent to the consumer as soon as their constituent bytes are written to this OutputStream. <p> The implementation is lifted from Apache commons-io. Many thanks to them!
[ "Creates", "an", "OutputStream", "which", "will", "print", "its", "content", "to", "the", "given", "StringPrinter", "encoding", "bytes", "according", "to", "the", "given", "Charset", ".", "Doesn", "t", "matter", "if", "you", "close", "the", "stream", "or", "...
train
https://github.com/diffplug/durian/blob/10631a3480e5491eb6eb6ee06e752d8596914232/src/com/diffplug/common/base/StringPrinter.java#L85-L143
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java
MultiLayerNetwork.activateSelectedLayers
public INDArray activateSelectedLayers(int from, int to, INDArray input) { if (input == null) throw new IllegalStateException("Unable to perform activation; no input found"); if (from < 0 || from >= layers.length || from >= to) throw new IllegalStateException("Unable to perform activation; FROM is out of layer space"); if (to < 1 || to >= layers.length) throw new IllegalStateException("Unable to perform activation; TO is out of layer space"); try { LayerWorkspaceMgr mgr = LayerWorkspaceMgr.noWorkspaces(helperWorkspaces); //TODO INDArray res = input; for (int l = from; l <= to; l++) { res = this.activationFromPrevLayer(l, res, false, mgr); } return res; } catch (OutOfMemoryError e){ CrashReportingUtil.writeMemoryCrashDump(this, e); throw e; } }
java
public INDArray activateSelectedLayers(int from, int to, INDArray input) { if (input == null) throw new IllegalStateException("Unable to perform activation; no input found"); if (from < 0 || from >= layers.length || from >= to) throw new IllegalStateException("Unable to perform activation; FROM is out of layer space"); if (to < 1 || to >= layers.length) throw new IllegalStateException("Unable to perform activation; TO is out of layer space"); try { LayerWorkspaceMgr mgr = LayerWorkspaceMgr.noWorkspaces(helperWorkspaces); //TODO INDArray res = input; for (int l = from; l <= to; l++) { res = this.activationFromPrevLayer(l, res, false, mgr); } return res; } catch (OutOfMemoryError e){ CrashReportingUtil.writeMemoryCrashDump(this, e); throw e; } }
[ "public", "INDArray", "activateSelectedLayers", "(", "int", "from", ",", "int", "to", ",", "INDArray", "input", ")", "{", "if", "(", "input", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "\"Unable to perform activation; no input found\"", ")", ...
Calculate activation for few layers at once. Suitable for autoencoder partial activation. In example: in 10-layer deep autoencoder, layers 0 - 4 inclusive are used for encoding part, and layers 5-9 inclusive are used for decoding part. @param from first layer to be activated, inclusive @param to last layer to be activated, inclusive @return the activation from the last layer
[ "Calculate", "activation", "for", "few", "layers", "at", "once", ".", "Suitable", "for", "autoencoder", "partial", "activation", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java#L819-L839
geomajas/geomajas-project-client-gwt2
common-gwt/command/src/main/java/org/geomajas/gwt/client/util/StyleUtil.java
StyleUtil.createGraphic
public static GraphicInfo createGraphic(MarkInfo mark, int size) { GraphicInfo graphicInfo = new GraphicInfo(); ChoiceInfo choice = new ChoiceInfo(); choice.setMark(mark); graphicInfo.getChoiceList().add(choice); SizeInfo sizeInfo = new SizeInfo(); sizeInfo.setValue(Integer.toString(size)); graphicInfo.setSize(sizeInfo); return graphicInfo; }
java
public static GraphicInfo createGraphic(MarkInfo mark, int size) { GraphicInfo graphicInfo = new GraphicInfo(); ChoiceInfo choice = new ChoiceInfo(); choice.setMark(mark); graphicInfo.getChoiceList().add(choice); SizeInfo sizeInfo = new SizeInfo(); sizeInfo.setValue(Integer.toString(size)); graphicInfo.setSize(sizeInfo); return graphicInfo; }
[ "public", "static", "GraphicInfo", "createGraphic", "(", "MarkInfo", "mark", ",", "int", "size", ")", "{", "GraphicInfo", "graphicInfo", "=", "new", "GraphicInfo", "(", ")", ";", "ChoiceInfo", "choice", "=", "new", "ChoiceInfo", "(", ")", ";", "choice", ".",...
Creates a graphic with the specified mark and size. @param mark the mark @param size the size @return the graphic
[ "Creates", "a", "graphic", "with", "the", "specified", "mark", "and", "size", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/common-gwt/command/src/main/java/org/geomajas/gwt/client/util/StyleUtil.java#L299-L308
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/Bindings.java
Bindings.bindEnabled
public static void bindEnabled (Value<Boolean> value, final FocusWidget... targets) { value.addListenerAndTrigger(new Value.Listener<Boolean>() { public void valueChanged (Boolean enabled) { for (FocusWidget target : targets) { target.setEnabled(enabled); } } }); }
java
public static void bindEnabled (Value<Boolean> value, final FocusWidget... targets) { value.addListenerAndTrigger(new Value.Listener<Boolean>() { public void valueChanged (Boolean enabled) { for (FocusWidget target : targets) { target.setEnabled(enabled); } } }); }
[ "public", "static", "void", "bindEnabled", "(", "Value", "<", "Boolean", ">", "value", ",", "final", "FocusWidget", "...", "targets", ")", "{", "value", ".", "addListenerAndTrigger", "(", "new", "Value", ".", "Listener", "<", "Boolean", ">", "(", ")", "{",...
Binds the enabledness state of the target widget to the supplied boolean value.
[ "Binds", "the", "enabledness", "state", "of", "the", "target", "widget", "to", "the", "supplied", "boolean", "value", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/Bindings.java#L59-L68
aws/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/util/StepFactory.java
StepFactory.newRunHiveScriptStepVersioned
public HadoopJarStepConfig newRunHiveScriptStepVersioned(String script, String hiveVersion, String... scriptArgs) { List<String> hiveArgs = new ArrayList<String>(); hiveArgs.add("--hive-versions"); hiveArgs.add(hiveVersion); hiveArgs.add("--run-hive-script"); hiveArgs.add("--args"); hiveArgs.add("-f"); hiveArgs.add(script); hiveArgs.addAll(Arrays.asList(scriptArgs)); return newHivePigStep("hive", hiveArgs.toArray(new String[0])); }
java
public HadoopJarStepConfig newRunHiveScriptStepVersioned(String script, String hiveVersion, String... scriptArgs) { List<String> hiveArgs = new ArrayList<String>(); hiveArgs.add("--hive-versions"); hiveArgs.add(hiveVersion); hiveArgs.add("--run-hive-script"); hiveArgs.add("--args"); hiveArgs.add("-f"); hiveArgs.add(script); hiveArgs.addAll(Arrays.asList(scriptArgs)); return newHivePigStep("hive", hiveArgs.toArray(new String[0])); }
[ "public", "HadoopJarStepConfig", "newRunHiveScriptStepVersioned", "(", "String", "script", ",", "String", "hiveVersion", ",", "String", "...", "scriptArgs", ")", "{", "List", "<", "String", ">", "hiveArgs", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ...
Step that runs a Hive script on your job flow using the specified Hive version. @param script The script to run. @param hiveVersion The Hive version to use. @param scriptArgs Arguments that get passed to the script. @return HadoopJarStepConfig that can be passed to your job flow.
[ "Step", "that", "runs", "a", "Hive", "script", "on", "your", "job", "flow", "using", "the", "specified", "Hive", "version", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/util/StepFactory.java#L205-L216
spotify/styx
styx-service-common/src/main/java/com/spotify/styx/util/ShardedCounter.java
ShardedCounter.updateCounter
public void updateCounter(StorageTransaction transaction, String counterId, long delta) throws IOException { CounterSnapshot snapshot = getCounterSnapshot(counterId); // If delta is negative, try to update shards with excess usage first if (delta < 0) { Optional<Integer> shardIndex = snapshot.pickShardWithExcessUsage(delta); if (shardIndex.isPresent()) { updateCounterShard(transaction, counterId, delta, shardIndex.get(), snapshot.shardCapacity(shardIndex.get())); return; } } int shardIndex = snapshot.pickShardWithSpareCapacity(delta); updateCounterShard(transaction, counterId, delta, shardIndex, snapshot.shardCapacity(shardIndex)); }
java
public void updateCounter(StorageTransaction transaction, String counterId, long delta) throws IOException { CounterSnapshot snapshot = getCounterSnapshot(counterId); // If delta is negative, try to update shards with excess usage first if (delta < 0) { Optional<Integer> shardIndex = snapshot.pickShardWithExcessUsage(delta); if (shardIndex.isPresent()) { updateCounterShard(transaction, counterId, delta, shardIndex.get(), snapshot.shardCapacity(shardIndex.get())); return; } } int shardIndex = snapshot.pickShardWithSpareCapacity(delta); updateCounterShard(transaction, counterId, delta, shardIndex, snapshot.shardCapacity(shardIndex)); }
[ "public", "void", "updateCounter", "(", "StorageTransaction", "transaction", ",", "String", "counterId", ",", "long", "delta", ")", "throws", "IOException", "{", "CounterSnapshot", "snapshot", "=", "getCounterSnapshot", "(", "counterId", ")", ";", "// If delta is nega...
Must be called within a TransactionCallable. Augments the transaction with certain operations that strongly consistently increment resp. decrement the counter referred to by counterId, and cause the transaction to fail to commit if the counter's associated limit is exceeded. Also spurious failures are possible. <p>Delta should be +/-1 for graceful behavior, due to how sharding is currently implemented. Updates with a larger delta are prone to spuriously fail even when the counter is not near to exceeding its limit. Failures are certain when delta >= limit / NUM_SHARDS + 1.
[ "Must", "be", "called", "within", "a", "TransactionCallable", ".", "Augments", "the", "transaction", "with", "certain", "operations", "that", "strongly", "consistently", "increment", "resp", ".", "decrement", "the", "counter", "referred", "to", "by", "counterId", ...
train
https://github.com/spotify/styx/blob/0d63999beeb93a17447e3bbccaa62175b74cf6e4/styx-service-common/src/main/java/com/spotify/styx/util/ShardedCounter.java#L250-L265
amazon-archives/aws-sdk-java-resources
aws-resources-core/src/main/java/com/amazonaws/resources/internal/ReflectionUtils.java
ReflectionUtils.setValue
private static void setValue(Object target, String field, Object value) { // TODO: Should we do this for all numbers, not just '0'? if ("0".equals(field)) { if (!(target instanceof Collection)) { throw new IllegalArgumentException( "Cannot evaluate '0' on object " + target); } @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) target; collection.add(value); } else { Method setter = findMethod(target, "set" + field, value.getClass()); try { setter.invoke(target, value); } catch (IllegalAccessException exception) { throw new IllegalStateException( "Unable to access setter method", exception); } catch(InvocationTargetException exception) { if (exception.getCause() instanceof RuntimeException) { throw (RuntimeException) exception.getCause(); } throw new IllegalStateException( "Checked exception thrown from setter method", exception); } } }
java
private static void setValue(Object target, String field, Object value) { // TODO: Should we do this for all numbers, not just '0'? if ("0".equals(field)) { if (!(target instanceof Collection)) { throw new IllegalArgumentException( "Cannot evaluate '0' on object " + target); } @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) target; collection.add(value); } else { Method setter = findMethod(target, "set" + field, value.getClass()); try { setter.invoke(target, value); } catch (IllegalAccessException exception) { throw new IllegalStateException( "Unable to access setter method", exception); } catch(InvocationTargetException exception) { if (exception.getCause() instanceof RuntimeException) { throw (RuntimeException) exception.getCause(); } throw new IllegalStateException( "Checked exception thrown from setter method", exception); } } }
[ "private", "static", "void", "setValue", "(", "Object", "target", ",", "String", "field", ",", "Object", "value", ")", "{", "// TODO: Should we do this for all numbers, not just '0'?", "if", "(", "\"0\"", ".", "equals", "(", "field", ")", ")", "{", "if", "(", ...
Uses reflection to set the value of the given property on the target object. @param target the object to reflect on @param field the name of the property to set @param value the new value of the property
[ "Uses", "reflection", "to", "set", "the", "value", "of", "the", "given", "property", "on", "the", "target", "object", "." ]
train
https://github.com/amazon-archives/aws-sdk-java-resources/blob/0f4fef2615d9687997b70a36eed1d62dd42df035/aws-resources-core/src/main/java/com/amazonaws/resources/internal/ReflectionUtils.java#L416-L450
ops4j/org.ops4j.pax.exam2
core/pax-exam-container-rbc-client/src/main/java/org/ops4j/pax/exam/rbc/client/intern/RemoteBundleContextClientImpl.java
RemoteBundleContextClientImpl.getRemoteBundleContext
private synchronized RemoteBundleContext getRemoteBundleContext() { if (remoteBundleContext == null) { // !! Absolutely necesary for RMI class loading to work // TODO maybe use ContextClassLoaderUtils.doWithClassLoader Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); LOG.info("Waiting for remote bundle context.. on " + registry + " name: " + name + " timout: " + rmiLookupTimeout); // TODO create registry here Throwable reason = null; long startedTrying = System.currentTimeMillis(); do { try { remoteBundleContext = (RemoteBundleContext) getRegistry(registry).lookup(name); } catch (RemoteException e) { reason = e; } catch (NotBoundException e) { reason = e; } } while (remoteBundleContext == null && (rmiLookupTimeout.isNoTimeout() || System.currentTimeMillis() < startedTrying + rmiLookupTimeout.getValue())); if (remoteBundleContext == null) { throw new RuntimeException("Cannot get the remote bundle context", reason); } LOG.debug("Remote bundle context found after " + (System.currentTimeMillis() - startedTrying) + " millis"); } return remoteBundleContext; }
java
private synchronized RemoteBundleContext getRemoteBundleContext() { if (remoteBundleContext == null) { // !! Absolutely necesary for RMI class loading to work // TODO maybe use ContextClassLoaderUtils.doWithClassLoader Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); LOG.info("Waiting for remote bundle context.. on " + registry + " name: " + name + " timout: " + rmiLookupTimeout); // TODO create registry here Throwable reason = null; long startedTrying = System.currentTimeMillis(); do { try { remoteBundleContext = (RemoteBundleContext) getRegistry(registry).lookup(name); } catch (RemoteException e) { reason = e; } catch (NotBoundException e) { reason = e; } } while (remoteBundleContext == null && (rmiLookupTimeout.isNoTimeout() || System.currentTimeMillis() < startedTrying + rmiLookupTimeout.getValue())); if (remoteBundleContext == null) { throw new RuntimeException("Cannot get the remote bundle context", reason); } LOG.debug("Remote bundle context found after " + (System.currentTimeMillis() - startedTrying) + " millis"); } return remoteBundleContext; }
[ "private", "synchronized", "RemoteBundleContext", "getRemoteBundleContext", "(", ")", "{", "if", "(", "remoteBundleContext", "==", "null", ")", "{", "// !! Absolutely necesary for RMI class loading to work", "// TODO maybe use ContextClassLoaderUtils.doWithClassLoader", "Thread", "...
Looks up the {@link RemoteBundleContext} via RMI. The lookup will timeout in the specified number of millis. @return remote bundle context
[ "Looks", "up", "the", "{", "@link", "RemoteBundleContext", "}", "via", "RMI", ".", "The", "lookup", "will", "timeout", "in", "the", "specified", "number", "of", "millis", "." ]
train
https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/core/pax-exam-container-rbc-client/src/main/java/org/ops4j/pax/exam/rbc/client/intern/RemoteBundleContextClientImpl.java#L226-L260
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/normalization/KerasBatchNormalization.java
KerasBatchNormalization.getBetaRegularizerFromConfig
private void getBetaRegularizerFromConfig(Map<String, Object> layerConfig, boolean enforceTrainingConfig) throws UnsupportedKerasConfigurationException, InvalidKerasConfigurationException { Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf); if (innerConfig.get(LAYER_FIELD_BETA_REGULARIZER) != null) { if (enforceTrainingConfig) throw new UnsupportedKerasConfigurationException( "Regularization for BatchNormalization beta parameter not supported"); else log.warn("Regularization for BatchNormalization beta parameter not supported...ignoring."); } }
java
private void getBetaRegularizerFromConfig(Map<String, Object> layerConfig, boolean enforceTrainingConfig) throws UnsupportedKerasConfigurationException, InvalidKerasConfigurationException { Map<String, Object> innerConfig = KerasLayerUtils.getInnerLayerConfigFromConfig(layerConfig, conf); if (innerConfig.get(LAYER_FIELD_BETA_REGULARIZER) != null) { if (enforceTrainingConfig) throw new UnsupportedKerasConfigurationException( "Regularization for BatchNormalization beta parameter not supported"); else log.warn("Regularization for BatchNormalization beta parameter not supported...ignoring."); } }
[ "private", "void", "getBetaRegularizerFromConfig", "(", "Map", "<", "String", ",", "Object", ">", "layerConfig", ",", "boolean", "enforceTrainingConfig", ")", "throws", "UnsupportedKerasConfigurationException", ",", "InvalidKerasConfigurationException", "{", "Map", "<", "...
Get BatchNormalization beta regularizer from Keras layer configuration. Currently unsupported. @param layerConfig dictionary containing Keras layer configuration @return Batchnormalization beta regularizer @throws InvalidKerasConfigurationException Invalid Keras config
[ "Get", "BatchNormalization", "beta", "regularizer", "from", "Keras", "layer", "configuration", ".", "Currently", "unsupported", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/normalization/KerasBatchNormalization.java#L305-L315
eclipse/hawkbit
hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java
AmqpMessageHandlerService.registerTarget
private void registerTarget(final Message message, final String virtualHost) { final String thingId = getStringHeaderKey(message, MessageHeaderKey.THING_ID, "ThingId is null"); final String replyTo = message.getMessageProperties().getReplyTo(); if (StringUtils.isEmpty(replyTo)) { logAndThrowMessageError(message, "No ReplyTo was set for the createThing message."); } final URI amqpUri = IpUtil.createAmqpUri(virtualHost, replyTo); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist(thingId, amqpUri); LOG.debug("Target {} reported online state.", thingId); lookIfUpdateAvailable(target); }
java
private void registerTarget(final Message message, final String virtualHost) { final String thingId = getStringHeaderKey(message, MessageHeaderKey.THING_ID, "ThingId is null"); final String replyTo = message.getMessageProperties().getReplyTo(); if (StringUtils.isEmpty(replyTo)) { logAndThrowMessageError(message, "No ReplyTo was set for the createThing message."); } final URI amqpUri = IpUtil.createAmqpUri(virtualHost, replyTo); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotExist(thingId, amqpUri); LOG.debug("Target {} reported online state.", thingId); lookIfUpdateAvailable(target); }
[ "private", "void", "registerTarget", "(", "final", "Message", "message", ",", "final", "String", "virtualHost", ")", "{", "final", "String", "thingId", "=", "getStringHeaderKey", "(", "message", ",", "MessageHeaderKey", ".", "THING_ID", ",", "\"ThingId is null\"", ...
Method to create a new target or to find the target if it already exists. @param targetID the ID of the target/thing @param ip the ip of the target/thing
[ "Method", "to", "create", "a", "new", "target", "or", "to", "find", "the", "target", "if", "it", "already", "exists", "." ]
train
https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-dmf/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpMessageHandlerService.java#L182-L195
fcrepo3/fcrepo
fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/objecteditor/ContentHandlerFactory.java
ContentHandlerFactory.getEditor
public static ContentEditor getEditor(String type, InputStream data) throws IOException { ContentEditor editor = (ContentEditor) s_editors.get(type); if (editor == null && type.endsWith("+xml")) { editor = (ContentEditor) s_editors.get("text/xml"); } return (ContentEditor) editor.newInstance(type, data, false); }
java
public static ContentEditor getEditor(String type, InputStream data) throws IOException { ContentEditor editor = (ContentEditor) s_editors.get(type); if (editor == null && type.endsWith("+xml")) { editor = (ContentEditor) s_editors.get("text/xml"); } return (ContentEditor) editor.newInstance(type, data, false); }
[ "public", "static", "ContentEditor", "getEditor", "(", "String", "type", ",", "InputStream", "data", ")", "throws", "IOException", "{", "ContentEditor", "editor", "=", "(", "ContentEditor", ")", "s_editors", ".", "get", "(", "type", ")", ";", "if", "(", "edi...
Get an editor for the given type, initialized with the given data. This should only be called if the caller knows there is an editor for the type.
[ "Get", "an", "editor", "for", "the", "given", "type", "initialized", "with", "the", "given", "data", ".", "This", "should", "only", "be", "called", "if", "the", "caller", "knows", "there", "is", "an", "editor", "for", "the", "type", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-client/fcrepo-client-admin/src/main/java/org/fcrepo/client/objecteditor/ContentHandlerFactory.java#L92-L99
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java
PublicIPPrefixesInner.createOrUpdateAsync
public Observable<PublicIPPrefixInner> createOrUpdateAsync(String resourceGroupName, String publicIpPrefixName, PublicIPPrefixInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, parameters).map(new Func1<ServiceResponse<PublicIPPrefixInner>, PublicIPPrefixInner>() { @Override public PublicIPPrefixInner call(ServiceResponse<PublicIPPrefixInner> response) { return response.body(); } }); }
java
public Observable<PublicIPPrefixInner> createOrUpdateAsync(String resourceGroupName, String publicIpPrefixName, PublicIPPrefixInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, publicIpPrefixName, parameters).map(new Func1<ServiceResponse<PublicIPPrefixInner>, PublicIPPrefixInner>() { @Override public PublicIPPrefixInner call(ServiceResponse<PublicIPPrefixInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "PublicIPPrefixInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "publicIpPrefixName", ",", "PublicIPPrefixInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroup...
Creates or updates a static or dynamic public IP prefix. @param resourceGroupName The name of the resource group. @param publicIpPrefixName The name of the public IP prefix. @param parameters Parameters supplied to the create or update public IP prefix operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "static", "or", "dynamic", "public", "IP", "prefix", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java#L471-L478
google/closure-compiler
src/com/google/javascript/jscomp/JSError.java
JSError.make
public static JSError make(Node n, DiagnosticType type, String... arguments) { return new JSError(n.getSourceFileName(), n, type, arguments); }
java
public static JSError make(Node n, DiagnosticType type, String... arguments) { return new JSError(n.getSourceFileName(), n, type, arguments); }
[ "public", "static", "JSError", "make", "(", "Node", "n", ",", "DiagnosticType", "type", ",", "String", "...", "arguments", ")", "{", "return", "new", "JSError", "(", "n", ".", "getSourceFileName", "(", ")", ",", "n", ",", "type", ",", "arguments", ")", ...
Creates a JSError from a file and Node position. @param n Determines the line and char position and source file name @param type The DiagnosticType @param arguments Arguments to be incorporated into the message
[ "Creates", "a", "JSError", "from", "a", "file", "and", "Node", "position", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/JSError.java#L119-L121
mabe02/lanterna
src/main/java/com/googlecode/lanterna/gui2/Panel.java
Panel.addComponent
public Panel addComponent(int index, Component component) { if(component == null) { throw new IllegalArgumentException("Cannot add null component"); } synchronized(components) { if(components.contains(component)) { return this; } if(component.getParent() != null) { component.getParent().removeComponent(component); } if (index > components.size()) { index = components.size(); } else if (index < 0) { index = 0; } components.add(index, component); } component.onAdded(this); invalidate(); return this; }
java
public Panel addComponent(int index, Component component) { if(component == null) { throw new IllegalArgumentException("Cannot add null component"); } synchronized(components) { if(components.contains(component)) { return this; } if(component.getParent() != null) { component.getParent().removeComponent(component); } if (index > components.size()) { index = components.size(); } else if (index < 0) { index = 0; } components.add(index, component); } component.onAdded(this); invalidate(); return this; }
[ "public", "Panel", "addComponent", "(", "int", "index", ",", "Component", "component", ")", "{", "if", "(", "component", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot add null component\"", ")", ";", "}", "synchronized", "(",...
Adds a new child component to the panel. Where within the panel the child will be displayed is up to the layout manager assigned to this panel. If the component has already been added to another panel, it will first be removed from that panel before added to this one. @param component Child component to add to this panel @param index At what index to add the component among the existing components @return Itself
[ "Adds", "a", "new", "child", "component", "to", "the", "panel", ".", "Where", "within", "the", "panel", "the", "child", "will", "be", "displayed", "is", "up", "to", "the", "layout", "manager", "assigned", "to", "this", "panel", ".", "If", "the", "compone...
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/gui2/Panel.java#L80-L102
lessthanoptimal/BoofCV
integration/boofcv-swing/src/main/java/boofcv/gui/feature/VisualizeShapes.java
VisualizeShapes.drawPolygon
public static void drawPolygon( Polygon2D_F64 polygon, boolean loop, Graphics2D g2 ) { for( int i = 0; i < polygon.size()-1; i++ ) { Point2D_F64 p0 = polygon.get(i); Point2D_F64 p1 = polygon.get(i+1); g2.drawLine((int)(p0.x+0.5),(int)(p0.y+0.5),(int)(p1.x+0.5),(int)(p1.y+0.5)); } if( loop && polygon.size() > 0) { Point2D_F64 p0 = polygon.get(0); Point2D_F64 p1 = polygon.get(polygon.size()-1); g2.drawLine((int)(p0.x+0.5),(int)(p0.y+0.5),(int)(p1.x+0.5),(int)(p1.y+0.5)); } }
java
public static void drawPolygon( Polygon2D_F64 polygon, boolean loop, Graphics2D g2 ) { for( int i = 0; i < polygon.size()-1; i++ ) { Point2D_F64 p0 = polygon.get(i); Point2D_F64 p1 = polygon.get(i+1); g2.drawLine((int)(p0.x+0.5),(int)(p0.y+0.5),(int)(p1.x+0.5),(int)(p1.y+0.5)); } if( loop && polygon.size() > 0) { Point2D_F64 p0 = polygon.get(0); Point2D_F64 p1 = polygon.get(polygon.size()-1); g2.drawLine((int)(p0.x+0.5),(int)(p0.y+0.5),(int)(p1.x+0.5),(int)(p1.y+0.5)); } }
[ "public", "static", "void", "drawPolygon", "(", "Polygon2D_F64", "polygon", ",", "boolean", "loop", ",", "Graphics2D", "g2", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "polygon", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")",...
Draws a polygon @param polygon The polygon @param loop true if the end points are connected, forming a loop @param g2 Graphics object it's drawn to
[ "Draws", "a", "polygon" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-swing/src/main/java/boofcv/gui/feature/VisualizeShapes.java#L204-L215
javabits/yar
yar-api/src/main/java/org/javabits/yar/InterruptedException.java
InterruptedException.newInterruptedException
public static InterruptedException newInterruptedException(String message, java.lang.InterruptedException cause) { Thread.currentThread().interrupt(); return new InterruptedException(message, cause); }
java
public static InterruptedException newInterruptedException(String message, java.lang.InterruptedException cause) { Thread.currentThread().interrupt(); return new InterruptedException(message, cause); }
[ "public", "static", "InterruptedException", "newInterruptedException", "(", "String", "message", ",", "java", ".", "lang", ".", "InterruptedException", "cause", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "return", "new",...
Re-interrupt the current thread and constructs an <code>InterruptedException</code> with the specified detail message. @param message the detail message. @param cause original {@code InterruptedException}
[ "Re", "-", "interrupt", "the", "current", "thread", "and", "constructs", "an", "<code", ">", "InterruptedException<", "/", "code", ">", "with", "the", "specified", "detail", "message", "." ]
train
https://github.com/javabits/yar/blob/e146a86611ca4831e8334c9a98fd7086cee9c03e/yar-api/src/main/java/org/javabits/yar/InterruptedException.java#L52-L55
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqlrtrim
public static void sqlrtrim(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "trim(trailing from ", "rtrim", parsedArgs); }
java
public static void sqlrtrim(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "trim(trailing from ", "rtrim", parsedArgs); }
[ "public", "static", "void", "sqlrtrim", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "singleArgumentFunctionCall", "(", "buf", ",", "\"trim(trailing from \"", ",", "\"rtrim\"", ...
rtrim translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "rtrim", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L282-L284
lucee/Lucee
core/src/main/java/lucee/runtime/op/Duplicator.java
Duplicator.duplicateMap
public static Map duplicateMap(Map map, boolean doKeysLower, boolean deepCopy) throws PageException { if (doKeysLower) { Map newMap; try { newMap = (Map) ClassUtil.loadInstance(map.getClass()); } catch (ClassException e) { newMap = new HashMap(); } boolean inside = ThreadLocalDuplication.set(map, newMap); try { Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); if (deepCopy) newMap.put(StringUtil.toLowerCase(Caster.toString(key)), duplicate(map.get(key), deepCopy)); else newMap.put(StringUtil.toLowerCase(Caster.toString(key)), map.get(key)); } } finally { if (!inside) ThreadLocalDuplication.reset(); } // return newMap; } return duplicateMap(map, deepCopy); }
java
public static Map duplicateMap(Map map, boolean doKeysLower, boolean deepCopy) throws PageException { if (doKeysLower) { Map newMap; try { newMap = (Map) ClassUtil.loadInstance(map.getClass()); } catch (ClassException e) { newMap = new HashMap(); } boolean inside = ThreadLocalDuplication.set(map, newMap); try { Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); if (deepCopy) newMap.put(StringUtil.toLowerCase(Caster.toString(key)), duplicate(map.get(key), deepCopy)); else newMap.put(StringUtil.toLowerCase(Caster.toString(key)), map.get(key)); } } finally { if (!inside) ThreadLocalDuplication.reset(); } // return newMap; } return duplicateMap(map, deepCopy); }
[ "public", "static", "Map", "duplicateMap", "(", "Map", "map", ",", "boolean", "doKeysLower", ",", "boolean", "deepCopy", ")", "throws", "PageException", "{", "if", "(", "doKeysLower", ")", "{", "Map", "newMap", ";", "try", "{", "newMap", "=", "(", "Map", ...
duplicate a map @param map @param doKeysLower @return duplicated Map @throws PageException
[ "duplicate", "a", "map" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Duplicator.java#L182-L207
shinesolutions/swagger-aem
java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/CustomApi.java
CustomApi.postConfigAemPasswordResetAsync
public com.squareup.okhttp.Call postConfigAemPasswordResetAsync(String runmode, List<String> pwdresetAuthorizables, String pwdresetAuthorizablesTypeHint, final ApiCallback<Void> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postConfigAemPasswordResetValidateBeforeCall(runmode, pwdresetAuthorizables, pwdresetAuthorizablesTypeHint, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; }
java
public com.squareup.okhttp.Call postConfigAemPasswordResetAsync(String runmode, List<String> pwdresetAuthorizables, String pwdresetAuthorizablesTypeHint, final ApiCallback<Void> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postConfigAemPasswordResetValidateBeforeCall(runmode, pwdresetAuthorizables, pwdresetAuthorizablesTypeHint, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "postConfigAemPasswordResetAsync", "(", "String", "runmode", ",", "List", "<", "String", ">", "pwdresetAuthorizables", ",", "String", "pwdresetAuthorizablesTypeHint", ",", "final", "ApiCallback", "<", "Vo...
(asynchronously) @param runmode (required) @param pwdresetAuthorizables (optional) @param pwdresetAuthorizablesTypeHint (optional) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "(", "asynchronously", ")" ]
train
https://github.com/shinesolutions/swagger-aem/blob/ae7da4df93e817dc2bad843779b2069d9c4e7c6b/java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/CustomApi.java#L430-L454
windup/windup
bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/AbstractListCommandWithoutFurnace.java
AbstractListCommandWithoutFurnace.printValuesSorted
protected static void printValuesSorted(String message, Set<String> values) { System.out.println(); System.out.println(message + ":"); List<String> sorted = new ArrayList<>(values); Collections.sort(sorted); for (String value : sorted) { System.out.println("\t" + value); } }
java
protected static void printValuesSorted(String message, Set<String> values) { System.out.println(); System.out.println(message + ":"); List<String> sorted = new ArrayList<>(values); Collections.sort(sorted); for (String value : sorted) { System.out.println("\t" + value); } }
[ "protected", "static", "void", "printValuesSorted", "(", "String", "message", ",", "Set", "<", "String", ">", "values", ")", "{", "System", ".", "out", ".", "println", "(", ")", ";", "System", ".", "out", ".", "println", "(", "message", "+", "\":\"", "...
Print the given values after displaying the provided message.
[ "Print", "the", "given", "values", "after", "displaying", "the", "provided", "message", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/AbstractListCommandWithoutFurnace.java#L16-L26
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPSpecificationOptionPersistenceImpl.java
CPSpecificationOptionPersistenceImpl.findAll
@Override public List<CPSpecificationOption> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CPSpecificationOption> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CPSpecificationOption", ">", "findAll", "(", ")", "{", "return", "findAll", "(", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}" ]
Returns all the cp specification options. @return the cp specification options
[ "Returns", "all", "the", "cp", "specification", "options", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPSpecificationOptionPersistenceImpl.java#L3479-L3482
lastaflute/lasta-di
src/main/java/org/lastaflute/di/util/LdiSrl.java
LdiSrl.indexOfLast
public static IndexOfInfo indexOfLast(final String str, final String... delimiters) { return doIndexOfLast(false, str, delimiters); }
java
public static IndexOfInfo indexOfLast(final String str, final String... delimiters) { return doIndexOfLast(false, str, delimiters); }
[ "public", "static", "IndexOfInfo", "indexOfLast", "(", "final", "String", "str", ",", "final", "String", "...", "delimiters", ")", "{", "return", "doIndexOfLast", "(", "false", ",", "str", ",", "delimiters", ")", ";", "}" ]
Get the index of the last-found delimiter. <pre> indexOfLast("foo.bar/baz.qux", ".", "/") returns the index of ".qux" </pre> @param str The target string. (NotNull) @param delimiters The array of delimiters. (NotNull) @return The information of index. (NullAllowed: if delimiter not found)
[ "Get", "the", "index", "of", "the", "last", "-", "found", "delimiter", ".", "<pre", ">", "indexOfLast", "(", "foo", ".", "bar", "/", "baz", ".", "qux", ".", "/", ")", "returns", "the", "index", "of", ".", "qux", "<", "/", "pre", ">" ]
train
https://github.com/lastaflute/lasta-di/blob/c4e123610c53a04cc836c5e456660e32d613447b/src/main/java/org/lastaflute/di/util/LdiSrl.java#L411-L413
OpenLiberty/open-liberty
dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/tsx/db/Query.java
Query.main
public static void main(String args[]) { String dbDriver = "COM.ibm.db2.jdbc.app.DB2Driver"; String url = "jdbc:db2:sample"; String user = "Murali"; String pass = "ibm"; String querystring = "Select * from Murali.department"; try { ConnectionProperties cp = new ConnectionProperties(dbDriver, url, user, pass); Query query = new Query(cp, querystring); QueryResults qs = query.execute(); System.out.println("Number of rows = " + qs.size()); for (int i = 0; i < qs.size(); i++) { String dept = qs.getValue("DEPTNAME", i); System.out.println("Department:" + dept); } /*Enumeration enum= qs.getRows(); while (enum.hasMoreElements()) { QueryRow qr = (QueryRow)enum.nextElement(); String fn = qr.getValue("DEPT"); String ln = qr.getValue("DEPTNAME"); // String bd = qr.getValue("BIRTHDATE"); //String sal = qr.getValue("SALARY"); System.out.println(fn + " " + ln); }*/ // while } // try catch (Exception e) { //com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.main", "310"); System.out.println("Exception:: " + e.getMessage()); } //catch }
java
public static void main(String args[]) { String dbDriver = "COM.ibm.db2.jdbc.app.DB2Driver"; String url = "jdbc:db2:sample"; String user = "Murali"; String pass = "ibm"; String querystring = "Select * from Murali.department"; try { ConnectionProperties cp = new ConnectionProperties(dbDriver, url, user, pass); Query query = new Query(cp, querystring); QueryResults qs = query.execute(); System.out.println("Number of rows = " + qs.size()); for (int i = 0; i < qs.size(); i++) { String dept = qs.getValue("DEPTNAME", i); System.out.println("Department:" + dept); } /*Enumeration enum= qs.getRows(); while (enum.hasMoreElements()) { QueryRow qr = (QueryRow)enum.nextElement(); String fn = qr.getValue("DEPT"); String ln = qr.getValue("DEPTNAME"); // String bd = qr.getValue("BIRTHDATE"); //String sal = qr.getValue("SALARY"); System.out.println(fn + " " + ln); }*/ // while } // try catch (Exception e) { //com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.webcontainer.jsp.tsx.db.Query.main", "310"); System.out.println("Exception:: " + e.getMessage()); } //catch }
[ "public", "static", "void", "main", "(", "String", "args", "[", "]", ")", "{", "String", "dbDriver", "=", "\"COM.ibm.db2.jdbc.app.DB2Driver\"", ";", "String", "url", "=", "\"jdbc:db2:sample\"", ";", "String", "user", "=", "\"Murali\"", ";", "String", "pass", "...
This method was created in VisualAge. @param args java.lang.String[]
[ "This", "method", "was", "created", "in", "VisualAge", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/tsx/db/Query.java#L294-L326
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/AstyanaxBlockedDataReaderDAO.java
AstyanaxBlockedDataReaderDAO.decodeRows
private Iterator<Record> decodeRows(List<Map.Entry<ByteBuffer, Key>> keys, final Rows<ByteBuffer, DeltaKey> rows, final int largeRowThreshold, final ReadConsistency consistency) { // Avoiding pinning multiple decoded rows into memory at once. return Iterators.transform(keys.iterator(), new Function<Map.Entry<ByteBuffer, Key>, Record>() { @Override public Record apply(Map.Entry<ByteBuffer, Key> entry) { Row<ByteBuffer, DeltaKey> row = rows.getRow(entry.getKey()); if (row == null) { return emptyRecord(entry.getValue()); } // Convert the results into a Record object, lazily fetching the rest of the columns as necessary. return newRecord(entry.getValue(), row.getRawKey(), row.getColumns(), largeRowThreshold, consistency, null); } }); }
java
private Iterator<Record> decodeRows(List<Map.Entry<ByteBuffer, Key>> keys, final Rows<ByteBuffer, DeltaKey> rows, final int largeRowThreshold, final ReadConsistency consistency) { // Avoiding pinning multiple decoded rows into memory at once. return Iterators.transform(keys.iterator(), new Function<Map.Entry<ByteBuffer, Key>, Record>() { @Override public Record apply(Map.Entry<ByteBuffer, Key> entry) { Row<ByteBuffer, DeltaKey> row = rows.getRow(entry.getKey()); if (row == null) { return emptyRecord(entry.getValue()); } // Convert the results into a Record object, lazily fetching the rest of the columns as necessary. return newRecord(entry.getValue(), row.getRawKey(), row.getColumns(), largeRowThreshold, consistency, null); } }); }
[ "private", "Iterator", "<", "Record", ">", "decodeRows", "(", "List", "<", "Map", ".", "Entry", "<", "ByteBuffer", ",", "Key", ">", ">", "keys", ",", "final", "Rows", "<", "ByteBuffer", ",", "DeltaKey", ">", "rows", ",", "final", "int", "largeRowThreshol...
Decodes rows returned by querying for a specific set of rows.
[ "Decodes", "rows", "returned", "by", "querying", "for", "a", "specific", "set", "of", "rows", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/AstyanaxBlockedDataReaderDAO.java#L1053-L1067
NoraUi/NoraUi
src/main/java/com/github/noraui/application/steps/Step.java
Step.updateText
protected void updateText(PageElement pageElement, String textOrKey, CharSequence keysToSend, Object... args) throws TechnicalException, FailureException { String value = getTextOrKey(textOrKey); if (!"".equals(value)) { try { final WebElement element = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(pageElement, args))); element.clear(); if (DriverFactory.IE.equals(Context.getBrowser())) { final String javascript = "arguments[0].value='" + value + "';"; ((JavascriptExecutor) getDriver()).executeScript(javascript, element); } else { element.sendKeys(value); } if (keysToSend != null) { element.sendKeys(keysToSend); } } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_ERROR_ON_INPUT), pageElement, pageElement.getPage().getApplication()), true, pageElement.getPage().getCallBack()); } } else { logger.debug("Empty data provided. No need to update text. If you want clear data, you need use: \"I clear text in ...\""); } }
java
protected void updateText(PageElement pageElement, String textOrKey, CharSequence keysToSend, Object... args) throws TechnicalException, FailureException { String value = getTextOrKey(textOrKey); if (!"".equals(value)) { try { final WebElement element = Context.waitUntil(ExpectedConditions.elementToBeClickable(Utilities.getLocator(pageElement, args))); element.clear(); if (DriverFactory.IE.equals(Context.getBrowser())) { final String javascript = "arguments[0].value='" + value + "';"; ((JavascriptExecutor) getDriver()).executeScript(javascript, element); } else { element.sendKeys(value); } if (keysToSend != null) { element.sendKeys(keysToSend); } } catch (final Exception e) { new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_ERROR_ON_INPUT), pageElement, pageElement.getPage().getApplication()), true, pageElement.getPage().getCallBack()); } } else { logger.debug("Empty data provided. No need to update text. If you want clear data, you need use: \"I clear text in ...\""); } }
[ "protected", "void", "updateText", "(", "PageElement", "pageElement", ",", "String", "textOrKey", ",", "CharSequence", "keysToSend", ",", "Object", "...", "args", ")", "throws", "TechnicalException", ",", "FailureException", "{", "String", "value", "=", "getTextOrKe...
Update a html input text with a text. @param pageElement Is target element @param textOrKey Is the new data (text or text in context (after a save)) @param keysToSend character to send to the element after {@link org.openqa.selenium.WebElement#sendKeys(CharSequence...) sendKeys} with textOrKey @param args list of arguments to format the found selector with @throws TechnicalException is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi. Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_ERROR_ON_INPUT} message (with screenshot, no exception) @throws FailureException if the scenario encounters a functional error
[ "Update", "a", "html", "input", "text", "with", "a", "text", "." ]
train
https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L207-L229
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/locale/LocaleFormatter.java
LocaleFormatter.getFormattedPercent
@Nonnull public static String getFormattedPercent (final double dValue, @Nonnull final Locale aDisplayLocale) { ValueEnforcer.notNull (aDisplayLocale, "DisplayLocale"); return NumberFormat.getPercentInstance (aDisplayLocale).format (dValue); }
java
@Nonnull public static String getFormattedPercent (final double dValue, @Nonnull final Locale aDisplayLocale) { ValueEnforcer.notNull (aDisplayLocale, "DisplayLocale"); return NumberFormat.getPercentInstance (aDisplayLocale).format (dValue); }
[ "@", "Nonnull", "public", "static", "String", "getFormattedPercent", "(", "final", "double", "dValue", ",", "@", "Nonnull", "final", "Locale", "aDisplayLocale", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aDisplayLocale", ",", "\"DisplayLocale\"", ")", ";", ...
Format the given value as percentage. The "%" sign is automatically appended according to the requested locale. The number of fractional digits depend on the locale. @param dValue The value to be used. E.g. "0.125" will result in something like "12.5%" @param aDisplayLocale The locale to use. @return The non-<code>null</code> formatted string.
[ "Format", "the", "given", "value", "as", "percentage", ".", "The", "%", "sign", "is", "automatically", "appended", "according", "to", "the", "requested", "locale", ".", "The", "number", "of", "fractional", "digits", "depend", "on", "the", "locale", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/locale/LocaleFormatter.java#L203-L209
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/AbsModule.java
AbsModule.getResourceIdOrThrow
String getResourceIdOrThrow(CMAResource resource, String param) { final String resourceId = resource.getId(); if (resourceId == null) { throw new IllegalArgumentException(String.format( "%s.setId() was not called.", param)); } return resourceId; }
java
String getResourceIdOrThrow(CMAResource resource, String param) { final String resourceId = resource.getId(); if (resourceId == null) { throw new IllegalArgumentException(String.format( "%s.setId() was not called.", param)); } return resourceId; }
[ "String", "getResourceIdOrThrow", "(", "CMAResource", "resource", ",", "String", "param", ")", "{", "final", "String", "resourceId", "=", "resource", ".", "getId", "(", ")", ";", "if", "(", "resourceId", "==", "null", ")", "{", "throw", "new", "IllegalArgume...
Extracts the resource ID from the given {@code resource} of name {@code param}. Throws {@link IllegalArgumentException} if the value is not present.
[ "Extracts", "the", "resource", "ID", "from", "the", "given", "{" ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/AbsModule.java#L71-L78
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java
TaskManagerService.storeTaskRecord
private TaskRecord storeTaskRecord(Tenant tenant, Task task) { DBTransaction dbTran = DBService.instance(tenant).startTransaction(); TaskRecord taskRecord = new TaskRecord(task.getTaskID()); Map<String, String> propMap = taskRecord.getProperties(); assert propMap.size() > 0 : "Need at least one property to store a row!"; for (String propName : propMap.keySet()) { dbTran.addColumn(TaskManagerService.TASKS_STORE_NAME, task.getTaskID(), propName, propMap.get(propName)); } DBService.instance(tenant).commit(dbTran); return taskRecord; }
java
private TaskRecord storeTaskRecord(Tenant tenant, Task task) { DBTransaction dbTran = DBService.instance(tenant).startTransaction(); TaskRecord taskRecord = new TaskRecord(task.getTaskID()); Map<String, String> propMap = taskRecord.getProperties(); assert propMap.size() > 0 : "Need at least one property to store a row!"; for (String propName : propMap.keySet()) { dbTran.addColumn(TaskManagerService.TASKS_STORE_NAME, task.getTaskID(), propName, propMap.get(propName)); } DBService.instance(tenant).commit(dbTran); return taskRecord; }
[ "private", "TaskRecord", "storeTaskRecord", "(", "Tenant", "tenant", ",", "Task", "task", ")", "{", "DBTransaction", "dbTran", "=", "DBService", ".", "instance", "(", "tenant", ")", ".", "startTransaction", "(", ")", ";", "TaskRecord", "taskRecord", "=", "new"...
Create a TaskRecord for the given task and write it to the Tasks table.
[ "Create", "a", "TaskRecord", "for", "the", "given", "task", "and", "write", "it", "to", "the", "Tasks", "table", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/taskmanager/TaskManagerService.java#L484-L494
googleapis/google-cloud-java
google-cloud-clients/google-cloud-containeranalysis/src/main/java/com/google/cloud/devtools/containeranalysis/v1beta1/GrafeasV1Beta1Client.java
GrafeasV1Beta1Client.createNote
public final Note createNote(ProjectName parent, String noteId, Note note) { CreateNoteRequest request = CreateNoteRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setNoteId(noteId) .setNote(note) .build(); return createNote(request); }
java
public final Note createNote(ProjectName parent, String noteId, Note note) { CreateNoteRequest request = CreateNoteRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setNoteId(noteId) .setNote(note) .build(); return createNote(request); }
[ "public", "final", "Note", "createNote", "(", "ProjectName", "parent", ",", "String", "noteId", ",", "Note", "note", ")", "{", "CreateNoteRequest", "request", "=", "CreateNoteRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", "==", "null",...
Creates a new note. <p>Sample code: <pre><code> try (GrafeasV1Beta1Client grafeasV1Beta1Client = GrafeasV1Beta1Client.create()) { ProjectName parent = ProjectName.of("[PROJECT]"); String noteId = ""; Note note = Note.newBuilder().build(); Note response = grafeasV1Beta1Client.createNote(parent, noteId, note); } </code></pre> @param parent The name of the project in the form of `projects/[PROJECT_ID]`, under which the note is to be created. @param noteId The ID to use for this note. @param note The note to create. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "new", "note", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-containeranalysis/src/main/java/com/google/cloud/devtools/containeranalysis/v1beta1/GrafeasV1Beta1Client.java#L1287-L1296
rabbitmq/hop
src/main/java/com/rabbitmq/http/client/Client.java
Client.deleteShovel
public void deleteShovel(String vhost, String shovelname) { this.deleteIgnoring404(uriWithPath("./parameters/shovel/" + encodePathSegment(vhost) + "/" + encodePathSegment(shovelname))); }
java
public void deleteShovel(String vhost, String shovelname) { this.deleteIgnoring404(uriWithPath("./parameters/shovel/" + encodePathSegment(vhost) + "/" + encodePathSegment(shovelname))); }
[ "public", "void", "deleteShovel", "(", "String", "vhost", ",", "String", "shovelname", ")", "{", "this", ".", "deleteIgnoring404", "(", "uriWithPath", "(", "\"./parameters/shovel/\"", "+", "encodePathSegment", "(", "vhost", ")", "+", "\"/\"", "+", "encodePathSegme...
Deletes the specified shovel from specified virtual host. @param vhost virtual host from where to delete the shovel @param shovelname Shovel to be deleted.
[ "Deletes", "the", "specified", "shovel", "from", "specified", "virtual", "host", "." ]
train
https://github.com/rabbitmq/hop/blob/94e70f1f7e39f523a11ab3162b4efc976311ee03/src/main/java/com/rabbitmq/http/client/Client.java#L827-L829
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/osgi/AbstractActivator.java
AbstractActivator.extractBundleContent
protected void extractBundleContent(String bundleRootPath, String toDirRoot) throws IOException { File toDir = new File(toDirRoot); if (!toDir.isDirectory()) { throw new RuntimeException("[" + toDir.getAbsolutePath() + "] is not a valid directory or does not exist!"); } toDir = new File(toDir, bundle.getSymbolicName()); toDir = new File(toDir, bundle.getVersion().toString()); FileUtils.forceMkdir(toDir); bundleExtractDir = toDir; Enumeration<String> entryPaths = bundle.getEntryPaths(bundleRootPath); if (entryPaths != null) { while (entryPaths.hasMoreElements()) { extractContent(bundleRootPath, entryPaths.nextElement(), bundleExtractDir); } } }
java
protected void extractBundleContent(String bundleRootPath, String toDirRoot) throws IOException { File toDir = new File(toDirRoot); if (!toDir.isDirectory()) { throw new RuntimeException("[" + toDir.getAbsolutePath() + "] is not a valid directory or does not exist!"); } toDir = new File(toDir, bundle.getSymbolicName()); toDir = new File(toDir, bundle.getVersion().toString()); FileUtils.forceMkdir(toDir); bundleExtractDir = toDir; Enumeration<String> entryPaths = bundle.getEntryPaths(bundleRootPath); if (entryPaths != null) { while (entryPaths.hasMoreElements()) { extractContent(bundleRootPath, entryPaths.nextElement(), bundleExtractDir); } } }
[ "protected", "void", "extractBundleContent", "(", "String", "bundleRootPath", ",", "String", "toDirRoot", ")", "throws", "IOException", "{", "File", "toDir", "=", "new", "File", "(", "toDirRoot", ")", ";", "if", "(", "!", "toDir", ".", "isDirectory", "(", ")...
Extracts content from the bundle to a directory. <p> Sub-class calls this method to extract all or part of bundle's content to a directory on disk. </p> <p> Note: bundle's content will be extracted to a sub-directory <code>toDirRoot/bundle_symbolic_name/bundle_version/</code> </p> @param bundleRootPath bundle's content under this path will be extracted @param toDirRoot bundle's content will be extracted to this directory @throws IOException
[ "Extracts", "content", "from", "the", "bundle", "to", "a", "directory", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/osgi/AbstractActivator.java#L105-L122
Impetus/Kundera
src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESClient.java
ESClient.executeQuery
public List executeQuery(QueryBuilder filter, AggregationBuilder aggregation, final EntityMetadata entityMetadata, KunderaQuery query, int firstResult, int maxResults) { String[] fieldsToSelect = query.getResult(); Class clazz = entityMetadata.getEntityClazz(); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(entityMetadata.getPersistenceUnit()); FilteredQueryBuilder queryBuilder = QueryBuilders.filteredQuery(null, filter); SearchRequestBuilder builder = txClient.prepareSearch(entityMetadata.getSchema().toLowerCase()) .setTypes(entityMetadata.getTableName()); addFieldsToBuilder(fieldsToSelect, clazz, metaModel, builder); if (aggregation == null) { builder.setQuery(queryBuilder); builder.setFrom(firstResult); builder.setSize(maxResults); addSortOrder(builder, query, entityMetadata); } else { logger.debug("Aggregated query identified"); builder.addAggregation(aggregation); if (fieldsToSelect.length == 1 || (query.isSelectStatement() && query.getSelectStatement().hasGroupByClause())) { builder.setSize(0); } } SearchResponse response = null; logger.debug("Query generated: " + builder); try { response = builder.execute().actionGet(); logger.debug("Query execution response: " + response); } catch (ElasticsearchException e) { logger.error("Exception occured while executing query on Elasticsearch.", e); throw new KunderaException("Exception occured while executing query on Elasticsearch.", e); } return esResponseReader.parseResponse(response, aggregation, fieldsToSelect, metaModel, clazz, entityMetadata, query); }
java
public List executeQuery(QueryBuilder filter, AggregationBuilder aggregation, final EntityMetadata entityMetadata, KunderaQuery query, int firstResult, int maxResults) { String[] fieldsToSelect = query.getResult(); Class clazz = entityMetadata.getEntityClazz(); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(entityMetadata.getPersistenceUnit()); FilteredQueryBuilder queryBuilder = QueryBuilders.filteredQuery(null, filter); SearchRequestBuilder builder = txClient.prepareSearch(entityMetadata.getSchema().toLowerCase()) .setTypes(entityMetadata.getTableName()); addFieldsToBuilder(fieldsToSelect, clazz, metaModel, builder); if (aggregation == null) { builder.setQuery(queryBuilder); builder.setFrom(firstResult); builder.setSize(maxResults); addSortOrder(builder, query, entityMetadata); } else { logger.debug("Aggregated query identified"); builder.addAggregation(aggregation); if (fieldsToSelect.length == 1 || (query.isSelectStatement() && query.getSelectStatement().hasGroupByClause())) { builder.setSize(0); } } SearchResponse response = null; logger.debug("Query generated: " + builder); try { response = builder.execute().actionGet(); logger.debug("Query execution response: " + response); } catch (ElasticsearchException e) { logger.error("Exception occured while executing query on Elasticsearch.", e); throw new KunderaException("Exception occured while executing query on Elasticsearch.", e); } return esResponseReader.parseResponse(response, aggregation, fieldsToSelect, metaModel, clazz, entityMetadata, query); }
[ "public", "List", "executeQuery", "(", "QueryBuilder", "filter", ",", "AggregationBuilder", "aggregation", ",", "final", "EntityMetadata", "entityMetadata", ",", "KunderaQuery", "query", ",", "int", "firstResult", ",", "int", "maxResults", ")", "{", "String", "[", ...
Execute query. @param filter the filter @param aggregation the aggregation @param entityMetadata the entity metadata @param query the query @param firstResult the first result @param maxResults the max results @return the list
[ "Execute", "query", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESClient.java#L313-L363
ihaolin/session
session-api/src/main/java/me/hao0/session/util/WebUtil.java
WebUtil.findCookieValue
public static String findCookieValue(HttpServletRequest request, String name) { Cookie cookie = findCookie(request, name); return cookie != null ? cookie.getValue() : null; }
java
public static String findCookieValue(HttpServletRequest request, String name) { Cookie cookie = findCookie(request, name); return cookie != null ? cookie.getValue() : null; }
[ "public", "static", "String", "findCookieValue", "(", "HttpServletRequest", "request", ",", "String", "name", ")", "{", "Cookie", "cookie", "=", "findCookie", "(", "request", ",", "name", ")", ";", "return", "cookie", "!=", "null", "?", "cookie", ".", "getVa...
find cookie value @param request current request @param name cookie name @return cookie value
[ "find", "cookie", "value" ]
train
https://github.com/ihaolin/session/blob/322c3a9f47b305a39345135fa8163dd7e065b4f8/session-api/src/main/java/me/hao0/session/util/WebUtil.java#L81-L84
Clivern/Racter
src/main/java/com/clivern/racter/senders/templates/GenericTemplate.java
GenericTemplate.setElementButton
public void setElementButton(Integer index, String title, String type, String url, Boolean messenger_extensions, String webview_height_ratio, String fallback_url) { if( this.elements.get(index).containsKey("buttons") ){ HashMap<String, String> button = new HashMap<String, String>(); button.put("title", title); button.put("type", type); button.put("url", url); button.put("messenger_extensions", String.valueOf(messenger_extensions)); button.put("webview_height_ratio", webview_height_ratio); button.put("fallback_url", fallback_url); @SuppressWarnings("unchecked") ArrayList<HashMap<String, String>> element_buttons = (ArrayList<HashMap<String, String>>) this.elements.get(index).get("buttons"); element_buttons.add(button); this.elements.get(index).put("buttons", element_buttons); }else{ ArrayList<HashMap<String, String>> element_buttons = new ArrayList<HashMap<String, String>>(); HashMap<String, String> button = new HashMap<String, String>(); button.put("title", title); button.put("type", type); button.put("url", url); button.put("messenger_extensions", String.valueOf(messenger_extensions)); button.put("webview_height_ratio", webview_height_ratio); button.put("fallback_url", fallback_url); element_buttons.add(button); this.elements.get(index).put("buttons", element_buttons); } }
java
public void setElementButton(Integer index, String title, String type, String url, Boolean messenger_extensions, String webview_height_ratio, String fallback_url) { if( this.elements.get(index).containsKey("buttons") ){ HashMap<String, String> button = new HashMap<String, String>(); button.put("title", title); button.put("type", type); button.put("url", url); button.put("messenger_extensions", String.valueOf(messenger_extensions)); button.put("webview_height_ratio", webview_height_ratio); button.put("fallback_url", fallback_url); @SuppressWarnings("unchecked") ArrayList<HashMap<String, String>> element_buttons = (ArrayList<HashMap<String, String>>) this.elements.get(index).get("buttons"); element_buttons.add(button); this.elements.get(index).put("buttons", element_buttons); }else{ ArrayList<HashMap<String, String>> element_buttons = new ArrayList<HashMap<String, String>>(); HashMap<String, String> button = new HashMap<String, String>(); button.put("title", title); button.put("type", type); button.put("url", url); button.put("messenger_extensions", String.valueOf(messenger_extensions)); button.put("webview_height_ratio", webview_height_ratio); button.put("fallback_url", fallback_url); element_buttons.add(button); this.elements.get(index).put("buttons", element_buttons); } }
[ "public", "void", "setElementButton", "(", "Integer", "index", ",", "String", "title", ",", "String", "type", ",", "String", "url", ",", "Boolean", "messenger_extensions", ",", "String", "webview_height_ratio", ",", "String", "fallback_url", ")", "{", "if", "(",...
Set Element Button @param index the element index @param title the element title @param type the element type @param url the element url @param messenger_extensions the messenger extensions @param webview_height_ratio the webview height ratio @param fallback_url the fallback url
[ "Set", "Element", "Button" ]
train
https://github.com/Clivern/Racter/blob/bbde02f0c2a8a80653ad6b1607376d8408acd71c/src/main/java/com/clivern/racter/senders/templates/GenericTemplate.java#L104-L130
VoltDB/voltdb
src/frontend/org/voltdb/planner/FilterMatcher.java
FilterMatcher.vectorsMatch
private static boolean vectorsMatch(VectorValueExpression e1, VectorValueExpression e2) { final Set<ConstantValueExpression> c1 = new HashSet<>(), c2 = new HashSet<>(); final Set<Integer> tveIndices1 = new HashSet<>(), tveIndices2 = new HashSet<>(); e1.getArgs().forEach(e -> { if (e instanceof ConstantValueExpression || e instanceof ParameterValueExpression) { c1.add(asCVE(e)); } else { assert (e instanceof TupleValueExpression); tveIndices1.add(((TupleValueExpression) e).getColumnIndex()); } }); e2.getArgs().forEach(e -> { if (e instanceof ConstantValueExpression || e instanceof ParameterValueExpression) { c2.add(asCVE(e)); } else { assert (e instanceof TupleValueExpression); tveIndices2.add(((TupleValueExpression) e).getColumnIndex()); } }); return c1.equals(c2) && tveIndices1.equals(tveIndices2); }
java
private static boolean vectorsMatch(VectorValueExpression e1, VectorValueExpression e2) { final Set<ConstantValueExpression> c1 = new HashSet<>(), c2 = new HashSet<>(); final Set<Integer> tveIndices1 = new HashSet<>(), tveIndices2 = new HashSet<>(); e1.getArgs().forEach(e -> { if (e instanceof ConstantValueExpression || e instanceof ParameterValueExpression) { c1.add(asCVE(e)); } else { assert (e instanceof TupleValueExpression); tveIndices1.add(((TupleValueExpression) e).getColumnIndex()); } }); e2.getArgs().forEach(e -> { if (e instanceof ConstantValueExpression || e instanceof ParameterValueExpression) { c2.add(asCVE(e)); } else { assert (e instanceof TupleValueExpression); tveIndices2.add(((TupleValueExpression) e).getColumnIndex()); } }); return c1.equals(c2) && tveIndices1.equals(tveIndices2); }
[ "private", "static", "boolean", "vectorsMatch", "(", "VectorValueExpression", "e1", ",", "VectorValueExpression", "e2", ")", "{", "final", "Set", "<", "ConstantValueExpression", ">", "c1", "=", "new", "HashSet", "<>", "(", ")", ",", "c2", "=", "new", "HashSet"...
Compare two vectors as sets, e.g. "WHERE a in (1, 2, 3)" vs. "WHERE a in (2, 1, 3)", to check whether two VVEs match. \pre all contents of VVE are either CVE or PVE. @param e1 first expression @param e2 second expression @return whether they are equivalent as collection of sets.
[ "Compare", "two", "vectors", "as", "sets", "e", ".", "g", ".", "WHERE", "a", "in", "(", "1", "2", "3", ")", "vs", ".", "WHERE", "a", "in", "(", "2", "1", "3", ")", "to", "check", "whether", "two", "VVEs", "match", ".", "\\", "pre", "all", "co...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/FilterMatcher.java#L170-L190
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/publisher/DataPublisher.java
DataPublisher.getInstance
public static DataPublisher getInstance(Class<? extends DataPublisher> dataPublisherClass, State state) throws ReflectiveOperationException { Constructor<? extends DataPublisher> dataPublisherConstructor = dataPublisherClass.getConstructor(State.class); return dataPublisherConstructor.newInstance(state); }
java
public static DataPublisher getInstance(Class<? extends DataPublisher> dataPublisherClass, State state) throws ReflectiveOperationException { Constructor<? extends DataPublisher> dataPublisherConstructor = dataPublisherClass.getConstructor(State.class); return dataPublisherConstructor.newInstance(state); }
[ "public", "static", "DataPublisher", "getInstance", "(", "Class", "<", "?", "extends", "DataPublisher", ">", "dataPublisherClass", ",", "State", "state", ")", "throws", "ReflectiveOperationException", "{", "Constructor", "<", "?", "extends", "DataPublisher", ">", "d...
Get an instance of {@link DataPublisher}. @param dataPublisherClass A concrete class that extends {@link DataPublisher}. @param state A {@link State} used to instantiate the {@link DataPublisher}. @return A {@link DataPublisher} instance.
[ "Get", "an", "instance", "of", "{", "@link", "DataPublisher", "}", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/publisher/DataPublisher.java#L97-L101
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/GroupWsSupport.java
GroupWsSupport.findGroup
public GroupId findGroup(DbSession dbSession, Request request) { return GroupId.from(findGroupDto(dbSession, request)); }
java
public GroupId findGroup(DbSession dbSession, Request request) { return GroupId.from(findGroupDto(dbSession, request)); }
[ "public", "GroupId", "findGroup", "(", "DbSession", "dbSession", ",", "Request", "request", ")", "{", "return", "GroupId", ".", "from", "(", "findGroupDto", "(", "dbSession", ",", "request", ")", ")", ";", "}" ]
Find a group by its id (parameter {@link #PARAM_GROUP_ID}) or couple organization key/group name (parameters {@link #PARAM_ORGANIZATION_KEY} and {@link #PARAM_GROUP_NAME}). The virtual group "Anyone" is not supported. @throws NotFoundException if parameters are missing/incorrect, if the requested group does not exist or if the virtual group "Anyone" is requested.
[ "Find", "a", "group", "by", "its", "id", "(", "parameter", "{", "@link", "#PARAM_GROUP_ID", "}", ")", "or", "couple", "organization", "key", "/", "group", "name", "(", "parameters", "{", "@link", "#PARAM_ORGANIZATION_KEY", "}", "and", "{", "@link", "#PARAM_G...
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/usergroups/ws/GroupWsSupport.java#L75-L77
VoltDB/voltdb
src/frontend/org/voltdb/planner/parseinfo/StmtTargetTableScan.java
StmtTargetTableScan.processTVE
@Override public AbstractExpression processTVE(TupleValueExpression tve, String columnName) { if (m_origSubqueryScan == null) { tve.resolveForTable(m_table); return tve; } // Example: // SELECT TA1.CA CA1 FROM (SELECT T.C CA FROM T TA) TA1; // gets simplified into // SELECT TA1.C CA1 FROM T TA1; // The TA1(TA1).(CA)CA1 TVE needs to be adjusted to be T(TA1).C(CA) // since the original SELECT T.C CA FROM T TA subquery was optimized out. // Table name TA1 is replaced with the original table name T // Column name CA is replaced with the original column name C // Expression differentiator to be replaced with the differentiator // from the original column (T.C) Integer columnIndex = m_origSubqueryScan.getColumnIndex(columnName, tve.getDifferentiator()); if (columnIndex == null) { throw new PlanningErrorException("Column <" + columnName + "> not found. Please update your query.", 1); } SchemaColumn originalSchemaColumn = m_origSubqueryScan.getSchemaColumn(columnIndex); assert(originalSchemaColumn != null); String origColumnName = originalSchemaColumn.getColumnName(); // Get the original column expression and adjust its aliases AbstractExpression colExpr = originalSchemaColumn.getExpression(); List<TupleValueExpression> tves = ExpressionUtil.getTupleValueExpressions(colExpr); for (TupleValueExpression subqTve : tves) { if (subqTve == colExpr) { subqTve.setTableName(getTableName()); subqTve.setColumnName(origColumnName); subqTve.setColumnAlias(tve.getColumnAlias()); } subqTve.setTableAlias(tve.getTableAlias()); subqTve.resolveForTable(m_table); } return colExpr; }
java
@Override public AbstractExpression processTVE(TupleValueExpression tve, String columnName) { if (m_origSubqueryScan == null) { tve.resolveForTable(m_table); return tve; } // Example: // SELECT TA1.CA CA1 FROM (SELECT T.C CA FROM T TA) TA1; // gets simplified into // SELECT TA1.C CA1 FROM T TA1; // The TA1(TA1).(CA)CA1 TVE needs to be adjusted to be T(TA1).C(CA) // since the original SELECT T.C CA FROM T TA subquery was optimized out. // Table name TA1 is replaced with the original table name T // Column name CA is replaced with the original column name C // Expression differentiator to be replaced with the differentiator // from the original column (T.C) Integer columnIndex = m_origSubqueryScan.getColumnIndex(columnName, tve.getDifferentiator()); if (columnIndex == null) { throw new PlanningErrorException("Column <" + columnName + "> not found. Please update your query.", 1); } SchemaColumn originalSchemaColumn = m_origSubqueryScan.getSchemaColumn(columnIndex); assert(originalSchemaColumn != null); String origColumnName = originalSchemaColumn.getColumnName(); // Get the original column expression and adjust its aliases AbstractExpression colExpr = originalSchemaColumn.getExpression(); List<TupleValueExpression> tves = ExpressionUtil.getTupleValueExpressions(colExpr); for (TupleValueExpression subqTve : tves) { if (subqTve == colExpr) { subqTve.setTableName(getTableName()); subqTve.setColumnName(origColumnName); subqTve.setColumnAlias(tve.getColumnAlias()); } subqTve.setTableAlias(tve.getTableAlias()); subqTve.resolveForTable(m_table); } return colExpr; }
[ "@", "Override", "public", "AbstractExpression", "processTVE", "(", "TupleValueExpression", "tve", ",", "String", "columnName", ")", "{", "if", "(", "m_origSubqueryScan", "==", "null", ")", "{", "tve", ".", "resolveForTable", "(", "m_table", ")", ";", "return", ...
/* Process this tve named columnName. Most often we just resolve the tve in the table of this scan. But if this is a table which is a replacement for a derived table, we may need to return the expression which is in the display list for the derived table and update aliases in tves in that expression.
[ "/", "*", "Process", "this", "tve", "named", "columnName", ".", "Most", "often", "we", "just", "resolve", "the", "tve", "in", "the", "table", "of", "this", "scan", ".", "But", "if", "this", "is", "a", "table", "which", "is", "a", "replacement", "for", ...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/planner/parseinfo/StmtTargetTableScan.java#L132-L173
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java
ChatController.handleMessageError
private Observable<ChatResult> handleMessageError(MessageProcessor mp, Throwable t) { return persistenceController.updateStoreForSentError(mp.getConversationId(), mp.getTempId(), mp.getSender()) .map(success -> new ChatResult(false, new ChatResult.Error(0, t))); }
java
private Observable<ChatResult> handleMessageError(MessageProcessor mp, Throwable t) { return persistenceController.updateStoreForSentError(mp.getConversationId(), mp.getTempId(), mp.getSender()) .map(success -> new ChatResult(false, new ChatResult.Error(0, t))); }
[ "private", "Observable", "<", "ChatResult", ">", "handleMessageError", "(", "MessageProcessor", "mp", ",", "Throwable", "t", ")", "{", "return", "persistenceController", ".", "updateStoreForSentError", "(", "mp", ".", "getConversationId", "(", ")", ",", "mp", ".",...
Handle failure when sent message. @param mp Message processor holding message sent details. @param t Thrown exception. @return Observable with Chat SDK result.
[ "Handle", "failure", "when", "sent", "message", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/ChatController.java#L219-L222
buschmais/jqa-java-plugin
src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java
VisitorHelper.resolveType
TypeCache.CachedType resolveType(String fullQualifiedName, TypeCache.CachedType<? extends ClassFileDescriptor> dependentType) { TypeCache.CachedType cachedType = getTypeResolver().resolve(fullQualifiedName, scannerContext); if (!dependentType.equals(cachedType)) { dependentType.addDependency(cachedType.getTypeDescriptor()); } return cachedType; }
java
TypeCache.CachedType resolveType(String fullQualifiedName, TypeCache.CachedType<? extends ClassFileDescriptor> dependentType) { TypeCache.CachedType cachedType = getTypeResolver().resolve(fullQualifiedName, scannerContext); if (!dependentType.equals(cachedType)) { dependentType.addDependency(cachedType.getTypeDescriptor()); } return cachedType; }
[ "TypeCache", ".", "CachedType", "resolveType", "(", "String", "fullQualifiedName", ",", "TypeCache", ".", "CachedType", "<", "?", "extends", "ClassFileDescriptor", ">", "dependentType", ")", "{", "TypeCache", ".", "CachedType", "cachedType", "=", "getTypeResolver", ...
/* Return the type descriptor for the given type name. @param typeName The full qualified name of the type (e.g. java.lang.Object).
[ "/", "*", "Return", "the", "type", "descriptor", "for", "the", "given", "type", "name", "." ]
train
https://github.com/buschmais/jqa-java-plugin/blob/4c050943e9c28cf1c4a08aa962d5b5bf03c4fe54/src/main/java/com/buschmais/jqassistant/plugin/java/impl/scanner/visitor/VisitorHelper.java#L51-L57
getsentry/sentry-java
sentry/src/main/java/io/sentry/event/EventBuilder.java
EventBuilder.withSentryInterface
public EventBuilder withSentryInterface(SentryInterface sentryInterface, boolean replace) { if (replace || !event.getSentryInterfaces().containsKey(sentryInterface.getInterfaceName())) { event.getSentryInterfaces().put(sentryInterface.getInterfaceName(), sentryInterface); } return this; }
java
public EventBuilder withSentryInterface(SentryInterface sentryInterface, boolean replace) { if (replace || !event.getSentryInterfaces().containsKey(sentryInterface.getInterfaceName())) { event.getSentryInterfaces().put(sentryInterface.getInterfaceName(), sentryInterface); } return this; }
[ "public", "EventBuilder", "withSentryInterface", "(", "SentryInterface", "sentryInterface", ",", "boolean", "replace", ")", "{", "if", "(", "replace", "||", "!", "event", ".", "getSentryInterfaces", "(", ")", ".", "containsKey", "(", "sentryInterface", ".", "getIn...
Adds a {@link SentryInterface} to the event. <p> Checks whether or not the entry already exists, and replaces it only if {@code replace} is true. @param sentryInterface sentry interface to add to the event. @param replace If true and a Sentry Interface with the same name has already been added it will be replaced. If false the statement will be ignored. @return the current {@code EventBuilder} for chained calls.
[ "Adds", "a", "{", "@link", "SentryInterface", "}", "to", "the", "event", ".", "<p", ">", "Checks", "whether", "or", "not", "the", "entry", "already", "exists", "and", "replaces", "it", "only", "if", "{", "@code", "replace", "}", "is", "true", "." ]
train
https://github.com/getsentry/sentry-java/blob/2e01461775cbd5951ff82b566069c349146d8aca/sentry/src/main/java/io/sentry/event/EventBuilder.java#L424-L429
gallandarakhneorg/afc
advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java
GISCoordinates.L1_WSG84
@Pure public static GeodesicPosition L1_WSG84(double x, double y) { final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_1_N, LAMBERT_1_C, LAMBERT_1_XS, LAMBERT_1_YS); return NTFLambdaPhi_WSG84(ntfLambdaPhi.getX(), ntfLambdaPhi.getY()); }
java
@Pure public static GeodesicPosition L1_WSG84(double x, double y) { final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y, LAMBERT_1_N, LAMBERT_1_C, LAMBERT_1_XS, LAMBERT_1_YS); return NTFLambdaPhi_WSG84(ntfLambdaPhi.getX(), ntfLambdaPhi.getY()); }
[ "@", "Pure", "public", "static", "GeodesicPosition", "L1_WSG84", "(", "double", "x", ",", "double", "y", ")", "{", "final", "Point2d", "ntfLambdaPhi", "=", "NTFLambert_NTFLambdaPhi", "(", "x", ",", "y", ",", "LAMBERT_1_N", ",", "LAMBERT_1_C", ",", "LAMBERT_1_X...
This function convert France Lambert I coordinate to geographic WSG84 Data. @param x is the coordinate in France Lambert I @param y is the coordinate in France Lambert I @return lambda and phi in geographic WSG84 in degrees.
[ "This", "function", "convert", "France", "Lambert", "I", "coordinate", "to", "geographic", "WSG84", "Data", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/coordinate/GISCoordinates.java#L287-L295
windup/windup
config-xml/addon/src/main/java/org/jboss/windup/config/parser/ParserContext.java
ParserContext.processDocument
public <T> T processDocument(URI uri) throws ConfigurationException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); DocumentBuilder dBuilder = null; try { dBuilder = dbFactory.newDocumentBuilder(); } catch (Exception e) { throw new WindupException("Failed to build xml parser due to: " + e.getMessage(), e); } try { Document doc = dBuilder.parse(uri.toString()); return processElement(doc.getDocumentElement()); } catch (Exception e) { throw new WindupException("Failed to parse document at: " + uri + ", due to: " + e.getMessage(), e); } }
java
public <T> T processDocument(URI uri) throws ConfigurationException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); dbFactory.setNamespaceAware(true); DocumentBuilder dBuilder = null; try { dBuilder = dbFactory.newDocumentBuilder(); } catch (Exception e) { throw new WindupException("Failed to build xml parser due to: " + e.getMessage(), e); } try { Document doc = dBuilder.parse(uri.toString()); return processElement(doc.getDocumentElement()); } catch (Exception e) { throw new WindupException("Failed to parse document at: " + uri + ", due to: " + e.getMessage(), e); } }
[ "public", "<", "T", ">", "T", "processDocument", "(", "URI", "uri", ")", "throws", "ConfigurationException", "{", "DocumentBuilderFactory", "dbFactory", "=", "DocumentBuilderFactory", ".", "newInstance", "(", ")", ";", "dbFactory", ".", "setNamespaceAware", "(", "...
Processes the XML document at the provided {@link URL} and returns a result from the namespace element handlers.
[ "Processes", "the", "XML", "document", "at", "the", "provided", "{" ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config-xml/addon/src/main/java/org/jboss/windup/config/parser/ParserContext.java#L108-L133
saxsys/SynchronizeFX
synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/executors/lists/ReplaceInListRepairer.java
ReplaceInListRepairer.repairCommand
public ReplaceInList repairCommand(final ReplaceInList toRepair, final AddToList repairAgainst) { if (repairAgainst.getPosition() > toRepair.getPosition()) { return toRepair; } return new ReplaceInList(toRepair.getListId(), toRepair.getListVersionChange(), toRepair.getValue(), toRepair.getPosition() + 1); }
java
public ReplaceInList repairCommand(final ReplaceInList toRepair, final AddToList repairAgainst) { if (repairAgainst.getPosition() > toRepair.getPosition()) { return toRepair; } return new ReplaceInList(toRepair.getListId(), toRepair.getListVersionChange(), toRepair.getValue(), toRepair.getPosition() + 1); }
[ "public", "ReplaceInList", "repairCommand", "(", "final", "ReplaceInList", "toRepair", ",", "final", "AddToList", "repairAgainst", ")", "{", "if", "(", "repairAgainst", ".", "getPosition", "(", ")", ">", "toRepair", ".", "getPosition", "(", ")", ")", "{", "ret...
Repairs a {@link ReplaceInList} in relation to an {@link AddToList} command. @param toRepair The command to repair. @param repairAgainst The command to repair against. @return The repaired command.
[ "Repairs", "a", "{", "@link", "ReplaceInList", "}", "in", "relation", "to", "an", "{", "@link", "AddToList", "}", "command", "." ]
train
https://github.com/saxsys/SynchronizeFX/blob/f3683020e4749110b38514eb5bc73a247998b579/synchronizefx-core/src/main/java/de/saxsys/synchronizefx/core/metamodel/executors/lists/ReplaceInListRepairer.java#L46-L52
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateTimePatternGenerator.java
DateTimePatternGenerator.getBestAppending
private String getBestAppending(DateTimeMatcher source, int missingFields, DistanceInfo distInfo, DateTimeMatcher skipMatcher, EnumSet<DTPGflags> flags, int options) { String resultPattern = null; if (missingFields != 0) { PatternWithMatcher resultPatternWithMatcher = getBestRaw(source, missingFields, distInfo, skipMatcher); resultPattern = adjustFieldTypes(resultPatternWithMatcher, source, flags, options); while (distInfo.missingFieldMask != 0) { // precondition: EVERY single field must work! // special hack for SSS. If we are missing SSS, and we had ss but found it, replace the s field according to the // number separator if ((distInfo.missingFieldMask & SECOND_AND_FRACTIONAL_MASK) == FRACTIONAL_MASK && (missingFields & SECOND_AND_FRACTIONAL_MASK) == SECOND_AND_FRACTIONAL_MASK) { resultPatternWithMatcher.pattern = resultPattern; flags = EnumSet.copyOf(flags); flags.add(DTPGflags.FIX_FRACTIONAL_SECONDS); resultPattern = adjustFieldTypes(resultPatternWithMatcher, source, flags, options); distInfo.missingFieldMask &= ~FRACTIONAL_MASK; // remove bit continue; } int startingMask = distInfo.missingFieldMask; PatternWithMatcher tempWithMatcher = getBestRaw(source, distInfo.missingFieldMask, distInfo, skipMatcher); String temp = adjustFieldTypes(tempWithMatcher, source, flags, options); int foundMask = startingMask & ~distInfo.missingFieldMask; int topField = getTopBitNumber(foundMask); resultPattern = SimpleFormatterImpl.formatRawPattern( getAppendFormat(topField), 2, 3, resultPattern, temp, getAppendName(topField)); } } return resultPattern; }
java
private String getBestAppending(DateTimeMatcher source, int missingFields, DistanceInfo distInfo, DateTimeMatcher skipMatcher, EnumSet<DTPGflags> flags, int options) { String resultPattern = null; if (missingFields != 0) { PatternWithMatcher resultPatternWithMatcher = getBestRaw(source, missingFields, distInfo, skipMatcher); resultPattern = adjustFieldTypes(resultPatternWithMatcher, source, flags, options); while (distInfo.missingFieldMask != 0) { // precondition: EVERY single field must work! // special hack for SSS. If we are missing SSS, and we had ss but found it, replace the s field according to the // number separator if ((distInfo.missingFieldMask & SECOND_AND_FRACTIONAL_MASK) == FRACTIONAL_MASK && (missingFields & SECOND_AND_FRACTIONAL_MASK) == SECOND_AND_FRACTIONAL_MASK) { resultPatternWithMatcher.pattern = resultPattern; flags = EnumSet.copyOf(flags); flags.add(DTPGflags.FIX_FRACTIONAL_SECONDS); resultPattern = adjustFieldTypes(resultPatternWithMatcher, source, flags, options); distInfo.missingFieldMask &= ~FRACTIONAL_MASK; // remove bit continue; } int startingMask = distInfo.missingFieldMask; PatternWithMatcher tempWithMatcher = getBestRaw(source, distInfo.missingFieldMask, distInfo, skipMatcher); String temp = adjustFieldTypes(tempWithMatcher, source, flags, options); int foundMask = startingMask & ~distInfo.missingFieldMask; int topField = getTopBitNumber(foundMask); resultPattern = SimpleFormatterImpl.formatRawPattern( getAppendFormat(topField), 2, 3, resultPattern, temp, getAppendName(topField)); } } return resultPattern; }
[ "private", "String", "getBestAppending", "(", "DateTimeMatcher", "source", ",", "int", "missingFields", ",", "DistanceInfo", "distInfo", ",", "DateTimeMatcher", "skipMatcher", ",", "EnumSet", "<", "DTPGflags", ">", "flags", ",", "int", "options", ")", "{", "String...
We only get called here if we failed to find an exact skeleton. We have broken it into date + time, and look for the pieces. If we fail to find a complete skeleton, we compose in a loop until we have all the fields.
[ "We", "only", "get", "called", "here", "if", "we", "failed", "to", "find", "an", "exact", "skeleton", ".", "We", "have", "broken", "it", "into", "date", "+", "time", "and", "look", "for", "the", "pieces", ".", "If", "we", "fail", "to", "find", "a", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateTimePatternGenerator.java#L1761-L1791
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java
ComputerVisionImpl.analyzeImageInStreamWithServiceResponseAsync
public Observable<ServiceResponse<ImageAnalysis>> analyzeImageInStreamWithServiceResponseAsync(byte[] image, AnalyzeImageInStreamOptionalParameter analyzeImageInStreamOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (image == null) { throw new IllegalArgumentException("Parameter image is required and cannot be null."); } final List<VisualFeatureTypes> visualFeatures = analyzeImageInStreamOptionalParameter != null ? analyzeImageInStreamOptionalParameter.visualFeatures() : null; final String details = analyzeImageInStreamOptionalParameter != null ? analyzeImageInStreamOptionalParameter.details() : null; final String language = analyzeImageInStreamOptionalParameter != null ? analyzeImageInStreamOptionalParameter.language() : null; return analyzeImageInStreamWithServiceResponseAsync(image, visualFeatures, details, language); }
java
public Observable<ServiceResponse<ImageAnalysis>> analyzeImageInStreamWithServiceResponseAsync(byte[] image, AnalyzeImageInStreamOptionalParameter analyzeImageInStreamOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (image == null) { throw new IllegalArgumentException("Parameter image is required and cannot be null."); } final List<VisualFeatureTypes> visualFeatures = analyzeImageInStreamOptionalParameter != null ? analyzeImageInStreamOptionalParameter.visualFeatures() : null; final String details = analyzeImageInStreamOptionalParameter != null ? analyzeImageInStreamOptionalParameter.details() : null; final String language = analyzeImageInStreamOptionalParameter != null ? analyzeImageInStreamOptionalParameter.language() : null; return analyzeImageInStreamWithServiceResponseAsync(image, visualFeatures, details, language); }
[ "public", "Observable", "<", "ServiceResponse", "<", "ImageAnalysis", ">", ">", "analyzeImageInStreamWithServiceResponseAsync", "(", "byte", "[", "]", "image", ",", "AnalyzeImageInStreamOptionalParameter", "analyzeImageInStreamOptionalParameter", ")", "{", "if", "(", "this"...
This operation extracts a rich set of visual features based on the image content. @param image An image stream. @param analyzeImageInStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImageAnalysis object
[ "This", "operation", "extracts", "a", "rich", "set", "of", "visual", "features", "based", "on", "the", "image", "content", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L1121-L1133
j-a-w-r/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PropertiesConfigHelper.java
PropertiesConfigHelper.getCustomBundlePropertyAsMap
public Map<String, List<String>> getCustomBundlePropertyAsMap(String bundleName, String key) { Map<String, List<String>> propertiesMap = new HashMap<>(); StringTokenizer tk = new StringTokenizer(getCustomBundleProperty(bundleName, key, ""), ";"); while (tk.hasMoreTokens()) { String[] mapEntry = tk.nextToken().trim().split(":"); String mapKey = mapEntry[0]; String values = mapEntry[1]; StringTokenizer valueTk = new StringTokenizer(values, ","); List<String> valueList = new ArrayList<>(); while (valueTk.hasMoreTokens()) { valueList.add(valueTk.nextToken().trim()); } propertiesMap.put(mapKey, valueList); } return propertiesMap; }
java
public Map<String, List<String>> getCustomBundlePropertyAsMap(String bundleName, String key) { Map<String, List<String>> propertiesMap = new HashMap<>(); StringTokenizer tk = new StringTokenizer(getCustomBundleProperty(bundleName, key, ""), ";"); while (tk.hasMoreTokens()) { String[] mapEntry = tk.nextToken().trim().split(":"); String mapKey = mapEntry[0]; String values = mapEntry[1]; StringTokenizer valueTk = new StringTokenizer(values, ","); List<String> valueList = new ArrayList<>(); while (valueTk.hasMoreTokens()) { valueList.add(valueTk.nextToken().trim()); } propertiesMap.put(mapKey, valueList); } return propertiesMap; }
[ "public", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "getCustomBundlePropertyAsMap", "(", "String", "bundleName", ",", "String", "key", ")", "{", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "propertiesMap", "=", "new", "H...
Returns as a set, the comma separated values of a property @param bundleName the bundle name @param key the key of the property @return a set of the comma separated values of a property
[ "Returns", "as", "a", "set", "the", "comma", "separated", "values", "of", "a", "property" ]
train
https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PropertiesConfigHelper.java#L215-L232
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java
DirContextDnsResolver.resolve
@Override public InetAddress[] resolve(String host) throws UnknownHostException { if (ipStringToBytes(host) != null) { return new InetAddress[] { InetAddress.getByAddress(ipStringToBytes(host)) }; } List<InetAddress> inetAddresses = new ArrayList<>(); try { resolve(host, inetAddresses); } catch (NamingException e) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname because of %s", host, e)); } if (inetAddresses.isEmpty()) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname", host)); } return inetAddresses.toArray(new InetAddress[inetAddresses.size()]); }
java
@Override public InetAddress[] resolve(String host) throws UnknownHostException { if (ipStringToBytes(host) != null) { return new InetAddress[] { InetAddress.getByAddress(ipStringToBytes(host)) }; } List<InetAddress> inetAddresses = new ArrayList<>(); try { resolve(host, inetAddresses); } catch (NamingException e) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname because of %s", host, e)); } if (inetAddresses.isEmpty()) { throw new UnknownHostException(String.format("Cannot resolve %s to a hostname", host)); } return inetAddresses.toArray(new InetAddress[inetAddresses.size()]); }
[ "@", "Override", "public", "InetAddress", "[", "]", "resolve", "(", "String", "host", ")", "throws", "UnknownHostException", "{", "if", "(", "ipStringToBytes", "(", "host", ")", "!=", "null", ")", "{", "return", "new", "InetAddress", "[", "]", "{", "InetAd...
Perform hostname to address resolution. @param host the hostname, must not be empty or {@literal null}. @return array of one or more {@link InetAddress adresses} @throws UnknownHostException
[ "Perform", "hostname", "to", "address", "resolution", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/resource/DirContextDnsResolver.java#L158-L177
apereo/cas
support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/WsFederationHelper.java
WsFederationHelper.buildSignatureTrustEngine
@SneakyThrows private static SignatureTrustEngine buildSignatureTrustEngine(final WsFederationConfiguration wsFederationConfiguration) { val signingWallet = wsFederationConfiguration.getSigningWallet(); LOGGER.debug("Building signature trust engine based on the following signing certificates:"); signingWallet.forEach(c -> LOGGER.debug("Credential entity id [{}] with public key [{}]", c.getEntityId(), c.getPublicKey())); val resolver = new StaticCredentialResolver(signingWallet); val keyResolver = new StaticKeyInfoCredentialResolver(signingWallet); return new ExplicitKeySignatureTrustEngine(resolver, keyResolver); }
java
@SneakyThrows private static SignatureTrustEngine buildSignatureTrustEngine(final WsFederationConfiguration wsFederationConfiguration) { val signingWallet = wsFederationConfiguration.getSigningWallet(); LOGGER.debug("Building signature trust engine based on the following signing certificates:"); signingWallet.forEach(c -> LOGGER.debug("Credential entity id [{}] with public key [{}]", c.getEntityId(), c.getPublicKey())); val resolver = new StaticCredentialResolver(signingWallet); val keyResolver = new StaticKeyInfoCredentialResolver(signingWallet); return new ExplicitKeySignatureTrustEngine(resolver, keyResolver); }
[ "@", "SneakyThrows", "private", "static", "SignatureTrustEngine", "buildSignatureTrustEngine", "(", "final", "WsFederationConfiguration", "wsFederationConfiguration", ")", "{", "val", "signingWallet", "=", "wsFederationConfiguration", ".", "getSigningWallet", "(", ")", ";", ...
Build signature trust engine. @param wsFederationConfiguration the ws federation configuration @return the signature trust engine
[ "Build", "signature", "trust", "engine", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-wsfederation/src/main/java/org/apereo/cas/support/wsfederation/WsFederationHelper.java#L92-L101
netty/netty
handler/src/main/java/io/netty/handler/ssl/SniHandler.java
SniHandler.replaceHandler
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception { SslHandler sslHandler = null; try { sslHandler = newSslHandler(sslContext, ctx.alloc()); ctx.pipeline().replace(this, SslHandler.class.getName(), sslHandler); sslHandler = null; } finally { // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not // transferred to the SslHandler. // See https://github.com/netty/netty/issues/5678 if (sslHandler != null) { ReferenceCountUtil.safeRelease(sslHandler.engine()); } } }
java
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception { SslHandler sslHandler = null; try { sslHandler = newSslHandler(sslContext, ctx.alloc()); ctx.pipeline().replace(this, SslHandler.class.getName(), sslHandler); sslHandler = null; } finally { // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not // transferred to the SslHandler. // See https://github.com/netty/netty/issues/5678 if (sslHandler != null) { ReferenceCountUtil.safeRelease(sslHandler.engine()); } } }
[ "protected", "void", "replaceHandler", "(", "ChannelHandlerContext", "ctx", ",", "String", "hostname", ",", "SslContext", "sslContext", ")", "throws", "Exception", "{", "SslHandler", "sslHandler", "=", "null", ";", "try", "{", "sslHandler", "=", "newSslHandler", "...
The default implementation of this method will simply replace {@code this} {@link SniHandler} instance with a {@link SslHandler}. Users may override this method to implement custom behavior. Please be aware that this method may get called after a client has already disconnected and custom implementations must take it into consideration when overriding this method. It's also possible for the hostname argument to be {@code null}.
[ "The", "default", "implementation", "of", "this", "method", "will", "simply", "replace", "{", "@code", "this", "}", "{", "@link", "SniHandler", "}", "instance", "with", "a", "{", "@link", "SslHandler", "}", ".", "Users", "may", "override", "this", "method", ...
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SniHandler.java#L130-L144
zk1931/jzab
src/main/java/com/github/zk1931/jzab/Participant.java
Participant.sendMessage
protected void sendMessage(String dest, Message message) { if (LOG.isTraceEnabled()) { LOG.trace("Sends message {} to {}.", TextFormat.shortDebugString(message), dest); } this.transport.send(dest, message); }
java
protected void sendMessage(String dest, Message message) { if (LOG.isTraceEnabled()) { LOG.trace("Sends message {} to {}.", TextFormat.shortDebugString(message), dest); } this.transport.send(dest, message); }
[ "protected", "void", "sendMessage", "(", "String", "dest", ",", "Message", "message", ")", "{", "if", "(", "LOG", ".", "isTraceEnabled", "(", ")", ")", "{", "LOG", ".", "trace", "(", "\"Sends message {} to {}.\"", ",", "TextFormat", ".", "shortDebugString", ...
Sends message to the specific destination. @param dest the destination of the message. @param message the message to be sent.
[ "Sends", "message", "to", "the", "specific", "destination", "." ]
train
https://github.com/zk1931/jzab/blob/2a8893bcc1a125f3aebdaddee80ad49c9761bba1/src/main/java/com/github/zk1931/jzab/Participant.java#L265-L272
kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/filter/statistic/ProfilerTimerFilter.java
ProfilerTimerFilter.sessionClosed
@Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { if (profileSessionClosed) { long start = timeNow(); nextFilter.sessionClosed(session); long end = timeNow(); sessionClosedTimerWorker.addNewDuration(end - start); } else { nextFilter.sessionClosed(session); } }
java
@Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { if (profileSessionClosed) { long start = timeNow(); nextFilter.sessionClosed(session); long end = timeNow(); sessionClosedTimerWorker.addNewDuration(end - start); } else { nextFilter.sessionClosed(session); } }
[ "@", "Override", "public", "void", "sessionClosed", "(", "NextFilter", "nextFilter", ",", "IoSession", "session", ")", "throws", "Exception", "{", "if", "(", "profileSessionClosed", ")", "{", "long", "start", "=", "timeNow", "(", ")", ";", "nextFilter", ".", ...
Profile a SessionClosed event. This method will gather the following informations : - the method duration - the shortest execution time - the slowest execution time - the average execution time - the global number of calls @param nextFilter The filter to call next @param session The associated session
[ "Profile", "a", "SessionClosed", "event", ".", "This", "method", "will", "gather", "the", "following", "informations", ":", "-", "the", "method", "duration", "-", "the", "shortest", "execution", "time", "-", "the", "slowest", "execution", "time", "-", "the", ...
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/filter/statistic/ProfilerTimerFilter.java#L465-L476