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
zeromq/jeromq
src/main/java/org/zeromq/ZContext.java
ZContext.shadow
public static ZContext shadow(ZContext ctx) { ZContext context = new ZContext(ctx.context, false, ctx.ioThreads); context.linger = ctx.linger; context.sndhwm = ctx.sndhwm; context.rcvhwm = ctx.rcvhwm; context.pipehwm = ctx.pipehwm; return context; }
java
public static ZContext shadow(ZContext ctx) { ZContext context = new ZContext(ctx.context, false, ctx.ioThreads); context.linger = ctx.linger; context.sndhwm = ctx.sndhwm; context.rcvhwm = ctx.rcvhwm; context.pipehwm = ctx.pipehwm; return context; }
[ "public", "static", "ZContext", "shadow", "(", "ZContext", "ctx", ")", "{", "ZContext", "context", "=", "new", "ZContext", "(", "ctx", ".", "context", ",", "false", ",", "ctx", ".", "ioThreads", ")", ";", "context", ".", "linger", "=", "ctx", ".", "lin...
Creates new shadow context. Shares same underlying org.zeromq.Context instance but has own list of managed sockets, io thread count etc. @param ctx Original ZContext to create shadow of @return New ZContext
[ "Creates", "new", "shadow", "context", ".", "Shares", "same", "underlying", "org", ".", "zeromq", ".", "Context", "instance", "but", "has", "own", "list", "of", "managed", "sockets", "io", "thread", "count", "etc", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZContext.java#L219-L227
train
zeromq/jeromq
src/main/java/org/zeromq/ZContext.java
ZContext.fork
public Socket fork(ZThread.IAttachedRunnable runnable, Object... args) { return ZThread.fork(this, runnable, args); }
java
public Socket fork(ZThread.IAttachedRunnable runnable, Object... args) { return ZThread.fork(this, runnable, args); }
[ "public", "Socket", "fork", "(", "ZThread", ".", "IAttachedRunnable", "runnable", ",", "Object", "...", "args", ")", "{", "return", "ZThread", ".", "fork", "(", "this", ",", "runnable", ",", "args", ")", ";", "}" ]
Create an attached thread, An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor its pipe, and exit if the pipe becomes unreadable @param runnable attached thread @param args forked runnable args @return pipe or null if there was an error
[ "Create", "an", "attached", "thread", "An", "attached", "thread", "gets", "a", "ctx", "and", "a", "PAIR", "pipe", "back", "to", "its", "parent", ".", "It", "must", "monitor", "its", "pipe", "and", "exit", "if", "the", "pipe", "becomes", "unreadable" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZContext.java#L237-L240
train
zeromq/jeromq
src/main/java/zmq/util/Wire.java
Wire.putUInt64
public static ByteBuffer putUInt64(ByteBuffer buf, long value) { buf.put((byte) ((value >>> 56) & 0xff)); buf.put((byte) ((value >>> 48) & 0xff)); buf.put((byte) ((value >>> 40) & 0xff)); buf.put((byte) ((value >>> 32) & 0xff)); buf.put((byte) ((value >>> 24) & 0xff)); buf.put((byte) ((value >>> 16) & 0xff)); buf.put((byte) ((value >>> 8) & 0xff)); buf.put((byte) ((value) & 0xff)); return buf; }
java
public static ByteBuffer putUInt64(ByteBuffer buf, long value) { buf.put((byte) ((value >>> 56) & 0xff)); buf.put((byte) ((value >>> 48) & 0xff)); buf.put((byte) ((value >>> 40) & 0xff)); buf.put((byte) ((value >>> 32) & 0xff)); buf.put((byte) ((value >>> 24) & 0xff)); buf.put((byte) ((value >>> 16) & 0xff)); buf.put((byte) ((value >>> 8) & 0xff)); buf.put((byte) ((value) & 0xff)); return buf; }
[ "public", "static", "ByteBuffer", "putUInt64", "(", "ByteBuffer", "buf", ",", "long", "value", ")", "{", "buf", ".", "put", "(", "(", "byte", ")", "(", "(", "value", ">>>", "56", ")", "&", "0xff", ")", ")", ";", "buf", ".", "put", "(", "(", "byte...
8 bytes value
[ "8", "bytes", "value" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/util/Wire.java#L124-L136
train
zeromq/jeromq
src/main/java/org/zeromq/ZThread.java
ZThread.fork
public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) { Socket pipe = ctx.createSocket(SocketType.PAIR); if (pipe != null) { pipe.bind(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); } else { return null; } // Connect child pipe to our pipe ZContext ccontext = ZContext.shadow(ctx); Socket cpipe = ccontext.createSocket(SocketType.PAIR); if (cpipe == null) { return null; } cpipe.connect(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); // Prepare child thread Thread shim = new ShimThread(ccontext, runnable, args, cpipe); shim.start(); return pipe; }
java
public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) { Socket pipe = ctx.createSocket(SocketType.PAIR); if (pipe != null) { pipe.bind(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); } else { return null; } // Connect child pipe to our pipe ZContext ccontext = ZContext.shadow(ctx); Socket cpipe = ccontext.createSocket(SocketType.PAIR); if (cpipe == null) { return null; } cpipe.connect(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); // Prepare child thread Thread shim = new ShimThread(ccontext, runnable, args, cpipe); shim.start(); return pipe; }
[ "public", "static", "Socket", "fork", "(", "ZContext", "ctx", ",", "IAttachedRunnable", "runnable", ",", "Object", "...", "args", ")", "{", "Socket", "pipe", "=", "ctx", ".", "createSocket", "(", "SocketType", ".", "PAIR", ")", ";", "if", "(", "pipe", "!...
pipe becomes unreadable. Returns pipe, or null if there was an error.
[ "pipe", "becomes", "unreadable", ".", "Returns", "pipe", "or", "null", "if", "there", "was", "an", "error", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZThread.java#L87-L111
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpConnecter.java
TcpConnecter.startConnecting
private void startConnecting() { // Open the connecting socket. try { boolean rc = open(); // Connect may succeed in synchronous manner. if (rc) { handle = ioObject.addFd(fd); connectEvent(); } // Connection establishment may be delayed. Poll for its completion. else { handle = ioObject.addFd(fd); ioObject.setPollConnect(handle); socket.eventConnectDelayed(addr.toString(), -1); } } catch (RuntimeException | IOException e) { // Handle any other error condition by eventual reconnect. if (fd != null) { close(); } addReconnectTimer(); } }
java
private void startConnecting() { // Open the connecting socket. try { boolean rc = open(); // Connect may succeed in synchronous manner. if (rc) { handle = ioObject.addFd(fd); connectEvent(); } // Connection establishment may be delayed. Poll for its completion. else { handle = ioObject.addFd(fd); ioObject.setPollConnect(handle); socket.eventConnectDelayed(addr.toString(), -1); } } catch (RuntimeException | IOException e) { // Handle any other error condition by eventual reconnect. if (fd != null) { close(); } addReconnectTimer(); } }
[ "private", "void", "startConnecting", "(", ")", "{", "// Open the connecting socket.", "try", "{", "boolean", "rc", "=", "open", "(", ")", ";", "// Connect may succeed in synchronous manner.", "if", "(", "rc", ")", "{", "handle", "=", "ioObject", ".", "addFd", ...
Internal function to start the actual connection establishment.
[ "Internal", "function", "to", "start", "the", "actual", "connection", "establishment", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpConnecter.java#L173-L198
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpConnecter.java
TcpConnecter.addReconnectTimer
private void addReconnectTimer() { int rcIvl = getNewReconnectIvl(); ioObject.addTimer(rcIvl, RECONNECT_TIMER_ID); // resolve address again to take into account other addresses // besides the failing one (e.g. multiple dns entries). try { addr.resolve(options.ipv6); } catch (Exception ignored) { // This will fail if the network goes away and the // address cannot be resolved for some reason. Try // not to fail as the event loop will quit } socket.eventConnectRetried(addr.toString(), rcIvl); timerStarted = true; }
java
private void addReconnectTimer() { int rcIvl = getNewReconnectIvl(); ioObject.addTimer(rcIvl, RECONNECT_TIMER_ID); // resolve address again to take into account other addresses // besides the failing one (e.g. multiple dns entries). try { addr.resolve(options.ipv6); } catch (Exception ignored) { // This will fail if the network goes away and the // address cannot be resolved for some reason. Try // not to fail as the event loop will quit } socket.eventConnectRetried(addr.toString(), rcIvl); timerStarted = true; }
[ "private", "void", "addReconnectTimer", "(", ")", "{", "int", "rcIvl", "=", "getNewReconnectIvl", "(", ")", ";", "ioObject", ".", "addTimer", "(", "rcIvl", ",", "RECONNECT_TIMER_ID", ")", ";", "// resolve address again to take into account other addresses", "// besides ...
Internal function to add a reconnect timer
[ "Internal", "function", "to", "add", "a", "reconnect", "timer" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpConnecter.java#L201-L219
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpConnecter.java
TcpConnecter.getNewReconnectIvl
private int getNewReconnectIvl() { // The new interval is the current interval + random value. int interval = currentReconnectIvl + (Utils.randomInt() % options.reconnectIvl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. if (options.reconnectIvlMax > 0 && options.reconnectIvlMax > options.reconnectIvl) { // Calculate the next interval currentReconnectIvl = Math.min(currentReconnectIvl * 2, options.reconnectIvlMax); } return interval; }
java
private int getNewReconnectIvl() { // The new interval is the current interval + random value. int interval = currentReconnectIvl + (Utils.randomInt() % options.reconnectIvl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. if (options.reconnectIvlMax > 0 && options.reconnectIvlMax > options.reconnectIvl) { // Calculate the next interval currentReconnectIvl = Math.min(currentReconnectIvl * 2, options.reconnectIvlMax); } return interval; }
[ "private", "int", "getNewReconnectIvl", "(", ")", "{", "// The new interval is the current interval + random value.", "int", "interval", "=", "currentReconnectIvl", "+", "(", "Utils", ".", "randomInt", "(", ")", "%", "options", ".", "reconnectIvl", ")", ";", "// Onl...
Returns the currently used interval
[ "Returns", "the", "currently", "used", "interval" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpConnecter.java#L224-L236
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpConnecter.java
TcpConnecter.open
private boolean open() throws IOException { assert (fd == null); // Resolve the address if (addr == null) { throw new IOException("Null address"); } addr.resolve(options.ipv6); Address.IZAddress resolved = addr.resolved(); if (resolved == null) { throw new IOException("Address not resolved"); } SocketAddress sa = resolved.address(); if (sa == null) { throw new IOException("Socket address not resolved"); } // Create the socket. if (options.selectorChooser == null) { fd = SocketChannel.open(); } else { fd = options.selectorChooser.choose(resolved, options).openSocketChannel(); } // On some systems, IPv4 mapping in IPv6 sockets is disabled by default. // Switch it on in such cases. // The method enableIpv4Mapping is empty. Still to be written if (resolved.family() == StandardProtocolFamily.INET6) { TcpUtils.enableIpv4Mapping(fd); } // Set the socket to non-blocking mode so that we get async connect(). TcpUtils.unblockSocket(fd); // Set the socket buffer limits for the underlying socket. if (options.sndbuf != 0) { TcpUtils.setTcpSendBuffer(fd, options.sndbuf); } if (options.rcvbuf != 0) { TcpUtils.setTcpReceiveBuffer(fd, options.rcvbuf); } // Set the IP Type-Of-Service priority for this socket if (options.tos != 0) { TcpUtils.setIpTypeOfService(fd, options.tos); } // TODO V4 Set a source address for conversations if (resolved.sourceAddress() != null) { // SocketChannel bind = channel.bind(resolved.sourceAddress()); // if (bind == null) { // return false; // } } // Connect to the remote peer. boolean rc; try { rc = fd.connect(sa); if (rc) { // Connect was successful immediately. } else { // Translate error codes indicating asynchronous connect has been // launched to a uniform EINPROGRESS. errno.set(ZError.EINPROGRESS); } } catch (IllegalArgumentException e) { // this will happen if sa is bad. Address validation is not documented but // I've found that IAE is thrown in openjdk as well as on android. throw new IOException(e.getMessage(), e); } return rc; }
java
private boolean open() throws IOException { assert (fd == null); // Resolve the address if (addr == null) { throw new IOException("Null address"); } addr.resolve(options.ipv6); Address.IZAddress resolved = addr.resolved(); if (resolved == null) { throw new IOException("Address not resolved"); } SocketAddress sa = resolved.address(); if (sa == null) { throw new IOException("Socket address not resolved"); } // Create the socket. if (options.selectorChooser == null) { fd = SocketChannel.open(); } else { fd = options.selectorChooser.choose(resolved, options).openSocketChannel(); } // On some systems, IPv4 mapping in IPv6 sockets is disabled by default. // Switch it on in such cases. // The method enableIpv4Mapping is empty. Still to be written if (resolved.family() == StandardProtocolFamily.INET6) { TcpUtils.enableIpv4Mapping(fd); } // Set the socket to non-blocking mode so that we get async connect(). TcpUtils.unblockSocket(fd); // Set the socket buffer limits for the underlying socket. if (options.sndbuf != 0) { TcpUtils.setTcpSendBuffer(fd, options.sndbuf); } if (options.rcvbuf != 0) { TcpUtils.setTcpReceiveBuffer(fd, options.rcvbuf); } // Set the IP Type-Of-Service priority for this socket if (options.tos != 0) { TcpUtils.setIpTypeOfService(fd, options.tos); } // TODO V4 Set a source address for conversations if (resolved.sourceAddress() != null) { // SocketChannel bind = channel.bind(resolved.sourceAddress()); // if (bind == null) { // return false; // } } // Connect to the remote peer. boolean rc; try { rc = fd.connect(sa); if (rc) { // Connect was successful immediately. } else { // Translate error codes indicating asynchronous connect has been // launched to a uniform EINPROGRESS. errno.set(ZError.EINPROGRESS); } } catch (IllegalArgumentException e) { // this will happen if sa is bad. Address validation is not documented but // I've found that IAE is thrown in openjdk as well as on android. throw new IOException(e.getMessage(), e); } return rc; }
[ "private", "boolean", "open", "(", ")", "throws", "IOException", "{", "assert", "(", "fd", "==", "null", ")", ";", "// Resolve the address", "if", "(", "addr", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"Null address\"", ")", ";", "}", ...
Returns false if async connect was launched.
[ "Returns", "false", "if", "async", "connect", "was", "launched", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpConnecter.java#L241-L322
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpConnecter.java
TcpConnecter.connect
private SocketChannel connect() { try { // Async connect has finished. Check whether an error occurred boolean finished = fd.finishConnect(); assert (finished); return fd; } catch (IOException e) { return null; } }
java
private SocketChannel connect() { try { // Async connect has finished. Check whether an error occurred boolean finished = fd.finishConnect(); assert (finished); return fd; } catch (IOException e) { return null; } }
[ "private", "SocketChannel", "connect", "(", ")", "{", "try", "{", "// Async connect has finished. Check whether an error occurred", "boolean", "finished", "=", "fd", ".", "finishConnect", "(", ")", ";", "assert", "(", "finished", ")", ";", "return", "fd", ";", "}...
null if the connection was unsuccessful.
[ "null", "if", "the", "connection", "was", "unsuccessful", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpConnecter.java#L326-L337
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpConnecter.java
TcpConnecter.close
protected void close() { assert (fd != null); try { fd.close(); socket.eventClosed(addr.toString(), fd); } catch (IOException e) { socket.eventCloseFailed(addr.toString(), ZError.exccode(e)); } fd = null; }
java
protected void close() { assert (fd != null); try { fd.close(); socket.eventClosed(addr.toString(), fd); } catch (IOException e) { socket.eventCloseFailed(addr.toString(), ZError.exccode(e)); } fd = null; }
[ "protected", "void", "close", "(", ")", "{", "assert", "(", "fd", "!=", "null", ")", ";", "try", "{", "fd", ".", "close", "(", ")", ";", "socket", ".", "eventClosed", "(", "addr", ".", "toString", "(", ")", ",", "fd", ")", ";", "}", "catch", "(...
Close the connecting socket.
[ "Close", "the", "connecting", "socket", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpConnecter.java#L340-L351
train
zeromq/jeromq
src/main/java/zmq/util/Timers.java
Timers.setInterval
@Deprecated public boolean setInterval(Timer timer, long interval) { assert (timer.parent == this); return timer.setInterval(interval); }
java
@Deprecated public boolean setInterval(Timer timer, long interval) { assert (timer.parent == this); return timer.setInterval(interval); }
[ "@", "Deprecated", "public", "boolean", "setInterval", "(", "Timer", "timer", ",", "long", "interval", ")", "{", "assert", "(", "timer", ".", "parent", "==", "this", ")", ";", "return", "timer", ".", "setInterval", "(", "interval", ")", ";", "}" ]
Changes the interval of the timer. This method is slow, canceling existing and adding a new timer yield better performance. @param timer the timer to change the interval to. @return true if set, otherwise false. @deprecated use {@link Timer#setInterval(long)} instead
[ "Changes", "the", "interval", "of", "the", "timer", ".", "This", "method", "is", "slow", "canceling", "existing", "and", "adding", "a", "new", "timer", "yield", "better", "performance", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/util/Timers.java#L139-L144
train
zeromq/jeromq
src/main/java/zmq/util/Timers.java
Timers.timeout
public long timeout() { final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); if (timer.alive) { // Live timer, lets return the timeout if (expiration - now > 0) { return expiration - now; } else { return 0; } } // Remove it from the list of active timers. timers.remove(expiration, timer); } // Wait forever as no timers are alive return -1; }
java
public long timeout() { final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); if (timer.alive) { // Live timer, lets return the timeout if (expiration - now > 0) { return expiration - now; } else { return 0; } } // Remove it from the list of active timers. timers.remove(expiration, timer); } // Wait forever as no timers are alive return -1; }
[ "public", "long", "timeout", "(", ")", "{", "final", "long", "now", "=", "now", "(", ")", ";", "for", "(", "Entry", "<", "Timer", ",", "Long", ">", "entry", ":", "entries", "(", ")", ")", "{", "final", "Timer", "timer", "=", "entry", ".", "getKey...
Returns the time in millisecond until the next timer. @return the time in millisecond until the next timer.
[ "Returns", "the", "time", "in", "millisecond", "until", "the", "next", "timer", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/util/Timers.java#L177-L199
train
zeromq/jeromq
src/main/java/zmq/util/Timers.java
Timers.execute
public int execute() { int executed = 0; final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); // Dead timer, lets remove it and continue if (!timer.alive) { // Remove it from the list of active timers. timers.remove(expiration, timer); continue; } // Map is ordered, if we have to wait for current timer we can stop. if (expiration - now > 0) { break; } insert(timer); timer.handler.time(timer.args); ++executed; } return executed; }
java
public int execute() { int executed = 0; final long now = now(); for (Entry<Timer, Long> entry : entries()) { final Timer timer = entry.getKey(); final Long expiration = entry.getValue(); // Dead timer, lets remove it and continue if (!timer.alive) { // Remove it from the list of active timers. timers.remove(expiration, timer); continue; } // Map is ordered, if we have to wait for current timer we can stop. if (expiration - now > 0) { break; } insert(timer); timer.handler.time(timer.args); ++executed; } return executed; }
[ "public", "int", "execute", "(", ")", "{", "int", "executed", "=", "0", ";", "final", "long", "now", "=", "now", "(", ")", ";", "for", "(", "Entry", "<", "Timer", ",", "Long", ">", "entry", ":", "entries", "(", ")", ")", "{", "final", "Timer", ...
Execute the timers. @return the number of timers triggered.
[ "Execute", "the", "timers", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/util/Timers.java#L205-L230
train
zeromq/jeromq
src/main/java/org/zeromq/ZProxy.java
ZProxy.newProxy
public static ZProxy newProxy(ZContext ctx, String name, Proxy sockets, String motdelafin, Object... args) { return new ZProxy(ctx, name, sockets, new ZmqPump(), motdelafin, args); }
java
public static ZProxy newProxy(ZContext ctx, String name, Proxy sockets, String motdelafin, Object... args) { return new ZProxy(ctx, name, sockets, new ZmqPump(), motdelafin, args); }
[ "public", "static", "ZProxy", "newProxy", "(", "ZContext", "ctx", ",", "String", "name", ",", "Proxy", "sockets", ",", "String", "motdelafin", ",", "Object", "...", "args", ")", "{", "return", "new", "ZProxy", "(", "ctx", ",", "name", ",", "sockets", ","...
Creates a new low-level proxy for better performances. @param ctx the context used for the proxy. Possibly null, in this case a new context will be created and automatically destroyed afterwards. @param name the name of the proxy. Possibly null. @param sockets the sockets creator of the proxy. Not null. @param motdelafin the final word used to mark the end of the proxy. Null to disable this mechanism. @param args an optional array of arguments that will be passed at the creation. @return the created proxy.
[ "Creates", "a", "new", "low", "-", "level", "proxy", "for", "better", "performances", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZProxy.java#L299-L302
train
zeromq/jeromq
src/main/java/org/zeromq/ZProxy.java
ZProxy.restart
public String restart(ZMsg hot) { ZMsg msg = new ZMsg(); msg.add(RESTART); final boolean cold = hot == null; if (cold) { msg.add(Boolean.toString(false)); } else { msg.add(Boolean.toString(true)); msg.append(hot); } String status = EXITED; if (agent.send(msg)) { status = status(false); } return status; }
java
public String restart(ZMsg hot) { ZMsg msg = new ZMsg(); msg.add(RESTART); final boolean cold = hot == null; if (cold) { msg.add(Boolean.toString(false)); } else { msg.add(Boolean.toString(true)); msg.append(hot); } String status = EXITED; if (agent.send(msg)) { status = status(false); } return status; }
[ "public", "String", "restart", "(", "ZMsg", "hot", ")", "{", "ZMsg", "msg", "=", "new", "ZMsg", "(", ")", ";", "msg", ".", "add", "(", "RESTART", ")", ";", "final", "boolean", "cold", "=", "hot", "==", "null", ";", "if", "(", "cold", ")", "{", ...
Restarts the proxy. Stays alive. @param hot null to make a cold restart (closing then re-creation of the sockets) or a configuration message to perform a configurable hot restart,
[ "Restarts", "the", "proxy", ".", "Stays", "alive", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZProxy.java#L445-L464
train
zeromq/jeromq
src/main/java/org/zeromq/ZProxy.java
ZProxy.exit
public String exit() { agent.send(EXIT); exit.awaitSilent(); agent.close(); return EXITED; }
java
public String exit() { agent.send(EXIT); exit.awaitSilent(); agent.close(); return EXITED; }
[ "public", "String", "exit", "(", ")", "{", "agent", ".", "send", "(", "EXIT", ")", ";", "exit", ".", "awaitSilent", "(", ")", ";", "agent", ".", "close", "(", ")", ";", "return", "EXITED", ";", "}" ]
Stops the proxy and exits. The call is synchronous. @return the read status.
[ "Stops", "the", "proxy", "and", "exits", ".", "The", "call", "is", "synchronous", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZProxy.java#L487-L493
train
zeromq/jeromq
src/main/java/org/zeromq/ZProxy.java
ZProxy.status
public String status(boolean sync) { if (exit.isExited()) { return EXITED; } try { String status = recvStatus(); if (agent.send(STATUS) && sync) { // wait for the response to emulate sync status = recvStatus(); // AND refill a status if (EXITED.equals(status) || !agent.send(STATUS)) { return EXITED; } } return status; } catch (ZMQException e) { return EXITED; } }
java
public String status(boolean sync) { if (exit.isExited()) { return EXITED; } try { String status = recvStatus(); if (agent.send(STATUS) && sync) { // wait for the response to emulate sync status = recvStatus(); // AND refill a status if (EXITED.equals(status) || !agent.send(STATUS)) { return EXITED; } } return status; } catch (ZMQException e) { return EXITED; } }
[ "public", "String", "status", "(", "boolean", "sync", ")", "{", "if", "(", "exit", ".", "isExited", "(", ")", ")", "{", "return", "EXITED", ";", "}", "try", "{", "String", "status", "=", "recvStatus", "(", ")", ";", "if", "(", "agent", ".", "send",...
Inquires for the status of the proxy. @param sync true to read the status in synchronous way, false for asynchronous mode. If false, you get the last cached status of the proxy
[ "Inquires", "for", "the", "status", "of", "the", "proxy", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZProxy.java#L510-L531
train
zeromq/jeromq
src/main/java/org/zeromq/ZProxy.java
ZProxy.recvStatus
private String recvStatus() { if (!agent.sign()) { return EXITED; } // receive the status response final ZMsg msg = agent.recv(); if (msg == null) { return EXITED; } String status = msg.popString(); msg.destroy(); return status; }
java
private String recvStatus() { if (!agent.sign()) { return EXITED; } // receive the status response final ZMsg msg = agent.recv(); if (msg == null) { return EXITED; } String status = msg.popString(); msg.destroy(); return status; }
[ "private", "String", "recvStatus", "(", ")", "{", "if", "(", "!", "agent", ".", "sign", "(", ")", ")", "{", "return", "EXITED", ";", "}", "// receive the status response", "final", "ZMsg", "msg", "=", "agent", ".", "recv", "(", ")", ";", "if", "(", "...
receives the last known state of the proxy
[ "receives", "the", "last", "known", "state", "of", "the", "proxy" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZProxy.java#L534-L549
train
zeromq/jeromq
src/main/java/org/zeromq/ZCertStore.java
ZCertStore.containsPublicKey
public boolean containsPublicKey(byte[] publicKey) { Utils.checkArgument( publicKey.length == 32, "publickey needs to have a size of 32 bytes. got only " + publicKey.length); return containsPublicKey(ZMQ.Curve.z85Encode(publicKey)); }
java
public boolean containsPublicKey(byte[] publicKey) { Utils.checkArgument( publicKey.length == 32, "publickey needs to have a size of 32 bytes. got only " + publicKey.length); return containsPublicKey(ZMQ.Curve.z85Encode(publicKey)); }
[ "public", "boolean", "containsPublicKey", "(", "byte", "[", "]", "publicKey", ")", "{", "Utils", ".", "checkArgument", "(", "publicKey", ".", "length", "==", "32", ",", "\"publickey needs to have a size of 32 bytes. got only \"", "+", "publicKey", ".", "length", ")"...
Check if a public key is in the certificate store. @param publicKey needs to be a 32 byte array representing the public key
[ "Check", "if", "a", "public", "key", "is", "in", "the", "certificate", "store", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZCertStore.java#L178-L184
train
zeromq/jeromq
src/main/java/org/zeromq/ZCertStore.java
ZCertStore.containsPublicKey
public boolean containsPublicKey(String publicKey) { Utils.checkArgument( publicKey.length() == 40, "z85 publickeys should have a length of 40 bytes but got " + publicKey.length()); reloadIfNecessary(); return publicKeys.containsKey(publicKey); }
java
public boolean containsPublicKey(String publicKey) { Utils.checkArgument( publicKey.length() == 40, "z85 publickeys should have a length of 40 bytes but got " + publicKey.length()); reloadIfNecessary(); return publicKeys.containsKey(publicKey); }
[ "public", "boolean", "containsPublicKey", "(", "String", "publicKey", ")", "{", "Utils", ".", "checkArgument", "(", "publicKey", ".", "length", "(", ")", "==", "40", ",", "\"z85 publickeys should have a length of 40 bytes but got \"", "+", "publicKey", ".", "length", ...
check if a z85-based public key is in the certificate store. This method will scan the folder for changes on every call @param publicKey
[ "check", "if", "a", "z85", "-", "based", "public", "key", "is", "in", "the", "certificate", "store", ".", "This", "method", "will", "scan", "the", "folder", "for", "changes", "on", "every", "call" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZCertStore.java#L191-L198
train
zeromq/jeromq
src/main/java/org/zeromq/ZCertStore.java
ZCertStore.checkForChanges
boolean checkForChanges() { // initialize with last checked files final Map<File, byte[]> presents = new HashMap<>(fingerprints); boolean modified = traverseDirectory(location, new IFileVisitor() { @Override public boolean visitFile(File file) { return modified(presents.remove(file), file); } @Override public boolean visitDir(File dir) { return modified(presents.remove(dir), dir); } }); // if some files remain, that means they have been deleted since last scan return modified || !presents.isEmpty(); }
java
boolean checkForChanges() { // initialize with last checked files final Map<File, byte[]> presents = new HashMap<>(fingerprints); boolean modified = traverseDirectory(location, new IFileVisitor() { @Override public boolean visitFile(File file) { return modified(presents.remove(file), file); } @Override public boolean visitDir(File dir) { return modified(presents.remove(dir), dir); } }); // if some files remain, that means they have been deleted since last scan return modified || !presents.isEmpty(); }
[ "boolean", "checkForChanges", "(", ")", "{", "// initialize with last checked files", "final", "Map", "<", "File", ",", "byte", "[", "]", ">", "presents", "=", "new", "HashMap", "<>", "(", "fingerprints", ")", ";", "boolean", "modified", "=", "traverseDirectory"...
Check if files in the certificate folders have been added or removed.
[ "Check", "if", "files", "in", "the", "certificate", "folders", "have", "been", "added", "or", "removed", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZCertStore.java#L273-L293
train
zeromq/jeromq
src/main/java/org/zeromq/ZAuth.java
ZAuth.configureCurve
public ZAuth configureCurve(String location) { Objects.requireNonNull(location, "Location has to be supplied"); return send(Mechanism.CURVE.name(), location); }
java
public ZAuth configureCurve(String location) { Objects.requireNonNull(location, "Location has to be supplied"); return send(Mechanism.CURVE.name(), location); }
[ "public", "ZAuth", "configureCurve", "(", "String", "location", ")", "{", "Objects", ".", "requireNonNull", "(", "location", ",", "\"Location has to be supplied\"", ")", ";", "return", "send", "(", "Mechanism", ".", "CURVE", ".", "name", "(", ")", ",", "locati...
Configure CURVE authentication @param location Can be ZAuth.CURVE_ALLOW_ANY or a directory with public-keys that will be accepted
[ "Configure", "CURVE", "authentication" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZAuth.java#L540-L544
train
zeromq/jeromq
src/main/java/org/zeromq/ZAuth.java
ZAuth.nextReply
public ZapReply nextReply(boolean wait) { if (!repliesEnabled) { System.out.println("ZAuth: replies are disabled. Please use replies(true);"); return null; } return ZapReply.recv(replies, wait); }
java
public ZapReply nextReply(boolean wait) { if (!repliesEnabled) { System.out.println("ZAuth: replies are disabled. Please use replies(true);"); return null; } return ZapReply.recv(replies, wait); }
[ "public", "ZapReply", "nextReply", "(", "boolean", "wait", ")", "{", "if", "(", "!", "repliesEnabled", ")", "{", "System", ".", "out", ".", "println", "(", "\"ZAuth: replies are disabled. Please use replies(true);\"", ")", ";", "return", "null", ";", "}", "retur...
Retrieves the next ZAP reply. @param wait true to wait for the next reply, false to immediately return if there is no next reply. @return the next reply or null if the actor is closed or if there is no next reply yet.
[ "Retrieves", "the", "next", "ZAP", "reply", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZAuth.java#L566-L573
train
zeromq/jeromq
src/main/java/zmq/ZMQ.java
ZMQ.send
public static int send(SocketBase s, String str, int flags) { byte[] data = str.getBytes(CHARSET); return send(s, data, data.length, flags); }
java
public static int send(SocketBase s, String str, int flags) { byte[] data = str.getBytes(CHARSET); return send(s, data, data.length, flags); }
[ "public", "static", "int", "send", "(", "SocketBase", "s", ",", "String", "str", ",", "int", "flags", ")", "{", "byte", "[", "]", "data", "=", "str", ".", "getBytes", "(", "CHARSET", ")", ";", "return", "send", "(", "s", ",", "data", ",", "data", ...
Sending functions.
[ "Sending", "functions", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/ZMQ.java#L402-L406
train
zeromq/jeromq
src/main/java/zmq/ZMQ.java
ZMQ.recv
public static Msg recv(SocketBase s, int flags) { checkSocket(s); Msg msg = recvMsg(s, flags); if (msg == null) { return null; } // At the moment an oversized message is silently truncated. // TODO: Build in a notification mechanism to report the overflows. //int to_copy = nbytes < len_ ? nbytes : len_; return msg; }
java
public static Msg recv(SocketBase s, int flags) { checkSocket(s); Msg msg = recvMsg(s, flags); if (msg == null) { return null; } // At the moment an oversized message is silently truncated. // TODO: Build in a notification mechanism to report the overflows. //int to_copy = nbytes < len_ ? nbytes : len_; return msg; }
[ "public", "static", "Msg", "recv", "(", "SocketBase", "s", ",", "int", "flags", ")", "{", "checkSocket", "(", "s", ")", ";", "Msg", "msg", "=", "recvMsg", "(", "s", ",", "flags", ")", ";", "if", "(", "msg", "==", "null", ")", "{", "return", "null...
Receiving functions.
[ "Receiving", "functions", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/ZMQ.java#L492-L505
train
zeromq/jeromq
src/main/java/zmq/ZMQ.java
ZMQ.getMessageMetadata
public static String getMessageMetadata(Msg msg, String property) { String data = null; Metadata metadata = msg.getMetadata(); if (metadata != null) { data = metadata.get(property); } return data; }
java
public static String getMessageMetadata(Msg msg, String property) { String data = null; Metadata metadata = msg.getMetadata(); if (metadata != null) { data = metadata.get(property); } return data; }
[ "public", "static", "String", "getMessageMetadata", "(", "Msg", "msg", ",", "String", "property", ")", "{", "String", "data", "=", "null", ";", "Metadata", "metadata", "=", "msg", ".", "getMetadata", "(", ")", ";", "if", "(", "metadata", "!=", "null", ")...
Get message metadata string
[ "Get", "message", "metadata", "string" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/ZMQ.java#L583-L591
train
zeromq/jeromq
src/main/java/zmq/ZMQ.java
ZMQ.proxy
public static boolean proxy(SocketBase frontend, SocketBase backend, SocketBase capture) { Utils.checkArgument(frontend != null, "Frontend socket has to be present for proxy"); Utils.checkArgument(backend != null, "Backend socket has to be present for proxy"); return Proxy.proxy(frontend, backend, capture, null); }
java
public static boolean proxy(SocketBase frontend, SocketBase backend, SocketBase capture) { Utils.checkArgument(frontend != null, "Frontend socket has to be present for proxy"); Utils.checkArgument(backend != null, "Backend socket has to be present for proxy"); return Proxy.proxy(frontend, backend, capture, null); }
[ "public", "static", "boolean", "proxy", "(", "SocketBase", "frontend", ",", "SocketBase", "backend", ",", "SocketBase", "capture", ")", "{", "Utils", ".", "checkArgument", "(", "frontend", "!=", "null", ",", "\"Frontend socket has to be present for proxy\"", ")", ";...
The proxy functionality
[ "The", "proxy", "functionality" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/ZMQ.java#L783-L788
train
zeromq/jeromq
src/main/java/org/zeromq/ZMonitor.java
ZMonitor.start
public final ZMonitor start() { if (started) { System.out.println("ZMonitor: Unable to start while already started."); return this; } agent.send(START); agent.recv(); started = true; return this; }
java
public final ZMonitor start() { if (started) { System.out.println("ZMonitor: Unable to start while already started."); return this; } agent.send(START); agent.recv(); started = true; return this; }
[ "public", "final", "ZMonitor", "start", "(", ")", "{", "if", "(", "started", ")", "{", "System", ".", "out", ".", "println", "(", "\"ZMonitor: Unable to start while already started.\"", ")", ";", "return", "this", ";", "}", "agent", ".", "send", "(", "START"...
Starts the monitoring. Event types have to be added before the start, or they will take no effect. @return this instance.
[ "Starts", "the", "monitoring", ".", "Event", "types", "have", "to", "be", "added", "before", "the", "start", "or", "they", "will", "take", "no", "effect", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZMonitor.java#L115-L125
train
zeromq/jeromq
src/main/java/org/zeromq/ZMonitor.java
ZMonitor.verbose
public final ZMonitor verbose(boolean verbose) { if (started) { System.out.println("ZMonitor: Unable to change verbosity while already started."); return this; } agent.send(VERBOSE, true); agent.send(Boolean.toString(verbose)); agent.recv(); return this; }
java
public final ZMonitor verbose(boolean verbose) { if (started) { System.out.println("ZMonitor: Unable to change verbosity while already started."); return this; } agent.send(VERBOSE, true); agent.send(Boolean.toString(verbose)); agent.recv(); return this; }
[ "public", "final", "ZMonitor", "verbose", "(", "boolean", "verbose", ")", "{", "if", "(", "started", ")", "{", "System", ".", "out", ".", "println", "(", "\"ZMonitor: Unable to change verbosity while already started.\"", ")", ";", "return", "this", ";", "}", "ag...
Sets verbosity of the monitor. @param verbose true for monitor to be verbose, otherwise false. @return this instance.
[ "Sets", "verbosity", "of", "the", "monitor", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZMonitor.java#L153-L163
train
zeromq/jeromq
src/main/java/org/zeromq/ZMonitor.java
ZMonitor.add
public final ZMonitor add(Event... events) { if (started) { System.out.println("ZMonitor: Unable to add events while already started."); return this; } ZMsg msg = new ZMsg(); msg.add(ADD_EVENTS); for (Event evt : events) { msg.add(evt.name()); } agent.send(msg); agent.recv(); return this; }
java
public final ZMonitor add(Event... events) { if (started) { System.out.println("ZMonitor: Unable to add events while already started."); return this; } ZMsg msg = new ZMsg(); msg.add(ADD_EVENTS); for (Event evt : events) { msg.add(evt.name()); } agent.send(msg); agent.recv(); return this; }
[ "public", "final", "ZMonitor", "add", "(", "Event", "...", "events", ")", "{", "if", "(", "started", ")", "{", "System", ".", "out", ".", "println", "(", "\"ZMonitor: Unable to add events while already started.\"", ")", ";", "return", "this", ";", "}", "ZMsg",...
Adds event types to monitor. @param events the types of events to monitor. @return this instance.
[ "Adds", "event", "types", "to", "monitor", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZMonitor.java#L170-L184
train
zeromq/jeromq
src/main/java/org/zeromq/ZMonitor.java
ZMonitor.nextEvent
public final ZEvent nextEvent(boolean wait) { if (!started) { System.out.println("ZMonitor: Start before getting events."); return null; } ZMsg msg = agent.recv(wait); if (msg == null) { return null; } return new ZEvent(msg); }
java
public final ZEvent nextEvent(boolean wait) { if (!started) { System.out.println("ZMonitor: Start before getting events."); return null; } ZMsg msg = agent.recv(wait); if (msg == null) { return null; } return new ZEvent(msg); }
[ "public", "final", "ZEvent", "nextEvent", "(", "boolean", "wait", ")", "{", "if", "(", "!", "started", ")", "{", "System", ".", "out", ".", "println", "(", "\"ZMonitor: Start before getting events.\"", ")", ";", "return", "null", ";", "}", "ZMsg", "msg", "...
Gets the next event, blocking for it until available if requested. @param wait true to block until next event is available, false to immediately return with null if there is no event. @return the next event or null if there is currently none.
[ "Gets", "the", "next", "event", "blocking", "for", "it", "until", "available", "if", "requested", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZMonitor.java#L221-L232
train
zeromq/jeromq
src/main/java/org/zeromq/ZSocket.java
ZSocket.sendFrame
public boolean sendFrame(ZFrame frame, int flags) { final byte[] data = frame.getData(); final Msg msg = new Msg(data); if (socketBase.send(msg, flags)) { return true; } mayRaise(); return false; }
java
public boolean sendFrame(ZFrame frame, int flags) { final byte[] data = frame.getData(); final Msg msg = new Msg(data); if (socketBase.send(msg, flags)) { return true; } mayRaise(); return false; }
[ "public", "boolean", "sendFrame", "(", "ZFrame", "frame", ",", "int", "flags", ")", "{", "final", "byte", "[", "]", "data", "=", "frame", ".", "getData", "(", ")", ";", "final", "Msg", "msg", "=", "new", "Msg", "(", "data", ")", ";", "if", "(", "...
Send a frame @param frame @param flags @return return true if successful
[ "Send", "a", "frame" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZSocket.java#L167-L176
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.pair
public static Pipe[] pair(ZObject[] parents, int[] hwms, boolean[] conflates) { Pipe[] pipes = new Pipe[2]; // Creates two pipe objects. These objects are connected by two ypipes, // each to pass messages in one direction. YPipeBase<Msg> upipe1 = conflates[0] ? new YPipeConflate<>() : new YPipe<Msg>(Config.MESSAGE_PIPE_GRANULARITY.getValue()); YPipeBase<Msg> upipe2 = conflates[1] ? new YPipeConflate<>() : new YPipe<Msg>(Config.MESSAGE_PIPE_GRANULARITY.getValue()); pipes[0] = new Pipe(parents[0], upipe1, upipe2, hwms[1], hwms[0], conflates[0]); pipes[1] = new Pipe(parents[1], upipe2, upipe1, hwms[0], hwms[1], conflates[1]); pipes[0].setPeer(pipes[1]); pipes[1].setPeer(pipes[0]); return pipes; }
java
public static Pipe[] pair(ZObject[] parents, int[] hwms, boolean[] conflates) { Pipe[] pipes = new Pipe[2]; // Creates two pipe objects. These objects are connected by two ypipes, // each to pass messages in one direction. YPipeBase<Msg> upipe1 = conflates[0] ? new YPipeConflate<>() : new YPipe<Msg>(Config.MESSAGE_PIPE_GRANULARITY.getValue()); YPipeBase<Msg> upipe2 = conflates[1] ? new YPipeConflate<>() : new YPipe<Msg>(Config.MESSAGE_PIPE_GRANULARITY.getValue()); pipes[0] = new Pipe(parents[0], upipe1, upipe2, hwms[1], hwms[0], conflates[0]); pipes[1] = new Pipe(parents[1], upipe2, upipe1, hwms[0], hwms[1], conflates[1]); pipes[0].setPeer(pipes[1]); pipes[1].setPeer(pipes[0]); return pipes; }
[ "public", "static", "Pipe", "[", "]", "pair", "(", "ZObject", "[", "]", "parents", ",", "int", "[", "]", "hwms", ",", "boolean", "[", "]", "conflates", ")", "{", "Pipe", "[", "]", "pipes", "=", "new", "Pipe", "[", "2", "]", ";", "// Creates two p...
terminates straight away.
[ "terminates", "straight", "away", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L121-L139
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.checkRead
public boolean checkRead() { if (!inActive) { return false; } if (state != State.ACTIVE && state != State.WAITING_FOR_DELIMITER) { return false; } // Check if there's an item in the pipe. if (!inpipe.checkRead()) { inActive = false; return false; } // If the next item in the pipe is message delimiter, // initiate termination process. if (isDelimiter(inpipe.probe())) { Msg msg = inpipe.read(); assert (msg != null); processDelimiter(); return false; } return true; }
java
public boolean checkRead() { if (!inActive) { return false; } if (state != State.ACTIVE && state != State.WAITING_FOR_DELIMITER) { return false; } // Check if there's an item in the pipe. if (!inpipe.checkRead()) { inActive = false; return false; } // If the next item in the pipe is message delimiter, // initiate termination process. if (isDelimiter(inpipe.probe())) { Msg msg = inpipe.read(); assert (msg != null); processDelimiter(); return false; } return true; }
[ "public", "boolean", "checkRead", "(", ")", "{", "if", "(", "!", "inActive", ")", "{", "return", "false", ";", "}", "if", "(", "state", "!=", "State", ".", "ACTIVE", "&&", "state", "!=", "State", ".", "WAITING_FOR_DELIMITER", ")", "{", "return", "false...
Returns true if there is at least one message to read in the pipe.
[ "Returns", "true", "if", "there", "is", "at", "least", "one", "message", "to", "read", "in", "the", "pipe", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L175-L201
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.read
public Msg read() { if (!inActive) { return null; } if (state != State.ACTIVE && state != State.WAITING_FOR_DELIMITER) { return null; } while (true) { Msg msg = inpipe.read(); if (msg == null) { inActive = false; return null; } // If this is a credential, save a copy and receive next message. if (msg.isCredential()) { credential = Blob.createBlob(msg); continue; } // If delimiter was read, start termination process of the pipe. if (msg.isDelimiter()) { processDelimiter(); return null; } if (!msg.hasMore() && !msg.isIdentity()) { msgsRead++; } if (lwm > 0 && msgsRead % lwm == 0) { sendActivateWrite(peer, msgsRead); } return msg; } }
java
public Msg read() { if (!inActive) { return null; } if (state != State.ACTIVE && state != State.WAITING_FOR_DELIMITER) { return null; } while (true) { Msg msg = inpipe.read(); if (msg == null) { inActive = false; return null; } // If this is a credential, save a copy and receive next message. if (msg.isCredential()) { credential = Blob.createBlob(msg); continue; } // If delimiter was read, start termination process of the pipe. if (msg.isDelimiter()) { processDelimiter(); return null; } if (!msg.hasMore() && !msg.isIdentity()) { msgsRead++; } if (lwm > 0 && msgsRead % lwm == 0) { sendActivateWrite(peer, msgsRead); } return msg; } }
[ "public", "Msg", "read", "(", ")", "{", "if", "(", "!", "inActive", ")", "{", "return", "null", ";", "}", "if", "(", "state", "!=", "State", ".", "ACTIVE", "&&", "state", "!=", "State", ".", "WAITING_FOR_DELIMITER", ")", "{", "return", "null", ";", ...
Reads a message to the underlying pipe.
[ "Reads", "a", "message", "to", "the", "underlying", "pipe", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L204-L242
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.checkWrite
public boolean checkWrite() { if (!outActive || state != State.ACTIVE) { return false; } // TODO DIFF V4 small change, it is done like this in 4.2.2 boolean full = !checkHwm(); if (full) { outActive = false; return false; } return true; }
java
public boolean checkWrite() { if (!outActive || state != State.ACTIVE) { return false; } // TODO DIFF V4 small change, it is done like this in 4.2.2 boolean full = !checkHwm(); if (full) { outActive = false; return false; } return true; }
[ "public", "boolean", "checkWrite", "(", ")", "{", "if", "(", "!", "outActive", "||", "state", "!=", "State", ".", "ACTIVE", ")", "{", "return", "false", ";", "}", "// TODO DIFF V4 small change, it is done like this in 4.2.2", "boolean", "full", "=", "!", "checkH...
the message would cause high watermark the function returns false.
[ "the", "message", "would", "cause", "high", "watermark", "the", "function", "returns", "false", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L246-L261
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.write
public boolean write(Msg msg) { if (!checkWrite()) { return false; } boolean more = msg.hasMore(); boolean identity = msg.isIdentity(); outpipe.write(msg, more); if (!more && !identity) { msgsWritten++; } return true; }
java
public boolean write(Msg msg) { if (!checkWrite()) { return false; } boolean more = msg.hasMore(); boolean identity = msg.isIdentity(); outpipe.write(msg, more); if (!more && !identity) { msgsWritten++; } return true; }
[ "public", "boolean", "write", "(", "Msg", "msg", ")", "{", "if", "(", "!", "checkWrite", "(", ")", ")", "{", "return", "false", ";", "}", "boolean", "more", "=", "msg", ".", "hasMore", "(", ")", ";", "boolean", "identity", "=", "msg", ".", "isIdent...
message cannot be written because high watermark was reached.
[ "message", "cannot", "be", "written", "because", "high", "watermark", "was", "reached", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L265-L280
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.rollback
public void rollback() { // Remove incomplete message from the outbound pipe. Msg msg; if (outpipe != null) { while ((msg = outpipe.unwrite()) != null) { assert (msg.hasMore()); } } }
java
public void rollback() { // Remove incomplete message from the outbound pipe. Msg msg; if (outpipe != null) { while ((msg = outpipe.unwrite()) != null) { assert (msg.hasMore()); } } }
[ "public", "void", "rollback", "(", ")", "{", "// Remove incomplete message from the outbound pipe.", "Msg", "msg", ";", "if", "(", "outpipe", "!=", "null", ")", "{", "while", "(", "(", "msg", "=", "outpipe", ".", "unwrite", "(", ")", ")", "!=", "null", ")...
Remove unfinished parts of the outbound message from the pipe.
[ "Remove", "unfinished", "parts", "of", "the", "outbound", "message", "from", "the", "pipe", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L283-L292
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.flush
public void flush() { // The peer does not exist anymore at this point. if (state == State.TERM_ACK_SENT) { return; } if (outpipe != null && !outpipe.flush()) { sendActivateRead(peer); } }
java
public void flush() { // The peer does not exist anymore at this point. if (state == State.TERM_ACK_SENT) { return; } if (outpipe != null && !outpipe.flush()) { sendActivateRead(peer); } }
[ "public", "void", "flush", "(", ")", "{", "// The peer does not exist anymore at this point.", "if", "(", "state", "==", "State", ".", "TERM_ACK_SENT", ")", "{", "return", ";", "}", "if", "(", "outpipe", "!=", "null", "&&", "!", "outpipe", ".", "flush", "("...
Flush the messages downstream.
[ "Flush", "the", "messages", "downstream", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L295-L305
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.terminate
public void terminate(boolean delay) { // Overload the value specified at pipe creation. this.delay = delay; // If terminate was already called, we can ignore the duplicit invocation. if (state == State.TERM_REQ_SENT_1 || state == State.TERM_REQ_SENT_2) { return; } // If the pipe is in the final phase of async termination, it's going to // closed anyway. No need to do anything special here. else if (state == State.TERM_ACK_SENT) { return; } // The simple sync termination case. Ask the peer to terminate and wait // for the ack. else if (state == State.ACTIVE) { sendPipeTerm(peer); state = State.TERM_REQ_SENT_1; } // There are still pending messages available, but the user calls // 'terminate'. We can act as if all the pending messages were read. else if (state == State.WAITING_FOR_DELIMITER && !this.delay) { outpipe = null; sendPipeTermAck(peer); state = State.TERM_ACK_SENT; } // If there are pending messages still available, do nothing. else if (state == State.WAITING_FOR_DELIMITER) { // do nothing } // We've already got delimiter, but not term command yet. We can ignore // the delimiter and ack synchronously terminate as if we were in // active state. else if (state == State.DELIMITER_RECEIVED) { sendPipeTerm(peer); state = State.TERM_REQ_SENT_1; } // There are no other states. else { assert (false); } // Stop outbound flow of messages. outActive = false; if (outpipe != null) { // Drop any unfinished outbound messages. rollback(); // Write the delimiter into the pipe. Note that watermarks are not // checked; thus the delimiter can be written even when the pipe is full. Msg msg = new Msg(); msg.initDelimiter(); outpipe.write(msg, false); flush(); } }
java
public void terminate(boolean delay) { // Overload the value specified at pipe creation. this.delay = delay; // If terminate was already called, we can ignore the duplicit invocation. if (state == State.TERM_REQ_SENT_1 || state == State.TERM_REQ_SENT_2) { return; } // If the pipe is in the final phase of async termination, it's going to // closed anyway. No need to do anything special here. else if (state == State.TERM_ACK_SENT) { return; } // The simple sync termination case. Ask the peer to terminate and wait // for the ack. else if (state == State.ACTIVE) { sendPipeTerm(peer); state = State.TERM_REQ_SENT_1; } // There are still pending messages available, but the user calls // 'terminate'. We can act as if all the pending messages were read. else if (state == State.WAITING_FOR_DELIMITER && !this.delay) { outpipe = null; sendPipeTermAck(peer); state = State.TERM_ACK_SENT; } // If there are pending messages still available, do nothing. else if (state == State.WAITING_FOR_DELIMITER) { // do nothing } // We've already got delimiter, but not term command yet. We can ignore // the delimiter and ack synchronously terminate as if we were in // active state. else if (state == State.DELIMITER_RECEIVED) { sendPipeTerm(peer); state = State.TERM_REQ_SENT_1; } // There are no other states. else { assert (false); } // Stop outbound flow of messages. outActive = false; if (outpipe != null) { // Drop any unfinished outbound messages. rollback(); // Write the delimiter into the pipe. Note that watermarks are not // checked; thus the delimiter can be written even when the pipe is full. Msg msg = new Msg(); msg.initDelimiter(); outpipe.write(msg, false); flush(); } }
[ "public", "void", "terminate", "(", "boolean", "delay", ")", "{", "// Overload the value specified at pipe creation.", "this", ".", "delay", "=", "delay", ";", "// If terminate was already called, we can ignore the duplicit invocation.", "if", "(", "state", "==", "State", ...
before actual shutdown.
[ "before", "actual", "shutdown", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L441-L499
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.processDelimiter
private void processDelimiter() { assert (state == State.ACTIVE || state == State.WAITING_FOR_DELIMITER); if (state == State.ACTIVE) { state = State.DELIMITER_RECEIVED; } else { outpipe = null; sendPipeTermAck(peer); state = State.TERM_ACK_SENT; } }
java
private void processDelimiter() { assert (state == State.ACTIVE || state == State.WAITING_FOR_DELIMITER); if (state == State.ACTIVE) { state = State.DELIMITER_RECEIVED; } else { outpipe = null; sendPipeTermAck(peer); state = State.TERM_ACK_SENT; } }
[ "private", "void", "processDelimiter", "(", ")", "{", "assert", "(", "state", "==", "State", ".", "ACTIVE", "||", "state", "==", "State", ".", "WAITING_FOR_DELIMITER", ")", ";", "if", "(", "state", "==", "State", ".", "ACTIVE", ")", "{", "state", "=", ...
Handler for delimiter read from the pipe.
[ "Handler", "for", "delimiter", "read", "from", "the", "pipe", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L535-L547
train
zeromq/jeromq
src/main/java/zmq/pipe/Pipe.java
Pipe.hiccup
public void hiccup() { // If termination is already under way do nothing. if (state != State.ACTIVE) { return; } // We'll drop the pointer to the inpipe. From now on, the peer is // responsible for deallocating it. inpipe = null; // Create new inpipe. if (conflate) { inpipe = new YPipeConflate<>(); } else { inpipe = new YPipe<>(Config.MESSAGE_PIPE_GRANULARITY.getValue()); } inActive = true; // Notify the peer about the hiccup. sendHiccup(peer, inpipe); }
java
public void hiccup() { // If termination is already under way do nothing. if (state != State.ACTIVE) { return; } // We'll drop the pointer to the inpipe. From now on, the peer is // responsible for deallocating it. inpipe = null; // Create new inpipe. if (conflate) { inpipe = new YPipeConflate<>(); } else { inpipe = new YPipe<>(Config.MESSAGE_PIPE_GRANULARITY.getValue()); } inActive = true; // Notify the peer about the hiccup. sendHiccup(peer, inpipe); }
[ "public", "void", "hiccup", "(", ")", "{", "// If termination is already under way do nothing.", "if", "(", "state", "!=", "State", ".", "ACTIVE", ")", "{", "return", ";", "}", "// We'll drop the pointer to the inpipe. From now on, the peer is", "// responsible for dealloc...
in the peer.
[ "in", "the", "peer", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/Pipe.java#L552-L574
train
zeromq/jeromq
src/main/java/zmq/socket/reqrep/Router.java
Router.rollback
protected boolean rollback() { if (currentOut != null) { currentOut.rollback(); currentOut = null; moreOut = false; } return true; }
java
protected boolean rollback() { if (currentOut != null) { currentOut.rollback(); currentOut = null; moreOut = false; } return true; }
[ "protected", "boolean", "rollback", "(", ")", "{", "if", "(", "currentOut", "!=", "null", ")", "{", "currentOut", ".", "rollback", "(", ")", ";", "currentOut", "=", "null", ";", "moreOut", "=", "false", ";", "}", "return", "true", ";", "}" ]
Rollback any message parts that were sent but not yet flushed.
[ "Rollback", "any", "message", "parts", "that", "were", "sent", "but", "not", "yet", "flushed", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/reqrep/Router.java#L345-L353
train
zeromq/jeromq
src/main/java/zmq/io/coder/EncoderBase.java
EncoderBase.encode
@Override public final int encode(ValueReference<ByteBuffer> data, int size) { int bufferSize = size; ByteBuffer buf = data.get(); if (buf == null) { buf = this.buffer; bufferSize = this.bufferSize; buffer.clear(); } if (inProgress == null) { return 0; } int pos = 0; buf.limit(buf.capacity()); while (pos < bufferSize) { // If there are no more data to return, run the state machine. // If there are still no data, return what we already have // in the buffer. if (toWrite == 0) { if (newMsgFlag) { inProgress = null; break; } next(); } // If there are no data in the buffer yet and we are able to // fill whole buffer in a single go, let's use zero-copy. // There's no disadvantage to it as we cannot stuck multiple // messages into the buffer anyway. Note that subsequent // write(s) are non-blocking, thus each single write writes // at most SO_SNDBUF bytes at once not depending on how large // is the chunk returned from here. // As a consequence, large messages being sent won't block // other engines running in the same I/O thread for excessive // amounts of time. if (pos == 0 && data.get() == null && toWrite >= bufferSize) { writeBuf.limit(writeBuf.capacity()); data.set(writeBuf); pos = toWrite; writeBuf = null; toWrite = 0; return pos; } // Copy data to the buffer. If the buffer is full, return. int toCopy = Math.min(toWrite, bufferSize - pos); int limit = writeBuf.limit(); writeBuf.limit(Math.min(writeBuf.capacity(), writeBuf.position() + toCopy)); int current = buf.position(); buf.put(writeBuf); toCopy = buf.position() - current; writeBuf.limit(limit); pos += toCopy; toWrite -= toCopy; } data.set(buf); return pos; }
java
@Override public final int encode(ValueReference<ByteBuffer> data, int size) { int bufferSize = size; ByteBuffer buf = data.get(); if (buf == null) { buf = this.buffer; bufferSize = this.bufferSize; buffer.clear(); } if (inProgress == null) { return 0; } int pos = 0; buf.limit(buf.capacity()); while (pos < bufferSize) { // If there are no more data to return, run the state machine. // If there are still no data, return what we already have // in the buffer. if (toWrite == 0) { if (newMsgFlag) { inProgress = null; break; } next(); } // If there are no data in the buffer yet and we are able to // fill whole buffer in a single go, let's use zero-copy. // There's no disadvantage to it as we cannot stuck multiple // messages into the buffer anyway. Note that subsequent // write(s) are non-blocking, thus each single write writes // at most SO_SNDBUF bytes at once not depending on how large // is the chunk returned from here. // As a consequence, large messages being sent won't block // other engines running in the same I/O thread for excessive // amounts of time. if (pos == 0 && data.get() == null && toWrite >= bufferSize) { writeBuf.limit(writeBuf.capacity()); data.set(writeBuf); pos = toWrite; writeBuf = null; toWrite = 0; return pos; } // Copy data to the buffer. If the buffer is full, return. int toCopy = Math.min(toWrite, bufferSize - pos); int limit = writeBuf.limit(); writeBuf.limit(Math.min(writeBuf.capacity(), writeBuf.position() + toCopy)); int current = buf.position(); buf.put(writeBuf); toCopy = buf.position() - current; writeBuf.limit(limit); pos += toCopy; toWrite -= toCopy; } data.set(buf); return pos; }
[ "@", "Override", "public", "final", "int", "encode", "(", "ValueReference", "<", "ByteBuffer", ">", "data", ",", "int", "size", ")", "{", "int", "bufferSize", "=", "size", ";", "ByteBuffer", "buf", "=", "data", ".", "get", "(", ")", ";", "if", "(", "...
is NULL) encoder will provide buffer of its own.
[ "is", "NULL", ")", "encoder", "will", "provide", "buffer", "of", "its", "own", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/coder/EncoderBase.java#L55-L119
train
zeromq/jeromq
src/main/java/zmq/io/coder/EncoderBase.java
EncoderBase.nextStep
private void nextStep(byte[] buf, int toWrite, Runnable next, boolean newMsgFlag) { if (buf != null) { writeBuf = ByteBuffer.wrap(buf); writeBuf.limit(toWrite); } else { writeBuf = null; } this.toWrite = toWrite; this.next = next; this.newMsgFlag = newMsgFlag; }
java
private void nextStep(byte[] buf, int toWrite, Runnable next, boolean newMsgFlag) { if (buf != null) { writeBuf = ByteBuffer.wrap(buf); writeBuf.limit(toWrite); } else { writeBuf = null; } this.toWrite = toWrite; this.next = next; this.newMsgFlag = newMsgFlag; }
[ "private", "void", "nextStep", "(", "byte", "[", "]", "buf", ",", "int", "toWrite", ",", "Runnable", "next", ",", "boolean", "newMsgFlag", ")", "{", "if", "(", "buf", "!=", "null", ")", "{", "writeBuf", "=", "ByteBuffer", ".", "wrap", "(", "buf", ")"...
to the buffer and schedule next state machine action.
[ "to", "the", "buffer", "and", "schedule", "next", "state", "machine", "action", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/coder/EncoderBase.java#L156-L168
train
zeromq/jeromq
src/main/java/zmq/poll/PollerBase.java
PollerBase.addTimer
public void addTimer(long timeout, IPollEvents sink, int id) { assert (Thread.currentThread() == worker); final long expiration = clock() + timeout; TimerInfo info = new TimerInfo(sink, id); timers.insert(expiration, info); changed = true; }
java
public void addTimer(long timeout, IPollEvents sink, int id) { assert (Thread.currentThread() == worker); final long expiration = clock() + timeout; TimerInfo info = new TimerInfo(sink, id); timers.insert(expiration, info); changed = true; }
[ "public", "void", "addTimer", "(", "long", "timeout", ",", "IPollEvents", "sink", ",", "int", "id", ")", "{", "assert", "(", "Thread", ".", "currentThread", "(", ")", "==", "worker", ")", ";", "final", "long", "expiration", "=", "clock", "(", ")", "+",...
argument set to id_.
[ "argument", "set", "to", "id_", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/poll/PollerBase.java#L111-L120
train
zeromq/jeromq
src/main/java/zmq/poll/PollerBase.java
PollerBase.cancelTimer
public void cancelTimer(IPollEvents sink, int id) { assert (Thread.currentThread() == worker); TimerInfo copy = new TimerInfo(sink, id); // Complexity of this operation is O(n). We assume it is rarely used. TimerInfo timerInfo = timers.find(copy); if (timerInfo != null) { // let's defer the removal during the loop timerInfo.cancelled = true; } }
java
public void cancelTimer(IPollEvents sink, int id) { assert (Thread.currentThread() == worker); TimerInfo copy = new TimerInfo(sink, id); // Complexity of this operation is O(n). We assume it is rarely used. TimerInfo timerInfo = timers.find(copy); if (timerInfo != null) { // let's defer the removal during the loop timerInfo.cancelled = true; } }
[ "public", "void", "cancelTimer", "(", "IPollEvents", "sink", ",", "int", "id", ")", "{", "assert", "(", "Thread", ".", "currentThread", "(", ")", "==", "worker", ")", ";", "TimerInfo", "copy", "=", "new", "TimerInfo", "(", "sink", ",", "id", ")", ";", ...
Cancel the timer created by sink_ object with ID equal to id_.
[ "Cancel", "the", "timer", "created", "by", "sink_", "object", "with", "ID", "equal", "to", "id_", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/poll/PollerBase.java#L123-L135
train
zeromq/jeromq
src/main/java/zmq/poll/PollerBase.java
PollerBase.executeTimers
protected long executeTimers() { assert (Thread.currentThread() == worker); changed = false; // Fast track. if (timers.isEmpty()) { return 0L; } // Get the current time. long current = clock(); // Execute the timers that are already due. for (Entry<TimerInfo, Long> entry : timers.entries()) { final TimerInfo timerInfo = entry.getKey(); if (timerInfo.cancelled) { timers.remove(entry.getValue(), timerInfo); continue; } // If we have to wait to execute the item, same will be true about // all the following items (multimap is sorted). Thus we can stop // checking the subsequent timers and return the time to wait for // the next timer (at least 1ms). final Long key = entry.getValue(); if (key > current) { return key - current; } // Remove it from the list of active timers. timers.remove(key, timerInfo); // Trigger the timer. timerInfo.sink.timerEvent(timerInfo.id); } // Remove empty list object for (Entry<TimerInfo, Long> entry : timers.entries()) { final Long key = entry.getValue(); if (!timers.hasValues(key)) { timers.remove(key); } } if (changed) { return executeTimers(); } // There are no more timers. return 0L; }
java
protected long executeTimers() { assert (Thread.currentThread() == worker); changed = false; // Fast track. if (timers.isEmpty()) { return 0L; } // Get the current time. long current = clock(); // Execute the timers that are already due. for (Entry<TimerInfo, Long> entry : timers.entries()) { final TimerInfo timerInfo = entry.getKey(); if (timerInfo.cancelled) { timers.remove(entry.getValue(), timerInfo); continue; } // If we have to wait to execute the item, same will be true about // all the following items (multimap is sorted). Thus we can stop // checking the subsequent timers and return the time to wait for // the next timer (at least 1ms). final Long key = entry.getValue(); if (key > current) { return key - current; } // Remove it from the list of active timers. timers.remove(key, timerInfo); // Trigger the timer. timerInfo.sink.timerEvent(timerInfo.id); } // Remove empty list object for (Entry<TimerInfo, Long> entry : timers.entries()) { final Long key = entry.getValue(); if (!timers.hasValues(key)) { timers.remove(key); } } if (changed) { return executeTimers(); } // There are no more timers. return 0L; }
[ "protected", "long", "executeTimers", "(", ")", "{", "assert", "(", "Thread", ".", "currentThread", "(", ")", "==", "worker", ")", ";", "changed", "=", "false", ";", "// Fast track.", "if", "(", "timers", ".", "isEmpty", "(", ")", ")", "{", "return", ...
to wait to match the next timer or 0 meaning "no timers".
[ "to", "wait", "to", "match", "the", "next", "timer", "or", "0", "meaning", "no", "timers", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/poll/PollerBase.java#L139-L192
train
zeromq/jeromq
src/main/java/zmq/Own.java
Own.processTerm
@Override protected void processTerm(int linger) { // Double termination should never happen. assert (!terminating); // Send termination request to all owned objects. for (Own it : owned) { sendTerm(it, linger); } registerTermAcks(owned.size()); owned.clear(); // Start termination process and check whether by chance we cannot // terminate immediately. terminating = true; checkTermAcks(); }
java
@Override protected void processTerm(int linger) { // Double termination should never happen. assert (!terminating); // Send termination request to all owned objects. for (Own it : owned) { sendTerm(it, linger); } registerTermAcks(owned.size()); owned.clear(); // Start termination process and check whether by chance we cannot // terminate immediately. terminating = true; checkTermAcks(); }
[ "@", "Override", "protected", "void", "processTerm", "(", "int", "linger", ")", "{", "// Double termination should never happen.", "assert", "(", "!", "terminating", ")", ";", "// Send termination request to all owned objects.", "for", "(", "Own", "it", ":", "owned", ...
steps to the beginning of the termination process.
[ "steps", "to", "the", "beginning", "of", "the", "termination", "process", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/Own.java#L197-L214
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Mtrie.java
Mtrie.rm
public boolean rm(Pipe pipe, IMtrieHandler func, XPub pub) { assert (pipe != null); assert (func != null); return rmHelper(pipe, new byte[0], 0, 0, func, pub); }
java
public boolean rm(Pipe pipe, IMtrieHandler func, XPub pub) { assert (pipe != null); assert (func != null); return rmHelper(pipe, new byte[0], 0, 0, func, pub); }
[ "public", "boolean", "rm", "(", "Pipe", "pipe", ",", "IMtrieHandler", "func", ",", "XPub", "pub", ")", "{", "assert", "(", "pipe", "!=", "null", ")", ";", "assert", "(", "func", "!=", "null", ")", ";", "return", "rmHelper", "(", "pipe", ",", "new", ...
supplied callback function.
[ "supplied", "callback", "function", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Mtrie.java#L122-L127
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Mtrie.java
Mtrie.rm
public boolean rm(Msg msg, Pipe pipe) { assert (msg != null); assert (pipe != null); return rmHelper(msg, 1, msg.size() - 1, pipe); }
java
public boolean rm(Msg msg, Pipe pipe) { assert (msg != null); assert (pipe != null); return rmHelper(msg, 1, msg.size() - 1, pipe); }
[ "public", "boolean", "rm", "(", "Msg", "msg", ",", "Pipe", "pipe", ")", "{", "assert", "(", "msg", "!=", "null", ")", ";", "assert", "(", "pipe", "!=", "null", ")", ";", "return", "rmHelper", "(", "msg", ",", "1", ",", "msg", ".", "size", "(", ...
actually removed rather than de-duplicated.
[ "actually", "removed", "rather", "than", "de", "-", "duplicated", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Mtrie.java#L243-L248
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Mtrie.java
Mtrie.match
public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub) { assert (data != null); assert (func != null); assert (pub != null); Mtrie current = this; int idx = 0; while (true) { // Signal the pipes attached to this node. if (current.pipes != null) { for (Pipe it : current.pipes) { func.invoke(it, null, 0, pub); } } // If we are at the end of the message, there's nothing more to match. if (size == 0) { break; } // If there are no subnodes in the trie, return. if (current.count == 0) { break; } byte c = data.get(idx); // If there's one subnode (optimisation). if (current.count == 1) { if (c != current.min) { break; } current = current.next[0]; idx++; size--; continue; } // If there are multiple subnodes. if (c < current.min || c >= current.min + current.count) { break; } if (current.next[c - current.min] == null) { break; } current = current.next[c - current.min]; idx++; size--; } }
java
public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub) { assert (data != null); assert (func != null); assert (pub != null); Mtrie current = this; int idx = 0; while (true) { // Signal the pipes attached to this node. if (current.pipes != null) { for (Pipe it : current.pipes) { func.invoke(it, null, 0, pub); } } // If we are at the end of the message, there's nothing more to match. if (size == 0) { break; } // If there are no subnodes in the trie, return. if (current.count == 0) { break; } byte c = data.get(idx); // If there's one subnode (optimisation). if (current.count == 1) { if (c != current.min) { break; } current = current.next[0]; idx++; size--; continue; } // If there are multiple subnodes. if (c < current.min || c >= current.min + current.count) { break; } if (current.next[c - current.min] == null) { break; } current = current.next[c - current.min]; idx++; size--; } }
[ "public", "void", "match", "(", "ByteBuffer", "data", ",", "int", "size", ",", "IMtrieHandler", "func", ",", "XPub", "pub", ")", "{", "assert", "(", "data", "!=", "null", ")", ";", "assert", "(", "func", "!=", "null", ")", ";", "assert", "(", "pub", ...
Signal all the matching pipes.
[ "Signal", "all", "the", "matching", "pipes", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Mtrie.java#L340-L389
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpListener.java
TcpListener.close
private void close() { assert (fd != null); try { fd.close(); socket.eventClosed(endpoint, fd); } catch (IOException e) { socket.eventCloseFailed(endpoint, ZError.exccode(e)); } fd = null; }
java
private void close() { assert (fd != null); try { fd.close(); socket.eventClosed(endpoint, fd); } catch (IOException e) { socket.eventCloseFailed(endpoint, ZError.exccode(e)); } fd = null; }
[ "private", "void", "close", "(", ")", "{", "assert", "(", "fd", "!=", "null", ")", ";", "try", "{", "fd", ".", "close", "(", ")", ";", "socket", ".", "eventClosed", "(", "endpoint", ",", "fd", ")", ";", "}", "catch", "(", "IOException", "e", ")",...
Close the listening socket.
[ "Close", "the", "listening", "socket", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpListener.java#L136-L148
train
zeromq/jeromq
src/main/java/zmq/io/net/tcp/TcpListener.java
TcpListener.accept
private SocketChannel accept() throws IOException { // The situation where connection cannot be accepted due to insufficient // resources is considered valid and treated by ignoring the connection. // Accept one connection and deal with different failure modes. assert (fd != null); SocketChannel sock = fd.accept(); if (!options.tcpAcceptFilters.isEmpty()) { boolean matched = false; for (TcpAddress.TcpAddressMask am : options.tcpAcceptFilters) { if (am.matchAddress(address.address())) { matched = true; break; } } if (!matched) { try { sock.close(); } catch (IOException e) { } return null; } } if (options.tos != 0) { TcpUtils.setIpTypeOfService(sock, options.tos); } // Set the socket buffer limits for the underlying socket. if (options.sndbuf != 0) { TcpUtils.setTcpSendBuffer(sock, options.sndbuf); } if (options.rcvbuf != 0) { TcpUtils.setTcpReceiveBuffer(sock, options.rcvbuf); } if (!isWindows) { TcpUtils.setReuseAddress(sock, true); } return sock; }
java
private SocketChannel accept() throws IOException { // The situation where connection cannot be accepted due to insufficient // resources is considered valid and treated by ignoring the connection. // Accept one connection and deal with different failure modes. assert (fd != null); SocketChannel sock = fd.accept(); if (!options.tcpAcceptFilters.isEmpty()) { boolean matched = false; for (TcpAddress.TcpAddressMask am : options.tcpAcceptFilters) { if (am.matchAddress(address.address())) { matched = true; break; } } if (!matched) { try { sock.close(); } catch (IOException e) { } return null; } } if (options.tos != 0) { TcpUtils.setIpTypeOfService(sock, options.tos); } // Set the socket buffer limits for the underlying socket. if (options.sndbuf != 0) { TcpUtils.setTcpSendBuffer(sock, options.sndbuf); } if (options.rcvbuf != 0) { TcpUtils.setTcpReceiveBuffer(sock, options.rcvbuf); } if (!isWindows) { TcpUtils.setReuseAddress(sock, true); } return sock; }
[ "private", "SocketChannel", "accept", "(", ")", "throws", "IOException", "{", "// The situation where connection cannot be accepted due to insufficient", "// resources is considered valid and treated by ignoring the connection.", "// Accept one connection and deal with different failure modes...
or was denied because of accept filters.
[ "or", "was", "denied", "because", "of", "accept", "filters", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/io/net/tcp/TcpListener.java#L217-L259
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.attach
public void attach(Pipe pipe) { // If we are in the middle of sending a message, we'll add new pipe // into the list of eligible pipes. Otherwise we add it to the list // of active pipes. if (more) { pipes.add(pipe); Collections.swap(pipes, eligible, pipes.size() - 1); eligible++; } else { pipes.add(pipe); Collections.swap(pipes, active, pipes.size() - 1); active++; eligible++; } }
java
public void attach(Pipe pipe) { // If we are in the middle of sending a message, we'll add new pipe // into the list of eligible pipes. Otherwise we add it to the list // of active pipes. if (more) { pipes.add(pipe); Collections.swap(pipes, eligible, pipes.size() - 1); eligible++; } else { pipes.add(pipe); Collections.swap(pipes, active, pipes.size() - 1); active++; eligible++; } }
[ "public", "void", "attach", "(", "Pipe", "pipe", ")", "{", "// If we are in the middle of sending a message, we'll add new pipe", "// into the list of eligible pipes. Otherwise we add it to the list", "// of active pipes.", "if", "(", "more", ")", "{", "pipes", ".", "add", "...
Adds the pipe to the distributor object.
[ "Adds", "the", "pipe", "to", "the", "distributor", "object", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L44-L60
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.match
public void match(Pipe pipe) { int idx = pipes.indexOf(pipe); // If pipe is already matching do nothing. if (idx < matching) { return; } // If the pipe isn't eligible, ignore it. if (idx >= eligible) { return; } // Mark the pipe as matching. Collections.swap(pipes, idx, matching); matching++; }
java
public void match(Pipe pipe) { int idx = pipes.indexOf(pipe); // If pipe is already matching do nothing. if (idx < matching) { return; } // If the pipe isn't eligible, ignore it. if (idx >= eligible) { return; } // Mark the pipe as matching. Collections.swap(pipes, idx, matching); matching++; }
[ "public", "void", "match", "(", "Pipe", "pipe", ")", "{", "int", "idx", "=", "pipes", ".", "indexOf", "(", "pipe", ")", ";", "// If pipe is already matching do nothing.", "if", "(", "idx", "<", "matching", ")", "{", "return", ";", "}", "// If the pipe isn'...
will send message also to this pipe.
[ "will", "send", "message", "also", "to", "this", "pipe", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L64-L80
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.terminated
public void terminated(Pipe pipe) { // Remove the pipe from the list; adjust number of matching, active and/or // eligible pipes accordingly. if (pipes.indexOf(pipe) < matching) { Collections.swap(pipes, pipes.indexOf(pipe), matching - 1); matching--; } if (pipes.indexOf(pipe) < active) { Collections.swap(pipes, pipes.indexOf(pipe), active - 1); active--; } if (pipes.indexOf(pipe) < eligible) { Collections.swap(pipes, pipes.indexOf(pipe), eligible - 1); eligible--; } pipes.remove(pipe); }
java
public void terminated(Pipe pipe) { // Remove the pipe from the list; adjust number of matching, active and/or // eligible pipes accordingly. if (pipes.indexOf(pipe) < matching) { Collections.swap(pipes, pipes.indexOf(pipe), matching - 1); matching--; } if (pipes.indexOf(pipe) < active) { Collections.swap(pipes, pipes.indexOf(pipe), active - 1); active--; } if (pipes.indexOf(pipe) < eligible) { Collections.swap(pipes, pipes.indexOf(pipe), eligible - 1); eligible--; } pipes.remove(pipe); }
[ "public", "void", "terminated", "(", "Pipe", "pipe", ")", "{", "// Remove the pipe from the list; adjust number of matching, active and/or", "// eligible pipes accordingly.", "if", "(", "pipes", ".", "indexOf", "(", "pipe", ")", "<", "matching", ")", "{", "Collections",...
Removes the pipe from the distributor object.
[ "Removes", "the", "pipe", "from", "the", "distributor", "object", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L89-L106
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.activated
public void activated(Pipe pipe) { // Move the pipe from passive to eligible state. Collections.swap(pipes, pipes.indexOf(pipe), eligible); eligible++; // If there's no message being sent at the moment, move it to // the active state. if (!more) { Collections.swap(pipes, eligible - 1, active); active++; } }
java
public void activated(Pipe pipe) { // Move the pipe from passive to eligible state. Collections.swap(pipes, pipes.indexOf(pipe), eligible); eligible++; // If there's no message being sent at the moment, move it to // the active state. if (!more) { Collections.swap(pipes, eligible - 1, active); active++; } }
[ "public", "void", "activated", "(", "Pipe", "pipe", ")", "{", "// Move the pipe from passive to eligible state.", "Collections", ".", "swap", "(", "pipes", ",", "pipes", ".", "indexOf", "(", "pipe", ")", ",", "eligible", ")", ";", "eligible", "++", ";", "// ...
Activates pipe that have previously reached high watermark.
[ "Activates", "pipe", "that", "have", "previously", "reached", "high", "watermark", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L109-L121
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.sendToMatching
public boolean sendToMatching(Msg msg) { // Is this end of a multipart message? boolean msgMore = msg.hasMore(); // Push the message to matching pipes. distribute(msg); // If mutlipart message is fully sent, activate all the eligible pipes. if (!msgMore) { active = eligible; } more = msgMore; return true; }
java
public boolean sendToMatching(Msg msg) { // Is this end of a multipart message? boolean msgMore = msg.hasMore(); // Push the message to matching pipes. distribute(msg); // If mutlipart message is fully sent, activate all the eligible pipes. if (!msgMore) { active = eligible; } more = msgMore; return true; }
[ "public", "boolean", "sendToMatching", "(", "Msg", "msg", ")", "{", "// Is this end of a multipart message?", "boolean", "msgMore", "=", "msg", ".", "hasMore", "(", ")", ";", "// Push the message to matching pipes.", "distribute", "(", "msg", ")", ";", "// If mutli...
Send the message to the matching outbound pipes.
[ "Send", "the", "message", "to", "the", "matching", "outbound", "pipes", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L131-L147
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.distribute
private void distribute(Msg msg) { // If there are no matching pipes available, simply drop the message. if (matching == 0) { return; } // TODO isVsm // Push copy of the message to each matching pipe. for (int idx = 0; idx < matching; ++idx) { if (!write(pipes.get(idx), msg)) { --idx; // Retry last write because index will have been swapped } } }
java
private void distribute(Msg msg) { // If there are no matching pipes available, simply drop the message. if (matching == 0) { return; } // TODO isVsm // Push copy of the message to each matching pipe. for (int idx = 0; idx < matching; ++idx) { if (!write(pipes.get(idx), msg)) { --idx; // Retry last write because index will have been swapped } } }
[ "private", "void", "distribute", "(", "Msg", "msg", ")", "{", "// If there are no matching pipes available, simply drop the message.", "if", "(", "matching", "==", "0", ")", "{", "return", ";", "}", "// TODO isVsm", "// Push copy of the message to each matching pipe.", "f...
Put the message to all active pipes.
[ "Put", "the", "message", "to", "all", "active", "pipes", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L150-L165
train
zeromq/jeromq
src/main/java/zmq/socket/pubsub/Dist.java
Dist.write
private boolean write(Pipe pipe, Msg msg) { if (!pipe.write(msg)) { Collections.swap(pipes, pipes.indexOf(pipe), matching - 1); matching--; Collections.swap(pipes, pipes.indexOf(pipe), active - 1); active--; Collections.swap(pipes, active, eligible - 1); eligible--; return false; } if (!msg.hasMore()) { pipe.flush(); } return true; }
java
private boolean write(Pipe pipe, Msg msg) { if (!pipe.write(msg)) { Collections.swap(pipes, pipes.indexOf(pipe), matching - 1); matching--; Collections.swap(pipes, pipes.indexOf(pipe), active - 1); active--; Collections.swap(pipes, active, eligible - 1); eligible--; return false; } if (!msg.hasMore()) { pipe.flush(); } return true; }
[ "private", "boolean", "write", "(", "Pipe", "pipe", ",", "Msg", "msg", ")", "{", "if", "(", "!", "pipe", ".", "write", "(", "msg", ")", ")", "{", "Collections", ".", "swap", "(", "pipes", ",", "pipes", ".", "indexOf", "(", "pipe", ")", ",", "matc...
fails. In such a case false is returned.
[ "fails", ".", "In", "such", "a", "case", "false", "is", "returned", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/socket/pubsub/Dist.java#L174-L189
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.register
public final boolean register(final SelectableChannel channel, final EventsHandler handler) { return register(channel, handler, IN | OUT | ERR); }
java
public final boolean register(final SelectableChannel channel, final EventsHandler handler) { return register(channel, handler, IN | OUT | ERR); }
[ "public", "final", "boolean", "register", "(", "final", "SelectableChannel", "channel", ",", "final", "EventsHandler", "handler", ")", "{", "return", "register", "(", "channel", ",", "handler", ",", "IN", "|", "OUT", "|", "ERR", ")", ";", "}" ]
Registers a SelectableChannel for polling on all events. @param channel the registering channel. @param handler the events handler for this channel @return true if registered, otherwise false
[ "Registers", "a", "SelectableChannel", "for", "polling", "on", "all", "events", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L589-L592
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.unregister
public final boolean unregister(final Object socketOrChannel) { if (socketOrChannel == null) { return false; } CompositePollItem items = this.items.remove(socketOrChannel); boolean rc = items != null; if (rc) { all.remove(items); } return rc; }
java
public final boolean unregister(final Object socketOrChannel) { if (socketOrChannel == null) { return false; } CompositePollItem items = this.items.remove(socketOrChannel); boolean rc = items != null; if (rc) { all.remove(items); } return rc; }
[ "public", "final", "boolean", "unregister", "(", "final", "Object", "socketOrChannel", ")", "{", "if", "(", "socketOrChannel", "==", "null", ")", "{", "return", "false", ";", "}", "CompositePollItem", "items", "=", "this", ".", "items", ".", "remove", "(", ...
Unregister a Socket or SelectableChannel for polling on the specified events. @param socketOrChannel the Socket or SelectableChannel to be unregistered @return true if unregistered, otherwise false TODO would it be useful to unregister only for specific events ?
[ "Unregister", "a", "Socket", "or", "SelectableChannel", "for", "polling", "on", "the", "specified", "events", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L624-L635
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.poll
protected int poll(final long timeout, final boolean dispatchEvents) { // get all the raw items final Set<PollItem> pollItems = new HashSet<>(); for (CompositePollItem it : all) { pollItems.add(it.item()); } // polling time final int rc = poll(selector, timeout, pollItems); if (!dispatchEvents) { // raw result return rc; } if (dispatch(all, pollItems.size())) { // returns event counts after dispatch if everything went fine return rc; } // error in dispatching return -1; }
java
protected int poll(final long timeout, final boolean dispatchEvents) { // get all the raw items final Set<PollItem> pollItems = new HashSet<>(); for (CompositePollItem it : all) { pollItems.add(it.item()); } // polling time final int rc = poll(selector, timeout, pollItems); if (!dispatchEvents) { // raw result return rc; } if (dispatch(all, pollItems.size())) { // returns event counts after dispatch if everything went fine return rc; } // error in dispatching return -1; }
[ "protected", "int", "poll", "(", "final", "long", "timeout", ",", "final", "boolean", "dispatchEvents", ")", "{", "// get all the raw items", "final", "Set", "<", "PollItem", ">", "pollItems", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Composit...
Issue a poll call, using the specified timeout value. @param timeout the timeout, as per zmq_poll (); @param dispatchEvents true to dispatch events using items handler and the global one. @see "http://api.zeromq.org/3-0:zmq-poll" @return how many objects where signaled by poll ()
[ "Issue", "a", "poll", "call", "using", "the", "specified", "timeout", "value", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L668-L689
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.poll
protected int poll(final Selector selector, final long tout, final Collection<zmq.poll.PollItem> items) { final int size = items.size(); return zmq.ZMQ.poll(selector, items.toArray(new PollItem[size]), size, tout); }
java
protected int poll(final Selector selector, final long tout, final Collection<zmq.poll.PollItem> items) { final int size = items.size(); return zmq.ZMQ.poll(selector, items.toArray(new PollItem[size]), size, tout); }
[ "protected", "int", "poll", "(", "final", "Selector", "selector", ",", "final", "long", "tout", ",", "final", "Collection", "<", "zmq", ".", "poll", ".", "PollItem", ">", "items", ")", "{", "final", "int", "size", "=", "items", ".", "size", "(", ")", ...
does the effective polling
[ "does", "the", "effective", "polling" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L700-L704
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.dispatch
protected boolean dispatch(final Collection<? extends ItemHolder> all, int size) { ItemHolder[] array = all.toArray(new ItemHolder[all.size()]); // protected against handlers unregistering during this loop for (ItemHolder holder : array) { EventsHandler handler = holder.handler(); if (handler == null) { handler = globalHandler; } if (handler == null) { // no handler, short-circuit continue; } final PollItem item = holder.item(); final int events = item.readyOps(); if (events <= 0) { // no events, short-circuit continue; } final Socket socket = holder.socket(); final SelectableChannel channel = holder.item().getRawSocket(); if (socket != null) { assert (channel == null); // dispatch on socket if (!handler.events(socket, events)) { return false; } } if (channel != null) { // dispatch on channel assert (socket == null); if (!handler.events(channel, events)) { return false; } } } return true; }
java
protected boolean dispatch(final Collection<? extends ItemHolder> all, int size) { ItemHolder[] array = all.toArray(new ItemHolder[all.size()]); // protected against handlers unregistering during this loop for (ItemHolder holder : array) { EventsHandler handler = holder.handler(); if (handler == null) { handler = globalHandler; } if (handler == null) { // no handler, short-circuit continue; } final PollItem item = holder.item(); final int events = item.readyOps(); if (events <= 0) { // no events, short-circuit continue; } final Socket socket = holder.socket(); final SelectableChannel channel = holder.item().getRawSocket(); if (socket != null) { assert (channel == null); // dispatch on socket if (!handler.events(socket, events)) { return false; } } if (channel != null) { // dispatch on channel assert (socket == null); if (!handler.events(channel, events)) { return false; } } } return true; }
[ "protected", "boolean", "dispatch", "(", "final", "Collection", "<", "?", "extends", "ItemHolder", ">", "all", ",", "int", "size", ")", "{", "ItemHolder", "[", "]", "array", "=", "all", ".", "toArray", "(", "new", "ItemHolder", "[", "all", ".", "size", ...
Dispatches the polled events. @param all the items used for dispatching @param size the number of items to dispatch @return true if correctly dispatched, false in case of error
[ "Dispatches", "the", "polled", "events", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L713-L752
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.readable
public boolean readable(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, READABLE); if (it == null) { return false; } return it.isReadable(); }
java
public boolean readable(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, READABLE); if (it == null) { return false; } return it.isReadable(); }
[ "public", "boolean", "readable", "(", "final", "Object", "socketOrChannel", ")", "{", "final", "PollItem", "it", "=", "filter", "(", "socketOrChannel", ",", "READABLE", ")", ";", "if", "(", "it", "==", "null", ")", "{", "return", "false", ";", "}", "retu...
checks for read event
[ "checks", "for", "read", "event" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L797-L804
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.writable
public boolean writable(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, WRITABLE); if (it == null) { return false; } return it.isWritable(); }
java
public boolean writable(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, WRITABLE); if (it == null) { return false; } return it.isWritable(); }
[ "public", "boolean", "writable", "(", "final", "Object", "socketOrChannel", ")", "{", "final", "PollItem", "it", "=", "filter", "(", "socketOrChannel", ",", "WRITABLE", ")", ";", "if", "(", "it", "==", "null", ")", "{", "return", "false", ";", "}", "retu...
checks for write event
[ "checks", "for", "write", "event" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L849-L856
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.error
public boolean error(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, ERR); if (it == null) { return false; } return it.isError(); }
java
public boolean error(final Object socketOrChannel) { final PollItem it = filter(socketOrChannel, ERR); if (it == null) { return false; } return it.isError(); }
[ "public", "boolean", "error", "(", "final", "Object", "socketOrChannel", ")", "{", "final", "PollItem", "it", "=", "filter", "(", "socketOrChannel", ",", "ERR", ")", ";", "if", "(", "it", "==", "null", ")", "{", "return", "false", ";", "}", "return", "...
checks for error event
[ "checks", "for", "error", "event" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L901-L908
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.add
protected boolean add(Object socketOrChannel, final ItemHolder holder) { if (socketOrChannel == null) { Socket socket = holder.socket(); SelectableChannel ch = holder.item().getRawSocket(); if (ch == null) { // not a channel assert (socket != null); socketOrChannel = socket; } else if (socket == null) { // not a socket socketOrChannel = ch; } } assert (socketOrChannel != null); CompositePollItem aggregate = items.get(socketOrChannel); if (aggregate == null) { aggregate = new CompositePollItem(socketOrChannel); items.put(socketOrChannel, aggregate); } final boolean rc = aggregate.holders.add(holder); if (rc) { all.add(aggregate); } return rc; }
java
protected boolean add(Object socketOrChannel, final ItemHolder holder) { if (socketOrChannel == null) { Socket socket = holder.socket(); SelectableChannel ch = holder.item().getRawSocket(); if (ch == null) { // not a channel assert (socket != null); socketOrChannel = socket; } else if (socket == null) { // not a socket socketOrChannel = ch; } } assert (socketOrChannel != null); CompositePollItem aggregate = items.get(socketOrChannel); if (aggregate == null) { aggregate = new CompositePollItem(socketOrChannel); items.put(socketOrChannel, aggregate); } final boolean rc = aggregate.holders.add(holder); if (rc) { all.add(aggregate); } return rc; }
[ "protected", "boolean", "add", "(", "Object", "socketOrChannel", ",", "final", "ItemHolder", "holder", ")", "{", "if", "(", "socketOrChannel", "==", "null", ")", "{", "Socket", "socket", "=", "holder", ".", "socket", "(", ")", ";", "SelectableChannel", "ch",...
add an item to this poller
[ "add", "an", "item", "to", "this", "poller" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L968-L995
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.items
protected Collection<? extends ItemHolder> items() { for (CompositePollItem item : all) { item.handler(globalHandler); } return all; }
java
protected Collection<? extends ItemHolder> items() { for (CompositePollItem item : all) { item.handler(globalHandler); } return all; }
[ "protected", "Collection", "<", "?", "extends", "ItemHolder", ">", "items", "(", ")", "{", "for", "(", "CompositePollItem", "item", ":", "all", ")", "{", "item", ".", "handler", "(", "globalHandler", ")", ";", "}", "return", "all", ";", "}" ]
gets all the items of this poller
[ "gets", "all", "the", "items", "of", "this", "poller" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L1005-L1011
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.items
protected Iterable<ItemHolder> items(final Object socketOrChannel) { final CompositePollItem aggregate = items.get(socketOrChannel); if (aggregate == null) { return Collections.emptySet(); } return aggregate.holders; }
java
protected Iterable<ItemHolder> items(final Object socketOrChannel) { final CompositePollItem aggregate = items.get(socketOrChannel); if (aggregate == null) { return Collections.emptySet(); } return aggregate.holders; }
[ "protected", "Iterable", "<", "ItemHolder", ">", "items", "(", "final", "Object", "socketOrChannel", ")", "{", "final", "CompositePollItem", "aggregate", "=", "items", ".", "get", "(", "socketOrChannel", ")", ";", "if", "(", "aggregate", "==", "null", ")", "...
gets all the items of this poller regarding the given input
[ "gets", "all", "the", "items", "of", "this", "poller", "regarding", "the", "given", "input" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L1014-L1021
train
zeromq/jeromq
src/main/java/org/zeromq/ZPoller.java
ZPoller.filter
protected PollItem filter(final Object socketOrChannel, int events) { if (socketOrChannel == null) { return null; } CompositePollItem item = items.get(socketOrChannel); if (item == null) { return null; } PollItem pollItem = item.item(); if (pollItem == null) { return null; } if (pollItem.hasEvent(events)) { return pollItem; } return null; }
java
protected PollItem filter(final Object socketOrChannel, int events) { if (socketOrChannel == null) { return null; } CompositePollItem item = items.get(socketOrChannel); if (item == null) { return null; } PollItem pollItem = item.item(); if (pollItem == null) { return null; } if (pollItem.hasEvent(events)) { return pollItem; } return null; }
[ "protected", "PollItem", "filter", "(", "final", "Object", "socketOrChannel", ",", "int", "events", ")", "{", "if", "(", "socketOrChannel", "==", "null", ")", "{", "return", "null", ";", "}", "CompositePollItem", "item", "=", "items", ".", "get", "(", "soc...
filters items to get the first one matching the criteria, or null if none found
[ "filters", "items", "to", "get", "the", "first", "one", "matching", "the", "criteria", "or", "null", "if", "none", "found" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZPoller.java#L1024-L1041
train
zeromq/jeromq
src/main/java/org/zeromq/proto/ZNeedle.java
ZNeedle.getShortString
public String getShortString() { String value = Wire.getShortString(needle, needle.position()); forward(value.length() + 1); return value; }
java
public String getShortString() { String value = Wire.getShortString(needle, needle.position()); forward(value.length() + 1); return value; }
[ "public", "String", "getShortString", "(", ")", "{", "String", "value", "=", "Wire", ".", "getShortString", "(", "needle", ",", "needle", ".", "position", "(", ")", ")", ";", "forward", "(", "value", ".", "length", "(", ")", "+", "1", ")", ";", "retu...
Get a string from the frame
[ "Get", "a", "string", "from", "the", "frame" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/proto/ZNeedle.java#L138-L143
train
zeromq/jeromq
src/main/java/org/zeromq/proto/ZNeedle.java
ZNeedle.getLongString
public String getLongString() { String value = Wire.getLongString(needle, needle.position()); forward(value.length() + 4); return value; }
java
public String getLongString() { String value = Wire.getLongString(needle, needle.position()); forward(value.length() + 4); return value; }
[ "public", "String", "getLongString", "(", ")", "{", "String", "value", "=", "Wire", ".", "getLongString", "(", "needle", ",", "needle", ".", "position", "(", ")", ")", ";", "forward", "(", "value", ".", "length", "(", ")", "+", "4", ")", ";", "return...
Get a long string from the frame
[ "Get", "a", "long", "string", "from", "the", "frame" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/proto/ZNeedle.java#L152-L157
train
zeromq/jeromq
src/main/java/org/zeromq/proto/ZNeedle.java
ZNeedle.putList
public void putList(Collection<String> elements) { if (elements == null) { putNumber1(0); } else { Utils.checkArgument(elements.size() < 256, "Collection has to be smaller than 256 elements"); putNumber1(elements.size()); for (String string : elements) { putString(string); } } }
java
public void putList(Collection<String> elements) { if (elements == null) { putNumber1(0); } else { Utils.checkArgument(elements.size() < 256, "Collection has to be smaller than 256 elements"); putNumber1(elements.size()); for (String string : elements) { putString(string); } } }
[ "public", "void", "putList", "(", "Collection", "<", "String", ">", "elements", ")", "{", "if", "(", "elements", "==", "null", ")", "{", "putNumber1", "(", "0", ")", ";", "}", "else", "{", "Utils", ".", "checkArgument", "(", "elements", ".", "size", ...
Put a collection of strings to the frame
[ "Put", "a", "collection", "of", "strings", "to", "the", "frame" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/proto/ZNeedle.java#L177-L189
train
zeromq/jeromq
src/main/java/org/zeromq/proto/ZNeedle.java
ZNeedle.putMap
public void putMap(Map<String, String> map) { if (map == null) { putNumber1(0); } else { Utils.checkArgument(map.size() < 256, "Map has to be smaller than 256 elements"); putNumber1(map.size()); for (Entry<String, String> entry : map.entrySet()) { if (entry.getKey().contains("=")) { throw new IllegalArgumentException("Keys cannot contain '=' sign. " + entry); } if (entry.getValue().contains("=")) { throw new IllegalArgumentException("Values cannot contain '=' sign. " + entry); } String val = entry.getKey() + "=" + entry.getValue(); putString(val); } } }
java
public void putMap(Map<String, String> map) { if (map == null) { putNumber1(0); } else { Utils.checkArgument(map.size() < 256, "Map has to be smaller than 256 elements"); putNumber1(map.size()); for (Entry<String, String> entry : map.entrySet()) { if (entry.getKey().contains("=")) { throw new IllegalArgumentException("Keys cannot contain '=' sign. " + entry); } if (entry.getValue().contains("=")) { throw new IllegalArgumentException("Values cannot contain '=' sign. " + entry); } String val = entry.getKey() + "=" + entry.getValue(); putString(val); } } }
[ "public", "void", "putMap", "(", "Map", "<", "String", ",", "String", ">", "map", ")", "{", "if", "(", "map", "==", "null", ")", "{", "putNumber1", "(", "0", ")", ";", "}", "else", "{", "Utils", ".", "checkArgument", "(", "map", ".", "size", "(",...
Put a map of strings to the frame
[ "Put", "a", "map", "of", "strings", "to", "the", "frame" ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/proto/ZNeedle.java#L202-L221
train
zeromq/jeromq
src/main/java/zmq/pipe/YQueue.java
YQueue.push
public void push(T val) { backChunk.values[backPos] = val; backChunk = endChunk; backPos = endPos; if (++endPos != size) { return; } Chunk<T> sc = spareChunk; if (sc != beginChunk) { spareChunk = spareChunk.next; endChunk.next = sc; sc.prev = endChunk; } else { endChunk.next = new Chunk<>(size, memoryPtr); memoryPtr += size; endChunk.next.prev = endChunk; } endChunk = endChunk.next; endPos = 0; }
java
public void push(T val) { backChunk.values[backPos] = val; backChunk = endChunk; backPos = endPos; if (++endPos != size) { return; } Chunk<T> sc = spareChunk; if (sc != beginChunk) { spareChunk = spareChunk.next; endChunk.next = sc; sc.prev = endChunk; } else { endChunk.next = new Chunk<>(size, memoryPtr); memoryPtr += size; endChunk.next.prev = endChunk; } endChunk = endChunk.next; endPos = 0; }
[ "public", "void", "push", "(", "T", "val", ")", "{", "backChunk", ".", "values", "[", "backPos", "]", "=", "val", ";", "backChunk", "=", "endChunk", ";", "backPos", "=", "endPos", ";", "if", "(", "++", "endPos", "!=", "size", ")", "{", "return", ";...
Adds an element to the back end of the queue.
[ "Adds", "an", "element", "to", "the", "back", "end", "of", "the", "queue", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/YQueue.java#L82-L105
train
zeromq/jeromq
src/main/java/zmq/pipe/YQueue.java
YQueue.unpush
public void unpush() { // First, move 'back' one position backwards. if (backPos > 0) { --backPos; } else { backPos = size - 1; backChunk = backChunk.prev; } // Now, move 'end' position backwards. Note that obsolete end chunk // is not used as a spare chunk. The analysis shows that doing so // would require free and atomic operation per chunk deallocated // instead of a simple free. if (endPos > 0) { --endPos; } else { endPos = size - 1; endChunk = endChunk.prev; endChunk.next = null; } }
java
public void unpush() { // First, move 'back' one position backwards. if (backPos > 0) { --backPos; } else { backPos = size - 1; backChunk = backChunk.prev; } // Now, move 'end' position backwards. Note that obsolete end chunk // is not used as a spare chunk. The analysis shows that doing so // would require free and atomic operation per chunk deallocated // instead of a simple free. if (endPos > 0) { --endPos; } else { endPos = size - 1; endChunk = endChunk.prev; endChunk.next = null; } }
[ "public", "void", "unpush", "(", ")", "{", "// First, move 'back' one position backwards.", "if", "(", "backPos", ">", "0", ")", "{", "--", "backPos", ";", "}", "else", "{", "backPos", "=", "size", "-", "1", ";", "backChunk", "=", "backChunk", ".", "prev"...
unsynchronised thread.
[ "unsynchronised", "thread", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/YQueue.java#L114-L137
train
zeromq/jeromq
src/main/java/zmq/pipe/YQueue.java
YQueue.pop
public T pop() { T val = beginChunk.values[beginPos]; beginChunk.values[beginPos] = null; beginPos++; if (beginPos == size) { beginChunk = beginChunk.next; beginChunk.prev = null; beginPos = 0; } return val; }
java
public T pop() { T val = beginChunk.values[beginPos]; beginChunk.values[beginPos] = null; beginPos++; if (beginPos == size) { beginChunk = beginChunk.next; beginChunk.prev = null; beginPos = 0; } return val; }
[ "public", "T", "pop", "(", ")", "{", "T", "val", "=", "beginChunk", ".", "values", "[", "beginPos", "]", ";", "beginChunk", ".", "values", "[", "beginPos", "]", "=", "null", ";", "beginPos", "++", ";", "if", "(", "beginPos", "==", "size", ")", "{",...
Removes an element from the front end of the queue.
[ "Removes", "an", "element", "from", "the", "front", "end", "of", "the", "queue", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/zmq/pipe/YQueue.java#L140-L151
train
zeromq/jeromq
src/main/java/org/zeromq/ZLoop.java
ZLoop.rebuild
private void rebuild() { pollact = null; pollSize = pollers.size(); if (pollset != null) { pollset.close(); } pollset = context.poller(pollSize); assert (pollset != null); pollact = new SPoller[pollSize]; int itemNbr = 0; for (SPoller poller : pollers) { pollset.register(poller.item); pollact[itemNbr] = poller; itemNbr++; } dirty = false; }
java
private void rebuild() { pollact = null; pollSize = pollers.size(); if (pollset != null) { pollset.close(); } pollset = context.poller(pollSize); assert (pollset != null); pollact = new SPoller[pollSize]; int itemNbr = 0; for (SPoller poller : pollers) { pollset.register(poller.item); pollact[itemNbr] = poller; itemNbr++; } dirty = false; }
[ "private", "void", "rebuild", "(", ")", "{", "pollact", "=", "null", ";", "pollSize", "=", "pollers", ".", "size", "(", ")", ";", "if", "(", "pollset", "!=", "null", ")", "{", "pollset", ".", "close", "(", ")", ";", "}", "pollset", "=", "context", ...
activity on pollers. Returns 0 on success, -1 on failure.
[ "activity", "on", "pollers", ".", "Returns", "0", "on", "success", "-", "1", "on", "failure", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZLoop.java#L103-L123
train
zeromq/jeromq
src/main/java/org/zeromq/ZLoop.java
ZLoop.addPoller
public int addPoller(PollItem pollItem, IZLoopHandler handler, Object arg) { if (pollItem.getRawSocket() == null && pollItem.getSocket() == null) { return -1; } SPoller poller = new SPoller(pollItem, handler, arg); pollers.add(poller); dirty = true; if (verbose) { System.out.printf( "I: zloop: register %s poller (%s, %s)\n", pollItem.getSocket() != null ? pollItem.getSocket().getType() : "RAW", pollItem.getSocket(), pollItem.getRawSocket()); } return 0; }
java
public int addPoller(PollItem pollItem, IZLoopHandler handler, Object arg) { if (pollItem.getRawSocket() == null && pollItem.getSocket() == null) { return -1; } SPoller poller = new SPoller(pollItem, handler, arg); pollers.add(poller); dirty = true; if (verbose) { System.out.printf( "I: zloop: register %s poller (%s, %s)\n", pollItem.getSocket() != null ? pollItem.getSocket().getType() : "RAW", pollItem.getSocket(), pollItem.getRawSocket()); } return 0; }
[ "public", "int", "addPoller", "(", "PollItem", "pollItem", ",", "IZLoopHandler", "handler", ",", "Object", "arg", ")", "{", "if", "(", "pollItem", ".", "getRawSocket", "(", ")", "==", "null", "&&", "pollItem", ".", "getSocket", "(", ")", "==", "null", ")...
corresponding handler.
[ "corresponding", "handler", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZLoop.java#L152-L170
train
zeromq/jeromq
src/main/java/org/zeromq/ZLoop.java
ZLoop.removeTimer
public int removeTimer(Object arg) { Objects.requireNonNull(arg, "Argument has to be supplied"); // We cannot touch self->timers because we may be executing that // from inside the poll loop. So, we hold the arg on the zombie // list, and process that list when we're done executing timers. zombies.add(arg); if (verbose) { System.out.printf("I: zloop: cancel timer\n"); } return 0; }
java
public int removeTimer(Object arg) { Objects.requireNonNull(arg, "Argument has to be supplied"); // We cannot touch self->timers because we may be executing that // from inside the poll loop. So, we hold the arg on the zombie // list, and process that list when we're done executing timers. zombies.add(arg); if (verbose) { System.out.printf("I: zloop: cancel timer\n"); } return 0; }
[ "public", "int", "removeTimer", "(", "Object", "arg", ")", "{", "Objects", ".", "requireNonNull", "(", "arg", ",", "\"Argument has to be supplied\"", ")", ";", "// We cannot touch self->timers because we may be executing that", "// from inside the poll loop. So, we hold the arg...
Returns 0 on success.
[ "Returns", "0", "on", "success", "." ]
8b4a2960b468d08b7aebb0d40bfb947e08fed040
https://github.com/zeromq/jeromq/blob/8b4a2960b468d08b7aebb0d40bfb947e08fed040/src/main/java/org/zeromq/ZLoop.java#L222-L235
train
SalomonBrys/ANR-WatchDog
anr-watchdog/src/main/java/com/github/anrwatchdog/ANRWatchDog.java
ANRWatchDog.setANRListener
public ANRWatchDog setANRListener(ANRListener listener) { if (listener == null) { _anrListener = DEFAULT_ANR_LISTENER; } else { _anrListener = listener; } return this; }
java
public ANRWatchDog setANRListener(ANRListener listener) { if (listener == null) { _anrListener = DEFAULT_ANR_LISTENER; } else { _anrListener = listener; } return this; }
[ "public", "ANRWatchDog", "setANRListener", "(", "ANRListener", "listener", ")", "{", "if", "(", "listener", "==", "null", ")", "{", "_anrListener", "=", "DEFAULT_ANR_LISTENER", ";", "}", "else", "{", "_anrListener", "=", "listener", ";", "}", "return", "this",...
Sets an interface for when an ANR is detected. If not set, the default behavior is to throw an error and crash the application. @param listener The new listener or null @return itself for chaining.
[ "Sets", "an", "interface", "for", "when", "an", "ANR", "is", "detected", ".", "If", "not", "set", "the", "default", "behavior", "is", "to", "throw", "an", "error", "and", "crash", "the", "application", "." ]
1969075f75f5980e9000eaffbaa13b0daf282dcb
https://github.com/SalomonBrys/ANR-WatchDog/blob/1969075f75f5980e9000eaffbaa13b0daf282dcb/anr-watchdog/src/main/java/com/github/anrwatchdog/ANRWatchDog.java#L133-L140
train
SalomonBrys/ANR-WatchDog
anr-watchdog/src/main/java/com/github/anrwatchdog/ANRWatchDog.java
ANRWatchDog.setANRInterceptor
public ANRWatchDog setANRInterceptor(ANRInterceptor interceptor) { if (interceptor == null) { _anrInterceptor = DEFAULT_ANR_INTERCEPTOR; } else { _anrInterceptor = interceptor; } return this; }
java
public ANRWatchDog setANRInterceptor(ANRInterceptor interceptor) { if (interceptor == null) { _anrInterceptor = DEFAULT_ANR_INTERCEPTOR; } else { _anrInterceptor = interceptor; } return this; }
[ "public", "ANRWatchDog", "setANRInterceptor", "(", "ANRInterceptor", "interceptor", ")", "{", "if", "(", "interceptor", "==", "null", ")", "{", "_anrInterceptor", "=", "DEFAULT_ANR_INTERCEPTOR", ";", "}", "else", "{", "_anrInterceptor", "=", "interceptor", ";", "}...
Sets an interface to intercept ANRs before they are reported. If set, you can define if, given the current duration of the detected ANR and external context, it is necessary to report the ANR. @param interceptor The new interceptor or null @return itself for chaining.
[ "Sets", "an", "interface", "to", "intercept", "ANRs", "before", "they", "are", "reported", ".", "If", "set", "you", "can", "define", "if", "given", "the", "current", "duration", "of", "the", "detected", "ANR", "and", "external", "context", "it", "is", "nec...
1969075f75f5980e9000eaffbaa13b0daf282dcb
https://github.com/SalomonBrys/ANR-WatchDog/blob/1969075f75f5980e9000eaffbaa13b0daf282dcb/anr-watchdog/src/main/java/com/github/anrwatchdog/ANRWatchDog.java#L149-L156
train
SalomonBrys/ANR-WatchDog
anr-watchdog/src/main/java/com/github/anrwatchdog/ANRWatchDog.java
ANRWatchDog.setInterruptionListener
public ANRWatchDog setInterruptionListener(InterruptionListener listener) { if (listener == null) { _interruptionListener = DEFAULT_INTERRUPTION_LISTENER; } else { _interruptionListener = listener; } return this; }
java
public ANRWatchDog setInterruptionListener(InterruptionListener listener) { if (listener == null) { _interruptionListener = DEFAULT_INTERRUPTION_LISTENER; } else { _interruptionListener = listener; } return this; }
[ "public", "ANRWatchDog", "setInterruptionListener", "(", "InterruptionListener", "listener", ")", "{", "if", "(", "listener", "==", "null", ")", "{", "_interruptionListener", "=", "DEFAULT_INTERRUPTION_LISTENER", ";", "}", "else", "{", "_interruptionListener", "=", "l...
Sets an interface for when the watchdog thread is interrupted. If not set, the default behavior is to just log the interruption message. @param listener The new listener or null. @return itself for chaining.
[ "Sets", "an", "interface", "for", "when", "the", "watchdog", "thread", "is", "interrupted", ".", "If", "not", "set", "the", "default", "behavior", "is", "to", "just", "log", "the", "interruption", "message", "." ]
1969075f75f5980e9000eaffbaa13b0daf282dcb
https://github.com/SalomonBrys/ANR-WatchDog/blob/1969075f75f5980e9000eaffbaa13b0daf282dcb/anr-watchdog/src/main/java/com/github/anrwatchdog/ANRWatchDog.java#L165-L172
train
vojtechhabarta/typescript-generator
typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/ModelCompiler.java
ModelCompiler.processTypeForDescendantLookup
private static Type processTypeForDescendantLookup(Type type) { if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getRawType(); } else { return type; } }
java
private static Type processTypeForDescendantLookup(Type type) { if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getRawType(); } else { return type; } }
[ "private", "static", "Type", "processTypeForDescendantLookup", "(", "Type", "type", ")", "{", "if", "(", "type", "instanceof", "ParameterizedType", ")", "{", "return", "(", "(", "ParameterizedType", ")", "type", ")", ".", "getRawType", "(", ")", ";", "}", "e...
Given a type, returns the type that should be used for the purpose of looking up implementations of that type.
[ "Given", "a", "type", "returns", "the", "type", "that", "should", "be", "used", "for", "the", "purpose", "of", "looking", "up", "implementations", "of", "that", "type", "." ]
23a43848f075360eefb15c5e233cfd71205b3e9f
https://github.com/vojtechhabarta/typescript-generator/blob/23a43848f075360eefb15c5e233cfd71205b3e9f/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/compiler/ModelCompiler.java#L287-L293
train
vojtechhabarta/typescript-generator
typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Utils.java
Utils.generateStream
private static <T> Stream<T> generateStream(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) { final Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(new Iterator<T>() { private T last = seed; @Override public boolean hasNext() { return hasNext.test(last); } @Override public T next() { final T current = last; last = next.apply(last); return current; } }, Spliterator.ORDERED); return StreamSupport.stream(spliterator, false); }
java
private static <T> Stream<T> generateStream(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) { final Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(new Iterator<T>() { private T last = seed; @Override public boolean hasNext() { return hasNext.test(last); } @Override public T next() { final T current = last; last = next.apply(last); return current; } }, Spliterator.ORDERED); return StreamSupport.stream(spliterator, false); }
[ "private", "static", "<", "T", ">", "Stream", "<", "T", ">", "generateStream", "(", "T", "seed", ",", "Predicate", "<", "?", "super", "T", ">", "hasNext", ",", "UnaryOperator", "<", "T", ">", "next", ")", "{", "final", "Spliterator", "<", "T", ">", ...
remove on Java 9 and replace with Stream.iterate
[ "remove", "on", "Java", "9", "and", "replace", "with", "Stream", ".", "iterate" ]
23a43848f075360eefb15c5e233cfd71205b3e9f
https://github.com/vojtechhabarta/typescript-generator/blob/23a43848f075360eefb15c5e233cfd71205b3e9f/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/util/Utils.java#L125-L143
train
vojtechhabarta/typescript-generator
typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtension.java
BeanPropertyPathExtension.writeBeanAndParentsFieldSpecs
private static Set<TsBeanModel> writeBeanAndParentsFieldSpecs( Writer writer, Settings settings, TsModel model, Set<TsBeanModel> emittedSoFar, TsBeanModel bean) { if (emittedSoFar.contains(bean)) { return new HashSet<>(); } final TsBeanModel parentBean = getBeanModelByType(model, bean.getParent()); final Set<TsBeanModel> emittedBeans = parentBean != null ? writeBeanAndParentsFieldSpecs(writer, settings, model, emittedSoFar, parentBean) : new HashSet<TsBeanModel>(); final String parentClassName = parentBean != null ? getBeanModelClassName(parentBean) + "Fields" : "Fields"; writer.writeIndentedLine(""); writer.writeIndentedLine( "class " + getBeanModelClassName(bean) + "Fields extends " + parentClassName + " {"); writer.writeIndentedLine( settings.indentString + "constructor(parent?: Fields, name?: string) { super(parent, name); }"); for (TsPropertyModel property : bean.getProperties()) { writeBeanProperty(writer, settings, model, bean, property); } writer.writeIndentedLine("}"); emittedBeans.add(bean); return emittedBeans; }
java
private static Set<TsBeanModel> writeBeanAndParentsFieldSpecs( Writer writer, Settings settings, TsModel model, Set<TsBeanModel> emittedSoFar, TsBeanModel bean) { if (emittedSoFar.contains(bean)) { return new HashSet<>(); } final TsBeanModel parentBean = getBeanModelByType(model, bean.getParent()); final Set<TsBeanModel> emittedBeans = parentBean != null ? writeBeanAndParentsFieldSpecs(writer, settings, model, emittedSoFar, parentBean) : new HashSet<TsBeanModel>(); final String parentClassName = parentBean != null ? getBeanModelClassName(parentBean) + "Fields" : "Fields"; writer.writeIndentedLine(""); writer.writeIndentedLine( "class " + getBeanModelClassName(bean) + "Fields extends " + parentClassName + " {"); writer.writeIndentedLine( settings.indentString + "constructor(parent?: Fields, name?: string) { super(parent, name); }"); for (TsPropertyModel property : bean.getProperties()) { writeBeanProperty(writer, settings, model, bean, property); } writer.writeIndentedLine("}"); emittedBeans.add(bean); return emittedBeans; }
[ "private", "static", "Set", "<", "TsBeanModel", ">", "writeBeanAndParentsFieldSpecs", "(", "Writer", "writer", ",", "Settings", "settings", ",", "TsModel", "model", ",", "Set", "<", "TsBeanModel", ">", "emittedSoFar", ",", "TsBeanModel", "bean", ")", "{", "if", ...
Emits a bean and its parent beans before if needed. Returns the list of beans that were emitted.
[ "Emits", "a", "bean", "and", "its", "parent", "beans", "before", "if", "needed", ".", "Returns", "the", "list", "of", "beans", "that", "were", "emitted", "." ]
23a43848f075360eefb15c5e233cfd71205b3e9f
https://github.com/vojtechhabarta/typescript-generator/blob/23a43848f075360eefb15c5e233cfd71205b3e9f/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtension.java#L74-L98
train
vojtechhabarta/typescript-generator
typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtension.java
BeanPropertyPathExtension.isOriginalTsType
private static boolean isOriginalTsType(TsType type) { if (type instanceof TsType.BasicType) { TsType.BasicType basicType = (TsType.BasicType)type; return !(basicType.name.equals("null") || basicType.name.equals("undefined")); } return true; }
java
private static boolean isOriginalTsType(TsType type) { if (type instanceof TsType.BasicType) { TsType.BasicType basicType = (TsType.BasicType)type; return !(basicType.name.equals("null") || basicType.name.equals("undefined")); } return true; }
[ "private", "static", "boolean", "isOriginalTsType", "(", "TsType", "type", ")", "{", "if", "(", "type", "instanceof", "TsType", ".", "BasicType", ")", "{", "TsType", ".", "BasicType", "basicType", "=", "(", "TsType", ".", "BasicType", ")", "type", ";", "re...
is this type an 'original' TS type, or a contextual information? null, undefined and optional info are not original types, everything else is original
[ "is", "this", "type", "an", "original", "TS", "type", "or", "a", "contextual", "information?", "null", "undefined", "and", "optional", "info", "are", "not", "original", "types", "everything", "else", "is", "original" ]
23a43848f075360eefb15c5e233cfd71205b3e9f
https://github.com/vojtechhabarta/typescript-generator/blob/23a43848f075360eefb15c5e233cfd71205b3e9f/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtension.java#L105-L111
train
vojtechhabarta/typescript-generator
typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtension.java
BeanPropertyPathExtension.extractOriginalTsType
private static TsType extractOriginalTsType(TsType type) { if (type instanceof TsType.OptionalType) { return extractOriginalTsType(((TsType.OptionalType)type).type); } if (type instanceof TsType.UnionType) { TsType.UnionType union = (TsType.UnionType)type; List<TsType> originalTypes = new ArrayList<>(); for (TsType curType : union.types) { if (isOriginalTsType(curType)) { originalTypes.add(curType); } } return originalTypes.size() == 1 ? extractOriginalTsType(originalTypes.get(0)) : type; } if (type instanceof TsType.BasicArrayType) { return extractOriginalTsType(((TsType.BasicArrayType)type).elementType); } return type; }
java
private static TsType extractOriginalTsType(TsType type) { if (type instanceof TsType.OptionalType) { return extractOriginalTsType(((TsType.OptionalType)type).type); } if (type instanceof TsType.UnionType) { TsType.UnionType union = (TsType.UnionType)type; List<TsType> originalTypes = new ArrayList<>(); for (TsType curType : union.types) { if (isOriginalTsType(curType)) { originalTypes.add(curType); } } return originalTypes.size() == 1 ? extractOriginalTsType(originalTypes.get(0)) : type; } if (type instanceof TsType.BasicArrayType) { return extractOriginalTsType(((TsType.BasicArrayType)type).elementType); } return type; }
[ "private", "static", "TsType", "extractOriginalTsType", "(", "TsType", "type", ")", "{", "if", "(", "type", "instanceof", "TsType", ".", "OptionalType", ")", "{", "return", "extractOriginalTsType", "(", "(", "(", "TsType", ".", "OptionalType", ")", "type", ")"...
If the type is optional of number|null|undefined, or list of of integer, we want to be able to recognize it as number to link the member to another class. => extract the original type while ignoring the |null|undefined and optional informations.
[ "If", "the", "type", "is", "optional", "of", "number|null|undefined", "or", "list", "of", "of", "integer", "we", "want", "to", "be", "able", "to", "recognize", "it", "as", "number", "to", "link", "the", "member", "to", "another", "class", ".", "=", ">", ...
23a43848f075360eefb15c5e233cfd71205b3e9f
https://github.com/vojtechhabarta/typescript-generator/blob/23a43848f075360eefb15c5e233cfd71205b3e9f/typescript-generator-core/src/main/java/cz/habarta/typescript/generator/ext/BeanPropertyPathExtension.java#L120-L140
train
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/NNChain.java
NNChain.findUnlinked
public static int findUnlinked(int pos, int end, DBIDArrayIter ix, PointerHierarchyRepresentationBuilder builder) { while(pos < end) { if(!builder.isLinked(ix.seek(pos))) { return pos; } ++pos; } return -1; }
java
public static int findUnlinked(int pos, int end, DBIDArrayIter ix, PointerHierarchyRepresentationBuilder builder) { while(pos < end) { if(!builder.isLinked(ix.seek(pos))) { return pos; } ++pos; } return -1; }
[ "public", "static", "int", "findUnlinked", "(", "int", "pos", ",", "int", "end", ",", "DBIDArrayIter", "ix", ",", "PointerHierarchyRepresentationBuilder", "builder", ")", "{", "while", "(", "pos", "<", "end", ")", "{", "if", "(", "!", "builder", ".", "isLi...
Find an unlinked object. @param pos Starting position @param end End position @param ix Iterator to translate into DBIDs @param builder Linkage information @return Position
[ "Find", "an", "unlinked", "object", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/NNChain.java#L199-L207
train
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/result/KMLOutputHandler.java
KMLOutputHandler.buildHullsRecursively
private DoubleObjPair<Polygon> buildHullsRecursively(Cluster<Model> clu, Hierarchy<Cluster<Model>> hier, Map<Object, DoubleObjPair<Polygon>> hulls, Relation<? extends NumberVector> coords) { final DBIDs ids = clu.getIDs(); FilteredConvexHull2D hull = new FilteredConvexHull2D(); for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { hull.add(coords.get(iter).toArray()); } double weight = ids.size(); if(hier != null) { final int numc = hier.numChildren(clu); if(numc > 0) { for(It<Cluster<Model>> iter = hier.iterChildren(clu); iter.valid(); iter.advance()) { final Cluster<Model> iclu = iter.get(); DoubleObjPair<Polygon> poly = hulls.get(iclu); if(poly == null) { poly = buildHullsRecursively(iclu, hier, hulls, coords); } // Add inner convex hull to outer convex hull. for(ArrayListIter<double[]> vi = poly.second.iter(); vi.valid(); vi.advance()) { hull.add(vi.get()); } weight += poly.first / numc; } } } DoubleObjPair<Polygon> pair = new DoubleObjPair<>(weight, hull.getHull()); hulls.put(clu, pair); return pair; }
java
private DoubleObjPair<Polygon> buildHullsRecursively(Cluster<Model> clu, Hierarchy<Cluster<Model>> hier, Map<Object, DoubleObjPair<Polygon>> hulls, Relation<? extends NumberVector> coords) { final DBIDs ids = clu.getIDs(); FilteredConvexHull2D hull = new FilteredConvexHull2D(); for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { hull.add(coords.get(iter).toArray()); } double weight = ids.size(); if(hier != null) { final int numc = hier.numChildren(clu); if(numc > 0) { for(It<Cluster<Model>> iter = hier.iterChildren(clu); iter.valid(); iter.advance()) { final Cluster<Model> iclu = iter.get(); DoubleObjPair<Polygon> poly = hulls.get(iclu); if(poly == null) { poly = buildHullsRecursively(iclu, hier, hulls, coords); } // Add inner convex hull to outer convex hull. for(ArrayListIter<double[]> vi = poly.second.iter(); vi.valid(); vi.advance()) { hull.add(vi.get()); } weight += poly.first / numc; } } } DoubleObjPair<Polygon> pair = new DoubleObjPair<>(weight, hull.getHull()); hulls.put(clu, pair); return pair; }
[ "private", "DoubleObjPair", "<", "Polygon", ">", "buildHullsRecursively", "(", "Cluster", "<", "Model", ">", "clu", ",", "Hierarchy", "<", "Cluster", "<", "Model", ">", ">", "hier", ",", "Map", "<", "Object", ",", "DoubleObjPair", "<", "Polygon", ">", ">",...
Recursively step through the clusters to build the hulls. @param clu Current cluster @param hier Clustering hierarchy @param hulls Hull map
[ "Recursively", "step", "through", "the", "clusters", "to", "build", "the", "hulls", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/result/KMLOutputHandler.java#L514-L542
train
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/result/KMLOutputHandler.java
KMLOutputHandler.getColorForValue
public static final Color getColorForValue(double val) { // Color positions double[] pos = new double[] { 0.0, 0.6, 0.8, 1.0 }; // Colors at these positions Color[] cols = new Color[] { new Color(0.0f, 0.0f, 0.0f, 0.6f), new Color(0.0f, 0.0f, 1.0f, 0.8f), new Color(1.0f, 0.0f, 0.0f, 0.9f), new Color(1.0f, 1.0f, 0.0f, 1.0f) }; assert (pos.length == cols.length); if(val < pos[0]) { val = pos[0]; } // Linear interpolation: for(int i = 1; i < pos.length; i++) { if(val <= pos[i]) { Color prev = cols[i - 1]; Color next = cols[i]; final double mix = (val - pos[i - 1]) / (pos[i] - pos[i - 1]); final int r = (int) ((1 - mix) * prev.getRed() + mix * next.getRed()); final int g = (int) ((1 - mix) * prev.getGreen() + mix * next.getGreen()); final int b = (int) ((1 - mix) * prev.getBlue() + mix * next.getBlue()); final int a = (int) ((1 - mix) * prev.getAlpha() + mix * next.getAlpha()); Color col = new Color(r, g, b, a); return col; } } return cols[cols.length - 1]; }
java
public static final Color getColorForValue(double val) { // Color positions double[] pos = new double[] { 0.0, 0.6, 0.8, 1.0 }; // Colors at these positions Color[] cols = new Color[] { new Color(0.0f, 0.0f, 0.0f, 0.6f), new Color(0.0f, 0.0f, 1.0f, 0.8f), new Color(1.0f, 0.0f, 0.0f, 0.9f), new Color(1.0f, 1.0f, 0.0f, 1.0f) }; assert (pos.length == cols.length); if(val < pos[0]) { val = pos[0]; } // Linear interpolation: for(int i = 1; i < pos.length; i++) { if(val <= pos[i]) { Color prev = cols[i - 1]; Color next = cols[i]; final double mix = (val - pos[i - 1]) / (pos[i] - pos[i - 1]); final int r = (int) ((1 - mix) * prev.getRed() + mix * next.getRed()); final int g = (int) ((1 - mix) * prev.getGreen() + mix * next.getGreen()); final int b = (int) ((1 - mix) * prev.getBlue() + mix * next.getBlue()); final int a = (int) ((1 - mix) * prev.getAlpha() + mix * next.getAlpha()); Color col = new Color(r, g, b, a); return col; } } return cols[cols.length - 1]; }
[ "public", "static", "final", "Color", "getColorForValue", "(", "double", "val", ")", "{", "// Color positions", "double", "[", "]", "pos", "=", "new", "double", "[", "]", "{", "0.0", ",", "0.6", ",", "0.8", ",", "1.0", "}", ";", "// Colors at these positio...
Get color from a simple heatmap. @param val Score value @return Color in heatmap
[ "Get", "color", "from", "a", "simple", "heatmap", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/result/KMLOutputHandler.java#L602-L626
train
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/savedialog/SVGSaveDialog.java
SVGSaveDialog.showSaveDialog
public static int showSaveDialog(SVGPlot plot, int width, int height) { JFileChooser fc = new JFileChooser(new File(".")); fc.setDialogTitle(DEFAULT_TITLE); // fc.setFileFilter(new ImageFilter()); SaveOptionsPanel optionsPanel = new SaveOptionsPanel(fc, width, height); fc.setAccessory(optionsPanel); int ret = fc.showSaveDialog(null); if(ret == JFileChooser.APPROVE_OPTION) { fc.setDialogTitle("Saving... Please wait."); File file = fc.getSelectedFile(); String format = optionsPanel.getSelectedFormat(); width = optionsPanel.getSelectedWidth(); height = optionsPanel.getSelectedHeight(); if(format == null || AUTOMAGIC_FORMAT.equals(format)) { format = guessFormat(file.getName()); } try { if(format == null) { showError(fc, "Error saving image.", "File format not recognized."); } else if("jpeg".equals(format) || "jpg".equals(format)) { float quality = optionsPanel.getJPEGQuality(); plot.saveAsJPEG(file, width, height, quality); } else if("png".equals(format)) { plot.saveAsPNG(file, width, height); } else if("ps".equals(format)) { plot.saveAsPS(file); } else if("eps".equals(format)) { plot.saveAsEPS(file); } else if("pdf".equals(format)) { plot.saveAsPDF(file); } else if("svg".equals(format)) { plot.saveAsSVG(file); } else { showError(fc, "Error saving image.", "Unsupported format: " + format); } } catch(java.lang.IncompatibleClassChangeError e) { showError(fc, "Error saving image.", "It seems that your Java version is incompatible with this version of Batik and Jpeg writing. Sorry."); } catch(ClassNotFoundException e) { showError(fc, "Error saving image.", "A class was not found when saving this image. Maybe installing Apache FOP will help (for PDF, PS and EPS output).\n" + e.toString()); } catch(TransformerFactoryConfigurationError | Exception e) { LOG.exception(e); showError(fc, "Error saving image.", e.toString()); } } else if(ret == JFileChooser.ERROR_OPTION) { showError(fc, "Error in file dialog.", "Unknown Error."); } else if(ret == JFileChooser.CANCEL_OPTION) { // do nothing - except return result } return ret; }
java
public static int showSaveDialog(SVGPlot plot, int width, int height) { JFileChooser fc = new JFileChooser(new File(".")); fc.setDialogTitle(DEFAULT_TITLE); // fc.setFileFilter(new ImageFilter()); SaveOptionsPanel optionsPanel = new SaveOptionsPanel(fc, width, height); fc.setAccessory(optionsPanel); int ret = fc.showSaveDialog(null); if(ret == JFileChooser.APPROVE_OPTION) { fc.setDialogTitle("Saving... Please wait."); File file = fc.getSelectedFile(); String format = optionsPanel.getSelectedFormat(); width = optionsPanel.getSelectedWidth(); height = optionsPanel.getSelectedHeight(); if(format == null || AUTOMAGIC_FORMAT.equals(format)) { format = guessFormat(file.getName()); } try { if(format == null) { showError(fc, "Error saving image.", "File format not recognized."); } else if("jpeg".equals(format) || "jpg".equals(format)) { float quality = optionsPanel.getJPEGQuality(); plot.saveAsJPEG(file, width, height, quality); } else if("png".equals(format)) { plot.saveAsPNG(file, width, height); } else if("ps".equals(format)) { plot.saveAsPS(file); } else if("eps".equals(format)) { plot.saveAsEPS(file); } else if("pdf".equals(format)) { plot.saveAsPDF(file); } else if("svg".equals(format)) { plot.saveAsSVG(file); } else { showError(fc, "Error saving image.", "Unsupported format: " + format); } } catch(java.lang.IncompatibleClassChangeError e) { showError(fc, "Error saving image.", "It seems that your Java version is incompatible with this version of Batik and Jpeg writing. Sorry."); } catch(ClassNotFoundException e) { showError(fc, "Error saving image.", "A class was not found when saving this image. Maybe installing Apache FOP will help (for PDF, PS and EPS output).\n" + e.toString()); } catch(TransformerFactoryConfigurationError | Exception e) { LOG.exception(e); showError(fc, "Error saving image.", e.toString()); } } else if(ret == JFileChooser.ERROR_OPTION) { showError(fc, "Error in file dialog.", "Unknown Error."); } else if(ret == JFileChooser.CANCEL_OPTION) { // do nothing - except return result } return ret; }
[ "public", "static", "int", "showSaveDialog", "(", "SVGPlot", "plot", ",", "int", "width", ",", "int", "height", ")", "{", "JFileChooser", "fc", "=", "new", "JFileChooser", "(", "new", "File", "(", "\".\"", ")", ")", ";", "fc", ".", "setDialogTitle", "(",...
Show a "Save as" dialog. @param plot The plot to be exported. @param width The width of the exported image (when export to JPEG/PNG). @param height The height of the exported image (when export to JPEG/PNG). @return Result from {@link JFileChooser#showSaveDialog}
[ "Show", "a", "Save", "as", "dialog", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/savedialog/SVGSaveDialog.java#L119-L181
train
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/savedialog/SVGSaveDialog.java
SVGSaveDialog.guessFormat
public static String guessFormat(String name) { String ext = FileUtil.getFilenameExtension(name); for(String format : FORMATS) { if(format.equalsIgnoreCase(ext)) { return ext; } } return null; }
java
public static String guessFormat(String name) { String ext = FileUtil.getFilenameExtension(name); for(String format : FORMATS) { if(format.equalsIgnoreCase(ext)) { return ext; } } return null; }
[ "public", "static", "String", "guessFormat", "(", "String", "name", ")", "{", "String", "ext", "=", "FileUtil", ".", "getFilenameExtension", "(", "name", ")", ";", "for", "(", "String", "format", ":", "FORMATS", ")", "{", "if", "(", "format", ".", "equal...
Guess a supported format from the file name. For "auto" format handling. @param name File name @return format or "null"
[ "Guess", "a", "supported", "format", "from", "the", "file", "name", ".", "For", "auto", "format", "handling", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/savedialog/SVGSaveDialog.java#L189-L197
train
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/ArrayLikeUtil.java
ArrayLikeUtil.featureVectorAdapter
@SuppressWarnings("unchecked") public static <F> FeatureVectorAdapter<F> featureVectorAdapter(FeatureVector<F> prototype) { return (FeatureVectorAdapter<F>) FEATUREVECTORADAPTER; }
java
@SuppressWarnings("unchecked") public static <F> FeatureVectorAdapter<F> featureVectorAdapter(FeatureVector<F> prototype) { return (FeatureVectorAdapter<F>) FEATUREVECTORADAPTER; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "F", ">", "FeatureVectorAdapter", "<", "F", ">", "featureVectorAdapter", "(", "FeatureVector", "<", "F", ">", "prototype", ")", "{", "return", "(", "FeatureVectorAdapter", "<", "F", "...
Get the static instance. @param prototype Prototype value, for type inference @return Instance
[ "Get", "the", "static", "instance", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/ArrayLikeUtil.java#L105-L108
train
elki-project/elki
elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/ArrayLikeUtil.java
ArrayLikeUtil.getIndexOfMaximum
public static <A> int getIndexOfMaximum(A array, NumberArrayAdapter<?, A> adapter) throws IndexOutOfBoundsException { final int size = adapter.size(array); int index = 0; double max = adapter.getDouble(array, 0); for (int i = 1; i < size; i++) { double val = adapter.getDouble(array, i); if (val > max) { max = val; index = i; } } return index; }
java
public static <A> int getIndexOfMaximum(A array, NumberArrayAdapter<?, A> adapter) throws IndexOutOfBoundsException { final int size = adapter.size(array); int index = 0; double max = adapter.getDouble(array, 0); for (int i = 1; i < size; i++) { double val = adapter.getDouble(array, i); if (val > max) { max = val; index = i; } } return index; }
[ "public", "static", "<", "A", ">", "int", "getIndexOfMaximum", "(", "A", "array", ",", "NumberArrayAdapter", "<", "?", ",", "A", ">", "adapter", ")", "throws", "IndexOutOfBoundsException", "{", "final", "int", "size", "=", "adapter", ".", "size", "(", "arr...
Returns the index of the maximum of the given values. If no value is bigger than the first, the index of the first entry is returned. @param <A> array type @param array Array to inspect @param adapter API adapter class @return the index of the maximum in the given values @throws IndexOutOfBoundsException if the length of the array is 0.
[ "Returns", "the", "index", "of", "the", "maximum", "of", "the", "given", "values", ".", "If", "no", "value", "is", "bigger", "than", "the", "first", "the", "index", "of", "the", "first", "entry", "is", "returned", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/arraylike/ArrayLikeUtil.java#L120-L132
train
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/spacefillingcurves/ZCurveTransformer.java
ZCurveTransformer.asByteArray
public byte[] asByteArray(NumberVector vector) { final long[] longValueList = new long[dimensionality]; for(int dim = 0; dim < dimensionality; ++dim) { final double minValue = minValues[dim]; final double maxValue = maxValues[dim]; double dimValue = vector.doubleValue(dim); dimValue = (dimValue - minValue) / (maxValue - minValue); longValueList[dim] = (long) (dimValue * (Long.MAX_VALUE)); } final byte[] bytes = new byte[Long.SIZE * dimensionality * (Long.SIZE / Byte.SIZE)]; int shiftCounter = 0; for(int i = 0; i < Long.SIZE; ++i) { for(int dim = 0; dim < dimensionality; ++dim) { long byteValue = longValueList[dim]; int localShift = shiftCounter % Byte.SIZE; bytes[(bytes.length - 1) - (shiftCounter / Byte.SIZE)] |= ((byteValue >> i) & 0x01) << localShift; shiftCounter++; } } return bytes; }
java
public byte[] asByteArray(NumberVector vector) { final long[] longValueList = new long[dimensionality]; for(int dim = 0; dim < dimensionality; ++dim) { final double minValue = minValues[dim]; final double maxValue = maxValues[dim]; double dimValue = vector.doubleValue(dim); dimValue = (dimValue - minValue) / (maxValue - minValue); longValueList[dim] = (long) (dimValue * (Long.MAX_VALUE)); } final byte[] bytes = new byte[Long.SIZE * dimensionality * (Long.SIZE / Byte.SIZE)]; int shiftCounter = 0; for(int i = 0; i < Long.SIZE; ++i) { for(int dim = 0; dim < dimensionality; ++dim) { long byteValue = longValueList[dim]; int localShift = shiftCounter % Byte.SIZE; bytes[(bytes.length - 1) - (shiftCounter / Byte.SIZE)] |= ((byteValue >> i) & 0x01) << localShift; shiftCounter++; } } return bytes; }
[ "public", "byte", "[", "]", "asByteArray", "(", "NumberVector", "vector", ")", "{", "final", "long", "[", "]", "longValueList", "=", "new", "long", "[", "dimensionality", "]", ";", "for", "(", "int", "dim", "=", "0", ";", "dim", "<", "dimensionality", ...
Transform a single vector. @param vector Vector to transform @return Z curve value as byte array
[ "Transform", "a", "single", "vector", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/spacefillingcurves/ZCurveTransformer.java#L83-L108
train
elki-project/elki
elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/SOD.java
SOD.run
public OutlierResult run(Relation<V> relation) { SimilarityQuery<V> snnInstance = similarityFunction.instantiate(relation); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Assigning Subspace Outlier Degree", relation.size(), LOG) : null; WritableDoubleDataStore sod_scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_STATIC); WritableDataStore<SODModel> sod_models = models ? DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_STATIC, SODModel.class) : null; DoubleMinMax minmax = new DoubleMinMax(); for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { DBIDs neighborhood = getNearestNeighbors(relation, snnInstance, iter); double[] center; long[] weightVector = null; double sod = 0.; if(neighborhood.size() > 0) { center = Centroid.make(relation, neighborhood).getArrayRef(); // Note: per-dimension variances; no covariances. double[] variances = computePerDimensionVariances(relation, center, neighborhood); double expectationOfVariance = Mean.of(variances); weightVector = BitsUtil.zero(variances.length); for(int d = 0; d < variances.length; d++) { if(variances[d] < alpha * expectationOfVariance) { BitsUtil.setI(weightVector, d); } } sod = subspaceOutlierDegree(relation.get(iter), center, weightVector); } else { center = relation.get(iter).toArray(); } if(sod_models != null) { sod_models.put(iter, new SODModel(center, weightVector)); } sod_scores.putDouble(iter, sod); minmax.put(sod); LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); // combine results. OutlierScoreMeta meta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax()); OutlierResult sodResult = new OutlierResult(meta, new MaterializedDoubleRelation("Subspace Outlier Degree", "sod-outlier", sod_scores, relation.getDBIDs())); if(sod_models != null) { sodResult.addChildResult(new MaterializedRelation<>("Subspace Outlier Model", "sod-outlier", new SimpleTypeInformation<>(SODModel.class), sod_models, relation.getDBIDs())); } return sodResult; }
java
public OutlierResult run(Relation<V> relation) { SimilarityQuery<V> snnInstance = similarityFunction.instantiate(relation); FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("Assigning Subspace Outlier Degree", relation.size(), LOG) : null; WritableDoubleDataStore sod_scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_STATIC); WritableDataStore<SODModel> sod_models = models ? DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_STATIC, SODModel.class) : null; DoubleMinMax minmax = new DoubleMinMax(); for(DBIDIter iter = relation.iterDBIDs(); iter.valid(); iter.advance()) { DBIDs neighborhood = getNearestNeighbors(relation, snnInstance, iter); double[] center; long[] weightVector = null; double sod = 0.; if(neighborhood.size() > 0) { center = Centroid.make(relation, neighborhood).getArrayRef(); // Note: per-dimension variances; no covariances. double[] variances = computePerDimensionVariances(relation, center, neighborhood); double expectationOfVariance = Mean.of(variances); weightVector = BitsUtil.zero(variances.length); for(int d = 0; d < variances.length; d++) { if(variances[d] < alpha * expectationOfVariance) { BitsUtil.setI(weightVector, d); } } sod = subspaceOutlierDegree(relation.get(iter), center, weightVector); } else { center = relation.get(iter).toArray(); } if(sod_models != null) { sod_models.put(iter, new SODModel(center, weightVector)); } sod_scores.putDouble(iter, sod); minmax.put(sod); LOG.incrementProcessed(progress); } LOG.ensureCompleted(progress); // combine results. OutlierScoreMeta meta = new BasicOutlierScoreMeta(minmax.getMin(), minmax.getMax()); OutlierResult sodResult = new OutlierResult(meta, new MaterializedDoubleRelation("Subspace Outlier Degree", "sod-outlier", sod_scores, relation.getDBIDs())); if(sod_models != null) { sodResult.addChildResult(new MaterializedRelation<>("Subspace Outlier Model", "sod-outlier", new SimpleTypeInformation<>(SODModel.class), sod_models, relation.getDBIDs())); } return sodResult; }
[ "public", "OutlierResult", "run", "(", "Relation", "<", "V", ">", "relation", ")", "{", "SimilarityQuery", "<", "V", ">", "snnInstance", "=", "similarityFunction", ".", "instantiate", "(", "relation", ")", ";", "FiniteProgress", "progress", "=", "LOG", ".", ...
Performs the SOD algorithm on the given database. @param relation Data relation to process @return Outlier result
[ "Performs", "the", "SOD", "algorithm", "on", "the", "given", "database", "." ]
b54673327e76198ecd4c8a2a901021f1a9174498
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/algorithm/outlier/subspace/SOD.java#L143-L187
train