_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q177300
AbstractDevice.getCrashLog
test
public String getCrashLog() { String crashLogFileName = null; File crashLogFile = new File(getExternalStoragePath(), crashLogFileName); // the "test" utility doesn't exist on all devices so we'll check the // output of ls. CommandLine directoryListCommand = adbCommand("shell", "ls", crashLogFile.getParentFile().getAbsolutePath()); String directoryList = executeCommandQuietly(directoryListCommand); if (directoryList.contains(crashLogFileName)) { return executeCommandQuietly(adbCommand("shell", "cat", crashLogFile.getAbsolutePath())); } return ""; }
java
{ "resource": "" }
q177301
TextEditor.detabify
test
public TextEditor detabify(final int tabWidth) { replaceAll(Pattern.compile("(.*?)\\t"), new Replacement() { public String replacement(Matcher m) { String lineSoFar = m.group(1); int width = lineSoFar.length(); StringBuilder replacement = new StringBuilder(lineSoFar); do { replacement.append(' '); ++width; } while (width % tabWidth != 0); return replacement.toString(); } }); return this; }
java
{ "resource": "" }
q177302
TextEditor.indent
test
public TextEditor indent(int spaces) { StringBuilder sb = new StringBuilder(spaces); for (int i = 0; i < spaces; i++) { sb.append(' '); } return replaceAll("^", sb.toString()); }
java
{ "resource": "" }
q177303
TextEditor.tokenizeHTML
test
public Collection<HTMLToken> tokenizeHTML() { List<HTMLToken> tokens = new ArrayList<HTMLToken>(); String nestedTags = nestedTagsRegex(6); Pattern p = Pattern.compile("" + "(?s:<!(--.*?--\\s*)+>)" + "|" + "(?s:<\\?.*?\\?>)" + "|" + nestedTags + "", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(text); int lastPos = 0; while (m.find()) { if (lastPos < m.start()) { tokens.add(HTMLToken.text(text.substring(lastPos, m.start()))); } tokens.add(HTMLToken.tag(text.substring(m.start(), m.end()))); lastPos = m.end(); } if (lastPos < text.length()) { tokens.add(HTMLToken.text(text.substring(lastPos, text.length()))); } return tokens; }
java
{ "resource": "" }
q177304
MarkdownProcessor.markdown
test
public String markdown(String txt) { if (txt == null) { txt = ""; } TextEditor text = new TextEditor(txt); // Standardize line endings: text.replaceAll("\\r\\n", "\n"); // DOS to Unix text.replaceAll("\\r", "\n"); // Mac to Unix text.replaceAll("^[ \\t]+$", ""); // Make sure $text ends with a couple of newlines: text.append("\n\n"); text.detabify(); text.deleteAll("^[ ]+$"); hashHTMLBlocks(text); stripLinkDefinitions(text); text = runBlockGamut(text); unEscapeSpecialChars(text); text.append("\n"); return text.toString(); }
java
{ "resource": "" }
q177305
MarkdownProcessor.escapeSpecialCharsWithinTagAttributes
test
private TextEditor escapeSpecialCharsWithinTagAttributes(TextEditor text) { Collection<HTMLToken> tokens = text.tokenizeHTML(); TextEditor newText = new TextEditor(""); for (HTMLToken token : tokens) { String value = token.getText(); if (token.isTag()) { value = value.replaceAll("\\\\", CHAR_PROTECTOR.encode("\\")); value = value.replaceAll("`", CHAR_PROTECTOR.encode("`")); value = value.replaceAll("\\*", CHAR_PROTECTOR.encode("*")); value = value.replaceAll("_", CHAR_PROTECTOR.encode("_")); } newText.append(value); } return newText; }
java
{ "resource": "" }
q177306
ExceptionCollector.addException
test
final void addException(SQLException exception) { if (!(exception instanceof SQLTimeoutException) && !(exception instanceof SQLTransactionRollbackException)) { getOrInit().offer(exception); // SQLExceptions from the above two sub-types are not stored } }
java
{ "resource": "" }
q177307
ClhmStatementCache.close
test
@Override public void close() { if (closed.getAndSet(true)) { return; } for (Map.Entry<StatementMethod, StatementHolder> entry : statementCache.entrySet()) { StatementHolder value = entry.getValue(); statementCache.remove(entry.getKey(), value); quietClose(value.rawStatement()); } }
java
{ "resource": "" }
q177308
BarberProcessor.findParentFqcn
test
private String findParentFqcn(TypeElement typeElement, Set<String> parents) { TypeMirror type; while (true) { type = typeElement.getSuperclass(); if (type.getKind() == TypeKind.NONE) { return null; } typeElement = (TypeElement) ((DeclaredType) type).asElement(); if (parents.contains(typeElement.toString())) { String packageName = getPackageName(typeElement); return packageName + "." + getClassName(typeElement, packageName); } } }
java
{ "resource": "" }
q177309
Barbershop.writeToFiler
test
void writeToFiler(Filer filer) throws IOException { ClassName targetClassName = ClassName.get(classPackage, targetClass); TypeSpec.Builder barberShop = TypeSpec.classBuilder(className) .addModifiers(Modifier.PUBLIC) .addTypeVariable(TypeVariableName.get("T", targetClassName)) .addMethod(generateStyleMethod()) .addMethod(generateCheckParentMethod()); if (parentBarbershop == null) { barberShop.addSuperinterface(ParameterizedTypeName.get(ClassName.get(Barber.IBarbershop.class), TypeVariableName.get("T"))); barberShop.addField(FieldSpec.builder(WeakHashSet.class, "lastStyledTargets", Modifier.PROTECTED).initializer("new $T()", WeakHashSet.class).build()); } else { barberShop.superclass(ParameterizedTypeName.get(ClassName.bestGuess(parentBarbershop), TypeVariableName.get("T"))); } JavaFile javaFile = JavaFile.builder(classPackage, barberShop.build()).build(); javaFile.writeTo(filer); }
java
{ "resource": "" }
q177310
TrieWriter.writeBitVector01Divider
test
public void writeBitVector01Divider(BitVector01Divider divider) throws IOException{ dos.writeBoolean(divider.isFirst()); dos.writeBoolean(divider.isZeroCounting()); }
java
{ "resource": "" }
q177311
BitVectorUtil.appendBitStrings
test
public static void appendBitStrings(BitVector bv, String[] bs){ for(String s : bs){ if(s.length() != 8) throw new RuntimeException( "The length of bit string must be 8 while " + s.length()); for(char c : s.toCharArray()){ if(c == '0') bv.append0(); else if(c == '1') bv.append1(); else throw new RuntimeException("invalid char '" + c + "' for bit string."); } } }
java
{ "resource": "" }
q177312
BitVector01Divider.readFrom
test
public void readFrom(InputStream is) throws IOException{ DataInputStream dis = new DataInputStream(is); first = dis.readBoolean(); zeroCounting = dis.readBoolean(); }
java
{ "resource": "" }
q177313
MTGAPI.getJsonObject
test
private static List<JsonObject> getJsonObject(String path, Gson deserializer) { String url = String.format("%s/%s", ENDPOINT, path); Request request = new Request.Builder().url(url).build(); Response response; try { response = CLIENT.newCall(request).execute(); ArrayList<JsonObject> objectList = new ArrayList<>(); String linkHeader = response.headers().get("Link"); if (linkHeader == null || linkHeader.isEmpty() || path.contains("page=")) { objectList.add(deserializer.fromJson(response.body() .string(), JsonObject.class)); return objectList; } else { int numberOfPages = 0; String[] linkStrings = linkHeader.split(DELIM_LINK); List<String[]> paramList = new ArrayList<>(); for (String link : linkStrings) { paramList.add(link.split(DELIM_LINK_PARAM)); } for (String[] params : paramList) { if (params[1].contains("last")) { Matcher matcher = Pattern.compile("page=[0-9]+").matcher(params[0]); numberOfPages = (matcher.find()) ? Integer.parseInt(matcher.group().substring(5)) : 0; } } objectList.add(deserializer.fromJson(response.body().string(), JsonObject.class)); if (!url.contains("?")) { url += "?"; } for(int i = 1; i <= numberOfPages; i++){ request = new Request.Builder().url(url + "&page=" + i).build(); response = CLIENT.newCall(request).execute(); objectList.add(deserializer.fromJson(response.body().string(), JsonObject.class)); } return objectList; } } catch (IOException e) { throw new HttpRequestFailedException(e); } }
java
{ "resource": "" }
q177314
MTGAPI.getList
test
protected static <TYPE> List<TYPE> getList(String path, String key, Class<TYPE> expectedClass, List<String> filters) { StringBuilder tempPath = new StringBuilder(path); tempPath.append("?"); for (String filter : filters) { tempPath.append(filter).append('&'); } return getList(tempPath.substring(0, tempPath.length() - 1), key, expectedClass); }
java
{ "resource": "" }
q177315
ExtentCucumberFormatter.setKlovReport
test
private static synchronized void setKlovReport() { if (extentReports == null) { //Extent reports object not found. call setExtentReport() first return; } ExtentProperties extentProperties = ExtentProperties.INSTANCE; //if reporter is not null that means it is already attached if (klovReporter != null) { //Already attached, attaching it again will create a new build/klov report return; } if (extentProperties.getKlovServerUrl() != null) { String hostname = extentProperties.getMongodbHost(); int port = extentProperties.getMongodbPort(); String database = extentProperties.getMongodbDatabase(); String username = extentProperties.getMongodbUsername(); String password = extentProperties.getMongodbPassword(); try { //Create a new KlovReporter object klovReporter = new KlovReporter(); if (username != null && password != null) { MongoClientURI uri = new MongoClientURI("mongodb://" + username + ":" + password + "@" + hostname + ":" + port + "/?authSource=" + database); klovReporter.initMongoDbConnection(uri); } else { klovReporter.initMongoDbConnection(hostname, port); } klovReporter.setProjectName(extentProperties.getKlovProjectName()); klovReporter.setReportName(extentProperties.getKlovReportName()); klovReporter.setKlovUrl(extentProperties.getKlovServerUrl()); extentReports.attachReporter(klovReporter); } catch (Exception ex) { klovReporter = null; throw new IllegalArgumentException("Error setting up Klov Reporter", ex); } } }
java
{ "resource": "" }
q177316
Reporter.addScreenCaptureFromPath
test
public static void addScreenCaptureFromPath(String imagePath, String title) throws IOException { getCurrentStep().addScreenCaptureFromPath(imagePath, title); }
java
{ "resource": "" }
q177317
Reporter.setSystemInfo
test
public static void setSystemInfo(String key, String value) { if (systemInfoKeyMap.isEmpty() || !systemInfoKeyMap.containsKey(key)) { systemInfoKeyMap.put(key, false); } if (systemInfoKeyMap.get(key)) { return; } getExtentReport().setSystemInfo(key, value); systemInfoKeyMap.put(key, true); }
java
{ "resource": "" }
q177318
Selector.select
test
public static Selector select( final String propName ) { return new Selector( propName, propName ) { @Override public void handleRow( int index, Map<String, Object> row, Object item, Map<String, FieldAccess> fields ) { getPropertyValueAndPutIntoRow(row, item, fields); } @Override public void handleStart( Collection<?> results ) { } @Override public void handleComplete( List<Map<String, Object>> rows ) { } }; }
java
{ "resource": "" }
q177319
Selector.selectAs
test
public static Selector selectAs( final String propName, final String alias, final Function transform) { return new Selector( propName, alias ) { @Override public void handleRow( int index, Map<String, Object> row, Object item, Map<String, FieldAccess> fields ) { if (!path && fields!=null) { row.put( this.name, transform.apply(fields.get( this.name ).getValue( item )) ); } else { row.put( alias, transform.apply(BeanUtils.atIndex( item, propName )) ); } } @Override public void handleStart( Collection<?> results ) { } @Override public void handleComplete( List<Map<String, Object>> rows ) { } }; }
java
{ "resource": "" }
q177320
Annotations.extractValidationAnnotationData
test
public static List<AnnotationData> extractValidationAnnotationData( Annotation[] annotations, Set<String> allowedPackages ) { List<AnnotationData> annotationsList = new ArrayList<>(); for ( Annotation annotation : annotations ) { AnnotationData annotationData = new AnnotationData( annotation, allowedPackages ); if ( annotationData.isAllowed() ) { annotationsList.add( annotationData ); } } return annotationsList; }
java
{ "resource": "" }
q177321
Annotations.extractAllAnnotationsForProperty
test
private static Annotation[] extractAllAnnotationsForProperty( Class<?> clazz, String propertyName, boolean useRead ) { try { Annotation[] annotations = findPropertyAnnotations( clazz, propertyName, useRead ); /* In the land of dynamic proxied AOP classes, * this class could be a proxy. This seems like a bug * waiting to happen. So far it has worked... */ if ( annotations.length == 0 ) { annotations = findPropertyAnnotations( clazz.getSuperclass(), propertyName, useRead ); } return annotations; } catch ( Exception ex ) { return Exceptions.handle ( Annotation[].class, sputs ( "Unable to extract annotation for property", propertyName, " of class ", clazz, " useRead ", useRead ), ex ); } }
java
{ "resource": "" }
q177322
Annotations.findPropertyAnnotations
test
private static Annotation[] findPropertyAnnotations( Class<?> clazz, String propertyName, boolean useRead ) throws IntrospectionException { PropertyDescriptor propertyDescriptor = getPropertyDescriptor( clazz, propertyName ); if ( propertyDescriptor == null ) { return new Annotation[]{ }; } Method accessMethod = null; if ( useRead ) { accessMethod = propertyDescriptor.getReadMethod(); } else { accessMethod = propertyDescriptor.getWriteMethod(); } if ( accessMethod != null ) { Annotation[] annotations = accessMethod.getAnnotations(); return annotations; } else { return new Annotation[]{ }; } }
java
{ "resource": "" }
q177323
Annotations.doGetPropertyDescriptor
test
private static PropertyDescriptor doGetPropertyDescriptor( final Class<?> type, final String propertyName ) { try { BeanInfo beanInfo = Introspector.getBeanInfo( type ); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for ( PropertyDescriptor pd : propertyDescriptors ) { if ( pd.getName().equals( propertyName ) ) { return pd; } } Class<?> superclass = type.getSuperclass(); if ( superclass != null ) { return doGetPropertyDescriptor( superclass, propertyName ); } return null; } catch ( Exception ex ) { throw new RuntimeException( "Unable to get property " + propertyName + " for class " + type, ex ); } }
java
{ "resource": "" }
q177324
BoonExpressionContext.doLookup
test
private Object doLookup(String objectExpression, Object defaultValue, boolean searchChildren) { if (Str.isEmpty(objectExpression)) { return defaultValue; } char firstChar = Str.idx(objectExpression, 0); char secondChar = Str.idx(objectExpression, 1); char lastChar = Str.idx(objectExpression, -1); boolean escape = false; switch(firstChar) { case '$': if (lastChar=='}') { objectExpression = slc(objectExpression, 2, -1); } else { objectExpression = slc(objectExpression, 1); } break; case '{': if (secondChar=='{' && lastChar=='}') { char thirdChar = Str.idx(objectExpression, 2); if (thirdChar == '{') { escape = true; objectExpression = slc(objectExpression, 3, -3); }else { objectExpression = slc(objectExpression, 2, -2); } } else { if (lastChar == '}') { return jsonParser.parse(objectExpression); } else { escape = true; objectExpression = slc(objectExpression, 1); } } break; case '[': return jsonParser.parse(objectExpression); case '.': if (secondChar=='.') { String newExp = slc(objectExpression, 2); return parent.doLookup(newExp, newExp, false); } } Object value; lastChar = Str.idx(objectExpression, -1); if (lastChar==')') { value = handleFunction(objectExpression, searchChildren); } else { value = findProperty(objectExpression, searchChildren); value = value == null ? defaultValue : value; } if (!escape) { return value; } else { return StandardFunctions.escapeXml(value); } }
java
{ "resource": "" }
q177325
MapObjectConversion.fromMap
test
@SuppressWarnings( "unchecked" ) public static <T> T fromMap( Map<String, Object> map, Class<T> clazz ) { return mapper.fromMap(map, clazz); }
java
{ "resource": "" }
q177326
MapObjectConversion.fromMap
test
@SuppressWarnings( "unchecked" ) public static <T> T fromMap( Map<String, Object> map, Class<T> clazz, String... excludeProperties ) { Set<String> ignoreProps = excludeProperties.length > 0 ? Sets.set(excludeProperties) : null; return new MapperComplex(FieldAccessMode.FIELD_THEN_PROPERTY.create( false ), ignoreProps, null, true).fromMap(map, clazz); }
java
{ "resource": "" }
q177327
MapObjectConversion.fromValueMap
test
@SuppressWarnings("unchecked") public static <T> T fromValueMap( boolean respectIgnore, String view, final FieldsAccessor fieldsAccessor, final Map<String, Value> valueMap, final Class<T> cls, Set<String> ignoreSet ) { Mapper mapper = new MapperComplex(fieldsAccessor, ignoreSet, view, respectIgnore); return mapper.fromValueMap(valueMap, cls); }
java
{ "resource": "" }
q177328
MapObjectConversion.toMap
test
public static Map<String, Object> toMap( final Object object, final String... ignore ) { return toMap( object, Sets.set( ignore ) ); }
java
{ "resource": "" }
q177329
MapObjectConversion.toMap
test
public static Map<String, Object> toMap( final Object object, Set<String> ignore ) { return new MapperComplex(ignore).toMap(object); }
java
{ "resource": "" }
q177330
AnnotationData.doGetValues
test
Map<String, Object> doGetValues(Annotation annotation) { /* Holds the value map. */ Map<String, Object> values = new HashMap<String, Object>(); /* Get the declared staticMethodMap from the actual annotation. */ Method[] methods = annotation.annotationType().getDeclaredMethods(); final Object[] noargs = ( Object[] ) null; /* Iterate through declared staticMethodMap and extract values * by invoking decalared staticMethodMap if they are no arg staticMethodMap. */ for ( Method method : methods ) { /* If it is a no arg method assume it is an annoation value. */ if ( method.getParameterTypes().length == 0 ) { try { /* Get the value. */ Object value = method.invoke( annotation, noargs ); if (value instanceof Enum) { Enum enumVal = (Enum)value; value = enumVal.name (); } values.put( method.getName(), value ); } catch ( Exception ex ) { throw new RuntimeException( ex ); } } } return values; }
java
{ "resource": "" }
q177331
RecursiveDescentPropertyValidator.createValidator
test
protected CompositeValidator createValidator( List<ValidatorMetaData> validationMetaDataList ) { /* * A field (property) can be associated with many validators so we use a * CompositeValidator to hold all of the validators associated with this * validator. */ CompositeValidator compositeValidator = new CompositeValidator(); // hold // all // of // the // validators // associated // with // the // field. /* * Lookup the list of validators for the current field and initialize * them with validation meta-data properties. */ List<FieldValidator> validatorsList = lookupTheListOfValidatorsAndInitializeThemWithMetaDataProperties( validationMetaDataList ); compositeValidator.setValidatorList( validatorsList ); return compositeValidator; }
java
{ "resource": "" }
q177332
RecursiveDescentPropertyValidator.lookupTheListOfValidatorsAndInitializeThemWithMetaDataProperties
test
private List<FieldValidator> lookupTheListOfValidatorsAndInitializeThemWithMetaDataProperties( List<ValidatorMetaData> validationMetaDataList ) { List<FieldValidator> validatorsList = new ArrayList<>(); /* * Look up the crank validators and then apply the properties from the * validationMetaData to them. */ for ( ValidatorMetaData validationMetaData : validationMetaDataList ) { /* Look up the FieldValidator. */ FieldValidator validator = lookupValidatorInRegistry( validationMetaData .getName() ); /* * Apply the properties from the validationMetaData to the * validator. */ applyValidationMetaDataPropertiesToValidator( validationMetaData, validator ); validatorsList.add( validator ); } return validatorsList; }
java
{ "resource": "" }
q177333
RecursiveDescentPropertyValidator.lookupValidatorInRegistry
test
private FieldValidator lookupValidatorInRegistry( String validationMetaDataName ) { Map<String, Object> applicationContext = ValidationContext.get().getObjectRegistry(); Exceptions.requireNonNull( applicationContext ); return ( FieldValidator ) applicationContext .get( "/org/boon/validator/" + validationMetaDataName ); }
java
{ "resource": "" }
q177334
RecursiveDescentPropertyValidator.applyValidationMetaDataPropertiesToValidator
test
private void applyValidationMetaDataPropertiesToValidator( ValidatorMetaData metaData, FieldValidator validator ) { Map<String, Object> properties = metaData.getProperties(); ifPropertyBlankRemove( properties, "detailMessage" ); ifPropertyBlankRemove( properties, "summaryMessage" ); BeanUtils.copyProperties( validator, properties ); }
java
{ "resource": "" }
q177335
RecursiveDescentPropertyValidator.ifPropertyBlankRemove
test
private void ifPropertyBlankRemove( Map<String, Object> properties, String property ) { Object object = properties.get( property ); if ( object == null ) { properties.remove( property ); } else if ( object instanceof String ) { String string = ( String ) object; if ( "".equals( string.trim() ) ) { properties.remove( property ); } } }
java
{ "resource": "" }
q177336
AsyncFileWriterDataStore.tick
test
@Override public void tick(long time) { this.time.set(time); /*Foreign thread every 20 or so mili-seconds so we don't spend too much time figuring out utc time. */ approxTime.set(Dates.utcNow()); }
java
{ "resource": "" }
q177337
SimpleConcurrentCache.size
test
@Override public int size() { int size = 0; for ( SimpleCache<K, V> cache : cacheRegions ) { size += cache.size(); } return size; }
java
{ "resource": "" }
q177338
SimpleConcurrentCache.hash
test
private final int hash( Object k ) { int h = hashSeed; h ^= k.hashCode(); h ^= ( h >>> 20 ) ^ ( h >>> 12 ); return h ^ ( h >>> 7 ) ^ ( h >>> 4 ); }
java
{ "resource": "" }
q177339
LevelDBKeyValueStore.defaultOptions
test
private Options defaultOptions() { Options options = new Options(); options.createIfMissing(true); options.blockSize(32_768); //32K options.cacheSize(67_108_864);//64MB return options; }
java
{ "resource": "" }
q177340
LevelDBKeyValueStore.openDB
test
private boolean openDB(File file, Options options) { try { database = JniDBFactory.factory.open(file, options); logger.info("Using JNI Level DB"); return true; } catch (IOException ex1) { try { database = Iq80DBFactory.factory.open(file, options); logger.info("Using Java Level DB"); return false; } catch (IOException ex2) { return Exceptions.handle(Boolean.class, ex2); } } }
java
{ "resource": "" }
q177341
LevelDBKeyValueStore.putAll
test
@Override public void putAll(Map<byte[], byte[]> values) { WriteBatch batch = database.createWriteBatch(); try { for (Map.Entry<byte[], byte[]> entry : values.entrySet()) { batch.put(entry.getKey(), entry.getValue()); } if (putAllWriteCount.addAndGet(values.size()) > 10_000) { putAllWriteCount.set(0); database.write(batch, flush); } else { database.write(batch, writeOptions); } } finally { closeBatch(batch); } }
java
{ "resource": "" }
q177342
LevelDBKeyValueStore.removeAll
test
@Override public void removeAll(Iterable<byte[]> keys) { WriteBatch batch = database.createWriteBatch(); try { for (byte[] key : keys) { batch.delete(key); } database.write(batch); } finally { closeBatch(batch); } }
java
{ "resource": "" }
q177343
LevelDBKeyValueStore.search
test
@Override public KeyValueIterable<byte[], byte[]> search(byte[] startKey) { final DBIterator iterator = database.iterator(); iterator.seek(startKey); return new KeyValueIterable<byte[], byte[]>() { @Override public void close() { closeIterator(iterator); } @Override public Iterator<Entry<byte[], byte[]>> iterator() { return new Iterator<Entry<byte[], byte[]>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<byte[], byte[]> next() { Map.Entry<byte[], byte[]> next = iterator.next(); return new Entry<>(next.getKey(), next.getValue()); } @Override public void remove() { iterator.remove(); } }; } }; }
java
{ "resource": "" }
q177344
LevelDBKeyValueStore.loadAllByKeys
test
@Override public Map<byte[], byte[]> loadAllByKeys(Collection<byte[]> keys) { if (keys == null || keys.size() == 0) { return Collections.EMPTY_MAP; } Map<byte[], byte[]> results = new LinkedHashMap<>(keys.size()); DBIterator iterator = null; try { iterator = database.iterator(); iterator.seek(keys.iterator().next()); while (iterator.hasNext()) { final Map.Entry<byte[], byte[]> next = iterator.next(); results.put(next.getKey(), next.getValue()); } } finally { try { if (iterator != null) { iterator.close(); } } catch (IOException e) { Exceptions.handle(e); } } return results; }
java
{ "resource": "" }
q177345
LevelDBKeyValueStore.close
test
@Override public void close() { try { flush(); database.close(); } catch (Exception e) { Exceptions.handle(e); } }
java
{ "resource": "" }
q177346
Dbl.reduceBy
test
public static <T> double reduceBy( final double[] array, T object ) { if (object.getClass().isAnonymousClass()) { return reduceByR(array, object ); } try { ConstantCallSite callSite = Invoker.invokeReducerLongIntReturnLongMethodHandle(object); MethodHandle methodHandle = callSite.dynamicInvoker(); try { double sum = 0; for ( double v : array ) { sum = (double) methodHandle.invokeExact( sum, v ); } return sum; } catch (Throwable throwable) { return handle(Long.class, throwable, "Unable to perform reduceBy"); } } catch (Exception ex) { return reduceByR(array, object); } }
java
{ "resource": "" }
q177347
Dbl.reduceByR
test
private static <T> double reduceByR( final double[] array, T object ) { try { Method method = Invoker.invokeReducerLongIntReturnLongMethod(object); double sum = 0; for ( double v : array ) { sum = (double) method.invoke(object, sum, v); } return sum; } catch (Throwable throwable) { return handle(Long.class, throwable, "Unable to perform reduceBy"); } }
java
{ "resource": "" }
q177348
Dbl.varianceDouble
test
public static double varianceDouble(double[] values, final int start, final int length) { double mean = mean(values, start, length); double temp = 0; for(int index = start; index < length; index++) { double a = values[index]; temp += (mean-a)*(mean-a); } return temp / length; }
java
{ "resource": "" }
q177349
Lng.meanDouble
test
public static double meanDouble( long[] values, final int start, final int length ) { double mean = ((double)sum(values, start, length))/ ((double) length); return mean; }
java
{ "resource": "" }
q177350
Invoker.invokeMethodFromObjectArg
test
public static Object invokeMethodFromObjectArg(Object object, MethodAccess method, Object args) { return invokeMethodFromObjectArg(false, null, null, object, method, args); }
java
{ "resource": "" }
q177351
Flt.reduceBy
test
public static double reduceBy( final float[] array, ReduceBy reduceBy ) { double sum = 0; for ( float v : array ) { sum = reduceBy.reduce(sum, v); } return sum; }
java
{ "resource": "" }
q177352
Dates.euroUTCSystemDateString
test
public static String euroUTCSystemDateString( long timestamp ) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis( timestamp ); calendar.setTimeZone( UTC_TIME_ZONE ); int day = calendar.get( Calendar.DAY_OF_MONTH ); int month = calendar.get( Calendar.MONTH ); int year = calendar.get( Calendar.YEAR ); int hour = calendar.get( Calendar.HOUR_OF_DAY ); int minute = calendar.get( Calendar.MINUTE ); int second = calendar.get( Calendar.SECOND ); CharBuf buf = CharBuf.create( 16 ); buf.add( Str.zfill ( day, 2 ) ).add( '_' ); buf.add( Str.zfill( month, 2 ) ).add( '_' ); buf.add( year ).add( '_' ); buf.add( Str.zfill( hour, 2 ) ).add( '_' ); buf.add( Str.zfill( minute, 2 ) ).add( '_' ); buf.add( Str.zfill( second, 2 ) ).add( "_utc_euro" ); return buf.toString(); }
java
{ "resource": "" }
q177353
ObjectFilter.matches
test
public static boolean matches( Object obj, Criteria... exp ) { return ObjectFilter.and( exp ).test( obj ); }
java
{ "resource": "" }
q177354
ObjectFilter.notIn
test
public static Criterion notIn( final Object name, final Object... values ) { return new Criterion<Object>( name.toString(), Operator.NOT_IN, values ) { @Override public boolean resolve( Object owner ) { Object fieldValue = fieldValue(); if ( value == null ) { return false; } return !valueSet().contains( fieldValue ); } }; }
java
{ "resource": "" }
q177355
ObjectFilter.criteriaFromList
test
public static Criteria criteriaFromList(List<?> list) { List<Object> args = new ArrayList(list); Object o = atIndex(args, -1); if (! (o instanceof List) ) { atIndex(args, -1, Collections.singletonList(o)); } return (Criteria) Invoker.invokeFromList(ObjectFilter.class, "createCriteriaFromClass", args); }
java
{ "resource": "" }
q177356
ObjectFilter.criteriaFromJson
test
public static Criteria criteriaFromJson(String json) { return (Criteria) Invoker.invokeFromObject(ObjectFilter.class, "createCriteriaFromClass", fromJson(json)); }
java
{ "resource": "" }
q177357
DoubleList.addArray
test
public boolean addArray(double... integers) { if (end + integers.length >= values.length) { values = grow(values, (values.length + integers.length) * 2); } System.arraycopy(integers, 0, values, end, integers.length); end += integers.length; return true; }
java
{ "resource": "" }
q177358
Ordering.max
test
public static <T> T max( T[] array ) { if (array.length > 1) { Sorting.sortDesc(array); return array[0]; } else { return null; } }
java
{ "resource": "" }
q177359
Ordering.firstOf
test
public static <T> List<T> firstOf( List<T> list, int count, Sort... sorts ) { if (list.size()>1) { Sorting.sort(list, sorts); return Lists.sliceOf(list, 0, count); } else { return null; } }
java
{ "resource": "" }
q177360
Ordering.lastOf
test
public static <T> T lastOf( List<T> list, Sort... sorts ) { if (list.size()>1) { Sorting.sort(list, sorts); return list.get(list.size()-1); } else { return null; } }
java
{ "resource": "" }
q177361
Ordering.lastOf
test
public static <T> List<T> lastOf( List<T> list, int count, Sort... sorts ) { if (list.size()>1) { Sorting.sort(list, sorts); return Lists.endSliceOf(list, count *-1); } else { return null; } }
java
{ "resource": "" }
q177362
Ordering.least
test
public static <T> List<T> least( List<T> list, int count ) { if (list.size()>1) { Sorting.sort(list); return Lists.sliceOf(list, 0, count); } else { return null; } }
java
{ "resource": "" }
q177363
Ordering.min
test
public static <T> T min( List<T> list ) { if (list.size()>1) { Sorting.sort(list); return list.get(0); } else { return null; } }
java
{ "resource": "" }
q177364
Ordering.min
test
public static <T> T min( T[] array, String sortBy ) { if ( array.length > 1 ) { Sorting.sort(array, sortBy); return array[0]; } else { return null; } }
java
{ "resource": "" }
q177365
MapperSimple.processArrayOfMaps
test
private void processArrayOfMaps( Object newInstance, FieldAccess field, Map<String, Object>[] maps) { List<Map<String, Object>> list = Lists.list(maps); handleCollectionOfMaps( newInstance, field, list); }
java
{ "resource": "" }
q177366
MapperSimple.handleCollectionOfMaps
test
@SuppressWarnings("unchecked") private void handleCollectionOfMaps( Object newInstance, FieldAccess field, Collection<Map<String, Object>> collectionOfMaps ) { Collection<Object> newCollection = Conversions.createCollection( field.type(), collectionOfMaps.size() ); Class<?> componentClass = field.getComponentClass(); if ( componentClass != null ) { for ( Map<String, Object> mapComponent : collectionOfMaps ) { newCollection.add( fromMap( mapComponent, componentClass ) ); } field.setObject( newInstance, newCollection ); } }
java
{ "resource": "" }
q177367
MapperSimple.fromMap
test
@Override public Object fromMap(Map<String, Object> map) { String clazz = (String) map.get( "class" ); Class cls = Reflection.loadClass( clazz ); return fromMap(map, cls); }
java
{ "resource": "" }
q177368
ConcurrentLruCache.get
test
@Override public VALUE get( KEY key ) { removeThenAddKey( key ); return map.get( key ); }
java
{ "resource": "" }
q177369
MessageUtils.createToolTipWithNameSpace
test
public static String createToolTipWithNameSpace( final String namespace, final String fieldName, final ResourceBundle bundle, final String toolTipType ) { String toolTip = null; try { try { /** Look for name-space + . + fieldName, e.g., Employee.firstName.toolTip. */ toolTip = bundle.getString( namespace + '.' + fieldName + '.' + toolTipType ); } catch ( MissingResourceException mre ) { /** Look for fieldName only, e.g., firstName.toolTip. */ toolTip = bundle.getString( fieldName + '.' + toolTipType ); } } catch ( MissingResourceException mre ) { } return toolTip; }
java
{ "resource": "" }
q177370
MessageUtils.generateLabelValue
test
public static String generateLabelValue( final String fieldName ) { final StringBuilder buffer = new StringBuilder( fieldName.length() * 2 ); class GenerationCommand { boolean capNextChar = false; boolean lastCharWasUpperCase = false; boolean lastCharWasNumber = false; boolean lastCharWasSpecial = false; boolean shouldContinue = true; char[] chars = fieldName.toCharArray(); void processFieldName() { for ( int index = 0; index < chars.length; index++ ) { char cchar = chars[ index ]; shouldContinue = true; processCharWasNumber( buffer, index, cchar ); if ( !shouldContinue ) { continue; } processCharWasUpperCase( buffer, index, cchar ); if ( !shouldContinue ) { continue; } processSpecialChars( buffer, cchar ); if ( !shouldContinue ) { continue; } cchar = processCapitalizeCommand( cchar ); cchar = processFirstCharacterCheck( buffer, index, cchar ); if ( !shouldContinue ) { continue; } buffer.append( cchar ); } } private void processCharWasNumber( StringBuilder buffer, int index, char cchar ) { if ( lastCharWasSpecial ) { return; } if ( Character.isDigit( cchar ) ) { if ( index != 0 && !lastCharWasNumber ) { buffer.append( ' ' ); } lastCharWasNumber = true; buffer.append( cchar ); this.shouldContinue = false; } else { lastCharWasNumber = false; } } private char processFirstCharacterCheck( final StringBuilder buffer, int index, char cchar ) { /* Always capitalize the first character. */ if ( index == 0 ) { cchar = Character.toUpperCase( cchar ); buffer.append( cchar ); this.shouldContinue = false; } return cchar; } private char processCapitalizeCommand( char cchar ) { /* Capitalize the character. */ if ( capNextChar ) { capNextChar = false; cchar = Character.toUpperCase( cchar ); } return cchar; } private void processSpecialChars( final StringBuilder buffer, char cchar ) { lastCharWasSpecial = false; /* If the character is '.' or '_' then append a space and mark * the next iteration to capitalize. */ if ( cchar == '.' || cchar == '_' ) { buffer.append( ' ' ); capNextChar = true; lastCharWasSpecial = false; this.shouldContinue = false; } } private void processCharWasUpperCase( final StringBuilder buffer, int index, char cchar ) { /* If the character is uppercase, append a space and keep track * that the last character was uppercase for the next iteration. */ if ( Character.isUpperCase( cchar ) ) { if ( index != 0 && !lastCharWasUpperCase ) { buffer.append( ' ' ); } lastCharWasUpperCase = true; buffer.append( cchar ); this.shouldContinue = false; } else { lastCharWasUpperCase = false; } } } GenerationCommand gc = new GenerationCommand(); gc.processFieldName(); /* This is a hack to get address.line_1 to work. */ return buffer.toString().replace( " ", " " ); }
java
{ "resource": "" }
q177371
CharBuf.addHex
test
public CharSequence addHex( final int decoded ) { int _location = location; char [] _buffer = buffer; int _capacity = capacity; if ( 2 + _location > _capacity ) { _buffer = Chr.grow( _buffer ); _capacity = _buffer.length; } _buffer [_location] = (char) encodeNibbleToHexAsciiCharByte( ( decoded >> 4 ) & 0x0F ); _location ++; _buffer [_location] = (char) encodeNibbleToHexAsciiCharByte( decoded & 0x0F );; _location ++; location = _location; buffer = _buffer; capacity = _capacity; return this; }
java
{ "resource": "" }
q177372
BaseDataStore.processReadQueue
test
private void processReadQueue() throws InterruptedException { ReadStatus readStatus = new ReadStatus(); while (true) { DataStoreRequest request = readOperationsQueue.poll(dataStoreConfig.pollTimeoutMS(), TimeUnit.MILLISECONDS); while (request != null) { readStatus.tracker.addCall(request, outputDataQueue); readOperationsBatch.add(request); if (readOperationsBatch.size() > dataStoreConfig.processQueueMaxBatchSize()) { break; } request = readOperationsQueue.poll(); } if (readOperationsBatch.size() > 0) { try { recievedReadBatch(new ArrayList<>(readOperationsBatch)); } finally { readOperationsBatch.clear(); } } else { flushReadsIfNeeded(); } if (readStatus.readBatchSize.size() > 1_000) { StatCount count; final long now = Timer.timer().time(); count = new StatCount(now, DataStoreSource.SERVER, Action.GET_STATS, "Thread TIME USER BaseDataStore " + Thread.currentThread().getName(), Sys.threadUserTime()); this.outputDataQueue.put(count); count = new StatCount(now, DataStoreSource.SERVER, Action.GET_STATS, "Thread TIME CPU BaseDataStore " + Thread.currentThread().getName(), Sys.threadCPUTime()); this.outputDataQueue.put(count); count = new StatCount(now, source, Action.GET, "BaseDataStore readStatus.readBatchSize.max", readStatus.readBatchSize.max()); outputDataQueue.put(count); count = new StatCount(now, source, Action.GET, "BaseDataStore readStatus.readBatchSize.min", readStatus.readBatchSize.min()); outputDataQueue.put(count); count = new StatCount(now, source, Action.GET, "BaseDataStore readStatus.readBatchSize.median", readStatus.readBatchSize.median()); outputDataQueue.put(count); count = new StatCount(now, source, Action.GET, "BaseDataStore readStatus.readBatchSize.mean", readStatus.readBatchSize.mean()); outputDataQueue.put(count); count = new StatCount(now, source, Action.GET, "BaseDataStore readStatus.readBatchSize.standardDeviation", readStatus.readBatchSize.standardDeviation()); outputDataQueue.put(count); count = new StatCount(now, source, Action.GET, "BaseDataStore readStatus.readBatchSize.variance", readStatus.readBatchSize.variance()); outputDataQueue.put(count); readStatus.readBatchSize.clear(); } } }
java
{ "resource": "" }
q177373
BaseDataStore.processWriteQueue
test
private void processWriteQueue() throws InterruptedException { WriteStatus status = new WriteStatus(); while (true) { DataStoreRequest operation = writeOperationsQueue.poll(dataStoreConfig.pollTimeoutMS(), TimeUnit.MILLISECONDS); while (operation != null) { status.tracker.addCall(operation, outputDataQueue); writeOperationsBatch.add(operation); if (writeOperationsBatch.size() > dataStoreConfig.processQueueMaxBatchSize()) { break; } operation = writeOperationsQueue.poll(); } if (writeOperationsBatch.size() > 0) { try { status.writeBatchSize.add(writeOperationsBatch.size()); recievedWriteBatch(new ArrayList<>(writeOperationsBatch)); } finally { writeOperationsBatch.clear(); } } else { flushWritesIfNeeded(); } if (status.writeBatchSize.size() > 1000) { status.sendBatchSize(source, outputDataQueue); } } }
java
{ "resource": "" }
q177374
BaseDataStore.start
test
public void start() { scheduledExecutorService = Executors.newScheduledThreadPool(2, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); thread.setName(" DataQueue Process " + source); return thread; } } ); future = scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (stop.get()) { return; } try { processWriteQueue(); } catch (InterruptedException ex) { //let it restart or stop } catch (Exception ex) { logger.fatal(ex); } } }, 0, dataStoreConfig.threadErrorResumeTimeMS(), TimeUnit.MILLISECONDS); future = scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (stop.get()) { return; } try { processReadQueue(); } catch (InterruptedException ex) { //let it restart or stop } catch (Exception ex) { logger.fatal(ex, "Problem with base data store running scheduled job"); } } }, 0, dataStoreConfig.threadErrorResumeTimeMS(), TimeUnit.MILLISECONDS); }
java
{ "resource": "" }
q177375
Str.atIndex
test
@Universal public static String atIndex( String str, int index, char c ) { return idx (str, index, c); }
java
{ "resource": "" }
q177376
Str.slc
test
@Universal public static String slc( String str, int start ) { return FastStringUtils.noCopyStringFromChars( Chr.slc( FastStringUtils.toCharArray(str), start ) ); }
java
{ "resource": "" }
q177377
Str.in
test
@Universal public static boolean in( char[] chars, String str ) { return Chr.in ( chars, FastStringUtils.toCharArray(str) ); }
java
{ "resource": "" }
q177378
Str.add
test
@Universal public static String add( String str, char c ) { return FastStringUtils.noCopyStringFromChars( Chr.add( FastStringUtils.toCharArray(str), c ) ); }
java
{ "resource": "" }
q177379
Str.addObjects
test
public static String addObjects( Object... objects ) { int length = 0; for ( Object obj : objects ) { if ( obj == null ) { continue; } length += obj.toString().length(); } CharBuf builder = CharBuf.createExact( length ); for ( Object str : objects ) { if ( str == null ) { continue; } builder.add( str.toString() ); } return builder.toString(); }
java
{ "resource": "" }
q177380
Str.compact
test
public static String compact( String str ) { return FastStringUtils.noCopyStringFromChars( Chr.compact( FastStringUtils.toCharArray(str) ) ); }
java
{ "resource": "" }
q177381
Str.split
test
public static String[] split( String str ) { char[][] split = Chr.split( FastStringUtils.toCharArray(str) ); return fromCharArrayOfArrayToStringArray( split ); }
java
{ "resource": "" }
q177382
Str.splitBySpace
test
public static String[] splitBySpace( String str ) { char[][] split = CharScanner.splitBySpace( FastStringUtils.toCharArray(str) ); return fromCharArrayOfArrayToStringArray( split ); }
java
{ "resource": "" }
q177383
Str.splitByPipe
test
public static String[] splitByPipe( String str ) { char[][] split = CharScanner.splitByPipe( FastStringUtils.toCharArray(str) ); return fromCharArrayOfArrayToStringArray( split ); }
java
{ "resource": "" }
q177384
Str.fromCharArrayOfArrayToStringArray
test
public static String[] fromCharArrayOfArrayToStringArray( char[][] split ) { String[] results = new String[ split.length ]; char[] array; for ( int index = 0; index < split.length; index++ ) { array = split[ index ]; results[ index ] = array.length == 0 ? EMPTY_STRING : FastStringUtils.noCopyStringFromChars( array ); } return results; }
java
{ "resource": "" }
q177385
Str.camelCase
test
public static String camelCase( String inStr, boolean upper ) { char[] in = FastStringUtils.toCharArray(inStr); char[] out = Chr.camelCase( in, upper ); return FastStringUtils.noCopyStringFromChars( out ); }
java
{ "resource": "" }
q177386
Str.insideOf
test
public static boolean insideOf(String start, String inStr, String end) { return Chr.insideOf(FastStringUtils.toCharArray(start), FastStringUtils.toCharArray(inStr), FastStringUtils.toCharArray(end)); }
java
{ "resource": "" }
q177387
Str.underBarCase
test
public static String underBarCase( String inStr ) { char[] in = FastStringUtils.toCharArray(inStr); char[] out = Chr.underBarCase( in ); return FastStringUtils.noCopyStringFromChars( out ); }
java
{ "resource": "" }
q177388
Str.num
test
public static String num(Number count) { if (count == null) { return ""; } if (count instanceof Double || count instanceof BigDecimal) { String s = count.toString(); if (idx(s, 1) == '.' && s.length() > 7) { s = slc(s, 0, 5); return s; } else { return s; } } else if (count instanceof Integer || count instanceof Long || count instanceof Short || count instanceof BigInteger){ String s = count.toString(); s = new StringBuilder(s).reverse().toString(); CharBuf buf = CharBuf.create(s.length()); int index = 0; for (char c : s.toCharArray()) { index++; buf.add(c); if (index % 3 == 0) { buf.add(','); } } if (buf.lastChar() == ',') { buf.removeLastChar(); } s = buf.toString(); s = new StringBuilder(s).reverse().toString(); return s; } return count.toString(); }
java
{ "resource": "" }
q177389
Sort.sorts
test
public static Sort sorts( Sort... sorts ) { if ( sorts == null || sorts.length == 0 ) { return null; } Sort main = sorts[ 0 ]; for ( int index = 1; index < sorts.length; index++ ) { main.then( sorts[ index ] ); } return main; }
java
{ "resource": "" }
q177390
Sort.sort
test
public void sort( List list, Map<String, FieldAccess> fields ) { Collections.sort( list, this.comparator( fields ) ); }
java
{ "resource": "" }
q177391
Sort.comparator
test
public Comparator comparator( Map<String, FieldAccess> fields ) { if ( comparator == null ) { comparator = universalComparator(this.getName(), fields, this.getType(), this.childComparators(fields)); } return comparator; }
java
{ "resource": "" }
q177392
Sort.childComparators
test
private List<Comparator> childComparators( Map<String, FieldAccess> fields ) { if ( this.comparators == null ) { this.comparators = new ArrayList<>( this.sorts.size() + 1 ); for ( Sort sort : sorts ) { Comparator comparator = universalComparator( sort.getName(), fields, sort.getType(), sort.childComparators(fields) ); this.comparators.add( comparator ); } } return this.comparators; }
java
{ "resource": "" }
q177393
Maps.valueIn
test
public static <K, V> boolean valueIn( V value, Map<K, V> map ) { return map.containsValue( value ); }
java
{ "resource": "" }
q177394
Int.equalsOrDie
test
public static boolean equalsOrDie(int expected, int got) { if (expected != got) { return die(Boolean.class, "Expected was", expected, "but we got ", got); } return true; }
java
{ "resource": "" }
q177395
Int.equalsOrDie
test
public static boolean equalsOrDie(int[] expected, int[] got) { if (expected.length != got.length) { die("Lengths did not match, expected length", expected.length, "but got", got.length); } for (int index=0; index< expected.length; index++) { if (expected[index]!= got[index]) { die("value at index did not match index", index , "expected value", expected[index], "but got", got[index]); } } return true; }
java
{ "resource": "" }
q177396
Int.sum
test
public static int sum( int[] values, int start, int length ) { long sum = 0; for (int index = start; index < length; index++ ) { sum+= values[index]; } if (sum < Integer.MIN_VALUE) { die ("overflow the sum is too small", sum); } if (sum > Integer.MAX_VALUE) { die ("overflow the sum is too big", sum); } return (int) sum; }
java
{ "resource": "" }
q177397
Int.roundUpToPowerOf2
test
public static int roundUpToPowerOf2( int number ) { int rounded = number >= 1_000 ? 1_000 : ( rounded = Integer.highestOneBit( number ) ) != 0 ? ( Integer.bitCount( number ) > 1 ) ? rounded << 1 : rounded : 1; return rounded; }
java
{ "resource": "" }
q177398
SortingInternal.sort
test
public static void sort( List list, String sortBy, Map<String, FieldAccess> fields, boolean ascending) { sort(list, sortBy, fields, ascending, false); }
java
{ "resource": "" }
q177399
SortingInternal.sort
test
public static void sort( List list, String sortBy, Map<String, FieldAccess> fields, boolean ascending, boolean nullsFirst) { try { /* If this list is null or empty, we have nothing to do so return. */ if ( list == null || list.size() == 0 ) { return; } /* Grab the first item in the list and see what it is. */ Object o = list.get( 0 ); /* if the sort by string is is this, and the object is comparable then use the objects themselves for the sort. */ if ( sortBy.equals( "this" ) ) { Collections.sort(list, thisUniversalComparator(ascending, nullsFirst)); return; } /* If you did not sort by "this", then sort by the field. */ final FieldAccess field = fields.get( sortBy ); if ( field != null ) { Collections.sort( list, Sorting.universalComparator(field, ascending, nullsFirst) ); } } catch (Exception ex) { Exceptions.handle(ex, "list", list, "\nsortBy", sortBy, "fields", fields, "ascending", ascending, "nullFirst", nullsFirst); } }
java
{ "resource": "" }