repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
threerings/nenya
tools/src/main/java/com/threerings/media/tile/tools/xml/XMLTileSetParser.java
XMLTileSetParser.loadTileSets
public void loadTileSets (String path, Map<String, TileSet> tilesets) throws IOException { // get an input stream for this XML file InputStream is = ConfigUtil.getStream(path); if (is == null) { String errmsg = "Can't load tileset description file from " + "classpath [path=" + path + "]."; throw new FileNotFoundException(errmsg); } // load up the tilesets loadTileSets(is, tilesets); }
java
public void loadTileSets (String path, Map<String, TileSet> tilesets) throws IOException { // get an input stream for this XML file InputStream is = ConfigUtil.getStream(path); if (is == null) { String errmsg = "Can't load tileset description file from " + "classpath [path=" + path + "]."; throw new FileNotFoundException(errmsg); } // load up the tilesets loadTileSets(is, tilesets); }
[ "public", "void", "loadTileSets", "(", "String", "path", ",", "Map", "<", "String", ",", "TileSet", ">", "tilesets", ")", "throws", "IOException", "{", "// get an input stream for this XML file", "InputStream", "is", "=", "ConfigUtil", ".", "getStream", "(", "path...
Loads all of the tilesets specified in the supplied XML tileset description file and places them into the supplied map indexed by tileset name. This method is not reentrant, so don't go calling it from multiple threads. @param path a path, relative to the classpath, at which the tileset definition file can be found. @param tilesets the map into which the tilesets will be placed, indexed by tileset name.
[ "Loads", "all", "of", "the", "tilesets", "specified", "in", "the", "supplied", "XML", "tileset", "description", "file", "and", "places", "them", "into", "the", "supplied", "map", "indexed", "by", "tileset", "name", ".", "This", "method", "is", "not", "reentr...
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/tools/src/main/java/com/threerings/media/tile/tools/xml/XMLTileSetParser.java#L97-L110
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Factory.java
Factory.createSetup
@SuppressWarnings("unchecked") private Setup createSetup(Media media) { final Configurer configurer = new Configurer(media); try { final FeaturableConfig config = FeaturableConfig.imports(configurer); final String setup = config.getSetupName(); final Class<? extends Setup> setupClass; if (setup.isEmpty()) { final Class<?> clazz = classLoader.loadClass(config.getClassName()); final Constructor<?> constructor = UtilReflection.getCompatibleConstructorParent(clazz, new Class<?>[] { Services.class, Setup.class }); setupClass = (Class<? extends Setup>) constructor.getParameterTypes()[SETUP_INDEX]; } else { setupClass = (Class<? extends Setup>) classLoader.loadClass(config.getSetupName()); } return UtilReflection.create(setupClass, new Class<?>[] { Media.class }, media); } catch (final ClassNotFoundException exception) { throw new LionEngineException(exception, ERROR_SETUP_CLASS); } catch (final NoSuchMethodException exception) { throw new LionEngineException(exception, ERROR_CONSTRUCTOR_MISSING + media.getPath()); } }
java
@SuppressWarnings("unchecked") private Setup createSetup(Media media) { final Configurer configurer = new Configurer(media); try { final FeaturableConfig config = FeaturableConfig.imports(configurer); final String setup = config.getSetupName(); final Class<? extends Setup> setupClass; if (setup.isEmpty()) { final Class<?> clazz = classLoader.loadClass(config.getClassName()); final Constructor<?> constructor = UtilReflection.getCompatibleConstructorParent(clazz, new Class<?>[] { Services.class, Setup.class }); setupClass = (Class<? extends Setup>) constructor.getParameterTypes()[SETUP_INDEX]; } else { setupClass = (Class<? extends Setup>) classLoader.loadClass(config.getSetupName()); } return UtilReflection.create(setupClass, new Class<?>[] { Media.class }, media); } catch (final ClassNotFoundException exception) { throw new LionEngineException(exception, ERROR_SETUP_CLASS); } catch (final NoSuchMethodException exception) { throw new LionEngineException(exception, ERROR_CONSTRUCTOR_MISSING + media.getPath()); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "Setup", "createSetup", "(", "Media", "media", ")", "{", "final", "Configurer", "configurer", "=", "new", "Configurer", "(", "media", ")", ";", "try", "{", "final", "FeaturableConfig", "config", "=...
Create a setup from its media. @param media The media reference. @return The setup instance.
[ "Create", "a", "setup", "from", "its", "media", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/Factory.java#L215-L250
CubeEngine/Dirigent
src/main/java/org/cubeengine/dirigent/builder/MessageBuilder.java
MessageBuilder.buildGroup
public void buildGroup(ComponentGroup group, BuilderT builder, Context context) { for (Component component : group.getComponents()) { buildAny(component, builder, context); } }
java
public void buildGroup(ComponentGroup group, BuilderT builder, Context context) { for (Component component : group.getComponents()) { buildAny(component, builder, context); } }
[ "public", "void", "buildGroup", "(", "ComponentGroup", "group", ",", "BuilderT", "builder", ",", "Context", "context", ")", "{", "for", "(", "Component", "component", ":", "group", ".", "getComponents", "(", ")", ")", "{", "buildAny", "(", "component", ",", ...
Appends a chain of Components to the builder @param group the chained Components @param builder the builder @param context the context
[ "Appends", "a", "chain", "of", "Components", "to", "the", "builder" ]
train
https://github.com/CubeEngine/Dirigent/blob/68587a8202754a6a6b629cc15e14c516806badaa/src/main/java/org/cubeengine/dirigent/builder/MessageBuilder.java#L65-L71
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UcsApi.java
UcsApi.findOrCreatePhoneCall
public ApiSuccessResponse findOrCreatePhoneCall(String id, FindOrCreateData findOrCreateData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = findOrCreatePhoneCallWithHttpInfo(id, findOrCreateData); return resp.getData(); }
java
public ApiSuccessResponse findOrCreatePhoneCall(String id, FindOrCreateData findOrCreateData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = findOrCreatePhoneCallWithHttpInfo(id, findOrCreateData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "findOrCreatePhoneCall", "(", "String", "id", ",", "FindOrCreateData", "findOrCreateData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "findOrCreatePhoneCallWithHttpInfo", "(", "id", ",", ...
Find or create phone call in UCS @param id id of the Voice Interaction (required) @param findOrCreateData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Find", "or", "create", "phone", "call", "in", "UCS" ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UcsApi.java#L652-L655
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectOneOfImpl_CustomFieldSerializer.java
OWLObjectOneOfImpl_CustomFieldSerializer.deserializeInstance
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectOneOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectOneOfImpl instance) throws SerializationException { deserialize(streamReader, instance); }
[ "@", "Override", "public", "void", "deserializeInstance", "(", "SerializationStreamReader", "streamReader", ",", "OWLObjectOneOfImpl", "instance", ")", "throws", "SerializationException", "{", "deserialize", "(", "streamReader", ",", "instance", ")", ";", "}" ]
Deserializes the content of the object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}. @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the object's content from @param instance the object instance to deserialize @throws com.google.gwt.user.client.rpc.SerializationException if the deserialization operation is not successful
[ "Deserializes", "the", "content", "of", "the", "object", "from", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamReader", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectOneOfImpl_CustomFieldSerializer.java#L89-L92
lightblueseas/swing-components
src/main/java/de/alpharogroup/swing/robot/RobotExtensions.java
RobotExtensions.typeCharacter
public static void typeCharacter(final Robot robot, final char character) throws IllegalAccessException, NoSuchFieldException { final boolean upperCase = Character.isUpperCase(character); final int keyCode = getKeyCode(character); if (upperCase) { robot.keyPress(KeyEvent.VK_SHIFT); } robot.keyPress(keyCode); robot.keyRelease(keyCode); if (upperCase) { robot.keyRelease(KeyEvent.VK_SHIFT); } }
java
public static void typeCharacter(final Robot robot, final char character) throws IllegalAccessException, NoSuchFieldException { final boolean upperCase = Character.isUpperCase(character); final int keyCode = getKeyCode(character); if (upperCase) { robot.keyPress(KeyEvent.VK_SHIFT); } robot.keyPress(keyCode); robot.keyRelease(keyCode); if (upperCase) { robot.keyRelease(KeyEvent.VK_SHIFT); } }
[ "public", "static", "void", "typeCharacter", "(", "final", "Robot", "robot", ",", "final", "char", "character", ")", "throws", "IllegalAccessException", ",", "NoSuchFieldException", "{", "final", "boolean", "upperCase", "=", "Character", ".", "isUpperCase", "(", "...
Types the given char with the given robot. @param robot the robot @param character the character @throws IllegalAccessException the illegal access exception @throws NoSuchFieldException the no such field exception
[ "Types", "the", "given", "char", "with", "the", "given", "robot", "." ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/swing/robot/RobotExtensions.java#L71-L86
lessthanoptimal/BoofCV
integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java
VisualizeCamera2Activity.renderBitmapImage
protected void renderBitmapImage( BitmapMode mode , ImageBase image ) { switch( mode ) { case UNSAFE: { if (image.getWidth() == bitmap.getWidth() && image.getHeight() == bitmap.getHeight()) ConvertBitmap.boofToBitmap(image, bitmap, bitmapTmp); } break; case DOUBLE_BUFFER: { // TODO if there are multiple processing threads bad stuff will happen here. Need one work buffer // per thread // convert the image. this can be a slow operation if (image.getWidth() == bitmapWork.getWidth() && image.getHeight() == bitmapWork.getHeight()) ConvertBitmap.boofToBitmap(image, bitmapWork, bitmapTmp); // swap the two buffers. If it's locked don't swap. This will skip a frame but will not cause // a significant slow down if( bitmapLock.tryLock() ) { try { Bitmap tmp = bitmapWork; bitmapWork = bitmap; bitmap = tmp; } finally { bitmapLock.unlock(); } } } break; } }
java
protected void renderBitmapImage( BitmapMode mode , ImageBase image ) { switch( mode ) { case UNSAFE: { if (image.getWidth() == bitmap.getWidth() && image.getHeight() == bitmap.getHeight()) ConvertBitmap.boofToBitmap(image, bitmap, bitmapTmp); } break; case DOUBLE_BUFFER: { // TODO if there are multiple processing threads bad stuff will happen here. Need one work buffer // per thread // convert the image. this can be a slow operation if (image.getWidth() == bitmapWork.getWidth() && image.getHeight() == bitmapWork.getHeight()) ConvertBitmap.boofToBitmap(image, bitmapWork, bitmapTmp); // swap the two buffers. If it's locked don't swap. This will skip a frame but will not cause // a significant slow down if( bitmapLock.tryLock() ) { try { Bitmap tmp = bitmapWork; bitmapWork = bitmap; bitmap = tmp; } finally { bitmapLock.unlock(); } } } break; } }
[ "protected", "void", "renderBitmapImage", "(", "BitmapMode", "mode", ",", "ImageBase", "image", ")", "{", "switch", "(", "mode", ")", "{", "case", "UNSAFE", ":", "{", "if", "(", "image", ".", "getWidth", "(", ")", "==", "bitmap", ".", "getWidth", "(", ...
Renders the bitmap image to output. If you don't wish to have this behavior then override this function. Jsut make sure you respect the bitmap mode or the image might not render as desired or you could crash the app.
[ "Renders", "the", "bitmap", "image", "to", "output", ".", "If", "you", "don", "t", "wish", "to", "have", "this", "behavior", "then", "override", "this", "function", ".", "Jsut", "make", "sure", "you", "respect", "the", "bitmap", "mode", "or", "the", "ima...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/src/main/java/boofcv/android/camera2/VisualizeCamera2Activity.java#L420-L447
jhy/jsoup
src/main/java/org/jsoup/nodes/Document.java
Document.normaliseStructure
private void normaliseStructure(String tag, Element htmlEl) { Elements elements = this.getElementsByTag(tag); Element master = elements.first(); // will always be available as created above if not existent if (elements.size() > 1) { // dupes, move contents to master List<Node> toMove = new ArrayList<>(); for (int i = 1; i < elements.size(); i++) { Node dupe = elements.get(i); toMove.addAll(dupe.ensureChildNodes()); dupe.remove(); } for (Node dupe : toMove) master.appendChild(dupe); } // ensure parented by <html> if (!master.parent().equals(htmlEl)) { htmlEl.appendChild(master); // includes remove() } }
java
private void normaliseStructure(String tag, Element htmlEl) { Elements elements = this.getElementsByTag(tag); Element master = elements.first(); // will always be available as created above if not existent if (elements.size() > 1) { // dupes, move contents to master List<Node> toMove = new ArrayList<>(); for (int i = 1; i < elements.size(); i++) { Node dupe = elements.get(i); toMove.addAll(dupe.ensureChildNodes()); dupe.remove(); } for (Node dupe : toMove) master.appendChild(dupe); } // ensure parented by <html> if (!master.parent().equals(htmlEl)) { htmlEl.appendChild(master); // includes remove() } }
[ "private", "void", "normaliseStructure", "(", "String", "tag", ",", "Element", "htmlEl", ")", "{", "Elements", "elements", "=", "this", ".", "getElementsByTag", "(", "tag", ")", ";", "Element", "master", "=", "elements", ".", "first", "(", ")", ";", "// wi...
merge multiple <head> or <body> contents into one, delete the remainder, and ensure they are owned by <html>
[ "merge", "multiple", "<head", ">", "or", "<body", ">", "contents", "into", "one", "delete", "the", "remainder", "and", "ensure", "they", "are", "owned", "by", "<html", ">" ]
train
https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Document.java#L161-L179
watchrabbit/rabbit-commons
src/main/java/com/watchrabbit/commons/sleep/Sleep.java
Sleep.untilNull
public static <T> T untilNull(Callable<T> callable, long timeout, TimeUnit unit) { return SleepBuilder.<T>sleep() .withComparer(argument -> argument == null) .withTimeout(timeout, unit) .withStatement(callable) .build(); }
java
public static <T> T untilNull(Callable<T> callable, long timeout, TimeUnit unit) { return SleepBuilder.<T>sleep() .withComparer(argument -> argument == null) .withTimeout(timeout, unit) .withStatement(callable) .build(); }
[ "public", "static", "<", "T", ">", "T", "untilNull", "(", "Callable", "<", "T", ">", "callable", ",", "long", "timeout", ",", "TimeUnit", "unit", ")", "{", "return", "SleepBuilder", ".", "<", "T", ">", "sleep", "(", ")", ".", "withComparer", "(", "ar...
Causes the current thread to wait until the callable is returning {@code null}, or the specified waiting time elapses. <p> If the callable returns not null then this method returns immediately with the value returned by callable. <p> Any {@code InterruptedException}'s are suppress and logged. Any {@code Exception}'s thrown by callable are propagate as SystemException @param callable callable checked by this method @param timeout the maximum time to wait @param unit the time unit of the {@code timeout} argument @return value returned by callable method @throws SystemException if callable throws exception
[ "Causes", "the", "current", "thread", "to", "wait", "until", "the", "callable", "is", "returning", "{", "@code", "null", "}", "or", "the", "specified", "waiting", "time", "elapses", "." ]
train
https://github.com/watchrabbit/rabbit-commons/blob/b11c9f804b5ab70b9264635c34a02f5029bd2a5d/src/main/java/com/watchrabbit/commons/sleep/Sleep.java#L117-L123
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/HandlablesImpl.java
HandlablesImpl.addType
private void addType(Class<?> type, Object object) { if (!items.containsKey(type)) { items.put(type, new HashSet<>()); } items.get(type).add(object); }
java
private void addType(Class<?> type, Object object) { if (!items.containsKey(type)) { items.put(type, new HashSet<>()); } items.get(type).add(object); }
[ "private", "void", "addType", "(", "Class", "<", "?", ">", "type", ",", "Object", "object", ")", "{", "if", "(", "!", "items", ".", "containsKey", "(", "type", ")", ")", "{", "items", ".", "put", "(", "type", ",", "new", "HashSet", "<>", "(", ")"...
Add a type from its interface. @param type The type interface. @param object The type value.
[ "Add", "a", "type", "from", "its", "interface", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/HandlablesImpl.java#L124-L131
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringParser.java
StringParser.parseBigDecimal
@Nullable public static BigDecimal parseBigDecimal (@Nullable final String sStr, @Nullable final BigDecimal aDefault) { if (sStr != null && sStr.length () > 0) try { return new BigDecimal (_getUnifiedDecimal (sStr)); } catch (final NumberFormatException ex) { // Fall through } return aDefault; }
java
@Nullable public static BigDecimal parseBigDecimal (@Nullable final String sStr, @Nullable final BigDecimal aDefault) { if (sStr != null && sStr.length () > 0) try { return new BigDecimal (_getUnifiedDecimal (sStr)); } catch (final NumberFormatException ex) { // Fall through } return aDefault; }
[ "@", "Nullable", "public", "static", "BigDecimal", "parseBigDecimal", "(", "@", "Nullable", "final", "String", "sStr", ",", "@", "Nullable", "final", "BigDecimal", "aDefault", ")", "{", "if", "(", "sStr", "!=", "null", "&&", "sStr", ".", "length", "(", ")"...
Parse the given {@link String} as {@link BigDecimal}. @param sStr The String to parse. May be <code>null</code>. @param aDefault The default value to be returned if the passed string could not be converted to a valid value. May be <code>null</code>. @return <code>aDefault</code> if the string does not represent a valid value.
[ "Parse", "the", "given", "{", "@link", "String", "}", "as", "{", "@link", "BigDecimal", "}", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L1481-L1494
stagemonitor/stagemonitor
stagemonitor-tracing/src/main/java/org/stagemonitor/tracing/soap/SoapHandlerTransformer.java
SoapHandlerTransformer.addHandlers
@Advice.OnMethodEnter private static void addHandlers(@Advice.Argument(value = 0, readOnly = false) List<Handler> handlerChain, @Advice.This Binding binding) { final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("org.stagemonitor.tracing.soap.SoapHandlerTransformer"); final List<Handler<?>> stagemonitorHandlers = Dispatcher.get("org.stagemonitor.tracing.soap.SoapHandlerTransformer"); if (stagemonitorHandlers != null) { logger.fine("Adding SOAPHandlers " + stagemonitorHandlers + " to handlerChain for Binding " + binding); if (handlerChain == null) { handlerChain = Collections.emptyList(); } // creating a new list as we don't know if handlerChain is immutable or not handlerChain = new ArrayList<Handler>(handlerChain); for (Handler<?> stagemonitorHandler : stagemonitorHandlers) { if (!handlerChain.contains(stagemonitorHandler) && // makes sure we only add the handler to the correct application Dispatcher.isVisibleToCurrentContextClassLoader(stagemonitorHandler)) { handlerChain.add(stagemonitorHandler); } } logger.fine("Handler Chain: " + handlerChain); } else { logger.fine("No SOAPHandlers found in Dispatcher for Binding " + binding); } }
java
@Advice.OnMethodEnter private static void addHandlers(@Advice.Argument(value = 0, readOnly = false) List<Handler> handlerChain, @Advice.This Binding binding) { final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("org.stagemonitor.tracing.soap.SoapHandlerTransformer"); final List<Handler<?>> stagemonitorHandlers = Dispatcher.get("org.stagemonitor.tracing.soap.SoapHandlerTransformer"); if (stagemonitorHandlers != null) { logger.fine("Adding SOAPHandlers " + stagemonitorHandlers + " to handlerChain for Binding " + binding); if (handlerChain == null) { handlerChain = Collections.emptyList(); } // creating a new list as we don't know if handlerChain is immutable or not handlerChain = new ArrayList<Handler>(handlerChain); for (Handler<?> stagemonitorHandler : stagemonitorHandlers) { if (!handlerChain.contains(stagemonitorHandler) && // makes sure we only add the handler to the correct application Dispatcher.isVisibleToCurrentContextClassLoader(stagemonitorHandler)) { handlerChain.add(stagemonitorHandler); } } logger.fine("Handler Chain: " + handlerChain); } else { logger.fine("No SOAPHandlers found in Dispatcher for Binding " + binding); } }
[ "@", "Advice", ".", "OnMethodEnter", "private", "static", "void", "addHandlers", "(", "@", "Advice", ".", "Argument", "(", "value", "=", "0", ",", "readOnly", "=", "false", ")", "List", "<", "Handler", ">", "handlerChain", ",", "@", "Advice", ".", "This"...
This code might be executed in the context of the bootstrap class loader. That's why we have to make sure we only call code which is visible. For example, we can't use slf4j or directly reference stagemonitor classes
[ "This", "code", "might", "be", "executed", "in", "the", "context", "of", "the", "bootstrap", "class", "loader", ".", "That", "s", "why", "we", "have", "to", "make", "sure", "we", "only", "call", "code", "which", "is", "visible", ".", "For", "example", ...
train
https://github.com/stagemonitor/stagemonitor/blob/7a1bf6848906f816aa465983f602ea1f1e8f2b7b/stagemonitor-tracing/src/main/java/org/stagemonitor/tracing/soap/SoapHandlerTransformer.java#L85-L108
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/ConsumerDispatcherState.java
ConsumerDispatcherState.setUser
public void setUser(String user, boolean isSIBServerSubject) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setUser", user); this.user = user; this.isSIBServerSubject = isSIBServerSubject; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setUser"); }
java
public void setUser(String user, boolean isSIBServerSubject) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setUser", user); this.user = user; this.isSIBServerSubject = isSIBServerSubject; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setUser"); }
[ "public", "void", "setUser", "(", "String", "user", ",", "boolean", "isSIBServerSubject", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "this", ","...
Sets the user. @param user The user to set @param isSIBServerSubject
[ "Sets", "the", "user", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/ConsumerDispatcherState.java#L427-L436
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java
WonderPushJobQueue.postJobWithDescription
protected Job postJobWithDescription(JSONObject jobDescription, long notBeforeRealtimeElapsed) { String jobId = UUID.randomUUID().toString(); InternalJob job = new InternalJob(jobId, jobDescription, notBeforeRealtimeElapsed); return post(job); }
java
protected Job postJobWithDescription(JSONObject jobDescription, long notBeforeRealtimeElapsed) { String jobId = UUID.randomUUID().toString(); InternalJob job = new InternalJob(jobId, jobDescription, notBeforeRealtimeElapsed); return post(job); }
[ "protected", "Job", "postJobWithDescription", "(", "JSONObject", "jobDescription", ",", "long", "notBeforeRealtimeElapsed", ")", "{", "String", "jobId", "=", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ";", "InternalJob", "job", "=", "new", ...
Creates and stores a job in the queue based on the provided description @return The stored job or null if something went wrong (the queue is full for instance)
[ "Creates", "and", "stores", "a", "job", "in", "the", "queue", "based", "on", "the", "provided", "description" ]
train
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/WonderPushJobQueue.java#L80-L84
beangle/beangle3
commons/core/src/main/java/org/beangle/commons/text/inflector/RuleBasedPluralizer.java
RuleBasedPluralizer.pluralize
public String pluralize(String word, int number) { if (number == 1) { return word; } Matcher matcher = pattern.matcher(word); if (matcher.matches()) { String pre = matcher.group(1); String trimmedWord = matcher.group(2); String post = matcher.group(3); String plural = pluralizeInternal(trimmedWord); if (plural == null) { return fallbackPluralizer.pluralize(word, number); } return pre + postProcess(trimmedWord, plural) + post; } return word; }
java
public String pluralize(String word, int number) { if (number == 1) { return word; } Matcher matcher = pattern.matcher(word); if (matcher.matches()) { String pre = matcher.group(1); String trimmedWord = matcher.group(2); String post = matcher.group(3); String plural = pluralizeInternal(trimmedWord); if (plural == null) { return fallbackPluralizer.pluralize(word, number); } return pre + postProcess(trimmedWord, plural) + post; } return word; }
[ "public", "String", "pluralize", "(", "String", "word", ",", "int", "number", ")", "{", "if", "(", "number", "==", "1", ")", "{", "return", "word", ";", "}", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "word", ")", ";", "if", "(", "m...
{@inheritDoc} <p> Converts a noun or pronoun to its plural form for the given number of instances. If <code>number</code> is 1, <code>word</code> is returned unchanged. </p> <p> The return value is not defined if this method is passed a plural form. </p>
[ "{" ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/text/inflector/RuleBasedPluralizer.java#L193-L205
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/internal/RandomAccessListIterate.java
RandomAccessListIterate.detectIndexWith
public static <T, IV> int detectIndexWith(List<T> list, Predicate2<? super T, ? super IV> predicate, IV injectedValue) { int size = list.size(); for (int i = 0; i < size; i++) { if (predicate.accept(list.get(i), injectedValue)) { return i; } } return -1; }
java
public static <T, IV> int detectIndexWith(List<T> list, Predicate2<? super T, ? super IV> predicate, IV injectedValue) { int size = list.size(); for (int i = 0; i < size; i++) { if (predicate.accept(list.get(i), injectedValue)) { return i; } } return -1; }
[ "public", "static", "<", "T", ",", "IV", ">", "int", "detectIndexWith", "(", "List", "<", "T", ">", "list", ",", "Predicate2", "<", "?", "super", "T", ",", "?", "super", "IV", ">", "predicate", ",", "IV", "injectedValue", ")", "{", "int", "size", "...
Searches for the first occurrence where the predicate evaluates to true. @see Iterate#detectIndexWith(Iterable, Predicate2, Object)
[ "Searches", "for", "the", "first", "occurrence", "where", "the", "predicate", "evaluates", "to", "true", "." ]
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/internal/RandomAccessListIterate.java#L1148-L1159
mqlight/java-mqlight
mqlight/src/main/java/com/ibm/mqlight/api/impl/logging/logback/LogbackLoggingImpl.java
LogbackLoggingImpl.createPatternLayoutEncoder
private static PatternLayoutEncoder createPatternLayoutEncoder(LoggerContext context, String patternProperty) { final String pattern = context.getProperty(patternProperty); final PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder(); patternLayoutEncoder.setContext(context); patternLayoutEncoder.setPattern(pattern); patternLayoutEncoder.start(); return patternLayoutEncoder; }
java
private static PatternLayoutEncoder createPatternLayoutEncoder(LoggerContext context, String patternProperty) { final String pattern = context.getProperty(patternProperty); final PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder(); patternLayoutEncoder.setContext(context); patternLayoutEncoder.setPattern(pattern); patternLayoutEncoder.start(); return patternLayoutEncoder; }
[ "private", "static", "PatternLayoutEncoder", "createPatternLayoutEncoder", "(", "LoggerContext", "context", ",", "String", "patternProperty", ")", "{", "final", "String", "pattern", "=", "context", ".", "getProperty", "(", "patternProperty", ")", ";", "final", "Patter...
Creates a {@link PatternLayoutEncoder} for the pattern specified for the pattern property. @param context Logger context to associate the pattern layout encoder with. @param patternProperty Logger context property that contains the required pattern. @return A {@link PatternLayoutEncoder} for the required pattern.
[ "Creates", "a", "{", "@link", "PatternLayoutEncoder", "}", "for", "the", "pattern", "specified", "for", "the", "pattern", "property", "." ]
train
https://github.com/mqlight/java-mqlight/blob/a565dfa6044050826d1221697da9e3268b557aeb/mqlight/src/main/java/com/ibm/mqlight/api/impl/logging/logback/LogbackLoggingImpl.java#L238-L245
xiancloud/xian
xian-log/xian-gelf-common/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java
ConfigurationSupport.setAdditionalFields
public static void setAdditionalFields(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 == index) { continue; } gelfMessageAssembler.addField(new StaticMessageField(field.substring(0, index), field.substring(index + 1))); } } }
java
public static void setAdditionalFields(String spec, GelfMessageAssembler gelfMessageAssembler) { if (null != spec) { String[] properties = spec.split(MULTI_VALUE_DELIMITTER); for (String field : properties) { final int index = field.indexOf(EQ); if (-1 == index) { continue; } gelfMessageAssembler.addField(new StaticMessageField(field.substring(0, index), field.substring(index + 1))); } } }
[ "public", "static", "void", "setAdditionalFields", "(", "String", "spec", ",", "GelfMessageAssembler", "gelfMessageAssembler", ")", "{", "if", "(", "null", "!=", "spec", ")", "{", "String", "[", "]", "properties", "=", "spec", ".", "split", "(", "MULTI_VALUE_D...
Set the additional (static) fields. @param spec field=value,field1=value1, ... @param gelfMessageAssembler the Gelf message assembler to apply the configuration
[ "Set", "the", "additional", "(", "static", ")", "fields", "." ]
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-log/xian-gelf-common/src/main/java/biz/paluch/logging/gelf/intern/ConfigurationSupport.java#L25-L37
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/SegmentKeyCache.java
SegmentKeyCache.includeUpdateBatch
List<Long> includeUpdateBatch(TableKeyBatch batch, long batchOffset, int generation) { val result = new ArrayList<Long>(batch.getItems().size()); synchronized (this) { for (TableKeyBatch.Item item : batch.getItems()) { long itemOffset = batchOffset + item.getOffset(); CacheBucketOffset existingOffset = get(item.getHash(), generation); if (existingOffset == null || itemOffset > existingOffset.getSegmentOffset()) { // We have no previous entry, or we do and the current offset is higher, so it prevails. this.tailOffsets.put(item.getHash(), new CacheBucketOffset(itemOffset, batch.isRemoval())); result.add(itemOffset); } else { // Current offset is lower. result.add(existingOffset.getSegmentOffset()); } if (existingOffset != null) { // Only record a backpointer if we have a previous location to point to. this.backpointers.put(itemOffset, existingOffset.getSegmentOffset()); } } } return result; }
java
List<Long> includeUpdateBatch(TableKeyBatch batch, long batchOffset, int generation) { val result = new ArrayList<Long>(batch.getItems().size()); synchronized (this) { for (TableKeyBatch.Item item : batch.getItems()) { long itemOffset = batchOffset + item.getOffset(); CacheBucketOffset existingOffset = get(item.getHash(), generation); if (existingOffset == null || itemOffset > existingOffset.getSegmentOffset()) { // We have no previous entry, or we do and the current offset is higher, so it prevails. this.tailOffsets.put(item.getHash(), new CacheBucketOffset(itemOffset, batch.isRemoval())); result.add(itemOffset); } else { // Current offset is lower. result.add(existingOffset.getSegmentOffset()); } if (existingOffset != null) { // Only record a backpointer if we have a previous location to point to. this.backpointers.put(itemOffset, existingOffset.getSegmentOffset()); } } } return result; }
[ "List", "<", "Long", ">", "includeUpdateBatch", "(", "TableKeyBatch", "batch", ",", "long", "batchOffset", ",", "int", "generation", ")", "{", "val", "result", "=", "new", "ArrayList", "<", "Long", ">", "(", "batch", ".", "getItems", "(", ")", ".", "size...
Updates the tail cache for with the contents of the given {@link TableKeyBatch}. Each {@link TableKeyBatch.Item} is updated only if no previous entry exists with its {@link TableKeyBatch.Item#getHash()} or if its {@link TableKeyBatch.Item#getOffset()} is greater than the existing entry's offset. This method should be used for processing new updates to the Index (as opposed from bulk-loading already indexed keys). @param batch An {@link TableKeyBatch} containing items to accept into the Cache. @param batchOffset Offset in the Segment where the first item in the {@link TableKeyBatch} has been written to. @param generation The current Cache Generation (from the Cache Manager). @return A List of offsets for each item in the {@link TableKeyBatch} (in the same order) of where the latest value for that item's Key exists now.
[ "Updates", "the", "tail", "cache", "for", "with", "the", "contents", "of", "the", "given", "{", "@link", "TableKeyBatch", "}", ".", "Each", "{", "@link", "TableKeyBatch", ".", "Item", "}", "is", "updated", "only", "if", "no", "previous", "entry", "exists",...
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/SegmentKeyCache.java#L148-L171
lestard/advanced-bindings
src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java
MathBindings.nextAfter
public static DoubleBinding nextAfter(final ObservableDoubleValue start, final ObservableDoubleValue direction) { return createDoubleBinding(() -> Math.nextAfter(start.get(), direction.get()), start, direction); }
java
public static DoubleBinding nextAfter(final ObservableDoubleValue start, final ObservableDoubleValue direction) { return createDoubleBinding(() -> Math.nextAfter(start.get(), direction.get()), start, direction); }
[ "public", "static", "DoubleBinding", "nextAfter", "(", "final", "ObservableDoubleValue", "start", ",", "final", "ObservableDoubleValue", "direction", ")", "{", "return", "createDoubleBinding", "(", "(", ")", "->", "Math", ".", "nextAfter", "(", "start", ".", "get"...
Binding for {@link java.lang.Math#nextAfter(double, double)} @param start starting floating-point value @param direction value indicating which of {@code start}'s neighbors or {@code start} should be returned @return The floating-point number adjacent to {@code start} in the direction of {@code direction}.
[ "Binding", "for", "{", "@link", "java", ".", "lang", ".", "Math#nextAfter", "(", "double", "double", ")", "}" ]
train
https://github.com/lestard/advanced-bindings/blob/054a5dde261c29f862b971765fa3da3704a13ab4/src/main/java/eu/lestard/advanced_bindings/api/MathBindings.java#L1084-L1086
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/ColumnText.java
ColumnText.setSimpleColumn
public void setSimpleColumn(Phrase phrase, float llx, float lly, float urx, float ury, float leading, int alignment) { addText(phrase); setSimpleColumn(llx, lly, urx, ury, leading, alignment); }
java
public void setSimpleColumn(Phrase phrase, float llx, float lly, float urx, float ury, float leading, int alignment) { addText(phrase); setSimpleColumn(llx, lly, urx, ury, leading, alignment); }
[ "public", "void", "setSimpleColumn", "(", "Phrase", "phrase", ",", "float", "llx", ",", "float", "lly", ",", "float", "urx", ",", "float", "ury", ",", "float", "leading", ",", "int", "alignment", ")", "{", "addText", "(", "phrase", ")", ";", "setSimpleCo...
Simplified method for rectangular columns. @param phrase a <CODE>Phrase</CODE> @param llx the lower left x corner @param lly the lower left y corner @param urx the upper right x corner @param ury the upper right y corner @param leading the leading @param alignment the column alignment
[ "Simplified", "method", "for", "rectangular", "columns", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/ColumnText.java#L609-L612
Esri/geometry-api-java
src/main/java/com/esri/core/geometry/Transformation2D.java
Transformation2D.setFlipX
public void setFlipX(double x0, double x1) { xx = -1; xy = 0; xd = x0 + x1; yx = 0; yy = 1; yd = 0; }
java
public void setFlipX(double x0, double x1) { xx = -1; xy = 0; xd = x0 + x1; yx = 0; yy = 1; yd = 0; }
[ "public", "void", "setFlipX", "(", "double", "x0", ",", "double", "x1", ")", "{", "xx", "=", "-", "1", ";", "xy", "=", "0", ";", "xd", "=", "x0", "+", "x1", ";", "yx", "=", "0", ";", "yy", "=", "1", ";", "yd", "=", "0", ";", "}" ]
Sets the transformation to be a flip around the X axis. Flips the X coordinates so that the x0 becomes x1 and vice verse. @param x0 The X coordinate to flip. @param x1 The X coordinate to flip to.
[ "Sets", "the", "transformation", "to", "be", "a", "flip", "around", "the", "X", "axis", ".", "Flips", "the", "X", "coordinates", "so", "that", "the", "x0", "becomes", "x1", "and", "vice", "verse", "." ]
train
https://github.com/Esri/geometry-api-java/blob/494da8ec953d76e7c6072afbc081abfe48ff07cf/src/main/java/com/esri/core/geometry/Transformation2D.java#L623-L630
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/DateField.java
DateField.setupDefaultView
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { converter = new DateConverter((Converter)converter, DBConstants.DATE_FORMAT); return super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties); }
java
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { converter = new DateConverter((Converter)converter, DBConstants.DATE_FORMAT); return super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties); }
[ "public", "ScreenComponent", "setupDefaultView", "(", "ScreenLoc", "itsLocation", ",", "ComponentParent", "targetScreen", ",", "Convert", "converter", ",", "int", "iDisplayFieldDesc", ",", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "converter"...
Set up the default screen control for this field (Default using a DateConverter). @param itsLocation Location of this component on screen (ie., GridBagConstraint). @param targetScreen Where to place this component (ie., Parent screen or GridBagLayout). @param converter The converter to set the screenfield to. @param iDisplayFieldDesc Display the label? (optional). @return Return the component or ScreenField that is created for this field. For a Date field, use DateConverter.
[ "Set", "up", "the", "default", "screen", "control", "for", "this", "field", "(", "Default", "using", "a", "DateConverter", ")", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/DateField.java#L103-L107
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java
JQLChecker.extractPlaceHoldersAsList
public List<JQLPlaceHolder> extractPlaceHoldersAsList(final JQLContext jqlContext, String jql) { return extractPlaceHolders(jqlContext, jql, new ArrayList<JQLPlaceHolder>()); }
java
public List<JQLPlaceHolder> extractPlaceHoldersAsList(final JQLContext jqlContext, String jql) { return extractPlaceHolders(jqlContext, jql, new ArrayList<JQLPlaceHolder>()); }
[ "public", "List", "<", "JQLPlaceHolder", ">", "extractPlaceHoldersAsList", "(", "final", "JQLContext", "jqlContext", ",", "String", "jql", ")", "{", "return", "extractPlaceHolders", "(", "jqlContext", ",", "jql", ",", "new", "ArrayList", "<", "JQLPlaceHolder", ">"...
Extract all bind parameters and dynamic part used in query. @param jqlContext the jql context @param jql the jql @return the list
[ "Extract", "all", "bind", "parameters", "and", "dynamic", "part", "used", "in", "query", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLChecker.java#L820-L822
kite-sdk/kite
kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Marker.java
Marker.valueFor
@Nullable public <S, T> T valueFor(FieldPartitioner<S, T> fp) { if (has(fp.getName())) { return getAs(fp.getName(), fp.getType()); } else if (has(fp.getSourceName())) { return fp.apply(getAs(fp.getSourceName(), fp.getSourceType())); } else { return null; } }
java
@Nullable public <S, T> T valueFor(FieldPartitioner<S, T> fp) { if (has(fp.getName())) { return getAs(fp.getName(), fp.getType()); } else if (has(fp.getSourceName())) { return fp.apply(getAs(fp.getSourceName(), fp.getSourceType())); } else { return null; } }
[ "@", "Nullable", "public", "<", "S", ",", "T", ">", "T", "valueFor", "(", "FieldPartitioner", "<", "S", ",", "T", ">", "fp", ")", "{", "if", "(", "has", "(", "fp", ".", "getName", "(", ")", ")", ")", "{", "return", "getAs", "(", "fp", ".", "g...
Return the value of a {@code FieldPartitioner} field for this {@link Marker}. If the {@code Marker} has a value for the field's name, that value is returned using {@link Marker#getAs(java.lang.String, java.lang.Class)}. If the {@code Marker} only has a value for the the source field name, then that value is retrieved using {@link org.kitesdk.data.spi.Marker#getAs(java.lang.String, java.lang.Class)} and the field's transformation is applied to it as the source value. @param fp a {@code FieldPartitioner} @return the value of the field for this {@code marker}, or null @since 0.9.0
[ "Return", "the", "value", "of", "a", "{", "@code", "FieldPartitioner", "}", "field", "for", "this", "{", "@link", "Marker", "}", "." ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Marker.java#L111-L120
jbossas/jboss-vfs
src/main/java/org/jboss/vfs/VFS.java
VFS.mountZipExpanded
public static Closeable mountZipExpanded(File zipFile, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException { boolean ok = false; final TempDir tempDir = tempFileProvider.createTempDir(zipFile.getName()); try { final File rootFile = tempDir.getRoot(); VFSUtils.unzip(zipFile, rootFile); final MountHandle handle = doMount(new RealFileSystem(rootFile), mountPoint, tempDir); ok = true; return handle; } finally { if (!ok) { VFSUtils.safeClose(tempDir); } } }
java
public static Closeable mountZipExpanded(File zipFile, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException { boolean ok = false; final TempDir tempDir = tempFileProvider.createTempDir(zipFile.getName()); try { final File rootFile = tempDir.getRoot(); VFSUtils.unzip(zipFile, rootFile); final MountHandle handle = doMount(new RealFileSystem(rootFile), mountPoint, tempDir); ok = true; return handle; } finally { if (!ok) { VFSUtils.safeClose(tempDir); } } }
[ "public", "static", "Closeable", "mountZipExpanded", "(", "File", "zipFile", ",", "VirtualFile", "mountPoint", ",", "TempFileProvider", "tempFileProvider", ")", "throws", "IOException", "{", "boolean", "ok", "=", "false", ";", "final", "TempDir", "tempDir", "=", "...
Create and mount an expanded zip file in a temporary file system, returning a single handle which will unmount and close the filesystem when closed. @param zipFile the zip file to mount @param mountPoint the point at which the filesystem should be mounted @param tempFileProvider the temporary file provider @return a handle @throws IOException if an error occurs
[ "Create", "and", "mount", "an", "expanded", "zip", "file", "in", "a", "temporary", "file", "system", "returning", "a", "single", "handle", "which", "will", "unmount", "and", "close", "the", "filesystem", "when", "closed", "." ]
train
https://github.com/jbossas/jboss-vfs/blob/420f4b896d6178ee5f6758f3421e9f350d2b8ab5/src/main/java/org/jboss/vfs/VFS.java#L417-L431
alkacon/opencms-core
src/org/opencms/xml/containerpage/CmsADESessionCache.java
CmsADESessionCache.addRecentFormatter
public void addRecentFormatter(String resType, CmsUUID formatterId) { List<CmsUUID> formatterIds = m_recentFormatters.get(resType); if (formatterIds == null) { formatterIds = new ArrayList<CmsUUID>(); m_recentFormatters.put(resType, formatterIds); } formatterIds.remove(formatterId); if (formatterIds.size() >= (RECENT_FORMATTERS_SIZE)) { formatterIds.remove(RECENT_FORMATTERS_SIZE - 1); } formatterIds.add(0, formatterId); }
java
public void addRecentFormatter(String resType, CmsUUID formatterId) { List<CmsUUID> formatterIds = m_recentFormatters.get(resType); if (formatterIds == null) { formatterIds = new ArrayList<CmsUUID>(); m_recentFormatters.put(resType, formatterIds); } formatterIds.remove(formatterId); if (formatterIds.size() >= (RECENT_FORMATTERS_SIZE)) { formatterIds.remove(RECENT_FORMATTERS_SIZE - 1); } formatterIds.add(0, formatterId); }
[ "public", "void", "addRecentFormatter", "(", "String", "resType", ",", "CmsUUID", "formatterId", ")", "{", "List", "<", "CmsUUID", ">", "formatterIds", "=", "m_recentFormatters", ".", "get", "(", "resType", ")", ";", "if", "(", "formatterIds", "==", "null", ...
Adds the formatter id to the recently used list for the given type.<p> @param resType the resource type @param formatterId the formatter id
[ "Adds", "the", "formatter", "id", "to", "the", "recently", "used", "list", "for", "the", "given", "type", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsADESessionCache.java#L229-L241
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java
DateFormatUtils.formatUTC
public static String formatUTC(final Date date, final String pattern) { return format(date, pattern, UTC_TIME_ZONE, null); }
java
public static String formatUTC(final Date date, final String pattern) { return format(date, pattern, UTC_TIME_ZONE, null); }
[ "public", "static", "String", "formatUTC", "(", "final", "Date", "date", ",", "final", "String", "pattern", ")", "{", "return", "format", "(", "date", ",", "pattern", ",", "UTC_TIME_ZONE", ",", "null", ")", ";", "}" ]
<p>Formats a date/time into a specific pattern using the UTC time zone.</p> @param date the date to format, not null @param pattern the pattern to use to format the date, not null @return the formatted date
[ "<p", ">", "Formats", "a", "date", "/", "time", "into", "a", "specific", "pattern", "using", "the", "UTC", "time", "zone", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java#L228-L230
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/V1InstanceGetter.java
V1InstanceGetter.buildProjects
public Collection<BuildProject> buildProjects(BuildProjectFilter filter) { return get(BuildProject.class, (filter != null) ? filter : new BuildProjectFilter()); }
java
public Collection<BuildProject> buildProjects(BuildProjectFilter filter) { return get(BuildProject.class, (filter != null) ? filter : new BuildProjectFilter()); }
[ "public", "Collection", "<", "BuildProject", ">", "buildProjects", "(", "BuildProjectFilter", "filter", ")", "{", "return", "get", "(", "BuildProject", ".", "class", ",", "(", "filter", "!=", "null", ")", "?", "filter", ":", "new", "BuildProjectFilter", "(", ...
Get Build Projects filtered by the criteria specified in the passed in filter. @param filter Limit the items returned. If null, then all items returned. @return Collection of items as specified in the filter.
[ "Get", "Build", "Projects", "filtered", "by", "the", "criteria", "specified", "in", "the", "passed", "in", "filter", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/V1InstanceGetter.java#L305-L307
alkacon/opencms-core
src/org/opencms/ui/apps/cacheadmin/CmsFlexCacheTable.java
CmsFlexCacheTable.showVariationsWindow
void showVariationsWindow(String resource) { final Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); CmsVariationsDialog variationsDialog = new CmsVariationsDialog(resource, new Runnable() { public void run() { window.close(); } }, Mode.FlexCache); try { CmsResource resourceObject = getRootCms().readResource(CmsFlexCacheKey.getResourceName(resource)); variationsDialog.displayResourceInfo(Collections.singletonList(resourceObject)); } catch (CmsException e) { // } window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_CACHE_VIEW_FLEX_VARIATIONS_1, resource)); window.setContent(variationsDialog); UI.getCurrent().addWindow(window); }
java
void showVariationsWindow(String resource) { final Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); CmsVariationsDialog variationsDialog = new CmsVariationsDialog(resource, new Runnable() { public void run() { window.close(); } }, Mode.FlexCache); try { CmsResource resourceObject = getRootCms().readResource(CmsFlexCacheKey.getResourceName(resource)); variationsDialog.displayResourceInfo(Collections.singletonList(resourceObject)); } catch (CmsException e) { // } window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_CACHE_VIEW_FLEX_VARIATIONS_1, resource)); window.setContent(variationsDialog); UI.getCurrent().addWindow(window); }
[ "void", "showVariationsWindow", "(", "String", "resource", ")", "{", "final", "Window", "window", "=", "CmsBasicDialog", ".", "prepareWindow", "(", "DialogWidth", ".", "max", ")", ";", "CmsVariationsDialog", "variationsDialog", "=", "new", "CmsVariationsDialog", "("...
Shows dialog for variations of given resource.<p> @param resource to show variations for
[ "Shows", "dialog", "for", "variations", "of", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/cacheadmin/CmsFlexCacheTable.java#L282-L303
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/xml/XMLUtils.java
XMLUtils.getNodeList
private NodeList getNodeList(final String xmlString, final String tagName) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlString)); Document doc = db.parse(is); LOG.info("Getting tagName: " + tagName); NodeList nodes = doc.getElementsByTagName(tagName); return nodes; }
java
private NodeList getNodeList(final String xmlString, final String tagName) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlString)); Document doc = db.parse(is); LOG.info("Getting tagName: " + tagName); NodeList nodes = doc.getElementsByTagName(tagName); return nodes; }
[ "private", "NodeList", "getNodeList", "(", "final", "String", "xmlString", ",", "final", "String", "tagName", ")", "throws", "ParserConfigurationException", ",", "SAXException", ",", "IOException", "{", "DocumentBuilderFactory", "dbf", "=", "DocumentBuilderFactory", "."...
Gets the nodes list for a given tag name. @param xmlString the XML String @param tagName the tag name to be searched @return the Node List for the given tag name @throws ParserConfigurationException if something goes wrong while parsing the XML @throws SAXException if XML is malformed @throws IOException if something goes wrong when reading the file
[ "Gets", "the", "nodes", "list", "for", "a", "given", "tag", "name", "." ]
train
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/xml/XMLUtils.java#L228-L249
Azure/azure-sdk-for-java
containerregistry/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_10_01/implementation/RegistriesInner.java
RegistriesInner.importImage
public void importImage(String resourceGroupName, String registryName, ImportImageParameters parameters) { importImageWithServiceResponseAsync(resourceGroupName, registryName, parameters).toBlocking().last().body(); }
java
public void importImage(String resourceGroupName, String registryName, ImportImageParameters parameters) { importImageWithServiceResponseAsync(resourceGroupName, registryName, parameters).toBlocking().last().body(); }
[ "public", "void", "importImage", "(", "String", "resourceGroupName", ",", "String", "registryName", ",", "ImportImageParameters", "parameters", ")", "{", "importImageWithServiceResponseAsync", "(", "resourceGroupName", ",", "registryName", ",", "parameters", ")", ".", "...
Copies an image to this container registry from the specified container registry. @param resourceGroupName The name of the resource group to which the container registry belongs. @param registryName The name of the container registry. @param parameters The parameters specifying the image to copy and the source container registry. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
[ "Copies", "an", "image", "to", "this", "container", "registry", "from", "the", "specified", "container", "registry", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/containerregistry/v2017_10_01/implementation/RegistriesInner.java#L166-L168
shrinkwrap/resolver
maven/impl-maven-archive/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/archive/plugins/ConfigurationUtils.java
ConfigurationUtils.valueAsString
static String valueAsString(Map<String, Object> map, Key key, String defaultValue) { Validate.notNullOrEmpty(key.key, "Key for plugin configuration must be set"); if (map.containsKey(key.key)) { return map.get(key.key).toString().length() == 0 ? defaultValue : map.get(key.key).toString(); } return defaultValue; }
java
static String valueAsString(Map<String, Object> map, Key key, String defaultValue) { Validate.notNullOrEmpty(key.key, "Key for plugin configuration must be set"); if (map.containsKey(key.key)) { return map.get(key.key).toString().length() == 0 ? defaultValue : map.get(key.key).toString(); } return defaultValue; }
[ "static", "String", "valueAsString", "(", "Map", "<", "String", ",", "Object", ">", "map", ",", "Key", "key", ",", "String", "defaultValue", ")", "{", "Validate", ".", "notNullOrEmpty", "(", "key", ".", "key", ",", "\"Key for plugin configuration must be set\"",...
Fetches a value specified by key @param map XPP3 map equivalent @param key navigation key @param defaultValue Default value if no such key exists @return String representation of the value
[ "Fetches", "a", "value", "specified", "by", "key" ]
train
https://github.com/shrinkwrap/resolver/blob/e881a84b8cff5b0a014f2a5ebf612be3eb9db01f/maven/impl-maven-archive/src/main/java/org/jboss/shrinkwrap/resolver/impl/maven/archive/plugins/ConfigurationUtils.java#L45-L51
m-m-m/util
value/src/main/java/net/sf/mmm/util/value/impl/ComposedValueConverterFactoryImpl.java
ComposedValueConverterFactoryImpl.setConverters
@Inject public void setConverters(List<ValueConverter<?, ?>> converterList) { getInitializationState().requireNotInitilized(); this.converters = new ArrayList<>(converterList.size()); for (ValueConverter<?, ?> converter : converterList) { if (!(converter instanceof ComposedValueConverter)) { this.converters.add(converter); } } }
java
@Inject public void setConverters(List<ValueConverter<?, ?>> converterList) { getInitializationState().requireNotInitilized(); this.converters = new ArrayList<>(converterList.size()); for (ValueConverter<?, ?> converter : converterList) { if (!(converter instanceof ComposedValueConverter)) { this.converters.add(converter); } } }
[ "@", "Inject", "public", "void", "setConverters", "(", "List", "<", "ValueConverter", "<", "?", ",", "?", ">", ">", "converterList", ")", "{", "getInitializationState", "(", ")", ".", "requireNotInitilized", "(", ")", ";", "this", ".", "converters", "=", "...
This method injects a {@link List} of {@link ValueConverter}s to use as default. @param converterList is the list of converters to register.
[ "This", "method", "injects", "a", "{", "@link", "List", "}", "of", "{", "@link", "ValueConverter", "}", "s", "to", "use", "as", "default", "." ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/value/src/main/java/net/sf/mmm/util/value/impl/ComposedValueConverterFactoryImpl.java#L81-L91
molgenis/molgenis
molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlExceptionTranslator.java
PostgreSqlExceptionTranslator.translateNotNullViolation
MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String tableName = serverErrorMessage.getTable(); String message = serverErrorMessage.getMessage(); Matcher matcher = Pattern.compile("null value in column \"?(.*?)\"? violates not-null constraint") .matcher(message); boolean matches = matcher.matches(); if (matches) { // exception message when adding data that does not match constraint String columnName = matcher.group(1); EntityTypeDescription entityTypeDescription = entityTypeRegistry.getEntityTypeDescription(tableName); entityTypeDescription.getAttributeDescriptionMap().get(columnName); ConstraintViolation constraintViolation = new ConstraintViolation( format( "The attribute '%s' of entity '%s' can not be null.", tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN), tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)), null); return new MolgenisValidationException(singleton(constraintViolation)); } else { // exception message when applying constraint on existing data matcher = Pattern.compile("column \"(.*?)\" contains null values").matcher(message); matches = matcher.matches(); if (!matches) { throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException); } String columnName = matcher.group(1); ConstraintViolation constraintViolation = new ConstraintViolation( format( "The attribute '%s' of entity '%s' contains null values.", tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN), tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)), null); return new MolgenisValidationException(singleton(constraintViolation)); } }
java
MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String tableName = serverErrorMessage.getTable(); String message = serverErrorMessage.getMessage(); Matcher matcher = Pattern.compile("null value in column \"?(.*?)\"? violates not-null constraint") .matcher(message); boolean matches = matcher.matches(); if (matches) { // exception message when adding data that does not match constraint String columnName = matcher.group(1); EntityTypeDescription entityTypeDescription = entityTypeRegistry.getEntityTypeDescription(tableName); entityTypeDescription.getAttributeDescriptionMap().get(columnName); ConstraintViolation constraintViolation = new ConstraintViolation( format( "The attribute '%s' of entity '%s' can not be null.", tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN), tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)), null); return new MolgenisValidationException(singleton(constraintViolation)); } else { // exception message when applying constraint on existing data matcher = Pattern.compile("column \"(.*?)\" contains null values").matcher(message); matches = matcher.matches(); if (!matches) { throw new RuntimeException(ERROR_TRANSLATING_EXCEPTION_MSG, pSqlException); } String columnName = matcher.group(1); ConstraintViolation constraintViolation = new ConstraintViolation( format( "The attribute '%s' of entity '%s' contains null values.", tryGetAttributeName(tableName, columnName).orElse(TOKEN_UNKNOWN), tryGetEntityTypeName(tableName).orElse(TOKEN_UNKNOWN)), null); return new MolgenisValidationException(singleton(constraintViolation)); } }
[ "MolgenisValidationException", "translateNotNullViolation", "(", "PSQLException", "pSqlException", ")", "{", "ServerErrorMessage", "serverErrorMessage", "=", "pSqlException", ".", "getServerErrorMessage", "(", ")", ";", "String", "tableName", "=", "serverErrorMessage", ".", ...
Package private for testability @param pSqlException PostgreSQL exception @return translated validation exception
[ "Package", "private", "for", "testability" ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlExceptionTranslator.java#L279-L321
infinispan/infinispan
client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCacheManager.java
RemoteCacheManager.getCache
@Override public <K, V> RemoteCache<K, V> getCache(String cacheName) { return getCache(cacheName, configuration.forceReturnValues(), null, null); }
java
@Override public <K, V> RemoteCache<K, V> getCache(String cacheName) { return getCache(cacheName, configuration.forceReturnValues(), null, null); }
[ "@", "Override", "public", "<", "K", ",", "V", ">", "RemoteCache", "<", "K", ",", "V", ">", "getCache", "(", "String", "cacheName", ")", "{", "return", "getCache", "(", "cacheName", ",", "configuration", ".", "forceReturnValues", "(", ")", ",", "null", ...
Retrieves a named cache from the remote server if the cache has been defined, otherwise if the cache name is undefined, it will return null. @param cacheName name of cache to retrieve @return a cache instance identified by cacheName or null if the cache name has not been defined
[ "Retrieves", "a", "named", "cache", "from", "the", "remote", "server", "if", "the", "cache", "has", "been", "defined", "otherwise", "if", "the", "cache", "name", "is", "undefined", "it", "will", "return", "null", "." ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/client/hotrod-client/src/main/java/org/infinispan/client/hotrod/RemoteCacheManager.java#L223-L226
3pillarlabs/spring-data-simpledb
spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SimpleDbQueryMethod.java
SimpleDbQueryMethod.getAnnotationValue
private <T> T getAnnotationValue(String attribute, Class<T> type) { Query annotation = method.getAnnotation(Query.class); Object value = annotation == null ? AnnotationUtils.getDefaultValue(Query.class, attribute) : AnnotationUtils .getValue(annotation, attribute); return type.cast(value); }
java
private <T> T getAnnotationValue(String attribute, Class<T> type) { Query annotation = method.getAnnotation(Query.class); Object value = annotation == null ? AnnotationUtils.getDefaultValue(Query.class, attribute) : AnnotationUtils .getValue(annotation, attribute); return type.cast(value); }
[ "private", "<", "T", ">", "T", "getAnnotationValue", "(", "String", "attribute", ",", "Class", "<", "T", ">", "type", ")", "{", "Query", "annotation", "=", "method", ".", "getAnnotation", "(", "Query", ".", "class", ")", ";", "Object", "value", "=", "a...
Returns the {@link Query} annotation's attribute casted to the given type or default value if no annotation available. @param attribute @param type @return
[ "Returns", "the", "{", "@link", "Query", "}", "annotation", "s", "attribute", "casted", "to", "the", "given", "type", "or", "default", "value", "if", "no", "annotation", "available", "." ]
train
https://github.com/3pillarlabs/spring-data-simpledb/blob/f1e0eb4e48ec4674d3966e8f5bc04c95031f93ae/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/query/SimpleDbQueryMethod.java#L108-L115
lucee/Lucee
core/src/main/java/lucee/runtime/tag/Lock.java
Lock.setType
public void setType(String type) throws ApplicationException { type = type.toLowerCase().trim(); if (type.equals("exclusive")) { this.type = LockManager.TYPE_EXCLUSIVE; } else if (type.startsWith("read")) { this.type = LockManager.TYPE_READONLY; } else throw new ApplicationException("invalid value [" + type + "] for attribute [type] from tag [lock]", "valid values are [exclusive,read-only]"); }
java
public void setType(String type) throws ApplicationException { type = type.toLowerCase().trim(); if (type.equals("exclusive")) { this.type = LockManager.TYPE_EXCLUSIVE; } else if (type.startsWith("read")) { this.type = LockManager.TYPE_READONLY; } else throw new ApplicationException("invalid value [" + type + "] for attribute [type] from tag [lock]", "valid values are [exclusive,read-only]"); }
[ "public", "void", "setType", "(", "String", "type", ")", "throws", "ApplicationException", "{", "type", "=", "type", ".", "toLowerCase", "(", ")", ".", "trim", "(", ")", ";", "if", "(", "type", ".", "equals", "(", "\"exclusive\"", ")", ")", "{", "this"...
set the value type readOnly or Exclusive. Specifies the type of lock: read-only or exclusive. Default is Exclusive. A read-only lock allows more than one request to read shared data. An exclusive lock allows only one request to read or write to shared data. @param type value to set @throws ApplicationException
[ "set", "the", "value", "type", "readOnly", "or", "Exclusive", ".", "Specifies", "the", "type", "of", "lock", ":", "read", "-", "only", "or", "exclusive", ".", "Default", "is", "Exclusive", ".", "A", "read", "-", "only", "lock", "allows", "more", "than", ...
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/tag/Lock.java#L149-L159
actorapp/actor-platform
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java
Messenger.sendMessageWithMentionsDetect
@ObjectiveCName("sendMessageWithMentionsDetect:withText:withMarkdownText:") public void sendMessageWithMentionsDetect(@NotNull Peer peer, @NotNull String text, @NotNull String markdownText) { sendMessage(peer, text, markdownText, null, true); }
java
@ObjectiveCName("sendMessageWithMentionsDetect:withText:withMarkdownText:") public void sendMessageWithMentionsDetect(@NotNull Peer peer, @NotNull String text, @NotNull String markdownText) { sendMessage(peer, text, markdownText, null, true); }
[ "@", "ObjectiveCName", "(", "\"sendMessageWithMentionsDetect:withText:withMarkdownText:\"", ")", "public", "void", "sendMessageWithMentionsDetect", "(", "@", "NotNull", "Peer", "peer", ",", "@", "NotNull", "String", "text", ",", "@", "NotNull", "String", "markdownText", ...
Send Text Message @param peer destination peer @param text message text
[ "Send", "Text", "Message" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/Messenger.java#L839-L842
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/persister/MapTilePersisterModel.java
MapTilePersisterModel.saveTile
protected void saveTile(FileWriting file, Tile tile) throws IOException { file.writeInteger(tile.getSheet().intValue()); file.writeInteger(tile.getNumber()); file.writeInteger(tile.getInTileX() % BLOC_SIZE); file.writeInteger(tile.getInTileY()); }
java
protected void saveTile(FileWriting file, Tile tile) throws IOException { file.writeInteger(tile.getSheet().intValue()); file.writeInteger(tile.getNumber()); file.writeInteger(tile.getInTileX() % BLOC_SIZE); file.writeInteger(tile.getInTileY()); }
[ "protected", "void", "saveTile", "(", "FileWriting", "file", ",", "Tile", "tile", ")", "throws", "IOException", "{", "file", ".", "writeInteger", "(", "tile", ".", "getSheet", "(", ")", ".", "intValue", "(", ")", ")", ";", "file", ".", "writeInteger", "(...
Save tile. Data are saved this way: <pre> (integer) sheet number (integer) index number inside sheet (integer) tile location x % MapTile.BLOC_SIZE (integer tile location y </pre> @param file The file writer reference. @param tile The tile to save. @throws IOException If error on writing.
[ "Save", "tile", ".", "Data", "are", "saved", "this", "way", ":" ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/persister/MapTilePersisterModel.java#L77-L83
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java
Director.fireProgressEvent
private void fireProgressEvent(int state, int progress, String messageKey, RepositoryResource installResource) throws InstallException { String resourceName = null; if (installResource instanceof EsaResource) { EsaResource esar = ((EsaResource) installResource); if (esar.getVisibility().equals(Visibility.PUBLIC) || esar.getVisibility().equals(Visibility.INSTALL)) { resourceName = (esar.getShortName() == null) ? installResource.getName() : esar.getShortName(); } else if (!firePublicAssetOnly && messageKey.equals("STATE_DOWNLOADING")) { messageKey = "STATE_DOWNLOADING_DEPENDENCY"; resourceName = ""; } else { return; } } if (installResource instanceof SampleResource) { SampleResource sr = ((SampleResource) installResource); resourceName = sr.getShortName() == null ? installResource.getName() : sr.getShortName(); } else { resourceName = installResource.getName(); } fireProgressEvent(state, progress, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(messageKey, resourceName)); }
java
private void fireProgressEvent(int state, int progress, String messageKey, RepositoryResource installResource) throws InstallException { String resourceName = null; if (installResource instanceof EsaResource) { EsaResource esar = ((EsaResource) installResource); if (esar.getVisibility().equals(Visibility.PUBLIC) || esar.getVisibility().equals(Visibility.INSTALL)) { resourceName = (esar.getShortName() == null) ? installResource.getName() : esar.getShortName(); } else if (!firePublicAssetOnly && messageKey.equals("STATE_DOWNLOADING")) { messageKey = "STATE_DOWNLOADING_DEPENDENCY"; resourceName = ""; } else { return; } } if (installResource instanceof SampleResource) { SampleResource sr = ((SampleResource) installResource); resourceName = sr.getShortName() == null ? installResource.getName() : sr.getShortName(); } else { resourceName = installResource.getName(); } fireProgressEvent(state, progress, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage(messageKey, resourceName)); }
[ "private", "void", "fireProgressEvent", "(", "int", "state", ",", "int", "progress", ",", "String", "messageKey", ",", "RepositoryResource", "installResource", ")", "throws", "InstallException", "{", "String", "resourceName", "=", "null", ";", "if", "(", "installR...
Fires a progress event message to be displayed @param state the state integer @param progress the progress integer @param messageKey the message key @param installResource the resource necessitating the progress event @throws InstallException
[ "Fires", "a", "progress", "event", "message", "to", "be", "displayed" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/Director.java#L168-L189
mapbox/mapbox-java
services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java
MultiLineString.fromLineString
public static MultiLineString fromLineString(@NonNull LineString lineString) { List<List<Point>> coordinates = Arrays.asList(lineString.coordinates()); return new MultiLineString(TYPE, null, coordinates); }
java
public static MultiLineString fromLineString(@NonNull LineString lineString) { List<List<Point>> coordinates = Arrays.asList(lineString.coordinates()); return new MultiLineString(TYPE, null, coordinates); }
[ "public", "static", "MultiLineString", "fromLineString", "(", "@", "NonNull", "LineString", "lineString", ")", "{", "List", "<", "List", "<", "Point", ">>", "coordinates", "=", "Arrays", ".", "asList", "(", "lineString", ".", "coordinates", "(", ")", ")", ";...
Create a new instance of this class by passing in a single {@link LineString} object. The LineStrings should comply with the GeoJson specifications described in the documentation. @param lineString a single LineString which make up this MultiLineString @return a new instance of this class defined by the values passed inside this static factory method @since 3.0.0
[ "Create", "a", "new", "instance", "of", "this", "class", "by", "passing", "in", "a", "single", "{", "@link", "LineString", "}", "object", ".", "The", "LineStrings", "should", "comply", "with", "the", "GeoJson", "specifications", "described", "in", "the", "do...
train
https://github.com/mapbox/mapbox-java/blob/c0be138f462f91441388584c668f3760ba0e18e2/services-geojson/src/main/java/com/mapbox/geojson/MultiLineString.java#L129-L132
actframework/actframework
src/main/java/act/ws/WebSocketContext.java
WebSocketContext.sendToTagged
public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) { return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf); }
java
public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) { return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf); }
[ "public", "WebSocketContext", "sendToTagged", "(", "String", "message", ",", "String", "tag", ",", "boolean", "excludeSelf", ")", "{", "return", "sendToConnections", "(", "message", ",", "tag", ",", "manager", ".", "tagRegistry", "(", ")", ",", "excludeSelf", ...
Send message to all connections labeled with tag specified. @param message the message to be sent @param tag the string that tag the connections to be sent @param excludeSelf specify whether the connection of this context should be send @return this context
[ "Send", "message", "to", "all", "connections", "labeled", "with", "tag", "specified", "." ]
train
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketContext.java#L232-L234
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java
ComboBoxArrowButtonPainter.paintButton
private void paintButton(Graphics2D g, JComponent c, int width, int height) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Shape s = createButtonPath(CornerSize.BORDER, 0, 2, width - 2, height - 4); g.setPaint(getComboBoxButtonBorderPaint(s, type)); g.fill(s); s = createButtonPath(CornerSize.INTERIOR, 1, 3, width - 4, height - 6); g.setPaint(getComboBoxButtonInteriorPaint(s, type)); g.fill(s); }
java
private void paintButton(Graphics2D g, JComponent c, int width, int height) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Shape s = createButtonPath(CornerSize.BORDER, 0, 2, width - 2, height - 4); g.setPaint(getComboBoxButtonBorderPaint(s, type)); g.fill(s); s = createButtonPath(CornerSize.INTERIOR, 1, 3, width - 4, height - 6); g.setPaint(getComboBoxButtonInteriorPaint(s, type)); g.fill(s); }
[ "private", "void", "paintButton", "(", "Graphics2D", "g", ",", "JComponent", "c", ",", "int", "width", ",", "int", "height", ")", "{", "g", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_ANTIALIASING", ",", "RenderingHints", ".", "VALUE_ANTIALIAS_ON",...
Paint the button shape. @param g the Graphics2D context to paint with. @param c the component to paint. @param width the width. @param height the height.
[ "Paint", "the", "button", "shape", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/ComboBoxArrowButtonPainter.java#L145-L156
overturetool/overture
core/interpreter/src/main/java/org/overture/interpreter/scheduler/SystemClock.java
SystemClock.timeToInternal
public static long timeToInternal(TimeUnit unit, Double time) { return Math.round(time * unit.getValue() / TimeUnit.nanosecond.getValue()); }
java
public static long timeToInternal(TimeUnit unit, Double time) { return Math.round(time * unit.getValue() / TimeUnit.nanosecond.getValue()); }
[ "public", "static", "long", "timeToInternal", "(", "TimeUnit", "unit", ",", "Double", "time", ")", "{", "return", "Math", ".", "round", "(", "time", "*", "unit", ".", "getValue", "(", ")", "/", "TimeUnit", ".", "nanosecond", ".", "getValue", "(", ")", ...
Utility method to convert a value in the given unit to the internal time @param unit The unit of the time parameter @param time The time to convert @return The internal time representation of the parameter
[ "Utility", "method", "to", "convert", "a", "value", "in", "the", "given", "unit", "to", "the", "internal", "time" ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/scheduler/SystemClock.java#L100-L104
goldmansachs/reladomo
reladomo/src/main/java/com/gs/fw/common/mithra/MithraManager.java
MithraManager.startOrContinueTransaction
public MithraTransaction startOrContinueTransaction(TransactionStyle style) throws MithraTransactionException { MithraTransaction result; MithraTransaction parent = this.getCurrentTransaction(); if (parent != null) { result = new MithraNestedTransaction(parent); } else { Transaction jtaTx; try { if (this.getJtaTransactionManager().getStatus() != Status.STATUS_ACTIVE) { this.getJtaTransactionManager().setTransactionTimeout(style.getTimeout()); this.getJtaTransactionManager().begin(); } jtaTx = this.getJtaTransactionManager().getTransaction(); result = this.createMithraRootTransaction(jtaTx, style.getTimeout()*1000); } catch (NotSupportedException e) { throw new MithraTransactionException("JTA exception", e); } catch (SystemException e) { throw new MithraTransactionException("JTA exception", e); } catch (RollbackException e) { throw new MithraTransactionException("JTA exception", e); } } this.setThreadTransaction(result); return result; }
java
public MithraTransaction startOrContinueTransaction(TransactionStyle style) throws MithraTransactionException { MithraTransaction result; MithraTransaction parent = this.getCurrentTransaction(); if (parent != null) { result = new MithraNestedTransaction(parent); } else { Transaction jtaTx; try { if (this.getJtaTransactionManager().getStatus() != Status.STATUS_ACTIVE) { this.getJtaTransactionManager().setTransactionTimeout(style.getTimeout()); this.getJtaTransactionManager().begin(); } jtaTx = this.getJtaTransactionManager().getTransaction(); result = this.createMithraRootTransaction(jtaTx, style.getTimeout()*1000); } catch (NotSupportedException e) { throw new MithraTransactionException("JTA exception", e); } catch (SystemException e) { throw new MithraTransactionException("JTA exception", e); } catch (RollbackException e) { throw new MithraTransactionException("JTA exception", e); } } this.setThreadTransaction(result); return result; }
[ "public", "MithraTransaction", "startOrContinueTransaction", "(", "TransactionStyle", "style", ")", "throws", "MithraTransactionException", "{", "MithraTransaction", "result", ";", "MithraTransaction", "parent", "=", "this", ".", "getCurrentTransaction", "(", ")", ";", "i...
Behaves like startOrContinueTransaction(), but with a custom transaction style @param style defines the parameters for this transaction. @return @throws MithraTransactionException
[ "Behaves", "like", "startOrContinueTransaction", "()", "but", "with", "a", "custom", "transaction", "style" ]
train
https://github.com/goldmansachs/reladomo/blob/e9a069452eece7a6ef9551caf81a69d3d9a3d990/reladomo/src/main/java/com/gs/fw/common/mithra/MithraManager.java#L246-L282
hal/core
gui/src/main/java/org/useware/kernel/model/structure/InteractionUnit.java
InteractionUnit.findMapping
public <T extends Mapping> T findMapping(MappingType type, Predicate<T> predicate) { T mapping = getMapping(type); if (mapping != null) { // check predicate: can invalidate the local mapping if (predicate != null) { mapping = (predicate.appliesTo(mapping)) ? mapping : null; } // complement the mapping (i.e. resource address at a higher level) if(mapping!=null && parent!=null) { Mapping parentMapping = parent.findMapping(type, predicate); if(parentMapping!=null) { mapping.complementFrom(parentMapping); } } } if (mapping == null && parent != null) { mapping = (T) parent.findMapping(type, predicate); } return mapping; }
java
public <T extends Mapping> T findMapping(MappingType type, Predicate<T> predicate) { T mapping = getMapping(type); if (mapping != null) { // check predicate: can invalidate the local mapping if (predicate != null) { mapping = (predicate.appliesTo(mapping)) ? mapping : null; } // complement the mapping (i.e. resource address at a higher level) if(mapping!=null && parent!=null) { Mapping parentMapping = parent.findMapping(type, predicate); if(parentMapping!=null) { mapping.complementFrom(parentMapping); } } } if (mapping == null && parent != null) { mapping = (T) parent.findMapping(type, predicate); } return mapping; }
[ "public", "<", "T", "extends", "Mapping", ">", "T", "findMapping", "(", "MappingType", "type", ",", "Predicate", "<", "T", ">", "predicate", ")", "{", "T", "mapping", "=", "getMapping", "(", "type", ")", ";", "if", "(", "mapping", "!=", "null", ")", ...
Finds the first mapping of a type within the hierarchy. Uses parent delegation if the mapping cannot be found locally. <p/> The predicate needs to apply. @param type @param predicate Use {@code null} to ignore @return
[ "Finds", "the", "first", "mapping", "of", "a", "type", "within", "the", "hierarchy", ".", "Uses", "parent", "delegation", "if", "the", "mapping", "cannot", "be", "found", "locally", ".", "<p", "/", ">", "The", "predicate", "needs", "to", "apply", "." ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/useware/kernel/model/structure/InteractionUnit.java#L157-L187
powermock/powermock
powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SuppressCode.java
SuppressCode.suppressField
public static synchronized void suppressField(Class<?> clazz, String... fieldNames) { if (fieldNames == null || fieldNames.length == 0) { suppressField(new Class<?>[] { clazz }); } else { for (Field field : Whitebox.getFields(clazz, fieldNames)) { MockRepository.addFieldToSuppress(field); } } }
java
public static synchronized void suppressField(Class<?> clazz, String... fieldNames) { if (fieldNames == null || fieldNames.length == 0) { suppressField(new Class<?>[] { clazz }); } else { for (Field field : Whitebox.getFields(clazz, fieldNames)) { MockRepository.addFieldToSuppress(field); } } }
[ "public", "static", "synchronized", "void", "suppressField", "(", "Class", "<", "?", ">", "clazz", ",", "String", "...", "fieldNames", ")", "{", "if", "(", "fieldNames", "==", "null", "||", "fieldNames", ".", "length", "==", "0", ")", "{", "suppressField",...
Suppress multiple methods for a class. @param clazz The class whose methods will be suppressed. @param fieldNames The names of the methods that'll be suppressed. If field names are empty, <i>all</i> fields in the supplied class will be suppressed.
[ "Suppress", "multiple", "methods", "for", "a", "class", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-api/powermock-api-support/src/main/java/org/powermock/api/support/SuppressCode.java#L127-L135
casmi/casmi
src/main/java/casmi/graphics/element/Box.java
Box.setGradationColor
public void setGradationColor(GradationMode3D mode, Color color1, Color color2) { setGradation(true); if (startColor == null || endColor == null) { startColor = new RGBColor(0.0, 0.0, 0.0); endColor = new RGBColor(0.0, 0.0, 0.0); } startColor = color1; endColor = color2; this.mode = mode; setGradationCorner(); }
java
public void setGradationColor(GradationMode3D mode, Color color1, Color color2) { setGradation(true); if (startColor == null || endColor == null) { startColor = new RGBColor(0.0, 0.0, 0.0); endColor = new RGBColor(0.0, 0.0, 0.0); } startColor = color1; endColor = color2; this.mode = mode; setGradationCorner(); }
[ "public", "void", "setGradationColor", "(", "GradationMode3D", "mode", ",", "Color", "color1", ",", "Color", "color2", ")", "{", "setGradation", "(", "true", ")", ";", "if", "(", "startColor", "==", "null", "||", "endColor", "==", "null", ")", "{", "startC...
Sets the gradation mode and colors. @param mode The mode of gradation. @param color1 The color for gradation. @param color2 The color for gradation. @see casmi.GradationMode2D
[ "Sets", "the", "gradation", "mode", "and", "colors", "." ]
train
https://github.com/casmi/casmi/blob/90f6514a9cbce0685186e7a92beb69e22a3b11c4/src/main/java/casmi/graphics/element/Box.java#L368-L379
apptentive/apptentive-android
apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java
Util.createLocalStoredFile
public static StoredFile createLocalStoredFile(String sourceUrl, String localFilePath, String mimeType) { InputStream is = null; try { Context context = ApptentiveInternal.getInstance().getApplicationContext(); if (URLUtil.isContentUrl(sourceUrl) && context != null) { Uri uri = Uri.parse(sourceUrl); is = context.getContentResolver().openInputStream(uri); } else { File file = new File(sourceUrl); is = new FileInputStream(file); } return createLocalStoredFile(is, sourceUrl, localFilePath, mimeType); } catch (FileNotFoundException e) { return null; } finally { ensureClosed(is); } }
java
public static StoredFile createLocalStoredFile(String sourceUrl, String localFilePath, String mimeType) { InputStream is = null; try { Context context = ApptentiveInternal.getInstance().getApplicationContext(); if (URLUtil.isContentUrl(sourceUrl) && context != null) { Uri uri = Uri.parse(sourceUrl); is = context.getContentResolver().openInputStream(uri); } else { File file = new File(sourceUrl); is = new FileInputStream(file); } return createLocalStoredFile(is, sourceUrl, localFilePath, mimeType); } catch (FileNotFoundException e) { return null; } finally { ensureClosed(is); } }
[ "public", "static", "StoredFile", "createLocalStoredFile", "(", "String", "sourceUrl", ",", "String", "localFilePath", ",", "String", "mimeType", ")", "{", "InputStream", "is", "=", "null", ";", "try", "{", "Context", "context", "=", "ApptentiveInternal", ".", "...
This method creates a cached file exactly copying from the input stream. @param sourceUrl the source file path or uri string @param localFilePath the cache file path string @param mimeType the mimeType of the source inputstream @return null if failed, otherwise a StoredFile object
[ "This", "method", "creates", "a", "cached", "file", "exactly", "copying", "from", "the", "input", "stream", "." ]
train
https://github.com/apptentive/apptentive-android/blob/887c08d7bd5ae6488a90366dfb58f58938861a93/apptentive/src/main/java/com/apptentive/android/sdk/util/Util.java#L914-L932
apache/groovy
src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java
BytecodeHelper.doCastToWrappedType
public static void doCastToWrappedType(MethodVisitor mv, ClassNode sourceType, ClassNode targetType) { mv.visitMethodInsn(INVOKESTATIC, getClassInternalName(targetType), "valueOf", "(" + getTypeDescription(sourceType) + ")" + getTypeDescription(targetType), false); }
java
public static void doCastToWrappedType(MethodVisitor mv, ClassNode sourceType, ClassNode targetType) { mv.visitMethodInsn(INVOKESTATIC, getClassInternalName(targetType), "valueOf", "(" + getTypeDescription(sourceType) + ")" + getTypeDescription(targetType), false); }
[ "public", "static", "void", "doCastToWrappedType", "(", "MethodVisitor", "mv", ",", "ClassNode", "sourceType", ",", "ClassNode", "targetType", ")", "{", "mv", ".", "visitMethodInsn", "(", "INVOKESTATIC", ",", "getClassInternalName", "(", "targetType", ")", ",", "\...
Given a primitive number type (byte, integer, short, ...), generates bytecode to convert it to a wrapped number (Integer, Long, Double) using calls to [WrappedType].valueOf @param mv method visitor @param sourceType the primitive number type @param targetType the wrapped target type
[ "Given", "a", "primitive", "number", "type", "(", "byte", "integer", "short", "...", ")", "generates", "bytecode", "to", "convert", "it", "to", "a", "wrapped", "number", "(", "Integer", "Long", "Double", ")", "using", "calls", "to", "[", "WrappedType", "]"...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/classgen/asm/BytecodeHelper.java#L472-L474
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/BibliographyCommand.java
BibliographyCommand.generateCSL
private int generateCSL(String style, String locale, String format, List<String> citationIds, ItemDataProvider provider, PrintWriter out) throws IOException { if (!checkStyle(style)) { return 1; } //initialize citation processor try (CSL citeproc = new CSL(provider, style, locale)) { //set output format citeproc.setOutputFormat(format); //register citation items String[] citationIdsArr = new String[citationIds.size()]; citationIdsArr = citationIds.toArray(citationIdsArr); if (citationIds.isEmpty()) { citationIdsArr = provider.getIds(); } citeproc.registerCitationItems(citationIdsArr); //generate bibliography doGenerateCSL(citeproc, citationIdsArr, out); } catch (FileNotFoundException e) { error(e.getMessage()); return 1; } return 0; }
java
private int generateCSL(String style, String locale, String format, List<String> citationIds, ItemDataProvider provider, PrintWriter out) throws IOException { if (!checkStyle(style)) { return 1; } //initialize citation processor try (CSL citeproc = new CSL(provider, style, locale)) { //set output format citeproc.setOutputFormat(format); //register citation items String[] citationIdsArr = new String[citationIds.size()]; citationIdsArr = citationIds.toArray(citationIdsArr); if (citationIds.isEmpty()) { citationIdsArr = provider.getIds(); } citeproc.registerCitationItems(citationIdsArr); //generate bibliography doGenerateCSL(citeproc, citationIdsArr, out); } catch (FileNotFoundException e) { error(e.getMessage()); return 1; } return 0; }
[ "private", "int", "generateCSL", "(", "String", "style", ",", "String", "locale", ",", "String", "format", ",", "List", "<", "String", ">", "citationIds", ",", "ItemDataProvider", "provider", ",", "PrintWriter", "out", ")", "throws", "IOException", "{", "if", ...
Performs CSL conversion and generates a bibliography @param style the CSL style @param locale the CSL locale @param format the output format @param citationIds the citation ids given on the command line @param provider a provider containing all citation item data @param out the print stream to write the output to @return the exit code @throws IOException if the CSL processor could not be initialized
[ "Performs", "CSL", "conversion", "and", "generates", "a", "bibliography" ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/BibliographyCommand.java#L152-L180
Alluxio/alluxio
core/common/src/main/java/alluxio/concurrent/jsr/CountedCompleter.java
CountedCompleter.firstComplete
public final CountedCompleter<?> firstComplete() { for (int c;;) { if ((c = pending) == 0) return this; else if (U.compareAndSwapInt(this, PENDING, c, c - 1)) return null; } }
java
public final CountedCompleter<?> firstComplete() { for (int c;;) { if ((c = pending) == 0) return this; else if (U.compareAndSwapInt(this, PENDING, c, c - 1)) return null; } }
[ "public", "final", "CountedCompleter", "<", "?", ">", "firstComplete", "(", ")", "{", "for", "(", "int", "c", ";", ";", ")", "{", "if", "(", "(", "c", "=", "pending", ")", "==", "0", ")", "return", "this", ";", "else", "if", "(", "U", ".", "com...
If this task's pending count is zero, returns this task; otherwise decrements its pending count and returns {@code null}. This method is designed to be used with {@link #nextComplete} in completion traversal loops. @return this task, if pending count was zero, else {@code null}
[ "If", "this", "task", "s", "pending", "count", "is", "zero", "returns", "this", "task", ";", "otherwise", "decrements", "its", "pending", "count", "and", "returns", "{", "@code", "null", "}", ".", "This", "method", "is", "designed", "to", "be", "used", "...
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/concurrent/jsr/CountedCompleter.java#L613-L620
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/ObjectsApi.java
ObjectsApi.getPermissions
public GetPermissionsSuccessResponse getPermissions(String objectType, String dbids, String dnType, String folderType) throws ApiException { ApiResponse<GetPermissionsSuccessResponse> resp = getPermissionsWithHttpInfo(objectType, dbids, dnType, folderType); return resp.getData(); }
java
public GetPermissionsSuccessResponse getPermissions(String objectType, String dbids, String dnType, String folderType) throws ApiException { ApiResponse<GetPermissionsSuccessResponse> resp = getPermissionsWithHttpInfo(objectType, dbids, dnType, folderType); return resp.getData(); }
[ "public", "GetPermissionsSuccessResponse", "getPermissions", "(", "String", "objectType", ",", "String", "dbids", ",", "String", "dnType", ",", "String", "folderType", ")", "throws", "ApiException", "{", "ApiResponse", "<", "GetPermissionsSuccessResponse", ">", "resp", ...
Get permissions for a list of objects. Get permissions from Configuration Server for objects identified by their type and DBIDs. @param objectType The type of object. Any type supported by the Config server (folders, business-attributes etc). (required) @param dbids Comma-separated list of object DBIDs to query permissions. (required) @param dnType If the object_type is &#39;dns&#39;, then you may specify the DN type (for example, CFGRoutingPoint). This parameter does not affect request results but may increase performance For possible values, see [CfgDNType](https://docs.genesys.com/Documentation/PSDK/9.0.x/ConfigLayerRef/CfgDNType) in the Platform SDK documentation. (optional) @param folderType If the object_type is &#39;folders&#39;, then you may specify the object type of the folders (for example, CFGPerson). This parameter does not affect request results but may increase performance For possible values, see [CfgObjectType](https://docs.genesys.com/Documentation/PSDK/9.0.x/ConfigLayerRef/CfgObjectType) in the Platform SDK documentation. (optional) @return GetPermissionsSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "permissions", "for", "a", "list", "of", "objects", ".", "Get", "permissions", "from", "Configuration", "Server", "for", "objects", "identified", "by", "their", "type", "and", "DBIDs", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/ObjectsApi.java#L349-L352
comapi/comapi-chat-sdk-android
COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java
PersistenceController.updateStoreForSentError
public Observable<Boolean> updateStoreForSentError(String conversationId, String tempId, String profileId) { return asObservable(new Executor<Boolean>() { @Override protected void execute(ChatStore store, Emitter<Boolean> emitter) { store.beginTransaction(); boolean isSuccess = store.update(ChatMessageStatus.builder().populate(conversationId, tempId, profileId, LocalMessageStatus.error, System.currentTimeMillis(), null).build()); store.endTransaction(); emitter.onNext(isSuccess); emitter.onCompleted(); } }); }
java
public Observable<Boolean> updateStoreForSentError(String conversationId, String tempId, String profileId) { return asObservable(new Executor<Boolean>() { @Override protected void execute(ChatStore store, Emitter<Boolean> emitter) { store.beginTransaction(); boolean isSuccess = store.update(ChatMessageStatus.builder().populate(conversationId, tempId, profileId, LocalMessageStatus.error, System.currentTimeMillis(), null).build()); store.endTransaction(); emitter.onNext(isSuccess); emitter.onCompleted(); } }); }
[ "public", "Observable", "<", "Boolean", ">", "updateStoreForSentError", "(", "String", "conversationId", ",", "String", "tempId", ",", "String", "profileId", ")", "{", "return", "asObservable", "(", "new", "Executor", "<", "Boolean", ">", "(", ")", "{", "@", ...
Insert 'error' message status if sending message failed. @param conversationId Unique conversation id. @param tempId Id of an temporary message for which @param profileId Profile id from current session data. @return Observable emitting result.
[ "Insert", "error", "message", "status", "if", "sending", "message", "failed", "." ]
train
https://github.com/comapi/comapi-chat-sdk-android/blob/388f37bfacb7793ce30c92ab70e5f32848bbe460/COMAPI/chat/src/main/java/com/comapi/chat/PersistenceController.java#L305-L317
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java
DiscoverInfo.hasIdentity
public boolean hasIdentity(String category, String type) { String key = XmppStringUtils.generateKey(category, type); return identitiesSet.contains(key); }
java
public boolean hasIdentity(String category, String type) { String key = XmppStringUtils.generateKey(category, type); return identitiesSet.contains(key); }
[ "public", "boolean", "hasIdentity", "(", "String", "category", ",", "String", "type", ")", "{", "String", "key", "=", "XmppStringUtils", ".", "generateKey", "(", "category", ",", "type", ")", ";", "return", "identitiesSet", ".", "contains", "(", "key", ")", ...
Returns true if this DiscoverInfo contains at least one Identity of the given category and type. @param category the category to look for. @param type the type to look for. @return true if this DiscoverInfo contains a Identity of the given category and type.
[ "Returns", "true", "if", "this", "DiscoverInfo", "contains", "at", "least", "one", "Identity", "of", "the", "given", "category", "and", "type", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java#L159-L162
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java
SDBaseOps.oneHot
public SDVariable oneHot(String name, SDVariable indices, int depth, int axis, double on, double off) { return oneHot(name, indices, depth, axis, on, off, OneHot.DEFAULT_DTYPE); }
java
public SDVariable oneHot(String name, SDVariable indices, int depth, int axis, double on, double off) { return oneHot(name, indices, depth, axis, on, off, OneHot.DEFAULT_DTYPE); }
[ "public", "SDVariable", "oneHot", "(", "String", "name", ",", "SDVariable", "indices", ",", "int", "depth", ",", "int", "axis", ",", "double", "on", ",", "double", "off", ")", "{", "return", "oneHot", "(", "name", ",", "indices", ",", "depth", ",", "ax...
Convert the array to a one-hot array with walues {@code on} and {@code off} for each entry<br> If input has shape [ a, ..., n] then output has shape [ a, ..., n, depth], with {@code out[i, ..., j, in[i,...,j]] = on} with other values being set to {@code off} @param name Output variable name @param indices Indices - value 0 to depth-1 @param depth Number of classes @return Output variable
[ "Convert", "the", "array", "to", "a", "one", "-", "hot", "array", "with", "walues", "{", "@code", "on", "}", "and", "{", "@code", "off", "}", "for", "each", "entry<br", ">", "If", "input", "has", "shape", "[", "a", "...", "n", "]", "then", "output"...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java#L1467-L1469
alkacon/opencms-core
src/org/opencms/loader/CmsImageScaler.java
CmsImageScaler.setCropArea
public void setCropArea(int x, int y, int width, int height) { m_cropX = x; m_cropY = y; m_cropWidth = width; m_cropHeight = height; }
java
public void setCropArea(int x, int y, int width, int height) { m_cropX = x; m_cropY = y; m_cropWidth = width; m_cropHeight = height; }
[ "public", "void", "setCropArea", "(", "int", "x", ",", "int", "y", ",", "int", "width", ",", "int", "height", ")", "{", "m_cropX", "=", "x", ";", "m_cropY", "=", "y", ";", "m_cropWidth", "=", "width", ";", "m_cropHeight", "=", "height", ";", "}" ]
Sets the image crop area.<p> @param x the x coordinate for the crop @param y the y coordinate for the crop @param width the crop width @param height the crop height
[ "Sets", "the", "image", "crop", "area", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsImageScaler.java#L1328-L1334
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java
BigDecimal.createAndStripZerosToMatchScale
private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) { while (Math.abs(compactVal) >= 10L && scale > preferredScale) { if ((compactVal & 1L) != 0L) break; // odd number cannot end in 0 long r = compactVal % 10L; if (r != 0L) break; // non-0 remainder compactVal /= 10; scale = checkScale(compactVal, (long) scale - 1); // could Overflow } return valueOf(compactVal, scale); }
java
private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) { while (Math.abs(compactVal) >= 10L && scale > preferredScale) { if ((compactVal & 1L) != 0L) break; // odd number cannot end in 0 long r = compactVal % 10L; if (r != 0L) break; // non-0 remainder compactVal /= 10; scale = checkScale(compactVal, (long) scale - 1); // could Overflow } return valueOf(compactVal, scale); }
[ "private", "static", "BigDecimal", "createAndStripZerosToMatchScale", "(", "long", "compactVal", ",", "int", "scale", ",", "long", "preferredScale", ")", "{", "while", "(", "Math", ".", "abs", "(", "compactVal", ")", ">=", "10L", "&&", "scale", ">", "preferred...
Remove insignificant trailing zeros from this {@code long} value until the preferred scale is reached or no more zeros can be removed. If the preferred scale is less than Integer.MIN_VALUE, all the trailing zeros will be removed. @return new {@code BigDecimal} with a scale possibly reduced to be closed to the preferred scale.
[ "Remove", "insignificant", "trailing", "zeros", "from", "this", "{", "@code", "long", "}", "value", "until", "the", "preferred", "scale", "is", "reached", "or", "no", "more", "zeros", "can", "be", "removed", ".", "If", "the", "preferred", "scale", "is", "l...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L4393-L4404
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.events_get
public T events_get(Integer userId, Collection<Long> eventIds, Long startTime, Long endTime) throws FacebookException, IOException { ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(FacebookMethod.EVENTS_GET.numParams()); boolean hasUserId = null != userId && 0 != userId; boolean hasEventIds = null != eventIds && !eventIds.isEmpty(); boolean hasStart = null != startTime && 0 != startTime; boolean hasEnd = null != endTime && 0 != endTime; if (hasUserId) params.add(new Pair<String, CharSequence>("uid", Integer.toString(userId))); if (hasEventIds) params.add(new Pair<String, CharSequence>("eids", delimit(eventIds))); if (hasStart) params.add(new Pair<String, CharSequence>("start_time", startTime.toString())); if (hasEnd) params.add(new Pair<String, CharSequence>("end_time", endTime.toString())); return this.callMethod(FacebookMethod.EVENTS_GET, params); }
java
public T events_get(Integer userId, Collection<Long> eventIds, Long startTime, Long endTime) throws FacebookException, IOException { ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(FacebookMethod.EVENTS_GET.numParams()); boolean hasUserId = null != userId && 0 != userId; boolean hasEventIds = null != eventIds && !eventIds.isEmpty(); boolean hasStart = null != startTime && 0 != startTime; boolean hasEnd = null != endTime && 0 != endTime; if (hasUserId) params.add(new Pair<String, CharSequence>("uid", Integer.toString(userId))); if (hasEventIds) params.add(new Pair<String, CharSequence>("eids", delimit(eventIds))); if (hasStart) params.add(new Pair<String, CharSequence>("start_time", startTime.toString())); if (hasEnd) params.add(new Pair<String, CharSequence>("end_time", endTime.toString())); return this.callMethod(FacebookMethod.EVENTS_GET, params); }
[ "public", "T", "events_get", "(", "Integer", "userId", ",", "Collection", "<", "Long", ">", "eventIds", ",", "Long", "startTime", ",", "Long", "endTime", ")", "throws", "FacebookException", ",", "IOException", "{", "ArrayList", "<", "Pair", "<", "String", ",...
Returns all visible events according to the filters specified. This may be used to find all events of a user, or to query specific eids. @param eventIds filter by these event ID's (optional) @param userId filter by this user only (optional) @param startTime UTC lower bound (optional) @param endTime UTC upper bound (optional) @return T of events
[ "Returns", "all", "visible", "events", "according", "to", "the", "filters", "specified", ".", "This", "may", "be", "used", "to", "find", "all", "events", "of", "a", "user", "or", "to", "query", "specific", "eids", "." ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1391-L1410
mongodb/stitch-android-sdk
core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java
DataSynchronizer.insertOne
void insertOne(final MongoNamespace namespace, final BsonDocument document) { this.waitUntilInitialized(); try { ongoingOperationsGroup.enter(); // Remove forbidden fields from the document before inserting it into the local collection. final BsonDocument docForStorage = sanitizeDocument(document); final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace); final Lock lock = nsConfig.getLock().writeLock(); lock.lock(); final ChangeEvent<BsonDocument> event; final BsonValue documentId; try { getLocalCollection(namespace).insertOne(docForStorage); documentId = BsonUtils.getDocumentId(docForStorage); event = ChangeEvents.changeEventForLocalInsert(namespace, docForStorage, true); final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument( namespace, documentId ); config.setSomePendingWritesAndSave(logicalT, event); } finally { lock.unlock(); } checkAndInsertNamespaceListener(namespace); eventDispatcher.emitEvent(nsConfig, event); } finally { ongoingOperationsGroup.exit(); } }
java
void insertOne(final MongoNamespace namespace, final BsonDocument document) { this.waitUntilInitialized(); try { ongoingOperationsGroup.enter(); // Remove forbidden fields from the document before inserting it into the local collection. final BsonDocument docForStorage = sanitizeDocument(document); final NamespaceSynchronizationConfig nsConfig = this.syncConfig.getNamespaceConfig(namespace); final Lock lock = nsConfig.getLock().writeLock(); lock.lock(); final ChangeEvent<BsonDocument> event; final BsonValue documentId; try { getLocalCollection(namespace).insertOne(docForStorage); documentId = BsonUtils.getDocumentId(docForStorage); event = ChangeEvents.changeEventForLocalInsert(namespace, docForStorage, true); final CoreDocumentSynchronizationConfig config = syncConfig.addAndGetSynchronizedDocument( namespace, documentId ); config.setSomePendingWritesAndSave(logicalT, event); } finally { lock.unlock(); } checkAndInsertNamespaceListener(namespace); eventDispatcher.emitEvent(nsConfig, event); } finally { ongoingOperationsGroup.exit(); } }
[ "void", "insertOne", "(", "final", "MongoNamespace", "namespace", ",", "final", "BsonDocument", "document", ")", "{", "this", ".", "waitUntilInitialized", "(", ")", ";", "try", "{", "ongoingOperationsGroup", ".", "enter", "(", ")", ";", "// Remove forbidden fields...
Inserts a single document locally and being to synchronize it based on its _id. Inserting a document with the same _id twice will result in a duplicate key exception. @param namespace the namespace to put the document in. @param document the document to insert.
[ "Inserts", "a", "single", "document", "locally", "and", "being", "to", "synchronize", "it", "based", "on", "its", "_id", ".", "Inserting", "a", "document", "with", "the", "same", "_id", "twice", "will", "result", "in", "a", "duplicate", "key", "exception", ...
train
https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/services/mongodb-remote/src/main/java/com/mongodb/stitch/core/services/mongodb/remote/sync/internal/DataSynchronizer.java#L2247-L2278
dbracewell/hermes
hermes-core/src/main/java/com/davidbracewell/hermes/Document.java
Document.create
public static Document create(@NonNull String text, @NonNull Map<AttributeType, ?> attributes) { return DocumentFactory.getInstance().create(text, Hermes.defaultLanguage(), attributes); }
java
public static Document create(@NonNull String text, @NonNull Map<AttributeType, ?> attributes) { return DocumentFactory.getInstance().create(text, Hermes.defaultLanguage(), attributes); }
[ "public", "static", "Document", "create", "(", "@", "NonNull", "String", "text", ",", "@", "NonNull", "Map", "<", "AttributeType", ",", "?", ">", "attributes", ")", "{", "return", "DocumentFactory", ".", "getInstance", "(", ")", ".", "create", "(", "text",...
Convenience method for creating a document using the default document factory. @param text the text content making up the document @param attributes the attributes, i.e. metadata, associated with the document @return the document
[ "Convenience", "method", "for", "creating", "a", "document", "using", "the", "default", "document", "factory", "." ]
train
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/Document.java#L138-L140
Azure/autorest-clientruntime-for-java
azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java
UserTokenCredentials.acquireAccessTokenFromRefreshToken
AuthenticationResult acquireAccessTokenFromRefreshToken(String resource, String refreshToken, boolean isMultipleResourceRefreshToken) throws IOException { ExecutorService executor = Executors.newSingleThreadExecutor(); try { return refreshTokenClient.refreshToken(domain(), clientId(), resource, refreshToken, isMultipleResourceRefreshToken); } catch (Exception e) { return null; } finally { executor.shutdown(); } }
java
AuthenticationResult acquireAccessTokenFromRefreshToken(String resource, String refreshToken, boolean isMultipleResourceRefreshToken) throws IOException { ExecutorService executor = Executors.newSingleThreadExecutor(); try { return refreshTokenClient.refreshToken(domain(), clientId(), resource, refreshToken, isMultipleResourceRefreshToken); } catch (Exception e) { return null; } finally { executor.shutdown(); } }
[ "AuthenticationResult", "acquireAccessTokenFromRefreshToken", "(", "String", "resource", ",", "String", "refreshToken", ",", "boolean", "isMultipleResourceRefreshToken", ")", "throws", "IOException", "{", "ExecutorService", "executor", "=", "Executors", ".", "newSingleThreadE...
Refresh tokens are currently not used since we don't know if the refresh token has expired
[ "Refresh", "tokens", "are", "currently", "not", "used", "since", "we", "don", "t", "know", "if", "the", "refresh", "token", "has", "expired" ]
train
https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java#L122-L131
alkacon/opencms-core
src/org/opencms/cache/CmsMemoryObjectCache.java
CmsMemoryObjectCache.putCachedObject
public void putCachedObject(Class<?> owner, String key, Object value) { key = owner.getName().concat(key); OpenCms.getMemoryMonitor().cacheMemObject(key, value); }
java
public void putCachedObject(Class<?> owner, String key, Object value) { key = owner.getName().concat(key); OpenCms.getMemoryMonitor().cacheMemObject(key, value); }
[ "public", "void", "putCachedObject", "(", "Class", "<", "?", ">", "owner", ",", "String", "key", ",", "Object", "value", ")", "{", "key", "=", "owner", ".", "getName", "(", ")", ".", "concat", "(", "key", ")", ";", "OpenCms", ".", "getMemoryMonitor", ...
Puts an object into the cache.<p> @param owner the owner class of the cached object (used to ensure keys don't overlap) @param key the key to store the object at @param value the object to store
[ "Puts", "an", "object", "into", "the", "cache", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/cache/CmsMemoryObjectCache.java#L116-L120
spotify/apollo
examples/spotify-api-example/src/main/java/com/spotify/apollo/example/AlbumResource.java
AlbumResource.parseAlbumData
private ArrayList<Album> parseAlbumData(String json) { ArrayList<Album> albums = new ArrayList<>(); try { JsonNode jsonNode = this.objectMapper.readTree(json); for (JsonNode albumNode : jsonNode.get("albums")) { JsonNode artistsNode = albumNode.get("artists"); // Exclude albums with 0 artists if (artistsNode.size() >= 1) { // Only keeping the first artist for simplicity Artist artist = new Artist(artistsNode.get(0).get("name").asText()); Album album = new Album(albumNode.get("name").asText(), artist); albums.add(album); } } } catch (IOException e) { throw new RuntimeException("Failed to parse JSON", e); } return albums; }
java
private ArrayList<Album> parseAlbumData(String json) { ArrayList<Album> albums = new ArrayList<>(); try { JsonNode jsonNode = this.objectMapper.readTree(json); for (JsonNode albumNode : jsonNode.get("albums")) { JsonNode artistsNode = albumNode.get("artists"); // Exclude albums with 0 artists if (artistsNode.size() >= 1) { // Only keeping the first artist for simplicity Artist artist = new Artist(artistsNode.get(0).get("name").asText()); Album album = new Album(albumNode.get("name").asText(), artist); albums.add(album); } } } catch (IOException e) { throw new RuntimeException("Failed to parse JSON", e); } return albums; }
[ "private", "ArrayList", "<", "Album", ">", "parseAlbumData", "(", "String", "json", ")", "{", "ArrayList", "<", "Album", ">", "albums", "=", "new", "ArrayList", "<>", "(", ")", ";", "try", "{", "JsonNode", "jsonNode", "=", "this", ".", "objectMapper", "....
Parses an album response from a <a href="https://developer.spotify.com/web-api/album-endpoints/">Spotify API album query</a>. @param json The json response @return A list of albums with artist information
[ "Parses", "an", "album", "response", "from", "a", "<a", "href", "=", "https", ":", "//", "developer", ".", "spotify", ".", "com", "/", "web", "-", "api", "/", "album", "-", "endpoints", "/", ">", "Spotify", "API", "album", "query<", "/", "a", ">", ...
train
https://github.com/spotify/apollo/blob/3aba09840538a2aff9cdac5be42cc114dd276c70/examples/spotify-api-example/src/main/java/com/spotify/apollo/example/AlbumResource.java#L74-L92
citrusframework/citrus
modules/citrus-ws/src/main/java/com/consol/citrus/ws/addressing/WsAddressingHeaders.java
WsAddressingHeaders.setFaultTo
public void setFaultTo(String faultTo) { try { this.faultTo = new EndpointReference(new URI(faultTo)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid faultTo uri", e); } }
java
public void setFaultTo(String faultTo) { try { this.faultTo = new EndpointReference(new URI(faultTo)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid faultTo uri", e); } }
[ "public", "void", "setFaultTo", "(", "String", "faultTo", ")", "{", "try", "{", "this", ".", "faultTo", "=", "new", "EndpointReference", "(", "new", "URI", "(", "faultTo", ")", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", ...
Sets the fault to endpoint reference by string. @param faultTo the faultTo to set
[ "Sets", "the", "fault", "to", "endpoint", "reference", "by", "string", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ws/src/main/java/com/consol/citrus/ws/addressing/WsAddressingHeaders.java#L230-L236
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/connmgmt/ConnectionHandle.java
ConnectionHandle.getConnectionHandle
public static ConnectionHandle getConnectionHandle(VirtualConnection vc) { if (vc == null) { return null; } ConnectionHandle connHandle = (ConnectionHandle) vc.getStateMap().get(CONNECTION_HANDLE_VC_KEY); // We can be here for two reasons: // a) We have one, just needed to find it in VC state map if (connHandle != null) return connHandle; // b) We want a new one connHandle = factory.createConnectionHandle(); // For some connections (outbound, most notably), the connection type // will be set on the VC before connect... in which case, read it // and set it on the connection handle at the earliest point // possible. if (connHandle != null) { connHandle.setConnectionType(vc); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "getConnectionHandle - created new connection handle: " + connHandle); } setConnectionHandle(vc, connHandle); return connHandle; }
java
public static ConnectionHandle getConnectionHandle(VirtualConnection vc) { if (vc == null) { return null; } ConnectionHandle connHandle = (ConnectionHandle) vc.getStateMap().get(CONNECTION_HANDLE_VC_KEY); // We can be here for two reasons: // a) We have one, just needed to find it in VC state map if (connHandle != null) return connHandle; // b) We want a new one connHandle = factory.createConnectionHandle(); // For some connections (outbound, most notably), the connection type // will be set on the VC before connect... in which case, read it // and set it on the connection handle at the earliest point // possible. if (connHandle != null) { connHandle.setConnectionType(vc); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "getConnectionHandle - created new connection handle: " + connHandle); } setConnectionHandle(vc, connHandle); return connHandle; }
[ "public", "static", "ConnectionHandle", "getConnectionHandle", "(", "VirtualConnection", "vc", ")", "{", "if", "(", "vc", "==", "null", ")", "{", "return", "null", ";", "}", "ConnectionHandle", "connHandle", "=", "(", "ConnectionHandle", ")", "vc", ".", "getSt...
Get ConnectionHandle stored in VirtualConnection state map (if one isn't there already, assign one). @param vc @return ConnectionHandle
[ "Get", "ConnectionHandle", "stored", "in", "VirtualConnection", "state", "map", "(", "if", "one", "isn", "t", "there", "already", "assign", "one", ")", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/connmgmt/ConnectionHandle.java#L68-L97
molgenis/molgenis
molgenis-one-click-importer/src/main/java/org/molgenis/oneclickimporter/service/impl/OneClickImporterServiceImpl.java
OneClickImporterServiceImpl.createColumnFromCell
private Column createColumnFromCell(Sheet sheet, Cell cell) { if (cell.getCellTypeEnum() == CellType.STRING) { return Column.create( cell.getStringCellValue(), cell.getColumnIndex(), getColumnDataFromSheet(sheet, cell.getColumnIndex())); } else { throw new MolgenisDataException( String.format( "Celltype [%s] is not supported for columnheaders", cell.getCellTypeEnum())); } }
java
private Column createColumnFromCell(Sheet sheet, Cell cell) { if (cell.getCellTypeEnum() == CellType.STRING) { return Column.create( cell.getStringCellValue(), cell.getColumnIndex(), getColumnDataFromSheet(sheet, cell.getColumnIndex())); } else { throw new MolgenisDataException( String.format( "Celltype [%s] is not supported for columnheaders", cell.getCellTypeEnum())); } }
[ "private", "Column", "createColumnFromCell", "(", "Sheet", "sheet", ",", "Cell", "cell", ")", "{", "if", "(", "cell", ".", "getCellTypeEnum", "(", ")", "==", "CellType", ".", "STRING", ")", "{", "return", "Column", ".", "create", "(", "cell", ".", "getSt...
Specific columntypes are permitted in the import. The supported columntypes are specified in the method. @param sheet worksheet @param cell cell on worksheet @return Column
[ "Specific", "columntypes", "are", "permitted", "in", "the", "import", ".", "The", "supported", "columntypes", "are", "specified", "in", "the", "method", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-one-click-importer/src/main/java/org/molgenis/oneclickimporter/service/impl/OneClickImporterServiceImpl.java#L171-L182
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/network/vlan_stats.java
vlan_stats.get
public static vlan_stats get(nitro_service service, Long id) throws Exception{ vlan_stats obj = new vlan_stats(); obj.set_id(id); vlan_stats response = (vlan_stats) obj.stat_resource(service); return response; }
java
public static vlan_stats get(nitro_service service, Long id) throws Exception{ vlan_stats obj = new vlan_stats(); obj.set_id(id); vlan_stats response = (vlan_stats) obj.stat_resource(service); return response; }
[ "public", "static", "vlan_stats", "get", "(", "nitro_service", "service", ",", "Long", "id", ")", "throws", "Exception", "{", "vlan_stats", "obj", "=", "new", "vlan_stats", "(", ")", ";", "obj", ".", "set_id", "(", "id", ")", ";", "vlan_stats", "response",...
Use this API to fetch statistics of vlan_stats resource of given name .
[ "Use", "this", "API", "to", "fetch", "statistics", "of", "vlan_stats", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/network/vlan_stats.java#L241-L246
phax/ph-masterdata
ph-masterdata/src/main/java/com/helger/masterdata/price/Price.java
Price.createFromGrossAmount
@Nonnull public static Price createFromGrossAmount (@Nonnull final ICurrencyValue aGrossAmount, @Nonnull final IVATItem aVATItem) { ValueEnforcer.notNull (aGrossAmount, "GrossAmount"); final ECurrency eCurrency = aGrossAmount.getCurrency (); final PerCurrencySettings aPCS = CurrencyHelper.getSettings (eCurrency); return createFromGrossAmount (aGrossAmount, aVATItem, aPCS.getScale (), aPCS.getRoundingMode ()); }
java
@Nonnull public static Price createFromGrossAmount (@Nonnull final ICurrencyValue aGrossAmount, @Nonnull final IVATItem aVATItem) { ValueEnforcer.notNull (aGrossAmount, "GrossAmount"); final ECurrency eCurrency = aGrossAmount.getCurrency (); final PerCurrencySettings aPCS = CurrencyHelper.getSettings (eCurrency); return createFromGrossAmount (aGrossAmount, aVATItem, aPCS.getScale (), aPCS.getRoundingMode ()); }
[ "@", "Nonnull", "public", "static", "Price", "createFromGrossAmount", "(", "@", "Nonnull", "final", "ICurrencyValue", "aGrossAmount", ",", "@", "Nonnull", "final", "IVATItem", "aVATItem", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aGrossAmount", ",", "\"Gros...
Create a price from a gross amount using the scale and rounding mode from the currency. @param aGrossAmount The gross amount to use. May not be <code>null</code>. @param aVATItem The VAT item to use. May not be <code>null</code>. @return The created {@link Price}
[ "Create", "a", "price", "from", "a", "gross", "amount", "using", "the", "scale", "and", "rounding", "mode", "from", "the", "currency", "." ]
train
https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/price/Price.java#L318-L327
JodaOrg/joda-time
src/main/java/org/joda/time/format/DateTimeFormatter.java
DateTimeFormatter.printTo
public void printTo(StringBuffer buf, ReadablePartial partial) { try { printTo((Appendable) buf, partial); } catch (IOException ex) { // StringBuffer does not throw IOException } }
java
public void printTo(StringBuffer buf, ReadablePartial partial) { try { printTo((Appendable) buf, partial); } catch (IOException ex) { // StringBuffer does not throw IOException } }
[ "public", "void", "printTo", "(", "StringBuffer", "buf", ",", "ReadablePartial", "partial", ")", "{", "try", "{", "printTo", "(", "(", "Appendable", ")", "buf", ",", "partial", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "// StringBuffer do...
Prints a ReadablePartial. <p> Neither the override chronology nor the override zone are used by this method. @param buf the destination to format to, not null @param partial partial to format
[ "Prints", "a", "ReadablePartial", ".", "<p", ">", "Neither", "the", "override", "chronology", "nor", "the", "override", "zone", "are", "used", "by", "this", "method", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatter.java#L602-L608
deeplearning4j/deeplearning4j
nd4j/nd4j-common/src/main/java/org/nd4j/linalg/primitives/Atomic.java
Atomic.cas
public boolean cas(T expected, T newValue) { try { lock.writeLock().lock(); if (Objects.equals(value, expected)) { this.value = newValue; return true; } else return false; } finally { lock.writeLock().unlock(); } }
java
public boolean cas(T expected, T newValue) { try { lock.writeLock().lock(); if (Objects.equals(value, expected)) { this.value = newValue; return true; } else return false; } finally { lock.writeLock().unlock(); } }
[ "public", "boolean", "cas", "(", "T", "expected", ",", "T", "newValue", ")", "{", "try", "{", "lock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "if", "(", "Objects", ".", "equals", "(", "value", ",", "expected", ")", ")", "{", "this...
This method implements compare-and-swap @param expected @param newValue @return true if value was swapped, false otherwise
[ "This", "method", "implements", "compare", "-", "and", "-", "swap" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-common/src/main/java/org/nd4j/linalg/primitives/Atomic.java#L76-L88
pravega/pravega
common/src/main/java/io/pravega/common/util/btree/BTreeIndex.java
BTreeIndex.locatePage
private CompletableFuture<PageWrapper> locatePage(ByteArraySegment key, PageCollection pageCollection, TimeoutTimer timer) { // Verify the sought key has the expected length. Preconditions.checkArgument(key.getLength() == this.leafPageConfig.getKeyLength(), "Invalid key length."); // Sanity check that our pageCollection has a somewhat correct view of the data index state. It is OK for it to // think the index length is less than what it actually is (since a concurrent update may have increased it), but // it is not a good sign if it thinks it's longer than the actual length. Preconditions.checkArgument(pageCollection.getIndexLength() <= this.state.get().length, "Unexpected PageCollection.IndexLength."); if (this.state.get().rootPageOffset == PagePointer.NO_OFFSET && pageCollection.getCount() == 0) { // No data. Return an empty (leaf) page, which will serve as the root for now. return CompletableFuture.completedFuture(pageCollection.insert(PageWrapper.wrapNew(createEmptyLeafPage(), null, null))); } // Locate the page by searching on the Key (within the page). return locatePage(page -> getPagePointer(key, page), page -> !page.isIndexPage(), pageCollection, timer); }
java
private CompletableFuture<PageWrapper> locatePage(ByteArraySegment key, PageCollection pageCollection, TimeoutTimer timer) { // Verify the sought key has the expected length. Preconditions.checkArgument(key.getLength() == this.leafPageConfig.getKeyLength(), "Invalid key length."); // Sanity check that our pageCollection has a somewhat correct view of the data index state. It is OK for it to // think the index length is less than what it actually is (since a concurrent update may have increased it), but // it is not a good sign if it thinks it's longer than the actual length. Preconditions.checkArgument(pageCollection.getIndexLength() <= this.state.get().length, "Unexpected PageCollection.IndexLength."); if (this.state.get().rootPageOffset == PagePointer.NO_OFFSET && pageCollection.getCount() == 0) { // No data. Return an empty (leaf) page, which will serve as the root for now. return CompletableFuture.completedFuture(pageCollection.insert(PageWrapper.wrapNew(createEmptyLeafPage(), null, null))); } // Locate the page by searching on the Key (within the page). return locatePage(page -> getPagePointer(key, page), page -> !page.isIndexPage(), pageCollection, timer); }
[ "private", "CompletableFuture", "<", "PageWrapper", ">", "locatePage", "(", "ByteArraySegment", "key", ",", "PageCollection", "pageCollection", ",", "TimeoutTimer", "timer", ")", "{", "// Verify the sought key has the expected length.", "Preconditions", ".", "checkArgument", ...
Locates the Leaf Page that contains or should contain the given Key. @param key A ByteArraySegment that represents the Key to look up the Leaf Page for. @param pageCollection A PageCollection that contains already looked-up pages. Any newly looked up pages will be inserted in this instance as well. @param timer Timer for the operation. @return A CompletableFuture with a PageWrapper for the sought page.
[ "Locates", "the", "Leaf", "Page", "that", "contains", "or", "should", "contain", "the", "given", "Key", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/util/btree/BTreeIndex.java#L586-L602
radkovo/jStyleParser
src/main/java/cz/vutbr/web/domassign/DirectAnalyzer.java
DirectAnalyzer.getElementStyle
public NodeData getElementStyle(Element el, PseudoElementType pseudo, String media) { return getElementStyle(el, pseudo, new MediaSpec(media)); }
java
public NodeData getElementStyle(Element el, PseudoElementType pseudo, String media) { return getElementStyle(el, pseudo, new MediaSpec(media)); }
[ "public", "NodeData", "getElementStyle", "(", "Element", "el", ",", "PseudoElementType", "pseudo", ",", "String", "media", ")", "{", "return", "getElementStyle", "(", "el", ",", "pseudo", ",", "new", "MediaSpec", "(", "media", ")", ")", ";", "}" ]
Computes the style of an element with an eventual pseudo element for the given media. @param el The DOM element. @param pseudo A pseudo element that should be used for style computation or <code>null</code> if no pseudo element should be used (e.g. :after). @param media Used media name (e.g. "screen" or "all") @return The relevant declarations from the registered style sheets.
[ "Computes", "the", "style", "of", "an", "element", "with", "an", "eventual", "pseudo", "element", "for", "the", "given", "media", "." ]
train
https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/domassign/DirectAnalyzer.java#L70-L73
logic-ng/LogicNG
src/main/java/org/logicng/io/readers/FormulaReader.java
FormulaReader.readPropositionalFormula
public static Formula readPropositionalFormula(final String fileName, final FormulaFactory f) throws IOException, ParserException { return read(new File(fileName), new PropositionalParser(f)); }
java
public static Formula readPropositionalFormula(final String fileName, final FormulaFactory f) throws IOException, ParserException { return read(new File(fileName), new PropositionalParser(f)); }
[ "public", "static", "Formula", "readPropositionalFormula", "(", "final", "String", "fileName", ",", "final", "FormulaFactory", "f", ")", "throws", "IOException", ",", "ParserException", "{", "return", "read", "(", "new", "File", "(", "fileName", ")", ",", "new",...
Reads a given file and returns the contained propositional formula. @param fileName the file name @param f the formula factory @return the parsed formula @throws IOException if there was a problem reading the file @throws ParserException if there was a problem parsing the formula
[ "Reads", "a", "given", "file", "and", "returns", "the", "contained", "propositional", "formula", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/io/readers/FormulaReader.java#L68-L70
landawn/AbacusUtil
src/com/landawn/abacus/util/N.java
N.callUninterruptibly
public static <T> T callUninterruptibly(final long timeoutInMillis, final Try.LongFunction<T, InterruptedException> cmd) { N.checkArgNotNull(cmd); boolean interrupted = false; try { long remainingMillis = timeoutInMillis; final long sysMillis = System.currentTimeMillis(); final long end = remainingMillis >= Long.MAX_VALUE - sysMillis ? Long.MAX_VALUE : sysMillis + remainingMillis; while (true) { try { return cmd.apply(remainingMillis); } catch (InterruptedException e) { interrupted = true; remainingMillis = end - System.currentTimeMillis(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
java
public static <T> T callUninterruptibly(final long timeoutInMillis, final Try.LongFunction<T, InterruptedException> cmd) { N.checkArgNotNull(cmd); boolean interrupted = false; try { long remainingMillis = timeoutInMillis; final long sysMillis = System.currentTimeMillis(); final long end = remainingMillis >= Long.MAX_VALUE - sysMillis ? Long.MAX_VALUE : sysMillis + remainingMillis; while (true) { try { return cmd.apply(remainingMillis); } catch (InterruptedException e) { interrupted = true; remainingMillis = end - System.currentTimeMillis(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
[ "public", "static", "<", "T", ">", "T", "callUninterruptibly", "(", "final", "long", "timeoutInMillis", ",", "final", "Try", ".", "LongFunction", "<", "T", ",", "InterruptedException", ">", "cmd", ")", "{", "N", ".", "checkArgNotNull", "(", "cmd", ")", ";"...
Note: Copied from Google Guava under Apache License v2.0 <br /> <br /> If a thread is interrupted during such a call, the call continues to block until the result is available or the timeout elapses, and only then re-interrupts the thread. @param timeoutInMillis @param cmd @return
[ "Note", ":", "Copied", "from", "Google", "Guava", "under", "Apache", "License", "v2", ".", "0", "<br", "/", ">", "<br", "/", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L28069-L28092
pressgang-ccms/PressGangCCMSContentSpec
src/main/java/org/jboss/pressgang/ccms/contentspec/utils/ContentSpecUtilities.java
ContentSpecUtilities.getContentSpecRevisionsById
public static RevisionList getContentSpecRevisionsById(final ContentSpecProvider contentSpecProvider, final Integer csId) { final List<Revision> results = new ArrayList<Revision>(); final CollectionWrapper<ContentSpecWrapper> contentSpecRevisions = contentSpecProvider.getContentSpec(csId).getRevisions(); // Create the unique array from the revisions if (contentSpecRevisions != null && contentSpecRevisions.getItems() != null) { final List<ContentSpecWrapper> contentSpecRevs = contentSpecRevisions.getItems(); for (final ContentSpecWrapper contentSpecRev : contentSpecRevs) { Revision revision = new Revision(); revision.setRevision(contentSpecRev.getRevision()); revision.setDate(contentSpecRev.getLastModified()); results.add(revision); } Collections.sort(results, new EnversRevisionSort()); return new RevisionList(csId, "Content Specification", results); } else { return null; } }
java
public static RevisionList getContentSpecRevisionsById(final ContentSpecProvider contentSpecProvider, final Integer csId) { final List<Revision> results = new ArrayList<Revision>(); final CollectionWrapper<ContentSpecWrapper> contentSpecRevisions = contentSpecProvider.getContentSpec(csId).getRevisions(); // Create the unique array from the revisions if (contentSpecRevisions != null && contentSpecRevisions.getItems() != null) { final List<ContentSpecWrapper> contentSpecRevs = contentSpecRevisions.getItems(); for (final ContentSpecWrapper contentSpecRev : contentSpecRevs) { Revision revision = new Revision(); revision.setRevision(contentSpecRev.getRevision()); revision.setDate(contentSpecRev.getLastModified()); results.add(revision); } Collections.sort(results, new EnversRevisionSort()); return new RevisionList(csId, "Content Specification", results); } else { return null; } }
[ "public", "static", "RevisionList", "getContentSpecRevisionsById", "(", "final", "ContentSpecProvider", "contentSpecProvider", ",", "final", "Integer", "csId", ")", "{", "final", "List", "<", "Revision", ">", "results", "=", "new", "ArrayList", "<", "Revision", ">",...
/* Gets a list of Revision's from the CSProcessor database for a specific content spec
[ "/", "*", "Gets", "a", "list", "of", "Revision", "s", "from", "the", "CSProcessor", "database", "for", "a", "specific", "content", "spec" ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/ContentSpecUtilities.java#L320-L340
actorapp/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/view/ActorToolbar.java
ActorToolbar.colorizeToolbar
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) { final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN); for (int i = 0; i < toolbarView.getChildCount(); i++) { final View v = toolbarView.getChildAt(i); doColorizing(v, colorFilter, toolbarIconsColor); } //Step 3: Changing the color of title and subtitle. toolbarView.setTitleTextColor(toolbarIconsColor); toolbarView.setSubtitleTextColor(toolbarIconsColor); }
java
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) { final PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN); for (int i = 0; i < toolbarView.getChildCount(); i++) { final View v = toolbarView.getChildAt(i); doColorizing(v, colorFilter, toolbarIconsColor); } //Step 3: Changing the color of title and subtitle. toolbarView.setTitleTextColor(toolbarIconsColor); toolbarView.setSubtitleTextColor(toolbarIconsColor); }
[ "public", "static", "void", "colorizeToolbar", "(", "Toolbar", "toolbarView", ",", "int", "toolbarIconsColor", ",", "Activity", "activity", ")", "{", "final", "PorterDuffColorFilter", "colorFilter", "=", "new", "PorterDuffColorFilter", "(", "toolbarIconsColor", ",", "...
Use this method to colorize toolbar icons to the desired target color @param toolbarView toolbar view being colored @param toolbarIconsColor the target color of toolbar icons @param activity reference to activity needed to register observers
[ "Use", "this", "method", "to", "colorize", "toolbar", "icons", "to", "the", "desired", "target", "color" ]
train
https://github.com/actorapp/actor-platform/blob/5123c1584757c6eeea0ed2a0e7e043629871a0c6/actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/view/ActorToolbar.java#L64-L77
structr/structr
structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java
HtmlServlet.notFound
private Page notFound(final HttpServletResponse response, final SecurityContext securityContext) throws IOException, FrameworkException { final List<Page> errorPages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).and(StructrApp.key(Page.class, "showOnErrorCodes"), "404", false).getAsList(); for (final Page errorPage : errorPages) { if (isVisibleForSite(securityContext.getRequest(), errorPage)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return errorPage; } } response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; }
java
private Page notFound(final HttpServletResponse response, final SecurityContext securityContext) throws IOException, FrameworkException { final List<Page> errorPages = StructrApp.getInstance(securityContext).nodeQuery(Page.class).and(StructrApp.key(Page.class, "showOnErrorCodes"), "404", false).getAsList(); for (final Page errorPage : errorPages) { if (isVisibleForSite(securityContext.getRequest(), errorPage)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return errorPage; } } response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; }
[ "private", "Page", "notFound", "(", "final", "HttpServletResponse", "response", ",", "final", "SecurityContext", "securityContext", ")", "throws", "IOException", ",", "FrameworkException", "{", "final", "List", "<", "Page", ">", "errorPages", "=", "StructrApp", ".",...
Handle 404 Not Found First, search the first page which handles the 404. If none found, issue the container's 404 error. @param response @param securityContext @param renderContext @throws IOException @throws FrameworkException
[ "Handle", "404", "Not", "Found" ]
train
https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/servlet/HtmlServlet.java#L937-L954
tvesalainen/util
util/src/main/java/org/vesalainen/nio/file/attribute/UserAttrs.java
UserAttrs.setLongAttribute
public static final void setLongAttribute(Path path, String attribute, long value, LinkOption... options) throws IOException { attribute = attribute.startsWith("user:") ? attribute : "user:"+attribute; Files.setAttribute(path, attribute, Primitives.writeLong(value), options); }
java
public static final void setLongAttribute(Path path, String attribute, long value, LinkOption... options) throws IOException { attribute = attribute.startsWith("user:") ? attribute : "user:"+attribute; Files.setAttribute(path, attribute, Primitives.writeLong(value), options); }
[ "public", "static", "final", "void", "setLongAttribute", "(", "Path", "path", ",", "String", "attribute", ",", "long", "value", ",", "LinkOption", "...", "options", ")", "throws", "IOException", "{", "attribute", "=", "attribute", ".", "startsWith", "(", "\"us...
Set user-defined-attribute @param path @param attribute user:attribute name. user: can be omitted. @param value @param options @throws IOException
[ "Set", "user", "-", "defined", "-", "attribute" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/file/attribute/UserAttrs.java#L66-L70
segmentio/analytics-android
analytics/src/main/java/com/segment/analytics/QueueFile.java
QueueFile.ringRead
@Private void ringRead(int position, byte[] buffer, int offset, int count) throws IOException { position = wrapPosition(position); if (position + count <= fileLength) { raf.seek(position); raf.readFully(buffer, offset, count); } else { // The read overlaps the EOF. // # of bytes to read before the EOF. int beforeEof = fileLength - position; raf.seek(position); raf.readFully(buffer, offset, beforeEof); raf.seek(HEADER_LENGTH); raf.readFully(buffer, offset + beforeEof, count - beforeEof); } }
java
@Private void ringRead(int position, byte[] buffer, int offset, int count) throws IOException { position = wrapPosition(position); if (position + count <= fileLength) { raf.seek(position); raf.readFully(buffer, offset, count); } else { // The read overlaps the EOF. // # of bytes to read before the EOF. int beforeEof = fileLength - position; raf.seek(position); raf.readFully(buffer, offset, beforeEof); raf.seek(HEADER_LENGTH); raf.readFully(buffer, offset + beforeEof, count - beforeEof); } }
[ "@", "Private", "void", "ringRead", "(", "int", "position", ",", "byte", "[", "]", "buffer", ",", "int", "offset", ",", "int", "count", ")", "throws", "IOException", "{", "position", "=", "wrapPosition", "(", "position", ")", ";", "if", "(", "position", ...
Reads count bytes into buffer from file. Wraps if necessary. @param position in file to read from @param buffer to read into @param count # of bytes to read
[ "Reads", "count", "bytes", "into", "buffer", "from", "file", ".", "Wraps", "if", "necessary", "." ]
train
https://github.com/segmentio/analytics-android/blob/93c7d5bb09b593440a2347a6089db3e9f74012da/analytics/src/main/java/com/segment/analytics/QueueFile.java#L265-L280
lamydev/Android-Notification
core/src/zemin/notification/NotificationBoardCallback.java
NotificationBoardCallback.onRowViewAdded
public void onRowViewAdded(NotificationBoard board, RowView rowView, NotificationEntry entry) { if (DBG) Log.v(TAG, "onRowViewAdded - " + entry.ID); if (entry.hasActions()) { ArrayList<Action> actions = entry.getActions(); ViewGroup vg = (ViewGroup) rowView.findViewById(R.id.actions); vg.setVisibility(View.VISIBLE); vg = (ViewGroup) vg.getChildAt(0); final View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { Action act = (Action) view.getTag(); onClickActionView(act.entry, act, view); act.execute(view.getContext()); } }; for (int i = 0, count = actions.size(); i < count; i++) { Action act = actions.get(i); Button actionBtn = (Button) vg.getChildAt(i); actionBtn.setVisibility(View.VISIBLE); actionBtn.setTag(act); actionBtn.setText(act.title); actionBtn.setOnClickListener(onClickListener); actionBtn.setCompoundDrawablesWithIntrinsicBounds(act.icon, 0, 0, 0); } } }
java
public void onRowViewAdded(NotificationBoard board, RowView rowView, NotificationEntry entry) { if (DBG) Log.v(TAG, "onRowViewAdded - " + entry.ID); if (entry.hasActions()) { ArrayList<Action> actions = entry.getActions(); ViewGroup vg = (ViewGroup) rowView.findViewById(R.id.actions); vg.setVisibility(View.VISIBLE); vg = (ViewGroup) vg.getChildAt(0); final View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { Action act = (Action) view.getTag(); onClickActionView(act.entry, act, view); act.execute(view.getContext()); } }; for (int i = 0, count = actions.size(); i < count; i++) { Action act = actions.get(i); Button actionBtn = (Button) vg.getChildAt(i); actionBtn.setVisibility(View.VISIBLE); actionBtn.setTag(act); actionBtn.setText(act.title); actionBtn.setOnClickListener(onClickListener); actionBtn.setCompoundDrawablesWithIntrinsicBounds(act.icon, 0, 0, 0); } } }
[ "public", "void", "onRowViewAdded", "(", "NotificationBoard", "board", ",", "RowView", "rowView", ",", "NotificationEntry", "entry", ")", "{", "if", "(", "DBG", ")", "Log", ".", "v", "(", "TAG", ",", "\"onRowViewAdded - \"", "+", "entry", ".", "ID", ")", "...
Called when a row view is added to the board. @param board @param rowView @param entry
[ "Called", "when", "a", "row", "view", "is", "added", "to", "the", "board", "." ]
train
https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationBoardCallback.java#L113-L142
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java
CmsContainerpageHandler.changeTemplateContextManually
@SuppressWarnings("deprecation") public void changeTemplateContextManually(final String cookieName, final String value) { if (value != null) { Cookies.setCookie(cookieName, value, new Date(300, 0, 1), null, "/", false); } else { Cookies.removeCookie(cookieName, "/"); } Window.Location.reload(); }
java
@SuppressWarnings("deprecation") public void changeTemplateContextManually(final String cookieName, final String value) { if (value != null) { Cookies.setCookie(cookieName, value, new Date(300, 0, 1), null, "/", false); } else { Cookies.removeCookie(cookieName, "/"); } Window.Location.reload(); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "void", "changeTemplateContextManually", "(", "final", "String", "cookieName", ",", "final", "String", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "Cookies", ".", "setCookie", "...
Switches the template context.<p> @param cookieName the cookie name @param value the new template context
[ "Switches", "the", "template", "context", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L256-L265
phax/ph-masterdata
ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java
PostalCodeManager.isValidPostalCode
@Nonnull public ETriState isValidPostalCode (@Nullable final Locale aCountry, @Nullable final String sPostalCode) { final IPostalCodeCountry aPostalCountry = getPostalCountryOfCountry (aCountry); if (aPostalCountry == null) return ETriState.UNDEFINED; return ETriState.valueOf (aPostalCountry.isValidPostalCode (sPostalCode)); }
java
@Nonnull public ETriState isValidPostalCode (@Nullable final Locale aCountry, @Nullable final String sPostalCode) { final IPostalCodeCountry aPostalCountry = getPostalCountryOfCountry (aCountry); if (aPostalCountry == null) return ETriState.UNDEFINED; return ETriState.valueOf (aPostalCountry.isValidPostalCode (sPostalCode)); }
[ "@", "Nonnull", "public", "ETriState", "isValidPostalCode", "(", "@", "Nullable", "final", "Locale", "aCountry", ",", "@", "Nullable", "final", "String", "sPostalCode", ")", "{", "final", "IPostalCodeCountry", "aPostalCountry", "=", "getPostalCountryOfCountry", "(", ...
Check if the passed postal code is valid for the passed country. @param aCountry The country to check. May be <code>null</code>. @param sPostalCode The postal code to check. May be <code>null</code>. @return {@link ETriState#UNDEFINED} if no information for the passed country are present, {@link ETriState#TRUE} if the postal code is valid or {@link ETriState#FALSE} if the passed postal code is explicitly not valid for the passed country.
[ "Check", "if", "the", "passed", "postal", "code", "is", "valid", "for", "the", "passed", "country", "." ]
train
https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/postal/PostalCodeManager.java#L111-L118
aol/cyclops
cyclops/src/main/java/cyclops/companion/Functions.java
Functions.concatInts
public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> concatInts( ReactiveSeq<Integer> b){ return a->ReactiveSeq.fromSpliterator(IntStream.concat(a.mapToInt(i->i),b.mapToInt(i->i)).spliterator()); }
java
public static Function<? super ReactiveSeq<Integer>, ? extends ReactiveSeq<Integer>> concatInts( ReactiveSeq<Integer> b){ return a->ReactiveSeq.fromSpliterator(IntStream.concat(a.mapToInt(i->i),b.mapToInt(i->i)).spliterator()); }
[ "public", "static", "Function", "<", "?", "super", "ReactiveSeq", "<", "Integer", ">", ",", "?", "extends", "ReactiveSeq", "<", "Integer", ">", ">", "concatInts", "(", "ReactiveSeq", "<", "Integer", ">", "b", ")", "{", "return", "a", "->", "ReactiveSeq", ...
/* Fluent integer concat operation using primitive types e.g. <pre> {@code import static cyclops.ReactiveSeq.concatInts; ReactiveSeq.ofInts(1,2,3) .to(concatInts(ReactiveSeq.range(5,10))); //[1,2,3,5,6,7,8,9] } </pre>
[ "/", "*", "Fluent", "integer", "concat", "operation", "using", "primitive", "types", "e", ".", "g", ".", "<pre", ">", "{", "@code", "import", "static", "cyclops", ".", "ReactiveSeq", ".", "concatInts", ";" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/cyclops/companion/Functions.java#L316-L318
Stratio/stratio-cassandra
src/java/org/apache/cassandra/io/sstable/IndexHelper.java
IndexHelper.indexFor
public static int indexFor(Composite name, List<IndexInfo> indexList, CType comparator, boolean reversed, int lastIndex) { if (name.isEmpty()) return lastIndex >= 0 ? lastIndex : reversed ? indexList.size() - 1 : 0; if (lastIndex >= indexList.size()) return -1; IndexInfo target = new IndexInfo(name, name, 0, 0); /* Take the example from the unit test, and say your index looks like this: [0..5][10..15][20..25] and you look for the slice [13..17]. When doing forward slice, we we doing a binary search comparing 13 (the start of the query) to the lastName part of the index slot. You'll end up with the "first" slot, going from left to right, that may contain the start. When doing a reverse slice, we do the same thing, only using as a start column the end of the query, i.e. 17 in this example, compared to the firstName part of the index slots. bsearch will give us the first slot where firstName > start ([20..25] here), so we subtract an extra one to get the slot just before. */ int startIdx = 0; List<IndexInfo> toSearch = indexList; if (lastIndex >= 0) { if (reversed) { toSearch = indexList.subList(0, lastIndex + 1); } else { startIdx = lastIndex; toSearch = indexList.subList(lastIndex, indexList.size()); } } int index = Collections.binarySearch(toSearch, target, getComparator(comparator, reversed)); return startIdx + (index < 0 ? -index - (reversed ? 2 : 1) : index); }
java
public static int indexFor(Composite name, List<IndexInfo> indexList, CType comparator, boolean reversed, int lastIndex) { if (name.isEmpty()) return lastIndex >= 0 ? lastIndex : reversed ? indexList.size() - 1 : 0; if (lastIndex >= indexList.size()) return -1; IndexInfo target = new IndexInfo(name, name, 0, 0); /* Take the example from the unit test, and say your index looks like this: [0..5][10..15][20..25] and you look for the slice [13..17]. When doing forward slice, we we doing a binary search comparing 13 (the start of the query) to the lastName part of the index slot. You'll end up with the "first" slot, going from left to right, that may contain the start. When doing a reverse slice, we do the same thing, only using as a start column the end of the query, i.e. 17 in this example, compared to the firstName part of the index slots. bsearch will give us the first slot where firstName > start ([20..25] here), so we subtract an extra one to get the slot just before. */ int startIdx = 0; List<IndexInfo> toSearch = indexList; if (lastIndex >= 0) { if (reversed) { toSearch = indexList.subList(0, lastIndex + 1); } else { startIdx = lastIndex; toSearch = indexList.subList(lastIndex, indexList.size()); } } int index = Collections.binarySearch(toSearch, target, getComparator(comparator, reversed)); return startIdx + (index < 0 ? -index - (reversed ? 2 : 1) : index); }
[ "public", "static", "int", "indexFor", "(", "Composite", "name", ",", "List", "<", "IndexInfo", ">", "indexList", ",", "CType", "comparator", ",", "boolean", "reversed", ",", "int", "lastIndex", ")", "{", "if", "(", "name", ".", "isEmpty", "(", ")", ")",...
The index of the IndexInfo in which a scan starting with @name should begin. @param name name of the index @param indexList list of the indexInfo objects @param comparator comparator type @param reversed is name reversed @return int index
[ "The", "index", "of", "the", "IndexInfo", "in", "which", "a", "scan", "starting", "with", "@name", "should", "begin", "." ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/io/sstable/IndexHelper.java#L112-L150
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/de/julielab/jules/types/OntClassMention.java
OntClassMention.setSemanticTypes
public void setSemanticTypes(int i, String v) { if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_semanticTypes == null) jcasType.jcas.throwFeatMissing("semanticTypes", "de.julielab.jules.types.OntClassMention"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i); jcasType.ll_cas.ll_setStringArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i, v);}
java
public void setSemanticTypes(int i, String v) { if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_semanticTypes == null) jcasType.jcas.throwFeatMissing("semanticTypes", "de.julielab.jules.types.OntClassMention"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i); jcasType.ll_cas.ll_setStringArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((OntClassMention_Type)jcasType).casFeatCode_semanticTypes), i, v);}
[ "public", "void", "setSemanticTypes", "(", "int", "i", ",", "String", "v", ")", "{", "if", "(", "OntClassMention_Type", ".", "featOkTst", "&&", "(", "(", "OntClassMention_Type", ")", "jcasType", ")", ".", "casFeat_semanticTypes", "==", "null", ")", "jcasType",...
indexed setter for semanticTypes - sets an indexed value - Names or IDs of associated semantic types. @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "semanticTypes", "-", "sets", "an", "indexed", "value", "-", "Names", "or", "IDs", "of", "associated", "semantic", "types", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/OntClassMention.java#L183-L187
michael-rapp/AndroidPreferenceActivity
example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java
AppearancePreferenceFragment.createBreadCrumbElevationChangeListener
private OnPreferenceChangeListener createBreadCrumbElevationChangeListener() { return new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { int elevation = Integer.valueOf((String) newValue); ((PreferenceActivity) getActivity()).setBreadCrumbElevation(elevation); return true; } }; }
java
private OnPreferenceChangeListener createBreadCrumbElevationChangeListener() { return new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { int elevation = Integer.valueOf((String) newValue); ((PreferenceActivity) getActivity()).setBreadCrumbElevation(elevation); return true; } }; }
[ "private", "OnPreferenceChangeListener", "createBreadCrumbElevationChangeListener", "(", ")", "{", "return", "new", "OnPreferenceChangeListener", "(", ")", "{", "@", "Override", "public", "boolean", "onPreferenceChange", "(", "Preference", "preference", ",", "Object", "ne...
Creates and returns a listener, which allows to adapt the elevation of the bread crumbs, when the value of the corresponding preference has been changed. @return The listener, which has been created, as an instance of the type {@link OnPreferenceChangeListener}
[ "Creates", "and", "returns", "a", "listener", "which", "allows", "to", "adapt", "the", "elevation", "of", "the", "bread", "crumbs", "when", "the", "value", "of", "the", "corresponding", "preference", "has", "been", "changed", "." ]
train
https://github.com/michael-rapp/AndroidPreferenceActivity/blob/0fcde73815b4b3bf6bcb36acd3d5733e301bbba5/example/src/main/java/de/mrapp/android/preference/activity/example/fragment/AppearancePreferenceFragment.java#L128-L139
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/WriterUtils.java
WriterUtils.getWriterFilePath
public static Path getWriterFilePath(State state, int numBranches, int branchId) { if (state.contains( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId))) { return new Path(state.getProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId))); } switch (getWriterFilePathType(state)) { case NAMESPACE_TABLE: return getNamespaceTableWriterFilePath(state); case TABLENAME: return WriterUtils.getTableNameWriterFilePath(state); default: return WriterUtils.getDefaultWriterFilePath(state, numBranches, branchId); } }
java
public static Path getWriterFilePath(State state, int numBranches, int branchId) { if (state.contains( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId))) { return new Path(state.getProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PATH, numBranches, branchId))); } switch (getWriterFilePathType(state)) { case NAMESPACE_TABLE: return getNamespaceTableWriterFilePath(state); case TABLENAME: return WriterUtils.getTableNameWriterFilePath(state); default: return WriterUtils.getDefaultWriterFilePath(state, numBranches, branchId); } }
[ "public", "static", "Path", "getWriterFilePath", "(", "State", "state", ",", "int", "numBranches", ",", "int", "branchId", ")", "{", "if", "(", "state", ".", "contains", "(", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "ConfigurationKeys", ".", "W...
Get the {@link Path} corresponding the the relative file path for a given {@link org.apache.gobblin.writer.DataWriter}. This method retrieves the value of {@link ConfigurationKeys#WRITER_FILE_PATH} from the given {@link State}. It also constructs the default value of the {@link ConfigurationKeys#WRITER_FILE_PATH} if not is not specified in the given {@link State}. @param state is the {@link State} corresponding to a specific {@link org.apache.gobblin.writer.DataWriter}. @param numBranches is the total number of branches for the given {@link State}. @param branchId is the id for the specific branch that the {{@link org.apache.gobblin.writer.DataWriter} will write to. @return a {@link Path} specifying the relative directory where the {@link org.apache.gobblin.writer.DataWriter} will write to.
[ "Get", "the", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/WriterUtils.java#L155-L170
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java
KeyChainGroup.freshAddress
public Address freshAddress(KeyChain.KeyPurpose purpose, Script.ScriptType outputScriptType, long keyRotationTimeSecs) { DeterministicKeyChain chain = getActiveKeyChain(outputScriptType, keyRotationTimeSecs); return Address.fromKey(params, chain.getKey(purpose), outputScriptType); }
java
public Address freshAddress(KeyChain.KeyPurpose purpose, Script.ScriptType outputScriptType, long keyRotationTimeSecs) { DeterministicKeyChain chain = getActiveKeyChain(outputScriptType, keyRotationTimeSecs); return Address.fromKey(params, chain.getKey(purpose), outputScriptType); }
[ "public", "Address", "freshAddress", "(", "KeyChain", ".", "KeyPurpose", "purpose", ",", "Script", ".", "ScriptType", "outputScriptType", ",", "long", "keyRotationTimeSecs", ")", "{", "DeterministicKeyChain", "chain", "=", "getActiveKeyChain", "(", "outputScriptType", ...
<p>Returns a fresh address for a given {@link KeyChain.KeyPurpose} and of a given {@link Script.ScriptType}.</p> <p>This method is meant for when you really need a fallback address. Normally, you should be using {@link #freshAddress(KeyChain.KeyPurpose)} or {@link #currentAddress(KeyChain.KeyPurpose)}.</p>
[ "<p", ">", "Returns", "a", "fresh", "address", "for", "a", "given", "{" ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L368-L371
OpenLiberty/open-liberty
dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/helpers/MBeanRoutedNotificationHelper.java
MBeanRoutedNotificationHelper.postRoutedNotificationListenerRegistrationEvent
private void postRoutedNotificationListenerRegistrationEvent(String operation, NotificationTargetInformation nti) { Map<String, Object> props = createListenerRegistrationEvent(operation, nti); safePostEvent(new Event(REGISTER_JMX_NOTIFICATION_LISTENER_TOPIC, props)); }
java
private void postRoutedNotificationListenerRegistrationEvent(String operation, NotificationTargetInformation nti) { Map<String, Object> props = createListenerRegistrationEvent(operation, nti); safePostEvent(new Event(REGISTER_JMX_NOTIFICATION_LISTENER_TOPIC, props)); }
[ "private", "void", "postRoutedNotificationListenerRegistrationEvent", "(", "String", "operation", ",", "NotificationTargetInformation", "nti", ")", "{", "Map", "<", "String", ",", "Object", ">", "props", "=", "createListenerRegistrationEvent", "(", "operation", ",", "nt...
Post an event to EventAdmin, instructing the Target-Client Manager to register or unregister a listener for a given target.
[ "Post", "an", "event", "to", "EventAdmin", "instructing", "the", "Target", "-", "Client", "Manager", "to", "register", "or", "unregister", "a", "listener", "for", "a", "given", "target", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.server.rest/src/com/ibm/ws/jmx/connector/server/rest/helpers/MBeanRoutedNotificationHelper.java#L231-L234
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/cache/JMapperCache.java
JMapperCache.getRelationalMapper
public static <T> IRelationalJMapper<T> getRelationalMapper(final Class<T> configuredClass, JMapperAPI jmapperAPI){ return getRelationalMapper(configuredClass, jmapperAPI.toXStream().toString()); }
java
public static <T> IRelationalJMapper<T> getRelationalMapper(final Class<T> configuredClass, JMapperAPI jmapperAPI){ return getRelationalMapper(configuredClass, jmapperAPI.toXStream().toString()); }
[ "public", "static", "<", "T", ">", "IRelationalJMapper", "<", "T", ">", "getRelationalMapper", "(", "final", "Class", "<", "T", ">", "configuredClass", ",", "JMapperAPI", "jmapperAPI", ")", "{", "return", "getRelationalMapper", "(", "configuredClass", ",", "jmap...
Returns an instance of JMapper from cache if exists, in alternative a new instance. <br>Takes in input the configured Class and the configuration in API format. @param configuredClass configured class @param jmapperAPI the configuration @param <T> Mapped class type @return the mapper instance
[ "Returns", "an", "instance", "of", "JMapper", "from", "cache", "if", "exists", "in", "alternative", "a", "new", "instance", ".", "<br", ">", "Takes", "in", "input", "the", "configured", "Class", "and", "the", "configuration", "in", "API", "format", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/cache/JMapperCache.java#L166-L168
kmi/iserve
iserve-elda/src/main/java/uk/ac/open/kmi/iserve/elda/EldaRouterRestletSupport.java
EldaRouterRestletSupport.expiresAtAsRFC1123
public static String expiresAtAsRFC1123(long expiresAt) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(expiresAt); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String result = dateFormat.format(c.getTime()); // System.err.println( ">> expires (RFC): " + result ); // long delta = expiresAt - System.currentTimeMillis(); // System.err.println( ">> expires in " + (delta/1000) + "s" ); return result; }
java
public static String expiresAtAsRFC1123(long expiresAt) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(expiresAt); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String result = dateFormat.format(c.getTime()); // System.err.println( ">> expires (RFC): " + result ); // long delta = expiresAt - System.currentTimeMillis(); // System.err.println( ">> expires in " + (delta/1000) + "s" ); return result; }
[ "public", "static", "String", "expiresAtAsRFC1123", "(", "long", "expiresAt", ")", "{", "Calendar", "c", "=", "Calendar", ".", "getInstance", "(", ")", ";", "c", ".", "setTimeInMillis", "(", "expiresAt", ")", ";", "SimpleDateFormat", "dateFormat", "=", "new", ...
expiresAt (date/time in milliseconds) as an RFC1123 date/time string suitable for use in an HTTP header.
[ "expiresAt", "(", "date", "/", "time", "in", "milliseconds", ")", "as", "an", "RFC1123", "date", "/", "time", "string", "suitable", "for", "use", "in", "an", "HTTP", "header", "." ]
train
https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-elda/src/main/java/uk/ac/open/kmi/iserve/elda/EldaRouterRestletSupport.java#L217-L229
pwall567/jsonutil
src/main/java/net/pwall/json/JSON.java
JSON.parseArray
public static JSONArray parseArray(InputStream is, Charset charSet) throws IOException { return (JSONArray)parse(is, charSet); }
java
public static JSONArray parseArray(InputStream is, Charset charSet) throws IOException { return (JSONArray)parse(is, charSet); }
[ "public", "static", "JSONArray", "parseArray", "(", "InputStream", "is", ",", "Charset", "charSet", ")", "throws", "IOException", "{", "return", "(", "JSONArray", ")", "parse", "(", "is", ",", "charSet", ")", ";", "}" ]
Parse a sequence of characters from an {@link InputStream} as a JSON array, specifying the character set. @param is the {@link InputStream} @param charSet the character set @return the JSON array @throws JSONException if the stream does not contain a valid JSON value @throws IOException on any I/O errors @throws ClassCastException if the value is not an array
[ "Parse", "a", "sequence", "of", "characters", "from", "an", "{", "@link", "InputStream", "}", "as", "a", "JSON", "array", "specifying", "the", "character", "set", "." ]
train
https://github.com/pwall567/jsonutil/blob/dd5960b9b0bcc9acfe6c52b884fffd9ee5f422fe/src/main/java/net/pwall/json/JSON.java#L377-L379
apache/spark
core/src/main/java/org/apache/spark/shuffle/sort/ShuffleInMemorySorter.java
ShuffleInMemorySorter.insertRecord
public void insertRecord(long recordPointer, int partitionId) { if (!hasSpaceForAnotherRecord()) { throw new IllegalStateException("There is no space for new record"); } array.set(pos, PackedRecordPointer.packPointer(recordPointer, partitionId)); pos++; }
java
public void insertRecord(long recordPointer, int partitionId) { if (!hasSpaceForAnotherRecord()) { throw new IllegalStateException("There is no space for new record"); } array.set(pos, PackedRecordPointer.packPointer(recordPointer, partitionId)); pos++; }
[ "public", "void", "insertRecord", "(", "long", "recordPointer", ",", "int", "partitionId", ")", "{", "if", "(", "!", "hasSpaceForAnotherRecord", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"There is no space for new record\"", ")", ";", "}"...
Inserts a record to be sorted. @param recordPointer a pointer to the record, encoded by the task memory manager. Due to certain pointer compression techniques used by the sorter, the sort can only operate on pointers that point to locations in the first {@link PackedRecordPointer#MAXIMUM_PAGE_SIZE_BYTES} bytes of a data page. @param partitionId the partition id, which must be less than or equal to {@link PackedRecordPointer#MAXIMUM_PARTITION_ID}.
[ "Inserts", "a", "record", "to", "be", "sorted", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/core/src/main/java/org/apache/spark/shuffle/sort/ShuffleInMemorySorter.java#L146-L152
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.readXMLFragment
public static DocumentFragment readXMLFragment(String file) throws IOException, SAXException, ParserConfigurationException { return readXMLFragment(file, false); }
java
public static DocumentFragment readXMLFragment(String file) throws IOException, SAXException, ParserConfigurationException { return readXMLFragment(file, false); }
[ "public", "static", "DocumentFragment", "readXMLFragment", "(", "String", "file", ")", "throws", "IOException", ",", "SAXException", ",", "ParserConfigurationException", "{", "return", "readXMLFragment", "(", "file", ",", "false", ")", ";", "}" ]
Read an XML fragment from an XML file. The XML file is well-formed. It means that the fragment will contains a single element: the root element within the input file. @param file is the file to read @return the fragment from the {@code file}. @throws IOException if the stream cannot be read. @throws SAXException if the stream does not contains valid XML data. @throws ParserConfigurationException if the parser cannot be configured.
[ "Read", "an", "XML", "fragment", "from", "an", "XML", "file", ".", "The", "XML", "file", "is", "well", "-", "formed", ".", "It", "means", "that", "the", "fragment", "will", "contains", "a", "single", "element", ":", "the", "root", "element", "within", ...
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L2101-L2103
OpenLiberty/open-liberty
dev/com.ibm.ws.security.client/src/com/ibm/ws/security/client/internal/jaas/JAASClientConfigurationImpl.java
JAASClientConfigurationImpl.createAppConfigurationEntry
public AppConfigurationEntry createAppConfigurationEntry(JAASLoginModuleConfig loginModule, String loginContextEntryName) { String loginModuleClassName = loginModule.getClassName(); LoginModuleControlFlag controlFlag = loginModule.getControlFlag(); Map<String, Object> options = new HashMap<String, Object>(); options.putAll(loginModule.getOptions()); if (JaasLoginConfigConstants.APPLICATION_WSLOGIN.equals(loginContextEntryName)) { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, true); } else { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, false); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "loginModuleClassName: " + loginModuleClassName + " options: " + options.toString() + " controlFlag: " + controlFlag.toString()); } AppConfigurationEntry loginModuleEntry = new AppConfigurationEntry(loginModuleClassName, controlFlag, options); return loginModuleEntry; }
java
public AppConfigurationEntry createAppConfigurationEntry(JAASLoginModuleConfig loginModule, String loginContextEntryName) { String loginModuleClassName = loginModule.getClassName(); LoginModuleControlFlag controlFlag = loginModule.getControlFlag(); Map<String, Object> options = new HashMap<String, Object>(); options.putAll(loginModule.getOptions()); if (JaasLoginConfigConstants.APPLICATION_WSLOGIN.equals(loginContextEntryName)) { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, true); } else { options.put(WAS_IGNORE_CLIENT_CONTAINER_DD, false); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "loginModuleClassName: " + loginModuleClassName + " options: " + options.toString() + " controlFlag: " + controlFlag.toString()); } AppConfigurationEntry loginModuleEntry = new AppConfigurationEntry(loginModuleClassName, controlFlag, options); return loginModuleEntry; }
[ "public", "AppConfigurationEntry", "createAppConfigurationEntry", "(", "JAASLoginModuleConfig", "loginModule", ",", "String", "loginContextEntryName", ")", "{", "String", "loginModuleClassName", "=", "loginModule", ".", "getClassName", "(", ")", ";", "LoginModuleControlFlag",...
Create an AppConfigurationEntry object for the given JAAS login module @param loginModule the JAAS login module @param loginContextEntryName the JAAS login context entry name referencing the login module @return the AppConfigurationEntry object @throws IllegalArgumentException if loginModuleName is null, if LoginModuleName has a length of 0, if controlFlag is not either REQUIRED, REQUISITE, SUFFICIENT or OPTIONAL, or if options is null.
[ "Create", "an", "AppConfigurationEntry", "object", "for", "the", "given", "JAAS", "login", "module" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.client/src/com/ibm/ws/security/client/internal/jaas/JAASClientConfigurationImpl.java#L122-L139
ical4j/ical4j
src/main/java/net/fortuna/ical4j/validate/PropertyValidator.java
PropertyValidator.assertNone
public void assertNone(final String propertyName, final PropertyList properties) throws ValidationException { if (properties.getProperty(propertyName) != null) { throw new ValidationException(ASSERT_NONE_MESSAGE, new Object[] {propertyName}); } }
java
public void assertNone(final String propertyName, final PropertyList properties) throws ValidationException { if (properties.getProperty(propertyName) != null) { throw new ValidationException(ASSERT_NONE_MESSAGE, new Object[] {propertyName}); } }
[ "public", "void", "assertNone", "(", "final", "String", "propertyName", ",", "final", "PropertyList", "properties", ")", "throws", "ValidationException", "{", "if", "(", "properties", ".", "getProperty", "(", "propertyName", ")", "!=", "null", ")", "{", "throw",...
Ensure a property doesn't occur in the specified list. @param propertyName the name of a property @param properties a list of properties @throws ValidationException thrown when the specified property is found in the list of properties
[ "Ensure", "a", "property", "doesn", "t", "occur", "in", "the", "specified", "list", "." ]
train
https://github.com/ical4j/ical4j/blob/7ac4bd1ce2bb2e0a2906fb69a56fbd2d9d974156/src/main/java/net/fortuna/ical4j/validate/PropertyValidator.java#L122-L126
moparisthebest/beehive
beehive-netui-compiler/src/main/java/org/apache/beehive/netui/compiler/CompilerUtils.java
CompilerUtils.assertAnnotationValue
private static AnnotationValue assertAnnotationValue( Declaration element, String annotationName, String valueName, boolean defaultIsNull ) { AnnotationInstance ann = getAnnotation( element, annotationName ); if ( ann == null ) { return null; } else { return getAnnotationValue( ann, valueName, defaultIsNull ); } }
java
private static AnnotationValue assertAnnotationValue( Declaration element, String annotationName, String valueName, boolean defaultIsNull ) { AnnotationInstance ann = getAnnotation( element, annotationName ); if ( ann == null ) { return null; } else { return getAnnotationValue( ann, valueName, defaultIsNull ); } }
[ "private", "static", "AnnotationValue", "assertAnnotationValue", "(", "Declaration", "element", ",", "String", "annotationName", ",", "String", "valueName", ",", "boolean", "defaultIsNull", ")", "{", "AnnotationInstance", "ann", "=", "getAnnotation", "(", "element", "...
If the given annotation exists, assert that the given member is not null</code>, and return it; otherwise, if the given annotation does not exist, return null</code>.
[ "If", "the", "given", "annotation", "exists", "assert", "that", "the", "given", "member", "is", "not", "null<", "/", "code", ">", "and", "return", "it", ";", "otherwise", "if", "the", "given", "annotation", "does", "not", "exist", "return", "null<", "/", ...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-compiler/src/main/java/org/apache/beehive/netui/compiler/CompilerUtils.java#L104-L117
Unicon/cas-addons
src/main/java/net/unicon/cas/addons/authentication/strong/oath/totp/TOTP.java
TOTP.hmacSha
private static byte[] hmacSha(String crypto, byte[] keyBytes, byte[] text) { try { Mac hmac; hmac = Mac.getInstance(crypto); SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } }
java
private static byte[] hmacSha(String crypto, byte[] keyBytes, byte[] text) { try { Mac hmac; hmac = Mac.getInstance(crypto); SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } }
[ "private", "static", "byte", "[", "]", "hmacSha", "(", "String", "crypto", ",", "byte", "[", "]", "keyBytes", ",", "byte", "[", "]", "text", ")", "{", "try", "{", "Mac", "hmac", ";", "hmac", "=", "Mac", ".", "getInstance", "(", "crypto", ")", ";", ...
This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash algorithm as a parameter. @param crypto : the crypto algorithm (HmacSHA1, HmacSHA256, HmacSHA512) @param keyBytes : the bytes to use for the HMAC key @param text : the message or text to be authenticated
[ "This", "method", "uses", "the", "JCE", "to", "provide", "the", "crypto", "algorithm", ".", "HMAC", "computes", "a", "Hashed", "Message", "Authentication", "Code", "with", "the", "crypto", "hash", "algorithm", "as", "a", "parameter", "." ]
train
https://github.com/Unicon/cas-addons/blob/9af2d4896e02d30622acec638539bfc41f45e480/src/main/java/net/unicon/cas/addons/authentication/strong/oath/totp/TOTP.java#L35-L45