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
sagiegurari/fax4j
src/main/java/org/fax4j/spi/comm/CommFaxClientSpi.java
CommFaxClientSpi.createFaxModemAdapter
protected final FaxModemAdapter createFaxModemAdapter() { //create new instance FaxModemAdapter adapter=(FaxModemAdapter)ReflectionHelper.createInstance(this.faxModemClassName); //initialize adapter.initialize(this); return adapter; }
java
protected final FaxModemAdapter createFaxModemAdapter() { //create new instance FaxModemAdapter adapter=(FaxModemAdapter)ReflectionHelper.createInstance(this.faxModemClassName); //initialize adapter.initialize(this); return adapter; }
[ "protected", "final", "FaxModemAdapter", "createFaxModemAdapter", "(", ")", "{", "//create new instance", "FaxModemAdapter", "adapter", "=", "(", "FaxModemAdapter", ")", "ReflectionHelper", ".", "createInstance", "(", "this", ".", "faxModemClassName", ")", ";", "//initi...
Creates and returns the fax modem adapter. @return The fax modem adapter
[ "Creates", "and", "returns", "the", "fax", "modem", "adapter", "." ]
42fa51acabe7bf279e27ab3dd1cf76146b27955f
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/comm/CommFaxClientSpi.java#L207-L216
train
sagiegurari/fax4j
src/main/java/org/fax4j/spi/comm/CommFaxClientSpi.java
CommFaxClientSpi.releaseCommPortConnection
protected void releaseCommPortConnection() { //get reference Connection<CommPortAdapter> connection=this.commConnection; this.commConnection=null; if(connection!=null) { //get logger Logger logger=this.getLogger(); try { //release connection logger.logInfo(new Object[]{"Closing COMM port connection."},null); connection.close(); } catch(Exception exception) { logger.logError(new Object[]{"Error while closing COMM port connection."},exception); } } }
java
protected void releaseCommPortConnection() { //get reference Connection<CommPortAdapter> connection=this.commConnection; this.commConnection=null; if(connection!=null) { //get logger Logger logger=this.getLogger(); try { //release connection logger.logInfo(new Object[]{"Closing COMM port connection."},null); connection.close(); } catch(Exception exception) { logger.logError(new Object[]{"Error while closing COMM port connection."},exception); } } }
[ "protected", "void", "releaseCommPortConnection", "(", ")", "{", "//get reference", "Connection", "<", "CommPortAdapter", ">", "connection", "=", "this", ".", "commConnection", ";", "this", ".", "commConnection", "=", "null", ";", "if", "(", "connection", "!=", ...
Releases the COMM port connection if open.
[ "Releases", "the", "COMM", "port", "connection", "if", "open", "." ]
42fa51acabe7bf279e27ab3dd1cf76146b27955f
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/comm/CommFaxClientSpi.java#L249-L271
train
sagiegurari/fax4j
src/main/java/org/fax4j/spi/comm/CommFaxClientSpi.java
CommFaxClientSpi.getCommPortConnection
protected Connection<CommPortAdapter> getCommPortConnection() { Connection<CommPortAdapter> connection=null; synchronized(this) { boolean connectionValid=true; //if no connection available if(this.commConnection==null) { connectionValid=false; } else { //get adapter CommPortAdapter adapter=this.commConnection.getResource(); //if current adapter is not valid/open if(!adapter.isOpen()) { connectionValid=false; } } if(!connectionValid) { //release old connection this.releaseCommPortConnection(); //create new connection this.commConnection=this.createCommPortConnection(); } } //get connection connection=this.commConnection; return connection; }
java
protected Connection<CommPortAdapter> getCommPortConnection() { Connection<CommPortAdapter> connection=null; synchronized(this) { boolean connectionValid=true; //if no connection available if(this.commConnection==null) { connectionValid=false; } else { //get adapter CommPortAdapter adapter=this.commConnection.getResource(); //if current adapter is not valid/open if(!adapter.isOpen()) { connectionValid=false; } } if(!connectionValid) { //release old connection this.releaseCommPortConnection(); //create new connection this.commConnection=this.createCommPortConnection(); } } //get connection connection=this.commConnection; return connection; }
[ "protected", "Connection", "<", "CommPortAdapter", ">", "getCommPortConnection", "(", ")", "{", "Connection", "<", "CommPortAdapter", ">", "connection", "=", "null", ";", "synchronized", "(", "this", ")", "{", "boolean", "connectionValid", "=", "true", ";", "//i...
Returns the COMM port connection to be used. @return The COMM port connection
[ "Returns", "the", "COMM", "port", "connection", "to", "be", "used", "." ]
42fa51acabe7bf279e27ab3dd1cf76146b27955f
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/comm/CommFaxClientSpi.java#L278-L315
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/EmbeddedJmxTrans.java
EmbeddedJmxTrans.stop
@PreDestroy public void stop() { logger.info("Stop..."); lifecycleLock.writeLock().lock(); try { if (!State.STARTED.equals(state)) { logger.debug("Ignore stop() command for " + state + " instance"); return; } logger.info("Unregister shutdown hook"); this.shutdownHook.unregisterFromRuntime(); logger.info("Shutdown collectScheduledExecutor and exportScheduledExecutor..."); // no need to `shutdown()` and `awaitTermination()` before `shutdownNow()` as we invoke `collectMetrics()` and `exportCollectedMetrics()` // `shutdownNow()` can be invoked before `collectMetrics()` and `exportCollectedMetrics()` collectScheduledExecutor.shutdownNow(); exportScheduledExecutor.shutdownNow(); try { logger.info("Collect metrics..."); collectMetrics(); logger.info("Export metrics..."); exportCollectedMetrics(); } catch (RuntimeException e) { logger.warn("Ignore failure collecting and exporting metrics during stop", e); } // queries and outputwriters can be stopped even if exports threads are running thanks to the lifecycleLock logger.info("Stop queries..."); for (Query query : queries) { try { query.stop(); } catch (Exception e) { logger.warn("Ignore exception stopping query {}", query, e); } } logger.info("Stop output writers..."); for (OutputWriter outputWriter : outputWriters) { try { outputWriter.stop(); } catch (Exception e) { logger.warn("Ignore exception stopping outputWriters", e); } } state = State.STOPPED; logger.info("Set state to {}", state); } catch (RuntimeException e) { state = State.ERROR; if (logger.isDebugEnabled()) { // to troubleshoot JMX call errors or equivalent, it may be useful to log and rethrow logger.warn("Exception stopping EmbeddedJmxTrans", e); } throw e; } finally { lifecycleLock.writeLock().unlock(); } logger.info("Stopped"); }
java
@PreDestroy public void stop() { logger.info("Stop..."); lifecycleLock.writeLock().lock(); try { if (!State.STARTED.equals(state)) { logger.debug("Ignore stop() command for " + state + " instance"); return; } logger.info("Unregister shutdown hook"); this.shutdownHook.unregisterFromRuntime(); logger.info("Shutdown collectScheduledExecutor and exportScheduledExecutor..."); // no need to `shutdown()` and `awaitTermination()` before `shutdownNow()` as we invoke `collectMetrics()` and `exportCollectedMetrics()` // `shutdownNow()` can be invoked before `collectMetrics()` and `exportCollectedMetrics()` collectScheduledExecutor.shutdownNow(); exportScheduledExecutor.shutdownNow(); try { logger.info("Collect metrics..."); collectMetrics(); logger.info("Export metrics..."); exportCollectedMetrics(); } catch (RuntimeException e) { logger.warn("Ignore failure collecting and exporting metrics during stop", e); } // queries and outputwriters can be stopped even if exports threads are running thanks to the lifecycleLock logger.info("Stop queries..."); for (Query query : queries) { try { query.stop(); } catch (Exception e) { logger.warn("Ignore exception stopping query {}", query, e); } } logger.info("Stop output writers..."); for (OutputWriter outputWriter : outputWriters) { try { outputWriter.stop(); } catch (Exception e) { logger.warn("Ignore exception stopping outputWriters", e); } } state = State.STOPPED; logger.info("Set state to {}", state); } catch (RuntimeException e) { state = State.ERROR; if (logger.isDebugEnabled()) { // to troubleshoot JMX call errors or equivalent, it may be useful to log and rethrow logger.warn("Exception stopping EmbeddedJmxTrans", e); } throw e; } finally { lifecycleLock.writeLock().unlock(); } logger.info("Stopped"); }
[ "@", "PreDestroy", "public", "void", "stop", "(", ")", "{", "logger", ".", "info", "(", "\"Stop...\"", ")", ";", "lifecycleLock", ".", "writeLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "if", "(", "!", "State", ".", "STARTED", ".", "equ...
Stop scheduled executors and collect-and-export metrics one last time.
[ "Stop", "scheduled", "executors", "and", "collect", "-", "and", "-", "export", "metrics", "one", "last", "time", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/EmbeddedJmxTrans.java#L257-L316
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/CsvWriter.java
CsvWriter.splitQueryResultsByTime
private SortedMap<String, List<QueryResult>> splitQueryResultsByTime(Iterable<QueryResult> results) { SortedMap<String, List<QueryResult>> resultsByTime = new TreeMap<String, List<QueryResult>>(); for (QueryResult result : results) { String epoch = String.valueOf(result.getEpoch(TimeUnit.SECONDS)); if (resultsByTime.containsKey(epoch)) { List<QueryResult> current = resultsByTime.get(epoch); current.add(result); resultsByTime.put(epoch, current); } else { ArrayList<QueryResult> newQueryList = new ArrayList<QueryResult>(); newQueryList.add(result); resultsByTime.put(epoch, newQueryList); } } return resultsByTime; }
java
private SortedMap<String, List<QueryResult>> splitQueryResultsByTime(Iterable<QueryResult> results) { SortedMap<String, List<QueryResult>> resultsByTime = new TreeMap<String, List<QueryResult>>(); for (QueryResult result : results) { String epoch = String.valueOf(result.getEpoch(TimeUnit.SECONDS)); if (resultsByTime.containsKey(epoch)) { List<QueryResult> current = resultsByTime.get(epoch); current.add(result); resultsByTime.put(epoch, current); } else { ArrayList<QueryResult> newQueryList = new ArrayList<QueryResult>(); newQueryList.add(result); resultsByTime.put(epoch, newQueryList); } } return resultsByTime; }
[ "private", "SortedMap", "<", "String", ",", "List", "<", "QueryResult", ">", ">", "splitQueryResultsByTime", "(", "Iterable", "<", "QueryResult", ">", "results", ")", "{", "SortedMap", "<", "String", ",", "List", "<", "QueryResult", ">", ">", "resultsByTime", ...
Often, query results for a given query come in batches so we need to split them up by time @param results from {@link CsvWriter#write(Iterable)} @return {@link Map} from epoch time in seconds --> results list from that time
[ "Often", "query", "results", "for", "a", "given", "query", "come", "in", "batches", "so", "we", "need", "to", "split", "them", "up", "by", "time" ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/CsvWriter.java#L160-L178
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/CsvWriter.java
CsvWriter.alignResults
List<Object> alignResults(List<QueryResult> results, String epoch) { Object[] alignedResults = new Object[results.size() + 1]; List<String> headerList = Arrays.asList(header); alignedResults[0] = epoch; for (QueryResult result : results) { alignedResults[headerList.indexOf(result.getName())] = result.getValue(); } return Arrays.asList(alignedResults); }
java
List<Object> alignResults(List<QueryResult> results, String epoch) { Object[] alignedResults = new Object[results.size() + 1]; List<String> headerList = Arrays.asList(header); alignedResults[0] = epoch; for (QueryResult result : results) { alignedResults[headerList.indexOf(result.getName())] = result.getValue(); } return Arrays.asList(alignedResults); }
[ "List", "<", "Object", ">", "alignResults", "(", "List", "<", "QueryResult", ">", "results", ",", "String", "epoch", ")", "{", "Object", "[", "]", "alignedResults", "=", "new", "Object", "[", "results", ".", "size", "(", ")", "+", "1", "]", ";", "Lis...
We have no guarantee that the results will always be in the same order, so we make sure to align them according to the header on each query.
[ "We", "have", "no", "guarantee", "that", "the", "results", "will", "always", "be", "in", "the", "same", "order", "so", "we", "make", "sure", "to", "align", "them", "according", "to", "the", "header", "on", "each", "query", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/CsvWriter.java#L200-L211
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/ResultNameStrategy.java
ResultNameStrategy.appendEscapedNonAlphaNumericChars
private void appendEscapedNonAlphaNumericChars(String str, boolean escapeDot, StringBuilder result) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; if (Character.isLetter(ch) || Character.isDigit(ch) || ch == '-') { result.append(ch); } else if (ch == '.') { result.append(escapeDot ? '_' : ch); } else if (ch == '"' && ((i == 0) || (i == chars.length - 1))) { // ignore starting and ending '"' that are used to quote() objectname's values (see ObjectName.value()) } else { result.append('_'); } } }
java
private void appendEscapedNonAlphaNumericChars(String str, boolean escapeDot, StringBuilder result) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; if (Character.isLetter(ch) || Character.isDigit(ch) || ch == '-') { result.append(ch); } else if (ch == '.') { result.append(escapeDot ? '_' : ch); } else if (ch == '"' && ((i == 0) || (i == chars.length - 1))) { // ignore starting and ending '"' that are used to quote() objectname's values (see ObjectName.value()) } else { result.append('_'); } } }
[ "private", "void", "appendEscapedNonAlphaNumericChars", "(", "String", "str", ",", "boolean", "escapeDot", ",", "StringBuilder", "result", ")", "{", "char", "[", "]", "chars", "=", "str", ".", "toCharArray", "(", ")", ";", "for", "(", "int", "i", "=", "0",...
Escape all non a-z,A-Z, 0-9 and '-' with a '_'. '.' is escaped with a '_' if {@code escapeDot} is {$code true}. @param str the string to escape @param escapeDot indicates whether '.' should be escaped into '_' or not. @param result the {@linkplain StringBuilder} in which the escaped string is appended
[ "Escape", "all", "non", "a", "-", "z", "A", "-", "Z", "0", "-", "9", "and", "-", "with", "a", "_", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/ResultNameStrategy.java#L292-L306
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/spring/EmbeddedJmxTransFactory.java
EmbeddedJmxTransFactory.computeConfigurationLastModified
private long computeConfigurationLastModified(List<Resource> configurations) { long result = 0; for (Resource configuration : configurations) { try { long currentConfigurationLastModified = configuration.lastModified(); if (currentConfigurationLastModified > result) { result = currentConfigurationLastModified; } } catch (IOException ioex) { logger.warn("Error while reading last configuration modification date.", ioex); } } return result; }
java
private long computeConfigurationLastModified(List<Resource> configurations) { long result = 0; for (Resource configuration : configurations) { try { long currentConfigurationLastModified = configuration.lastModified(); if (currentConfigurationLastModified > result) { result = currentConfigurationLastModified; } } catch (IOException ioex) { logger.warn("Error while reading last configuration modification date.", ioex); } } return result; }
[ "private", "long", "computeConfigurationLastModified", "(", "List", "<", "Resource", ">", "configurations", ")", "{", "long", "result", "=", "0", ";", "for", "(", "Resource", "configuration", ":", "configurations", ")", "{", "try", "{", "long", "currentConfigura...
Computes the last modified date of all configuration files. @param configurations the list of available configurations as Spring resources @return
[ "Computes", "the", "last", "modified", "date", "of", "all", "configuration", "files", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/spring/EmbeddedJmxTransFactory.java#L128-L141
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/spring/EmbeddedJmxTransFactory.java
EmbeddedJmxTransFactory.getConfigurations
private List<Resource> getConfigurations() { List<Resource> result = new ArrayList<Resource>(); for (String delimitedConfigurationUrl : configurationUrls) { String[] tokens = StringUtils.commaDelimitedListToStringArray(delimitedConfigurationUrl); tokens = StringUtils.trimArrayElements(tokens); for (String configurationUrl : tokens) { configurationUrl = configurationUrl.trim(); Resource configuration = resourceLoader.getResource(configurationUrl); if (configuration != null && configuration.exists()) { result.add(configuration); } else if (ignoreConfigurationNotFound) { logger.debug("Ignore missing configuration file {}", configuration); } else { throw new EmbeddedJmxTransException("Configuration file " + configuration + " not found"); } } } return result; }
java
private List<Resource> getConfigurations() { List<Resource> result = new ArrayList<Resource>(); for (String delimitedConfigurationUrl : configurationUrls) { String[] tokens = StringUtils.commaDelimitedListToStringArray(delimitedConfigurationUrl); tokens = StringUtils.trimArrayElements(tokens); for (String configurationUrl : tokens) { configurationUrl = configurationUrl.trim(); Resource configuration = resourceLoader.getResource(configurationUrl); if (configuration != null && configuration.exists()) { result.add(configuration); } else if (ignoreConfigurationNotFound) { logger.debug("Ignore missing configuration file {}", configuration); } else { throw new EmbeddedJmxTransException("Configuration file " + configuration + " not found"); } } } return result; }
[ "private", "List", "<", "Resource", ">", "getConfigurations", "(", ")", "{", "List", "<", "Resource", ">", "result", "=", "new", "ArrayList", "<", "Resource", ">", "(", ")", ";", "for", "(", "String", "delimitedConfigurationUrl", ":", "configurationUrls", ")...
Returns the list of all configuration spring resources. @return
[ "Returns", "the", "list", "of", "all", "configuration", "spring", "resources", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/spring/EmbeddedJmxTransFactory.java#L148-L166
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/smpp/balancer/impl/ServerConnectionImpl.java
ServerConnectionImpl.sendGenericNack
private void sendGenericNack(Pdu packet){ GenericNack genericNack = new GenericNack(); genericNack.setSequenceNumber(packet.getSequenceNumber()); genericNack.setCommandStatus(SmppConstants.STATUS_INVCMDID); ChannelBuffer buffer = null; try { buffer = transcoder.encode(genericNack); } catch (UnrecoverablePduException e) { logger.error("Encode error: ", e); }catch(RecoverablePduException e){ logger.error("Encode error: ", e); } if(logger.isDebugEnabled()) logger.debug("LB sent generic_nack response for packet ("+ packet +") to " + channel.getRemoteAddress().toString() + ". session ID : " + sessionId); channel.write(buffer); }
java
private void sendGenericNack(Pdu packet){ GenericNack genericNack = new GenericNack(); genericNack.setSequenceNumber(packet.getSequenceNumber()); genericNack.setCommandStatus(SmppConstants.STATUS_INVCMDID); ChannelBuffer buffer = null; try { buffer = transcoder.encode(genericNack); } catch (UnrecoverablePduException e) { logger.error("Encode error: ", e); }catch(RecoverablePduException e){ logger.error("Encode error: ", e); } if(logger.isDebugEnabled()) logger.debug("LB sent generic_nack response for packet ("+ packet +") to " + channel.getRemoteAddress().toString() + ". session ID : " + sessionId); channel.write(buffer); }
[ "private", "void", "sendGenericNack", "(", "Pdu", "packet", ")", "{", "GenericNack", "genericNack", "=", "new", "GenericNack", "(", ")", ";", "genericNack", ".", "setSequenceNumber", "(", "packet", ".", "getSequenceNumber", "(", ")", ")", ";", "genericNack", "...
Send generic_nack to client if unable to convert request from client @param packet PDU packet
[ "Send", "generic_nack", "to", "client", "if", "unable", "to", "convert", "request", "from", "client" ]
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/smpp/balancer/impl/ServerConnectionImpl.java#L419-L438
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/config/EtcdKVStore.java
EtcdKVStore.getKeyValue
public KeyValue getKeyValue(String KeyURI) throws EmbeddedJmxTransException { String etcdURI = KeyURI.substring(0, KeyURI.indexOf("/", 7)); String key = KeyURI.substring(KeyURI.indexOf("/", 7)); try { return getFromEtcd(makeEtcdBaseUris(etcdURI), key); } catch (Throwable t) { throw new EmbeddedJmxTransException("Exception reading etcd key '" + KeyURI + "': " + t.getMessage(), t); } }
java
public KeyValue getKeyValue(String KeyURI) throws EmbeddedJmxTransException { String etcdURI = KeyURI.substring(0, KeyURI.indexOf("/", 7)); String key = KeyURI.substring(KeyURI.indexOf("/", 7)); try { return getFromEtcd(makeEtcdBaseUris(etcdURI), key); } catch (Throwable t) { throw new EmbeddedJmxTransException("Exception reading etcd key '" + KeyURI + "': " + t.getMessage(), t); } }
[ "public", "KeyValue", "getKeyValue", "(", "String", "KeyURI", ")", "throws", "EmbeddedJmxTransException", "{", "String", "etcdURI", "=", "KeyURI", ".", "substring", "(", "0", ",", "KeyURI", ".", "indexOf", "(", "\"/\"", ",", "7", ")", ")", ";", "String", "...
Get a key value from etcd. Returns the key value and the etcd modification index as version @param KeyURI URI of the key in the form etcd://ipaddr:port/path for an etcd cluster you can use etcd://[ipaddr1:port1, ipaddr:port2,...]:/path @return a KeyValue object @throws EmbeddedJmxTransException @see org.jmxtrans.embedded.config.KVStore#getKeyValue(java.lang.String)
[ "Get", "a", "key", "value", "from", "etcd", ".", "Returns", "the", "key", "value", "and", "the", "etcd", "modification", "index", "as", "version" ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/config/EtcdKVStore.java#L208-L219
train
aloha-app/thrift-client-pool-java
src/main/java/com/wealoha/thrift/ThriftUtil.java
ThriftUtil.closeClient
public static void closeClient(TServiceClient client) { if (client == null) { return; } try { TProtocol proto = client.getInputProtocol(); if (proto != null) { proto.getTransport().close(); } } catch (Throwable e) { logger.warn("close input transport fail", e); } try { TProtocol proto = client.getOutputProtocol(); if (proto != null) { proto.getTransport().close(); } } catch (Throwable e) { logger.warn("close output transport fail", e); } }
java
public static void closeClient(TServiceClient client) { if (client == null) { return; } try { TProtocol proto = client.getInputProtocol(); if (proto != null) { proto.getTransport().close(); } } catch (Throwable e) { logger.warn("close input transport fail", e); } try { TProtocol proto = client.getOutputProtocol(); if (proto != null) { proto.getTransport().close(); } } catch (Throwable e) { logger.warn("close output transport fail", e); } }
[ "public", "static", "void", "closeClient", "(", "TServiceClient", "client", ")", "{", "if", "(", "client", "==", "null", ")", "{", "return", ";", "}", "try", "{", "TProtocol", "proto", "=", "client", ".", "getInputProtocol", "(", ")", ";", "if", "(", "...
close internal transport @param client
[ "close", "internal", "transport" ]
7781fc18f81ced14ea7b03d3ffd070c411c33a17
https://github.com/aloha-app/thrift-client-pool-java/blob/7781fc18f81ced14ea7b03d3ffd070c411c33a17/src/main/java/com/wealoha/thrift/ThriftUtil.java#L22-L43
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java
StackdriverWriter.start
@Override public void start() { try { url = new URL(getStringSetting(SETTING_URL, DEFAULT_STACKDRIVER_API_URL)); } catch (MalformedURLException e) { throw new EmbeddedJmxTransException(e); } apiKey = getStringSetting(SETTING_TOKEN); if (getStringSetting(SETTING_PROXY_HOST, null) != null && !getStringSetting(SETTING_PROXY_HOST).isEmpty()) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getStringSetting(SETTING_PROXY_HOST), getIntSetting(SETTING_PROXY_PORT))); } logger.info("Starting Stackdriver writer connected to '{}', proxy {} ...", url, proxy); stackdriverApiTimeoutInMillis = getIntSetting(SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS, DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS); // try to get and instance ID if (getStringSetting(SETTING_SOURCE_INSTANCE, null) != null && !getStringSetting(SETTING_SOURCE_INSTANCE).isEmpty()) { // if one is set directly use that instanceId = getStringSetting(SETTING_SOURCE_INSTANCE); logger.info("Using instance ID {} from setting {}", instanceId, SETTING_SOURCE_INSTANCE); } else if (getStringSetting(SETTING_DETECT_INSTANCE, null) != null && "AWS".equalsIgnoreCase(getStringSetting(SETTING_DETECT_INSTANCE))) { // if setting is to detect, look on the local machine URL logger.info("Detect instance set to AWS, trying to determine AWS instance ID"); instanceId = getLocalAwsInstanceId(); if (instanceId != null) { logger.info("Detected instance ID as {}", instanceId); } else { logger.info("Unable to detect AWS instance ID for this machine, sending metrics without an instance ID"); } } else { // no instance ID, the metrics will be sent as "bare" custom metrics and not associated with an instance instanceId = null; logger.info("No source instance ID passed, and not set to detect, sending metrics without and instance ID"); } }
java
@Override public void start() { try { url = new URL(getStringSetting(SETTING_URL, DEFAULT_STACKDRIVER_API_URL)); } catch (MalformedURLException e) { throw new EmbeddedJmxTransException(e); } apiKey = getStringSetting(SETTING_TOKEN); if (getStringSetting(SETTING_PROXY_HOST, null) != null && !getStringSetting(SETTING_PROXY_HOST).isEmpty()) { proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getStringSetting(SETTING_PROXY_HOST), getIntSetting(SETTING_PROXY_PORT))); } logger.info("Starting Stackdriver writer connected to '{}', proxy {} ...", url, proxy); stackdriverApiTimeoutInMillis = getIntSetting(SETTING_STACKDRIVER_API_TIMEOUT_IN_MILLIS, DEFAULT_STACKDRIVER_API_TIMEOUT_IN_MILLIS); // try to get and instance ID if (getStringSetting(SETTING_SOURCE_INSTANCE, null) != null && !getStringSetting(SETTING_SOURCE_INSTANCE).isEmpty()) { // if one is set directly use that instanceId = getStringSetting(SETTING_SOURCE_INSTANCE); logger.info("Using instance ID {} from setting {}", instanceId, SETTING_SOURCE_INSTANCE); } else if (getStringSetting(SETTING_DETECT_INSTANCE, null) != null && "AWS".equalsIgnoreCase(getStringSetting(SETTING_DETECT_INSTANCE))) { // if setting is to detect, look on the local machine URL logger.info("Detect instance set to AWS, trying to determine AWS instance ID"); instanceId = getLocalAwsInstanceId(); if (instanceId != null) { logger.info("Detected instance ID as {}", instanceId); } else { logger.info("Unable to detect AWS instance ID for this machine, sending metrics without an instance ID"); } } else { // no instance ID, the metrics will be sent as "bare" custom metrics and not associated with an instance instanceId = null; logger.info("No source instance ID passed, and not set to detect, sending metrics without and instance ID"); } }
[ "@", "Override", "public", "void", "start", "(", ")", "{", "try", "{", "url", "=", "new", "URL", "(", "getStringSetting", "(", "SETTING_URL", ",", "DEFAULT_STACKDRIVER_API_URL", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "thr...
Initial setup for the writer class. Loads in settings and initializes one-time setup variables like instanceId.
[ "Initial", "setup", "for", "the", "writer", "class", ".", "Loads", "in", "settings", "and", "initializes", "one", "-", "time", "setup", "variables", "like", "instanceId", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java#L110-L149
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java
StackdriverWriter.write
@Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); serialize(results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode, urlConnection.getResponseMessage(), url, proxy); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } }
java
@Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); serialize(results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode, urlConnection.getResponseMessage(), url, proxy); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } }
[ "@", "Override", "public", "void", "write", "(", "Iterable", "<", "QueryResult", ">", "results", ")", "{", "logger", ".", "debug", "(", "\"Export to '{}', proxy {} metrics {}\"", ",", "url", ",", "proxy", ",", "results", ")", ";", "HttpURLConnection", "urlConnec...
Send given metrics to the Stackdriver server using HTTP @param results Iterable collection of data points
[ "Send", "given", "metrics", "to", "the", "Stackdriver", "server", "using", "HTTP" ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java#L157-L208
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java
StackdriverWriter.getLocalAwsInstanceId
@Nullable private String getLocalAwsInstanceId() { String detectedInstanceId = null; try { final URL metadataUrl = new URL("http://169.254.169.254/latest/meta-data/instance-id"); URLConnection metadataConnection = metadataUrl.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(metadataConnection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { detectedInstanceId = inputLine; } in.close(); } catch (Exception e) { logger.warn("unable to determine AWS instance ID", e); } return detectedInstanceId; }
java
@Nullable private String getLocalAwsInstanceId() { String detectedInstanceId = null; try { final URL metadataUrl = new URL("http://169.254.169.254/latest/meta-data/instance-id"); URLConnection metadataConnection = metadataUrl.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(metadataConnection.getInputStream(), "UTF-8")); String inputLine; while ((inputLine = in.readLine()) != null) { detectedInstanceId = inputLine; } in.close(); } catch (Exception e) { logger.warn("unable to determine AWS instance ID", e); } return detectedInstanceId; }
[ "@", "Nullable", "private", "String", "getLocalAwsInstanceId", "(", ")", "{", "String", "detectedInstanceId", "=", "null", ";", "try", "{", "final", "URL", "metadataUrl", "=", "new", "URL", "(", "\"http://169.254.169.254/latest/meta-data/instance-id\"", ")", ";", "U...
Use the EC2 Metadata URL to determine the instance ID that this code is running on. Useful if you don't want to configure the instance ID manually. Pass detectInstance = "AWS" to have this run in your configuration. @return String containing an AWS instance id, or null if none is found
[ "Use", "the", "EC2", "Metadata", "URL", "to", "determine", "the", "instance", "ID", "that", "this", "code", "is", "running", "on", ".", "Useful", "if", "you", "don", "t", "want", "to", "configure", "the", "instance", "ID", "manually", ".", "Pass", "detec...
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/StackdriverWriter.java#L216-L232
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/smpp/multiplexer/MServer.java
MServer.start
public void start() { try { this.regularBootstrap.bind(new InetSocketAddress(regularConfiguration.getHost(), regularConfiguration.getPort())); if(logger.isInfoEnabled()) { logger.info(regularConfiguration.getName() + " started at " + regularConfiguration.getHost() + " : " + regularConfiguration.getPort()); } if(this.securedConfiguration!=null) { this.securedBootstrap.bind(new InetSocketAddress(securedConfiguration.getHost(), securedConfiguration.getPort())); if(logger.isInfoEnabled()) { logger.info(securedConfiguration.getName() + " uses port : " + securedConfiguration.getPort() + " for TLS clients."); } } } catch (ChannelException e) { logger.error("Smpp Channel Exception:", e); } }
java
public void start() { try { this.regularBootstrap.bind(new InetSocketAddress(regularConfiguration.getHost(), regularConfiguration.getPort())); if(logger.isInfoEnabled()) { logger.info(regularConfiguration.getName() + " started at " + regularConfiguration.getHost() + " : " + regularConfiguration.getPort()); } if(this.securedConfiguration!=null) { this.securedBootstrap.bind(new InetSocketAddress(securedConfiguration.getHost(), securedConfiguration.getPort())); if(logger.isInfoEnabled()) { logger.info(securedConfiguration.getName() + " uses port : " + securedConfiguration.getPort() + " for TLS clients."); } } } catch (ChannelException e) { logger.error("Smpp Channel Exception:", e); } }
[ "public", "void", "start", "(", ")", "{", "try", "{", "this", ".", "regularBootstrap", ".", "bind", "(", "new", "InetSocketAddress", "(", "regularConfiguration", ".", "getHost", "(", ")", ",", "regularConfiguration", ".", "getPort", "(", ")", ")", ")", ";"...
Start load balancer server
[ "Start", "load", "balancer", "server" ]
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/smpp/multiplexer/MServer.java#L75-L95
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/smpp/multiplexer/MServer.java
MServer.stop
public void stop() { if (this.channels.size() > 0) { logger.info(regularConfiguration.getName() + " currently has [" + this.channels.size() + "] open child channel(s) that will be closed as part of stop()"); } this.channelFactory.shutdown(); this.channels.close().awaitUninterruptibly(); this.regularBootstrap.shutdown(); if(this.securedBootstrap!=null) this.securedBootstrap.shutdown(); logger.info(regularConfiguration.getName() + " stopped at " + regularConfiguration.getHost()); }
java
public void stop() { if (this.channels.size() > 0) { logger.info(regularConfiguration.getName() + " currently has [" + this.channels.size() + "] open child channel(s) that will be closed as part of stop()"); } this.channelFactory.shutdown(); this.channels.close().awaitUninterruptibly(); this.regularBootstrap.shutdown(); if(this.securedBootstrap!=null) this.securedBootstrap.shutdown(); logger.info(regularConfiguration.getName() + " stopped at " + regularConfiguration.getHost()); }
[ "public", "void", "stop", "(", ")", "{", "if", "(", "this", ".", "channels", ".", "size", "(", ")", ">", "0", ")", "{", "logger", ".", "info", "(", "regularConfiguration", ".", "getName", "(", ")", "+", "\" currently has [\"", "+", "this", ".", "chan...
Stop load balancer server
[ "Stop", "load", "balancer", "server" ]
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/smpp/multiplexer/MServer.java#L107-L118
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/AbstractOutputWriter.java
AbstractOutputWriter.getStringSetting
protected String getStringSetting(String name, String defaultValue) { if (settings.containsKey(name)) { return settings.get(name).toString(); } else { return defaultValue; } }
java
protected String getStringSetting(String name, String defaultValue) { if (settings.containsKey(name)) { return settings.get(name).toString(); } else { return defaultValue; } }
[ "protected", "String", "getStringSetting", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "if", "(", "settings", ".", "containsKey", "(", "name", ")", ")", "{", "return", "settings", ".", "get", "(", "name", ")", ".", "toString", "(", ")...
Return the value of the given property. If the property is not found, the <code>defaultValue</code> is returned. @param name name of the property @param defaultValue default value if the property is not defined. @return value of the property or <code>defaultValue</code> if the property is not defined.
[ "Return", "the", "value", "of", "the", "given", "property", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/AbstractOutputWriter.java#L190-L196
train
aloha-app/thrift-client-pool-java
src/main/java/com/wealoha/thrift/ThriftClientPool.java
ThriftClientPool.setServices
public void setServices(List<ServiceInfo> services) { if (services == null || services.size() == 0) { throw new IllegalArgumentException("services is empty!"); } this.services = services; serviceReset = true; }
java
public void setServices(List<ServiceInfo> services) { if (services == null || services.size() == 0) { throw new IllegalArgumentException("services is empty!"); } this.services = services; serviceReset = true; }
[ "public", "void", "setServices", "(", "List", "<", "ServiceInfo", ">", "services", ")", "{", "if", "(", "services", "==", "null", "||", "services", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"services is ...
set new services for this pool @param services
[ "set", "new", "services", "for", "this", "pool" ]
7781fc18f81ced14ea7b03d3ffd070c411c33a17
https://github.com/aloha-app/thrift-client-pool-java/blob/7781fc18f81ced14ea7b03d3ffd070c411c33a17/src/main/java/com/wealoha/thrift/ThriftClientPool.java#L175-L181
train
aloha-app/thrift-client-pool-java
src/main/java/com/wealoha/thrift/ThriftClientPool.java
ThriftClientPool.getRandomService
private ServiceInfo getRandomService(List<ServiceInfo> serviceList) { if (serviceList == null || serviceList.size() == 0) { return null; } return serviceList.get(RandomUtils.nextInt(0, serviceList.size())); }
java
private ServiceInfo getRandomService(List<ServiceInfo> serviceList) { if (serviceList == null || serviceList.size() == 0) { return null; } return serviceList.get(RandomUtils.nextInt(0, serviceList.size())); }
[ "private", "ServiceInfo", "getRandomService", "(", "List", "<", "ServiceInfo", ">", "serviceList", ")", "{", "if", "(", "serviceList", "==", "null", "||", "serviceList", ".", "size", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "return", "s...
get a random service @param serviceList @return
[ "get", "a", "random", "service" ]
7781fc18f81ced14ea7b03d3ffd070c411c33a17
https://github.com/aloha-app/thrift-client-pool-java/blob/7781fc18f81ced14ea7b03d3ffd070c411c33a17/src/main/java/com/wealoha/thrift/ThriftClientPool.java#L205-L210
train
aloha-app/thrift-client-pool-java
src/main/java/com/wealoha/thrift/ThriftClientPool.java
ThriftClientPool.getClient
public ThriftClient<T> getClient() throws ThriftException { try { return pool.borrowObject(); } catch (Exception e) { if (e instanceof ThriftException) { throw (ThriftException) e; } throw new ThriftException("Get client from pool failed.", e); } }
java
public ThriftClient<T> getClient() throws ThriftException { try { return pool.borrowObject(); } catch (Exception e) { if (e instanceof ThriftException) { throw (ThriftException) e; } throw new ThriftException("Get client from pool failed.", e); } }
[ "public", "ThriftClient", "<", "T", ">", "getClient", "(", ")", "throws", "ThriftException", "{", "try", "{", "return", "pool", ".", "borrowObject", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "e", "instanceof", "ThriftExcept...
get a client from pool @return @throws ThriftException @throws NoBackendServiceException if {@link PoolConfig#setFailover(boolean)} is set and no service can connect to @throws ConnectionFailException if {@link PoolConfig#setFailover(boolean)} not set and connection fail
[ "get", "a", "client", "from", "pool" ]
7781fc18f81ced14ea7b03d3ffd070c411c33a17
https://github.com/aloha-app/thrift-client-pool-java/blob/7781fc18f81ced14ea7b03d3ffd070c411c33a17/src/main/java/com/wealoha/thrift/ThriftClientPool.java#L232-L241
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/sip/balancer/SIPBalancerForwarder.java
SIPBalancerForwarder.checkRouteHeaderForSipNode
private Node checkRouteHeaderForSipNode(SipURI routeSipUri) { Node node = null; String hostNode = routeSipUri.getParameter(ROUTE_PARAM_NODE_HOST); String hostPort = routeSipUri.getParameter(ROUTE_PARAM_NODE_PORT); String hostVersion = routeSipUri.getParameter(ROUTE_PARAM_NODE_VERSION); if(hostNode != null && hostPort != null) { int port = Integer.parseInt(hostPort); String transport = routeSipUri.getTransportParam(); if(transport == null) transport = ListeningPoint.UDP; node = register.getNode(hostNode, port, transport, hostVersion); } return node; }
java
private Node checkRouteHeaderForSipNode(SipURI routeSipUri) { Node node = null; String hostNode = routeSipUri.getParameter(ROUTE_PARAM_NODE_HOST); String hostPort = routeSipUri.getParameter(ROUTE_PARAM_NODE_PORT); String hostVersion = routeSipUri.getParameter(ROUTE_PARAM_NODE_VERSION); if(hostNode != null && hostPort != null) { int port = Integer.parseInt(hostPort); String transport = routeSipUri.getTransportParam(); if(transport == null) transport = ListeningPoint.UDP; node = register.getNode(hostNode, port, transport, hostVersion); } return node; }
[ "private", "Node", "checkRouteHeaderForSipNode", "(", "SipURI", "routeSipUri", ")", "{", "Node", "node", "=", "null", ";", "String", "hostNode", "=", "routeSipUri", ".", "getParameter", "(", "ROUTE_PARAM_NODE_HOST", ")", ";", "String", "hostPort", "=", "routeSipUr...
This will check if in the route header there is information on which node from the cluster send the request. If the request is not received from the cluster, this information will not be present. @param routeHeader the route header to check @return the corresponding Sip Node
[ "This", "will", "check", "if", "in", "the", "route", "header", "there", "is", "information", "on", "which", "node", "from", "the", "cluster", "send", "the", "request", ".", "If", "the", "request", "is", "not", "received", "from", "the", "cluster", "this", ...
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/sip/balancer/SIPBalancerForwarder.java#L1650-L1662
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/sip/balancer/SIPBalancerForwarder.java
SIPBalancerForwarder.comesFromInternalNode
protected Boolean comesFromInternalNode(Response externalResponse,InvocationContext ctx,String host,Integer port,String transport,Boolean isIpV6) { boolean found = false; if(host!=null && port!=null) { if(ctx.sipNodeMap(isIpV6).containsKey(new KeySip(host, port,isIpV6))) found = true; // for(Node node : ctx.nodes) { // if(node.getIp().equals(host)) { // if(port.equals(node.getProperties().get(transport+"Port"))) { // found = true; // break; // } // } // } } return found; }
java
protected Boolean comesFromInternalNode(Response externalResponse,InvocationContext ctx,String host,Integer port,String transport,Boolean isIpV6) { boolean found = false; if(host!=null && port!=null) { if(ctx.sipNodeMap(isIpV6).containsKey(new KeySip(host, port,isIpV6))) found = true; // for(Node node : ctx.nodes) { // if(node.getIp().equals(host)) { // if(port.equals(node.getProperties().get(transport+"Port"))) { // found = true; // break; // } // } // } } return found; }
[ "protected", "Boolean", "comesFromInternalNode", "(", "Response", "externalResponse", ",", "InvocationContext", "ctx", ",", "String", "host", ",", "Integer", "port", ",", "String", "transport", ",", "Boolean", "isIpV6", ")", "{", "boolean", "found", "=", "false", ...
need to verify that comes from external in case of single leg
[ "need", "to", "verify", "that", "comes", "from", "external", "in", "case", "of", "single", "leg" ]
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/sip/balancer/SIPBalancerForwarder.java#L2283-L2300
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerConf.java
BalancerConf.initialise
public void initialise() { if (log.isDebugEnabled()) { log.debug("now initialising conf"); } initDecodeUsing(decodeUsing); boolean rulesOk = true; for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); if (!rule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < outboundRules.size(); i++) { final OutboundRule outboundRule = (OutboundRule) outboundRules.get(i); if (!outboundRule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < catchElems.size(); i++) { final CatchElem catchElem = (CatchElem) catchElems.get(i); if (!catchElem.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } if (rulesOk) { ok = true; } if (log.isDebugEnabled()) { log.debug("conf status " + ok); } }
java
public void initialise() { if (log.isDebugEnabled()) { log.debug("now initialising conf"); } initDecodeUsing(decodeUsing); boolean rulesOk = true; for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); if (!rule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < outboundRules.size(); i++) { final OutboundRule outboundRule = (OutboundRule) outboundRules.get(i); if (!outboundRule.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } for (int i = 0; i < catchElems.size(); i++) { final CatchElem catchElem = (CatchElem) catchElems.get(i); if (!catchElem.initialise(context)) { // if we failed to initialise anything set the status to bad rulesOk = false; } } if (rulesOk) { ok = true; } if (log.isDebugEnabled()) { log.debug("conf status " + ok); } }
[ "public", "void", "initialise", "(", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"now initialising conf\"", ")", ";", "}", "initDecodeUsing", "(", "decodeUsing", ")", ";", "boolean", "rulesOk", "=", ...
Initialise the conf file. This will run initialise on each rule and condition in the conf file.
[ "Initialise", "the", "conf", "file", ".", "This", "will", "run", "initialise", "on", "each", "rule", "and", "condition", "in", "the", "conf", "file", "." ]
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerConf.java#L331-L366
train
RestComm/load-balancer
jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerConf.java
BalancerConf.destroy
public void destroy() { for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); rule.destroy(); } }
java
public void destroy() { for (int i = 0; i < rules.size(); i++) { final Rule rule = (Rule) rules.get(i); rule.destroy(); } }
[ "public", "void", "destroy", "(", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "rules", ".", "size", "(", ")", ";", "i", "++", ")", "{", "final", "Rule", "rule", "=", "(", "Rule", ")", "rules", ".", "get", "(", "i", ")", ";", ...
Destory the conf gracefully.
[ "Destory", "the", "conf", "gracefully", "." ]
54768d0b81004b2653d429720016ad2617fe754f
https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/http/urlrewriting/BalancerConf.java#L399-L404
train
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/output/CopperEggWriter.java
CopperEggWriter.ensure_dashboards
private void ensure_dashboards() { HttpURLConnection urlConnection = null; OutputStreamWriter wr = null; URL myurl = null; try { myurl = new URL(url_str + "/dashboards.json"); urlConnection = (HttpURLConnection) myurl.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(coppereggApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn("Bad responsecode " + String.valueOf(responseCode)+ " from Dahsboards Index: " + myurl); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception on dashboards index request "+ myurl + " "+ e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); String theString = convertStreamToString(in); for (Map.Entry<String, String> entry : dashMap.entrySet()) { String checkName = entry.getKey(); try { String Rslt = groupFind(checkName, theString, 1); if(Rslt != null){ // Update it Rslt = Send_Commmand("/dashboards/" + Rslt + ".json", "PUT", entry.getValue(),1); } else { // create it Rslt = Send_Commmand("/dashboards.json", "POST", entry.getValue(),1); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in dashboard update or create: "+ myurl + " "+ e); } } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception flushing http connection"+ e); } } } }
java
private void ensure_dashboards() { HttpURLConnection urlConnection = null; OutputStreamWriter wr = null; URL myurl = null; try { myurl = new URL(url_str + "/dashboards.json"); urlConnection = (HttpURLConnection) myurl.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(coppereggApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn("Bad responsecode " + String.valueOf(responseCode)+ " from Dahsboards Index: " + myurl); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception on dashboards index request "+ myurl + " "+ e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); String theString = convertStreamToString(in); for (Map.Entry<String, String> entry : dashMap.entrySet()) { String checkName = entry.getKey(); try { String Rslt = groupFind(checkName, theString, 1); if(Rslt != null){ // Update it Rslt = Send_Commmand("/dashboards/" + Rslt + ".json", "PUT", entry.getValue(),1); } else { // create it Rslt = Send_Commmand("/dashboards.json", "POST", entry.getValue(),1); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in dashboard update or create: "+ myurl + " "+ e); } } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception flushing http connection"+ e); } } } }
[ "private", "void", "ensure_dashboards", "(", ")", "{", "HttpURLConnection", "urlConnection", "=", "null", ";", "OutputStreamWriter", "wr", "=", "null", ";", "URL", "myurl", "=", "null", ";", "try", "{", "myurl", "=", "new", "URL", "(", "url_str", "+", "\"/...
If dashboard doesn't exist, create it If it does exist, update it.
[ "If", "dashboard", "doesn", "t", "exist", "create", "it", "If", "it", "does", "exist", "update", "it", "." ]
17224389e7d8323284cabc2a5167fc03bed6d223
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/output/CopperEggWriter.java#L708-L757
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/Normalization.java
Normalization.normalizeL2
public static double[] normalizeL2(double[] vector) { // compute vector 2-norm double norm2 = 0; for (int i = 0; i < vector.length; i++) { norm2 += vector[i] * vector[i]; } norm2 = (double) Math.sqrt(norm2); if (norm2 == 0) { Arrays.fill(vector, 1); } else { for (int i = 0; i < vector.length; i++) { vector[i] = vector[i] / norm2; } } return vector; }
java
public static double[] normalizeL2(double[] vector) { // compute vector 2-norm double norm2 = 0; for (int i = 0; i < vector.length; i++) { norm2 += vector[i] * vector[i]; } norm2 = (double) Math.sqrt(norm2); if (norm2 == 0) { Arrays.fill(vector, 1); } else { for (int i = 0; i < vector.length; i++) { vector[i] = vector[i] / norm2; } } return vector; }
[ "public", "static", "double", "[", "]", "normalizeL2", "(", "double", "[", "]", "vector", ")", "{", "// compute vector 2-norm\r", "double", "norm2", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector", ".", "length", ";", "i", "+...
This method applies L2 normalization on a given array of doubles. The passed vector is modified by the method. @param vector the original vector @return the L2 normalized vector
[ "This", "method", "applies", "L2", "normalization", "on", "a", "given", "array", "of", "doubles", ".", "The", "passed", "vector", "is", "modified", "by", "the", "method", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/Normalization.java#L21-L37
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/Normalization.java
Normalization.normalizeL1
public static double[] normalizeL1(double[] vector) { // compute vector 1-norm double norm1 = 0; for (int i = 0; i < vector.length; i++) { norm1 += Math.abs(vector[i]); } if (norm1 == 0) { Arrays.fill(vector, 1.0 / vector.length); } else { for (int i = 0; i < vector.length; i++) { vector[i] = vector[i] / norm1; } } return vector; }
java
public static double[] normalizeL1(double[] vector) { // compute vector 1-norm double norm1 = 0; for (int i = 0; i < vector.length; i++) { norm1 += Math.abs(vector[i]); } if (norm1 == 0) { Arrays.fill(vector, 1.0 / vector.length); } else { for (int i = 0; i < vector.length; i++) { vector[i] = vector[i] / norm1; } } return vector; }
[ "public", "static", "double", "[", "]", "normalizeL1", "(", "double", "[", "]", "vector", ")", "{", "// compute vector 1-norm\r", "double", "norm1", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector", ".", "length", ";", "i", "+...
This method applies L1 normalization on a given array of doubles. The passed vector is modified by the method. @param vector the original vector @return the L1 normalized vector
[ "This", "method", "applies", "L1", "normalization", "on", "a", "given", "array", "of", "doubles", ".", "The", "passed", "vector", "is", "modified", "by", "the", "method", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/Normalization.java#L47-L62
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/Normalization.java
Normalization.normalizePower
public static double[] normalizePower(double[] vector, double aParameter) { for (int i = 0; i < vector.length; i++) { vector[i] = Math.signum(vector[i]) * Math.pow(Math.abs(vector[i]), aParameter); } return vector; }
java
public static double[] normalizePower(double[] vector, double aParameter) { for (int i = 0; i < vector.length; i++) { vector[i] = Math.signum(vector[i]) * Math.pow(Math.abs(vector[i]), aParameter); } return vector; }
[ "public", "static", "double", "[", "]", "normalizePower", "(", "double", "[", "]", "vector", ",", "double", "aParameter", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector", ".", "length", ";", "i", "++", ")", "{", "vector", "[", ...
This method applies power normalization on a given array of doubles. The passed vector is modified by the method. @param vector the original vector @param aParameter the a parameter used @return the power normalized vector
[ "This", "method", "applies", "power", "normalization", "on", "a", "given", "array", "of", "doubles", ".", "The", "passed", "vector", "is", "modified", "by", "the", "method", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/Normalization.java#L74-L79
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/aggregation/VladAggregator.java
VladAggregator.aggregateInternal
protected double[] aggregateInternal(ArrayList<double[]> descriptors) { double[] vlad = new double[numCentroids * descriptorLength]; if (descriptors.size() == 0) { // when there are 0 local descriptors extracted return vlad; } for (double[] descriptor : descriptors) { int nnIndex = computeNearestCentroid(descriptor); for (int i = 0; i < descriptorLength; i++) { vlad[nnIndex * descriptorLength + i] += descriptor[i] - codebook[nnIndex][i]; } } return vlad; }
java
protected double[] aggregateInternal(ArrayList<double[]> descriptors) { double[] vlad = new double[numCentroids * descriptorLength]; if (descriptors.size() == 0) { // when there are 0 local descriptors extracted return vlad; } for (double[] descriptor : descriptors) { int nnIndex = computeNearestCentroid(descriptor); for (int i = 0; i < descriptorLength; i++) { vlad[nnIndex * descriptorLength + i] += descriptor[i] - codebook[nnIndex][i]; } } return vlad; }
[ "protected", "double", "[", "]", "aggregateInternal", "(", "ArrayList", "<", "double", "[", "]", ">", "descriptors", ")", "{", "double", "[", "]", "vlad", "=", "new", "double", "[", "numCentroids", "*", "descriptorLength", "]", ";", "if", "(", "descriptors...
Takes as input an ArrayList of double arrays which contains the set of local descriptors for an image. Returns the VLAD vector representation of the image using the codebook supplied in the constructor. @param descriptors @return the VLAD vector @throws Exception
[ "Takes", "as", "input", "an", "ArrayList", "of", "double", "arrays", "which", "contains", "the", "set", "of", "local", "descriptors", "for", "an", "image", ".", "Returns", "the", "VLAD", "vector", "representation", "of", "the", "image", "using", "the", "code...
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/aggregation/VladAggregator.java#L35-L47
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/CSLDateParser.java
CSLDateParser.parse
public CSLDate parse(String str) { Map<String, Object> res; try { Map<String, Object> m = runner.callMethod( parser, "parseDateToArray", Map.class, str); res = m; } catch (ScriptRunnerException e) { throw new IllegalArgumentException("Could not update items", e); } CSLDate r = CSLDate.fromJson(res); if (r.getDateParts().length == 2 && Arrays.equals(r.getDateParts()[0], r.getDateParts()[1])) { r = new CSLDateBuilder(r).dateParts(r.getDateParts()[0]).build(); } return r; }
java
public CSLDate parse(String str) { Map<String, Object> res; try { Map<String, Object> m = runner.callMethod( parser, "parseDateToArray", Map.class, str); res = m; } catch (ScriptRunnerException e) { throw new IllegalArgumentException("Could not update items", e); } CSLDate r = CSLDate.fromJson(res); if (r.getDateParts().length == 2 && Arrays.equals(r.getDateParts()[0], r.getDateParts()[1])) { r = new CSLDateBuilder(r).dateParts(r.getDateParts()[0]).build(); } return r; }
[ "public", "CSLDate", "parse", "(", "String", "str", ")", "{", "Map", "<", "String", ",", "Object", ">", "res", ";", "try", "{", "Map", "<", "String", ",", "Object", ">", "m", "=", "runner", ".", "callMethod", "(", "parser", ",", "\"parseDateToArray\"",...
Parses a string to a date @param str the string to parse @return the parsed date
[ "Parses", "a", "string", "to", "a", "date" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/CSLDateParser.java#L80-L95
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/dimreduction/PCALearningExample.java
PCALearningExample.main
public static void main(String[] args) throws Exception { String indexLocation = args[0]; int numTrainVectors = Integer.parseInt(args[1]); int vectorLength = Integer.parseInt(args[2]); int numPrincipalComponents = Integer.parseInt(args[3]); boolean whitening = true; boolean compact = false; PCA pca = new PCA(numPrincipalComponents, numTrainVectors, vectorLength, whitening); pca.setCompact(compact); // load the vectors into the PCA class Linear vladArray = new Linear(vectorLength, numTrainVectors, true, indexLocation, false, true, 0); for (int i = 0; i < numTrainVectors; i++) { pca.addSample(vladArray.getVector(i)); } // now we are able to perform SVD and compute the eigenvectors System.out.println("PCA computation started!"); long start = System.currentTimeMillis(); pca.computeBasis(); long end = System.currentTimeMillis(); System.out.println("PCA computation completed in " + (end - start) + " ms"); // now we can save the PCA matrix in a file String PCAfile = indexLocation + "pca_" + numTrainVectors + "_" + numPrincipalComponents + "_" + (end - start) + "ms.txt"; pca.savePCAToFile(PCAfile); }
java
public static void main(String[] args) throws Exception { String indexLocation = args[0]; int numTrainVectors = Integer.parseInt(args[1]); int vectorLength = Integer.parseInt(args[2]); int numPrincipalComponents = Integer.parseInt(args[3]); boolean whitening = true; boolean compact = false; PCA pca = new PCA(numPrincipalComponents, numTrainVectors, vectorLength, whitening); pca.setCompact(compact); // load the vectors into the PCA class Linear vladArray = new Linear(vectorLength, numTrainVectors, true, indexLocation, false, true, 0); for (int i = 0; i < numTrainVectors; i++) { pca.addSample(vladArray.getVector(i)); } // now we are able to perform SVD and compute the eigenvectors System.out.println("PCA computation started!"); long start = System.currentTimeMillis(); pca.computeBasis(); long end = System.currentTimeMillis(); System.out.println("PCA computation completed in " + (end - start) + " ms"); // now we can save the PCA matrix in a file String PCAfile = indexLocation + "pca_" + numTrainVectors + "_" + numPrincipalComponents + "_" + (end - start) + "ms.txt"; pca.savePCAToFile(PCAfile); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "String", "indexLocation", "=", "args", "[", "0", "]", ";", "int", "numTrainVectors", "=", "Integer", ".", "parseInt", "(", "args", "[", "1", "]", ")"...
This method can be used to learn a PCA projection matrix. @param args [0] full path to the location of the BDB store which contains the training vectors (use backslashes) @param args [1] number of vectors to use for learning (the first vectors will be used), e.g. 10000 @param args [2] length of the supplied vectors, e.g. 4096 (for VLAD+SURF vectors generated using 64 centroids) @param args [3] number of first principal components to be kept, e.g. 1024 @throws Exception
[ "This", "method", "can", "be", "used", "to", "learn", "a", "PCA", "projection", "matrix", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/dimreduction/PCALearningExample.java#L27-L56
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/mendeley/MendeleyConverter.java
MendeleyConverter.toAuthors
private static CSLName[] toAuthors(List<Map<String, Object>> authors) { CSLName[] result = new CSLName[authors.size()]; int i = 0; for (Map<String, Object> a : authors) { CSLNameBuilder builder = new CSLNameBuilder(); if (a.containsKey(FIELD_FIRSTNAME)) { builder.given(strOrNull(a.get(FIELD_FIRSTNAME))); } if (a.containsKey(FIELD_LASTNAME)) { builder.family(strOrNull(a.get(FIELD_LASTNAME))); } builder.parseNames(true); result[i] = builder.build(); ++i; } return result; }
java
private static CSLName[] toAuthors(List<Map<String, Object>> authors) { CSLName[] result = new CSLName[authors.size()]; int i = 0; for (Map<String, Object> a : authors) { CSLNameBuilder builder = new CSLNameBuilder(); if (a.containsKey(FIELD_FIRSTNAME)) { builder.given(strOrNull(a.get(FIELD_FIRSTNAME))); } if (a.containsKey(FIELD_LASTNAME)) { builder.family(strOrNull(a.get(FIELD_LASTNAME))); } builder.parseNames(true); result[i] = builder.build(); ++i; } return result; }
[ "private", "static", "CSLName", "[", "]", "toAuthors", "(", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "authors", ")", "{", "CSLName", "[", "]", "result", "=", "new", "CSLName", "[", "authors", ".", "size", "(", ")", "]", ";", "int...
Converts a list of authors @param authors the authors as returned by Mendeley @return the authors in CSL format
[ "Converts", "a", "list", "of", "authors" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/mendeley/MendeleyConverter.java#L264-L280
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/mendeley/MendeleyConverter.java
MendeleyConverter.toType
private static CSLType toType(String type) { if (type.equalsIgnoreCase(TYPE_BILL)) { return CSLType.BILL; } else if (type.equalsIgnoreCase(TYPE_BOOK)) { return CSLType.BOOK; } else if (type.equalsIgnoreCase(TYPE_BOOK_SECTION)) { return CSLType.CHAPTER; } else if (type.equalsIgnoreCase(TYPE_CASE)) { return CSLType.ARTICLE; } else if (type.equalsIgnoreCase(TYPE_COMPUTER_PROGRAM)) { return CSLType.ARTICLE; } else if (type.equalsIgnoreCase(TYPE_CONFERENCE_PROCEEDINGS)) { return CSLType.PAPER_CONFERENCE; } else if (type.equalsIgnoreCase(TYPE_ENCYCLOPEDIA_ARTICLE)) { return CSLType.ENTRY_ENCYCLOPEDIA; } else if (type.equalsIgnoreCase(TYPE_FILM)) { return CSLType.MOTION_PICTURE; } else if (type.equalsIgnoreCase(TYPE_GENERIC)) { return CSLType.ARTICLE; } else if (type.equalsIgnoreCase(TYPE_HEARING)) { return CSLType.SPEECH; } else if (type.equalsIgnoreCase(TYPE_JOURNAL)) { return CSLType.ARTICLE_JOURNAL; } else if (type.equalsIgnoreCase(TYPE_MAGAZINE_ARTICLE)) { return CSLType.ARTICLE_MAGAZINE; } else if (type.equalsIgnoreCase(TYPE_NEWSPAPER_ARTICLE)) { return CSLType.ARTICLE_NEWSPAPER; } else if (type.equalsIgnoreCase(TYPE_PATENT)) { return CSLType.PATENT; } else if (type.equalsIgnoreCase(TYPE_REPORT)) { return CSLType.REPORT; } else if (type.equalsIgnoreCase(TYPE_STATUTE)) { return CSLType.LEGISLATION; } else if (type.equalsIgnoreCase(TYPE_TELEVISION_BROADCAST)) { return CSLType.BROADCAST; } else if (type.equalsIgnoreCase(TYPE_THESIS)) { return CSLType.THESIS; } else if (type.equalsIgnoreCase(TYPE_WEB_PAGE)) { return CSLType.WEBPAGE; } else if (type.equalsIgnoreCase(TYPE_WORKING_PAPER)) { return CSLType.ARTICLE; } return CSLType.ARTICLE; }
java
private static CSLType toType(String type) { if (type.equalsIgnoreCase(TYPE_BILL)) { return CSLType.BILL; } else if (type.equalsIgnoreCase(TYPE_BOOK)) { return CSLType.BOOK; } else if (type.equalsIgnoreCase(TYPE_BOOK_SECTION)) { return CSLType.CHAPTER; } else if (type.equalsIgnoreCase(TYPE_CASE)) { return CSLType.ARTICLE; } else if (type.equalsIgnoreCase(TYPE_COMPUTER_PROGRAM)) { return CSLType.ARTICLE; } else if (type.equalsIgnoreCase(TYPE_CONFERENCE_PROCEEDINGS)) { return CSLType.PAPER_CONFERENCE; } else if (type.equalsIgnoreCase(TYPE_ENCYCLOPEDIA_ARTICLE)) { return CSLType.ENTRY_ENCYCLOPEDIA; } else if (type.equalsIgnoreCase(TYPE_FILM)) { return CSLType.MOTION_PICTURE; } else if (type.equalsIgnoreCase(TYPE_GENERIC)) { return CSLType.ARTICLE; } else if (type.equalsIgnoreCase(TYPE_HEARING)) { return CSLType.SPEECH; } else if (type.equalsIgnoreCase(TYPE_JOURNAL)) { return CSLType.ARTICLE_JOURNAL; } else if (type.equalsIgnoreCase(TYPE_MAGAZINE_ARTICLE)) { return CSLType.ARTICLE_MAGAZINE; } else if (type.equalsIgnoreCase(TYPE_NEWSPAPER_ARTICLE)) { return CSLType.ARTICLE_NEWSPAPER; } else if (type.equalsIgnoreCase(TYPE_PATENT)) { return CSLType.PATENT; } else if (type.equalsIgnoreCase(TYPE_REPORT)) { return CSLType.REPORT; } else if (type.equalsIgnoreCase(TYPE_STATUTE)) { return CSLType.LEGISLATION; } else if (type.equalsIgnoreCase(TYPE_TELEVISION_BROADCAST)) { return CSLType.BROADCAST; } else if (type.equalsIgnoreCase(TYPE_THESIS)) { return CSLType.THESIS; } else if (type.equalsIgnoreCase(TYPE_WEB_PAGE)) { return CSLType.WEBPAGE; } else if (type.equalsIgnoreCase(TYPE_WORKING_PAPER)) { return CSLType.ARTICLE; } return CSLType.ARTICLE; }
[ "private", "static", "CSLType", "toType", "(", "String", "type", ")", "{", "if", "(", "type", ".", "equalsIgnoreCase", "(", "TYPE_BILL", ")", ")", "{", "return", "CSLType", ".", "BILL", ";", "}", "else", "if", "(", "type", ".", "equalsIgnoreCase", "(", ...
Converts a Mendeley type to a CSL type @param type the Mendeley type @return the CSL type
[ "Converts", "a", "Mendeley", "type", "to", "a", "CSL", "type" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/mendeley/MendeleyConverter.java#L287-L330
train
googleapis/api-client-staging
generated/java/gapic-google-longrunning-v1/src/main/java/com/google/longrunning/OperationsClient.java
OperationsClient.getOperation
public final Operation getOperation(String name) { GetOperationRequest request = GetOperationRequest.newBuilder().setName(name).build(); return getOperation(request); }
java
public final Operation getOperation(String name) { GetOperationRequest request = GetOperationRequest.newBuilder().setName(name).build(); return getOperation(request); }
[ "public", "final", "Operation", "getOperation", "(", "String", "name", ")", "{", "GetOperationRequest", "request", "=", "GetOperationRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "name", ")", ".", "build", "(", ")", ";", "return", "getOperation",...
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. <p>Sample code: <pre><code> try (OperationsClient operationsClient = OperationsClient.create()) { String name = ""; Operation response = operationsClient.getOperation(name); } </code></pre> @param name The name of the operation resource. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Gets", "the", "latest", "state", "of", "a", "long", "-", "running", "operation", ".", "Clients", "can", "use", "this", "method", "to", "poll", "the", "operation", "result", "at", "intervals", "as", "recommended", "by", "the", "API", "service", "." ]
126aee68401977b5dc2b1b4be48decd0e9759db7
https://github.com/googleapis/api-client-staging/blob/126aee68401977b5dc2b1b4be48decd0e9759db7/generated/java/gapic-google-longrunning-v1/src/main/java/com/google/longrunning/OperationsClient.java#L176-L180
train
googleapis/api-client-staging
generated/java/gapic-google-longrunning-v1/src/main/java/com/google/longrunning/OperationsClient.java
OperationsClient.listOperations
public final ListOperationsPagedResponse listOperations(String name, String filter) { ListOperationsRequest request = ListOperationsRequest.newBuilder().setName(name).setFilter(filter).build(); return listOperations(request); }
java
public final ListOperationsPagedResponse listOperations(String name, String filter) { ListOperationsRequest request = ListOperationsRequest.newBuilder().setName(name).setFilter(filter).build(); return listOperations(request); }
[ "public", "final", "ListOperationsPagedResponse", "listOperations", "(", "String", "name", ",", "String", "filter", ")", "{", "ListOperationsRequest", "request", "=", "ListOperationsRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "name", ")", ".", "set...
Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. <p>NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/&#42;/operations`. <p>Sample code: <pre><code> try (OperationsClient operationsClient = OperationsClient.create()) { String name = ""; String filter = ""; for (Operation element : operationsClient.listOperations(name, filter).iterateAll()) { // doThingsWith(element); } } </code></pre> @param name The name of the operation collection. @param filter The standard list filter. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Lists", "operations", "that", "match", "the", "specified", "filter", "in", "the", "request", ".", "If", "the", "server", "doesn", "t", "support", "this", "method", "it", "returns", "UNIMPLEMENTED", "." ]
126aee68401977b5dc2b1b4be48decd0e9759db7
https://github.com/googleapis/api-client-staging/blob/126aee68401977b5dc2b1b4be48decd0e9759db7/generated/java/gapic-google-longrunning-v1/src/main/java/com/google/longrunning/OperationsClient.java#L253-L257
train
googleapis/api-client-staging
generated/java/gapic-google-longrunning-v1/src/main/java/com/google/longrunning/OperationsClient.java
OperationsClient.deleteOperation
public final void deleteOperation(String name) { DeleteOperationRequest request = DeleteOperationRequest.newBuilder().setName(name).build(); deleteOperation(request); }
java
public final void deleteOperation(String name) { DeleteOperationRequest request = DeleteOperationRequest.newBuilder().setName(name).build(); deleteOperation(request); }
[ "public", "final", "void", "deleteOperation", "(", "String", "name", ")", "{", "DeleteOperationRequest", "request", "=", "DeleteOperationRequest", ".", "newBuilder", "(", ")", ".", "setName", "(", "name", ")", ".", "build", "(", ")", ";", "deleteOperation", "(...
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. <p>Sample code: <pre><code> try (OperationsClient operationsClient = OperationsClient.create()) { String name = ""; operationsClient.deleteOperation(name); } </code></pre> @param name The name of the operation resource to be deleted. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Deletes", "a", "long", "-", "running", "operation", ".", "This", "method", "indicates", "that", "the", "client", "is", "no", "longer", "interested", "in", "the", "operation", "result", ".", "It", "does", "not", "cancel", "the", "operation", ".", "If", "th...
126aee68401977b5dc2b1b4be48decd0e9759db7
https://github.com/googleapis/api-client-staging/blob/126aee68401977b5dc2b1b4be48decd0e9759db7/generated/java/gapic-google-longrunning-v1/src/main/java/com/google/longrunning/OperationsClient.java#L465-L469
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/AdditionalShellCommands.java
AdditionalShellCommands.setCommand
@CommandDescList({ @CommandDesc(longName = "load", description = "load an input bibliography from a file", command = ShellLoadCommand.class), @CommandDesc(longName = "get", description = "get values of shell variables", command = ShellGetCommand.class), @CommandDesc(longName = "set", description = "assign values to shell variables", command = ShellSetCommand.class), @CommandDesc(longName = "help", description = "display help for a given command", command = ShellHelpCommand.class), @CommandDesc(longName = "exit", description = "exit the interactive shell", command = ShellExitCommand.class), @CommandDesc(longName = "quit", description = "exit the interactive shell", command = ShellQuitCommand.class), }) public void setCommand(AbstractCSLToolCommand command) { //we don't have to do anything here }
java
@CommandDescList({ @CommandDesc(longName = "load", description = "load an input bibliography from a file", command = ShellLoadCommand.class), @CommandDesc(longName = "get", description = "get values of shell variables", command = ShellGetCommand.class), @CommandDesc(longName = "set", description = "assign values to shell variables", command = ShellSetCommand.class), @CommandDesc(longName = "help", description = "display help for a given command", command = ShellHelpCommand.class), @CommandDesc(longName = "exit", description = "exit the interactive shell", command = ShellExitCommand.class), @CommandDesc(longName = "quit", description = "exit the interactive shell", command = ShellQuitCommand.class), }) public void setCommand(AbstractCSLToolCommand command) { //we don't have to do anything here }
[ "@", "CommandDescList", "(", "{", "@", "CommandDesc", "(", "longName", "=", "\"load\"", ",", "description", "=", "\"load an input bibliography from a file\"", ",", "command", "=", "ShellLoadCommand", ".", "class", ")", ",", "@", "CommandDesc", "(", "longName", "="...
Configures all additional shell commands @param command the configured command
[ "Configures", "all", "additional", "shell", "commands" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/AdditionalShellCommands.java#L30-L52
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/components/KeypadAdapter.java
KeypadAdapter.vibrateIfEnabled
private void vibrateIfEnabled() { final boolean enabled = styledAttributes.getBoolean(R.styleable.PinLock_vibrateOnClick, false); if(enabled){ Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); final int duration = styledAttributes.getInt(R.styleable.PinLock_vibrateDuration, 20); v.vibrate(duration); } }
java
private void vibrateIfEnabled() { final boolean enabled = styledAttributes.getBoolean(R.styleable.PinLock_vibrateOnClick, false); if(enabled){ Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); final int duration = styledAttributes.getInt(R.styleable.PinLock_vibrateDuration, 20); v.vibrate(duration); } }
[ "private", "void", "vibrateIfEnabled", "(", ")", "{", "final", "boolean", "enabled", "=", "styledAttributes", ".", "getBoolean", "(", "R", ".", "styleable", ".", "PinLock_vibrateOnClick", ",", "false", ")", ";", "if", "(", "enabled", ")", "{", "Vibrator", "v...
Vibrate device on each key press if the feature is enabled
[ "Vibrate", "device", "on", "each", "key", "press", "if", "the", "feature", "is", "enabled" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/components/KeypadAdapter.java#L138-L145
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/components/KeypadAdapter.java
KeypadAdapter.setStyle
private void setStyle(Button view) { final int textSize = styledAttributes.getInt(R.styleable.PinLock_keypadTextSize, 12); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); final int color = styledAttributes.getColor(R.styleable.PinLock_keypadTextColor, Color.BLACK); view.setTextColor(color); final int background = styledAttributes .getResourceId(R.styleable.PinLock_keypadButtonShape, R.drawable.rectangle); view.setBackgroundResource(background); }
java
private void setStyle(Button view) { final int textSize = styledAttributes.getInt(R.styleable.PinLock_keypadTextSize, 12); view.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize); final int color = styledAttributes.getColor(R.styleable.PinLock_keypadTextColor, Color.BLACK); view.setTextColor(color); final int background = styledAttributes .getResourceId(R.styleable.PinLock_keypadButtonShape, R.drawable.rectangle); view.setBackgroundResource(background); }
[ "private", "void", "setStyle", "(", "Button", "view", ")", "{", "final", "int", "textSize", "=", "styledAttributes", ".", "getInt", "(", "R", ".", "styleable", ".", "PinLock_keypadTextSize", ",", "12", ")", ";", "view", ".", "setTextSize", "(", "TypedValue",...
Setting Button background styles such as background, size and shape @param view Button itself
[ "Setting", "Button", "background", "styles", "such", "as", "background", "size", "and", "shape" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/components/KeypadAdapter.java#L152-L162
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/components/KeypadAdapter.java
KeypadAdapter.setValues
private void setValues(int position, Button view) { if (position == 10) { view.setText("0"); } else if (position == 9) { view.setVisibility(View.INVISIBLE); } else { view.setText(String.valueOf((position + 1) % 10)); } }
java
private void setValues(int position, Button view) { if (position == 10) { view.setText("0"); } else if (position == 9) { view.setVisibility(View.INVISIBLE); } else { view.setText(String.valueOf((position + 1) % 10)); } }
[ "private", "void", "setValues", "(", "int", "position", ",", "Button", "view", ")", "{", "if", "(", "position", "==", "10", ")", "{", "view", ".", "setText", "(", "\"0\"", ")", ";", "}", "else", "if", "(", "position", "==", "9", ")", "{", "view", ...
Setting Button text @param position Position of Button in GridView @param view Button itself
[ "Setting", "Button", "text" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/components/KeypadAdapter.java#L170-L178
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java
FeatureIO.writeBinary
public static void writeBinary(String featuresFileName, double[][] features) throws Exception { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream( featuresFileName))); for (int i = 0; i < features.length; i++) { for (int j = 0; j < features[i].length; j++) { out.writeDouble(features[i][j]); } } out.close(); }
java
public static void writeBinary(String featuresFileName, double[][] features) throws Exception { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream( featuresFileName))); for (int i = 0; i < features.length; i++) { for (int j = 0; j < features[i].length; j++) { out.writeDouble(features[i][j]); } } out.close(); }
[ "public", "static", "void", "writeBinary", "(", "String", "featuresFileName", ",", "double", "[", "]", "[", "]", "features", ")", "throws", "Exception", "{", "DataOutputStream", "out", "=", "new", "DataOutputStream", "(", "new", "BufferedOutputStream", "(", "new...
Takes a two-dimensional double array with features and writes them in a binary file. @param featuresFileName The binary file's name. @param features The features. @throws Exception
[ "Takes", "a", "two", "-", "dimensional", "double", "array", "with", "features", "and", "writes", "them", "in", "a", "binary", "file", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java#L101-L110
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java
FeatureIO.writeText
public static void writeText(String featuresFileName, double[][] features) throws Exception { BufferedWriter out = new BufferedWriter(new FileWriter(featuresFileName)); for (double[] feature : features) { for (int j = 0; j < feature.length - 1; j++) { out.write(feature[j] + ","); } out.write(feature[feature.length - 1] + "\n"); } out.close(); }
java
public static void writeText(String featuresFileName, double[][] features) throws Exception { BufferedWriter out = new BufferedWriter(new FileWriter(featuresFileName)); for (double[] feature : features) { for (int j = 0; j < feature.length - 1; j++) { out.write(feature[j] + ","); } out.write(feature[feature.length - 1] + "\n"); } out.close(); }
[ "public", "static", "void", "writeText", "(", "String", "featuresFileName", ",", "double", "[", "]", "[", "]", "features", ")", "throws", "Exception", "{", "BufferedWriter", "out", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "featuresFileName", ...
Takes a two-dimensional double array with features and writes them in a comma separated text file. @param featuresFileName The text file's name. @param features The features. @throws Exception
[ "Takes", "a", "two", "-", "dimensional", "double", "array", "with", "features", "and", "writes", "them", "in", "a", "comma", "separated", "text", "file", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java#L121-L130
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java
FeatureIO.textToBinary
public static void textToBinary(String featuresFolder, final String featureType, int featureLength) throws Exception { // read the folder containing the description files File dir = new File(featuresFolder); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith("." + featureType)) return true; else return false; } }; String[] files = dir.list(filter); for (int i = 0; i < files.length; i++) { if (i % 100 == 0) { System.out.println("Converting file " + i); } BufferedReader in = new BufferedReader(new FileReader(new File(featuresFolder + files[i]))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream( featuresFolder + files[i] + "b"))); String line; while ((line = in.readLine()) != null) { String[] nums = line.split(","); for (int j = 0; j < featureLength; j++) { out.writeDouble(Double.parseDouble(nums[j])); } } in.close(); out.close(); } }
java
public static void textToBinary(String featuresFolder, final String featureType, int featureLength) throws Exception { // read the folder containing the description files File dir = new File(featuresFolder); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith("." + featureType)) return true; else return false; } }; String[] files = dir.list(filter); for (int i = 0; i < files.length; i++) { if (i % 100 == 0) { System.out.println("Converting file " + i); } BufferedReader in = new BufferedReader(new FileReader(new File(featuresFolder + files[i]))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream( featuresFolder + files[i] + "b"))); String line; while ((line = in.readLine()) != null) { String[] nums = line.split(","); for (int j = 0; j < featureLength; j++) { out.writeDouble(Double.parseDouble(nums[j])); } } in.close(); out.close(); } }
[ "public", "static", "void", "textToBinary", "(", "String", "featuresFolder", ",", "final", "String", "featureType", ",", "int", "featureLength", ")", "throws", "Exception", "{", "// read the folder containing the description files\r", "File", "dir", "=", "new", "File", ...
Takes a folder with feature files in text format and converts them to binary. @param featuresFolder @param featureType @param featureLength @throws Exception
[ "Takes", "a", "folder", "with", "feature", "files", "in", "text", "format", "and", "converts", "them", "to", "binary", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java#L140-L171
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java
FeatureIO.binaryToText
public static void binaryToText(String featuresFolder, final String featureType, int featureLength) throws Exception { // read the folder containing the description files File dir = new File(featuresFolder); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith("." + featureType + "b")) return true; else return false; } }; String[] files = dir.list(filter); for (int i = 0; i < files.length; i++) { if (i % 100 == 0) { System.out.println("Converting file " + i); } DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream( featuresFolder + files[i]))); BufferedWriter out = new BufferedWriter(new FileWriter(new File(featuresFolder + files[i].replace("b", "")))); long counter = 0; while (true) { try { double val = in.readDouble(); out.write(String.valueOf(val)); } catch (EOFException e) { break; } counter++; if (counter % featureLength == 0) { out.write("\n"); } else { out.write(","); } } in.close(); out.close(); } }
java
public static void binaryToText(String featuresFolder, final String featureType, int featureLength) throws Exception { // read the folder containing the description files File dir = new File(featuresFolder); FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { if (name.endsWith("." + featureType + "b")) return true; else return false; } }; String[] files = dir.list(filter); for (int i = 0; i < files.length; i++) { if (i % 100 == 0) { System.out.println("Converting file " + i); } DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream( featuresFolder + files[i]))); BufferedWriter out = new BufferedWriter(new FileWriter(new File(featuresFolder + files[i].replace("b", "")))); long counter = 0; while (true) { try { double val = in.readDouble(); out.write(String.valueOf(val)); } catch (EOFException e) { break; } counter++; if (counter % featureLength == 0) { out.write("\n"); } else { out.write(","); } } in.close(); out.close(); } }
[ "public", "static", "void", "binaryToText", "(", "String", "featuresFolder", ",", "final", "String", "featureType", ",", "int", "featureLength", ")", "throws", "Exception", "{", "// read the folder containing the description files\r", "File", "dir", "=", "new", "File", ...
Takes a folder with feature files in binary format and converts them to text. @param featuresFolder @param featureType @param featureLength @throws Exception
[ "Takes", "a", "folder", "with", "feature", "files", "in", "binary", "format", "and", "converts", "them", "to", "text", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/FeatureIO.java#L181-L223
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/BasePinActivity.java
BasePinActivity.setupButtons
private void setupButtons() { cancelButton = (TextView) findViewById(R.id.cancelButton); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(CANCELLED); finish(); } }); forgetButton = (TextView) findViewById(R.id.forgotPin); forgetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onForgotPin(); setResult(FORGOT); finish(); } }); }
java
private void setupButtons() { cancelButton = (TextView) findViewById(R.id.cancelButton); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(CANCELLED); finish(); } }); forgetButton = (TextView) findViewById(R.id.forgotPin); forgetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onForgotPin(); setResult(FORGOT); finish(); } }); }
[ "private", "void", "setupButtons", "(", ")", "{", "cancelButton", "=", "(", "TextView", ")", "findViewById", "(", "R", ".", "id", ".", "cancelButton", ")", ";", "cancelButton", ".", "setOnClickListener", "(", "new", "View", ".", "OnClickListener", "(", ")", ...
Setting up cancel and forgot buttons and adding onClickListeners to them
[ "Setting", "up", "cancel", "and", "forgot", "buttons", "and", "adding", "onClickListeners", "to", "them" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/BasePinActivity.java#L76-L94
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/CSLTool.java
CSLTool.setOutputFile
@OptionDesc(longName = "output", shortName = "o", description = "write output to FILE instead of stdout", argumentName = "FILE", argumentType = ArgumentType.STRING) public void setOutputFile(String outputFile) { this.outputFile = outputFile; }
java
@OptionDesc(longName = "output", shortName = "o", description = "write output to FILE instead of stdout", argumentName = "FILE", argumentType = ArgumentType.STRING) public void setOutputFile(String outputFile) { this.outputFile = outputFile; }
[ "@", "OptionDesc", "(", "longName", "=", "\"output\"", ",", "shortName", "=", "\"o\"", ",", "description", "=", "\"write output to FILE instead of stdout\"", ",", "argumentName", "=", "\"FILE\"", ",", "argumentType", "=", "ArgumentType", ".", "STRING", ")", "public"...
Sets the name of the output file @param outputFile the file name or null if output should be written to standard out
[ "Sets", "the", "name", "of", "the", "output", "file" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/CSLTool.java#L64-L69
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/CSLTool.java
CSLTool.setCommand
@CommandDescList({ @CommandDesc(longName = "bibliography", description = "generate a bibliography", command = BibliographyCommand.class), @CommandDesc(longName = "citation", description = "generate citations", command = CitationCommand.class), @CommandDesc(longName = "list", description = "display sorted list of available citation IDs", command = ListCommand.class), @CommandDesc(longName = "lint", description = "validate citation items", command = LintCommand.class), @CommandDesc(longName = "json", description = "convert input bibliography to JSON", command = JsonCommand.class), @CommandDesc(longName = "mendeley", description = "connect to Mendeley Web", command = MendeleyCommand.class), @CommandDesc(longName = "zotero", description = "connect to Zotero", command = ZoteroCommand.class), @CommandDesc(longName = "shell", description = "run citeproc-java in interactive mode", command = ShellCommand.class), @CommandDesc(longName = "help", description = "display help for a given command", command = HelpCommand.class) }) public void setCommand(AbstractCSLToolCommand command) { if (command instanceof ProviderCommand) { this.command = new InputFileCommand((ProviderCommand)command); } else { this.command = command; } }
java
@CommandDescList({ @CommandDesc(longName = "bibliography", description = "generate a bibliography", command = BibliographyCommand.class), @CommandDesc(longName = "citation", description = "generate citations", command = CitationCommand.class), @CommandDesc(longName = "list", description = "display sorted list of available citation IDs", command = ListCommand.class), @CommandDesc(longName = "lint", description = "validate citation items", command = LintCommand.class), @CommandDesc(longName = "json", description = "convert input bibliography to JSON", command = JsonCommand.class), @CommandDesc(longName = "mendeley", description = "connect to Mendeley Web", command = MendeleyCommand.class), @CommandDesc(longName = "zotero", description = "connect to Zotero", command = ZoteroCommand.class), @CommandDesc(longName = "shell", description = "run citeproc-java in interactive mode", command = ShellCommand.class), @CommandDesc(longName = "help", description = "display help for a given command", command = HelpCommand.class) }) public void setCommand(AbstractCSLToolCommand command) { if (command instanceof ProviderCommand) { this.command = new InputFileCommand((ProviderCommand)command); } else { this.command = command; } }
[ "@", "CommandDescList", "(", "{", "@", "CommandDesc", "(", "longName", "=", "\"bibliography\"", ",", "description", "=", "\"generate a bibliography\"", ",", "command", "=", "BibliographyCommand", ".", "class", ")", ",", "@", "CommandDesc", "(", "longName", "=", ...
Sets the command to execute @param command the command
[ "Sets", "the", "command", "to", "execute" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/CSLTool.java#L86-L121
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/ErrorOutputStream.java
ErrorOutputStream.enableRed
private boolean enableRed() throws IOException { boolean oldwriting = writing; if (!writing) { writing = true; byte[] en = "\u001B[31m".getBytes(); super.write(en, 0, en.length); } return oldwriting; }
java
private boolean enableRed() throws IOException { boolean oldwriting = writing; if (!writing) { writing = true; byte[] en = "\u001B[31m".getBytes(); super.write(en, 0, en.length); } return oldwriting; }
[ "private", "boolean", "enableRed", "(", ")", "throws", "IOException", "{", "boolean", "oldwriting", "=", "writing", ";", "if", "(", "!", "writing", ")", "{", "writing", "=", "true", ";", "byte", "[", "]", "en", "=", "\"\\u001B[31m\"", ".", "getBytes", "(...
Enables colored output @return true if the colored output was already enabled before @throws IOException if writing to the underlying output stream failed
[ "Enables", "colored", "output" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/ErrorOutputStream.java#L62-L70
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/ErrorOutputStream.java
ErrorOutputStream.disableRed
private void disableRed() throws IOException { byte[] dis = "\u001B[0m".getBytes(); super.write(dis, 0, dis.length); writing = false; }
java
private void disableRed() throws IOException { byte[] dis = "\u001B[0m".getBytes(); super.write(dis, 0, dis.length); writing = false; }
[ "private", "void", "disableRed", "(", ")", "throws", "IOException", "{", "byte", "[", "]", "dis", "=", "\"\\u001B[0m\"", ".", "getBytes", "(", ")", ";", "super", ".", "write", "(", "dis", ",", "0", ",", "dis", ".", "length", ")", ";", "writing", "=",...
Disabled colored output @throws IOException if writing to the underlying output stream failed
[ "Disabled", "colored", "output" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/shell/ErrorOutputStream.java#L76-L80
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java
BibliographyFileReader.readBibliographyFile
public ItemDataProvider readBibliographyFile(File bibfile) throws FileNotFoundException, IOException { //open buffered input stream to bibliography file if (!bibfile.exists()) { throw new FileNotFoundException("Bibliography file `" + bibfile.getName() + "' does not exist"); } try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(bibfile))) { return readBibliographyFile(bis, bibfile.getName()); } }
java
public ItemDataProvider readBibliographyFile(File bibfile) throws FileNotFoundException, IOException { //open buffered input stream to bibliography file if (!bibfile.exists()) { throw new FileNotFoundException("Bibliography file `" + bibfile.getName() + "' does not exist"); } try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(bibfile))) { return readBibliographyFile(bis, bibfile.getName()); } }
[ "public", "ItemDataProvider", "readBibliographyFile", "(", "File", "bibfile", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "//open buffered input stream to bibliography file", "if", "(", "!", "bibfile", ".", "exists", "(", ")", ")", "{", "throw", "...
Reads all items from an input bibliography file and returns a provider serving these items @param bibfile the input file @return the provider @throws FileNotFoundException if the input file was not found @throws IOException if the input file could not be read
[ "Reads", "all", "items", "from", "an", "input", "bibliography", "file", "and", "returns", "a", "provider", "serving", "these", "items" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java#L103-L114
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java
BibliographyFileReader.determineFileFormat
public FileFormat determineFileFormat(File bibfile) throws FileNotFoundException, IOException { if (!bibfile.exists()) { throw new FileNotFoundException("Bibliography file `" + bibfile.getName() + "' does not exist"); } try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(bibfile))) { return determineFileFormat(bis, bibfile.getName()); } }
java
public FileFormat determineFileFormat(File bibfile) throws FileNotFoundException, IOException { if (!bibfile.exists()) { throw new FileNotFoundException("Bibliography file `" + bibfile.getName() + "' does not exist"); } try (BufferedInputStream bis = new BufferedInputStream( new FileInputStream(bibfile))) { return determineFileFormat(bis, bibfile.getName()); } }
[ "public", "FileFormat", "determineFileFormat", "(", "File", "bibfile", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "if", "(", "!", "bibfile", ".", "exists", "(", ")", ")", "{", "throw", "new", "FileNotFoundException", "(", "\"Bibliography file...
Reads the first 100 KB of the given bibliography file and tries to determine the file format @param bibfile the input file @return the file format (or {@link FileFormat#UNKNOWN} if the format could not be determined) @throws FileNotFoundException if the input file was not found @throws IOException if the input file could not be read
[ "Reads", "the", "first", "100", "KB", "of", "the", "given", "bibliography", "file", "and", "tries", "to", "determine", "the", "file", "format" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/BibliographyFileReader.java#L238-L248
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.requestCredentials
private Token requestCredentials(URL url, Method method, Token token, Map<String, String> additionalAuthParams) throws IOException { Response r = requestInternal(url, method, token, additionalAuthParams, null); InputStream is = r.getInputStream(); String response = CSLUtils.readStreamToString(is, UTF8); //create token for temporary credentials Map<String, String> sr = splitResponse(response); return responseToToken(sr); }
java
private Token requestCredentials(URL url, Method method, Token token, Map<String, String> additionalAuthParams) throws IOException { Response r = requestInternal(url, method, token, additionalAuthParams, null); InputStream is = r.getInputStream(); String response = CSLUtils.readStreamToString(is, UTF8); //create token for temporary credentials Map<String, String> sr = splitResponse(response); return responseToToken(sr); }
[ "private", "Token", "requestCredentials", "(", "URL", "url", ",", "Method", "method", ",", "Token", "token", ",", "Map", "<", "String", ",", "String", ">", "additionalAuthParams", ")", "throws", "IOException", "{", "Response", "r", "=", "requestInternal", "(",...
Sends a request to the server and returns a token @param url the URL to send the request to @param method the HTTP request method @param token a token used for authorization (may be null if the app is not authorized yet) @param additionalAuthParams additional parameters that should be added to the <code>Authorization</code> header @return the token @throws IOException if the request was not successful @throws RequestException if the server returned an error @throws UnauthorizedException if the request is not authorized
[ "Sends", "a", "request", "to", "the", "server", "and", "returns", "a", "token" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L131-L140
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.responseToToken
protected Token responseToToken(Map<String, String> response) { return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET)); }
java
protected Token responseToToken(Map<String, String> response) { return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET)); }
[ "protected", "Token", "responseToToken", "(", "Map", "<", "String", ",", "String", ">", "response", ")", "{", "return", "new", "Token", "(", "response", ".", "get", "(", "OAUTH_TOKEN", ")", ",", "response", ".", "get", "(", "OAUTH_TOKEN_SECRET", ")", ")", ...
Parses a service response and creates a token @param response the response @return the token
[ "Parses", "a", "service", "response", "and", "creates", "a", "token" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L147-L149
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.requestInternal
private Response requestInternal(URL url, Method method, Token token, Map<String, String> additionalAuthParams, Map<String, String> additionalHeaders) throws IOException { //prepare HTTP connection HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setInstanceFollowRedirects(true); conn.setRequestMethod(method.toString()); conn.setRequestProperty(HEADER_HOST, makeBaseUri(url)); String timestamp = makeTimestamp(); String nonce = makeNonce(timestamp); //create OAuth parameters Map<String, String> authParams = new HashMap<>(); if (additionalAuthParams != null) { authParams.putAll(additionalAuthParams); } if (token != null) { authParams.put(OAUTH_TOKEN, token.getToken()); } authParams.put(OAUTH_CONSUMER_KEY, consumerKey); authParams.put(OAUTH_SIGNATURE_METHOD, HMAC_SHA1_METHOD); authParams.put(OAUTH_TIMESTAMP, timestamp); authParams.put(OAUTH_NONCE, nonce); authParams.put(OAUTH_VERSION, OAUTH_IMPL_VERSION); //create signature from method, url, and OAuth parameters String signature = makeSignature(method.toString(), url, authParams, token); //put OAuth parameters into "Authorization" header StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> e : authParams.entrySet()) { appendAuthParam(sb, e.getKey(), e.getValue()); } appendAuthParam(sb, OAUTH_SIGNATURE, signature); conn.setRequestProperty(HEADER_AUTHORIZATION, "OAuth " + sb.toString()); if (additionalHeaders != null) { for (Map.Entry<String, String> e : additionalHeaders.entrySet()) { conn.setRequestProperty(e.getKey(), e.getValue()); } } //perform request conn.connect(); //check response if (conn.getResponseCode() == 401) { throw new UnauthorizedException("Not authorized"); } else if (conn.getResponseCode() != 200) { throw new RequestException("HTTP request failed with error code: " + conn.getResponseCode()); } return new Response(conn); }
java
private Response requestInternal(URL url, Method method, Token token, Map<String, String> additionalAuthParams, Map<String, String> additionalHeaders) throws IOException { //prepare HTTP connection HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setInstanceFollowRedirects(true); conn.setRequestMethod(method.toString()); conn.setRequestProperty(HEADER_HOST, makeBaseUri(url)); String timestamp = makeTimestamp(); String nonce = makeNonce(timestamp); //create OAuth parameters Map<String, String> authParams = new HashMap<>(); if (additionalAuthParams != null) { authParams.putAll(additionalAuthParams); } if (token != null) { authParams.put(OAUTH_TOKEN, token.getToken()); } authParams.put(OAUTH_CONSUMER_KEY, consumerKey); authParams.put(OAUTH_SIGNATURE_METHOD, HMAC_SHA1_METHOD); authParams.put(OAUTH_TIMESTAMP, timestamp); authParams.put(OAUTH_NONCE, nonce); authParams.put(OAUTH_VERSION, OAUTH_IMPL_VERSION); //create signature from method, url, and OAuth parameters String signature = makeSignature(method.toString(), url, authParams, token); //put OAuth parameters into "Authorization" header StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> e : authParams.entrySet()) { appendAuthParam(sb, e.getKey(), e.getValue()); } appendAuthParam(sb, OAUTH_SIGNATURE, signature); conn.setRequestProperty(HEADER_AUTHORIZATION, "OAuth " + sb.toString()); if (additionalHeaders != null) { for (Map.Entry<String, String> e : additionalHeaders.entrySet()) { conn.setRequestProperty(e.getKey(), e.getValue()); } } //perform request conn.connect(); //check response if (conn.getResponseCode() == 401) { throw new UnauthorizedException("Not authorized"); } else if (conn.getResponseCode() != 200) { throw new RequestException("HTTP request failed with error code: " + conn.getResponseCode()); } return new Response(conn); }
[ "private", "Response", "requestInternal", "(", "URL", "url", ",", "Method", "method", ",", "Token", "token", ",", "Map", "<", "String", ",", "String", ">", "additionalAuthParams", ",", "Map", "<", "String", ",", "String", ">", "additionalHeaders", ")", "thro...
Sends a request to the server and returns an input stream from which the response can be read. The caller is responsible for consuming the input stream's content and for closing the stream. @param url the URL to send the request to @param method the HTTP request method @param token a token used for authorization (may be null if the app is not authorized yet) @param additionalAuthParams additional parameters that should be added to the <code>Authorization</code> header (may be null) @param additionalHeaders additional HTTP headers (may be null) @return a response @throws IOException if the request was not successful @throws RequestException if the server returned an error @throws UnauthorizedException if the request is not authorized
[ "Sends", "a", "request", "to", "the", "server", "and", "returns", "an", "input", "stream", "from", "which", "the", "response", "can", "be", "read", ".", "The", "caller", "is", "responsible", "for", "consuming", "the", "input", "stream", "s", "content", "an...
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L167-L224
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.appendAuthParam
private static void appendAuthParam(StringBuilder sb, String key, String value) { if (sb.length() > 0) { sb.append(","); } sb.append(key); sb.append("=\""); sb.append(value); sb.append("\""); }
java
private static void appendAuthParam(StringBuilder sb, String key, String value) { if (sb.length() > 0) { sb.append(","); } sb.append(key); sb.append("=\""); sb.append(value); sb.append("\""); }
[ "private", "static", "void", "appendAuthParam", "(", "StringBuilder", "sb", ",", "String", "key", ",", "String", "value", ")", "{", "if", "(", "sb", ".", "length", "(", ")", ">", "0", ")", "{", "sb", ".", "append", "(", "\",\"", ")", ";", "}", "sb"...
Appends an authorization parameter to the given string builder @param sb the string builder @param key the parameter's key @param value the parameter's value
[ "Appends", "an", "authorization", "parameter", "to", "the", "given", "string", "builder" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L232-L240
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.makeNonce
private String makeNonce(String timestamp) { byte[] bytes = new byte[10]; random.nextBytes(bytes); StringBuilder sb = new StringBuilder(timestamp); sb.append("-"); for (int i = 0; i < bytes.length; ++i) { String b = Integer.toHexString(bytes[i] & 0xff); if (b.length() < 2) { sb.append("0"); } sb.append(b); } return sb.toString(); }
java
private String makeNonce(String timestamp) { byte[] bytes = new byte[10]; random.nextBytes(bytes); StringBuilder sb = new StringBuilder(timestamp); sb.append("-"); for (int i = 0; i < bytes.length; ++i) { String b = Integer.toHexString(bytes[i] & 0xff); if (b.length() < 2) { sb.append("0"); } sb.append(b); } return sb.toString(); }
[ "private", "String", "makeNonce", "(", "String", "timestamp", ")", "{", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "10", "]", ";", "random", ".", "nextBytes", "(", "bytes", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "ti...
Generates a nonce for a request using a secure random number generator @param timestamp the request's timestamp (generated by {@link #makeTimestamp()}) @return the nonce
[ "Generates", "a", "nonce", "for", "a", "request", "using", "a", "secure", "random", "number", "generator" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L255-L268
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.makeBaseUri
private static String makeBaseUri(URL url) { String r = url.getProtocol().toLowerCase() + "://" + url.getHost().toLowerCase(); if ((url.getProtocol().equalsIgnoreCase("http") && url.getPort() != -1 && url.getPort() != 80) || (url.getProtocol().equalsIgnoreCase("https") && url.getPort() != -1 && url.getPort() != 443)) { r += ":" + url.getPort(); } return r; }
java
private static String makeBaseUri(URL url) { String r = url.getProtocol().toLowerCase() + "://" + url.getHost().toLowerCase(); if ((url.getProtocol().equalsIgnoreCase("http") && url.getPort() != -1 && url.getPort() != 80) || (url.getProtocol().equalsIgnoreCase("https") && url.getPort() != -1 && url.getPort() != 443)) { r += ":" + url.getPort(); } return r; }
[ "private", "static", "String", "makeBaseUri", "(", "URL", "url", ")", "{", "String", "r", "=", "url", ".", "getProtocol", "(", ")", ".", "toLowerCase", "(", ")", "+", "\"://\"", "+", "url", ".", "getHost", "(", ")", ".", "toLowerCase", "(", ")", ";",...
Generates a base URI from a given URL. The base URI consists of the protocol, the host, and also the port if its not the default port for the given protocol. @param url the URL from which the URI should be generated @return the base URI
[ "Generates", "a", "base", "URI", "from", "a", "given", "URL", ".", "The", "base", "URI", "consists", "of", "the", "protocol", "the", "host", "and", "also", "the", "port", "if", "its", "not", "the", "default", "port", "for", "the", "given", "protocol", ...
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L277-L287
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.splitAndEncodeParams
private static List<String> splitAndEncodeParams(URL url) { if (url.getQuery() == null) { return new ArrayList<>(); } String[] params = url.getQuery().split("&"); List<String> result = new ArrayList<>(params.length); for (String p : params) { String[] kv = p.split("="); kv[0] = PercentEncoding.decode(kv[0]); kv[1] = PercentEncoding.decode(kv[1]); kv[0] = PercentEncoding.encode(kv[0]); kv[1] = PercentEncoding.encode(kv[1]); String np = kv[0] + "=" + kv[1]; result.add(np); } return result; }
java
private static List<String> splitAndEncodeParams(URL url) { if (url.getQuery() == null) { return new ArrayList<>(); } String[] params = url.getQuery().split("&"); List<String> result = new ArrayList<>(params.length); for (String p : params) { String[] kv = p.split("="); kv[0] = PercentEncoding.decode(kv[0]); kv[1] = PercentEncoding.decode(kv[1]); kv[0] = PercentEncoding.encode(kv[0]); kv[1] = PercentEncoding.encode(kv[1]); String np = kv[0] + "=" + kv[1]; result.add(np); } return result; }
[ "private", "static", "List", "<", "String", ">", "splitAndEncodeParams", "(", "URL", "url", ")", "{", "if", "(", "url", ".", "getQuery", "(", ")", "==", "null", ")", "{", "return", "new", "ArrayList", "<>", "(", ")", ";", "}", "String", "[", "]", "...
Splits the query parameters of the given URL, encodes their keys and values and puts each key-value pair in a list @param url the URL @return the encoded parameters
[ "Splits", "the", "query", "parameters", "of", "the", "given", "URL", "encodes", "their", "keys", "and", "values", "and", "puts", "each", "key", "-", "value", "pair", "in", "a", "list" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L295-L311
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java
OAuth1.makeSignature
private String makeSignature(String method, URL url, Map<String, String> authParams, Token token) { //encode method and URL StringBuilder sb = new StringBuilder(method + "&" + PercentEncoding.encode(makeBaseUri(url) + url.getPath())); //encode parameters List<String> params = splitAndEncodeParams(url); for (Map.Entry<String, String> p : authParams.entrySet()) { params.add(PercentEncoding.encode(p.getKey()) + "=" + PercentEncoding.encode(p.getValue())); } //sort parameters and append them to the base string Collections.sort(params); StringBuilder pb = new StringBuilder(); for (String p : params) { if (pb.length() > 0) { pb.append("&"); } pb.append(p); } sb.append("&"); sb.append(PercentEncoding.encode(pb.toString())); //create base string and key for hash function String baseString = sb.toString(); String tokenSecret = token != null ? token.getSecret() : ""; String key = PercentEncoding.encode(consumerSecret) + "&" + PercentEncoding.encode(tokenSecret); //hash base string with the secret key try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(UTF8), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(secretKey); byte[] bytes = mac.doFinal(baseString.getBytes(UTF8)); return PercentEncoding.encode(DatatypeConverter.printBase64Binary(bytes)); } catch (UnsupportedEncodingException e) { //should never happen throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { //should never happen throw new RuntimeException(e); } catch (InvalidKeyException e) { //should never happen throw new RuntimeException(e); } }
java
private String makeSignature(String method, URL url, Map<String, String> authParams, Token token) { //encode method and URL StringBuilder sb = new StringBuilder(method + "&" + PercentEncoding.encode(makeBaseUri(url) + url.getPath())); //encode parameters List<String> params = splitAndEncodeParams(url); for (Map.Entry<String, String> p : authParams.entrySet()) { params.add(PercentEncoding.encode(p.getKey()) + "=" + PercentEncoding.encode(p.getValue())); } //sort parameters and append them to the base string Collections.sort(params); StringBuilder pb = new StringBuilder(); for (String p : params) { if (pb.length() > 0) { pb.append("&"); } pb.append(p); } sb.append("&"); sb.append(PercentEncoding.encode(pb.toString())); //create base string and key for hash function String baseString = sb.toString(); String tokenSecret = token != null ? token.getSecret() : ""; String key = PercentEncoding.encode(consumerSecret) + "&" + PercentEncoding.encode(tokenSecret); //hash base string with the secret key try { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(UTF8), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(secretKey); byte[] bytes = mac.doFinal(baseString.getBytes(UTF8)); return PercentEncoding.encode(DatatypeConverter.printBase64Binary(bytes)); } catch (UnsupportedEncodingException e) { //should never happen throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { //should never happen throw new RuntimeException(e); } catch (InvalidKeyException e) { //should never happen throw new RuntimeException(e); } }
[ "private", "String", "makeSignature", "(", "String", "method", ",", "URL", "url", ",", "Map", "<", "String", ",", "String", ">", "authParams", ",", "Token", "token", ")", "{", "//encode method and URL", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ...
Generates a OAuth signature from the HTTP method, the URL, and the authorization parameters @param method the HTTP method @param url the URL @param authParams the authorization parameters @param token the authorization token used for this request (may be null) @return the signature
[ "Generates", "a", "OAuth", "signature", "from", "the", "HTTP", "method", "the", "URL", "and", "the", "authorization", "parameters" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/OAuth1.java#L337-L386
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/ShellCommand.java
ShellCommand.mainLoop
private String mainLoop(ConsoleReader reader, PrintWriter cout) throws IOException { InputReader lr = new ConsoleInputReader(reader); String line; while ((line = reader.readLine()) != null) { if (line.isEmpty()) { continue; } String[] args = ShellCommandParser.split(line); Result pr; try { pr = ShellCommandParser.parse(args, EXCLUDED_COMMANDS); } catch (OptionParserException e) { //there is an option, only commands are allowed in the //interactive shell error(e.getMessage()); continue; } catch (IntrospectionException e) { //should never happen throw new RuntimeException(e); } Class<? extends Command> cmdClass = pr.getFirstCommand(); if (cmdClass == ShellExitCommand.class || cmdClass == ShellQuitCommand.class) { break; } else if (cmdClass == null) { error("unknown command `" + args[0] + "'"); continue; } Command cmd; try { cmd = cmdClass.newInstance(); } catch (Exception e) { //should never happen throw new RuntimeException(e); } boolean acceptsInputFile = false; if (cmd instanceof ProviderCommand) { cmd = new InputFileCommand((ProviderCommand)cmd); acceptsInputFile = true; } args = ArrayUtils.subarray(args, 1, args.length); args = augmentCommand(args, pr.getLastCommand(), acceptsInputFile); try { cmd.run(args, lr, cout); } catch (OptionParserException e) { error(e.getMessage()); } } return line; }
java
private String mainLoop(ConsoleReader reader, PrintWriter cout) throws IOException { InputReader lr = new ConsoleInputReader(reader); String line; while ((line = reader.readLine()) != null) { if (line.isEmpty()) { continue; } String[] args = ShellCommandParser.split(line); Result pr; try { pr = ShellCommandParser.parse(args, EXCLUDED_COMMANDS); } catch (OptionParserException e) { //there is an option, only commands are allowed in the //interactive shell error(e.getMessage()); continue; } catch (IntrospectionException e) { //should never happen throw new RuntimeException(e); } Class<? extends Command> cmdClass = pr.getFirstCommand(); if (cmdClass == ShellExitCommand.class || cmdClass == ShellQuitCommand.class) { break; } else if (cmdClass == null) { error("unknown command `" + args[0] + "'"); continue; } Command cmd; try { cmd = cmdClass.newInstance(); } catch (Exception e) { //should never happen throw new RuntimeException(e); } boolean acceptsInputFile = false; if (cmd instanceof ProviderCommand) { cmd = new InputFileCommand((ProviderCommand)cmd); acceptsInputFile = true; } args = ArrayUtils.subarray(args, 1, args.length); args = augmentCommand(args, pr.getLastCommand(), acceptsInputFile); try { cmd.run(args, lr, cout); } catch (OptionParserException e) { error(e.getMessage()); } } return line; }
[ "private", "String", "mainLoop", "(", "ConsoleReader", "reader", ",", "PrintWriter", "cout", ")", "throws", "IOException", "{", "InputReader", "lr", "=", "new", "ConsoleInputReader", "(", "reader", ")", ";", "String", "line", ";", "while", "(", "(", "line", ...
Runs the shell's main loop @param reader the console reader used to read user input from the command line @param cout the output stream @return the last line read or null if the user pressed Ctrl+D and the input stream has ended @throws IOException if an I/O error occurs
[ "Runs", "the", "shell", "s", "main", "loop" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/ShellCommand.java#L137-L196
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/ShellCommand.java
ShellCommand.augmentCommand
private String[] augmentCommand(String[] args, Class<? extends Command> cmd, boolean acceptsInputFile) { OptionGroup<ID> options; try { if (acceptsInputFile) { options = OptionIntrospector.introspect(cmd, InputFileCommand.class); } else { options = OptionIntrospector.introspect(cmd); } } catch (IntrospectionException e) { //should never happen throw new RuntimeException(e); } ShellContext sc = ShellContext.current(); for (Option<ID> o : options.getOptions()) { if (o.getLongName().equals("style")) { args = ArrayUtils.add(args, "--style"); args = ArrayUtils.add(args, sc.getStyle()); } else if (o.getLongName().equals("locale")) { args = ArrayUtils.add(args, "--locale"); args = ArrayUtils.add(args, sc.getLocale()); } else if (o.getLongName().equals("format")) { args = ArrayUtils.add(args, "--format"); args = ArrayUtils.add(args, sc.getFormat()); } else if (o.getLongName().equals("input") && sc.getInputFile() != null && !sc.getInputFile().isEmpty()) { args = ArrayUtils.add(args, "--input"); args = ArrayUtils.add(args, sc.getInputFile()); } } return args; }
java
private String[] augmentCommand(String[] args, Class<? extends Command> cmd, boolean acceptsInputFile) { OptionGroup<ID> options; try { if (acceptsInputFile) { options = OptionIntrospector.introspect(cmd, InputFileCommand.class); } else { options = OptionIntrospector.introspect(cmd); } } catch (IntrospectionException e) { //should never happen throw new RuntimeException(e); } ShellContext sc = ShellContext.current(); for (Option<ID> o : options.getOptions()) { if (o.getLongName().equals("style")) { args = ArrayUtils.add(args, "--style"); args = ArrayUtils.add(args, sc.getStyle()); } else if (o.getLongName().equals("locale")) { args = ArrayUtils.add(args, "--locale"); args = ArrayUtils.add(args, sc.getLocale()); } else if (o.getLongName().equals("format")) { args = ArrayUtils.add(args, "--format"); args = ArrayUtils.add(args, sc.getFormat()); } else if (o.getLongName().equals("input") && sc.getInputFile() != null && !sc.getInputFile().isEmpty()) { args = ArrayUtils.add(args, "--input"); args = ArrayUtils.add(args, sc.getInputFile()); } } return args; }
[ "private", "String", "[", "]", "augmentCommand", "(", "String", "[", "]", "args", ",", "Class", "<", "?", "extends", "Command", ">", "cmd", ",", "boolean", "acceptsInputFile", ")", "{", "OptionGroup", "<", "ID", ">", "options", ";", "try", "{", "if", "...
Augments the given command line with context variables @param args the current command line @param cmd the last parsed command in the command line @param acceptsInputFile true if the given command accepts an input file @return the new command line
[ "Augments", "the", "given", "command", "line", "with", "context", "variables" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/ShellCommand.java#L205-L238
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/components/StatusDots.java
StatusDots.addDots
private void addDots(int length) { removeAllViews(); final int pinLength = styledAttributes.getInt(R.styleable.PinLock_pinLength, 4); for (int i = 0; i < pinLength; i++) { Dot dot = new Dot(context, styledAttributes, i < length); addView(dot); } }
java
private void addDots(int length) { removeAllViews(); final int pinLength = styledAttributes.getInt(R.styleable.PinLock_pinLength, 4); for (int i = 0; i < pinLength; i++) { Dot dot = new Dot(context, styledAttributes, i < length); addView(dot); } }
[ "private", "void", "addDots", "(", "int", "length", ")", "{", "removeAllViews", "(", ")", ";", "final", "int", "pinLength", "=", "styledAttributes", ".", "getInt", "(", "R", ".", "styleable", ".", "PinLock_pinLength", ",", "4", ")", ";", "for", "(", "int...
Adding Dot objects to layout @param length Length of PIN entered so far
[ "Adding", "Dot", "objects", "to", "layout" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/components/StatusDots.java#L59-L66
train
manupsunny/PinLock
pinlock/src/main/java/com/manusunny/pinlock/components/Dot.java
Dot.setBackground
private void setBackground(boolean filled) { if (filled) { final int background = styledAttributes .getResourceId(R.styleable.PinLock_statusFilledBackground, R.drawable.dot_filled); setBackgroundResource(background); } else { final int background = styledAttributes .getResourceId(R.styleable.PinLock_statusEmptyBackground, R.drawable.dot_empty); setBackgroundResource(background); } }
java
private void setBackground(boolean filled) { if (filled) { final int background = styledAttributes .getResourceId(R.styleable.PinLock_statusFilledBackground, R.drawable.dot_filled); setBackgroundResource(background); } else { final int background = styledAttributes .getResourceId(R.styleable.PinLock_statusEmptyBackground, R.drawable.dot_empty); setBackgroundResource(background); } }
[ "private", "void", "setBackground", "(", "boolean", "filled", ")", "{", "if", "(", "filled", ")", "{", "final", "int", "background", "=", "styledAttributes", ".", "getResourceId", "(", "R", ".", "styleable", ".", "PinLock_statusFilledBackground", ",", "R", "."...
Setting up background for the view. Should pass shapes for both filled and empty dots. Otherwise will use the default backgrounds
[ "Setting", "up", "background", "for", "the", "view", ".", "Should", "pass", "shapes", "for", "both", "filled", "and", "empty", "dots", ".", "Otherwise", "will", "use", "the", "default", "backgrounds" ]
bbb5d53cc57d4e163be01a95157d335231b55dc0
https://github.com/manupsunny/PinLock/blob/bbb5d53cc57d4e163be01a95157d335231b55dc0/pinlock/src/main/java/com/manusunny/pinlock/components/Dot.java#L70-L80
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java
JsonLexer.readNextToken
public Type readNextToken() throws IOException { int c; if (currentCharacter >= 0 && !Character.isWhitespace(currentCharacter)) { //there's still a character left from the last step c = currentCharacter; currentCharacter = -1; } else { //skip whitespace characters c = skipWhitespace(); } if (c < 0) { return null; } //handle character if (c =='{') { currentTokenType = Type.START_OBJECT; } else if (c == '}') { currentTokenType = Type.END_OBJECT; } else if (c == '[') { currentTokenType = Type.START_ARRAY; } else if (c == ']') { currentTokenType = Type.END_ARRAY; } else if (c == ':') { currentTokenType = Type.COLON; } else if (c == ',') { currentTokenType = Type.COMMA; } else if (c == '"') { currentTokenType = Type.STRING; } else if (c == '-' || (c >= '0' && c<= '9')) { currentTokenType = Type.NUMBER; //the next token is a number. save the last character read because //readNumber() will need it. currentCharacter = c; } else if (c == 't') { int c2 = r.read(); int c3 = r.read(); int c4 = r.read(); if (c2 == 'r' && c3 == 'u' & c4 == 'e') { currentTokenType = Type.TRUE; } else { currentTokenType = null; } } else if (c == 'f') { int c2 = r.read(); int c3 = r.read(); int c4 = r.read(); int c5 = r.read(); if (c2 == 'a' && c3 == 'l' & c4 == 's' && c5 == 'e') { currentTokenType = Type.FALSE; } else { currentTokenType = null; } } else if (c == 'n') { int c2 = r.read(); int c3 = r.read(); int c4 = r.read(); if (c2 == 'u' && c3 == 'l' & c4 == 'l') { currentTokenType = Type.NULL; } else { currentTokenType = null; } } else { currentTokenType = null; } if (currentTokenType == null) { throw new IllegalStateException("Unrecognized token: " + (char)c); } return currentTokenType; }
java
public Type readNextToken() throws IOException { int c; if (currentCharacter >= 0 && !Character.isWhitespace(currentCharacter)) { //there's still a character left from the last step c = currentCharacter; currentCharacter = -1; } else { //skip whitespace characters c = skipWhitespace(); } if (c < 0) { return null; } //handle character if (c =='{') { currentTokenType = Type.START_OBJECT; } else if (c == '}') { currentTokenType = Type.END_OBJECT; } else if (c == '[') { currentTokenType = Type.START_ARRAY; } else if (c == ']') { currentTokenType = Type.END_ARRAY; } else if (c == ':') { currentTokenType = Type.COLON; } else if (c == ',') { currentTokenType = Type.COMMA; } else if (c == '"') { currentTokenType = Type.STRING; } else if (c == '-' || (c >= '0' && c<= '9')) { currentTokenType = Type.NUMBER; //the next token is a number. save the last character read because //readNumber() will need it. currentCharacter = c; } else if (c == 't') { int c2 = r.read(); int c3 = r.read(); int c4 = r.read(); if (c2 == 'r' && c3 == 'u' & c4 == 'e') { currentTokenType = Type.TRUE; } else { currentTokenType = null; } } else if (c == 'f') { int c2 = r.read(); int c3 = r.read(); int c4 = r.read(); int c5 = r.read(); if (c2 == 'a' && c3 == 'l' & c4 == 's' && c5 == 'e') { currentTokenType = Type.FALSE; } else { currentTokenType = null; } } else if (c == 'n') { int c2 = r.read(); int c3 = r.read(); int c4 = r.read(); if (c2 == 'u' && c3 == 'l' & c4 == 'l') { currentTokenType = Type.NULL; } else { currentTokenType = null; } } else { currentTokenType = null; } if (currentTokenType == null) { throw new IllegalStateException("Unrecognized token: " + (char)c); } return currentTokenType; }
[ "public", "Type", "readNextToken", "(", ")", "throws", "IOException", "{", "int", "c", ";", "if", "(", "currentCharacter", ">=", "0", "&&", "!", "Character", ".", "isWhitespace", "(", "currentCharacter", ")", ")", "{", "//there's still a character left from the la...
Reads the next token from the stream @return the token @throws IOException if the stream could not be read
[ "Reads", "the", "next", "token", "from", "the", "stream" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java#L108-L179
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java
JsonLexer.skipWhitespace
private int skipWhitespace() throws IOException { int c = 0; do { c = r.read(); if (c < 0) { return -1; } } while (Character.isWhitespace(c)); return c; }
java
private int skipWhitespace() throws IOException { int c = 0; do { c = r.read(); if (c < 0) { return -1; } } while (Character.isWhitespace(c)); return c; }
[ "private", "int", "skipWhitespace", "(", ")", "throws", "IOException", "{", "int", "c", "=", "0", ";", "do", "{", "c", "=", "r", ".", "read", "(", ")", ";", "if", "(", "c", "<", "0", ")", "{", "return", "-", "1", ";", "}", "}", "while", "(", ...
Reads characters from the stream until a non-whitespace character has been found. Reads at least one character. @return the next non-whitespace character @throws IOException if the stream could not be read
[ "Reads", "characters", "from", "the", "stream", "until", "a", "non", "-", "whitespace", "character", "has", "been", "found", ".", "Reads", "at", "least", "one", "character", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java#L187-L197
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java
JsonLexer.readString
public String readString() throws IOException { StringBuilder result = new StringBuilder(); while (true) { int c = r.read(); if (c < 0) { throw new IllegalStateException("Premature end of stream"); } else if (c == '"') { break; } else if (c == '\\') { int c2 = r.read(); if (c2 == '"' || c2 == '\\' || c2 == '/') { result.append((char)c2); } else if (c2 == 'b') { result.append("\b"); } else if (c2 == 'f') { result.append("\f"); } else if (c2 == 'n') { result.append("\n"); } else if (c2 == 'r') { result.append("\r"); } else if (c2 == 't') { result.append("\t"); } else if (c2 == 'u') { int d1 = r.read(); int d2 = r.read(); int d3 = r.read(); int d4 = r.read(); checkHexDigit(d1); checkHexDigit(d2); checkHexDigit(d3); checkHexDigit(d4); int e = Character.digit(d1, 16); e = (e << 4) + Character.digit(d2, 16); e = (e << 4) + Character.digit(d3, 16); e = (e << 4) + Character.digit(d4, 16); result.append((char)e); } } else { result.append((char)c); } } return result.toString(); }
java
public String readString() throws IOException { StringBuilder result = new StringBuilder(); while (true) { int c = r.read(); if (c < 0) { throw new IllegalStateException("Premature end of stream"); } else if (c == '"') { break; } else if (c == '\\') { int c2 = r.read(); if (c2 == '"' || c2 == '\\' || c2 == '/') { result.append((char)c2); } else if (c2 == 'b') { result.append("\b"); } else if (c2 == 'f') { result.append("\f"); } else if (c2 == 'n') { result.append("\n"); } else if (c2 == 'r') { result.append("\r"); } else if (c2 == 't') { result.append("\t"); } else if (c2 == 'u') { int d1 = r.read(); int d2 = r.read(); int d3 = r.read(); int d4 = r.read(); checkHexDigit(d1); checkHexDigit(d2); checkHexDigit(d3); checkHexDigit(d4); int e = Character.digit(d1, 16); e = (e << 4) + Character.digit(d2, 16); e = (e << 4) + Character.digit(d3, 16); e = (e << 4) + Character.digit(d4, 16); result.append((char)e); } } else { result.append((char)c); } } return result.toString(); }
[ "public", "String", "readString", "(", ")", "throws", "IOException", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "while", "(", "true", ")", "{", "int", "c", "=", "r", ".", "read", "(", ")", ";", "if", "(", "c", "<", ...
Reads a string from the stream @return the string @throws IOException if the stream could not be read
[ "Reads", "a", "string", "from", "the", "stream" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java#L204-L246
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java
JsonLexer.checkHexDigit
private static void checkHexDigit(int c) { if (!Character.isDigit(c) && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) { throw new IllegalStateException("Not a hexadecimal digit: " + c); } }
java
private static void checkHexDigit(int c) { if (!Character.isDigit(c) && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) { throw new IllegalStateException("Not a hexadecimal digit: " + c); } }
[ "private", "static", "void", "checkHexDigit", "(", "int", "c", ")", "{", "if", "(", "!", "Character", ".", "isDigit", "(", "c", ")", "&&", "!", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "&&", "!", "(", "c", ">=", "'", "'", "...
Checks if the given character is a hexadecimal character @param c the character @throws IllegalStateException if the character is not hexadecimal
[ "Checks", "if", "the", "given", "character", "is", "a", "hexadecimal", "character" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java#L253-L257
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java
JsonLexer.readNumber
public Number readNumber() throws IOException { //there should be a character left from readNextToken! if (currentCharacter < 0) { throw new IllegalStateException("Missed first digit"); } //read sign boolean negative = false; if (currentCharacter == '-') { negative = true; currentCharacter = r.read(); } //try to real an integer first long result = 0; while (currentCharacter >= 0) { if (currentCharacter >= '0' && currentCharacter <= '9') { result = result * 10 + currentCharacter - '0'; } else if (currentCharacter == '.') { //there is a dot. read real number return readReal(result, negative); } else { break; } currentCharacter = r.read(); } return negative ? -result : result; }
java
public Number readNumber() throws IOException { //there should be a character left from readNextToken! if (currentCharacter < 0) { throw new IllegalStateException("Missed first digit"); } //read sign boolean negative = false; if (currentCharacter == '-') { negative = true; currentCharacter = r.read(); } //try to real an integer first long result = 0; while (currentCharacter >= 0) { if (currentCharacter >= '0' && currentCharacter <= '9') { result = result * 10 + currentCharacter - '0'; } else if (currentCharacter == '.') { //there is a dot. read real number return readReal(result, negative); } else { break; } currentCharacter = r.read(); } return negative ? -result : result; }
[ "public", "Number", "readNumber", "(", ")", "throws", "IOException", "{", "//there should be a character left from readNextToken!", "if", "(", "currentCharacter", "<", "0", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Missed first digit\"", ")", ";", "}", ...
Reads a number from the stream @return the number @throws IOException if the stream could not be read
[ "Reads", "a", "number", "from", "the", "stream" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java#L264-L292
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java
JsonLexer.readReal
private Number readReal(long prev, boolean negative) throws IOException { StringBuilder b = new StringBuilder(prev + "."); boolean exponent = false; boolean expsign = false; do { currentCharacter = r.read(); if (currentCharacter >= '0' && currentCharacter <= '9') { b.append((char)currentCharacter); } else if (currentCharacter == 'e' || currentCharacter == 'E') { if (exponent) { break; } b.append((char)currentCharacter); exponent = true; } else if (currentCharacter == '-' || currentCharacter == '+') { if (expsign) { break; } b.append((char)currentCharacter); expsign = true; } else { break; } } while (currentCharacter >= 0); double result = Double.parseDouble(b.toString()); return negative ? -result : result; }
java
private Number readReal(long prev, boolean negative) throws IOException { StringBuilder b = new StringBuilder(prev + "."); boolean exponent = false; boolean expsign = false; do { currentCharacter = r.read(); if (currentCharacter >= '0' && currentCharacter <= '9') { b.append((char)currentCharacter); } else if (currentCharacter == 'e' || currentCharacter == 'E') { if (exponent) { break; } b.append((char)currentCharacter); exponent = true; } else if (currentCharacter == '-' || currentCharacter == '+') { if (expsign) { break; } b.append((char)currentCharacter); expsign = true; } else { break; } } while (currentCharacter >= 0); double result = Double.parseDouble(b.toString()); return negative ? -result : result; }
[ "private", "Number", "readReal", "(", "long", "prev", ",", "boolean", "negative", ")", "throws", "IOException", "{", "StringBuilder", "b", "=", "new", "StringBuilder", "(", "prev", "+", "\".\"", ")", ";", "boolean", "exponent", "=", "false", ";", "boolean", ...
Reads a real number from the stream @param prev the digits read to far @param negative true if the number is negative @return the real number @throws IOException if the stream could not be read
[ "Reads", "a", "real", "number", "from", "the", "stream" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/JsonLexer.java#L301-L328
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/PercentEncoding.java
PercentEncoding.decode
public static String decode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { //should never happen throw new RuntimeException(e); } }
java
public static String decode(String str) { try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { //should never happen throw new RuntimeException(e); } }
[ "public", "static", "String", "decode", "(", "String", "str", ")", "{", "try", "{", "return", "URLDecoder", ".", "decode", "(", "str", ",", "\"UTF-8\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "//should never happen", "thr...
Decodes a string @param str the string @return the decoded string
[ "Decodes", "a", "string" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/oauth/PercentEncoding.java#L47-L54
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/AbstractRemoteCommand.java
AbstractRemoteCommand.authorize
private boolean authorize(RemoteConnector mc, InputReader in) { //get authorization URL String authUrl; try { authUrl = mc.getAuthorizationURL(); } catch (IOException e) { error("could not get authorization URL from remote server."); return false; } //ask user to point browser to authorization URL System.out.println("This tool requires authorization. Please point your " + "web browser to the\nfollowing URL and follow the instructions:\n"); System.out.println(authUrl); System.out.println(); //open authorization tool in browser if (Desktop.isDesktopSupported()) { Desktop d = Desktop.getDesktop(); if (d.isSupported(Desktop.Action.BROWSE)) { try { d.browse(new URI(authUrl)); } catch (Exception e) { //ignore. let the user open the browser manually. } } } //read verification code from console String verificationCode; try { verificationCode = in.readLine("Enter verification code: "); } catch (IOException e) { throw new RuntimeException("Could not read from console."); } if (verificationCode == null || verificationCode.isEmpty()) { //user aborted process return false; } //authorize... try { System.out.println("Connecting ..."); mc.authorize(verificationCode); } catch (IOException e) { error("remote server refused authorization."); return false; } return true; }
java
private boolean authorize(RemoteConnector mc, InputReader in) { //get authorization URL String authUrl; try { authUrl = mc.getAuthorizationURL(); } catch (IOException e) { error("could not get authorization URL from remote server."); return false; } //ask user to point browser to authorization URL System.out.println("This tool requires authorization. Please point your " + "web browser to the\nfollowing URL and follow the instructions:\n"); System.out.println(authUrl); System.out.println(); //open authorization tool in browser if (Desktop.isDesktopSupported()) { Desktop d = Desktop.getDesktop(); if (d.isSupported(Desktop.Action.BROWSE)) { try { d.browse(new URI(authUrl)); } catch (Exception e) { //ignore. let the user open the browser manually. } } } //read verification code from console String verificationCode; try { verificationCode = in.readLine("Enter verification code: "); } catch (IOException e) { throw new RuntimeException("Could not read from console."); } if (verificationCode == null || verificationCode.isEmpty()) { //user aborted process return false; } //authorize... try { System.out.println("Connecting ..."); mc.authorize(verificationCode); } catch (IOException e) { error("remote server refused authorization."); return false; } return true; }
[ "private", "boolean", "authorize", "(", "RemoteConnector", "mc", ",", "InputReader", "in", ")", "{", "//get authorization URL", "String", "authUrl", ";", "try", "{", "authUrl", "=", "mc", ".", "getAuthorizationURL", "(", ")", ";", "}", "catch", "(", "IOExcepti...
Request authorization for the tool from remote server @param mc the remote connector @param in a stream from which user input can be read @return true if authorization was successful
[ "Request", "authorization", "for", "the", "tool", "from", "remote", "server" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/AbstractRemoteCommand.java#L248-L299
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/utilities/RandomPermutation.java
RandomPermutation.permute
public double[] permute(double[] vector) { double[] permuted = new double[vector.length]; for (int i = 0; i < vector.length; i++) { permuted[i] = vector[randomlyPermutatedIndices[i]]; } return permuted; }
java
public double[] permute(double[] vector) { double[] permuted = new double[vector.length]; for (int i = 0; i < vector.length; i++) { permuted[i] = vector[randomlyPermutatedIndices[i]]; } return permuted; }
[ "public", "double", "[", "]", "permute", "(", "double", "[", "]", "vector", ")", "{", "double", "[", "]", "permuted", "=", "new", "double", "[", "vector", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vector", ".", ...
Randomly permutes a vector using the random permutation of the indices that was created in the constructor. @param vector The initial vector @return The randomly permuted vector
[ "Randomly", "permutes", "a", "vector", "using", "the", "random", "permutation", "of", "the", "indices", "that", "was", "created", "in", "the", "constructor", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/utilities/RandomPermutation.java#L50-L56
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/BibliographyCommand.java
BibliographyCommand.checkStyle
private boolean checkStyle(String style) throws IOException { if (CSL.supportsStyle(style)) { //style is supported return true; } //style is not supported. look for alternatives. String message = "Could not find style in classpath: " + style; Set<String> availableStyles = CSL.getSupportedStyles(); //output alternative if (!availableStyles.isEmpty()) { String dyms = ToolUtils.getDidYouMeanString(availableStyles, style); if (dyms != null && !dyms.isEmpty()) { message += "\n\n" + dyms; } } error(message); return false; }
java
private boolean checkStyle(String style) throws IOException { if (CSL.supportsStyle(style)) { //style is supported return true; } //style is not supported. look for alternatives. String message = "Could not find style in classpath: " + style; Set<String> availableStyles = CSL.getSupportedStyles(); //output alternative if (!availableStyles.isEmpty()) { String dyms = ToolUtils.getDidYouMeanString(availableStyles, style); if (dyms != null && !dyms.isEmpty()) { message += "\n\n" + dyms; } } error(message); return false; }
[ "private", "boolean", "checkStyle", "(", "String", "style", ")", "throws", "IOException", "{", "if", "(", "CSL", ".", "supportsStyle", "(", "style", ")", ")", "{", "//style is supported", "return", "true", ";", "}", "//style is not supported. look for alternatives."...
Checks if the given style exists and output possible alternatives if it does not @param style the style @return true if the style exists, false otherwise @throws IOException if the style could not be loaded
[ "Checks", "if", "the", "given", "style", "exists", "and", "output", "possible", "alternatives", "if", "it", "does", "not" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/BibliographyCommand.java#L106-L126
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.loadProductQuantizer
public void loadProductQuantizer(String filename) throws Exception { productQuantizer = new double[numSubVectors][numProductCentroids][subVectorLength]; BufferedReader in = new BufferedReader(new FileReader(new File(filename))); for (int i = 0; i < numSubVectors; i++) { for (int j = 0; j < numProductCentroids; j++) { String line = in.readLine(); String[] centroidString = line.split(","); for (int k = 0; k < subVectorLength; k++) { productQuantizer[i][j][k] = Double.parseDouble(centroidString[k]); } } } in.close(); }
java
public void loadProductQuantizer(String filename) throws Exception { productQuantizer = new double[numSubVectors][numProductCentroids][subVectorLength]; BufferedReader in = new BufferedReader(new FileReader(new File(filename))); for (int i = 0; i < numSubVectors; i++) { for (int j = 0; j < numProductCentroids; j++) { String line = in.readLine(); String[] centroidString = line.split(","); for (int k = 0; k < subVectorLength; k++) { productQuantizer[i][j][k] = Double.parseDouble(centroidString[k]); } } } in.close(); }
[ "public", "void", "loadProductQuantizer", "(", "String", "filename", ")", "throws", "Exception", "{", "productQuantizer", "=", "new", "double", "[", "numSubVectors", "]", "[", "numProductCentroids", "]", "[", "subVectorLength", "]", ";", "BufferedReader", "in", "=...
Load the product quantizer from the given file. @param filename Full path to the file containing the product quantizer @throws Exception
[ "Load", "the", "product", "quantizer", "from", "the", "given", "file", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L275-L288
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.loadCoarseQuantizer
public void loadCoarseQuantizer(String filename) throws IOException { coarseQuantizer = new double[numCoarseCentroids][vectorLength]; coarseQuantizer = AbstractFeatureAggregator.readQuantizer(filename, numCoarseCentroids, vectorLength); }
java
public void loadCoarseQuantizer(String filename) throws IOException { coarseQuantizer = new double[numCoarseCentroids][vectorLength]; coarseQuantizer = AbstractFeatureAggregator.readQuantizer(filename, numCoarseCentroids, vectorLength); }
[ "public", "void", "loadCoarseQuantizer", "(", "String", "filename", ")", "throws", "IOException", "{", "coarseQuantizer", "=", "new", "double", "[", "numCoarseCentroids", "]", "[", "vectorLength", "]", ";", "coarseQuantizer", "=", "AbstractFeatureAggregator", ".", "...
Load the coarse quantizer from the given file. @param filname Full path to the file containing the coarse quantizer @throws Exception
[ "Load", "the", "coarse", "quantizer", "from", "the", "given", "file", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L297-L300
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.computeKnnIVFADC
private BoundedPriorityQueue<Result> computeKnnIVFADC(int k, double[] qVector) throws Exception { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); // find the w nearest coarse centroids int[] nearestCoarseCentroidIndices = computeNearestCoarseIndices(qVector, w); for (int i = 0; i < w; i++) { // for each assignment // quantize to the i-th closest centroid of the coarse quantizer and compute residual vector int nearestCoarseIndex = nearestCoarseCentroidIndices[i]; double[] residualVectorQuery = computeResidualVector(qVector, nearestCoarseIndex); // apply a random transformation if needed if (transformation == TransformationType.RandomRotation) { residualVectorQuery = rr.rotate(residualVectorQuery); } else if (transformation == TransformationType.RandomPermutation) { residualVectorQuery = rp.permute(residualVectorQuery); } // compute lookup table double[][] lookUpTable = computeLookupADC(residualVectorQuery); for (int j = 0; j < invertedLists[nearestCoarseIndex].size(); j++) { int iid = invertedLists[nearestCoarseIndex].getQuick(j); double l2distance = 0; int codeStart = j * numSubVectors; if (numProductCentroids <= 256) { byte[] pqCode = pqByteCodes[nearestCoarseIndex].toArray(codeStart, numSubVectors); for (int m = 0; m < pqCode.length; m++) { // plus 128 because byte range is -128..127 l2distance += lookUpTable[m][pqCode[m] + 128]; } } else { short[] pqCode = pqShortCodes[nearestCoarseIndex].toArray(codeStart, numSubVectors); for (int m = 0; m < pqCode.length; m++) { l2distance += lookUpTable[m][pqCode[m]]; } } nn.offer(new Result(iid, l2distance)); } } return nn; }
java
private BoundedPriorityQueue<Result> computeKnnIVFADC(int k, double[] qVector) throws Exception { BoundedPriorityQueue<Result> nn = new BoundedPriorityQueue<Result>(new Result(), k); // find the w nearest coarse centroids int[] nearestCoarseCentroidIndices = computeNearestCoarseIndices(qVector, w); for (int i = 0; i < w; i++) { // for each assignment // quantize to the i-th closest centroid of the coarse quantizer and compute residual vector int nearestCoarseIndex = nearestCoarseCentroidIndices[i]; double[] residualVectorQuery = computeResidualVector(qVector, nearestCoarseIndex); // apply a random transformation if needed if (transformation == TransformationType.RandomRotation) { residualVectorQuery = rr.rotate(residualVectorQuery); } else if (transformation == TransformationType.RandomPermutation) { residualVectorQuery = rp.permute(residualVectorQuery); } // compute lookup table double[][] lookUpTable = computeLookupADC(residualVectorQuery); for (int j = 0; j < invertedLists[nearestCoarseIndex].size(); j++) { int iid = invertedLists[nearestCoarseIndex].getQuick(j); double l2distance = 0; int codeStart = j * numSubVectors; if (numProductCentroids <= 256) { byte[] pqCode = pqByteCodes[nearestCoarseIndex].toArray(codeStart, numSubVectors); for (int m = 0; m < pqCode.length; m++) { // plus 128 because byte range is -128..127 l2distance += lookUpTable[m][pqCode[m] + 128]; } } else { short[] pqCode = pqShortCodes[nearestCoarseIndex].toArray(codeStart, numSubVectors); for (int m = 0; m < pqCode.length; m++) { l2distance += lookUpTable[m][pqCode[m]]; } } nn.offer(new Result(iid, l2distance)); } } return nn; }
[ "private", "BoundedPriorityQueue", "<", "Result", ">", "computeKnnIVFADC", "(", "int", "k", ",", "double", "[", "]", "qVector", ")", "throws", "Exception", "{", "BoundedPriorityQueue", "<", "Result", ">", "nn", "=", "new", "BoundedPriorityQueue", "<", "Result", ...
Computes and returns the k nearest neighbors of the query vector using the IVFADC approach. @param k The number of nearest neighbors to be returned @param qVector The query vector @return @throws Exception
[ "Computes", "and", "returns", "the", "k", "nearest", "neighbors", "of", "the", "query", "vector", "using", "the", "IVFADC", "approach", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L408-L450
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.computeNearestCoarseIndex
private int computeNearestCoarseIndex(double[] vector) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCoarseCentroids; i++) { double distance = 0; for (int j = 0; j < vectorLength; j++) { distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]); if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
java
private int computeNearestCoarseIndex(double[] vector) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCoarseCentroids; i++) { double distance = 0; for (int j = 0; j < vectorLength; j++) { distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]); if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
[ "private", "int", "computeNearestCoarseIndex", "(", "double", "[", "]", "vector", ")", "{", "int", "centroidIndex", "=", "-", "1", ";", "double", "minDistance", "=", "Double", ".", "MAX_VALUE", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "num...
Returns the index of the coarse centroid which is closer to the given vector. @param vector The vector @return The index of the nearest coarse centroid
[ "Returns", "the", "index", "of", "the", "coarse", "centroid", "which", "is", "closer", "to", "the", "given", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L547-L564
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.computeNearestCoarseIndices
protected int[] computeNearestCoarseIndices(double[] vector, int k) { BoundedPriorityQueue<Result> bpq = new BoundedPriorityQueue<Result>(new Result(), k); double lowest = Double.MAX_VALUE; for (int i = 0; i < numCoarseCentroids; i++) { boolean skip = false; double l2distance = 0; for (int j = 0; j < vectorLength; j++) { l2distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]); if (l2distance > lowest) { skip = true; break; } } if (!skip) { bpq.offer(new Result(i, l2distance)); if (i >= k) { lowest = bpq.last().getDistance(); } } } int[] nn = new int[k]; for (int i = 0; i < k; i++) { nn[i] = bpq.poll().getId(); } return nn; }
java
protected int[] computeNearestCoarseIndices(double[] vector, int k) { BoundedPriorityQueue<Result> bpq = new BoundedPriorityQueue<Result>(new Result(), k); double lowest = Double.MAX_VALUE; for (int i = 0; i < numCoarseCentroids; i++) { boolean skip = false; double l2distance = 0; for (int j = 0; j < vectorLength; j++) { l2distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]); if (l2distance > lowest) { skip = true; break; } } if (!skip) { bpq.offer(new Result(i, l2distance)); if (i >= k) { lowest = bpq.last().getDistance(); } } } int[] nn = new int[k]; for (int i = 0; i < k; i++) { nn[i] = bpq.poll().getId(); } return nn; }
[ "protected", "int", "[", "]", "computeNearestCoarseIndices", "(", "double", "[", "]", "vector", ",", "int", "k", ")", "{", "BoundedPriorityQueue", "<", "Result", ">", "bpq", "=", "new", "BoundedPriorityQueue", "<", "Result", ">", "(", "new", "Result", "(", ...
Returns the indices of the k coarse centroids which are closer to the given vector. @param vector The vector @param k The number of nearest centroids to return @return The indices of the k nearest coarse centroids
[ "Returns", "the", "indices", "of", "the", "k", "coarse", "centroids", "which", "are", "closer", "to", "the", "given", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L575-L601
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.computeNearestProductIndex
private int computeNearestProductIndex(double[] subvector, int subQuantizerIndex) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numProductCentroids; i++) { double distance = 0; for (int j = 0; j < subVectorLength; j++) { distance += (productQuantizer[subQuantizerIndex][i][j] - subvector[j]) * (productQuantizer[subQuantizerIndex][i][j] - subvector[j]); if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
java
private int computeNearestProductIndex(double[] subvector, int subQuantizerIndex) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numProductCentroids; i++) { double distance = 0; for (int j = 0; j < subVectorLength; j++) { distance += (productQuantizer[subQuantizerIndex][i][j] - subvector[j]) * (productQuantizer[subQuantizerIndex][i][j] - subvector[j]); if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
[ "private", "int", "computeNearestProductIndex", "(", "double", "[", "]", "subvector", ",", "int", "subQuantizerIndex", ")", "{", "int", "centroidIndex", "=", "-", "1", ";", "double", "minDistance", "=", "Double", ".", "MAX_VALUE", ";", "for", "(", "int", "i"...
Finds and returns the index of the centroid of the subquantizer with the given index which is closer to the given subvector. @param subvector The subvector @param subQuantizerIndex The index of the the subquantizer @return The index of the nearest centroid
[ "Finds", "and", "returns", "the", "index", "of", "the", "centroid", "of", "the", "subquantizer", "with", "the", "given", "index", "which", "is", "closer", "to", "the", "given", "subvector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L613-L631
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.computeResidualVector
private double[] computeResidualVector(double[] vector, int centroidIndex) { double[] residualVector = new double[vectorLength]; for (int i = 0; i < vectorLength; i++) { residualVector[i] = coarseQuantizer[centroidIndex][i] - vector[i]; } return residualVector; }
java
private double[] computeResidualVector(double[] vector, int centroidIndex) { double[] residualVector = new double[vectorLength]; for (int i = 0; i < vectorLength; i++) { residualVector[i] = coarseQuantizer[centroidIndex][i] - vector[i]; } return residualVector; }
[ "private", "double", "[", "]", "computeResidualVector", "(", "double", "[", "]", "vector", ",", "int", "centroidIndex", ")", "{", "double", "[", "]", "residualVector", "=", "new", "double", "[", "vectorLength", "]", ";", "for", "(", "int", "i", "=", "0",...
Computes the residual vector. @param vector The original vector @param centroidIndex The centroid of the coarse quantizer from which the original vector is subtracted @return The residual vector
[ "Computes", "the", "residual", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L642-L648
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.outputItemsPerList
public void outputItemsPerList() { int max = 0; int min = Integer.MAX_VALUE; double sum = 0; for (int i = 0; i < numCoarseCentroids; i++) { // System.out.println("List " + (i + 1) + ": " + perListLoadCounter[i]); if (invertedLists[i].size() > max) { max = invertedLists[i].size(); } if (invertedLists[i].size() < min) { min = invertedLists[i].size(); } sum += invertedLists[i].size(); } System.out.println("Maximum number of vectors: " + max); System.out.println("Minimum number of vectors: " + min); System.out.println("Average number of vectors: " + (sum / numCoarseCentroids)); }
java
public void outputItemsPerList() { int max = 0; int min = Integer.MAX_VALUE; double sum = 0; for (int i = 0; i < numCoarseCentroids; i++) { // System.out.println("List " + (i + 1) + ": " + perListLoadCounter[i]); if (invertedLists[i].size() > max) { max = invertedLists[i].size(); } if (invertedLists[i].size() < min) { min = invertedLists[i].size(); } sum += invertedLists[i].size(); } System.out.println("Maximum number of vectors: " + max); System.out.println("Minimum number of vectors: " + min); System.out.println("Average number of vectors: " + (sum / numCoarseCentroids)); }
[ "public", "void", "outputItemsPerList", "(", ")", "{", "int", "max", "=", "0", ";", "int", "min", "=", "Integer", ".", "MAX_VALUE", ";", "double", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numCoarseCentroids", ";", "i"...
Utility method that calculates and prints the min, max and avg number of items per inverted list of the index.
[ "Utility", "method", "that", "calculates", "and", "prints", "the", "min", "max", "and", "avg", "number", "of", "items", "per", "inverted", "list", "of", "the", "index", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L654-L673
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.getPQCodeByte
public byte[] getPQCodeByte(String id) throws Exception { int iid = getInternalId(id); if (iid == -1) { throw new Exception("Id does not exist!"); } if (numProductCentroids > 256) { throw new Exception("Call the short variant of the method!"); } DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); DatabaseEntry data = new DatabaseEntry(); if ((iidToIvfpqDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { TupleInput input = TupleBinding.entryToInput(data); input.readInt(); // skip the list id byte[] code = new byte[numSubVectors]; for (int i = 0; i < numSubVectors; i++) { code[i] = input.readByte(); } return code; } else { throw new Exception("Id does not exist!"); } }
java
public byte[] getPQCodeByte(String id) throws Exception { int iid = getInternalId(id); if (iid == -1) { throw new Exception("Id does not exist!"); } if (numProductCentroids > 256) { throw new Exception("Call the short variant of the method!"); } DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); DatabaseEntry data = new DatabaseEntry(); if ((iidToIvfpqDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { TupleInput input = TupleBinding.entryToInput(data); input.readInt(); // skip the list id byte[] code = new byte[numSubVectors]; for (int i = 0; i < numSubVectors; i++) { code[i] = input.readByte(); } return code; } else { throw new Exception("Id does not exist!"); } }
[ "public", "byte", "[", "]", "getPQCodeByte", "(", "String", "id", ")", "throws", "Exception", "{", "int", "iid", "=", "getInternalId", "(", "id", ")", ";", "if", "(", "iid", "==", "-", "1", ")", "{", "throw", "new", "Exception", "(", "\"Id does not exi...
Returns the pq code of the image with the given id. @param id @return @throws Exception
[ "Returns", "the", "pq", "code", "of", "the", "image", "with", "the", "given", "id", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L801-L824
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java
IVFPQ.getInvertedListId
public int getInvertedListId(String id) throws Exception { int iid = getInternalId(id); if (iid == -1) { throw new Exception("Id does not exist!"); } DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); DatabaseEntry data = new DatabaseEntry(); if ((iidToIvfpqDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { TupleInput input = TupleBinding.entryToInput(data); int listId = input.readInt(); return listId; } else { throw new Exception("Id does not exist!"); } }
java
public int getInvertedListId(String id) throws Exception { int iid = getInternalId(id); if (iid == -1) { throw new Exception("Id does not exist!"); } DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(iid, key); DatabaseEntry data = new DatabaseEntry(); if ((iidToIvfpqDB.get(null, key, data, null) == OperationStatus.SUCCESS)) { TupleInput input = TupleBinding.entryToInput(data); int listId = input.readInt(); return listId; } else { throw new Exception("Id does not exist!"); } }
[ "public", "int", "getInvertedListId", "(", "String", "id", ")", "throws", "Exception", "{", "int", "iid", "=", "getInternalId", "(", "id", ")", ";", "if", "(", "iid", "==", "-", "1", ")", "{", "throw", "new", "Exception", "(", "\"Id does not exist!\"", "...
Returns the inverted list of the image with the given id. @param id @return @throws Exception
[ "Returns", "the", "inverted", "list", "of", "the", "image", "with", "the", "given", "id", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/datastructures/IVFPQ.java#L865-L881
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/PageParser.java
PageParser.parse
public static PageRange parse(String pages) { ANTLRInputStream is = new ANTLRInputStream(pages); InternalPageLexer lexer = new InternalPageLexer(is); lexer.removeErrorListeners(); //do not output errors to console CommonTokenStream tokens = new CommonTokenStream(lexer); InternalPageParser parser = new InternalPageParser(tokens); parser.removeErrorListeners(); //do not output errors to console PagesContext ctx = parser.pages(); return new PageRange(ctx.literal != null ? ctx.literal : pages, ctx.pageFrom, ctx.numberOfPages); }
java
public static PageRange parse(String pages) { ANTLRInputStream is = new ANTLRInputStream(pages); InternalPageLexer lexer = new InternalPageLexer(is); lexer.removeErrorListeners(); //do not output errors to console CommonTokenStream tokens = new CommonTokenStream(lexer); InternalPageParser parser = new InternalPageParser(tokens); parser.removeErrorListeners(); //do not output errors to console PagesContext ctx = parser.pages(); return new PageRange(ctx.literal != null ? ctx.literal : pages, ctx.pageFrom, ctx.numberOfPages); }
[ "public", "static", "PageRange", "parse", "(", "String", "pages", ")", "{", "ANTLRInputStream", "is", "=", "new", "ANTLRInputStream", "(", "pages", ")", ";", "InternalPageLexer", "lexer", "=", "new", "InternalPageLexer", "(", "is", ")", ";", "lexer", ".", "r...
Parses a given page or range of pages. If the given string cannot be parsed, the method will return a page range with a literal string. @param pages the page or range of pages @return the parsed page or page range (never null)
[ "Parses", "a", "given", "page", "or", "range", "of", "pages", ".", "If", "the", "given", "string", "cannot", "be", "parsed", "the", "method", "will", "return", "a", "page", "range", "with", "a", "literal", "string", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/PageParser.java#L35-L44
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/download/ImageDownload.java
ImageDownload.main
public static void main(String args[]) throws Exception { String urlStr = "http://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg"; String id = "Sunset_2007-1"; String downloadFolder = "images/"; boolean saveThumb = true; boolean saveOriginal = true; boolean followRedirects = false; ImageDownload imdown = new ImageDownload(urlStr, id, downloadFolder, saveThumb, saveOriginal, followRedirects); imdown.setDebug(true); ImageDownloadResult imdr = imdown.call(); System.out.println("Getting the BufferedImage object of the downloaded image."); imdr.getImage(); System.out.println("Reading the downloaded image thumbnail into a BufferedImage object."); ImageIO.read(new File(downloadFolder + id + "-thumb.jpg")); System.out.println("Success!"); }
java
public static void main(String args[]) throws Exception { String urlStr = "http://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg"; String id = "Sunset_2007-1"; String downloadFolder = "images/"; boolean saveThumb = true; boolean saveOriginal = true; boolean followRedirects = false; ImageDownload imdown = new ImageDownload(urlStr, id, downloadFolder, saveThumb, saveOriginal, followRedirects); imdown.setDebug(true); ImageDownloadResult imdr = imdown.call(); System.out.println("Getting the BufferedImage object of the downloaded image."); imdr.getImage(); System.out.println("Reading the downloaded image thumbnail into a BufferedImage object."); ImageIO.read(new File(downloadFolder + id + "-thumb.jpg")); System.out.println("Success!"); }
[ "public", "static", "void", "main", "(", "String", "args", "[", "]", ")", "throws", "Exception", "{", "String", "urlStr", "=", "\"http://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg\"", ";", "String", "id", "=", "\"Sunset_2007-1\"", ";", "String", "do...
Example of a single image download using this class. @param args @throws Exception
[ "Example", "of", "a", "single", "image", "download", "using", "this", "class", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/download/ImageDownload.java#L268-L286
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java
DateParser.merge
private static CSLDate merge(CSLDate d1, CSLDate d2) { if (d1 == null) { return d2; } else if (d2 == null) { return d1; } CSLDateBuilder builder = new CSLDateBuilder(); //handle date parts builder.dateParts(d1.getDateParts()[0], d2.getDateParts()[d2.getDateParts().length - 1]); //handle circa if (d1.getCirca() != null) { builder.circa(d1.getCirca()); } if (d2.getCirca() != null && (d1.getCirca() == null || d2.getCirca().booleanValue())) { builder.circa(d2.getCirca()); } //handle literal strings if (d1.getLiteral() != null) { builder.literal(d1.getLiteral()); } if (d2.getLiteral() != null) { if (d1.getLiteral() != null) { builder.literal(d1.getLiteral() + "-" + d2.getLiteral()); } else { builder.literal(d2.getLiteral()); } } //handle seasons if (d1.getSeason() != null) { builder.season(d1.getSeason()); } if (d2.getSeason() != null) { if (d1.getSeason() != null) { builder.season(d1.getSeason() + "-" + d2.getSeason()); } else { builder.season(d2.getSeason()); } } //handle raw strings if (d1.getRaw() != null) { builder.raw(d1.getRaw()); } if (d2.getRaw() != null) { if (d1.getRaw() != null) { builder.raw(d1.getRaw() + "-" + d2.getRaw()); } else { builder.raw(d2.getRaw()); } } return builder.build(); }
java
private static CSLDate merge(CSLDate d1, CSLDate d2) { if (d1 == null) { return d2; } else if (d2 == null) { return d1; } CSLDateBuilder builder = new CSLDateBuilder(); //handle date parts builder.dateParts(d1.getDateParts()[0], d2.getDateParts()[d2.getDateParts().length - 1]); //handle circa if (d1.getCirca() != null) { builder.circa(d1.getCirca()); } if (d2.getCirca() != null && (d1.getCirca() == null || d2.getCirca().booleanValue())) { builder.circa(d2.getCirca()); } //handle literal strings if (d1.getLiteral() != null) { builder.literal(d1.getLiteral()); } if (d2.getLiteral() != null) { if (d1.getLiteral() != null) { builder.literal(d1.getLiteral() + "-" + d2.getLiteral()); } else { builder.literal(d2.getLiteral()); } } //handle seasons if (d1.getSeason() != null) { builder.season(d1.getSeason()); } if (d2.getSeason() != null) { if (d1.getSeason() != null) { builder.season(d1.getSeason() + "-" + d2.getSeason()); } else { builder.season(d2.getSeason()); } } //handle raw strings if (d1.getRaw() != null) { builder.raw(d1.getRaw()); } if (d2.getRaw() != null) { if (d1.getRaw() != null) { builder.raw(d1.getRaw() + "-" + d2.getRaw()); } else { builder.raw(d2.getRaw()); } } return builder.build(); }
[ "private", "static", "CSLDate", "merge", "(", "CSLDate", "d1", ",", "CSLDate", "d2", ")", "{", "if", "(", "d1", "==", "null", ")", "{", "return", "d2", ";", "}", "else", "if", "(", "d2", "==", "null", ")", "{", "return", "d1", ";", "}", "CSLDateB...
Merges two dates @param d1 the first date @param d2 the second date @return the merged date
[ "Merges", "two", "dates" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java#L190-L247
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java
DateParser.toMonth
public static int toMonth(String month) { int m = -1; if (month != null && !month.isEmpty()) { if (StringUtils.isNumeric(month)) { m = Integer.parseInt(month); if (m < 1 || m > 12) { //invalid month m = -1; } } else { m = tryParseMonth(month, Locale.ENGLISH); if (m <= 0) { m = tryParseMonth(month, Locale.getDefault()); if (m <= 0) { for (Locale l : Locale.getAvailableLocales()) { m = tryParseMonth(month, l); if (m > 0) { break; } } } } } } return m; }
java
public static int toMonth(String month) { int m = -1; if (month != null && !month.isEmpty()) { if (StringUtils.isNumeric(month)) { m = Integer.parseInt(month); if (m < 1 || m > 12) { //invalid month m = -1; } } else { m = tryParseMonth(month, Locale.ENGLISH); if (m <= 0) { m = tryParseMonth(month, Locale.getDefault()); if (m <= 0) { for (Locale l : Locale.getAvailableLocales()) { m = tryParseMonth(month, l); if (m > 0) { break; } } } } } } return m; }
[ "public", "static", "int", "toMonth", "(", "String", "month", ")", "{", "int", "m", "=", "-", "1", ";", "if", "(", "month", "!=", "null", "&&", "!", "month", ".", "isEmpty", "(", ")", ")", "{", "if", "(", "StringUtils", ".", "isNumeric", "(", "mo...
Parses the given month string @param month the month to parse. May be a number (<code>1-12</code>), a short month name (<code>Jan</code> to <code>Dec</code>), or a long month name (<code>January</code> to <code>December</code>). This method is also able to recognize month names in several locales. @return the month's number (<code>1-12</code>) or <code>-1</code> if the string could not be parsed
[ "Parses", "the", "given", "month", "string" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java#L258-L283
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java
DateParser.getMonthNames
private static Map<String, Integer> getMonthNames(Locale locale) { Map<String, Integer> r = MONTH_NAMES_CACHE.get(locale); if (r == null) { DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale); r = new HashMap<>(24); //insert long month names String[] months = symbols.getMonths(); for (int i = 0; i < months.length; ++i) { String m = months[i]; if (!m.isEmpty()) { r.put(m.toUpperCase(), i + 1); } } //insert short month names String[] shortMonths = symbols.getShortMonths(); for (int i = 0; i < shortMonths.length; ++i) { String m = shortMonths[i]; if (!m.isEmpty()) { r.put(m.toUpperCase(), i + 1); } } MONTH_NAMES_CACHE.put(locale, r); } return r; }
java
private static Map<String, Integer> getMonthNames(Locale locale) { Map<String, Integer> r = MONTH_NAMES_CACHE.get(locale); if (r == null) { DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale); r = new HashMap<>(24); //insert long month names String[] months = symbols.getMonths(); for (int i = 0; i < months.length; ++i) { String m = months[i]; if (!m.isEmpty()) { r.put(m.toUpperCase(), i + 1); } } //insert short month names String[] shortMonths = symbols.getShortMonths(); for (int i = 0; i < shortMonths.length; ++i) { String m = shortMonths[i]; if (!m.isEmpty()) { r.put(m.toUpperCase(), i + 1); } } MONTH_NAMES_CACHE.put(locale, r); } return r; }
[ "private", "static", "Map", "<", "String", ",", "Integer", ">", "getMonthNames", "(", "Locale", "locale", ")", "{", "Map", "<", "String", ",", "Integer", ">", "r", "=", "MONTH_NAMES_CACHE", ".", "get", "(", "locale", ")", ";", "if", "(", "r", "==", "...
Retrieves and caches a list of month names for a given locale @param locale the locale @return the list of month names (short and long). All names are converted to upper case
[ "Retrieves", "and", "caches", "a", "list", "of", "month", "names", "for", "a", "given", "locale" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java#L291-L318
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java
DateParser.tryParseMonth
private static int tryParseMonth(String month, Locale locale) { Map<String, Integer> names = getMonthNames(locale); Integer r = names.get(month.toUpperCase()); if (r != null) { return r; } return -1; }
java
private static int tryParseMonth(String month, Locale locale) { Map<String, Integer> names = getMonthNames(locale); Integer r = names.get(month.toUpperCase()); if (r != null) { return r; } return -1; }
[ "private", "static", "int", "tryParseMonth", "(", "String", "month", ",", "Locale", "locale", ")", "{", "Map", "<", "String", ",", "Integer", ">", "names", "=", "getMonthNames", "(", "locale", ")", ";", "Integer", "r", "=", "names", ".", "get", "(", "m...
Tries to parse the given month string using the month names of the given locale @param month the month string @param locale the locale @return the month's number (<code>1-12</code>) or <code>-1</code> if the string could not be parsed
[ "Tries", "to", "parse", "the", "given", "month", "string", "using", "the", "month", "names", "of", "the", "given", "locale" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/DateParser.java#L328-L335
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/quantization/ResidualVectorComputation.java
ResidualVectorComputation.computeNearestCentroid
private int computeNearestCentroid(double[] vector) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCentroids; i++) { double distance = 0; for (int j = 0; j < vectorLength; j++) { distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]); if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
java
private int computeNearestCentroid(double[] vector) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCentroids; i++) { double distance = 0; for (int j = 0; j < vectorLength; j++) { distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i][j] - vector[j]); if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return centroidIndex; }
[ "private", "int", "computeNearestCentroid", "(", "double", "[", "]", "vector", ")", "{", "int", "centroidIndex", "=", "-", "1", ";", "double", "minDistance", "=", "Double", ".", "MAX_VALUE", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numCen...
Finds and returns the index of the coarse quantizer's centroid which is closer to the given vector. @param vector @return
[ "Finds", "and", "returns", "the", "index", "of", "the", "coarse", "quantizer", "s", "centroid", "which", "is", "closer", "to", "the", "given", "vector", "." ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/quantization/ResidualVectorComputation.java#L45-L62
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/CitationIdsCommand.java
CitationIdsCommand.checkCitationIds
protected boolean checkCitationIds(List<String> citationIds, ItemDataProvider provider) { for (String id : citationIds) { if (provider.retrieveItem(id) == null) { String message = "unknown citation id: " + id; //find alternatives List<String> availableIds = Arrays.asList(provider.getIds()); if (!availableIds.isEmpty()) { Collection<String> mins = Levenshtein.findSimilar(availableIds, id); if (mins.size() > 0) { if (mins.size() == 1) { message += "\n\nDid you mean this?"; } else { message += "\n\nDid you mean one of these?"; } for (String m : mins) { message += "\n\t" + m; } } } error(message); return false; } } return true; }
java
protected boolean checkCitationIds(List<String> citationIds, ItemDataProvider provider) { for (String id : citationIds) { if (provider.retrieveItem(id) == null) { String message = "unknown citation id: " + id; //find alternatives List<String> availableIds = Arrays.asList(provider.getIds()); if (!availableIds.isEmpty()) { Collection<String> mins = Levenshtein.findSimilar(availableIds, id); if (mins.size() > 0) { if (mins.size() == 1) { message += "\n\nDid you mean this?"; } else { message += "\n\nDid you mean one of these?"; } for (String m : mins) { message += "\n\t" + m; } } } error(message); return false; } } return true; }
[ "protected", "boolean", "checkCitationIds", "(", "List", "<", "String", ">", "citationIds", ",", "ItemDataProvider", "provider", ")", "{", "for", "(", "String", "id", ":", "citationIds", ")", "{", "if", "(", "provider", ".", "retrieveItem", "(", "id", ")", ...
Checks the citation IDs provided on the command line @param citationIds the citation IDs @param provider the item data provider @return true if all citation IDs are OK, false if they're not
[ "Checks", "the", "citation", "IDs", "provided", "on", "the", "command", "line" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/CitationIdsCommand.java#L77-L104
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/BibTeXConverter.java
BibTeXConverter.toItemData
public Map<String, CSLItemData> toItemData(BibTeXDatabase db) { Map<String, CSLItemData> result = new HashMap<>(); for (Map.Entry<Key, BibTeXEntry> e : db.getEntries().entrySet()) { result.put(e.getKey().getValue(), toItemData(e.getValue())); } return result; }
java
public Map<String, CSLItemData> toItemData(BibTeXDatabase db) { Map<String, CSLItemData> result = new HashMap<>(); for (Map.Entry<Key, BibTeXEntry> e : db.getEntries().entrySet()) { result.put(e.getKey().getValue(), toItemData(e.getValue())); } return result; }
[ "public", "Map", "<", "String", ",", "CSLItemData", ">", "toItemData", "(", "BibTeXDatabase", "db", ")", "{", "Map", "<", "String", ",", "CSLItemData", ">", "result", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "...
Converts the given database to a map of CSL citation items @param db the database @return a map consisting of citation keys and citation items
[ "Converts", "the", "given", "database", "to", "a", "map", "of", "CSL", "citation", "items" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/BibTeXConverter.java#L162-L168
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/BibTeXConverter.java
BibTeXConverter.toType
public CSLType toType(Key type) { String s = type.getValue(); if (s.equalsIgnoreCase(TYPE_ARTICLE)) { return CSLType.ARTICLE_JOURNAL; } else if (s.equalsIgnoreCase(TYPE_PROCEEDINGS)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_MANUAL)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_BOOK)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_PERIODICAL)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_BOOKLET)) { return CSLType.PAMPHLET; } else if (s.equalsIgnoreCase(TYPE_INBOOK)) { return CSLType.CHAPTER; } else if (s.equalsIgnoreCase(TYPE_INCOLLECTION)) { return CSLType.CHAPTER; } else if (s.equalsIgnoreCase(TYPE_INPROCEEDINGS)) { return CSLType.PAPER_CONFERENCE; } else if (s.equalsIgnoreCase(TYPE_CONFERENCE)) { return CSLType.PAPER_CONFERENCE; } else if (s.equalsIgnoreCase(TYPE_MASTERSTHESIS)) { return CSLType.THESIS; } else if (s.equalsIgnoreCase(TYPE_PHDTHESIS)) { return CSLType.THESIS; } else if (s.equalsIgnoreCase(TYPE_TECHREPORT)) { return CSLType.REPORT; } else if (s.equalsIgnoreCase(TYPE_PATENT)) { return CSLType.PATENT; } else if (s.equalsIgnoreCase(TYPE_ELECTRONIC)) { return CSLType.WEBPAGE; } else if (s.equalsIgnoreCase(TYPE_ONLINE)) { return CSLType.WEBPAGE; } else if (s.equalsIgnoreCase(TYPE_WWW)) { return CSLType.WEBPAGE; } else if (s.equalsIgnoreCase(TYPE_STANDARD)) { return CSLType.LEGISLATION; } else if (s.equalsIgnoreCase(TYPE_UNPUBLISHED)) { return CSLType.MANUSCRIPT; } return CSLType.ARTICLE; }
java
public CSLType toType(Key type) { String s = type.getValue(); if (s.equalsIgnoreCase(TYPE_ARTICLE)) { return CSLType.ARTICLE_JOURNAL; } else if (s.equalsIgnoreCase(TYPE_PROCEEDINGS)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_MANUAL)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_BOOK)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_PERIODICAL)) { return CSLType.BOOK; } else if (s.equalsIgnoreCase(TYPE_BOOKLET)) { return CSLType.PAMPHLET; } else if (s.equalsIgnoreCase(TYPE_INBOOK)) { return CSLType.CHAPTER; } else if (s.equalsIgnoreCase(TYPE_INCOLLECTION)) { return CSLType.CHAPTER; } else if (s.equalsIgnoreCase(TYPE_INPROCEEDINGS)) { return CSLType.PAPER_CONFERENCE; } else if (s.equalsIgnoreCase(TYPE_CONFERENCE)) { return CSLType.PAPER_CONFERENCE; } else if (s.equalsIgnoreCase(TYPE_MASTERSTHESIS)) { return CSLType.THESIS; } else if (s.equalsIgnoreCase(TYPE_PHDTHESIS)) { return CSLType.THESIS; } else if (s.equalsIgnoreCase(TYPE_TECHREPORT)) { return CSLType.REPORT; } else if (s.equalsIgnoreCase(TYPE_PATENT)) { return CSLType.PATENT; } else if (s.equalsIgnoreCase(TYPE_ELECTRONIC)) { return CSLType.WEBPAGE; } else if (s.equalsIgnoreCase(TYPE_ONLINE)) { return CSLType.WEBPAGE; } else if (s.equalsIgnoreCase(TYPE_WWW)) { return CSLType.WEBPAGE; } else if (s.equalsIgnoreCase(TYPE_STANDARD)) { return CSLType.LEGISLATION; } else if (s.equalsIgnoreCase(TYPE_UNPUBLISHED)) { return CSLType.MANUSCRIPT; } return CSLType.ARTICLE; }
[ "public", "CSLType", "toType", "(", "Key", "type", ")", "{", "String", "s", "=", "type", ".", "getValue", "(", ")", ";", "if", "(", "s", ".", "equalsIgnoreCase", "(", "TYPE_ARTICLE", ")", ")", "{", "return", "CSLType", ".", "ARTICLE_JOURNAL", ";", "}",...
Converts a BibTeX type to a CSL type @param type the type to convert @return the converted type (never null, falls back to {@link CSLType#ARTICLE})
[ "Converts", "a", "BibTeX", "type", "to", "a", "CSL", "type" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/bibtex/BibTeXConverter.java#L336-L378
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/csl/CitationIDIndexPair.java
CitationIDIndexPair.fromJson
public static CitationIDIndexPair fromJson(List<?> arr) { String citationId = (String)arr.get(0); int noteIndex = ((Number)arr.get(1)).intValue(); return new CitationIDIndexPair(citationId, noteIndex); }
java
public static CitationIDIndexPair fromJson(List<?> arr) { String citationId = (String)arr.get(0); int noteIndex = ((Number)arr.get(1)).intValue(); return new CitationIDIndexPair(citationId, noteIndex); }
[ "public", "static", "CitationIDIndexPair", "fromJson", "(", "List", "<", "?", ">", "arr", ")", "{", "String", "citationId", "=", "(", "String", ")", "arr", ".", "get", "(", "0", ")", ";", "int", "noteIndex", "=", "(", "(", "Number", ")", "arr", ".", ...
Converts a JSON array to a CitationIDIndexPair object. @param arr the JSON array to convert @return the converted CitationIDIndexPair object
[ "Converts", "a", "JSON", "array", "to", "a", "CitationIDIndexPair", "object", "." ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/csl/CitationIDIndexPair.java#L74-L78
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/StringHelper.java
StringHelper.sanitize
public static String sanitize(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); switch (c) { case '\u00c0': case '\u00c1': case '\u00c3': case '\u00c4': sb.append('A'); break; case '\u00c8': case '\u00c9': case '\u00cb': sb.append('E'); break; case '\u00cc': case '\u00cd': case '\u00cf': sb.append('I'); break; case '\u00d2': case '\u00d3': case '\u00d5': case '\u00d6': sb.append('O'); break; case '\u00d9': case '\u00da': case '\u00dc': sb.append('U'); break; case '\u00e0': case '\u00e1': case '\u00e3': case '\u00e4': sb.append('a'); break; case '\u00e8': case '\u00e9': case '\u00eb': sb.append('e'); break; case '\u00ec': case '\u00ed': case '\u00ef': sb.append('i'); break; case '\u00f2': case '\u00f3': case '\u00f6': case '\u00f5': sb.append('o'); break; case '\u00f9': case '\u00fa': case '\u00fc': sb.append('u'); break; case '\u00d1': sb.append('N'); break; case '\u00f1': sb.append('n'); break; case '\u010c': sb.append('C'); break; case '\u0160': sb.append('S'); break; case '\u017d': sb.append('Z'); break; case '\u010d': sb.append('c'); break; case '\u0161': sb.append('s'); break; case '\u017e': sb.append('z'); break; case '\u00df': sb.append("ss"); break; default: if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { sb.append(c); } else { sb.append('_'); } break; } } return sb.toString(); }
java
public static String sanitize(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); switch (c) { case '\u00c0': case '\u00c1': case '\u00c3': case '\u00c4': sb.append('A'); break; case '\u00c8': case '\u00c9': case '\u00cb': sb.append('E'); break; case '\u00cc': case '\u00cd': case '\u00cf': sb.append('I'); break; case '\u00d2': case '\u00d3': case '\u00d5': case '\u00d6': sb.append('O'); break; case '\u00d9': case '\u00da': case '\u00dc': sb.append('U'); break; case '\u00e0': case '\u00e1': case '\u00e3': case '\u00e4': sb.append('a'); break; case '\u00e8': case '\u00e9': case '\u00eb': sb.append('e'); break; case '\u00ec': case '\u00ed': case '\u00ef': sb.append('i'); break; case '\u00f2': case '\u00f3': case '\u00f6': case '\u00f5': sb.append('o'); break; case '\u00f9': case '\u00fa': case '\u00fc': sb.append('u'); break; case '\u00d1': sb.append('N'); break; case '\u00f1': sb.append('n'); break; case '\u010c': sb.append('C'); break; case '\u0160': sb.append('S'); break; case '\u017d': sb.append('Z'); break; case '\u010d': sb.append('c'); break; case '\u0161': sb.append('s'); break; case '\u017e': sb.append('z'); break; case '\u00df': sb.append("ss"); break; default: if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { sb.append(c); } else { sb.append('_'); } break; } } return sb.toString(); }
[ "public", "static", "String", "sanitize", "(", "String", "s", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", ";", "++", "i", ")", "{", ...
Sanitizes a string so it can be used as an identifier @param s the string to sanitize @return the sanitized string
[ "Sanitizes", "a", "string", "so", "it", "can", "be", "used", "as", "an", "identifier" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/StringHelper.java#L35-L151
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/StringHelper.java
StringHelper.escapeJava
public static String escapeJava(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(Math.min(2, s.length() * 3 / 2)); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == '\b') { sb.append("\\b"); } else if (c == '\n') { sb.append("\\n"); } else if (c == '\t') { sb.append("\\t"); } else if (c == '\f') { sb.append("\\f"); } else if (c == '\r') { sb.append("\\r"); } else if (c == '\\') { sb.append("\\\\"); } else if (c == '"') { sb.append("\\\""); } else if (c < 32 || c > 0x7f) { sb.append("\\u"); sb.append(hex4(c)); } else { sb.append(c); } } return sb.toString(); }
java
public static String escapeJava(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(Math.min(2, s.length() * 3 / 2)); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == '\b') { sb.append("\\b"); } else if (c == '\n') { sb.append("\\n"); } else if (c == '\t') { sb.append("\\t"); } else if (c == '\f') { sb.append("\\f"); } else if (c == '\r') { sb.append("\\r"); } else if (c == '\\') { sb.append("\\\\"); } else if (c == '"') { sb.append("\\\""); } else if (c < 32 || c > 0x7f) { sb.append("\\u"); sb.append(hex4(c)); } else { sb.append(c); } } return sb.toString(); }
[ "public", "static", "String", "escapeJava", "(", "String", "s", ")", "{", "if", "(", "s", "==", "null", ")", "{", "return", "null", ";", "}", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "Math", ".", "min", "(", "2", ",", "s", ".", "len...
Escapes characters in the given string according to Java rules @param s the string to escape @return the escpaped string
[ "Escapes", "characters", "in", "the", "given", "string", "according", "to", "Java", "rules" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/StringHelper.java#L158-L187
train
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/StringHelper.java
StringHelper.hex4
private static String hex4(char c) { char[] r = new char[] { '0', '0', '0', '0' }; int i = 3; while (c > 0) { r[i] = HEX_DIGITS[c & 0xF]; c >>>= 4; --i; } return new String(r); }
java
private static String hex4(char c) { char[] r = new char[] { '0', '0', '0', '0' }; int i = 3; while (c > 0) { r[i] = HEX_DIGITS[c & 0xF]; c >>>= 4; --i; } return new String(r); }
[ "private", "static", "String", "hex4", "(", "char", "c", ")", "{", "char", "[", "]", "r", "=", "new", "char", "[", "]", "{", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", "}", ";", "int", "i", "=", "3", ";", "while", "(", "c", ...
Converts the given character to a four-digit hexadecimal string @param c the character to convert @return the string
[ "Converts", "the", "given", "character", "to", "a", "four", "-", "digit", "hexadecimal", "string" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/StringHelper.java#L194-L203
train
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/extraction/AbstractFeatureExtractor.java
AbstractFeatureExtractor.extractFeatures
public double[][] extractFeatures(BufferedImage image) throws Exception { long start = System.currentTimeMillis(); double[][] features = extractFeaturesInternal(image); totalNumberInterestPoints += features.length; totalExtractionTime += System.currentTimeMillis() - start; return features; }
java
public double[][] extractFeatures(BufferedImage image) throws Exception { long start = System.currentTimeMillis(); double[][] features = extractFeaturesInternal(image); totalNumberInterestPoints += features.length; totalExtractionTime += System.currentTimeMillis() - start; return features; }
[ "public", "double", "[", "]", "[", "]", "extractFeatures", "(", "BufferedImage", "image", ")", "throws", "Exception", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "double", "[", "]", "[", "]", "features", "=", "extractFeatu...
Any normalizations of the features should be performed in the specific classes! @param image @return @throws Exception
[ "Any", "normalizations", "of", "the", "features", "should", "be", "performed", "in", "the", "specific", "classes!" ]
f82e8e517da706651f4b7a719805401f3102e135
https://github.com/MKLab-ITI/multimedia-indexing/blob/f82e8e517da706651f4b7a719805401f3102e135/src/main/java/gr/iti/mklab/visual/extraction/AbstractFeatureExtractor.java#L33-L39
train
michel-kraemer/citeproc-java
citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/AbstractCSLToolCommand.java
AbstractCSLToolCommand.error
protected void error(String msg) { System.err.println(CSLToolContext.current().getToolName() + ": " + msg); }
java
protected void error(String msg) { System.err.println(CSLToolContext.current().getToolName() + ": " + msg); }
[ "protected", "void", "error", "(", "String", "msg", ")", "{", "System", ".", "err", ".", "println", "(", "CSLToolContext", ".", "current", "(", ")", ".", "getToolName", "(", ")", "+", "\": \"", "+", "msg", ")", ";", "}" ]
Outputs an error message @param msg the message
[ "Outputs", "an", "error", "message" ]
1d5bf0e7bbb2bdc47309530babf0ecaba838bf10
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java-tool/src/main/java/de/undercouch/citeproc/tool/AbstractCSLToolCommand.java#L60-L62
train