_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q179600
StructsBatchCompiler.internalInstallJvmTypeProvider
test
private void internalInstallJvmTypeProvider(XtextResourceSet resourceSet, File tmpClassDirectory, boolean skipIndexLookup) { Iterable<String> classPathEntries = concat(getClassPathEntries(), getSourcePathDirectories(), asList(tmpClassDirectory.toString())); classPathEntries = filter(classPathEntries, new Predicate<String>() { public boolean apply(String input) { return !Strings.isEmpty(input.trim()); } }); Function<String, URL> toUrl = new Function<String, URL>() { public URL apply(String from) { try { return new File(from).toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } }; Iterable<URL> classPathUrls = Iterables.transform(classPathEntries, toUrl); log.debug("classpath used for Struct compilation : " + classPathUrls); ClassLoader parentClassLoader; if (useCurrentClassLoaderAsParent) { parentClassLoader = currentClassLoader; } else { if (isEmpty(bootClassPath)) { parentClassLoader = ClassLoader.getSystemClassLoader().getParent(); } else { Iterable<URL> bootClassPathUrls = Iterables.transform(getBootClassPathEntries(), toUrl); parentClassLoader = new BootClassLoader(toArray(bootClassPathUrls, URL.class)); } } ClassLoader urlClassLoader = new URLClassLoader(toArray(classPathUrls, URL.class), parentClassLoader); new ClasspathTypeProvider(urlClassLoader, resourceSet, skipIndexLookup ? null : indexedJvmTypeAccess); resourceSet.setClasspathURIContext(urlClassLoader); // for annotation processing we need to have the compiler's classpath as // a parent. URLClassLoader urlClassLoaderForAnnotationProcessing = new URLClassLoader(toArray(classPathUrls, URL.class), currentClassLoader); resourceSet.eAdapters().add(new ProcessorClassloaderAdapter(urlClassLoaderForAnnotationProcessing)); }
java
{ "resource": "" }
q179601
StructsBatchCompiler.cleanFolder
test
protected static boolean cleanFolder(File parentFolder, FileFilter filter, boolean continueOnError, boolean deleteParentFolder) { if (!parentFolder.exists()) { return true; } if (filter == null) filter = ACCEPT_ALL_FILTER; log.debug("Cleaning folder " + parentFolder.toString()); final File[] contents = parentFolder.listFiles(filter); for (int j = 0; j < contents.length; j++) { final File file = contents[j]; if (file.isDirectory()) { if (!cleanFolder(file, filter, continueOnError, true) && !continueOnError) return false; } else { if (!file.delete()) { log.warn("Couldn't delete " + file.getAbsolutePath()); if (!continueOnError) return false; } } } if (deleteParentFolder) { if (parentFolder.list().length == 0 && !parentFolder.delete()) { log.warn("Couldn't delete " + parentFolder.getAbsolutePath()); return false; } } return true; }
java
{ "resource": "" }
q179602
Dispatcher.dispatchOnFxThread
test
public void dispatchOnFxThread(Action action) { if(Platform.isFxApplicationThread()) { actionStream.push(action); } else { Platform.runLater(() -> actionStream.push(action)); } }
java
{ "resource": "" }
q179603
Dispatcher.getActionStream
test
@SuppressWarnings("unchecked") <T extends Action> EventStream<T> getActionStream(Class<T> actionType) { return Dispatcher.getInstance() .getActionStream() .filter(action -> action.getClass().equals(actionType)) .map(action -> (T) action); }
java
{ "resource": "" }
q179604
ViewLoader.createFxmlPath
test
private static String createFxmlPath(Class<?> viewType) { final StringBuilder pathBuilder = new StringBuilder(); pathBuilder.append("/"); if (viewType.getPackage() != null) { pathBuilder.append(viewType.getPackage().getName().replaceAll("\\.", "/")); pathBuilder.append("/"); } pathBuilder.append(viewType.getSimpleName()); pathBuilder.append(".fxml"); return pathBuilder.toString(); }
java
{ "resource": "" }
q179605
RecordJoiner.oneToMany
test
public Stream<Record> oneToMany(Collection<? extends Record> rights, ListKey<Record> manyKey) { return oneToMany(rights.stream(), manyKey); }
java
{ "resource": "" }
q179606
Joiner.manyToOne
test
public Stream<T2<L, R>> manyToOne(Collection<? extends R> rights) { return manyToOne(rights.stream()); }
java
{ "resource": "" }
q179607
Joiner.strictManyToOne
test
public Stream<T2<L, R>> strictManyToOne(Collection<? extends R> rights) { return strictManyToOne(rights.stream()); }
java
{ "resource": "" }
q179608
Joiner.strictOneToOne
test
public Stream<T2<L, R>> strictOneToOne(Collection<? extends R> rights) { return strictOneToOne(rights.stream()); }
java
{ "resource": "" }
q179609
ContentView.getAllowRobots
test
@Override public boolean getAllowRobots(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Page page) throws ServletException, IOException { return PageUtils.findAllowRobots(servletContext, request, response, page); }
java
{ "resource": "" }
q179610
TakeOrderSteps.the_instruction_generated_should_be
test
@Then("^the instruction generated should be \"([^\"]*)\"$") public void the_instruction_generated_should_be(String command) throws Throwable { verify(context.getDrinkMaker()).executeCommand(eq(command)); }
java
{ "resource": "" }
q179611
Effect.main
test
public static void main(String[] args) throws Exception { int n = 1; if(args.length < 1) { usage(); return; } Properties analyzers = new Properties(); analyzers.load(new FileInputStream(new File("analyzer.properties"))); String mode = System.getProperty("mode", "complex"); String a = System.getProperty("analyzer", "mmseg4j"); Analyzer analyzer = null; String an = (String) analyzers.get(a); if(an != null) { analyzer = (Analyzer)Class.forName(an).newInstance(); mode = a; } else { usage(); return; } if(args.length > 1) { try { n = Integer.parseInt(args[1]); } catch (NumberFormatException e) { } } File path = new File(args[0]); System.out.println("analyzer="+analyzer.getClass().getName()); Effect ef = new Effect(path, analyzer); ef.run(mode, n); }
java
{ "resource": "" }
q179612
Performance.main
test
public static void main(String[] args) throws IOException { if(args.length < 1) { System.out.println("Usage:"); System.out.println("\t-Dmode=simple, defalut is complex"); System.out.println("\tPerformance <txt path> - is a directory that contain *.txt"); return; } String mode = System.getProperty("mode", "complex"); Seg seg = null; Dictionary dic = Dictionary.getInstance(); if("simple".equals(mode)) { seg = new SimpleSeg(dic); } else { seg = new ComplexSeg(dic); } File path = new File(args[0]); File[] txts = path.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".txt"); } }); long time = 0; for(File txt : txts) { MMSeg mmSeg = new MMSeg(new InputStreamReader(new FileInputStream(txt)), seg); Word word = null; OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(txt.getAbsoluteFile()+"."+mode+".word"))); BufferedWriter bw = new BufferedWriter(osw); long start = System.currentTimeMillis(); while((word=mmSeg.next())!=null) { bw.append(new String(word.getString())).append("\r\n"); } time += System.currentTimeMillis() - start; bw.close(); } System.out.println("use "+time+"ms"); }
java
{ "resource": "" }
q179613
Chunk.getSumDegree
test
public int getSumDegree() { if(sumDegree < 0) { int sum = 0; for(Word word : words) { if(word != null && word.getDegree() > -1) { sum += word.getDegree(); } } sumDegree = sum; } return sumDegree; }
java
{ "resource": "" }
q179614
JdbcStemmerOverrideFilterFactory.superclassArgs
test
private static Map<String, String> superclassArgs(Map<String, String> args) { Map<String, String> result = new HashMap<>(); // resource loading does not take place if no file has been configured. if (!result.containsKey("dictionary")) { result.put("dictionary", JdbcResourceLoader.DATABASE); } for (String arg : ImmutableList.of("dictionary", "ignoreCase")) { String value = args.get(arg); if (value != null) { result.put(arg, value); } } return result; }
java
{ "resource": "" }
q179615
JdbcKeepWordFilterFactory.inform
test
@Override public void inform(ResourceLoader loader) throws IOException { super.inform(new JdbcResourceLoader(loader, reader, StandardCharsets.UTF_8)); }
java
{ "resource": "" }
q179616
SimpleJdbcReader.checkDatasource
test
protected final void checkDatasource() { // Check database connection information of data source if (dataSource != null) { //noinspection unused,EmptyTryBlock try (Connection connection = dataSource.getConnection()) { // Just get the connection to check if data source parameters are configured correctly. } catch (SQLException e) { dataSource = null; logger.error("Failed to connect to database of data source: {}.", e.getMessage()); if (!ignore) { throw new IllegalArgumentException("Failed to connect to the database.", e); } } } }
java
{ "resource": "" }
q179617
Any.iterableOf
test
@NonNull public static <T> Iterable<T> iterableOf(final InstanceOf<T> type) { return PrivateGenerate.FIXTURE.createMany(type); }
java
{ "resource": "" }
q179618
Any.arrayOf
test
@NonNull public static <T> T[] arrayOf(final Class<T> clazz) { assertIsNotParameterized(clazz, ErrorMessages.msg("arrayOf")); return PrivateGenerate.manyAsArrayOf(TypeToken.of(clazz)); }
java
{ "resource": "" }
q179619
Any.listOf
test
@NonNull public static <T> List<T> listOf(final Class<T> clazz) { assertIsNotParameterized(clazz, ErrorMessages.msg("listOf")); return PrivateGenerate.manyAsListOf(TypeToken.of(clazz)); }
java
{ "resource": "" }
q179620
Any.collectionOf
test
@NonNull public static <T> Collection<T> collectionOf(final InstanceOf<T> typeToken, final InlineConstrainedGenerator<T> omittedValues) { return PrivateGenerate.manyAsListOf(typeToken, omittedValues); }
java
{ "resource": "" }
q179621
AnyVavr.listOf
test
@NonNull public static <T> List<T> listOf(Class<T> clazz) { assertIsNotParameterized(clazz, msg("listOf")); return io.vavr.collection.List.ofAll(Any.listOf(clazz)); }
java
{ "resource": "" }
q179622
AnyVavr.left
test
@NonNull public static <T,U> Either<T, U> left(final Class<T> leftType) { assertIsNotParameterized(leftType, msgInline("left")); return Either.left(Any.instanceOf(leftType)); }
java
{ "resource": "" }
q179623
AnyVavr.right
test
@NonNull public static <T,U> Either<T, U> right(final Class<U> rightType) { assertIsNotParameterized(rightType, msgInline("right")); return Either.right(Any.instanceOf(rightType)); }
java
{ "resource": "" }
q179624
AnyVavr.validationFailed
test
@NonNull public static <T,U> Validation<T, U> validationFailed(final Class<T> type) { assertIsNotParameterized(type, msgInline("validationFailed")); return Validation.invalid(Any.instanceOf(type)); }
java
{ "resource": "" }
q179625
AnyVavr.validationSuccess
test
@NonNull public static <T,U> Validation<T, U> validationSuccess(final Class<U> type) { assertIsNotParameterized(type, msgInline("validationSuccess")); return Validation.valid(Any.instanceOf(type)); }
java
{ "resource": "" }
q179626
AnyVavr.trySuccess
test
@NonNull public static <T> Try<T> trySuccess(final Class<T> type) { assertIsNotParameterized(type, msgInline("trySuccess")); return Try.success(Any.instanceOf(type)); }
java
{ "resource": "" }
q179627
JdbcFixture.connectJdbcOnWithUrlAndDriverAndUsernameAndPassword
test
@SuppressWarnings("unchecked") public boolean connectJdbcOnWithUrlAndDriverAndUsernameAndPassword(String dataBaseId, String url, String driverClassName, String username, String password) throws ReflectiveOperationException { SimpleDriverDataSource dataSource = new SimpleDriverDataSource(); dataSource.setUrl(url); dataSource.setDriverClass((Class<Driver>) Class.forName(driverClassName)); dataSource.setUsername(username); dataSource.setPassword(password); this.templateMap.put(dataBaseId, new JdbcTemplate(dataSource)); return true; }
java
{ "resource": "" }
q179628
JdbcFixture.runInTheSql
test
public boolean runInTheSql(String database, final String sql) { getDatabaseJdbcTemplate(database).update(sql); return true; }
java
{ "resource": "" }
q179629
JdbcFixture.queryInWithSql
test
public String queryInWithSql(String database, String sql) { JdbcTemplate template = getDatabaseJdbcTemplate(database); if (sql != null && !sql.trim().toUpperCase().startsWith(JdbcFixture.SELECT_COMMAND_PREFIX)) { return Objects.toString(template.update(sql)); } List<String> results = template.queryForList(sql, String.class); if(results == null || results.isEmpty()) { return null; } return results.get(0); }
java
{ "resource": "" }
q179630
UBValue.asBoolArray
test
public boolean[] asBoolArray() { boolean[] retval; UBArray array = asArray(); switch(array.getStrongType()){ case Int8: { byte[] data = ((UBInt8Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Int16: { short[] data = ((UBInt16Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Int32: { int[] data = ((UBInt32Array)array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Int64: { long[] data = ((UBInt64Array)array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Float32: { float[] data = ((UBFloat32Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Float64: { double[] data = ((UBFloat64Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } default: throw new RuntimeException("not an int32[] type"); } return retval; }
java
{ "resource": "" }
q179631
Query.byExample
test
public Query<T> byExample(T obj) { if (obj != null) { return dao.getTableHelper().buildFilter(this, obj); } return this; }
java
{ "resource": "" }
q179632
TableHelper.onUpgrade
test
protected void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { db.execSQL(upgradeSql(oldVersion, newVersion)); }
java
{ "resource": "" }
q179633
TableHelper.backup
test
public boolean backup(SQLiteDatabase db, Context ctx, String suffix) { try { new CsvTableWriter(this).dumpToCsv(ctx, db, suffix); } catch (SQLException e) { if (e.getMessage().contains("no such table")) { Log.w(TAG, "Table " + this.getTableName() + " doesn't exist. This is expected if the table is new in this db version."); } } catch (FileNotFoundException e) { e.printStackTrace(); return false; } return true; }
java
{ "resource": "" }
q179634
TableHelper.restore
test
public void restore(SQLiteDatabase db, Context ctx, String suffix) { new CsvTableReader(this).importFromCsv(ctx, db, suffix); }
java
{ "resource": "" }
q179635
ContactActivity.setEmptyText
test
public void setEmptyText(CharSequence emptyText) { if (mListView != null){ View emptyView = mListView.getEmptyView(); if (emptyText instanceof TextView) { ((TextView) emptyView).setText(emptyText); } } }
java
{ "resource": "" }
q179636
CsvTableWriter.dumpToCsv
test
public int dumpToCsv(Context ctx, SQLiteDatabase db, String suffix) throws FileNotFoundException { int numRowsWritten = 0; Cursor c; String filename = getCsvFilename(db.getPath(), db.getVersion(), suffix); c = db.query(th.getTableName(), null, null, null, null, null, null); FileOutputStream fos; fos = ctx.openFileOutput(filename, 0); PrintWriter printWriter = new PrintWriter(fos); String headerRow = buildHeaderRow(); printWriter.println(headerRow); for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c .moveToNext()) { String csv = buildCsvRow(c); printWriter.println(csv); numRowsWritten++; } printWriter.flush(); printWriter.close(); return numRowsWritten; }
java
{ "resource": "" }
q179637
CsvUtils.unescapeCsv
test
public static String unescapeCsv(String str) { if (str == null) return null; if (!(str.charAt(0) == QUOTE && str.charAt(str.length() - 1) == QUOTE)) return str; String quoteless = str.substring(1, str.length() - 1); return quoteless.replace(QUOTE_STR + QUOTE_STR, QUOTE_STR); }
java
{ "resource": "" }
q179638
CsvUtils.getValues
test
public static List<String> getValues(String csvRow) { List<String> values = new ArrayList<String>(); StringReader in = new StringReader(csvRow); String value; try { value = nextValue(in); while (true) { values.add(value); value = nextValue(in); } } catch (IOException e) { // TODO handle case of final null value better? if (csvRow.lastIndexOf(',') == csvRow.length() - 1) values.add(null); return values; } }
java
{ "resource": "" }
q179639
CsvUtils.getAsMap
test
public static Map<String,String> getAsMap(String csvPairs) { Map<String,String> map = new HashMap<String,String>(); String[] pairs = csvPairs.split(","); for (String pair : pairs) { String[] split = pair.split("="); map.put(split[0], split[1]); } return map; }
java
{ "resource": "" }
q179640
CsvUtils.mapToCsv
test
public static String mapToCsv(Map<String,String> map) { StringBuilder sb = new StringBuilder(); for (String key : map.keySet()) { sb.append(","); String val = map.get(key); sb.append(key + "=" + val); } return sb.toString().substring(1); }
java
{ "resource": "" }
q179641
StringUtils.join
test
public static String join(final List<String> list) { // zero, empty or one element if (list == null) { return null; } else if (list.size() == 0) { return ""; } else if (list.size() == 1) { return list.get(0); } // two or more elements final StringBuilder builder = new StringBuilder(); for (String item : list) { if (builder.length() > 0) { builder.append(", "); } builder.append(item); } return builder.toString(); }
java
{ "resource": "" }
q179642
StringUtils.join
test
public static String join(final String[] list) { // zero, empty or one element if (list == null) { return null; } else if (list.length == 0) { return ""; } else if (list.length == 1) { return list[0]; } // two or more elements final StringBuilder builder = new StringBuilder(); for (String item : list) { if (builder.length() > 0) { builder.append(", "); } builder.append(item); } return builder.toString(); }
java
{ "resource": "" }
q179643
DatabaseModel.readFromIndex
test
public static DatabaseModel readFromIndex(BufferedReader reader, ProcessorLogger logger) throws IOException { String dbInfo = reader.readLine(); logger.info(dbInfo); Map<String, String> props = CsvUtils.getAsMap(dbInfo); String dbName = props.get("dbName"); int dbVersion = Integer.parseInt(props.get("dbVersion")); String helperClass = props.get("helperClass"); DatabaseModel dbModel = new DatabaseModel(dbName, dbVersion, helperClass); // read TableHelpers List<String> tables = new ArrayList<String>(); String th = reader.readLine(); while (th != null && !th.equals(StormEnvironment.END_DATABASE)) { tables.add(th); th = reader.readLine(); } dbModel.tableHelpers = tables; return dbModel; }
java
{ "resource": "" }
q179644
DatabaseModel.writeToIndex
test
public void writeToIndex(PrintWriter out) { out.println(StormEnvironment.BEGIN_DATABASE); Map<String,String> dbMap = new HashMap<String,String>(); dbMap.put("dbName", this.getDbName()); dbMap.put("dbVersion", String.valueOf(this.getDbVersion())); dbMap.put("helperClass", this.getQualifiedClassName()); String dbInfo = CsvUtils .mapToCsv(dbMap); out.println(dbInfo); // write TableHelpers for (String th: this.tableHelpers) { out.println(th); } out.println(StormEnvironment.END_DATABASE); }
java
{ "resource": "" }
q179645
EntityProcessor.inspectId
test
private void inspectId() { if (entityModel.getIdField() == null) { // Default to field named "id" List<FieldModel> fields = entityModel.getFields(); for (FieldModel f : fields) { if (EntityModel.DEFAULT_ID_FIELD.equals(f.getFieldName())) { entityModel.setIdField(f); } } } FieldModel idField = entityModel.getIdField(); if (idField != null && "long".equals(idField.getJavaType())) { return; } else { abort("Entity must contain a field named id or annotated with @Id of type long"); } }
java
{ "resource": "" }
q179646
EntityProcessor.getBaseDaoClass
test
private static BaseDaoModel getBaseDaoClass(Entity entity) { String qualifiedName = SQLiteDao.class.getName(); TypeMirror typeMirror = getBaseDaoTypeMirror(entity); if(typeMirror != null) qualifiedName = typeMirror.toString(); return new BaseDaoModel(qualifiedName); }
java
{ "resource": "" }
q179647
FieldModel.getBindType
test
public String getBindType() { String bindType = getConverter().getBindType().name(); return bindType.charAt(0) + bindType.toLowerCase().substring(1); }
java
{ "resource": "" }
q179648
CsvTableReader.importFromCsv
test
public int importFromCsv(Context ctx, SQLiteDatabase db, String suffix) { String filename = getCsvFilename(db.getPath(), db.getVersion(), suffix); FileInputStream fileInputStream; try { fileInputStream = ctx.openFileInput(filename); return importFromCsv(db, fileInputStream); } catch (FileNotFoundException e) { e.printStackTrace(); return -1; } }
java
{ "resource": "" }
q179649
DatabaseHelper.backupAllTablesToCsv
test
public boolean backupAllTablesToCsv(Context ctx, SQLiteDatabase db, String suffix) { boolean allSucceeded = true; for (TableHelper table : getTableHelpers()) { allSucceeded &= table.backup(db, ctx, suffix); } return allSucceeded; }
java
{ "resource": "" }
q179650
DatabaseHelper.restoreAllTablesFromCsv
test
public void restoreAllTablesFromCsv(Context ctx, SQLiteDatabase db, String suffix) { for (TableHelper table : getTableHelpers()) { table.restore(db, ctx, suffix); } }
java
{ "resource": "" }
q179651
StormEnvironment.writeIndex
test
void writeIndex(Filer filer) { StandardLocation location = StandardLocation.SOURCE_OUTPUT; FileObject indexFile; try { indexFile = filer.createResource(location, "com.turbomanage.storm", ENV_FILE); OutputStream fos = indexFile.openOutputStream(); PrintWriter out = new PrintWriter(fos); // Dump converters out.println(BEGIN_CONVERTERS); for (ConverterModel converter : converters) { converter.writeToIndex(out); } out.println(END_CONVERTERS); // Dump databases for (DatabaseModel dbModel : dbModels.values()) { dbModel.writeToIndex(out); } out.close(); } catch (IOException e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q179652
QueryBuilder.createQuery
test
public Query createQuery(final EntityManager manager) { if (manager == null) { throw new NullPointerException("Entity Manager required"); } final Query query = manager.createQuery(render()); for (Parameter<?> parameter : parameters) { parameter.apply(query); } return query; }
java
{ "resource": "" }
q179653
QueryBuilder.createQuery
test
public <T> TypedQuery<T> createQuery(final EntityManager manager, Class<T> type) { if (manager == null) { throw new NullPointerException("Entity Manager required"); } TypedQuery<T> result = manager.createQuery(render(), type); for (Parameter<?> parameter : parameters) { parameter.apply(result); } return result; }
java
{ "resource": "" }
q179654
QueryBuilder.render
test
public String render() { StringBuilder query = new StringBuilder(); if (!select.isEmpty()) { query.append("SELECT "); query.append(StringUtils.join(select.items)); } if (!deleteFrom.isEmpty()) { query.append("DELETE FROM "); query.append(deleteFrom.item); } if (!update.isEmpty()) { query.append("UPDATE "); query.append(update.item); if (!set.isEmpty()) { query.append(" SET "); query.append(StringUtils.join(set.items)); } } if (!from.isEmpty()) { query.append(" FROM "); query.append(StringUtils.join(from.items)); } if (!where.isEmpty()) { query.append(" WHERE "); query.append(where.render()); } if (!group.isEmpty()) { query.append(" GROUP BY "); query.append(StringUtils.join(group.items)); } if (order.isEmpty() == false) { query.append(" ORDER BY "); query.append(StringUtils.join(order.items)); } return query.toString(); }
java
{ "resource": "" }
q179655
SQLiteDao.delete
test
public int delete(Long id) { if (id != null) { return getWritableDb().delete(th.getTableName(), th.getIdCol() + "=?", new String[]{id.toString()}); } return 0; }
java
{ "resource": "" }
q179656
SQLiteDao.save
test
public long save(T obj) { if (th.getId(obj) == 0) { return insert(obj); } long updated = update(obj); if (updated == 1) { return 0; } return -1; }
java
{ "resource": "" }
q179657
SQLiteDao.update
test
public long update(T obj) { ContentValues cv = th.getEditableValues(obj); Long id = th.getId(obj); int numRowsUpdated = getWritableDb().update(th.getTableName(), cv, th.getIdCol() + "=?", new String[] { id.toString() }); return numRowsUpdated; }
java
{ "resource": "" }
q179658
WhereItems.notIn
test
public <V extends Object> WhereItems notIn(final String expression, final V... array) { items.add(new WhereIn(builder(), expression, true, array)); return this; }
java
{ "resource": "" }
q179659
WhereItems.subquery
test
public QueryBuilder subquery(final String lhsPredicate) { final WhereSubquery subquery = new WhereSubquery(builder(), lhsPredicate); items.add(subquery); return subquery.getQueryBuilder(); }
java
{ "resource": "" }
q179660
IntentionStacks.nextActiveStack
test
Stack255 nextActiveStack() { activeStack = (activeStack + 1) % stacks.size(); return (Stack255) stacks.get(activeStack); }
java
{ "resource": "" }
q179661
IntentionStacks.getEmptyIntentionStack
test
Stack255 getEmptyIntentionStack() { // If the active stack is empty then return it (don't check other stacks) if (!stacks.isEmpty() && getActiveStack().isEmpty()) { return getActiveStack(); } // else create an empty stack, add it to the list ot stacks, and return it Stack255 stack = new Stack255((byte) 8, (byte) 2); stacks.push(stack); return stack; }
java
{ "resource": "" }
q179662
PlanBindings.add
test
public void add(Plan plan, Set<Belief> planBindings) { if (plan == null) { return; } // remove any old bindings, making sure to decrement the cached size if (this.bindings.containsKey(plan)) { Set<Belief> oldBindings = this.bindings.remove(plan); if (oldBindings == null || oldBindings.isEmpty()) { cachedsize--; } else { cachedsize -= oldBindings.size(); } } // add this binding and update the cached size this.bindings.put(plan, planBindings); if (planBindings == null || planBindings.isEmpty()) { cachedsize++; } else { cachedsize += planBindings.size(); } }
java
{ "resource": "" }
q179663
PlanBindings.selectPlan
test
public Plan selectPlan(PlanSelectionPolicy policy) { Plan plan = null; int index = 0; switch (policy) { case FIRST: case LAST: Plan[] plans = bindings.keySet().toArray(new Plan[0]); plan = (policy == PlanSelectionPolicy.FIRST) ? plans[0] : plans[plans.length - 1]; index = (policy == PlanSelectionPolicy.FIRST) ? 0 : plans.length - 1; setPlanVariables(plan.getAgent(), plan, bindings.get(plan), index); break; case RANDOM: plan = selectPlanAtRandom(); break; default: // TODO: ignore remaining polic break; } return plan; }
java
{ "resource": "" }
q179664
PlanBindings.selectPlanAtRandom
test
private Plan selectPlanAtRandom() { Plan plan = null; Set<Belief> vars = null; int index = rand.nextInt(size()); int idx = 0; boolean bindingsExist = false; for (Plan p : bindings.keySet()) { vars = bindings.get(p); bindingsExist = (vars != null && !vars.isEmpty()); idx += bindingsExist ? vars.size() : 1; if (idx > index) { plan = p; if (bindingsExist) { index = index - (idx - vars.size()); setPlanVariables(plan.getAgent(), plan, vars, index); } break; } } return plan; }
java
{ "resource": "" }
q179665
PlanBindings.setPlanVariables
test
private final void setPlanVariables(Agent agent, Plan planInstance, Set<Belief> results, int choice) { if (agent == null || planInstance == null) { return; } Belief belief = getResultAtIndex(results, choice); if (belief == null) { return; } Object[] tuple = belief.getTuple(); if (tuple == null) { return; } int index = 0; HashMap<String, Object> vars = new HashMap<String, Object>(); for (Object o : belief.getTuple()) { try { String fieldname = ABeliefStore.getFieldName(agent.getId(), belief.getBeliefset(), index); vars.put(fieldname, o); } catch (BeliefBaseException e) { Log.error( "Agent " + agent.getId() + " could not retrive belief set field: " + e.getMessage()); } index++; } planInstance.setPlanVariables(vars); }
java
{ "resource": "" }
q179666
PlanBindings.getResultAtIndex
test
private Belief getResultAtIndex(Set<Belief> results, int index) { Belief belief = null; if (!(results == null || index < 0 || index >= results.size())) { int idx = 0; for (Belief b : results) { if (idx == index) { belief = b; break; } idx++; } } return belief; }
java
{ "resource": "" }
q179667
GoalPlanType.getParents
test
public byte[] getParents() { if (parents == null) { return null; } byte[] arr = new byte[parents.length]; System.arraycopy(parents, 0, arr, 0, arr.length); return arr; }
java
{ "resource": "" }
q179668
GoalPlanType.getChildren
test
public byte[] getChildren() { if (children == null) { return null; } byte[] arr = new byte[children.length]; System.arraycopy(children, 0, arr, 0, arr.length); return arr; }
java
{ "resource": "" }
q179669
GoalPlanType.grow
test
public static byte[] grow(byte[] bytes, int increment) { if (bytes == null) { return new byte[1]; } byte[] temp = new byte[bytes.length + increment]; System.arraycopy(bytes, 0, temp, 0, bytes.length); return temp; }
java
{ "resource": "" }
q179670
Log.createLogger
test
public static Logger createLogger(String name, Level level, String file) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); PatternLayoutEncoder ple = new PatternLayoutEncoder(); ple.setPattern("%date %level [%thread] %logger{10} [%file:%line]%n%msg%n%n"); ple.setContext(lc); ple.start(); FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>(); fileAppender.setFile(file); fileAppender.setEncoder(ple); fileAppender.setAppend(false); fileAppender.setContext(lc); fileAppender.start(); logger = (Logger) LoggerFactory.getLogger(name); logger.detachAndStopAllAppenders(); // detach console (doesn't seem to work) logger.addAppender(fileAppender); // attach file appender logger.setLevel(level); logger.setAdditive(true); // set to true if root should log too return logger; }
java
{ "resource": "" }
q179671
Plan.step
test
public void step() { if (body == null || body.length == 0 || index < 0 || index >= body.length) { return; } body[index++].step(); }
java
{ "resource": "" }
q179672
AgentType.setGoals
test
public void setGoals(byte[] arr) { if (arr == null) { goals = null; return; } goals = new byte[arr.length]; System.arraycopy(arr, 0, goals, 0, goals.length); }
java
{ "resource": "" }
q179673
Program.pauseForUserInput
test
static void pauseForUserInput() { System.out.println("Press the Enter/Return key to continue.."); Scanner in = new Scanner(System.in); in.nextLine(); in.close(); }
java
{ "resource": "" }
q179674
Program.initIntentionSelectionPools
test
public static void initIntentionSelectionPools(int nagents, int ncores) { Main.poolsize = (nagents > ncores) ? (nagents / ncores) : 1; Main.npools = (nagents > ncores) ? ncores : nagents; }
java
{ "resource": "" }
q179675
Program.initIntentionSelectionThreads
test
static void initIntentionSelectionThreads(Config config) { int ncores = config.getNumThreads(); Main.intentionSelectors = new IntentionSelector[ncores]; for (int i = 0; i < Main.npools; i++) { Main.intentionSelectors[i] = new IntentionSelector(i, config.getRandomSeed()); } }
java
{ "resource": "" }
q179676
Program.startIntentionSelectionThreads
test
static void startIntentionSelectionThreads() { for (int i = 0; i < Main.npools; i++) { Thread thread = new Thread(Main.intentionSelectors[i]); thread.setName("jill-" + i); thread.start(); // start and wait at the entry barrier } }
java
{ "resource": "" }
q179677
Program.shutdownIntentionSelectionThreads
test
static void shutdownIntentionSelectionThreads() { for (int i = 0; i < Main.npools; i++) { Main.intentionSelectors[i].shutdown(); } }
java
{ "resource": "" }
q179678
Program.registerExtension
test
public static void registerExtension(JillExtension extension) { if (extension != null) { GlobalState.eventHandlers.add(extension); Main.logger.info("Registered Jill extension: " + extension); } else { Main.logger.warn("Cannot register null extension; will ignore."); } }
java
{ "resource": "" }
q179679
GlobalState.reset
test
public static void reset() { agentTypes = new AObjectCatalog("agentTypes", 5, 5); goalTypes = new AObjectCatalog("goalTypes", 10, 5); planTypes = new AObjectCatalog("planTypes", 20, 5); agents = null; beliefbase = null; eventHandlers = new HashSet<JillExtension>(); }
java
{ "resource": "" }
q179680
ProgramLoader.loadAgent
test
public static boolean loadAgent(String className, int num, AObjectCatalog agents) { // Load the Agent class Class<?> aclass = loadClass(className, Agent.class); if (aclass == null) { return false; } // Save this agent type to the catalog of known agent types AgentType atype = new AgentType(className); atype.setAgentClass(aclass); GlobalState.agentTypes.push(atype); // Find the goals that this agent has String[] goals = getGoalsFromAgentInfoAnnotation(aclass); if (goals.length == 0) { return false; } // First pass: get the goals and their plans (flat goal-plan list) loadGoalPlanNodes(atype, goals); // Second pass: complete the goal-plan hierarchy completeGoalPlanHierarchy(); // Now create the specified number of instances of this agent type createAgentsInCatalog(agents, atype, aclass, num); // return success return true; }
java
{ "resource": "" }
q179681
ProgramLoader.processPlansForGoal
test
private static boolean processPlansForGoal(GoalType gtype, String[] plans) { for (int j = 0; j < plans.length; j++) { // Load the Plan class Class<?> pclass = loadClass(plans[j], Plan.class); if (pclass == null) { return false; } // Found the plan class, so add this plan to the catalog of known plan types logger.info("Found Plan " + pclass.getName() + " that handles Goal " + gtype.getName()); PlanType ptype = new PlanType(pclass.getName()); ptype.setPlanClass(pclass); GlobalState.planTypes.push(ptype); // Set up the parent/child links between them (makings of a goal-plan tree) ptype.addParent((byte) gtype.getId()); gtype.addChild((byte) ptype.getId()); } return true; }
java
{ "resource": "" }
q179682
ProgramLoader.createAgentsInCatalog
test
private static void createAgentsInCatalog(AObjectCatalog agents, AgentType atype, Class<?> aclass, int num) { int added = 0; try { for (int i = 0; i < num; i++) { // Create a new instance (name prefix 'a' for agents) Agent agent = (Agent) (aclass.getConstructor(String.class).newInstance("a" + Integer.toString(i))); // Assign the static goal plan tree hierarchy to this instance agent.setGoals(atype.getGoals()); // Add this instance to the catalog of agent instances agents.push(agent); added++; } logger.info("Finished loading {} agents", added); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.error("Could not create instance of class " + aclass.getName()); } }
java
{ "resource": "" }
q179683
ProgramLoader.loadClass
test
private static Class<?> loadClass(String className, Class<?> classType) { Class<?> aclass = null; try { aclass = Class.forName(className); } catch (ClassNotFoundException e) { logger.error("Class not found: " + className, e); return null; } if (!classType.isAssignableFrom(aclass)) { logger.error("Class '" + className + "' is not of type " + classType.getName()); return null; } logger.info("Found class " + className + " of type " + classType.getName()); return aclass; }
java
{ "resource": "" }
q179684
ProgramLoader.loadExtension
test
public static JillExtension loadExtension(String className) { JillExtension extension = null; Class<?> eclass; try { // Check that we have the extension class, else abort eclass = Class.forName(className); if (!JillExtension.class.isAssignableFrom(eclass)) { logger .error("Class '" + className + "' does not implement " + JillExtension.class.getName()); return null; } logger.info("Loading extension " + className); extension = (JillExtension) (eclass.newInstance()); } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { logger.error("Could not load extension " + className, e); } return extension; }
java
{ "resource": "" }
q179685
AObject.isNameEqual
test
public static boolean isNameEqual(AObject obj1, AObject obj2) { // Not equal if the names are null, or empty, or not the same size if (obj1.name == null || obj2.name == null || obj1.name.length != obj2.name.length || obj1.name.length == 0) { return false; } // Not equal if any name character is different for (int i = 0; i < obj1.name.length; i++) { if (obj1.name[i] != obj2.name[i]) { return false; } } // Else equal return true; }
java
{ "resource": "" }
q179686
ArgumentsLoader.usage
test
public static String usage() { return GlobalConstant.APP_HEADER + "\n\n" + "usage: " + Main.class.getName() + " [options] --agent-class <agentclass> --num-agents <numagents>" + "\n" + " --config <string> load configuration from string" + "\n" + " --configfile <file> load configuration from file" + "\n" + " --exit-on-idle <boolean> forces system exit when all agents are " + "idle (default is '" + GlobalConstant.EXIT_ON_IDLE + "')\n" + " --help print this usage message and exit \n" + " --plan-selection-policy <policy> policy for selecting from plan instances " + "(FIRST, RANDOM, or LAST (default is '" + GlobalConstant.PLAN_SELECTION_POLICY + "')\n" + " --plan-instances-limit <number> maximum number of applicable plan instances " + "to consider (default is '" + GlobalConstant.PLAN_INSTANCES_LIMIT + "')\n"; }
java
{ "resource": "" }
q179687
ArgumentsLoader.parse
test
public static void parse(String[] args) { for (int i = 0; args != null && i < args.length; i++) { // First parse args that don't require an option if ("--help".equals(args[i])) { abort(null); } // Now parse args that must be accompanied by an option if (i + 1 < args.length) { parseArgumentWithOption(args[i], args[++i]); // force increment the counter } } // Abort if required args were not given if (config == null) { abort("Configuration file or string was not given"); } else if (config.getAgents() == null || config.getAgents().isEmpty()) { abort("Configuration is missing agents specification"); } }
java
{ "resource": "" }
q179688
ArgumentsLoader.parseArgumentWithOption
test
private static void parseArgumentWithOption(String arg, String opt) { switch (arg) { case "--config": config = loadConfigFromString(opt); break; case "--configfile": config = loadConfigFromFile(opt); break; case "--exit-on-idle": GlobalConstant.EXIT_ON_IDLE = Boolean.parseBoolean(opt); break; case "--plan-selection-policy": try { GlobalConstant.PLAN_SELECTION_POLICY = GlobalConstant.PlanSelectionPolicy.valueOf(opt); } catch (IllegalArgumentException e) { abort("Unknown plan selection policy '" + opt + "'"); } break; case "--plan-instances-limit": try { GlobalConstant.PLAN_INSTANCES_LIMIT = Integer.parseInt(opt); } catch (NumberFormatException e) { abort("Option value '" + opt + "' is not a number"); } break; default: // Ignore any other arguments (which may be used by components external to Jill) break; } }
java
{ "resource": "" }
q179689
BeliefBase.doEval
test
public static void doEval(BeliefBase bb, int agentId, String query) throws BeliefBaseException { final long t0 = System.currentTimeMillis(); bb.eval(agentId, query); final long t1 = System.currentTimeMillis(); Log.info("Agent " + agentId + " searched for '" + query + "' " + Log.formattedDuration(t0, t1)); }
java
{ "resource": "" }
q179690
AObjectCatalog.get
test
public AObject get(int index) { if (index >= 0 && index < objects.length) { return objects[index]; } return null; }
java
{ "resource": "" }
q179691
AObjectCatalog.find
test
public AObject find(String name) { for (int i = 0; i < nextid; i++) { if (objects[i].getName().equals(name)) { return objects[i]; } } return null; }
java
{ "resource": "" }
q179692
AObjectCatalog.push
test
public void push(AObject obj) { if (obj == null || obj.getId() != GlobalConstant.NULLID) { return; } // Grow if we are at capacity if (nextid == objects.length) { grow(); } obj.setId(nextid); objects[nextid++] = obj; }
java
{ "resource": "" }
q179693
Stack255.get
test
public Object get(int idx) { int index = idx & 0xff; if (isEmpty()) { // System.err.println("index "+index+" is invalid as stack is empty"); return null; } else if (index < 0 || index >= size) { // System.err.println("index "+index+" is outside of range [0,"+(size-1)+"]"); return null; } return objects[index]; }
java
{ "resource": "" }
q179694
Stack255.push
test
public boolean push(Object obj) { // Cannot add beyond maximum capacity if (isFull()) { return false; } // Grow if we are at capacity if (size == objects.length) { grow(); } objects[size++] = obj; return true; }
java
{ "resource": "" }
q179695
Stack255.pop
test
public Object pop() { if (isEmpty()) { return null; } size--; Object obj = objects[size]; objects[size] = null; return obj; }
java
{ "resource": "" }
q179696
ABeliefStore.getType
test
public static String getType(Object obj) { if (obj == null) { return null; } String type = null; if (obj instanceof String || obj instanceof Integer || obj instanceof Double || obj instanceof Boolean) { type = obj.getClass().getName(); } return type; }
java
{ "resource": "" }
q179697
ABeliefStore.match
test
private static boolean match(Belief belief, AQuery query) { assert (belief != null); assert (query != null); if (belief.getBeliefset() != query.getBeliefset()) { return false; } switch (query.getOp()) { case EQ: Object lhs = belief.getTuple()[query.getField()]; Object rhs = query.getValue(); // Match wildcard or exact string return "*".equals(rhs) || lhs.equals(rhs); case GT: // TODO: Handle Operator.GT case LT: // TODO: Handle Operator.LT default: break; } return false; }
java
{ "resource": "" }
q179698
ABeliefStore.main
test
public static void main(String[] args) throws BeliefBaseException { BeliefBase bb = new ABeliefStore(100, 4); bb.eval(0, "neighbour.age < 31"); Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); } while (true) { Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: ")); Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: ")); boolean found = false; while (matcher.find()) { console.format( "I found the text" + " \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if (!found) { console.format("No match found.%n"); } } }
java
{ "resource": "" }
q179699
AString.toBytes
test
public static byte[] toBytes(String str) { if (str == null) { return new byte[0]; } byte[] val = null; try { val = str.getBytes(CHARSET); } catch (UnsupportedEncodingException e) { // NOPMD - ignore empty catch // Can never occur since CHARSET is correct and final } return val; }
java
{ "resource": "" }