code
stringlengths
73
34.1k
label
stringclasses
1 value
public void setCorridor(float[] target, List<Long> path) { vCopy(m_target, target); m_path = new ArrayList<>(path); }
java
public static int findEdge(Poly node, Poly neighbour, MeshData tile, MeshData neighbourTile) { // Compare indices first assuming there are no duplicate vertices for (int i = 0; i < node.vertCount; i++) { int j = (i + 1) % node.vertCount; for (int k = 0; k < neighbour.vertCount; k++) { int l = (k + 1) % ne...
java
public static int findEdge(Poly node, MeshData tile, float value, int comp) { float error = Float.MAX_VALUE; int edge = 0; for (int i = 0; i < node.vertCount; i++) { int j = (i + 1) % node.vertCount; float v1 = tile.verts[3 * node.verts[i] + comp] - value; float v2 = tile.verts[3 * node.verts[j] + comp] ...
java
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) { for (int n = 0; n < connections.size(); n++) { int[] nodeConnections = connections.get(n); MeshData tile = graphData.getTile(n); Poly node = graphData.getNode(n); for (int connection : nodeConnections) { MeshData neighbourT...
java
private void buildExternalLink(MeshData tile, Poly node, MeshData neighbourTile) { if (neighbourTile.header.bmin[0] > tile.header.bmin[0]) { node.neis[PolyUtils.findEdge(node, tile, neighbourTile.header.bmin[0], 0)] = NavMesh.DT_EXT_LINK; } else if (neighbourTile.header.bmin[0] < tile.header.bmin[0]) { node.n...
java
private static int[] findLeftMostVertex(Contour contour) { int minx = contour.verts[0]; int minz = contour.verts[2]; int leftmost = 0; for (int i = 1; i < contour.nverts; i++) { int x = contour.verts[i * 4 + 0]; int z = contour.verts[i * 4 + 2]; if (x ...
java
public Result<List<Long>> queryPolygons(float[] center, float[] halfExtents, QueryFilter filter) { if (Objects.isNull(center) || !vIsFinite(center) || Objects.isNull(halfExtents) || !vIsFinite(halfExtents) || Objects.isNull(filter)) { // return DT_FAILURE | DT_INVALID_PARAM; ...
java
public Status initSlicedFindPath(long startRef, long endRef, float[] startPos, float[] endPos, QueryFilter filter, int options) { // Init path state. m_query = new QueryData(); m_query.status = Status.FAILURE; m_query.startRef = startRef; m_query.endRef = endRef; ...
java
protected Result<float[]> getEdgeMidPoint(long from, long to) { Result<PortalResult> ppoints = getPortalPoints(from, to); if (ppoints.failed()) { return Result.of(ppoints.status, ppoints.message); } float[] left = ppoints.result.left; float[] right = ppoints.result.ri...
java
public Result<List<Long>> getPathFromDijkstraSearch(long endRef) { if (!m_nav.isValidPolyRef(endRef)) { return Result.invalidParam("Invalid end ref"); } List<Node> nodes = m_nodePool.findNodes(endRef); if (nodes.size() != 1) { return Result.invalidParam("Invalid e...
java
private List<Long> getPathToNode(Node endNode) { List<Long> path = new ArrayList<>(); // Reverse the path. Node curNode = endNode; do { path.add(0, curNode.id); curNode = m_nodePool.getNodeAtIdx(curNode.pidx); } while (curNode != null); return pat...
java
public boolean update() { if (m_update.isEmpty()) { // Process requests. for (ObstacleRequest req : m_reqs) { int idx = decodeObstacleIdObstacle(req.ref); if (idx >= m_obstacles.size()) { continue; } TileCacheObstacle ob = m_obstacles.get(idx); int salt = deco...
java
static float[] randomPointInConvexPoly(float[] pts, int npts, float[] areas, float s, float t) { // Calc triangle araes float areasum = 0.0f; for (int i = 2; i < npts; i++) { areas[i] = triArea2D(pts, 0, (i - 1) * 3, i * 3); areasum += Math.max(0.001f, areas[i]); ...
java
private static float polyMinExtent(float[] verts, int nverts) { float minDist = Float.MAX_VALUE; for (int i = 0; i < nverts; i++) { int ni = (i + 1) % nverts; int p1 = i * 3; int p2 = ni * 3; float maxEdgeDist = 0; for (int j = 0; j < nverts; j...
java
static boolean left(int[] verts, int a, int b, int c) { return area2(verts, a, b, c) < 0; }
java
private static boolean intersectProp(int[] verts, int a, int b, int c, int d) { // Eliminate improper cases. if (collinear(verts, a, b, c) || collinear(verts, a, b, d) || collinear(verts, c, d, a) || collinear(verts, c, d, b)) return false; return (left(verts, a, b, ...
java
private static boolean between(int[] verts, int a, int b, int c) { if (!collinear(verts, a, b, c)) return false; // If ab not vertical, check betweenness on x; else on y. if (verts[a + 0] != verts[b + 0]) return ((verts[a + 0] <= verts[c + 0]) && (verts[c + 0] <= verts[b ...
java
static boolean intersect(int[] verts, int a, int b, int c, int d) { if (intersectProp(verts, a, b, c, d)) return true; else if (between(verts, a, b, c) || between(verts, a, b, d) || between(verts, c, d, a) || between(verts, c, d, b)) return true; else ...
java
private static boolean inCone(int i, int j, int n, int[] verts, int[] indices) { int pi = (indices[i] & 0x0fffffff) * 4; int pj = (indices[j] & 0x0fffffff) * 4; int pi1 = (indices[next(i, n)] & 0x0fffffff) * 4; int pin1 = (indices[prev(i, n)] & 0x0fffffff) * 4; // If P[i] is a co...
java
private static boolean diagonal(int i, int j, int n, int[] verts, int[] indices) { return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices); }
java
public static String encrypt(String c, String key) { try { SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encoded = cipher.doFinal(c...
java
protected void inject(Collection<? extends Expression> objs) { for (Object o : objs) { if (o == null) { continue; } injector.injectMembers(o); } }
java
protected String join(Collection<?> list, String delimiter) { return Joiner.on(delimiter).join(list); }
java
public String translate(final When when) { inject(when.condition); inject(when.action); return String.format("WHEN %s THEN %s", when.condition.translate(), when.action.translate()); }
java
public String translate(final Case aCase) { String elseString = ""; if (aCase.getFalseAction() != null) { inject(aCase.getFalseAction()); elseString = String.format("ELSE %s", aCase.getFalseAction().translate()); } final String whens = aCase.whens.stream() ...
java
public String translate(final Values values) { final ArrayList<Values.Row> rows = new ArrayList<>(values.getRows()); final String[] aliases = values.getAliases(); // If aliases does not exist, throw an exception. // Otherwise, apply them to the columns. if (aliases == null || al...
java
public String translate(final Values.Row row) { inject(row.getExpressions()); final String translation = row.getExpressions().stream() .map(expression -> { // Enforce aliases to be translated. final String alias = expression.isAliased() ? " AS " +...
java
protected Union rowsToUnion(final List<Expression> rows) { // Create an union in form of a binary tree from a list of rows. // The tree shape is to prevent stack overflow on some // database engines when the list of rows is too big. List<Expression> rowsWithSelect = new ArrayList<>(rows...
java
public Query select(final Expression... selectColumns) { if (selectColumns == null) { return this; } return select(Arrays.asList(selectColumns)); }
java
private Expression getParsedOrderByColumn(final Expression column) { if (column instanceof Name) { final Name columnName = (Name) column; final String environment = columnName.getEnvironment(); if (environment != null && !environment.isEmpty()) { final Expres...
java
protected void start() { // if a periodic execution throws an exception, future executions are suspended, // this task wraps the call in a try-catch block to prevent that. Errors are still propagated. final Runnable resilientTask = () -> { try { run(); } c...
java
public void destroy() { logger.trace("{} - Destroy called on Batch", name); scheduler.shutdown(); try { if (!scheduler.awaitTermination(maxAwaitTimeShutdown, TimeUnit.MILLISECONDS)) { logger.warn( "Could not terminate batch within {}. Forcing ...
java
public void flush() { List<BatchEntry> temp; bufferLock.lock(); try { // Reset the last flush timestamp, even if the batch is empty or flush fails lastFlush = System.currentTimeMillis(); // No-op if batch is empty if (batch == batchSize) { ...
java
public final void merge(final Properties properties) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { setProperty(entry.getKey().toString(), entry.getValue().toString()); } }
java
public int getIsolationLevel() { final Optional<IsolationLevel> e = Enums.getIfPresent(IsolationLevel.class, getProperty(ISOLATION_LEVEL).toUpperCase()); if (!e.isPresent()) { throw new DatabaseEngineRuntimeException(ISOLATION_LEVEL + " must be set and be one of the following: " + EnumSet.a...
java
public void checkMandatoryProperties() throws PdbConfigurationException { StringBuilder exceptionMessage = new StringBuilder(); if (StringUtils.isBlank(getJdbc())) { exceptionMessage.append("- A connection string should be declared under the 'database.jdbc' property.\n"); } ...
java
private String reorg(String tableName) { List<String> statement = new ArrayList<>(); statement.add("CALL sysproc.admin_cmd('REORG TABLE"); statement.add(quotize(tableName)); statement.add("')"); return join(statement, " "); }
java
private String alterColumnSetNotNull(String tableName, List<String> columnNames) { List<String> statement = new ArrayList<>(); statement.add("ALTER TABLE"); statement.add(quotize(tableName)); for (String columnName : columnNames) { statement.add("ALTER COLUMN"); ...
java
public static String md5(final String message) { byte[] res; try { MessageDigest instance = MessageDigest.getInstance("MD5"); instance.reset(); instance.update(message.getBytes()); res = instance.digest(); } catch (final NoSuchAlgorithmException ...
java
public static String md5(final String message, final int nchar) { final String hash = md5(message); return nchar > hash.length() ? hash : hash.substring(0, nchar); }
java
public static String readString(final InputStream stream) throws IOException { InputStreamReader br = null; StringBuilder sb = new StringBuilder(); try { br = new InputStreamReader(stream); int got; while (!Thread.currentThread().isInterrupted()) { ...
java
@Override protected Object processObject(Object o) { if (o instanceof PGobject && ((PGobject)o).getType().equals("jsonb")) { return ((PGobject) o).getValue(); } return super.processObject(o); }
java
public static DatabaseEngine getConnection(Properties p) throws DatabaseFactoryException { PdbProperties pdbProperties = new PdbProperties(p, true); final String engine = pdbProperties.getEngine(); if (StringUtils.isBlank(engine)) { throw new DatabaseFactoryException("pdb.engine pro...
java
public static Case caseWhen(final Expression condition, final Expression trueAction) { return Case.caseWhen(condition, trueAction); }
java
public static Expression in(final Expression e1, final Expression e2) { return new RepeatDelimiter(IN, e1.isEnclosed() ? e1 : e1.enclose(), e2.isEnclosed() ? e2 : e2.enclose()); }
java
public static Expression notIn(final Expression e1, final Expression e2) { return new RepeatDelimiter(NOTIN, e1.isEnclosed() ? e1 : e1.enclose(), e2.isEnclosed() ? e2 : e2.enclose()); }
java
public static Between between(final Expression exp1, final Expression exp2, final Expression exp3) { return new Between(exp1, and(exp2, exp3)); }
java
public static Between notBetween(final Expression exp1, final Expression exp2, final Expression exp3) { return new Between(exp1, and(exp2, exp3)).not(); }
java
public static AlterColumn alterColumn(Expression table, Name column, DbColumnType dbColumnType, DbColumnConstraint... constraints) { return alterColumn( table, dbColumn().name(column.getName()).type(dbColumnType).addConstraints(constraints).build()); }
java
public static DbColumn.Builder dbColumn(String name, DbColumnType type, boolean autoInc) { return new DbColumn.Builder().name(name).type(type).autoInc(autoInc); }
java
public With andWith(final String alias, final Expression expression) { this.clauses.add(new ImmutablePair<>(new Name(alias), expression)); return this; }
java
private void setAnsiMode() throws SQLException { Statement s = conn.createStatement(); s.executeUpdate("SET sql_mode = 'ansi'"); s.close(); }
java
public boolean containsColumn(String columnName) { return columns.stream() .map(DbColumn::getName) .anyMatch(listColName -> listColName.equals(columnName)); }
java
public Builder newBuilder() { return new Builder() .name(name) .addColumn(columns) .addFk(fks) .pkFields(pkFields) .addIndexes(indexes); }
java
public Case when(final Expression condition, final Expression action) { whens.add(When.when(condition, action)); return this; }
java
private Object getJSONValue(String val) throws DatabaseEngineException { try { PGobject dataObject = new PGobject(); dataObject.setType("jsonb"); dataObject.setValue(val); return dataObject; } catch (final SQLException ex) { throw new DatabaseE...
java
public Expression leftOuterJoin(final Expression table, final Expression expr) { if (table instanceof Query) { table.enclose(); } joins.add(new Join("LEFT OUTER JOIN", table, expr)); return this; }
java
public Builder newBuilder() { return new Builder() .name(name) .type(dbColumnType) .size(size) .addConstraints(columnConstraints) .autoInc(autoInc) .defaultValue(defaultValue); }
java
protected String getPrivateKey() throws Exception { String location = this.properties.getProperty(SECRET_LOCATION); if (StringUtils.isBlank(location)) { throw new DatabaseEngineException("Encryption was specified but there's no location specified for the private key."); } Fi...
java
@Override public synchronized void close() { try { for (final PreparedStatementCapsule preparedStatement : stmts.values()) { try { preparedStatement.ps.close(); } catch (final SQLException e) { logger.warn("Could not close ...
java
private void addEntity(DbEntity entity, boolean recovering) throws DatabaseEngineException { if (!recovering) { try { getConnection(); } catch (final Exception e) { throw new DatabaseEngineException("Could not add entity", e); } va...
java
@Override public synchronized void dropEntity(String entity) throws DatabaseEngineException { if (!containsEntity(entity)) { return; } dropEntity(entities.get(entity).getEntity()); }
java
@Override public synchronized void dropEntity(final DbEntity entity) throws DatabaseEngineException { dropSequences(entity); dropTable(entity); entities.remove(entity.getName()); logger.trace("Entity {} dropped", entity.getName()); }
java
private void dropAllEntities() { for (final MappedEntity mappedEntity : ImmutableList.copyOf(entities.values())) { try { dropEntity(mappedEntity.getEntity()); } catch (final DatabaseEngineException ex) { logger.debug(String.format("Failed to drop entity '...
java
@Override public synchronized void flush() throws DatabaseEngineException { /* * Reconnect on this method does not make sense since a new connection will have nothing to flush. */ try { for (MappedEntity me : entities.values()) { me.getInsert().executeB...
java
@Override public synchronized int executeUpdate(final String query) throws DatabaseEngineException { Statement s = null; try { getConnection(); s = conn.createStatement(); return s.executeUpdate(query); } catch (final Exception ex) { throw new ...
java
@Override public synchronized int executeUpdate(final Expression query) throws DatabaseEngineException { /* * Reconnection is already assured by "void executeUpdate(final String query)". */ final String trans = translate(query); logger.trace(trans); return executeUp...
java
@Override public synchronized boolean checkConnection(final boolean forceReconnect) { if (checkConnection(conn)) { return true; } else if (forceReconnect) { try { connect(); recover(); return true; } catch (final Ex...
java
@Override public synchronized void addBatch(final String name, final EntityEntry entry) throws DatabaseEngineException { try { final MappedEntity me = entities.get(name); if (me == null) { throw new DatabaseEngineException(String.format("Unknown entity '%s'", name)...
java
@Override public synchronized DatabaseEngine duplicate(Properties mergeProperties, final boolean copyEntities) throws DuplicateEngineException { if (mergeProperties == null) { mergeProperties = new Properties(); } final PdbProperties niwProps = properties.clone(); niwPro...
java
@Override public synchronized List<Map<String, ResultColumn>> getPSResultSet(final String name) throws DatabaseEngineException { return processResultIterator(getPSIterator(name)); }
java
@Override public synchronized void executePS(final String name) throws DatabaseEngineException, ConnectionResetException { final PreparedStatementCapsule ps = stmts.get(name); if (ps == null) { throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' does not ...
java
@Override public synchronized void clearParameters(final String name) throws DatabaseEngineException, ConnectionResetException { final PreparedStatementCapsule ps = stmts.get(name); if (ps == null) { throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' doe...
java
@Override public synchronized Integer executePSUpdate(final String name) throws DatabaseEngineException, ConnectionResetException { final PreparedStatementCapsule ps = stmts.get(name); if (ps == null) { throw new DatabaseEngineRuntimeException(String.format("PreparedStatement named '%s' ...
java
private void createPreparedStatement(final String name, final String query, final int timeout, final boolean recovering) throws NameAlreadyExistsException, DatabaseEngineException { if (!recovering) { if (stmts.containsKey(name)) { throw new NameAlreadyExistsException(String.format(...
java
protected final synchronized byte[] objectToArray(Object val) throws IOException { final ByteArrayOutputStream bos = new InitiallyReusableByteArrayOutputStream(getReusableByteBuffer()); final ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(val); return bos.toByteAr...
java
public boolean hasIdentityColumn(DbEntity entity) { for (final DbColumn column : entity.getColumns()) { if (column.isAutoInc()) { return true; } } return false; }
java
public static Properties getPropertiesFromClasspath(String fileName) throws PropertiesFileNotFoundException { Properties props = new Properties(); try { InputStream is = ClassLoader.getSystemResourceAsStream(fileName); if (is == null) { // try this instead is = Thread.currentThread()....
java
public static Properties getPropertiesFromPath(String fileName) throws PropertiesFileNotFoundException { Properties props = new Properties(); FileInputStream fis; try { fis = new FileInputStream(fileName); props.load(fis); fis.close(); } catch (Exception e) { throw new Pro...
java
public static int execute(String sql, Object[] params) throws YankSQLException { return execute(YankPoolManager.DEFAULT_POOL_NAME, sql, params); }
java
public static int execute(String poolName, String sql, Object[] params) throws YankSQLException { int returnInt = 0; try { returnInt = new QueryRunner(YANK_POOL_MANAGER.getConnectionPool(poolName)).update(sql, params); } catch (SQLException e) { handleSQLException(e, poolName, sql)...
java
public static <T> T queryScalar(String sql, Class<T> scalarType, Object[] params) throws SQLStatementNotFoundException, YankSQLException { return queryScalar(YankPoolManager.DEFAULT_POOL_NAME, sql, scalarType, params); }
java
public static <T> T queryScalar(String poolName, String sql, Class<T> scalarType, Object[] params) throws SQLStatementNotFoundException, YankSQLException { T returnObject = null; try { ScalarHandler<T> resultSetHandler; if (scalarType.equals(Integer.class)) { resultSetHandler = (Scal...
java
public static <T> T queryBean(String sql, Class<T> beanType, Object[] params) throws YankSQLException { return queryBean(YankPoolManager.DEFAULT_POOL_NAME, sql, beanType, params); }
java
public static <T> T queryBean(String poolName, String sql, Class<T> beanType, Object[] params) throws YankSQLException { T returnObject = null; try { BeanHandler<T> resultSetHandler = new BeanHandler<T>(beanType, new BasicRowProcessor(new YankBeanProcessor<T>(beanType))); returnO...
java
public static <T> List<T> queryBeanList(String sql, Class<T> beanType, Object[] params) throws YankSQLException { return queryBeanList(YankPoolManager.DEFAULT_POOL_NAME, sql, beanType, params); }
java
public static <T> List<T> queryBeanList( String poolName, String sql, Class<T> beanType, Object[] params) throws YankSQLException { List<T> returnList = null; try { BeanListHandler<T> resultSetHandler = new BeanListHandler<T>( beanType, new BasicRowProcessor(new YankBeanPr...
java
public static <T> List<T> queryColumn( String sql, String columnName, Class<T> columnType, Object[] params) throws YankSQLException { return queryColumn(YankPoolManager.DEFAULT_POOL_NAME, sql, columnName, columnType, params); }
java
public static <T> List<T> queryColumn( String poolName, String sql, String columnName, Class<T> columnType, Object[] params) throws YankSQLException { List<T> returnList = null; try { ColumnListHandler<T> resultSetHandler; if (columnType.equals(Integer.class)) { resultSetHandle...
java
public static int[] executeBatch(String sql, Object[][] params) throws YankSQLException { return executeBatch(YankPoolManager.DEFAULT_POOL_NAME, sql, params); }
java
public static int[] executeBatch(String poolName, String sql, Object[][] params) throws YankSQLException { int[] returnIntArray = null; try { returnIntArray = new QueryRunner(YANK_POOL_MANAGER.getConnectionPool(poolName)).batch(sql, params); } catch (SQLException e) { handleS...
java
private static void handleSQLException(SQLException e, String poolName, String sql) { YankSQLException yankSQLException = new YankSQLException(e, poolName, sql); if (throwWrappedExceptions) { throw yankSQLException; } else { logger.error(yankSQLException.getMessage(), yankSQLException); } ...
java
private void createPool(String poolName, Properties connectionPoolProperties) { releaseConnectionPool(poolName); // DBUtils execute methods require autoCommit to be true. connectionPoolProperties.put("autoCommit", true); HikariConfig config = new HikariConfig(connectionPoolProperties); config.set...
java
protected synchronized void releaseConnectionPool(String poolName) { HikariDataSource pool = pools.get(poolName); if (pool != null) { logger.info("Releasing pool: {}...", pool.getPoolName()); pool.close(); } }
java
protected synchronized void releaseAllConnectionPools() { for (HikariDataSource pool : pools.values()) { if (pool != null) { logger.info("Releasing pool: {}...", pool.getPoolName()); pool.close(); } } }
java
@Override public int compareTo(DetectedLanguage o) { int compare = Double.compare(o.probability, this.probability); if (compare!=0) return compare; return this.locale.toString().compareTo(o.locale.toString()); }
java
public static void main(String[] args) throws IOException { CommandLineInterface cli = new CommandLineInterface(); cli.addOpt("-d", "directory", "./"); cli.addOpt("-a", "alpha", "" + DEFAULT_ALPHA); cli.addOpt("-s", "seed", null); cli.parse(args); if (cli.hasParam("--gen...
java
private void parse(String[] args) { for (int i=0; i<args.length; i++) { if (opt_with_value.containsKey(args[i])) { String key = opt_with_value.get(args[i]); values.put(key, args[i+1]); i++; } else if (args[i].startsWith("-")) { ...
java
private double getParamDouble(String key, double defaultValue) { String value = values.get(key); if (value==null || value.isEmpty()) { return defaultValue; } try { return Double.valueOf(value); } catch (NumberFormatException e) { throw new Runt...
java
public void generateProfile() { File directory = new File(arglist.get(0)); String lang = arglist.get(1); File file = searchFile(directory, lang + "wiki-.*-abstract\\.xml.*"); if (file == null) { System.err.println("Not Found text file : lang = " + lang); return; ...
java