code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
protected final FaxModemAdapter createFaxModemAdapter()
{
//create new instance
FaxModemAdapter adapter=(FaxModemAdapter)ReflectionHelper.createInstance(this.faxModemClassName);
//initialize
adapter.initialize(this);
return adapter;
} | java |
protected void releaseCommPortConnection()
{
//get reference
Connection<CommPortAdapter> connection=this.commConnection;
this.commConnection=null;
if(connection!=null)
{
//get logger
Logger logger=this.getLogger();
try
{
... | java |
protected Connection<CommPortAdapter> getCommPortConnection()
{
Connection<CommPortAdapter> connection=null;
synchronized(this)
{
boolean connectionValid=true;
//if no connection available
if(this.commConnection==null)
{
connect... | 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("Un... | 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.SE... | 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(... | 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 == '-') {
... | java |
private long computeConfigurationLastModified(List<Resource> configurations) {
long result = 0;
for (Resource configuration : configurations) {
try {
long currentConfigurationLastModified = configuration.lastModified();
if (currentConfigurationLastModified > resu... | 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 ... | 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 (Un... | 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 Em... | 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) {
... | 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 && !getString... | 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 = (HttpURLConn... | 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 I... | java |
public void start()
{
try
{
this.regularBootstrap.bind(new InetSocketAddress(regularConfiguration.getHost(), regularConfiguration.getPort()));
if(logger.isInfoEnabled()) {
logger.info(regularConfiguration.getName() + " started at " + regularConfiguration... | 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(... | java |
protected String getStringSetting(String name, String defaultValue) {
if (settings.containsKey(name)) {
return settings.get(name).toString();
} else {
return defaultValue;
}
} | java |
public void setServices(List<ServiceInfo> services) {
if (services == null || services.size() == 0) {
throw new IllegalArgumentException("services is empty!");
}
this.services = services;
serviceReset = true;
} | java |
private ServiceInfo getRandomService(List<ServiceInfo> serviceList) {
if (serviceList == null || serviceList.size() == 0) {
return null;
}
return serviceList.get(RandomUtils.nextInt(0, serviceList.size()));
} | 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.",... | 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);
... | 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 :... | 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.initi... | java |
public void destroy() {
for (int i = 0; i < rules.size(); i++) {
final Rule rule = (Rule) rules.get(i);
rule.destroy();
}
} | 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.setR... | 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... | 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++) {
v... | 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;
} | 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 = computeNearestCen... | 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.fromJso... | 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... | 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)))... | 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)) {
... | java |
public final Operation getOperation(String name) {
GetOperationRequest request = GetOperationRequest.newBuilder().setName(name).build();
return getOperation(request);
} | java |
public final ListOperationsPagedResponse listOperations(String name, String filter) {
ListOperationsRequest request =
ListOperationsRequest.newBuilder().setName(name).setFilter(filter).build();
return listOperations(request);
} | java |
public final void deleteOperation(String name) {
DeleteOperationRequest request = DeleteOperationRequest.newBuilder().setName(name).build();
deleteOperation(request);
} | 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",
descripti... | 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.PinL... | 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.setTextC... | 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));
}
} | 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++) {
o... | 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(feat... | 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) {
... | 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) {
... | java |
private void setupButtons() {
cancelButton = (TextView) findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(CANCELLED);
finish();
}
});
... | 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;
} | 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 = "dis... | 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;
} | java |
private void disableRed() throws IOException {
byte[] dis = "\u001B[0m".getBytes();
super.write(dis, 0, dis.length);
writing = false;
} | 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 (BufferedInputStrea... | 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(bi... | 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);
/... | java |
protected Token responseToToken(Map<String, String> response) {
return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET));
} | 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);
con... | 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("\"");
} | 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");
}
... | 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.... | 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... | 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)... | 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;
... | 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... | 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);
}
} | 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 =... | 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 ... | java |
private int skipWhitespace() throws IOException {
int c = 0;
do {
c = r.read();
if (c < 0) {
return -1;
}
} while (Character.isWhitespace(c));
return c;
} | 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 == '"' || ... | 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);
}
} | 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.r... | 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);
... | java |
public static String decode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
//should never happen
throw new RuntimeException(e);
}
} | 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 U... | 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;
} | 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();
... | 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 < numProductCentro... | java |
public void loadCoarseQuantizer(String filename) throws IOException {
coarseQuantizer = new double[numCoarseCentroids][vectorLength];
coarseQuantizer = AbstractFeatureAggregator.readQuantizer(filename, numCoarseCentroids, vectorLength);
} | 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 ... | 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]... | 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;... | 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[subQuant... | 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;
} | 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 (... | 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();
In... | 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(n... | 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 Interna... | 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;
I... | 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 cir... | 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... | 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();
fo... | 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;
} | 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] - vec... | 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... | 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;
} | 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.equalsIgnoreCas... | 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);
} | 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 '\u... | 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");
} el... | 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);
} | 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;
} | java |
protected void error(String msg) {
System.err.println(CSLToolContext.current().getToolName() + ": " + msg);
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.