repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnection.java
PresentsConnection.handleDatagram
public void handleDatagram (InetSocketAddress source, DatagramChannel channel, ByteBuffer buf, long when) { // lazily create our various bits and bobs if (_digest == null) { try { _digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { log.warning("Missing MD5 algorithm."); return; } _sequencer = _pcmgr.createDatagramSequencer(); } // verify the hash buf.position(12); _digest.update(buf); byte[] hash = _digest.digest(_datagramSecret); buf.position(4); for (int ii = 0; ii < 8; ii++) { if (hash[ii] != buf.get()) { log.warning("Datagram failed hash check", "id", _connectionId, "source", source); return; } } // update our target address _datagramAddress = source; _datagramChannel = channel; // read the contents through the sequencer try { Message msg = _sequencer.readDatagram(); if (msg == null) { return; // received out of order } msg.received = when; _handler.handleMessage(msg); } catch (ClassNotFoundException cnfe) { log.warning("Error reading datagram", "error", cnfe); } catch (IOException ioe) { log.warning("Error reading datagram", "error", ioe); } }
java
public void handleDatagram (InetSocketAddress source, DatagramChannel channel, ByteBuffer buf, long when) { // lazily create our various bits and bobs if (_digest == null) { try { _digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { log.warning("Missing MD5 algorithm."); return; } _sequencer = _pcmgr.createDatagramSequencer(); } // verify the hash buf.position(12); _digest.update(buf); byte[] hash = _digest.digest(_datagramSecret); buf.position(4); for (int ii = 0; ii < 8; ii++) { if (hash[ii] != buf.get()) { log.warning("Datagram failed hash check", "id", _connectionId, "source", source); return; } } // update our target address _datagramAddress = source; _datagramChannel = channel; // read the contents through the sequencer try { Message msg = _sequencer.readDatagram(); if (msg == null) { return; // received out of order } msg.received = when; _handler.handleMessage(msg); } catch (ClassNotFoundException cnfe) { log.warning("Error reading datagram", "error", cnfe); } catch (IOException ioe) { log.warning("Error reading datagram", "error", ioe); } }
[ "public", "void", "handleDatagram", "(", "InetSocketAddress", "source", ",", "DatagramChannel", "channel", ",", "ByteBuffer", "buf", ",", "long", "when", ")", "{", "// lazily create our various bits and bobs", "if", "(", "_digest", "==", "null", ")", "{", "try", "...
Processes a datagram sent to this connection.
[ "Processes", "a", "datagram", "sent", "to", "this", "connection", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnection.java#L165-L210
train
threerings/narya
core/src/main/java/com/threerings/presents/server/net/PresentsConnection.java
PresentsConnection.inheritStreams
protected void inheritStreams (PresentsConnection other) { _fin = other._fin; _oin = other._oin; _oout = other._oout; if (_loader != null) { _oin.setClassLoader(_loader); } }
java
protected void inheritStreams (PresentsConnection other) { _fin = other._fin; _oin = other._oin; _oout = other._oout; if (_loader != null) { _oin.setClassLoader(_loader); } }
[ "protected", "void", "inheritStreams", "(", "PresentsConnection", "other", ")", "{", "_fin", "=", "other", ".", "_fin", ";", "_oin", "=", "other", ".", "_oin", ";", "_oout", "=", "other", ".", "_oout", ";", "if", "(", "_loader", "!=", "null", ")", "{",...
Instructs this connection to inherit its streams from the supplied connection object. This is called by the connection manager when the time comes to pass streams from the authing connection to the running connection.
[ "Instructs", "this", "connection", "to", "inherit", "its", "streams", "from", "the", "supplied", "connection", "object", ".", "This", "is", "called", "by", "the", "connection", "manager", "when", "the", "time", "comes", "to", "pass", "streams", "from", "the", ...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/net/PresentsConnection.java#L287-L295
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.setDefaultAccessController
public void setDefaultAccessController (AccessController controller) { AccessController oldDefault = _defaultController; _defaultController = controller; // switch all objects from the old default (null, usually) to the new default. for (DObject obj : _objects.values()) { if (oldDefault == obj.getAccessController()) { obj.setAccessController(controller); } } }
java
public void setDefaultAccessController (AccessController controller) { AccessController oldDefault = _defaultController; _defaultController = controller; // switch all objects from the old default (null, usually) to the new default. for (DObject obj : _objects.values()) { if (oldDefault == obj.getAccessController()) { obj.setAccessController(controller); } } }
[ "public", "void", "setDefaultAccessController", "(", "AccessController", "controller", ")", "{", "AccessController", "oldDefault", "=", "_defaultController", ";", "_defaultController", "=", "controller", ";", "// switch all objects from the old default (null, usually) to the new de...
Sets up an access controller that will be provided to any distributed objects created on the server. The controllers can subsequently be overridden if desired, but a default controller is useful for implementing basic access control policies.
[ "Sets", "up", "an", "access", "controller", "that", "will", "be", "provided", "to", "any", "distributed", "objects", "created", "on", "the", "server", ".", "The", "controllers", "can", "subsequently", "be", "overridden", "if", "desired", "but", "a", "default",...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L152-L163
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.clearProxyObject
public void clearProxyObject (int origObjectId, DObject object) { if (_proxies.remove(object.getOid()) == null) { log.warning("Missing proxy mapping for cleared proxy", "ooid", origObjectId); } _objects.remove(object.getOid()); }
java
public void clearProxyObject (int origObjectId, DObject object) { if (_proxies.remove(object.getOid()) == null) { log.warning("Missing proxy mapping for cleared proxy", "ooid", origObjectId); } _objects.remove(object.getOid()); }
[ "public", "void", "clearProxyObject", "(", "int", "origObjectId", ",", "DObject", "object", ")", "{", "if", "(", "_proxies", ".", "remove", "(", "object", ".", "getOid", "(", ")", ")", "==", "null", ")", "{", "log", ".", "warning", "(", "\"Missing proxy ...
Clears a proxy object reference from our local distributed object space. This merely removes it from our internal tables, the caller is responsible for coordinating the deregistration of the object with the proxying client.
[ "Clears", "a", "proxy", "object", "reference", "from", "our", "local", "distributed", "object", "space", ".", "This", "merely", "removes", "it", "from", "our", "internal", "tables", "the", "caller", "is", "responsible", "for", "coordinating", "the", "deregistrat...
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L186-L192
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.getStats
public Stats getStats (boolean snapshot) { if (snapshot) { _recent = _current; _current = new Stats(); _current.maxQueueSize = _evqueue.size(); } return _recent; }
java
public Stats getStats (boolean snapshot) { if (snapshot) { _recent = _current; _current = new Stats(); _current.maxQueueSize = _evqueue.size(); } return _recent; }
[ "public", "Stats", "getStats", "(", "boolean", "snapshot", ")", "{", "if", "(", "snapshot", ")", "{", "_recent", "=", "_current", ";", "_current", "=", "new", "Stats", "(", ")", ";", "_current", ".", "maxQueueSize", "=", "_evqueue", ".", "size", "(", "...
Returns a recent snapshot of runtime statistics tracked by the distributed object manager. @param snapshot if true, the current stats will be snapshotted and reset and the new snapshot will be returned. If false, the previous snapshot will be returned. If no snapshot has ever been taken, the current stats that have been accumulting since the JVM start will be returned.
[ "Returns", "a", "recent", "snapshot", "of", "runtime", "statistics", "tracked", "by", "the", "distributed", "object", "manager", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L311-L319
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.run
public void run () { log.info("DOMGR running."); // make a note of the thread that's processing events synchronized (this) { _dobjThread = Thread.currentThread(); } while (isRunning()) { // pop the next unit off the queue and process it processUnit(_evqueue.get()); } log.info("DOMGR exited."); }
java
public void run () { log.info("DOMGR running."); // make a note of the thread that's processing events synchronized (this) { _dobjThread = Thread.currentThread(); } while (isRunning()) { // pop the next unit off the queue and process it processUnit(_evqueue.get()); } log.info("DOMGR exited."); }
[ "public", "void", "run", "(", ")", "{", "log", ".", "info", "(", "\"DOMGR running.\"", ")", ";", "// make a note of the thread that's processing events", "synchronized", "(", "this", ")", "{", "_dobjThread", "=", "Thread", ".", "currentThread", "(", ")", ";", "}...
Runs the dobjmgr event loop until it is requested to exit. This should be called from the main application thread.
[ "Runs", "the", "dobjmgr", "event", "loop", "until", "it", "is", "requested", "to", "exit", ".", "This", "should", "be", "called", "from", "the", "main", "application", "thread", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L388-L403
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.dumpUnitProfiles
public void dumpUnitProfiles () { for (Map.Entry<String, UnitProfile> entry : _profiles.entrySet()) { log.info("P: " + entry.getKey() + " => " + entry.getValue()); } }
java
public void dumpUnitProfiles () { for (Map.Entry<String, UnitProfile> entry : _profiles.entrySet()) { log.info("P: " + entry.getKey() + " => " + entry.getValue()); } }
[ "public", "void", "dumpUnitProfiles", "(", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "UnitProfile", ">", "entry", ":", "_profiles", ".", "entrySet", "(", ")", ")", "{", "log", ".", "info", "(", "\"P: \"", "+", "entry", ".", "getK...
Dumps collected profiling information to the system log.
[ "Dumps", "collected", "profiling", "information", "to", "the", "system", "log", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L438-L443
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.processUnit
protected void processUnit (Object unit) { long start = System.nanoTime(); // keep track of the largest queue size we've seen int queueSize = _evqueue.size(); if (queueSize > _current.maxQueueSize) { _current.maxQueueSize = queueSize; } try { if (unit instanceof Runnable) { // if this is a runnable, it's just an executable unit that should be invoked ((Runnable)unit).run(); } else { DEvent event = (DEvent)unit; // if this event is on a proxied object, forward it to the owning manager ProxyReference proxy = _proxies.get(event.getTargetOid()); if (proxy != null) { // rewrite the oid into the originating manager's id space event.setTargetOid(proxy.origObjectId); // then pass it on to the originating manager to handle proxy.origManager.postEvent(event); } else if (event instanceof CompoundEvent) { processCompoundEvent((CompoundEvent)event); } else { processEvent(event); } } } catch (VirtualMachineError e) { handleFatalError(unit, e); } catch (Throwable t) { log.warning("Execution unit failed", "unit", unit, t); } // compute the elapsed time in microseconds long elapsed = (System.nanoTime() - start)/1000; // report excessively long units if (elapsed > 500000 && !(unit instanceof LongRunnable)) { log.warning("Long dobj unit " + StringUtil.shortClassName(unit), "unit", unit, "time", (elapsed/1000) + "ms"); } // periodically sample and record the time spent processing a unit if (UNIT_PROF_ENABLED && _eventCount % _unitProfInterval == 0) { String cname; // do some jiggery pokery to get more fine grained profiling details on certain // "popular" unit types if (unit instanceof Interval.RunBuddy) { cname = StringUtil.shortClassName( ((Interval.RunBuddy)unit).getIntervalClassName()); } else if (unit instanceof InvocationRequestEvent) { InvocationRequestEvent ire = (InvocationRequestEvent)unit; Class<?> c = _invmgr.getDispatcherClass(ire.getInvCode()); cname = (c == null) ? "dobj.InvocationRequestEvent:(no longer registered)" : StringUtil.shortClassName(c) + ":" + ire.getMethodId(); } else { cname = StringUtil.shortClassName(unit); } UnitProfile uprof = _profiles.get(cname); if (uprof == null) { _profiles.put(cname, uprof = new UnitProfile()); } uprof.record(elapsed); } }
java
protected void processUnit (Object unit) { long start = System.nanoTime(); // keep track of the largest queue size we've seen int queueSize = _evqueue.size(); if (queueSize > _current.maxQueueSize) { _current.maxQueueSize = queueSize; } try { if (unit instanceof Runnable) { // if this is a runnable, it's just an executable unit that should be invoked ((Runnable)unit).run(); } else { DEvent event = (DEvent)unit; // if this event is on a proxied object, forward it to the owning manager ProxyReference proxy = _proxies.get(event.getTargetOid()); if (proxy != null) { // rewrite the oid into the originating manager's id space event.setTargetOid(proxy.origObjectId); // then pass it on to the originating manager to handle proxy.origManager.postEvent(event); } else if (event instanceof CompoundEvent) { processCompoundEvent((CompoundEvent)event); } else { processEvent(event); } } } catch (VirtualMachineError e) { handleFatalError(unit, e); } catch (Throwable t) { log.warning("Execution unit failed", "unit", unit, t); } // compute the elapsed time in microseconds long elapsed = (System.nanoTime() - start)/1000; // report excessively long units if (elapsed > 500000 && !(unit instanceof LongRunnable)) { log.warning("Long dobj unit " + StringUtil.shortClassName(unit), "unit", unit, "time", (elapsed/1000) + "ms"); } // periodically sample and record the time spent processing a unit if (UNIT_PROF_ENABLED && _eventCount % _unitProfInterval == 0) { String cname; // do some jiggery pokery to get more fine grained profiling details on certain // "popular" unit types if (unit instanceof Interval.RunBuddy) { cname = StringUtil.shortClassName( ((Interval.RunBuddy)unit).getIntervalClassName()); } else if (unit instanceof InvocationRequestEvent) { InvocationRequestEvent ire = (InvocationRequestEvent)unit; Class<?> c = _invmgr.getDispatcherClass(ire.getInvCode()); cname = (c == null) ? "dobj.InvocationRequestEvent:(no longer registered)" : StringUtil.shortClassName(c) + ":" + ire.getMethodId(); } else { cname = StringUtil.shortClassName(unit); } UnitProfile uprof = _profiles.get(cname); if (uprof == null) { _profiles.put(cname, uprof = new UnitProfile()); } uprof.record(elapsed); } }
[ "protected", "void", "processUnit", "(", "Object", "unit", ")", "{", "long", "start", "=", "System", ".", "nanoTime", "(", ")", ";", "// keep track of the largest queue size we've seen", "int", "queueSize", "=", "_evqueue", ".", "size", "(", ")", ";", "if", "(...
Processes a single unit from the queue.
[ "Processes", "a", "single", "unit", "from", "the", "queue", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L653-L725
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.processCompoundEvent
protected void processCompoundEvent (CompoundEvent event) { List<DEvent> events = event.getEvents(); int ecount = events.size(); // look up the target object DObject target = _objects.get(event.getTargetOid()); if (target == null) { log.debug("Compound event target no longer exists", "event", event); return; } // check the permissions on all of the events for (int ii = 0; ii < ecount; ii++) { DEvent sevent = events.get(ii); if (!target.checkPermissions(sevent)) { log.warning("Event failed permissions check", "event", sevent, "target", target); return; } } // dispatch the events for (int ii = 0; ii < ecount; ii++) { dispatchEvent(events.get(ii), target); } // always notify proxies of compound events target.notifyProxies(event); }
java
protected void processCompoundEvent (CompoundEvent event) { List<DEvent> events = event.getEvents(); int ecount = events.size(); // look up the target object DObject target = _objects.get(event.getTargetOid()); if (target == null) { log.debug("Compound event target no longer exists", "event", event); return; } // check the permissions on all of the events for (int ii = 0; ii < ecount; ii++) { DEvent sevent = events.get(ii); if (!target.checkPermissions(sevent)) { log.warning("Event failed permissions check", "event", sevent, "target", target); return; } } // dispatch the events for (int ii = 0; ii < ecount; ii++) { dispatchEvent(events.get(ii), target); } // always notify proxies of compound events target.notifyProxies(event); }
[ "protected", "void", "processCompoundEvent", "(", "CompoundEvent", "event", ")", "{", "List", "<", "DEvent", ">", "events", "=", "event", ".", "getEvents", "(", ")", ";", "int", "ecount", "=", "events", ".", "size", "(", ")", ";", "// look up the target obje...
Performs the processing associated with a compound event, notifying listeners and the like.
[ "Performs", "the", "processing", "associated", "with", "a", "compound", "event", "notifying", "listeners", "and", "the", "like", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L730-L758
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.processEvent
protected void processEvent (DEvent event) { // look up the target object DObject target = _objects.get(event.getTargetOid()); if (target == null) { log.debug("Event target no longer exists", "event", event); return; } // check the event's permissions if (!target.checkPermissions(event)) { log.warning("Event failed permissions check", "event", event, "target", target); return; } if (dispatchEvent(event, target)) { // unless requested not to, notify any proxies target.notifyProxies(event); } }
java
protected void processEvent (DEvent event) { // look up the target object DObject target = _objects.get(event.getTargetOid()); if (target == null) { log.debug("Event target no longer exists", "event", event); return; } // check the event's permissions if (!target.checkPermissions(event)) { log.warning("Event failed permissions check", "event", event, "target", target); return; } if (dispatchEvent(event, target)) { // unless requested not to, notify any proxies target.notifyProxies(event); } }
[ "protected", "void", "processEvent", "(", "DEvent", "event", ")", "{", "// look up the target object", "DObject", "target", "=", "_objects", ".", "get", "(", "event", ".", "getTargetOid", "(", ")", ")", ";", "if", "(", "target", "==", "null", ")", "{", "lo...
Performs the processing associated with an event, notifying listeners and the like.
[ "Performs", "the", "processing", "associated", "with", "an", "event", "notifying", "listeners", "and", "the", "like", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L763-L782
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.handleFatalError
protected void handleFatalError (Object causer, Error error) { if (_fatalThrottle.throttleOp()) { throw error; } log.warning("Fatal error caused by '" + causer + "': " + error, error); }
java
protected void handleFatalError (Object causer, Error error) { if (_fatalThrottle.throttleOp()) { throw error; } log.warning("Fatal error caused by '" + causer + "': " + error, error); }
[ "protected", "void", "handleFatalError", "(", "Object", "causer", ",", "Error", "error", ")", "{", "if", "(", "_fatalThrottle", ".", "throttleOp", "(", ")", ")", "{", "throw", "error", ";", "}", "log", ".", "warning", "(", "\"Fatal error caused by '\"", "+",...
Attempts to recover from fatal errors but rethrows if things are freaking out too frequently.
[ "Attempts", "to", "recover", "from", "fatal", "errors", "but", "rethrows", "if", "things", "are", "freaking", "out", "too", "frequently", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L829-L835
train
threerings/narya
core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java
PresentsDObjectMgr.registerEventHelpers
protected void registerEventHelpers () { try { _helpers.put(ObjectDestroyedEvent.class, new EventHelper () { public boolean invoke (DEvent event, DObject target) { return objectDestroyed(event, target); } }); _helpers.put(ObjectAddedEvent.class, new EventHelper() { public boolean invoke (DEvent event, DObject target) { return objectAdded(event, target); } }); _helpers.put(ObjectRemovedEvent.class, new EventHelper() { public boolean invoke (DEvent event, DObject target) { return objectRemoved(event, target); } }); } catch (Exception e) { log.warning("Unable to register event helpers", "error", e); } }
java
protected void registerEventHelpers () { try { _helpers.put(ObjectDestroyedEvent.class, new EventHelper () { public boolean invoke (DEvent event, DObject target) { return objectDestroyed(event, target); } }); _helpers.put(ObjectAddedEvent.class, new EventHelper() { public boolean invoke (DEvent event, DObject target) { return objectAdded(event, target); } }); _helpers.put(ObjectRemovedEvent.class, new EventHelper() { public boolean invoke (DEvent event, DObject target) { return objectRemoved(event, target); } }); } catch (Exception e) { log.warning("Unable to register event helpers", "error", e); } }
[ "protected", "void", "registerEventHelpers", "(", ")", "{", "try", "{", "_helpers", ".", "put", "(", "ObjectDestroyedEvent", ".", "class", ",", "new", "EventHelper", "(", ")", "{", "public", "boolean", "invoke", "(", "DEvent", "event", ",", "DObject", "targe...
Registers our event helper methods.
[ "Registers", "our", "event", "helper", "methods", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/PresentsDObjectMgr.java#L884-L906
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/GenTask.java
GenTask.setHeader
public void setHeader (File header) { try { _header = StreamUtil.toString(new FileReader(header)); } catch (IOException ioe) { System.err.println("Unabled to load header '" + header + ": " + ioe.getMessage()); } }
java
public void setHeader (File header) { try { _header = StreamUtil.toString(new FileReader(header)); } catch (IOException ioe) { System.err.println("Unabled to load header '" + header + ": " + ioe.getMessage()); } }
[ "public", "void", "setHeader", "(", "File", "header", ")", "{", "try", "{", "_header", "=", "StreamUtil", ".", "toString", "(", "new", "FileReader", "(", "header", ")", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "System", ".", "err", ...
Configures us with a header file that we'll prepend to all generated source files.
[ "Configures", "us", "with", "a", "header", "file", "that", "we", "ll", "prepend", "to", "all", "generated", "source", "files", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GenTask.java#L69-L77
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/GenTask.java
GenTask.wouldProduceSameFile
protected boolean wouldProduceSameFile (String generated, File existing) throws IOException { Iterator<String> generatedLines = Splitter.on(EOL).split(generated).iterator(); for (String prev : Files.readLines(existing, UTF_8)) { if (!generatedLines.hasNext()) { return false; } String cur = generatedLines.next(); if (!prev.equals(cur) && !(prev.startsWith("// $Id") && cur.startsWith("// $Id"))) { return false; } } // If the generated output ends with a newline, it'll have one more next from the splitter // that reading the file doesn't produce. if (generatedLines.hasNext()) { return generatedLines.next().equals("") && !generatedLines.hasNext(); } return true; }
java
protected boolean wouldProduceSameFile (String generated, File existing) throws IOException { Iterator<String> generatedLines = Splitter.on(EOL).split(generated).iterator(); for (String prev : Files.readLines(existing, UTF_8)) { if (!generatedLines.hasNext()) { return false; } String cur = generatedLines.next(); if (!prev.equals(cur) && !(prev.startsWith("// $Id") && cur.startsWith("// $Id"))) { return false; } } // If the generated output ends with a newline, it'll have one more next from the splitter // that reading the file doesn't produce. if (generatedLines.hasNext()) { return generatedLines.next().equals("") && !generatedLines.hasNext(); } return true; }
[ "protected", "boolean", "wouldProduceSameFile", "(", "String", "generated", ",", "File", "existing", ")", "throws", "IOException", "{", "Iterator", "<", "String", ">", "generatedLines", "=", "Splitter", ".", "on", "(", "EOL", ")", ".", "split", "(", "generated...
Returns true if the given string has the same content as the file, sans svn prop lines.
[ "Returns", "true", "if", "the", "given", "string", "has", "the", "same", "content", "as", "the", "file", "sans", "svn", "prop", "lines", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GenTask.java#L178-L198
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/GenTask.java
GenTask.mergeTemplate
protected String mergeTemplate (String template, Object... data) throws IOException { return mergeTemplate(template, createMap(data)); }
java
protected String mergeTemplate (String template, Object... data) throws IOException { return mergeTemplate(template, createMap(data)); }
[ "protected", "String", "mergeTemplate", "(", "String", "template", ",", "Object", "...", "data", ")", "throws", "IOException", "{", "return", "mergeTemplate", "(", "template", ",", "createMap", "(", "data", ")", ")", ";", "}" ]
Merges the specified template using the supplied mapping of keys to objects. @param data a series of key, value pairs where the keys must be strings and the values can be any object.
[ "Merges", "the", "specified", "template", "using", "the", "supplied", "mapping", "of", "keys", "to", "objects", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GenTask.java#L206-L210
train
threerings/narya
tools/src/main/java/com/threerings/presents/tools/GenTask.java
GenTask.mergeTemplate
protected String mergeTemplate (String template, Map<String, Object> data) throws IOException { Reader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(template), UTF_8); return convertEols(Mustache.compiler().escapeHTML(false).compile(reader).execute(data)); }
java
protected String mergeTemplate (String template, Map<String, Object> data) throws IOException { Reader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(template), UTF_8); return convertEols(Mustache.compiler().escapeHTML(false).compile(reader).execute(data)); }
[ "protected", "String", "mergeTemplate", "(", "String", "template", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "throws", "IOException", "{", "Reader", "reader", "=", "new", "InputStreamReader", "(", "getClass", "(", ")", ".", "getClassLoader", ...
Merges the specified template using the supplied mapping of string keys to objects. @return a string containing the merged text.
[ "Merges", "the", "specified", "template", "using", "the", "supplied", "mapping", "of", "string", "keys", "to", "objects", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/tools/src/main/java/com/threerings/presents/tools/GenTask.java#L217-L223
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java
CurseFilter.comicChars
public static String comicChars (int length) { char[] chars = new char[length]; for (int ii=0; ii < length; ii++) { chars[ii] = RandomUtil.pickRandom(COMIC_CHARS); } return new String(chars); }
java
public static String comicChars (int length) { char[] chars = new char[length]; for (int ii=0; ii < length; ii++) { chars[ii] = RandomUtil.pickRandom(COMIC_CHARS); } return new String(chars); }
[ "public", "static", "String", "comicChars", "(", "int", "length", ")", "{", "char", "[", "]", "chars", "=", "new", "char", "[", "length", "]", ";", "for", "(", "int", "ii", "=", "0", ";", "ii", "<", "length", ";", "ii", "++", ")", "{", "chars", ...
Return a comicy replacement of the specified length.
[ "Return", "a", "comicy", "replacement", "of", "the", "specified", "length", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java#L48-L55
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java
CurseFilter.filter
public String filter (String msg, Name otherUser, boolean outgoing) { // first, check against the drop-always list _stopMatcher.reset(msg); if (_stopMatcher.find()) { return null; } // then see what kind of curse filtering the user has configured Mode level = getFilterMode(); if (level == Mode.UNFILTERED) { return msg; } StringBuffer inbuf = new StringBuffer(msg); StringBuffer outbuf = new StringBuffer(msg.length()); for (int ii=0, nn=_matchers.length; ii < nn; ii++) { Matcher m = _matchers[ii]; m.reset(inbuf); while (m.find()) { switch (level) { case DROP: return null; case COMIC: m.appendReplacement(outbuf, _replacements[ii].replace(" ", comicChars(_comicLength[ii]))); break; case VERNACULAR: String vernacular = _vernacular[ii]; if (Character.isUpperCase(m.group(2).codePointAt(0))) { int firstCharLen = Character.charCount(vernacular.codePointAt(0)); vernacular = vernacular.substring(0, firstCharLen).toUpperCase() + vernacular.substring(firstCharLen); } m.appendReplacement(outbuf, _replacements[ii].replace(" ", vernacular)); break; case UNFILTERED: // We returned the msg unadulterated above in this case, so it should be // impossible to wind up here, but let's enumerate it so we can let the compiler // scream about missing enum values in a switch log.warning("Omg? We're trying to filter chat even though we're unfiltered?"); break; } } if (outbuf.length() == 0) { // optimization: if we didn't find a match, jump to the next // pattern without doing any StringBuilder jimmying continue; } m.appendTail(outbuf); // swap the buffers around and clear the output StringBuffer temp = inbuf; inbuf = outbuf; outbuf = temp; outbuf.setLength(0); } return inbuf.toString(); }
java
public String filter (String msg, Name otherUser, boolean outgoing) { // first, check against the drop-always list _stopMatcher.reset(msg); if (_stopMatcher.find()) { return null; } // then see what kind of curse filtering the user has configured Mode level = getFilterMode(); if (level == Mode.UNFILTERED) { return msg; } StringBuffer inbuf = new StringBuffer(msg); StringBuffer outbuf = new StringBuffer(msg.length()); for (int ii=0, nn=_matchers.length; ii < nn; ii++) { Matcher m = _matchers[ii]; m.reset(inbuf); while (m.find()) { switch (level) { case DROP: return null; case COMIC: m.appendReplacement(outbuf, _replacements[ii].replace(" ", comicChars(_comicLength[ii]))); break; case VERNACULAR: String vernacular = _vernacular[ii]; if (Character.isUpperCase(m.group(2).codePointAt(0))) { int firstCharLen = Character.charCount(vernacular.codePointAt(0)); vernacular = vernacular.substring(0, firstCharLen).toUpperCase() + vernacular.substring(firstCharLen); } m.appendReplacement(outbuf, _replacements[ii].replace(" ", vernacular)); break; case UNFILTERED: // We returned the msg unadulterated above in this case, so it should be // impossible to wind up here, but let's enumerate it so we can let the compiler // scream about missing enum values in a switch log.warning("Omg? We're trying to filter chat even though we're unfiltered?"); break; } } if (outbuf.length() == 0) { // optimization: if we didn't find a match, jump to the next // pattern without doing any StringBuilder jimmying continue; } m.appendTail(outbuf); // swap the buffers around and clear the output StringBuffer temp = inbuf; inbuf = outbuf; outbuf = temp; outbuf.setLength(0); } return inbuf.toString(); }
[ "public", "String", "filter", "(", "String", "msg", ",", "Name", "otherUser", ",", "boolean", "outgoing", ")", "{", "// first, check against the drop-always list", "_stopMatcher", ".", "reset", "(", "msg", ")", ";", "if", "(", "_stopMatcher", ".", "find", "(", ...
from interface ChatFilter
[ "from", "interface", "ChatFilter" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java#L89-L152
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java
CurseFilter.configureCurseWords
protected void configureCurseWords (String curseWords) { StringTokenizer st = new StringTokenizer(curseWords); int numWords = st.countTokens(); _matchers = new Matcher[numWords]; _replacements = new String[numWords]; _vernacular = new String[numWords]; _comicLength = new int[numWords]; for (int ii=0; ii < numWords; ii++) { String mapping = st.nextToken(); StringTokenizer st2 = new StringTokenizer(mapping, "="); if (st2.countTokens() != 2) { log.warning("Something looks wrong in the x.cursewords properties (" + mapping + "), skipping."); continue; } String curse = st2.nextToken(); String s = ""; String p = ""; if (curse.startsWith("*")) { curse = curse.substring(1); p += "([\\p{L}\\p{Digit}]*)"; s += "$1"; } else { p += "()"; } s += " "; p += " "; if (curse.endsWith("*")) { curse = curse.substring(0, curse.length() - 1); p += "([\\p{L}\\p{Digit}]*)"; s += "$3"; } String pattern = "\\b" + p.replace(" ", "(" + curse + ")") + "\\b"; Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); _matchers[ii] = pat.matcher(""); _replacements[ii] = s; _vernacular[ii] = st2.nextToken().replace('_', ' '); _comicLength[ii] = curse.codePointCount(0, curse.length()); } }
java
protected void configureCurseWords (String curseWords) { StringTokenizer st = new StringTokenizer(curseWords); int numWords = st.countTokens(); _matchers = new Matcher[numWords]; _replacements = new String[numWords]; _vernacular = new String[numWords]; _comicLength = new int[numWords]; for (int ii=0; ii < numWords; ii++) { String mapping = st.nextToken(); StringTokenizer st2 = new StringTokenizer(mapping, "="); if (st2.countTokens() != 2) { log.warning("Something looks wrong in the x.cursewords properties (" + mapping + "), skipping."); continue; } String curse = st2.nextToken(); String s = ""; String p = ""; if (curse.startsWith("*")) { curse = curse.substring(1); p += "([\\p{L}\\p{Digit}]*)"; s += "$1"; } else { p += "()"; } s += " "; p += " "; if (curse.endsWith("*")) { curse = curse.substring(0, curse.length() - 1); p += "([\\p{L}\\p{Digit}]*)"; s += "$3"; } String pattern = "\\b" + p.replace(" ", "(" + curse + ")") + "\\b"; Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); _matchers[ii] = pat.matcher(""); _replacements[ii] = s; _vernacular[ii] = st2.nextToken().replace('_', ' '); _comicLength[ii] = curse.codePointCount(0, curse.length()); } }
[ "protected", "void", "configureCurseWords", "(", "String", "curseWords", ")", "{", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "curseWords", ")", ";", "int", "numWords", "=", "st", ".", "countTokens", "(", ")", ";", "_matchers", "=", "new", ...
Configure the curse word portion of our filtering.
[ "Configure", "the", "curse", "word", "portion", "of", "our", "filtering", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java#L157-L201
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java
CurseFilter.configureStopWords
protected void configureStopWords (String stopWords) { List<String> patterns = Lists.newArrayList(); for (StringTokenizer st = new StringTokenizer(stopWords); st.hasMoreTokens(); ) { patterns.add(getStopWordRegexp(st.nextToken())); } String pattern = patterns.isEmpty() ? ".\\A" // matches nothing : "(" + Joiner.on('|').join(patterns) + ")"; setStopPattern(pattern); }
java
protected void configureStopWords (String stopWords) { List<String> patterns = Lists.newArrayList(); for (StringTokenizer st = new StringTokenizer(stopWords); st.hasMoreTokens(); ) { patterns.add(getStopWordRegexp(st.nextToken())); } String pattern = patterns.isEmpty() ? ".\\A" // matches nothing : "(" + Joiner.on('|').join(patterns) + ")"; setStopPattern(pattern); }
[ "protected", "void", "configureStopWords", "(", "String", "stopWords", ")", "{", "List", "<", "String", ">", "patterns", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "stopWords", "...
Configure the words that will stop.
[ "Configure", "the", "words", "that", "will", "stop", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java#L206-L216
train
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java
CurseFilter.setStopPattern
protected void setStopPattern (String pattern) { _stopMatcher = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(""); }
java
protected void setStopPattern (String pattern) { _stopMatcher = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(""); }
[ "protected", "void", "setStopPattern", "(", "String", "pattern", ")", "{", "_stopMatcher", "=", "Pattern", ".", "compile", "(", "pattern", ",", "Pattern", ".", "CASE_INSENSITIVE", ")", ".", "matcher", "(", "\"\"", ")", ";", "}" ]
Sets our stop word matcher to one for the given regular expression.
[ "Sets", "our", "stop", "word", "matcher", "to", "one", "for", "the", "given", "regular", "expression", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/CurseFilter.java#L221-L224
train
threerings/narya
core/src/main/java/com/threerings/web/server/ServletWaiter.java
ServletWaiter.queueAndWait
public static <T> T queueAndWait ( RunQueue runq, final String name, final Callable<T> action) throws ServiceException { final ServletWaiter<T> waiter = new ServletWaiter<T>(name); runq.postRunnable(new Runnable() { public void run () { try { waiter.postSuccess(action.call()); } catch (final Exception e) { waiter.postFailure(e); } } }); return waiter.waitForResult(); }
java
public static <T> T queueAndWait ( RunQueue runq, final String name, final Callable<T> action) throws ServiceException { final ServletWaiter<T> waiter = new ServletWaiter<T>(name); runq.postRunnable(new Runnable() { public void run () { try { waiter.postSuccess(action.call()); } catch (final Exception e) { waiter.postFailure(e); } } }); return waiter.waitForResult(); }
[ "public", "static", "<", "T", ">", "T", "queueAndWait", "(", "RunQueue", "runq", ",", "final", "String", "name", ",", "final", "Callable", "<", "T", ">", "action", ")", "throws", "ServiceException", "{", "final", "ServletWaiter", "<", "T", ">", "waiter", ...
Posts a result getter to be executed on the run queue thread and blocks waiting for the result.
[ "Posts", "a", "result", "getter", "to", "be", "executed", "on", "the", "run", "queue", "thread", "and", "blocks", "waiting", "for", "the", "result", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/web/server/ServletWaiter.java#L83-L98
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.count
public static <T extends TOP> int count(final Class<T> type, final JCas aJCas) { return JCasUtil.select(aJCas, type).size(); }
java
public static <T extends TOP> int count(final Class<T> type, final JCas aJCas) { return JCasUtil.select(aJCas, type).size(); }
[ "public", "static", "<", "T", "extends", "TOP", ">", "int", "count", "(", "final", "Class", "<", "T", ">", "type", ",", "final", "JCas", "aJCas", ")", "{", "return", "JCasUtil", ".", "select", "(", "aJCas", ",", "type", ")", ".", "size", "(", ")", ...
Counts the number of features structures of the given type in the JCas @param type the type @param aJCas the JCas @return the number of occurrences
[ "Counts", "the", "number", "of", "features", "structures", "of", "the", "given", "type", "in", "the", "JCas" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L54-L57
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.hasAny
public static <T extends TOP> boolean hasAny(final Class<T> type, final JCas aJCas) { return count(type, aJCas) != 0; }
java
public static <T extends TOP> boolean hasAny(final Class<T> type, final JCas aJCas) { return count(type, aJCas) != 0; }
[ "public", "static", "<", "T", "extends", "TOP", ">", "boolean", "hasAny", "(", "final", "Class", "<", "T", ">", "type", ",", "final", "JCas", "aJCas", ")", "{", "return", "count", "(", "type", ",", "aJCas", ")", "!=", "0", ";", "}" ]
Returns whether there is any feature structure of the given type @param type the type @param aJCas the JCas @return whether there is any feature structure of the given type
[ "Returns", "whether", "there", "is", "any", "feature", "structure", "of", "the", "given", "type" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L66-L69
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.hasNo
public static <T extends TOP> boolean hasNo(final Class<T> type, final JCas aJCas) { return !hasAny(type, aJCas); }
java
public static <T extends TOP> boolean hasNo(final Class<T> type, final JCas aJCas) { return !hasAny(type, aJCas); }
[ "public", "static", "<", "T", "extends", "TOP", ">", "boolean", "hasNo", "(", "final", "Class", "<", "T", ">", "type", ",", "final", "JCas", "aJCas", ")", "{", "return", "!", "hasAny", "(", "type", ",", "aJCas", ")", ";", "}" ]
Returns whether there is no feature structure of the given type @param type the type @param aJCas the JCas @return whether there is no feature structure of the given type
[ "Returns", "whether", "there", "is", "no", "feature", "structure", "of", "the", "given", "type" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L78-L81
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.selectAsList
public static <T extends TOP> List<T> selectAsList(final JCas jCas, final Class<T> type) { return new ArrayList<>(JCasUtil.select(jCas, type)); }
java
public static <T extends TOP> List<T> selectAsList(final JCas jCas, final Class<T> type) { return new ArrayList<>(JCasUtil.select(jCas, type)); }
[ "public", "static", "<", "T", "extends", "TOP", ">", "List", "<", "T", ">", "selectAsList", "(", "final", "JCas", "jCas", ",", "final", "Class", "<", "T", ">", "type", ")", "{", "return", "new", "ArrayList", "<>", "(", "JCasUtil", ".", "select", "(",...
Convenience method that selects all feature structures of the given type and creates a list from them. @param jCas the JCas @return the list of all features structures of the given type in the JCas @see JCasUtil#select(JCas, Class)
[ "Convenience", "method", "that", "selects", "all", "feature", "structures", "of", "the", "given", "type", "and", "creates", "a", "list", "from", "them", "." ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L124-L127
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.doOverlap
public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); }
java
public static <T extends Annotation> boolean doOverlap(final T anno1, final T anno2) { return anno1.getEnd() > anno2.getBegin() && anno1.getBegin() < anno2.getEnd(); }
[ "public", "static", "<", "T", "extends", "Annotation", ">", "boolean", "doOverlap", "(", "final", "T", "anno1", ",", "final", "T", "anno2", ")", "{", "return", "anno1", ".", "getEnd", "(", ")", ">", "anno2", ".", "getBegin", "(", ")", "&&", "anno1", ...
Returns whether the given annotations have a non-empty overlap. <p> Note that this method is symmetric. Two annotations overlap if they have at least one character position in common. Annotations that merely touch at the begin or end are not overlapping. </p> <ul> <li>anno1[0,1], anno2[1,2] =&gt; no overlap</li> <li>anno1[0,2], anno2[1,2] =&gt; overlap</li> <li>anno1[0,2], anno2[0,2] =&gt; overlap (same span)</li> </ul> @param anno1 first annotation @param anno2 second annotation @return whether the annotations overlap
[ "Returns", "whether", "the", "given", "annotations", "have", "a", "non", "-", "empty", "overlap", "." ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L182-L185
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.haveSameSpan
public static boolean haveSameSpan(final Annotation anno1, final Annotation anno2) { return anno1.getBegin() == anno2.getBegin() && anno1.getEnd() == anno2.getEnd(); }
java
public static boolean haveSameSpan(final Annotation anno1, final Annotation anno2) { return anno1.getBegin() == anno2.getBegin() && anno1.getEnd() == anno2.getEnd(); }
[ "public", "static", "boolean", "haveSameSpan", "(", "final", "Annotation", "anno1", ",", "final", "Annotation", "anno2", ")", "{", "return", "anno1", ".", "getBegin", "(", ")", "==", "anno2", ".", "getBegin", "(", ")", "&&", "anno1", ".", "getEnd", "(", ...
Returns whether two annotations share the same span <p> The method checks the spans based on the begin and end indices and not based on the covered text. </p> @param anno1 first annotation @param anno2 second annotation @return whether the spans are identical
[ "Returns", "whether", "two", "annotations", "share", "the", "same", "span" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L199-L202
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.getJCas
public static JCas getJCas(final Annotation annotation) { JCas result = null; try { result = annotation.getCAS().getJCas(); } catch (final CASException e) { throw new IllegalArgumentException(e); } return result; }
java
public static JCas getJCas(final Annotation annotation) { JCas result = null; try { result = annotation.getCAS().getJCas(); } catch (final CASException e) { throw new IllegalArgumentException(e); } return result; }
[ "public", "static", "JCas", "getJCas", "(", "final", "Annotation", "annotation", ")", "{", "JCas", "result", "=", "null", ";", "try", "{", "result", "=", "annotation", ".", "getCAS", "(", ")", ".", "getJCas", "(", ")", ";", "}", "catch", "(", "final", ...
Returns the JCas of this annotation. <p> The method converts the potentially thrown {@link CASException} to an unchecked {@link IllegalArgumentException}. </p> @param annotation the annotation @return the extracted JCas
[ "Returns", "the", "JCas", "of", "this", "annotation", "." ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L215-L227
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.isFirstCoveredToken
public static boolean isFirstCoveredToken(final Token token, final Annotation annotation) { final JCas jCas = getJCas(annotation); final List<Token> coveredTokens = JCasUtil.selectCovered(jCas, Token.class, annotation); if (coveredTokens.isEmpty()) { return false; } else { final Token firstCoveredToken = coveredTokens.get(0); return haveSameSpan(token, firstCoveredToken); } }
java
public static boolean isFirstCoveredToken(final Token token, final Annotation annotation) { final JCas jCas = getJCas(annotation); final List<Token> coveredTokens = JCasUtil.selectCovered(jCas, Token.class, annotation); if (coveredTokens.isEmpty()) { return false; } else { final Token firstCoveredToken = coveredTokens.get(0); return haveSameSpan(token, firstCoveredToken); } }
[ "public", "static", "boolean", "isFirstCoveredToken", "(", "final", "Token", "token", ",", "final", "Annotation", "annotation", ")", "{", "final", "JCas", "jCas", "=", "getJCas", "(", "annotation", ")", ";", "final", "List", "<", "Token", ">", "coveredTokens",...
Returns whether the given token is the first token covered by the given annotation. @param token the token @param annotation the annotation @return whether the token is the first covered token
[ "Returns", "whether", "the", "given", "token", "is", "the", "first", "token", "covered", "by", "the", "given", "annotation", "." ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L236-L248
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.updateEnd
public static void updateEnd(final Annotation annotation, final int end) { annotation.removeFromIndexes(); annotation.setEnd(end); annotation.addToIndexes(); }
java
public static void updateEnd(final Annotation annotation, final int end) { annotation.removeFromIndexes(); annotation.setEnd(end); annotation.addToIndexes(); }
[ "public", "static", "void", "updateEnd", "(", "final", "Annotation", "annotation", ",", "final", "int", "end", ")", "{", "annotation", ".", "removeFromIndexes", "(", ")", ";", "annotation", ".", "setEnd", "(", "end", ")", ";", "annotation", ".", "addToIndexe...
Sets the end value of the annotation, updating indexes appropriately @param annotation the annotation @param end the new end value
[ "Sets", "the", "end", "value", "of", "the", "annotation", "updating", "indexes", "appropriately" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L287-L292
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.updateBegin
public static void updateBegin(final Annotation annotation, final int begin) { annotation.removeFromIndexes(); annotation.setBegin(begin); annotation.addToIndexes(); }
java
public static void updateBegin(final Annotation annotation, final int begin) { annotation.removeFromIndexes(); annotation.setBegin(begin); annotation.addToIndexes(); }
[ "public", "static", "void", "updateBegin", "(", "final", "Annotation", "annotation", ",", "final", "int", "begin", ")", "{", "annotation", ".", "removeFromIndexes", "(", ")", ";", "annotation", ".", "setBegin", "(", "begin", ")", ";", "annotation", ".", "add...
Sets the begin value of the annotation, updating indexes appropriately @param annotation the annotation @param begin the new begin value
[ "Sets", "the", "begin", "value", "of", "the", "annotation", "updating", "indexes", "appropriately" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L300-L305
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.findTokenByBeginPosition
public static Token findTokenByBeginPosition(JCas jCas, int begin) { for (Token token : JCasUtil.select(getInitialView(jCas), Token.class)) { if (token.getBegin() == begin) { return token; } } return null; }
java
public static Token findTokenByBeginPosition(JCas jCas, int begin) { for (Token token : JCasUtil.select(getInitialView(jCas), Token.class)) { if (token.getBegin() == begin) { return token; } } return null; }
[ "public", "static", "Token", "findTokenByBeginPosition", "(", "JCas", "jCas", ",", "int", "begin", ")", "{", "for", "(", "Token", "token", ":", "JCasUtil", ".", "select", "(", "getInitialView", "(", "jCas", ")", ",", "Token", ".", "class", ")", ")", "{",...
Returns token at the given position @param jCas jCas @param begin token begin position @return Token or null
[ "Returns", "token", "at", "the", "given", "position" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L332-L341
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.findTokenByEndPosition
public static Token findTokenByEndPosition(JCas jCas, int end) { for (Token token : JCasUtil.select(getInitialView(jCas), Token.class)) { if (token.getEnd() == end) { return token; } } return null; }
java
public static Token findTokenByEndPosition(JCas jCas, int end) { for (Token token : JCasUtil.select(getInitialView(jCas), Token.class)) { if (token.getEnd() == end) { return token; } } return null; }
[ "public", "static", "Token", "findTokenByEndPosition", "(", "JCas", "jCas", ",", "int", "end", ")", "{", "for", "(", "Token", "token", ":", "JCasUtil", ".", "select", "(", "getInitialView", "(", "jCas", ")", ",", "Token", ".", "class", ")", ")", "{", "...
Returns token ending at the given position @param jCas jCas @param end end @return Token or null
[ "Returns", "token", "ending", "at", "the", "given", "position" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L350-L359
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.getPrecedingTokens
public static List<Token> getPrecedingTokens(JCas jCas, Token token) { List<Token> result = new ArrayList<Token>(); for (Token t : JCasUtil.select(getInitialView(jCas), Token.class)) { if (t.getBegin() < token.getBegin()) { result.add(t); } } return result; }
java
public static List<Token> getPrecedingTokens(JCas jCas, Token token) { List<Token> result = new ArrayList<Token>(); for (Token t : JCasUtil.select(getInitialView(jCas), Token.class)) { if (t.getBegin() < token.getBegin()) { result.add(t); } } return result; }
[ "public", "static", "List", "<", "Token", ">", "getPrecedingTokens", "(", "JCas", "jCas", ",", "Token", "token", ")", "{", "List", "<", "Token", ">", "result", "=", "new", "ArrayList", "<", "Token", ">", "(", ")", ";", "for", "(", "Token", "t", ":", ...
Returns a list of tokens preceding the given token @param jCas jCas @param token token @return list of tokens (may be empty if the token is the first one, but never null)
[ "Returns", "a", "list", "of", "tokens", "preceding", "the", "given", "token" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L368-L379
train
dkpro/dkpro-argumentation
dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java
JCasUtil2.getPrecedingSentences
public static List<Sentence> getPrecedingSentences(JCas jCas, Sentence annotation) { List<Sentence> result = new ArrayList<Sentence>(); for (Sentence sentence : JCasUtil.select(getInitialView(jCas), Sentence.class)) { if (sentence.getBegin() < annotation.getBegin()) { result.add(sentence); } } Collections.sort(result, new Comparator<Sentence>() { @Override public int compare(Sentence o1, Sentence o2) { return o2.getBegin() - o1.getBegin(); } }); return result; }
java
public static List<Sentence> getPrecedingSentences(JCas jCas, Sentence annotation) { List<Sentence> result = new ArrayList<Sentence>(); for (Sentence sentence : JCasUtil.select(getInitialView(jCas), Sentence.class)) { if (sentence.getBegin() < annotation.getBegin()) { result.add(sentence); } } Collections.sort(result, new Comparator<Sentence>() { @Override public int compare(Sentence o1, Sentence o2) { return o2.getBegin() - o1.getBegin(); } }); return result; }
[ "public", "static", "List", "<", "Sentence", ">", "getPrecedingSentences", "(", "JCas", "jCas", ",", "Sentence", "annotation", ")", "{", "List", "<", "Sentence", ">", "result", "=", "new", "ArrayList", "<", "Sentence", ">", "(", ")", ";", "for", "(", "Se...
Returns a list of annotations of the same type preceding the given annotation @param jCas jcas @param annotation sentence @return list of sentences sorted incrementally by position
[ "Returns", "a", "list", "of", "annotations", "of", "the", "same", "type", "preceding", "the", "given", "annotation" ]
57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb
https://github.com/dkpro/dkpro-argumentation/blob/57ce6f5e73d8075b7088aeeebb107c85b3d4bbcb/dkpro-argumentation-misc/src/main/java/org/dkpro/argumentation/misc/uima/JCasUtil2.java#L408-L427
train
threerings/narya
core/src/main/java/com/threerings/presents/net/PublicKeyCredentials.java
PublicKeyCredentials.getSecret
public byte[] getSecret (PrivateKey key) { if (_secret == null) { _secret = SecureUtil.decryptBytes(key, _encodedSecret, _salt); } return _secret; }
java
public byte[] getSecret (PrivateKey key) { if (_secret == null) { _secret = SecureUtil.decryptBytes(key, _encodedSecret, _salt); } return _secret; }
[ "public", "byte", "[", "]", "getSecret", "(", "PrivateKey", "key", ")", "{", "if", "(", "_secret", "==", "null", ")", "{", "_secret", "=", "SecureUtil", ".", "decryptBytes", "(", "key", ",", "_encodedSecret", ",", "_salt", ")", ";", "}", "return", "_se...
Decodes the secret.
[ "Decodes", "the", "secret", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/net/PublicKeyCredentials.java#L71-L77
train
threerings/narya
core/src/main/java/com/threerings/io/ObjectOutputStream.java
ObjectOutputStream.addTranslation
public void addTranslation (String className, String streamedName) { if (_translations == null) { _translations = Maps.newHashMap(); } _translations.put(className, streamedName); }
java
public void addTranslation (String className, String streamedName) { if (_translations == null) { _translations = Maps.newHashMap(); } _translations.put(className, streamedName); }
[ "public", "void", "addTranslation", "(", "String", "className", ",", "String", "streamedName", ")", "{", "if", "(", "_translations", "==", "null", ")", "{", "_translations", "=", "Maps", ".", "newHashMap", "(", ")", ";", "}", "_translations", ".", "put", "...
Configures this object output stream with a mapping from a classname to a streamed name.
[ "Configures", "this", "object", "output", "stream", "with", "a", "mapping", "from", "a", "classname", "to", "a", "streamed", "name", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/ObjectOutputStream.java#L54-L60
train
threerings/narya
core/src/main/java/com/threerings/io/ObjectOutputStream.java
ObjectOutputStream.writeIntern
public void writeIntern (String value) throws IOException { // if the value to be written is null, simply write a zero if (value == null) { writeShort(0); return; } // create our intern map if necessary if (_internmap == null) { _internmap = Maps.newHashMap(); } // look up the intern mapping record Short code = _internmap.get(value); // create a mapping for the value if we've not got one if (code == null) { if (ObjectInputStream.STREAM_DEBUG) { log.info(hashCode() + ": Creating intern mapping", "code", _nextInternCode, "value", value); } code = createInternMapping(_nextInternCode++); _internmap.put(value.intern(), code); // make sure we didn't blow past our maximum intern count if (_nextInternCode <= 0) { throw new RuntimeException("Too many unique interns written to ObjectOutputStream"); } writeNewInternMapping(code, value); } else { writeExistingInternMapping(code, value); } }
java
public void writeIntern (String value) throws IOException { // if the value to be written is null, simply write a zero if (value == null) { writeShort(0); return; } // create our intern map if necessary if (_internmap == null) { _internmap = Maps.newHashMap(); } // look up the intern mapping record Short code = _internmap.get(value); // create a mapping for the value if we've not got one if (code == null) { if (ObjectInputStream.STREAM_DEBUG) { log.info(hashCode() + ": Creating intern mapping", "code", _nextInternCode, "value", value); } code = createInternMapping(_nextInternCode++); _internmap.put(value.intern(), code); // make sure we didn't blow past our maximum intern count if (_nextInternCode <= 0) { throw new RuntimeException("Too many unique interns written to ObjectOutputStream"); } writeNewInternMapping(code, value); } else { writeExistingInternMapping(code, value); } }
[ "public", "void", "writeIntern", "(", "String", "value", ")", "throws", "IOException", "{", "// if the value to be written is null, simply write a zero", "if", "(", "value", "==", "null", ")", "{", "writeShort", "(", "0", ")", ";", "return", ";", "}", "// create o...
Writes a pooled string value to the output stream.
[ "Writes", "a", "pooled", "string", "value", "to", "the", "output", "stream", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/ObjectOutputStream.java#L84-L119
train
threerings/narya
core/src/main/java/com/threerings/io/ObjectOutputStream.java
ObjectOutputStream.writeClassMapping
protected ClassMapping writeClassMapping (Class<?> sclass) throws IOException { // create our classmap if necessary if (_classmap == null) { _classmap = Maps.newHashMap(); } // look up the class mapping record ClassMapping cmap = _classmap.get(sclass); // create a class mapping for this class if we've not got one if (cmap == null) { // see if we just want to use an existing class mapping Class<?> collClass = Streamer.getCollectionClass(sclass); if (collClass != null && !collClass.equals(sclass)) { cmap = writeClassMapping(collClass); _classmap.put(sclass, cmap); return cmap; } // create a streamer instance and assign a code to this class Streamer streamer = Streamer.getStreamer(sclass); // we specifically do not inline the getStreamer() call into the ClassMapping // constructor because we want to be sure not to call _nextClassCode++ if getStreamer() // throws an exception if (ObjectInputStream.STREAM_DEBUG) { log.info(hashCode() + ": Creating class mapping", "code", _nextClassCode, "class", sclass.getName()); } cmap = createClassMapping(_nextClassCode++, sclass, streamer); _classmap.put(sclass, cmap); // make sure we didn't blow past our maximum class count if (_nextClassCode <= 0) { throw new RuntimeException("Too many unique classes written to ObjectOutputStream"); } writeNewClassMapping(cmap); } else { writeExistingClassMapping(cmap); } return cmap; }
java
protected ClassMapping writeClassMapping (Class<?> sclass) throws IOException { // create our classmap if necessary if (_classmap == null) { _classmap = Maps.newHashMap(); } // look up the class mapping record ClassMapping cmap = _classmap.get(sclass); // create a class mapping for this class if we've not got one if (cmap == null) { // see if we just want to use an existing class mapping Class<?> collClass = Streamer.getCollectionClass(sclass); if (collClass != null && !collClass.equals(sclass)) { cmap = writeClassMapping(collClass); _classmap.put(sclass, cmap); return cmap; } // create a streamer instance and assign a code to this class Streamer streamer = Streamer.getStreamer(sclass); // we specifically do not inline the getStreamer() call into the ClassMapping // constructor because we want to be sure not to call _nextClassCode++ if getStreamer() // throws an exception if (ObjectInputStream.STREAM_DEBUG) { log.info(hashCode() + ": Creating class mapping", "code", _nextClassCode, "class", sclass.getName()); } cmap = createClassMapping(_nextClassCode++, sclass, streamer); _classmap.put(sclass, cmap); // make sure we didn't blow past our maximum class count if (_nextClassCode <= 0) { throw new RuntimeException("Too many unique classes written to ObjectOutputStream"); } writeNewClassMapping(cmap); } else { writeExistingClassMapping(cmap); } return cmap; }
[ "protected", "ClassMapping", "writeClassMapping", "(", "Class", "<", "?", ">", "sclass", ")", "throws", "IOException", "{", "// create our classmap if necessary", "if", "(", "_classmap", "==", "null", ")", "{", "_classmap", "=", "Maps", ".", "newHashMap", "(", "...
Retrieves or creates the class mapping for the supplied class, writes it out to the stream, and returns a reference to it.
[ "Retrieves", "or", "creates", "the", "class", "mapping", "for", "the", "supplied", "class", "writes", "it", "out", "to", "the", "stream", "and", "returns", "a", "reference", "to", "it", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/ObjectOutputStream.java#L162-L205
train
threerings/narya
core/src/main/java/com/threerings/io/ObjectOutputStream.java
ObjectOutputStream.writeClassMapping
protected void writeClassMapping (int code, Class<?> sclass) throws IOException { writeShort(code); String cname = sclass.getName(); if (_translations != null) { String tname = _translations.get(cname); if (tname != null) { cname = tname; } } writeUTF(cname); }
java
protected void writeClassMapping (int code, Class<?> sclass) throws IOException { writeShort(code); String cname = sclass.getName(); if (_translations != null) { String tname = _translations.get(cname); if (tname != null) { cname = tname; } } writeUTF(cname); }
[ "protected", "void", "writeClassMapping", "(", "int", "code", ",", "Class", "<", "?", ">", "sclass", ")", "throws", "IOException", "{", "writeShort", "(", "code", ")", ";", "String", "cname", "=", "sclass", ".", "getName", "(", ")", ";", "if", "(", "_t...
Writes out the mapping for a class.
[ "Writes", "out", "the", "mapping", "for", "a", "class", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/io/ObjectOutputStream.java#L237-L249
train
threerings/narya
core/src/main/java/com/threerings/presents/data/TimeBaseMarshaller.java
TimeBaseMarshaller.getTimeOid
public void getTimeOid (String arg1, TimeBaseService.GotTimeBaseListener arg2) { TimeBaseMarshaller.GotTimeBaseMarshaller listener2 = new TimeBaseMarshaller.GotTimeBaseMarshaller(); listener2.listener = arg2; sendRequest(GET_TIME_OID, new Object[] { arg1, listener2 }); }
java
public void getTimeOid (String arg1, TimeBaseService.GotTimeBaseListener arg2) { TimeBaseMarshaller.GotTimeBaseMarshaller listener2 = new TimeBaseMarshaller.GotTimeBaseMarshaller(); listener2.listener = arg2; sendRequest(GET_TIME_OID, new Object[] { arg1, listener2 }); }
[ "public", "void", "getTimeOid", "(", "String", "arg1", ",", "TimeBaseService", ".", "GotTimeBaseListener", "arg2", ")", "{", "TimeBaseMarshaller", ".", "GotTimeBaseMarshaller", "listener2", "=", "new", "TimeBaseMarshaller", ".", "GotTimeBaseMarshaller", "(", ")", ";",...
from interface TimeBaseService
[ "from", "interface", "TimeBaseService" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/data/TimeBaseMarshaller.java#L76-L83
train
threerings/narya
core/src/main/java/com/threerings/presents/util/DatagramSequencer.java
DatagramSequencer.writeDatagram
public synchronized void writeDatagram (Message datagram) throws IOException { // first write the sequence and acknowledge numbers _uout.writeInt(++_lastNumber); _uout.writeInt(_lastReceived); // make sure the mapped sets are clear Set<Class<?>> mappedClasses = _uout.getMappedClasses(); mappedClasses.clear(); Set<String> mappedInterns = _uout.getMappedInterns(); mappedInterns.clear(); // write the object _uout.writeObject(datagram); // if we wrote any class mappings, we will keep them in the send record if (mappedClasses.isEmpty()) { mappedClasses = null; } else { _uout.setMappedClasses(new HashSet<Class<?>>()); } // likewise with the intern mappings if (mappedInterns.isEmpty()) { mappedInterns = null; } else { _uout.setMappedInterns(new HashSet<String>()); } // record the transmission _sendrecs.add(new SendRecord(_lastNumber, mappedClasses, mappedInterns)); }
java
public synchronized void writeDatagram (Message datagram) throws IOException { // first write the sequence and acknowledge numbers _uout.writeInt(++_lastNumber); _uout.writeInt(_lastReceived); // make sure the mapped sets are clear Set<Class<?>> mappedClasses = _uout.getMappedClasses(); mappedClasses.clear(); Set<String> mappedInterns = _uout.getMappedInterns(); mappedInterns.clear(); // write the object _uout.writeObject(datagram); // if we wrote any class mappings, we will keep them in the send record if (mappedClasses.isEmpty()) { mappedClasses = null; } else { _uout.setMappedClasses(new HashSet<Class<?>>()); } // likewise with the intern mappings if (mappedInterns.isEmpty()) { mappedInterns = null; } else { _uout.setMappedInterns(new HashSet<String>()); } // record the transmission _sendrecs.add(new SendRecord(_lastNumber, mappedClasses, mappedInterns)); }
[ "public", "synchronized", "void", "writeDatagram", "(", "Message", "datagram", ")", "throws", "IOException", "{", "// first write the sequence and acknowledge numbers", "_uout", ".", "writeInt", "(", "++", "_lastNumber", ")", ";", "_uout", ".", "writeInt", "(", "_last...
Writes a datagram to the underlying stream.
[ "Writes", "a", "datagram", "to", "the", "underlying", "stream", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/DatagramSequencer.java#L55-L89
train
threerings/narya
core/src/main/java/com/threerings/presents/util/DatagramSequencer.java
DatagramSequencer.readDatagram
public synchronized Message readDatagram () throws IOException, ClassNotFoundException { // read in the sequence number and determine if it's out-of-order int number = _uin.readInt(); if (number <= _lastReceived) { return null; } _missedCount = number - _lastReceived - 1; _lastReceived = number; // read the acknowledge number and process all send records up to that one int received = _uin.readInt(); int remove = 0; for (int ii = 0, nn = _sendrecs.size(); ii < nn; ii++) { SendRecord sendrec = _sendrecs.get(ii); if (sendrec.number > received) { break; } remove++; if (sendrec.number == received) { if (sendrec.mappedClasses != null) { _uout.noteClassMappingsReceived(sendrec.mappedClasses); } if (sendrec.mappedInterns != null) { _uout.noteInternMappingsReceived(sendrec.mappedInterns); } } } if (remove > 0) { _sendrecs.subList(0, remove).clear(); } // read the contents of the datagram, note the transport, and return Message datagram = (Message)_uin.readObject(); datagram.setTransport(Transport.UNRELIABLE_ORDERED); return datagram; }
java
public synchronized Message readDatagram () throws IOException, ClassNotFoundException { // read in the sequence number and determine if it's out-of-order int number = _uin.readInt(); if (number <= _lastReceived) { return null; } _missedCount = number - _lastReceived - 1; _lastReceived = number; // read the acknowledge number and process all send records up to that one int received = _uin.readInt(); int remove = 0; for (int ii = 0, nn = _sendrecs.size(); ii < nn; ii++) { SendRecord sendrec = _sendrecs.get(ii); if (sendrec.number > received) { break; } remove++; if (sendrec.number == received) { if (sendrec.mappedClasses != null) { _uout.noteClassMappingsReceived(sendrec.mappedClasses); } if (sendrec.mappedInterns != null) { _uout.noteInternMappingsReceived(sendrec.mappedInterns); } } } if (remove > 0) { _sendrecs.subList(0, remove).clear(); } // read the contents of the datagram, note the transport, and return Message datagram = (Message)_uin.readObject(); datagram.setTransport(Transport.UNRELIABLE_ORDERED); return datagram; }
[ "public", "synchronized", "Message", "readDatagram", "(", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "// read in the sequence number and determine if it's out-of-order", "int", "number", "=", "_uin", ".", "readInt", "(", ")", ";", "if", "(", "numb...
Reads a datagram from the underlying stream. @return the contents of the datagram, or <code>null</code> if the datagram was received out-of-order.
[ "Reads", "a", "datagram", "from", "the", "underlying", "stream", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/DatagramSequencer.java#L97-L134
train
threerings/narya
core/src/main/java/com/threerings/crowd/server/PlaceManagerDelegate.java
PlaceManagerDelegate.addProvider
protected <T extends InvocationMarshaller<?>> T addProvider ( InvocationProvider prov, Class<T> mclass) { return _plmgr.addProvider(prov, mclass); }
java
protected <T extends InvocationMarshaller<?>> T addProvider ( InvocationProvider prov, Class<T> mclass) { return _plmgr.addProvider(prov, mclass); }
[ "protected", "<", "T", "extends", "InvocationMarshaller", "<", "?", ">", ">", "T", "addProvider", "(", "InvocationProvider", "prov", ",", "Class", "<", "T", ">", "mclass", ")", "{", "return", "_plmgr", ".", "addProvider", "(", "prov", ",", "mclass", ")", ...
Registers an invocation provider and notes the registration such that it will be automatically cleared when our parent manager shuts down.
[ "Registers", "an", "invocation", "provider", "and", "notes", "the", "registration", "such", "that", "it", "will", "be", "automatically", "cleared", "when", "our", "parent", "manager", "shuts", "down", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/server/PlaceManagerDelegate.java#L118-L122
train
threerings/narya
core/src/main/java/com/threerings/crowd/server/PlaceManagerDelegate.java
PlaceManagerDelegate.addDispatcher
protected <T extends InvocationMarshaller<?>> T addDispatcher (InvocationDispatcher<T> disp) { return _plmgr.addDispatcher(disp); }
java
protected <T extends InvocationMarshaller<?>> T addDispatcher (InvocationDispatcher<T> disp) { return _plmgr.addDispatcher(disp); }
[ "protected", "<", "T", "extends", "InvocationMarshaller", "<", "?", ">", ">", "T", "addDispatcher", "(", "InvocationDispatcher", "<", "T", ">", "disp", ")", "{", "return", "_plmgr", ".", "addDispatcher", "(", "disp", ")", ";", "}" ]
Registers an invocation dispatcher and notes the registration such that it will be automatically cleared when our parent manager shuts down.
[ "Registers", "an", "invocation", "dispatcher", "and", "notes", "the", "registration", "such", "that", "it", "will", "be", "automatically", "cleared", "when", "our", "parent", "manager", "shuts", "down", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/server/PlaceManagerDelegate.java#L128-L131
train
threerings/narya
core/src/main/java/com/threerings/presents/net/SecureResponse.java
SecureResponse.createSecret
public byte[] createSecret (PublicKeyCredentials pkcred, PrivateKey key, int length) { _data = new AuthResponseData(); byte[] clientSecret = pkcred.getSecret(key); if (clientSecret == null) { _data.code = FAILED_TO_SECURE; return null; } byte[] secret = SecureUtil.createRandomKey(length); _data.code = StringUtil.hexlate(SecureUtil.xorBytes(secret, clientSecret)); return secret; }
java
public byte[] createSecret (PublicKeyCredentials pkcred, PrivateKey key, int length) { _data = new AuthResponseData(); byte[] clientSecret = pkcred.getSecret(key); if (clientSecret == null) { _data.code = FAILED_TO_SECURE; return null; } byte[] secret = SecureUtil.createRandomKey(length); _data.code = StringUtil.hexlate(SecureUtil.xorBytes(secret, clientSecret)); return secret; }
[ "public", "byte", "[", "]", "createSecret", "(", "PublicKeyCredentials", "pkcred", ",", "PrivateKey", "key", ",", "int", "length", ")", "{", "_data", "=", "new", "AuthResponseData", "(", ")", ";", "byte", "[", "]", "clientSecret", "=", "pkcred", ".", "getS...
Encodes the server secret in the response data, or sets the failed state. @return the server secret if successfully encoded, or null.
[ "Encodes", "the", "server", "secret", "in", "the", "response", "data", "or", "sets", "the", "failed", "state", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/net/SecureResponse.java#L59-L70
train
threerings/narya
core/src/main/java/com/threerings/presents/net/SecureResponse.java
SecureResponse.getCodeBytes
public byte[] getCodeBytes (PublicKeyCredentials pkcreds) { return pkcreds == null || _data.code == null || _data.code.equals(FAILED_TO_SECURE) ? null : SecureUtil.xorBytes(StringUtil.unhexlate(_data.code), pkcreds.getSecret()); }
java
public byte[] getCodeBytes (PublicKeyCredentials pkcreds) { return pkcreds == null || _data.code == null || _data.code.equals(FAILED_TO_SECURE) ? null : SecureUtil.xorBytes(StringUtil.unhexlate(_data.code), pkcreds.getSecret()); }
[ "public", "byte", "[", "]", "getCodeBytes", "(", "PublicKeyCredentials", "pkcreds", ")", "{", "return", "pkcreds", "==", "null", "||", "_data", ".", "code", "==", "null", "||", "_data", ".", "code", ".", "equals", "(", "FAILED_TO_SECURE", ")", "?", "null",...
Returns the code bytes or null for a failed state.
[ "Returns", "the", "code", "bytes", "or", "null", "for", "a", "failed", "state", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/net/SecureResponse.java#L75-L79
train
threerings/narya
core/src/main/java/com/threerings/presents/server/ReportManager.java
ReportManager.activatePeriodicReport
public void activatePeriodicReport (RootDObjectManager omgr) { // queue up an interval which will generate reports as long as the omgr is alive omgr.newInterval(new Runnable() { public void run () { logReport(LOG_REPORT_HEADER + generateReport(DEFAULT_TYPE, System.currentTimeMillis(), true)); } }).schedule(getReportInterval(), true); }
java
public void activatePeriodicReport (RootDObjectManager omgr) { // queue up an interval which will generate reports as long as the omgr is alive omgr.newInterval(new Runnable() { public void run () { logReport(LOG_REPORT_HEADER + generateReport(DEFAULT_TYPE, System.currentTimeMillis(), true)); } }).schedule(getReportInterval(), true); }
[ "public", "void", "activatePeriodicReport", "(", "RootDObjectManager", "omgr", ")", "{", "// queue up an interval which will generate reports as long as the omgr is alive", "omgr", ".", "newInterval", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")...
Starts up our periodic report generation task.
[ "Starts", "up", "our", "periodic", "report", "generation", "task", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/ReportManager.java#L67-L76
train
threerings/narya
core/src/main/java/com/threerings/presents/server/ReportManager.java
ReportManager.generateReport
protected String generateReport (String type, long now, boolean reset) { long sinceLast = now - _lastReportStamp; long uptime = now - _serverStartTime; StringBuilder report = new StringBuilder(); // add standard bits to the default report if (DEFAULT_TYPE.equals(type)) { report.append("- Uptime: "); report.append(StringUtil.intervalToString(uptime)).append("\n"); report.append("- Report period: "); report.append(StringUtil.intervalToString(sinceLast)).append("\n"); // report on the state of memory Runtime rt = Runtime.getRuntime(); long total = rt.totalMemory(), max = rt.maxMemory(); long used = (total - rt.freeMemory()); report.append("- Memory: ").append(used/1024).append("k used, "); report.append(total/1024).append("k total, "); report.append(max/1024).append("k max\n"); } for (Reporter rptr : _reporters.get(type)) { try { rptr.appendReport(report, now, sinceLast, reset); } catch (Throwable t) { log.warning("Reporter choked", "rptr", rptr, t); } } /* The following Interval debug methods are no longer supported, * but they could be added back easily if needed. report.append("* samskivert.Interval:\n"); report.append("- Registered intervals: "); report.append(Interval.registeredIntervalCount()); report.append("\n- Fired since last report: "); report.append(Interval.getAndClearFiredIntervals()); report.append("\n"); */ // strip off the final newline int blen = report.length(); if (report.length() > 0 && report.charAt(blen-1) == '\n') { report.delete(blen-1, blen); } // only reset the last report time if this is a periodic report if (reset) { _lastReportStamp = now; } return report.toString(); }
java
protected String generateReport (String type, long now, boolean reset) { long sinceLast = now - _lastReportStamp; long uptime = now - _serverStartTime; StringBuilder report = new StringBuilder(); // add standard bits to the default report if (DEFAULT_TYPE.equals(type)) { report.append("- Uptime: "); report.append(StringUtil.intervalToString(uptime)).append("\n"); report.append("- Report period: "); report.append(StringUtil.intervalToString(sinceLast)).append("\n"); // report on the state of memory Runtime rt = Runtime.getRuntime(); long total = rt.totalMemory(), max = rt.maxMemory(); long used = (total - rt.freeMemory()); report.append("- Memory: ").append(used/1024).append("k used, "); report.append(total/1024).append("k total, "); report.append(max/1024).append("k max\n"); } for (Reporter rptr : _reporters.get(type)) { try { rptr.appendReport(report, now, sinceLast, reset); } catch (Throwable t) { log.warning("Reporter choked", "rptr", rptr, t); } } /* The following Interval debug methods are no longer supported, * but they could be added back easily if needed. report.append("* samskivert.Interval:\n"); report.append("- Registered intervals: "); report.append(Interval.registeredIntervalCount()); report.append("\n- Fired since last report: "); report.append(Interval.getAndClearFiredIntervals()); report.append("\n"); */ // strip off the final newline int blen = report.length(); if (report.length() > 0 && report.charAt(blen-1) == '\n') { report.delete(blen-1, blen); } // only reset the last report time if this is a periodic report if (reset) { _lastReportStamp = now; } return report.toString(); }
[ "protected", "String", "generateReport", "(", "String", "type", ",", "long", "now", ",", "boolean", "reset", ")", "{", "long", "sinceLast", "=", "now", "-", "_lastReportStamp", ";", "long", "uptime", "=", "now", "-", "_serverStartTime", ";", "StringBuilder", ...
Generates and logs a "state of server" report.
[ "Generates", "and", "logs", "a", "state", "of", "server", "report", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/server/ReportManager.java#L113-L165
train
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/PeerNode.java
PeerNode.init
public void init (NodeRecord record) { _record = record; _client = new Client(null, _omgr) { @Override protected void convertFromRemote (DObject target, DEvent event) { super.convertFromRemote(target, event); // rewrite the event's target oid using the oid currently configured on the // distributed object (we will have it mapped in our remote server's oid space, // but it may have been remapped into the oid space of the local server) event.setTargetOid(target.getOid()); // assign an eventId to this event so that our stale event detection code can // properly deal with it event.eventId = PeerNode.this._omgr.getNextEventId(true); } @Override protected Communicator createCommunicator () { return PeerNode.this.createCommunicator(this); } @Override protected boolean isFailureLoggable (FailureType type) { return (type != FailureType.UNSUBSCRIBE_NOT_PROXIED) && super.isFailureLoggable(type); } }; _client.addClientObserver(this); _client.getInvocationDirector().setMaximumListenerAge(getMaximumInvocationWait()); }
java
public void init (NodeRecord record) { _record = record; _client = new Client(null, _omgr) { @Override protected void convertFromRemote (DObject target, DEvent event) { super.convertFromRemote(target, event); // rewrite the event's target oid using the oid currently configured on the // distributed object (we will have it mapped in our remote server's oid space, // but it may have been remapped into the oid space of the local server) event.setTargetOid(target.getOid()); // assign an eventId to this event so that our stale event detection code can // properly deal with it event.eventId = PeerNode.this._omgr.getNextEventId(true); } @Override protected Communicator createCommunicator () { return PeerNode.this.createCommunicator(this); } @Override protected boolean isFailureLoggable (FailureType type) { return (type != FailureType.UNSUBSCRIBE_NOT_PROXIED) && super.isFailureLoggable(type); } }; _client.addClientObserver(this); _client.getInvocationDirector().setMaximumListenerAge(getMaximumInvocationWait()); }
[ "public", "void", "init", "(", "NodeRecord", "record", ")", "{", "_record", "=", "record", ";", "_client", "=", "new", "Client", "(", "null", ",", "_omgr", ")", "{", "@", "Override", "protected", "void", "convertFromRemote", "(", "DObject", "target", ",", ...
Initializes this peer node and creates its internal client.
[ "Initializes", "this", "peer", "node", "and", "creates", "its", "internal", "client", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerNode.java#L66-L90
train
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/PeerNode.java
PeerNode.objectAvailable
public void objectAvailable (NodeObject object) { // listen for lock and cache updates nodeobj = object; nodeobj.addListener(_listener = createListener()); _peermgr.connectedToPeer(this); String nodeName = getNodeName(); for (ClientInfo clinfo : nodeobj.clients) { _peermgr.clientLoggedOn(nodeName, clinfo); } for (NodeObject.Lock lock : nodeobj.locks) { _peermgr.peerAddedLock(nodeName, lock); } }
java
public void objectAvailable (NodeObject object) { // listen for lock and cache updates nodeobj = object; nodeobj.addListener(_listener = createListener()); _peermgr.connectedToPeer(this); String nodeName = getNodeName(); for (ClientInfo clinfo : nodeobj.clients) { _peermgr.clientLoggedOn(nodeName, clinfo); } for (NodeObject.Lock lock : nodeobj.locks) { _peermgr.peerAddedLock(nodeName, lock); } }
[ "public", "void", "objectAvailable", "(", "NodeObject", "object", ")", "{", "// listen for lock and cache updates", "nodeobj", "=", "object", ";", "nodeobj", ".", "addListener", "(", "_listener", "=", "createListener", "(", ")", ")", ";", "_peermgr", ".", "connect...
documentation inherited from interface Subscriber
[ "documentation", "inherited", "from", "interface", "Subscriber" ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerNode.java#L246-L261
train
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java
NodeRepository.loadNodes
public List<NodeRecord> loadNodes (String namespace, boolean includeShutdown) { // we specifically avoid caching this query because we want the servers to always see the // most up to date set of nodes Query<NodeRecord> query = from(NodeRecord.class).noCache(); List<SQLExpression<?>> conditions = Lists.newArrayList(); if (!StringUtil.isBlank(namespace)) { conditions.add(NodeRecord.NODE_NAME.like(namespace + "%")); } if (!includeShutdown) { conditions.add(Ops.not(NodeRecord.SHUTDOWN)); } return (conditions.isEmpty() ? query : query.where(conditions)).select(); }
java
public List<NodeRecord> loadNodes (String namespace, boolean includeShutdown) { // we specifically avoid caching this query because we want the servers to always see the // most up to date set of nodes Query<NodeRecord> query = from(NodeRecord.class).noCache(); List<SQLExpression<?>> conditions = Lists.newArrayList(); if (!StringUtil.isBlank(namespace)) { conditions.add(NodeRecord.NODE_NAME.like(namespace + "%")); } if (!includeShutdown) { conditions.add(Ops.not(NodeRecord.SHUTDOWN)); } return (conditions.isEmpty() ? query : query.where(conditions)).select(); }
[ "public", "List", "<", "NodeRecord", ">", "loadNodes", "(", "String", "namespace", ",", "boolean", "includeShutdown", ")", "{", "// we specifically avoid caching this query because we want the servers to always see the", "// most up to date set of nodes", "Query", "<", "NodeRecor...
Returns a list of all nodes registered in the repository with names starting with the given string, optionally including nodes that are explicitly shut down.
[ "Returns", "a", "list", "of", "all", "nodes", "registered", "in", "the", "repository", "with", "names", "starting", "with", "the", "given", "string", "optionally", "including", "nodes", "that", "are", "explicitly", "shut", "down", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java#L78-L91
train
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java
NodeRepository.loadNodesFromRegion
public List<NodeRecord> loadNodesFromRegion (String region) { return from(NodeRecord.class) .noCache() .where(NodeRecord.REGION.eq(region), Ops.not(NodeRecord.SHUTDOWN)) .select(); }
java
public List<NodeRecord> loadNodesFromRegion (String region) { return from(NodeRecord.class) .noCache() .where(NodeRecord.REGION.eq(region), Ops.not(NodeRecord.SHUTDOWN)) .select(); }
[ "public", "List", "<", "NodeRecord", ">", "loadNodesFromRegion", "(", "String", "region", ")", "{", "return", "from", "(", "NodeRecord", ".", "class", ")", ".", "noCache", "(", ")", ".", "where", "(", "NodeRecord", ".", "REGION", ".", "eq", "(", "region"...
Returns a list of nodes registered in the repository with the specified region that are not explicitly shut down.
[ "Returns", "a", "list", "of", "nodes", "registered", "in", "the", "repository", "with", "the", "specified", "region", "that", "are", "not", "explicitly", "shut", "down", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java#L97-L103
train
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java
NodeRepository.updateNode
public void updateNode (NodeRecord record) { record.lastUpdated = new Timestamp(System.currentTimeMillis()); store(record); }
java
public void updateNode (NodeRecord record) { record.lastUpdated = new Timestamp(System.currentTimeMillis()); store(record); }
[ "public", "void", "updateNode", "(", "NodeRecord", "record", ")", "{", "record", ".", "lastUpdated", "=", "new", "Timestamp", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "store", "(", "record", ")", ";", "}" ]
Updates the supplied node record, inserting it into the database if necessary.
[ "Updates", "the", "supplied", "node", "record", "inserting", "it", "into", "the", "database", "if", "necessary", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java#L108-L112
train
threerings/narya
core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java
NodeRepository.shutdownNode
public void shutdownNode (String nodeName) { updatePartial(NodeRecord.getKey(nodeName), NodeRecord.SHUTDOWN, true); }
java
public void shutdownNode (String nodeName) { updatePartial(NodeRecord.getKey(nodeName), NodeRecord.SHUTDOWN, true); }
[ "public", "void", "shutdownNode", "(", "String", "nodeName", ")", "{", "updatePartial", "(", "NodeRecord", ".", "getKey", "(", "nodeName", ")", ",", "NodeRecord", ".", "SHUTDOWN", ",", "true", ")", ";", "}" ]
Marks the identified node as shut down in its record.
[ "Marks", "the", "identified", "node", "as", "shut", "down", "in", "its", "record", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/persist/NodeRepository.java#L127-L130
train
xbib/marc
src/main/java/org/xbib/marc/io/BytesArray.java
BytesArray.split
public List<byte[]> split(byte sep) { List<byte[]> l = new LinkedList<>(); int start = 0; for (int i = 0; i < bytes.length; i++) { if (sep == bytes[i]) { byte[] b = Arrays.copyOfRange(bytes, start, i); if (b.length > 0) { l.add(b); } start = i + 1; i = start; } } l.add(Arrays.copyOfRange(bytes, start, bytes.length)); return l; }
java
public List<byte[]> split(byte sep) { List<byte[]> l = new LinkedList<>(); int start = 0; for (int i = 0; i < bytes.length; i++) { if (sep == bytes[i]) { byte[] b = Arrays.copyOfRange(bytes, start, i); if (b.length > 0) { l.add(b); } start = i + 1; i = start; } } l.add(Arrays.copyOfRange(bytes, start, bytes.length)); return l; }
[ "public", "List", "<", "byte", "[", "]", ">", "split", "(", "byte", "sep", ")", "{", "List", "<", "byte", "[", "]", ">", "l", "=", "new", "LinkedList", "<>", "(", ")", ";", "int", "start", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";...
Split byte array by a separator byte. @param sep the separator @return a list of byte arrays
[ "Split", "byte", "array", "by", "a", "separator", "byte", "." ]
d8426fcfc686507cab59b3d8181b08f83718418c
https://github.com/xbib/marc/blob/d8426fcfc686507cab59b3d8181b08f83718418c/src/main/java/org/xbib/marc/io/BytesArray.java#L113-L128
train
threerings/narya
core/src/main/java/com/threerings/crowd/client/OccupantDirector.java
OccupantDirector.getOccupantInfo
public OccupantInfo getOccupantInfo (int bodyOid) { // make sure we're somewhere return (_place == null) ? null : _place.occupantInfo.get(Integer.valueOf(bodyOid)); }
java
public OccupantInfo getOccupantInfo (int bodyOid) { // make sure we're somewhere return (_place == null) ? null : _place.occupantInfo.get(Integer.valueOf(bodyOid)); }
[ "public", "OccupantInfo", "getOccupantInfo", "(", "int", "bodyOid", ")", "{", "// make sure we're somewhere", "return", "(", "_place", "==", "null", ")", "?", "null", ":", "_place", ".", "occupantInfo", ".", "get", "(", "Integer", ".", "valueOf", "(", "bodyOid...
Returns the occupant info for the user in question if it exists in the currently occupied place. Returns null if no occupant info exists for the specified body.
[ "Returns", "the", "occupant", "info", "for", "the", "user", "in", "question", "if", "it", "exists", "in", "the", "currently", "occupied", "place", ".", "Returns", "null", "if", "no", "occupant", "info", "exists", "for", "the", "specified", "body", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/client/OccupantDirector.java#L95-L99
train
threerings/narya
core/src/main/java/com/threerings/crowd/client/OccupantDirector.java
OccupantDirector.getOccupantInfo
public OccupantInfo getOccupantInfo (Name username) { return (_place == null) ? null : _place.getOccupantInfo(username); }
java
public OccupantInfo getOccupantInfo (Name username) { return (_place == null) ? null : _place.getOccupantInfo(username); }
[ "public", "OccupantInfo", "getOccupantInfo", "(", "Name", "username", ")", "{", "return", "(", "_place", "==", "null", ")", "?", "null", ":", "_place", ".", "getOccupantInfo", "(", "username", ")", ";", "}" ]
Returns the occupant info for the user in question if it exists in the currently occupied place. Returns null if no occupant info exists with the specified username.
[ "Returns", "the", "occupant", "info", "for", "the", "user", "in", "question", "if", "it", "exists", "in", "the", "currently", "occupied", "place", ".", "Returns", "null", "if", "no", "occupant", "info", "exists", "with", "the", "specified", "username", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/client/OccupantDirector.java#L106-L109
train
threerings/narya
core/src/main/java/com/threerings/crowd/client/OccupantDirector.java
OccupantDirector.entryAdded
public void entryAdded (EntryAddedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // now let the occupant observers know what's up final OccupantInfo info = event.getEntry(); _observers.apply(new ObserverList.ObserverOp<OccupantObserver>() { public boolean apply (OccupantObserver observer) { observer.occupantEntered(info); return true; } }); }
java
public void entryAdded (EntryAddedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // now let the occupant observers know what's up final OccupantInfo info = event.getEntry(); _observers.apply(new ObserverList.ObserverOp<OccupantObserver>() { public boolean apply (OccupantObserver observer) { observer.occupantEntered(info); return true; } }); }
[ "public", "void", "entryAdded", "(", "EntryAddedEvent", "<", "OccupantInfo", ">", "event", ")", "{", "// bail if this isn't for the OCCUPANT_INFO field", "if", "(", "!", "event", ".", "getName", "(", ")", ".", "equals", "(", "PlaceObject", ".", "OCCUPANT_INFO", ")...
Deals with all of the processing when an occupant shows up.
[ "Deals", "with", "all", "of", "the", "processing", "when", "an", "occupant", "shows", "up", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/client/OccupantDirector.java#L152-L167
train
threerings/narya
core/src/main/java/com/threerings/crowd/client/OccupantDirector.java
OccupantDirector.entryUpdated
public void entryUpdated (EntryUpdatedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // now let the occupant observers know what's up final OccupantInfo info = event.getEntry(); final OccupantInfo oinfo = event.getOldEntry(); _observers.apply(new ObserverList.ObserverOp<OccupantObserver>() { public boolean apply (OccupantObserver observer) { observer.occupantUpdated(oinfo, info); return true; } }); }
java
public void entryUpdated (EntryUpdatedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // now let the occupant observers know what's up final OccupantInfo info = event.getEntry(); final OccupantInfo oinfo = event.getOldEntry(); _observers.apply(new ObserverList.ObserverOp<OccupantObserver>() { public boolean apply (OccupantObserver observer) { observer.occupantUpdated(oinfo, info); return true; } }); }
[ "public", "void", "entryUpdated", "(", "EntryUpdatedEvent", "<", "OccupantInfo", ">", "event", ")", "{", "// bail if this isn't for the OCCUPANT_INFO field", "if", "(", "!", "event", ".", "getName", "(", ")", ".", "equals", "(", "PlaceObject", ".", "OCCUPANT_INFO", ...
Deals with all of the processing when an occupant is updated.
[ "Deals", "with", "all", "of", "the", "processing", "when", "an", "occupant", "is", "updated", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/client/OccupantDirector.java#L172-L188
train
threerings/narya
core/src/main/java/com/threerings/crowd/client/OccupantDirector.java
OccupantDirector.entryRemoved
public void entryRemoved (EntryRemovedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // let the occupant observers know what's up final OccupantInfo oinfo = event.getOldEntry(); _observers.apply(new ObserverList.ObserverOp<OccupantObserver>() { public boolean apply (OccupantObserver observer) { observer.occupantLeft(oinfo); return true; } }); }
java
public void entryRemoved (EntryRemovedEvent<OccupantInfo> event) { // bail if this isn't for the OCCUPANT_INFO field if (!event.getName().equals(PlaceObject.OCCUPANT_INFO)) { return; } // let the occupant observers know what's up final OccupantInfo oinfo = event.getOldEntry(); _observers.apply(new ObserverList.ObserverOp<OccupantObserver>() { public boolean apply (OccupantObserver observer) { observer.occupantLeft(oinfo); return true; } }); }
[ "public", "void", "entryRemoved", "(", "EntryRemovedEvent", "<", "OccupantInfo", ">", "event", ")", "{", "// bail if this isn't for the OCCUPANT_INFO field", "if", "(", "!", "event", ".", "getName", "(", ")", ".", "equals", "(", "PlaceObject", ".", "OCCUPANT_INFO", ...
Deals with all of the processing when an occupant leaves.
[ "Deals", "with", "all", "of", "the", "processing", "when", "an", "occupant", "leaves", "." ]
5b01edc8850ed0c32d004b4049e1ac4a02027ede
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/client/OccupantDirector.java#L193-L208
train
Gperez88/CalculatorInputView
calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/CalculatorBuilder.java
CalculatorBuilder.start
public void start(Activity activity) { Intent i = new Intent(activity, CalculatorActivity.class); if (!TextUtils.isEmpty(activityTitle)) { i.putExtra(CalculatorActivity.TITLE_ACTIVITY, activityTitle); } if (!TextUtils.isEmpty(value)) { i.putExtra(CalculatorActivity.VALUE, value); } activity.startActivityForResult(i, CalculatorActivity.REQUEST_RESULT_SUCCESSFUL); }
java
public void start(Activity activity) { Intent i = new Intent(activity, CalculatorActivity.class); if (!TextUtils.isEmpty(activityTitle)) { i.putExtra(CalculatorActivity.TITLE_ACTIVITY, activityTitle); } if (!TextUtils.isEmpty(value)) { i.putExtra(CalculatorActivity.VALUE, value); } activity.startActivityForResult(i, CalculatorActivity.REQUEST_RESULT_SUCCESSFUL); }
[ "public", "void", "start", "(", "Activity", "activity", ")", "{", "Intent", "i", "=", "new", "Intent", "(", "activity", ",", "CalculatorActivity", ".", "class", ")", ";", "if", "(", "!", "TextUtils", ".", "isEmpty", "(", "activityTitle", ")", ")", "{", ...
Start the activity using the parent activity @param activity the current activity
[ "Start", "the", "activity", "using", "the", "parent", "activity" ]
735029095fbcbd32d25cde65529061903f522a89
https://github.com/Gperez88/CalculatorInputView/blob/735029095fbcbd32d25cde65529061903f522a89/calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/CalculatorBuilder.java#L44-L55
train
Gperez88/CalculatorInputView
calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/CalculatorBuilder.java
CalculatorBuilder.start
public void start(Fragment fragment) { Intent i = new Intent(fragment.getContext(), CalculatorActivity.class); if (!TextUtils.isEmpty(activityTitle)) { i.putExtra(CalculatorActivity.TITLE_ACTIVITY, activityTitle); } if (!TextUtils.isEmpty(value)) { i.putExtra(CalculatorActivity.VALUE, value); } fragment.startActivityForResult(i, CalculatorActivity.REQUEST_RESULT_SUCCESSFUL); }
java
public void start(Fragment fragment) { Intent i = new Intent(fragment.getContext(), CalculatorActivity.class); if (!TextUtils.isEmpty(activityTitle)) { i.putExtra(CalculatorActivity.TITLE_ACTIVITY, activityTitle); } if (!TextUtils.isEmpty(value)) { i.putExtra(CalculatorActivity.VALUE, value); } fragment.startActivityForResult(i, CalculatorActivity.REQUEST_RESULT_SUCCESSFUL); }
[ "public", "void", "start", "(", "Fragment", "fragment", ")", "{", "Intent", "i", "=", "new", "Intent", "(", "fragment", ".", "getContext", "(", ")", ",", "CalculatorActivity", ".", "class", ")", ";", "if", "(", "!", "TextUtils", ".", "isEmpty", "(", "a...
Start the activity using the parent fragment @param fragment the current fragment
[ "Start", "the", "activity", "using", "the", "parent", "fragment" ]
735029095fbcbd32d25cde65529061903f522a89
https://github.com/Gperez88/CalculatorInputView/blob/735029095fbcbd32d25cde65529061903f522a89/calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/CalculatorBuilder.java#L62-L73
train
twotoasters/SectionCursorAdapter
library/src/main/java/com/twotoasters/sectioncursoradapter/SectionCursorAdapter.java
SectionCursorAdapter.getIndexWithinSections
public int getIndexWithinSections(int listPosition) { boolean isSection = false; int numPrecedingSections = 0; for (Integer sectionPosition : mSections.keySet()) { if (listPosition > sectionPosition) numPrecedingSections++; else if (listPosition == sectionPosition) isSection = true; else break; } return isSection ? numPrecedingSections : Math.max(numPrecedingSections - 1, 0); }
java
public int getIndexWithinSections(int listPosition) { boolean isSection = false; int numPrecedingSections = 0; for (Integer sectionPosition : mSections.keySet()) { if (listPosition > sectionPosition) numPrecedingSections++; else if (listPosition == sectionPosition) isSection = true; else break; } return isSection ? numPrecedingSections : Math.max(numPrecedingSections - 1, 0); }
[ "public", "int", "getIndexWithinSections", "(", "int", "listPosition", ")", "{", "boolean", "isSection", "=", "false", ";", "int", "numPrecedingSections", "=", "0", ";", "for", "(", "Integer", "sectionPosition", ":", "mSections", ".", "keySet", "(", ")", ")", ...
Finds the section index for a given list position. @param listPosition the position of the current item in the list with mSections included @return an index in an ordered list of section names
[ "Finds", "the", "section", "index", "for", "a", "given", "list", "position", "." ]
f74a52894f0ad8b809ff1e0298cc5f9068c8dcb8
https://github.com/twotoasters/SectionCursorAdapter/blob/f74a52894f0ad8b809ff1e0298cc5f9068c8dcb8/library/src/main/java/com/twotoasters/sectioncursoradapter/SectionCursorAdapter.java#L226-L238
train
twotoasters/SectionCursorAdapter
library/src/main/java/com/twotoasters/sectioncursoradapter/SectionCursorAdapter.java
SectionCursorAdapter.getPositionForSection
@Override public int getPositionForSection(int sectionIndex) { if (mSectionList.size() == 0) { for (Integer key : mSections.keySet()) { mSectionList.add(key); } } return sectionIndex < mSectionList.size() ? mSectionList.get(sectionIndex) : getCount(); }
java
@Override public int getPositionForSection(int sectionIndex) { if (mSectionList.size() == 0) { for (Integer key : mSections.keySet()) { mSectionList.add(key); } } return sectionIndex < mSectionList.size() ? mSectionList.get(sectionIndex) : getCount(); }
[ "@", "Override", "public", "int", "getPositionForSection", "(", "int", "sectionIndex", ")", "{", "if", "(", "mSectionList", ".", "size", "(", ")", "==", "0", ")", "{", "for", "(", "Integer", "key", ":", "mSections", ".", "keySet", "(", ")", ")", "{", ...
Given the index of a section within the array of section objects, returns the starting position of that section within the adapter. If the section's starting position is outside of the adapter bounds, the position must be clipped to fall within the size of the adapter. @param sectionIndex the index of the section within the array of section objects @return the starting position of that section within the adapter, constrained to fall within the adapter bounds
[ "Given", "the", "index", "of", "a", "section", "within", "the", "array", "of", "section", "objects", "returns", "the", "starting", "position", "of", "that", "section", "within", "the", "adapter", "." ]
f74a52894f0ad8b809ff1e0298cc5f9068c8dcb8
https://github.com/twotoasters/SectionCursorAdapter/blob/f74a52894f0ad8b809ff1e0298cc5f9068c8dcb8/library/src/main/java/com/twotoasters/sectioncursoradapter/SectionCursorAdapter.java#L357-L365
train
twotoasters/SectionCursorAdapter
library/src/main/java/com/twotoasters/sectioncursoradapter/SectionCursorAdapter.java
SectionCursorAdapter.getSectionForPosition
@Override public int getSectionForPosition(int position) { Object[] objects = getSections(); // the fast scroll section objects int sectionIndex = getIndexWithinSections(position); return sectionIndex < objects.length ? sectionIndex : 0; }
java
@Override public int getSectionForPosition(int position) { Object[] objects = getSections(); // the fast scroll section objects int sectionIndex = getIndexWithinSections(position); return sectionIndex < objects.length ? sectionIndex : 0; }
[ "@", "Override", "public", "int", "getSectionForPosition", "(", "int", "position", ")", "{", "Object", "[", "]", "objects", "=", "getSections", "(", ")", ";", "// the fast scroll section objects", "int", "sectionIndex", "=", "getIndexWithinSections", "(", "position"...
Given a position within the adapter, returns the index of the corresponding section within the array of section objects. If the section index is outside of the section array bounds, the index must be clipped to fall within the size of the section array. For example, consider an indexer where the section at array index 0 starts at adapter position 100. Calling this method with position 10, which is before the first section, must return index 0. @param position the position within the adapter for which to return the corresponding section index @return the index of the corresponding section within the array of section objects, constrained to fall within the array bounds
[ "Given", "a", "position", "within", "the", "adapter", "returns", "the", "index", "of", "the", "corresponding", "section", "within", "the", "array", "of", "section", "objects", "." ]
f74a52894f0ad8b809ff1e0298cc5f9068c8dcb8
https://github.com/twotoasters/SectionCursorAdapter/blob/f74a52894f0ad8b809ff1e0298cc5f9068c8dcb8/library/src/main/java/com/twotoasters/sectioncursoradapter/SectionCursorAdapter.java#L383-L389
train
Gperez88/CalculatorInputView
calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/widget/NumericEditText.java
NumericEditText.getNumericValue
public double getNumericValue() { String original = getText().toString().replaceAll(mNumberFilterRegex, ""); if (hasCustomDecimalSeparator) { // swap custom decimal separator with locale one to allow parsing original = StringUtils.replace(original, String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR)); } try { return NumberFormat.getInstance().parse(original).doubleValue(); } catch (ParseException e) { return Double.NaN; } }
java
public double getNumericValue() { String original = getText().toString().replaceAll(mNumberFilterRegex, ""); if (hasCustomDecimalSeparator) { // swap custom decimal separator with locale one to allow parsing original = StringUtils.replace(original, String.valueOf(mDecimalSeparator), String.valueOf(DECIMAL_SEPARATOR)); } try { return NumberFormat.getInstance().parse(original).doubleValue(); } catch (ParseException e) { return Double.NaN; } }
[ "public", "double", "getNumericValue", "(", ")", "{", "String", "original", "=", "getText", "(", ")", ".", "toString", "(", ")", ".", "replaceAll", "(", "mNumberFilterRegex", ",", "\"\"", ")", ";", "if", "(", "hasCustomDecimalSeparator", ")", "{", "// swap c...
Return numeric value represented by the text field @return numeric value
[ "Return", "numeric", "value", "represented", "by", "the", "text", "field" ]
735029095fbcbd32d25cde65529061903f522a89
https://github.com/Gperez88/CalculatorInputView/blob/735029095fbcbd32d25cde65529061903f522a89/calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/widget/NumericEditText.java#L160-L173
train
Gperez88/CalculatorInputView
calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/widget/NumericEditText.java
NumericEditText.format
private String format(final String original) { final String[] parts = original.split("\\" + mDecimalSeparator, -1); String number = parts[0] // since we split with limit -1 there will always be at least 1 part .replaceAll(mNumberFilterRegex, "") .replaceFirst(LEADING_ZERO_FILTER_REGEX, ""); // only add grouping separators for non custom decimal separator if (!hasCustomDecimalSeparator) { // add grouping separators, need to reverse back and forth since Java regex does not support // right to left matching number = StringUtils.reverse( StringUtils.reverse(number).replaceAll("(.{3})", "$1" + GROUPING_SEPARATOR)); // remove leading grouping separator if any number = StringUtils.removeStart(number, String.valueOf(GROUPING_SEPARATOR)); } // add fraction part if any if (parts.length > 1) { if (parts[1].length() > 2) { number += mDecimalSeparator + parts[1].substring(parts[1].length() - 2, parts[1].length()); } else { number += mDecimalSeparator + parts[1]; } } return number; }
java
private String format(final String original) { final String[] parts = original.split("\\" + mDecimalSeparator, -1); String number = parts[0] // since we split with limit -1 there will always be at least 1 part .replaceAll(mNumberFilterRegex, "") .replaceFirst(LEADING_ZERO_FILTER_REGEX, ""); // only add grouping separators for non custom decimal separator if (!hasCustomDecimalSeparator) { // add grouping separators, need to reverse back and forth since Java regex does not support // right to left matching number = StringUtils.reverse( StringUtils.reverse(number).replaceAll("(.{3})", "$1" + GROUPING_SEPARATOR)); // remove leading grouping separator if any number = StringUtils.removeStart(number, String.valueOf(GROUPING_SEPARATOR)); } // add fraction part if any if (parts.length > 1) { if (parts[1].length() > 2) { number += mDecimalSeparator + parts[1].substring(parts[1].length() - 2, parts[1].length()); } else { number += mDecimalSeparator + parts[1]; } } return number; }
[ "private", "String", "format", "(", "final", "String", "original", ")", "{", "final", "String", "[", "]", "parts", "=", "original", ".", "split", "(", "\"\\\\\"", "+", "mDecimalSeparator", ",", "-", "1", ")", ";", "String", "number", "=", "parts", "[", ...
Add grouping separators to string @param original original string, may already contains incorrect grouping separators @return string with correct grouping separators
[ "Add", "grouping", "separators", "to", "string" ]
735029095fbcbd32d25cde65529061903f522a89
https://github.com/Gperez88/CalculatorInputView/blob/735029095fbcbd32d25cde65529061903f522a89/calculatorInputView/src/main/java/com/gp89developers/calculatorinputview/widget/NumericEditText.java#L181-L207
train
kiegroup/jbpmmigration
src/main/java/org/jbpm/migration/XmlUtils.java
XmlUtils.createEmptyDocument
public static Document createEmptyDocument() { Document output = null; try { final DocumentBuilder db = FACTORY.newDocumentBuilder(); db.setErrorHandler(new ParserErrorHandler()); output = db.newDocument(); } catch (final Exception ex) { LOGGER.error("Problem creating empty XML document.", ex); } return output; }
java
public static Document createEmptyDocument() { Document output = null; try { final DocumentBuilder db = FACTORY.newDocumentBuilder(); db.setErrorHandler(new ParserErrorHandler()); output = db.newDocument(); } catch (final Exception ex) { LOGGER.error("Problem creating empty XML document.", ex); } return output; }
[ "public", "static", "Document", "createEmptyDocument", "(", ")", "{", "Document", "output", "=", "null", ";", "try", "{", "final", "DocumentBuilder", "db", "=", "FACTORY", ".", "newDocumentBuilder", "(", ")", ";", "db", ".", "setErrorHandler", "(", "new", "P...
Create an empty XML structure. @return An empty DOM tree.
[ "Create", "an", "empty", "XML", "structure", "." ]
5e133e2824aa38f316a2eb061123313a7276aba0
https://github.com/kiegroup/jbpmmigration/blob/5e133e2824aa38f316a2eb061123313a7276aba0/src/main/java/org/jbpm/migration/XmlUtils.java#L75-L86
train
kiegroup/jbpmmigration
src/main/java/org/jbpm/migration/XmlUtils.java
XmlUtils.validate
public static boolean validate(final Source input, final Source[] schemas) { boolean isValid = true; try { final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new SchemaLSResourceResolver()); final Validator val = factory.newSchema(schemas).newValidator(); final ParserErrorHandler eh = new ParserErrorHandler(); val.setErrorHandler(eh); val.validate(input); if (eh.didErrorOccur()) { isValid = false; eh.logErrors(LOGGER); } } catch (final Exception ex) { LOGGER.error("Problem validating the given process definition.", ex); isValid = false; } return isValid; }
java
public static boolean validate(final Source input, final Source[] schemas) { boolean isValid = true; try { final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setResourceResolver(new SchemaLSResourceResolver()); final Validator val = factory.newSchema(schemas).newValidator(); final ParserErrorHandler eh = new ParserErrorHandler(); val.setErrorHandler(eh); val.validate(input); if (eh.didErrorOccur()) { isValid = false; eh.logErrors(LOGGER); } } catch (final Exception ex) { LOGGER.error("Problem validating the given process definition.", ex); isValid = false; } return isValid; }
[ "public", "static", "boolean", "validate", "(", "final", "Source", "input", ",", "final", "Source", "[", "]", "schemas", ")", "{", "boolean", "isValid", "=", "true", ";", "try", "{", "final", "SchemaFactory", "factory", "=", "SchemaFactory", ".", "newInstanc...
Validate an XML document against an XML Schema definition. @param input The input XML document. @param schemas The XML Schema(s) against which the document must be validated. @return Whether the validation was successful.
[ "Validate", "an", "XML", "document", "against", "an", "XML", "Schema", "definition", "." ]
5e133e2824aa38f316a2eb061123313a7276aba0
https://github.com/kiegroup/jbpmmigration/blob/5e133e2824aa38f316a2eb061123313a7276aba0/src/main/java/org/jbpm/migration/XmlUtils.java#L165-L184
train
kiegroup/jbpmmigration
src/main/java/org/jbpm/migration/XmlUtils.java
XmlUtils.transform
public static void transform(final Source input, final Source sheet, final Result output) { try { final DOMResult intermediate = new DOMResult(createEmptyDocument()); // Transform. createTransformer(sheet).transform(input, intermediate); // Format. format(new DOMSource(intermediate.getNode()), output); } catch (final Exception ex) { LOGGER.error("Problem transforming XML file.", ex); } }
java
public static void transform(final Source input, final Source sheet, final Result output) { try { final DOMResult intermediate = new DOMResult(createEmptyDocument()); // Transform. createTransformer(sheet).transform(input, intermediate); // Format. format(new DOMSource(intermediate.getNode()), output); } catch (final Exception ex) { LOGGER.error("Problem transforming XML file.", ex); } }
[ "public", "static", "void", "transform", "(", "final", "Source", "input", ",", "final", "Source", "sheet", ",", "final", "Result", "output", ")", "{", "try", "{", "final", "DOMResult", "intermediate", "=", "new", "DOMResult", "(", "createEmptyDocument", "(", ...
Transform an XML document according to an XSL style sheet. @param input The input XML {@link Source}. @param sheet The XSL style sheet according to which the document must be transformed. @param output The {@link Result} in which the transformed XML is to be stored.
[ "Transform", "an", "XML", "document", "according", "to", "an", "XSL", "style", "sheet", "." ]
5e133e2824aa38f316a2eb061123313a7276aba0
https://github.com/kiegroup/jbpmmigration/blob/5e133e2824aa38f316a2eb061123313a7276aba0/src/main/java/org/jbpm/migration/XmlUtils.java#L196-L208
train
kiegroup/jbpmmigration
src/main/java/org/jbpm/migration/Validator.java
Validator.loadDefinition
static Document loadDefinition(final File def) { // Parse the jDPL definition into a DOM tree. final Document document = XmlUtils.parseFile(def); if (document == null) { return null; } // Log the jPDL version from the process definition (if applicable and available). final Node xmlnsNode = document.getFirstChild().getAttributes().getNamedItem("xmlns"); if (xmlnsNode != null && StringUtils.isNotBlank(xmlnsNode.getNodeValue()) && xmlnsNode.getNodeValue().contains("jpdl")) { final String version = xmlnsNode.getNodeValue().substring(xmlnsNode.getNodeValue().length() - 3); LOGGER.info("jPDL version == " + version); } return document; }
java
static Document loadDefinition(final File def) { // Parse the jDPL definition into a DOM tree. final Document document = XmlUtils.parseFile(def); if (document == null) { return null; } // Log the jPDL version from the process definition (if applicable and available). final Node xmlnsNode = document.getFirstChild().getAttributes().getNamedItem("xmlns"); if (xmlnsNode != null && StringUtils.isNotBlank(xmlnsNode.getNodeValue()) && xmlnsNode.getNodeValue().contains("jpdl")) { final String version = xmlnsNode.getNodeValue().substring(xmlnsNode.getNodeValue().length() - 3); LOGGER.info("jPDL version == " + version); } return document; }
[ "static", "Document", "loadDefinition", "(", "final", "File", "def", ")", "{", "// Parse the jDPL definition into a DOM tree.\r", "final", "Document", "document", "=", "XmlUtils", ".", "parseFile", "(", "def", ")", ";", "if", "(", "document", "==", "null", ")", ...
Load a process definition from file. @param def The {@link File} which contains a definition. @return The definition in {@link Document} format, or <code>null</code> if the file could not be found or didn't contain parseable XML.
[ "Load", "a", "process", "definition", "from", "file", "." ]
5e133e2824aa38f316a2eb061123313a7276aba0
https://github.com/kiegroup/jbpmmigration/blob/5e133e2824aa38f316a2eb061123313a7276aba0/src/main/java/org/jbpm/migration/Validator.java#L60-L75
train
kiegroup/jbpmmigration
src/main/java/org/jbpm/migration/JbpmMigration.java
JbpmMigration.transform
private static void transform(final String xmlFileName, final String xsltFileName, final String outputFileName) { Source xsltSource = null; if (StringUtils.isNotBlank(xsltFileName)) { // Use the given stylesheet. xsltSource = new StreamSource(new File(xsltFileName)); } else { // Use the default stylesheet. xsltSource = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_XSLT_SHEET)); } // Transform the given input file and put the result in the given output file. final Source xmlSource = new StreamSource(new File(xmlFileName)); final Result xmlResult = new StreamResult(new File(outputFileName)); XmlUtils.transform(xmlSource, xsltSource, xmlResult); }
java
private static void transform(final String xmlFileName, final String xsltFileName, final String outputFileName) { Source xsltSource = null; if (StringUtils.isNotBlank(xsltFileName)) { // Use the given stylesheet. xsltSource = new StreamSource(new File(xsltFileName)); } else { // Use the default stylesheet. xsltSource = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_XSLT_SHEET)); } // Transform the given input file and put the result in the given output file. final Source xmlSource = new StreamSource(new File(xmlFileName)); final Result xmlResult = new StreamResult(new File(outputFileName)); XmlUtils.transform(xmlSource, xsltSource, xmlResult); }
[ "private", "static", "void", "transform", "(", "final", "String", "xmlFileName", ",", "final", "String", "xsltFileName", ",", "final", "String", "outputFileName", ")", "{", "Source", "xsltSource", "=", "null", ";", "if", "(", "StringUtils", ".", "isNotBlank", ...
Perform the transformation called from the main method. @param xmlFileName The name of an XML input file. @param xsltFileName The name of an XSLT stylesheet. @param outputFileName The name of the file the result of the transformation is to be written to.
[ "Perform", "the", "transformation", "called", "from", "the", "main", "method", "." ]
5e133e2824aa38f316a2eb061123313a7276aba0
https://github.com/kiegroup/jbpmmigration/blob/5e133e2824aa38f316a2eb061123313a7276aba0/src/main/java/org/jbpm/migration/JbpmMigration.java#L69-L84
train
mjeanroy/junit-runif
src/main/java/com/github/mjeanroy/junit4/runif/conditions/JavaUtils.java
JavaUtils.parseVersion
private static Version parseVersion(String version) { String[] parts = version.split("\\."); int nbParts = parts.length; int majorIndex = nbParts > 1 ? 1 : 0; int major = Integer.parseInt(parts[majorIndex]); return new Version(major); }
java
private static Version parseVersion(String version) { String[] parts = version.split("\\."); int nbParts = parts.length; int majorIndex = nbParts > 1 ? 1 : 0; int major = Integer.parseInt(parts[majorIndex]); return new Version(major); }
[ "private", "static", "Version", "parseVersion", "(", "String", "version", ")", "{", "String", "[", "]", "parts", "=", "version", ".", "split", "(", "\"\\\\.\"", ")", ";", "int", "nbParts", "=", "parts", ".", "length", ";", "int", "majorIndex", "=", "nbPa...
Parse Java version number. @param version The version number. @return The version.
[ "Parse", "Java", "version", "number", "." ]
6fcfe39196d3f51ee1a8db7316567f540063e255
https://github.com/mjeanroy/junit-runif/blob/6fcfe39196d3f51ee1a8db7316567f540063e255/src/main/java/com/github/mjeanroy/junit4/runif/conditions/JavaUtils.java#L57-L63
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.initialize
@Override public void initialize(URL location, ResourceBundle resources) { // Add an event handler to automatically close the stage in the event of // any exception encountered. addEventHandler(WindowEvent.ANY, new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent window) { Platform.runLater(new Runnable() { @Override public void run() { if (isLoadingError) { close(); } } }); } }); // Set default focus to the appropriate UI component Platform.runLater( new Runnable() { @Override public void run() { switch (dialogType) { case INFORMATION: okButton.requestFocus(); break; case CONFIRMATION: yesButton.requestFocus(); break; case CONFIRMATION_ALT1: okButton.requestFocus(); break; case CONFIRMATION_ALT2: yesButton.requestFocus(); break; case WARNING: okButton.requestFocus(); break; case ERROR: okButton.requestFocus(); break; case EXCEPTION: okButton.requestFocus(); break; case INPUT_TEXT: inputTextField.requestFocus(); break; case GENERIC_OK: okButton.requestFocus(); break; case GENERIC_OK_CANCEL: okButton.requestFocus(); break; case GENERIC_YES_NO: yesButton.requestFocus(); break; case GENERIC_YES_NO_CANCEL: yesButton.requestFocus(); break; } } } ); this.detailsLabel.setWrapText( true); this.headerLabel.setText(getHeader()); this.detailsLabel.setText(getDetails()); // Filter behaviour for exception dialog if (dialogType == DialogType.EXCEPTION) { this.exceptionArea.clear(); if (this.exception != null) { this.exceptionArea.appendText( Arrays.toString(this.exception.getStackTrace())); } else { this.exceptionArea.appendText( DialogText.NO_EXCEPTION_TRACE.getText()); } this.exceptionArea.setWrapText(true); this.exceptionArea.setEditable(false); } // Filter whether it headless or not if (this.dialogStyle == DialogStyle.HEADLESS) { this.topBoxContainer.getChildren().remove(this.headContainer); this.setHeadlessPadding(); } // Apply Header CSS style color this.setHeaderColorStyle( this.headerColorStyle); }
java
@Override public void initialize(URL location, ResourceBundle resources) { // Add an event handler to automatically close the stage in the event of // any exception encountered. addEventHandler(WindowEvent.ANY, new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent window) { Platform.runLater(new Runnable() { @Override public void run() { if (isLoadingError) { close(); } } }); } }); // Set default focus to the appropriate UI component Platform.runLater( new Runnable() { @Override public void run() { switch (dialogType) { case INFORMATION: okButton.requestFocus(); break; case CONFIRMATION: yesButton.requestFocus(); break; case CONFIRMATION_ALT1: okButton.requestFocus(); break; case CONFIRMATION_ALT2: yesButton.requestFocus(); break; case WARNING: okButton.requestFocus(); break; case ERROR: okButton.requestFocus(); break; case EXCEPTION: okButton.requestFocus(); break; case INPUT_TEXT: inputTextField.requestFocus(); break; case GENERIC_OK: okButton.requestFocus(); break; case GENERIC_OK_CANCEL: okButton.requestFocus(); break; case GENERIC_YES_NO: yesButton.requestFocus(); break; case GENERIC_YES_NO_CANCEL: yesButton.requestFocus(); break; } } } ); this.detailsLabel.setWrapText( true); this.headerLabel.setText(getHeader()); this.detailsLabel.setText(getDetails()); // Filter behaviour for exception dialog if (dialogType == DialogType.EXCEPTION) { this.exceptionArea.clear(); if (this.exception != null) { this.exceptionArea.appendText( Arrays.toString(this.exception.getStackTrace())); } else { this.exceptionArea.appendText( DialogText.NO_EXCEPTION_TRACE.getText()); } this.exceptionArea.setWrapText(true); this.exceptionArea.setEditable(false); } // Filter whether it headless or not if (this.dialogStyle == DialogStyle.HEADLESS) { this.topBoxContainer.getChildren().remove(this.headContainer); this.setHeadlessPadding(); } // Apply Header CSS style color this.setHeaderColorStyle( this.headerColorStyle); }
[ "@", "Override", "public", "void", "initialize", "(", "URL", "location", ",", "ResourceBundle", "resources", ")", "{", "// Add an event handler to automatically close the stage in the event of ", "// any exception encountered.", "addEventHandler", "(", "WindowEvent", ".", "ANY"...
Initializes the dialog. Sets default focus to OK button. Wraps the text for details message label and apply the user-defined header and details. Filter the behavior for the exception dialog for a null and non-null exception object given. Applies corresponding header background css style. @param location The location used to resolve relative paths for the root object, or null if the location is not known @param resources The resources used to localize the root object, or null if the root object was not localized.
[ "Initializes", "the", "dialog", ".", "Sets", "default", "focus", "to", "OK", "button", ".", "Wraps", "the", "text", "for", "details", "message", "label", "and", "apply", "the", "user", "-", "defined", "header", "and", "details", ".", "Filter", "the", "beha...
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L484-L593
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.setHeadlessPadding
private void setHeadlessPadding() { if (dialogType == DialogType.INPUT_TEXT) { bodyContainer.setStyle( PreDefinedStyle.INPUT_DIALOG_HEADLESS_PADDING.getStyle()); } else if (dialogType == DialogType.EXCEPTION) { bodyContainer.setStyle( PreDefinedStyle.EXCEPTION_DIALOG_HEADLESS_PADDING.getStyle()); } else { bodyContainer.setStyle( PreDefinedStyle.HEADLESS_PADDING.getStyle()); } }
java
private void setHeadlessPadding() { if (dialogType == DialogType.INPUT_TEXT) { bodyContainer.setStyle( PreDefinedStyle.INPUT_DIALOG_HEADLESS_PADDING.getStyle()); } else if (dialogType == DialogType.EXCEPTION) { bodyContainer.setStyle( PreDefinedStyle.EXCEPTION_DIALOG_HEADLESS_PADDING.getStyle()); } else { bodyContainer.setStyle( PreDefinedStyle.HEADLESS_PADDING.getStyle()); } }
[ "private", "void", "setHeadlessPadding", "(", ")", "{", "if", "(", "dialogType", "==", "DialogType", ".", "INPUT_TEXT", ")", "{", "bodyContainer", ".", "setStyle", "(", "PreDefinedStyle", ".", "INPUT_DIALOG_HEADLESS_PADDING", ".", "getStyle", "(", ")", ")", ";",...
Sets the padding for a headless dialog
[ "Sets", "the", "padding", "for", "a", "headless", "dialog" ]
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L598-L610
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.setHeaderColorStyle
public final void setHeaderColorStyle(HeaderColorStyle headerColorStyle) { this.headerColorStyle = headerColorStyle; if (!headerColorStyle.getColorStyle().isEmpty()) { this.getHeaderLabel().setStyle(headerColorStyle.getColorStyle()); // It's either DEFAULT or CUSTOM value (all empty values) // If it is DEFAULT, it sets the default style color // Otherwise if it is CUSTOM, by default no style is applied // (default css "generic" color is in play), user has // to manually set it via setCustomHeaderColorStyle(String colorStyle) } else { if (headerColorStyle == HeaderColorStyle.DEFAULT) { switch (this.dialogType) { case INFORMATION: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_INFO); break; case ERROR: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_ERROR); break; case WARNING: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_WARNING); break; case CONFIRMATION: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_CONFIRM); break; case CONFIRMATION_ALT1: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_CONFIRM); break; case CONFIRMATION_ALT2: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_CONFIRM); break; case EXCEPTION: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_EXCEPTION); break; case INPUT_TEXT: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_INPUT); break; default: this.updateHeaderColorStyle(HeaderColorStyle.GENERIC); break; } } } }
java
public final void setHeaderColorStyle(HeaderColorStyle headerColorStyle) { this.headerColorStyle = headerColorStyle; if (!headerColorStyle.getColorStyle().isEmpty()) { this.getHeaderLabel().setStyle(headerColorStyle.getColorStyle()); // It's either DEFAULT or CUSTOM value (all empty values) // If it is DEFAULT, it sets the default style color // Otherwise if it is CUSTOM, by default no style is applied // (default css "generic" color is in play), user has // to manually set it via setCustomHeaderColorStyle(String colorStyle) } else { if (headerColorStyle == HeaderColorStyle.DEFAULT) { switch (this.dialogType) { case INFORMATION: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_INFO); break; case ERROR: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_ERROR); break; case WARNING: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_WARNING); break; case CONFIRMATION: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_CONFIRM); break; case CONFIRMATION_ALT1: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_CONFIRM); break; case CONFIRMATION_ALT2: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_CONFIRM); break; case EXCEPTION: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_EXCEPTION); break; case INPUT_TEXT: this.updateHeaderColorStyle(HeaderColorStyle.GLOSS_INPUT); break; default: this.updateHeaderColorStyle(HeaderColorStyle.GENERIC); break; } } } }
[ "public", "final", "void", "setHeaderColorStyle", "(", "HeaderColorStyle", "headerColorStyle", ")", "{", "this", ".", "headerColorStyle", "=", "headerColorStyle", ";", "if", "(", "!", "headerColorStyle", ".", "getColorStyle", "(", ")", ".", "isEmpty", "(", ")", ...
Applies a predefined JavaFX CSS background color style for the header label @param headerColorStyle A <code>HeaderColorStyle</code> option containing a color scheme.
[ "Applies", "a", "predefined", "JavaFX", "CSS", "background", "color", "style", "for", "the", "header", "label" ]
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L619-L664
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.setFont
public void setFont(String header_font_family, int header_font_size, String details_font_family, int details_font_size) { this.headerLabel .setStyle("-fx-font-family: \"" + header_font_family + "\";" + "-fx-font-size:" + Integer.toString(header_font_size) + "px;"); this.detailsLabel .setStyle("-fx-font-family: \"" + details_font_family + "\";" + "-fx-font-size:" + Integer.toString(details_font_size) + "px;"); }
java
public void setFont(String header_font_family, int header_font_size, String details_font_family, int details_font_size) { this.headerLabel .setStyle("-fx-font-family: \"" + header_font_family + "\";" + "-fx-font-size:" + Integer.toString(header_font_size) + "px;"); this.detailsLabel .setStyle("-fx-font-family: \"" + details_font_family + "\";" + "-fx-font-size:" + Integer.toString(details_font_size) + "px;"); }
[ "public", "void", "setFont", "(", "String", "header_font_family", ",", "int", "header_font_size", ",", "String", "details_font_family", ",", "int", "details_font_size", ")", "{", "this", ".", "headerLabel", ".", "setStyle", "(", "\"-fx-font-family: \\\"\"", "+", "he...
Sets the font sizes and the font families for the header and details label. @param header_font_family The header font family in <code>Strings</code> @param header_font_size The header font size in pixels @param details_font_family The details font family in <code>Strings</code> @param details_font_size The details font size in pixels
[ "Sets", "the", "font", "sizes", "and", "the", "font", "families", "for", "the", "header", "and", "details", "label", "." ]
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L842-L850
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.setHeaderFont
public void setHeaderFont(String font_family, int font_size) { this.headerLabel .setStyle("-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer.toString(font_size) + "px;"); }
java
public void setHeaderFont(String font_family, int font_size) { this.headerLabel .setStyle("-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer.toString(font_size) + "px;"); }
[ "public", "void", "setHeaderFont", "(", "String", "font_family", ",", "int", "font_size", ")", "{", "this", ".", "headerLabel", ".", "setStyle", "(", "\"-fx-font-family: \\\"\"", "+", "font_family", "+", "\"\\\";\"", "+", "\"-fx-font-size:\"", "+", "Integer", ".",...
Sets both header label's font family and size. @param font_family Font family in <code>Strings</code> @param font_size Font size in <code>integer</code> (pixels)
[ "Sets", "both", "header", "label", "s", "font", "family", "and", "size", "." ]
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L858-L862
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.setDetailsFont
public void setDetailsFont(String font_family, int font_size) { this.detailsLabel .setStyle("-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer.toString(font_size) + "px;"); }
java
public void setDetailsFont(String font_family, int font_size) { this.detailsLabel .setStyle("-fx-font-family: \"" + font_family + "\";" + "-fx-font-size:" + Integer.toString(font_size) + "px;"); }
[ "public", "void", "setDetailsFont", "(", "String", "font_family", ",", "int", "font_size", ")", "{", "this", ".", "detailsLabel", ".", "setStyle", "(", "\"-fx-font-family: \\\"\"", "+", "font_family", "+", "\"\\\";\"", "+", "\"-fx-font-size:\"", "+", "Integer", "....
Sets both details label's font family and size. @param font_family Font family in <code>Strings</code> @param font_size Font size in <code>integer</code> (pixels)
[ "Sets", "both", "details", "label", "s", "font", "family", "and", "size", "." ]
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L870-L874
train
Daytron/SimpleDialogFX
src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java
Dialog.send_btn_on_click
@FXML private void send_btn_on_click(ActionEvent event) { // Future proof for other uses of send event handler if (this.dialogType == DialogType.INPUT_TEXT) { this.textEntry = this.inputTextField.getText(); } setResponse(DialogResponse.SEND); close(); }
java
@FXML private void send_btn_on_click(ActionEvent event) { // Future proof for other uses of send event handler if (this.dialogType == DialogType.INPUT_TEXT) { this.textEntry = this.inputTextField.getText(); } setResponse(DialogResponse.SEND); close(); }
[ "@", "FXML", "private", "void", "send_btn_on_click", "(", "ActionEvent", "event", ")", "{", "// Future proof for other uses of send event handler", "if", "(", "this", ".", "dialogType", "==", "DialogType", ".", "INPUT_TEXT", ")", "{", "this", ".", "textEntry", "=", ...
Event handler when sendButton is pressed. Sets response to SEND and closes the dialog window. @param event Action event object
[ "Event", "handler", "when", "sendButton", "is", "pressed", ".", "Sets", "response", "to", "SEND", "and", "closes", "the", "dialog", "window", "." ]
54e813dbb0ebabad8e0a81b6b5f05e518747611e
https://github.com/Daytron/SimpleDialogFX/blob/54e813dbb0ebabad8e0a81b6b5f05e518747611e/src/main/java/com/github/daytron/simpledialogfx/dialog/Dialog.java#L993-L1002
train
probedock/probedock-java
src/main/java/io/probedock/client/common/utils/FingerprintGenerator.java
FingerprintGenerator.fingerprint
public static String fingerprint(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); return byteArrayToHexString(md.digest(str.getBytes())); } catch (NoSuchAlgorithmException nsae) { LOGGER.warning("Unable to calculate the fingerprint for string [" + str + "]."); return null; } }
java
public static String fingerprint(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); return byteArrayToHexString(md.digest(str.getBytes())); } catch (NoSuchAlgorithmException nsae) { LOGGER.warning("Unable to calculate the fingerprint for string [" + str + "]."); return null; } }
[ "public", "static", "String", "fingerprint", "(", "String", "str", ")", "{", "try", "{", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA-1\"", ")", ";", "return", "byteArrayToHexString", "(", "md", ".", "digest", "(", "str", ".",...
Generate a fingerprint for a given string @param str The string to fingerprint @return The fingerprint generated
[ "Generate", "a", "fingerprint", "for", "a", "given", "string" ]
92ee6634ba4fe3fdffeb4e202f5372ef947a67c3
https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/common/utils/FingerprintGenerator.java#L22-L31
train
probedock/probedock-java
src/main/java/io/probedock/client/common/utils/FingerprintGenerator.java
FingerprintGenerator.fingerprint
public static String fingerprint(Class cl, Method m) { return fingerprint(cl, m.getName()); }
java
public static String fingerprint(Class cl, Method m) { return fingerprint(cl, m.getName()); }
[ "public", "static", "String", "fingerprint", "(", "Class", "cl", ",", "Method", "m", ")", "{", "return", "fingerprint", "(", "cl", ",", "m", ".", "getName", "(", ")", ")", ";", "}" ]
Generate a fingerprint based on class and method @param cl The class @param m The method @return The fingerprint generated
[ "Generate", "a", "fingerprint", "based", "on", "class", "and", "method" ]
92ee6634ba4fe3fdffeb4e202f5372ef947a67c3
https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/common/utils/FingerprintGenerator.java#L40-L42
train
probedock/probedock-java
src/main/java/io/probedock/client/common/utils/FingerprintGenerator.java
FingerprintGenerator.fingerprint
public static String fingerprint(Class cl, String methodName) { return fingerprint(cl.getCanonicalName() + "." + methodName); }
java
public static String fingerprint(Class cl, String methodName) { return fingerprint(cl.getCanonicalName() + "." + methodName); }
[ "public", "static", "String", "fingerprint", "(", "Class", "cl", ",", "String", "methodName", ")", "{", "return", "fingerprint", "(", "cl", ".", "getCanonicalName", "(", ")", "+", "\".\"", "+", "methodName", ")", ";", "}" ]
Generate a fingerprint based on class and method name @param cl The class @param methodName The method name @return The fingerprint generated
[ "Generate", "a", "fingerprint", "based", "on", "class", "and", "method", "name" ]
92ee6634ba4fe3fdffeb4e202f5372ef947a67c3
https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/common/utils/FingerprintGenerator.java#L51-L53
train
probedock/probedock-java
src/main/java/io/probedock/client/utils/CollectionHelper.java
CollectionHelper.getContributors
public static Set<String> getContributors(Set<String> baseContributors, ProbeTest methodAnnotation, ProbeTestClass classAnnotation) { Set<String> contributors; if (baseContributors == null) { contributors = new HashSet<>(); } else { contributors = populateContributors(baseContributors, new HashSet<String>()); } if (classAnnotation != null && classAnnotation.contributors() != null) { contributors = populateContributors(new HashSet<>(Arrays.asList(classAnnotation.contributors())), contributors); } if (methodAnnotation != null && methodAnnotation.contributors() != null) { contributors = populateContributors(new HashSet<>(Arrays.asList(methodAnnotation.contributors())), contributors); } return contributors; }
java
public static Set<String> getContributors(Set<String> baseContributors, ProbeTest methodAnnotation, ProbeTestClass classAnnotation) { Set<String> contributors; if (baseContributors == null) { contributors = new HashSet<>(); } else { contributors = populateContributors(baseContributors, new HashSet<String>()); } if (classAnnotation != null && classAnnotation.contributors() != null) { contributors = populateContributors(new HashSet<>(Arrays.asList(classAnnotation.contributors())), contributors); } if (methodAnnotation != null && methodAnnotation.contributors() != null) { contributors = populateContributors(new HashSet<>(Arrays.asList(methodAnnotation.contributors())), contributors); } return contributors; }
[ "public", "static", "Set", "<", "String", ">", "getContributors", "(", "Set", "<", "String", ">", "baseContributors", ",", "ProbeTest", "methodAnnotation", ",", "ProbeTestClass", "classAnnotation", ")", "{", "Set", "<", "String", ">", "contributors", ";", "if", ...
Retrieve the contributors and compile them from the different sources @param baseContributors a list of base contributors @param methodAnnotation The method annotation that could contain contributors @param classAnnotation The class annotation that could contain contributors @return The contributors from the different sources
[ "Retrieve", "the", "contributors", "and", "compile", "them", "from", "the", "different", "sources" ]
92ee6634ba4fe3fdffeb4e202f5372ef947a67c3
https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/utils/CollectionHelper.java#L35-L53
train
probedock/probedock-java
src/main/java/io/probedock/client/utils/CollectionHelper.java
CollectionHelper.populateContributors
private static Set<String> populateContributors(Set<String> source, Set<String> destination) { for (String contributor : source) { if (!emailPattern.matcher(contributor).matches()) { LOGGER.warning("The contributor '" + contributor + "' does not respect the email pattern " + emailPattern.pattern() + " and is ignored"); } else if (destination.contains(contributor)) { LOGGER.info("The contributor '" + contributor + "' is already present in the collection and is ignored"); } else { destination.add(contributor); } } return destination; }
java
private static Set<String> populateContributors(Set<String> source, Set<String> destination) { for (String contributor : source) { if (!emailPattern.matcher(contributor).matches()) { LOGGER.warning("The contributor '" + contributor + "' does not respect the email pattern " + emailPattern.pattern() + " and is ignored"); } else if (destination.contains(contributor)) { LOGGER.info("The contributor '" + contributor + "' is already present in the collection and is ignored"); } else { destination.add(contributor); } } return destination; }
[ "private", "static", "Set", "<", "String", ">", "populateContributors", "(", "Set", "<", "String", ">", "source", ",", "Set", "<", "String", ">", "destination", ")", "{", "for", "(", "String", "contributor", ":", "source", ")", "{", "if", "(", "!", "em...
Populate the source with the destination contributors only if they match the pattern rules for the contributors @param source The source to check @param destination The destination to fill @return The destination updated
[ "Populate", "the", "source", "with", "the", "destination", "contributors", "only", "if", "they", "match", "the", "pattern", "rules", "for", "the", "contributors" ]
92ee6634ba4fe3fdffeb4e202f5372ef947a67c3
https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/utils/CollectionHelper.java#L62-L75
train
aoindustries/aocode-public
src/main/java/com/aoindustries/util/SortedArrayList.java
SortedArrayList.binarySearchHashCode
protected int binarySearchHashCode(int elemHash) { int left = 0; int right = size()-1; while(left <= right) { int mid = (left + right)>>1; int midHash = get(mid).hashCode(); if(elemHash==midHash) return mid; if(elemHash<midHash) right = mid-1; else left = mid+1; } return -(left+1); }
java
protected int binarySearchHashCode(int elemHash) { int left = 0; int right = size()-1; while(left <= right) { int mid = (left + right)>>1; int midHash = get(mid).hashCode(); if(elemHash==midHash) return mid; if(elemHash<midHash) right = mid-1; else left = mid+1; } return -(left+1); }
[ "protected", "int", "binarySearchHashCode", "(", "int", "elemHash", ")", "{", "int", "left", "=", "0", ";", "int", "right", "=", "size", "(", ")", "-", "1", ";", "while", "(", "left", "<=", "right", ")", "{", "int", "mid", "=", "(", "left", "+", ...
Performs a binary search on hashCode values only. It will return any matching element, not necessarily the first or the last.
[ "Performs", "a", "binary", "search", "on", "hashCode", "values", "only", ".", "It", "will", "return", "any", "matching", "element", "not", "necessarily", "the", "first", "or", "the", "last", "." ]
c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/SortedArrayList.java#L62-L73
train
aoindustries/aocode-public
src/main/java/com/aoindustries/util/SortedArrayList.java
SortedArrayList.indexOf
public int indexOf(int hashCode) { int pos=binarySearchHashCode(hashCode); if(pos<0) return -1; // Try backwards until different hashCode while(pos>0 && get(pos-1).hashCode()==hashCode) pos--; return pos; }
java
public int indexOf(int hashCode) { int pos=binarySearchHashCode(hashCode); if(pos<0) return -1; // Try backwards until different hashCode while(pos>0 && get(pos-1).hashCode()==hashCode) pos--; return pos; }
[ "public", "int", "indexOf", "(", "int", "hashCode", ")", "{", "int", "pos", "=", "binarySearchHashCode", "(", "hashCode", ")", ";", "if", "(", "pos", "<", "0", ")", "return", "-", "1", ";", "// Try backwards until different hashCode", "while", "(", "pos", ...
Finds the first index where the object has the provided hashCode
[ "Finds", "the", "first", "index", "where", "the", "object", "has", "the", "provided", "hashCode" ]
c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/SortedArrayList.java#L124-L131
train
aoindustries/aocode-public
src/main/java/com/aoindustries/util/SortedArrayList.java
SortedArrayList.add
@Override public boolean add(E o) { // Shortcut for empty int size=size(); if(size==0) { super.add(o); } else { int Ohash=o.hashCode(); // Shortcut for adding to end (makes imports of already-sorted data operate at constant-time instead of logarithmic complexity) if(Ohash>=get(size-1).hashCode()) { super.add(o); } else { int index=binarySearchHashCode(Ohash); if(index<0) { // Not found in list super.add(-(index+1), o); } else { // Add after the last item with matching hashCodes while(index<(size-1) && get(index+1).hashCode()==Ohash) index++; super.add(index+1, o); } } } return true; }
java
@Override public boolean add(E o) { // Shortcut for empty int size=size(); if(size==0) { super.add(o); } else { int Ohash=o.hashCode(); // Shortcut for adding to end (makes imports of already-sorted data operate at constant-time instead of logarithmic complexity) if(Ohash>=get(size-1).hashCode()) { super.add(o); } else { int index=binarySearchHashCode(Ohash); if(index<0) { // Not found in list super.add(-(index+1), o); } else { // Add after the last item with matching hashCodes while(index<(size-1) && get(index+1).hashCode()==Ohash) index++; super.add(index+1, o); } } } return true; }
[ "@", "Override", "public", "boolean", "add", "(", "E", "o", ")", "{", "// Shortcut for empty", "int", "size", "=", "size", "(", ")", ";", "if", "(", "size", "==", "0", ")", "{", "super", ".", "add", "(", "o", ")", ";", "}", "else", "{", "int", ...
Adds the specified element in sorted position within this list. When two elements have the same hashCode, the new item is added at the end of the list of matching hashCodes. @param o element to be appended to this list. @return <tt>true</tt> (as per the general contract of Collection.add).
[ "Adds", "the", "specified", "element", "in", "sorted", "position", "within", "this", "list", ".", "When", "two", "elements", "have", "the", "same", "hashCode", "the", "new", "item", "is", "added", "at", "the", "end", "of", "the", "list", "of", "matching", ...
c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/SortedArrayList.java#L194-L220
train
aoindustries/aocode-public
src/main/java/com/aoindustries/net/UnmodifiableHttpParameters.java
UnmodifiableHttpParameters.wrap
public static HttpParameters wrap(HttpParameters wrapped) { // null remains null if(wrapped == null) return null; // Empty are unmodifiable if(wrapped == EmptyParameters.getInstance()) return wrapped; // ServletRequest parameters are unmodifiable already if(wrapped instanceof ServletRequestParameters) return wrapped; // Already wrapped if(wrapped instanceof UnmodifiableHttpParameters) return wrapped; // Wrapping necessary return new UnmodifiableHttpParameters(wrapped); }
java
public static HttpParameters wrap(HttpParameters wrapped) { // null remains null if(wrapped == null) return null; // Empty are unmodifiable if(wrapped == EmptyParameters.getInstance()) return wrapped; // ServletRequest parameters are unmodifiable already if(wrapped instanceof ServletRequestParameters) return wrapped; // Already wrapped if(wrapped instanceof UnmodifiableHttpParameters) return wrapped; // Wrapping necessary return new UnmodifiableHttpParameters(wrapped); }
[ "public", "static", "HttpParameters", "wrap", "(", "HttpParameters", "wrapped", ")", "{", "// null remains null", "if", "(", "wrapped", "==", "null", ")", "return", "null", ";", "// Empty are unmodifiable", "if", "(", "wrapped", "==", "EmptyParameters", ".", "getI...
Wraps the given parameters to ensure they are unmodifiable. @return {@code null} when wrapped is {@code null}, otherwise unmodifiable parameters
[ "Wraps", "the", "given", "parameters", "to", "ensure", "they", "are", "unmodifiable", "." ]
c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/net/UnmodifiableHttpParameters.java#L44-L55
train
aoindustries/semanticcms-news-servlet
src/main/java/com/semanticcms/news/servlet/RssUtils.java
RssUtils.isRssEnabled
public static boolean isRssEnabled(ServletContext servletContext) { // Note: no locking performed since it's ok for two threads to do the work concurrently at first Boolean isRssEnabled = (Boolean)servletContext.getAttribute(ISS_RSS_ENABLED_CACHE_KEY); if(isRssEnabled == null) { try { Class.forName(RSS_SERVLET_CLASSNAME); isRssEnabled = true; } catch(ClassNotFoundException e) { isRssEnabled = false; } servletContext.setAttribute(ISS_RSS_ENABLED_CACHE_KEY, isRssEnabled); } return isRssEnabled; }
java
public static boolean isRssEnabled(ServletContext servletContext) { // Note: no locking performed since it's ok for two threads to do the work concurrently at first Boolean isRssEnabled = (Boolean)servletContext.getAttribute(ISS_RSS_ENABLED_CACHE_KEY); if(isRssEnabled == null) { try { Class.forName(RSS_SERVLET_CLASSNAME); isRssEnabled = true; } catch(ClassNotFoundException e) { isRssEnabled = false; } servletContext.setAttribute(ISS_RSS_ENABLED_CACHE_KEY, isRssEnabled); } return isRssEnabled; }
[ "public", "static", "boolean", "isRssEnabled", "(", "ServletContext", "servletContext", ")", "{", "// Note: no locking performed since it's ok for two threads to do the work concurrently at first", "Boolean", "isRssEnabled", "=", "(", "Boolean", ")", "servletContext", ".", "getAt...
Checks if the RSS module is installed. This is done by checking for the existence of the servlet class. This is cached in application scope to avoid throwing and catching ClassNotFoundException repeatedly.
[ "Checks", "if", "the", "RSS", "module", "is", "installed", ".", "This", "is", "done", "by", "checking", "for", "the", "existence", "of", "the", "servlet", "class", ".", "This", "is", "cached", "in", "application", "scope", "to", "avoid", "throwing", "and",...
3899c14fedffb4decc7be3e1560930e82cb5c933
https://github.com/aoindustries/semanticcms-news-servlet/blob/3899c14fedffb4decc7be3e1560930e82cb5c933/src/main/java/com/semanticcms/news/servlet/RssUtils.java#L51-L64
train
aoindustries/semanticcms-news-servlet
src/main/java/com/semanticcms/news/servlet/RssUtils.java
RssUtils.isProtectedExtension
public static boolean isProtectedExtension(String path) { for(String extension : PROTECTED_EXTENSIONS) { if(path.endsWith(extension)) return true; } return false; }
java
public static boolean isProtectedExtension(String path) { for(String extension : PROTECTED_EXTENSIONS) { if(path.endsWith(extension)) return true; } return false; }
[ "public", "static", "boolean", "isProtectedExtension", "(", "String", "path", ")", "{", "for", "(", "String", "extension", ":", "PROTECTED_EXTENSIONS", ")", "{", "if", "(", "path", ".", "endsWith", "(", "extension", ")", ")", "return", "true", ";", "}", "r...
Checks that the given resource should not be included under any circumstances.
[ "Checks", "that", "the", "given", "resource", "should", "not", "be", "included", "under", "any", "circumstances", "." ]
3899c14fedffb4decc7be3e1560930e82cb5c933
https://github.com/aoindustries/semanticcms-news-servlet/blob/3899c14fedffb4decc7be3e1560930e82cb5c933/src/main/java/com/semanticcms/news/servlet/RssUtils.java#L91-L96
train
aoindustries/semanticcms-news-servlet
src/main/java/com/semanticcms/news/servlet/RssUtils.java
RssUtils.getRssServletPath
public static String getRssServletPath(PageRef pageRef) { String servletPath = pageRef.getBookRef().getPrefix() + pageRef.getPath(); for(String extension : RESOURCE_EXTENSIONS) { if(servletPath.endsWith(extension)) { servletPath = servletPath.substring(0, servletPath.length() - extension.length()); break; } } return servletPath + EXTENSION; }
java
public static String getRssServletPath(PageRef pageRef) { String servletPath = pageRef.getBookRef().getPrefix() + pageRef.getPath(); for(String extension : RESOURCE_EXTENSIONS) { if(servletPath.endsWith(extension)) { servletPath = servletPath.substring(0, servletPath.length() - extension.length()); break; } } return servletPath + EXTENSION; }
[ "public", "static", "String", "getRssServletPath", "(", "PageRef", "pageRef", ")", "{", "String", "servletPath", "=", "pageRef", ".", "getBookRef", "(", ")", ".", "getPrefix", "(", ")", "+", "pageRef", ".", "getPath", "(", ")", ";", "for", "(", "String", ...
Gets the servletPath to the RSS feed for the give page ref.
[ "Gets", "the", "servletPath", "to", "the", "RSS", "feed", "for", "the", "give", "page", "ref", "." ]
3899c14fedffb4decc7be3e1560930e82cb5c933
https://github.com/aoindustries/semanticcms-news-servlet/blob/3899c14fedffb4decc7be3e1560930e82cb5c933/src/main/java/com/semanticcms/news/servlet/RssUtils.java#L101-L110
train
aoindustries/semanticcms-core-model
src/main/java/com/semanticcms/core/model/BookRef.java
BookRef.compareTo
public int compareTo(BookRef o) { int diff = domain.compareTo(o.domain); if(diff != 0) return diff; return path.compareTo(o.path); }
java
public int compareTo(BookRef o) { int diff = domain.compareTo(o.domain); if(diff != 0) return diff; return path.compareTo(o.path); }
[ "public", "int", "compareTo", "(", "BookRef", "o", ")", "{", "int", "diff", "=", "domain", ".", "compareTo", "(", "o", ".", "domain", ")", ";", "if", "(", "diff", "!=", "0", ")", "return", "diff", ";", "return", "path", ".", "compareTo", "(", "o", ...
Ordered by domain, path.
[ "Ordered", "by", "domain", "path", "." ]
14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624
https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/BookRef.java#L96-L100
train
nlalevee/jsourcemap
jsourcemap/src/java/org/hibnet/jsourcemap/IndexedSourceMapConsumer.java
IndexedSourceMapConsumer.sources
@Override public List<String> sources() { List<String> sources = new ArrayList<>(); for (int i = 0; i < this._sections.size(); i++) { for (int j = 0; j < this._sections.get(i).consumer.sources().size(); j++) { sources.add(this._sections.get(i).consumer.sources().get(j)); } } return sources; }
java
@Override public List<String> sources() { List<String> sources = new ArrayList<>(); for (int i = 0; i < this._sections.size(); i++) { for (int j = 0; j < this._sections.get(i).consumer.sources().size(); j++) { sources.add(this._sections.get(i).consumer.sources().get(j)); } } return sources; }
[ "@", "Override", "public", "List", "<", "String", ">", "sources", "(", ")", "{", "List", "<", "String", ">", "sources", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "_sections", ".", ...
The list of original sources.
[ "The", "list", "of", "original", "sources", "." ]
361a99c73d51c11afa5579dd83d477c4d0345599
https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/IndexedSourceMapConsumer.java#L130-L139
train
aoindustries/aocode-public
src/main/java/com/aoindustries/io/SyncFile.java
SyncFile.syncFile
public static long syncFile(InputStream in, RandomAccessFile out) throws IOException { byte[] inBuff = new byte[BLOCK_SIZE]; byte[] outBuff = new byte[BLOCK_SIZE]; long pos = 0; long bytesWritten = 0; int numBytes; while((numBytes=in.read(inBuff, 0, BLOCK_SIZE))!=-1) { if(DEBUG) System.err.println(pos+": Read " + numBytes + " bytes of input"); out.seek(pos); long blockEnd = pos + numBytes; if(out.length()>=blockEnd) { // Read block from out if(DEBUG) System.err.println(pos+": Reading " + numBytes + " bytes of output"); out.readFully(outBuff, 0, numBytes); if(!AoArrays.equals(inBuff, outBuff, 0, numBytes)) { if(DEBUG) System.err.println(pos+": Updating " + numBytes + " bytes of output"); out.seek(pos); if(!DRY_RUN) out.write(inBuff, 0, numBytes); bytesWritten += numBytes; } else { if(DEBUG) System.err.println(pos+": Data matches, not writing"); } } else { // At end, write entire block if(DEBUG) System.err.println(pos+": Appending " + numBytes +" bytes to output"); if(!DRY_RUN) out.write(inBuff, 0, numBytes); bytesWritten += numBytes; } pos = blockEnd; } if(out.length()!=pos) { if(DEBUG) System.err.println(pos+": Truncating output to " + pos + " bytes"); assert out.length()>pos; if(!DRY_RUN) { try { out.setLength(pos); } catch(IOException e) { System.err.println("Warning: Unable to truncate output to " + pos +" bytes"); } } } return bytesWritten; }
java
public static long syncFile(InputStream in, RandomAccessFile out) throws IOException { byte[] inBuff = new byte[BLOCK_SIZE]; byte[] outBuff = new byte[BLOCK_SIZE]; long pos = 0; long bytesWritten = 0; int numBytes; while((numBytes=in.read(inBuff, 0, BLOCK_SIZE))!=-1) { if(DEBUG) System.err.println(pos+": Read " + numBytes + " bytes of input"); out.seek(pos); long blockEnd = pos + numBytes; if(out.length()>=blockEnd) { // Read block from out if(DEBUG) System.err.println(pos+": Reading " + numBytes + " bytes of output"); out.readFully(outBuff, 0, numBytes); if(!AoArrays.equals(inBuff, outBuff, 0, numBytes)) { if(DEBUG) System.err.println(pos+": Updating " + numBytes + " bytes of output"); out.seek(pos); if(!DRY_RUN) out.write(inBuff, 0, numBytes); bytesWritten += numBytes; } else { if(DEBUG) System.err.println(pos+": Data matches, not writing"); } } else { // At end, write entire block if(DEBUG) System.err.println(pos+": Appending " + numBytes +" bytes to output"); if(!DRY_RUN) out.write(inBuff, 0, numBytes); bytesWritten += numBytes; } pos = blockEnd; } if(out.length()!=pos) { if(DEBUG) System.err.println(pos+": Truncating output to " + pos + " bytes"); assert out.length()>pos; if(!DRY_RUN) { try { out.setLength(pos); } catch(IOException e) { System.err.println("Warning: Unable to truncate output to " + pos +" bytes"); } } } return bytesWritten; }
[ "public", "static", "long", "syncFile", "(", "InputStream", "in", ",", "RandomAccessFile", "out", ")", "throws", "IOException", "{", "byte", "[", "]", "inBuff", "=", "new", "byte", "[", "BLOCK_SIZE", "]", ";", "byte", "[", "]", "outBuff", "=", "new", "by...
Synchronized the input to the provided output, only writing data that doesn't already match the input. Returns the number of bytes written.
[ "Synchronized", "the", "input", "to", "the", "provided", "output", "only", "writing", "data", "that", "doesn", "t", "already", "match", "the", "input", ".", "Returns", "the", "number", "of", "bytes", "written", "." ]
c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/SyncFile.java#L88-L130
train
aoindustries/semanticcms-core-taglib
src/main/java/com/semanticcms/core/taglib/ElementTag.java
ElementTag.evaluateAttributes
protected void evaluateAttributes(E element, ELContext elContext) throws JspTagException, IOException { String idStr = nullIfEmpty(resolveValue(id, String.class, elContext)); if(idStr != null) element.setId(idStr); }
java
protected void evaluateAttributes(E element, ELContext elContext) throws JspTagException, IOException { String idStr = nullIfEmpty(resolveValue(id, String.class, elContext)); if(idStr != null) element.setId(idStr); }
[ "protected", "void", "evaluateAttributes", "(", "E", "element", ",", "ELContext", "elContext", ")", "throws", "JspTagException", ",", "IOException", "{", "String", "idStr", "=", "nullIfEmpty", "(", "resolveValue", "(", "id", ",", "String", ".", "class", ",", "...
Resolves all attributes, setting into the created element as appropriate, This is only called for captureLevel >= META. Attributes are resolved before the element is added to any parent node. Typically, deferred expressions will be evaluated here. Overriding methods must call this implementation.
[ "Resolves", "all", "attributes", "setting", "into", "the", "created", "element", "as", "appropriate", "This", "is", "only", "called", "for", "captureLevel", ">", "=", "META", ".", "Attributes", "are", "resolved", "before", "the", "element", "is", "added", "to"...
2e6c5dd3b1299c6cc6a87a335302460c5c69c539
https://github.com/aoindustries/semanticcms-core-taglib/blob/2e6c5dd3b1299c6cc6a87a335302460c5c69c539/src/main/java/com/semanticcms/core/taglib/ElementTag.java#L179-L182
train
aoindustries/semanticcms-core-taglib
src/main/java/com/semanticcms/core/taglib/ElementTag.java
ElementTag.doBody
protected void doBody(E element, CaptureLevel captureLevel) throws JspException, IOException { JspFragment body = getJspBody(); if(body != null) { if(captureLevel == CaptureLevel.BODY) { final PageContext pageContext = (PageContext)getJspContext(); // Invoke tag body, capturing output BufferWriter capturedOut = AutoEncodingBufferedTag.newBufferWriter(pageContext.getRequest()); try { body.invoke(capturedOut); } finally { capturedOut.close(); } element.setBody(capturedOut.getResult().trim()); } else if(captureLevel == CaptureLevel.META) { // Invoke body for any meta data, but discard any output body.invoke(NullWriter.getInstance()); } else { throw new AssertionError(); } } }
java
protected void doBody(E element, CaptureLevel captureLevel) throws JspException, IOException { JspFragment body = getJspBody(); if(body != null) { if(captureLevel == CaptureLevel.BODY) { final PageContext pageContext = (PageContext)getJspContext(); // Invoke tag body, capturing output BufferWriter capturedOut = AutoEncodingBufferedTag.newBufferWriter(pageContext.getRequest()); try { body.invoke(capturedOut); } finally { capturedOut.close(); } element.setBody(capturedOut.getResult().trim()); } else if(captureLevel == CaptureLevel.META) { // Invoke body for any meta data, but discard any output body.invoke(NullWriter.getInstance()); } else { throw new AssertionError(); } } }
[ "protected", "void", "doBody", "(", "E", "element", ",", "CaptureLevel", "captureLevel", ")", "throws", "JspException", ",", "IOException", "{", "JspFragment", "body", "=", "getJspBody", "(", ")", ";", "if", "(", "body", "!=", "null", ")", "{", "if", "(", ...
This is only called for captureLevel >= META.
[ "This", "is", "only", "called", "for", "captureLevel", ">", "=", "META", "." ]
2e6c5dd3b1299c6cc6a87a335302460c5c69c539
https://github.com/aoindustries/semanticcms-core-taglib/blob/2e6c5dd3b1299c6cc6a87a335302460c5c69c539/src/main/java/com/semanticcms/core/taglib/ElementTag.java#L187-L207
train
aoindustries/aocode-public
src/main/java/com/aoindustries/servlet/PropertiesUtils.java
PropertiesUtils.loadFromResource
public static Properties loadFromResource(ServletContext servletContext, String resource) throws IOException { Properties props = new Properties(); InputStream in = servletContext.getResourceAsStream(resource); if(in==null) throw new LocalizedIOException(accessor, "PropertiesUtils.readProperties.resourceNotFound", resource); try { props.load(in); } finally { in.close(); } return props; }
java
public static Properties loadFromResource(ServletContext servletContext, String resource) throws IOException { Properties props = new Properties(); InputStream in = servletContext.getResourceAsStream(resource); if(in==null) throw new LocalizedIOException(accessor, "PropertiesUtils.readProperties.resourceNotFound", resource); try { props.load(in); } finally { in.close(); } return props; }
[ "public", "static", "Properties", "loadFromResource", "(", "ServletContext", "servletContext", ",", "String", "resource", ")", "throws", "IOException", "{", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "InputStream", "in", "=", "servletContext", ...
Loads properties from a web resource.
[ "Loads", "properties", "from", "a", "web", "resource", "." ]
c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3
https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/PropertiesUtils.java#L47-L57
train