auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testListBreak() { String html = parseToHtml("* item 1" + BR + "* item 2" + BR + "" + BR + "first list done" + BR + "- item 3" + BR); assertEquals("testListBreak", html, "<ul>" + "<li> item 1</li>" + "<li> item 2</li></ul>" + "<p>first list done</p>" + BR + "<ul><li> item 3</li></ul>"); }

Target:
public void testListBreak() { String html = parseToHtml("* item 1" + BR + "* item 2" + BR + "" + BR + "first list done" + BR + "- item 3" + BR); assertEquals("testListBreak", "" + "<ul>" + "<li>item 1</li>" + "<li>item 2</li></ul>" + "<p>first list done</p>\n" + "<ul><li>item 3</li></ul>", html); }
Source:
public void initLandmarkWeights(final int lmIdx, int lmNodeId, final long rowSize, final int offset) { IntObjectMap<SPTEntry> map = from ? bestWeightMapFrom : bestWeightMapTo; final AtomicInteger maxedout = new AtomicInteger(0); final Map.Entry<Double, Double> finalMaxWeight = new MapEntry<>(0d, 0d); map.forEach(new IntObjectProcedure<SPTEntry>() { @Override public void apply(int nodeId, SPTEntry b) { if (!lms.setWeight(nodeId * rowSize + lmIdx * 4 + offset, b.weight)) { maxedout.incrementAndGet(); finalMaxWeight.setValue(Math.max(b.weight, finalMaxWeight.getValue())); } } }); if ((double) maxedout.get() / map.size() > 0.1) { LOGGER.warn("landmark " + lmIdx + " (" + nodeAccess.getLatitude(lmNodeId) + "," + nodeAccess.getLongitude(lmNodeId) + "): " + "too many weights were maxed out (" + maxedout.get() + "/" + map.size() + "). Use a bigger factor than " + lms.factor + ". For example use the following in the config.properties: weighting=" + weighting.getName() + "|maximum=" + finalMaxWeight.getValue() * 1.2 / PRECISION); } }

Target:
public void initLandmarkWeights(final int lmIdx, int lmNodeId, final long rowSize, final int offset) { IntObjectMap<SPTEntry> map = from ? bestWeightMapFrom : bestWeightMapTo; final AtomicInteger maxedout = new AtomicInteger(0); final Map.Entry<Double, Double> finalMaxWeight = new MapEntry<>(0d, 0d); map.forEach(new IntObjectProcedure<SPTEntry>() { @Override public void apply(int nodeId, SPTEntry b) { if (!lms.setWeight(nodeId * rowSize + lmIdx * 4 + offset, b.weight)) { maxedout.incrementAndGet(); finalMaxWeight.setValue(Math.max(b.weight, finalMaxWeight.getValue())); } } }); if ((double) maxedout.get() / map.size() > 0.1) { LOGGER.warn("landmark " + lmIdx + " (" + nodeAccess.getLatitude(lmNodeId) + "," + nodeAccess.getLongitude(lmNodeId) + "): " + "too many weights were maxed out (" + maxedout.get() + "/" + map.size() + "). Use a bigger factor than " + lms.factor + ". For example use the following in the config.properties: weighting=" + weighting.getName() + "|maximum=" + finalMaxWeight.getValue() * 1.2); } }
Source:
public Repository openMetadataRepository(Project.NameKey name) throws RepositoryNotFoundException, IOException { return openRepository(name); }

Target:
public Repository openMetadataRepository(Project.NameKey name) throws RepositoryNotFoundException, IOException { return openRepository(noteDbPath, name); }
Source:
public boolean clickModerationHintButton() { click(By.id("moderationHintButton")); WebElement moderationHint = browser.driver.findElement(By.id("moderationHint")); return moderationHint.isDisplayed(); }

Target:
public void clickModerationHintButton() { click(By.id("moderationHintButton")); }
Source:
public void testGetMilisToNextSunrise() { System.out.println("getMilisToNextSunrise"); long dayToMilis = 86400000; Calendar calendar = Calendar.getInstance(); long nextSunrise = DateTimeUtils.getMilisToNextSunrise(calendar, 40.4131699, -3.6830699); assertTrue(nextSunrise < dayToMilis); }

Target:
public void testGetMilisToNextSunrise() { System.out.println("getMilisToNextSunrise"); Calendar calendar = Calendar.getInstance(); long nextSunrise = DateTimeUtils.getMilisToNextSunrise(calendar, LATITUDE, LONGITUDE); assertTrue(nextSunrise < DAYTOMILIS); }
Source:
private byte[] generateRandomData(int dataSize, boolean useChars) { byte[] buffer = null; if (useChars) { String singleByteChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String multiByteChars = "ÅÄÇÉÑÖÕÜàäâáãçëèêéîïìíñôöòóüûùúÿ"; String punctuationChars = "!,.;?"; int maxWordLength = 20; StringBuffer data = new StringBuffer(); while (data.toString().getBytes().length < dataSize) { int wordLength = random.nextInt(maxWordLength); for (int i = 0; i < wordLength; i++) { if (random.nextBoolean() || dataSize - data.toString().getBytes().length == 1) { data.append(singleByteChars.charAt(random.nextInt(singleByteChars.length() - 1))); } else { data.append(multiByteChars.charAt(random.nextInt(multiByteChars.length() - 1))); } } if (random.nextBoolean()) { data.append(punctuationChars.charAt(random.nextInt(punctuationChars.length() - 1))); } if (random.nextBoolean()) { data.append(' '); } else { data.append('\n'); } } buffer = Arrays.copyOf(data.toString().getBytes(), dataSize); } else { buffer = new byte[dataSize]; random.nextBytes(buffer); } return buffer; }

Target:
private byte[] generateRandomData(int dataSize, boolean useChars) { byte[] buffer = null; if (useChars) { String punctuationChars = "!,.;?"; ByteBuffer data = ByteBuffer.allocate(dataSize); int remainingBytes = dataSize; int maxWordLength = 20; while (remainingBytes > 0) { byte[] word = this.generateRandomWord(maxWordLength); data = data.put(word); remainingBytes -= word.length; if (remainingBytes >= 2 && random.nextInt() % 5 == 0 && random.nextBoolean()) { data.put((byte) punctuationChars.charAt(random.nextInt(punctuationChars.length() - 1))); data.put((byte) '\n'); remainingBytes -= 2; } else { if (remainingBytes >= 1) { data.put((byte) ' '); remainingBytes--; } } if (remainingBytes < maxWordLength) { maxWordLength = remainingBytes; } } buffer = data.array(); } else { buffer = new byte[dataSize]; random.nextBytes(buffer); } return buffer; }
Source:
public void stopSyncAndJournal(RpcContext rpcContext, AlluxioURI syncPoint) throws InvalidPathException { try (LockResource r = new LockResource(mLock)) { MountTable.Resolution resolution = mMountTable.resolve(syncPoint); if (resolution == null) { throw new InvalidPathException(syncPoint + " is not a sync point."); } LOG.debug("stop syncPoint {}", syncPoint.getPath()); final long mountId = resolution.getMountId(); RemoveSyncPointEntry removeSyncPoint = File.RemoveSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()) .setMountId(mountId) .build(); applyAndJournal(rpcContext, removeSyncPoint); try { stopSyncInternal(syncPoint); } catch (Throwable e) { LOG.warn("Stop sync failed on {}", syncPoint, e); AddSyncPointEntry addSyncPoint = File.AddSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()).build(); applyAndJournal(rpcContext, addSyncPoint); recoverFromStopSync(syncPoint); } } }

Target:
public void stopSyncAndJournal(RpcContext rpcContext, AlluxioURI syncPoint) throws InvalidPathException { try (LockResource r = new LockResource(mLock)) { MountTable.Resolution resolution = mMountTable.resolve(syncPoint); if (resolution == null) { throw new InvalidPathException("Failed to stop sync point " + syncPoint + " because it is not mounted."); } LOG.debug("stop syncPoint {}", syncPoint.getPath()); final long mountId = resolution.getMountId(); RemoveSyncPointEntry removeSyncPoint = File.RemoveSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()) .setMountId(mountId) .build(); applyAndJournal(rpcContext, removeSyncPoint); try { stopSyncInternal(syncPoint); } catch (Throwable e) { LOG.warn("Stop sync failed on {}", syncPoint, e); AddSyncPointEntry addSyncPoint = File.AddSyncPointEntry.newBuilder() .setSyncpointPath(syncPoint.toString()).build(); applyAndJournal(rpcContext, addSyncPoint); recoverFromStopSync(syncPoint); } } }
Source:
public String send(String message) throws ProducerException { ProducerRecord record = new ProducerRecord<>(topic, null, message); try { RecordMetadata result = (RecordMetadata)kafkaProducer.send(record).get(); return result.topic() + "-" + result.partition() + "-" + result.offset(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ProducerException("Error sending Kafka Message", e); } catch (ExecutionException e) { throw new ProducerException("Error sending Kafka Message", e); } }

Target:
public String send(String message) throws ProducerException { return sendForkliftWrappedMessage(message, null); }
Source:
public Locale getCurrentTimeLocale() { Locale set; if (TimeInfo.getTimeInfoByDisplayName(preferencesService.getPreferences().getChat().getUkTime()).equals(TimeInfo.AUTO)) { set = locale; } else { set = TimeInfo.getTimeInfoByDisplayName(preferencesService.getPreferences().getChat().getUkTime()).getUsedLocale(); } return set; }

Target:
private Locale getCurrentTimeLocale() { ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); if (chatPrefs.getTimeFormat().equals(TimeInfo.AUTO)) { return Locale.getDefault(); } return preferencesService.getPreferences().getChat().getTimeFormat().getUsedLocale(); }
Source:
private void handleBulletCreation(ByteBuffer input) { GameObjectDAO data = new GameObjectDAO(); data.x = input.getDouble(); data.y = input.getDouble(); data.height = input.getDouble(); data.velocityX = input.getDouble(); data.velocityY = input.getDouble(); data.bulletType = Bullet.Type.values()[input.getInt()]; data.damage = input.getDouble(); data.ownerId = input.getInt(); data.objectId = input.getInt(); map.addGameObject(data); }

Target:
private void handleBulletCreation(ByteBuffer input) { GameObjectDAO data = new GameObjectDAO(); data.x = input.getDouble(); data.y = input.getDouble(); data.height = input.getDouble(); data.velocityX = input.getDouble(); data.velocityY = input.getDouble(); data.bulletType = Bullet.Type.fromInteger(input.getInt()); data.damage = input.getDouble(); data.ownerId = input.getInt(); data.objectId = input.getInt(); data.entityType = EntityFactory.EntityType.fromInteger(input.getInt()); map.addGameObject(data); }
Source:
private String getPathForContainer(IContainer container) { return container.getLocation().toOSString(); }

Target:
private String getPathForContainer(IContainer container) { return container.getLocation().toPortableString(); }
Source:
protected void readValue(BlockBuilder blockBuilder, Type type) { if (definitionLevel == columnDescriptor.getMaxDefinitionLevel()) { type.writeDouble(blockBuilder, valuesReader.readDouble()); } else if (isNullValue()) { blockBuilder.appendNull(); } }

Target:
protected void readValue(BlockBuilder blockBuilder, Type type) { if (definitionLevel == columnDescriptor.getMaxDefinitionLevel()) { type.writeDouble(blockBuilder, valuesReader.readDouble()); } else if (isValueNull()) { blockBuilder.appendNull(); } }
Source:
private String getZoneFromEureka() { String zone; boolean approximateZoneFromHostname = Boolean.parseBoolean( environment.getProperty(APPROXIMATE_ZONE_FROM_HOSTNAME, "false")); if (approximateZoneFromHostname && eurekaConfig != null) { return ZoneUtils.extractApproximateZone(this.eurekaConfig.getHostName(false)); } else { zone = eurekaConfig == null ? null : eurekaConfig.getMetadataMap().get("zone"); if (zone == null) { String[] zones = clientConfig .getAvailabilityZones(clientConfig.getRegion()); zone = zones != null && zones.length > 0 ? zones[0] : null; } return zone; } }

Target:
private String getZoneFromEureka() { String zone; boolean approximateZoneFromHostname = eurekaLoadBalancerProperties .isApproximateZoneFromHostname(); if (approximateZoneFromHostname && eurekaConfig != null) { return ZoneUtils.extractApproximateZone(this.eurekaConfig.getHostName(false)); } else { zone = eurekaConfig == null ? null : eurekaConfig.getMetadataMap().get("zone"); if (StringUtils.isEmpty(zone)) { String[] zones = clientConfig .getAvailabilityZones(clientConfig.getRegion()); zone = zones != null && zones.length > 0 ? zones[0] : null; } return zone; } }
Source:
public boolean isIgnored(File targetFile) throws IOException { String target = targetFile.getAbsolutePath(); if (!target.startsWith(baseDir.getAbsolutePath())) { return false; } if (rules.isEmpty()) { try { parse(); } catch (IOException e) { e.printStackTrace(); } } if (rules == null || rules.size() == 0) return false; matched = false; String tar = target.replaceFirst(baseDir.getAbsolutePath(), ""); int i; for (i = rules.size() -1; i > -1; i--) { matched = rules.get(i).isMatch(tar, targetFile.isDirectory()); if (matched) { break; } } if (i > -1 && rules.get(i) != null) { return rules.get(i).getResult(); } return false; }

Target:
public boolean isIgnored(File targetFile) throws IOException { String target = targetFile.getAbsolutePath(); if (!target.startsWith(baseDir.getAbsolutePath())) { return false; } if (rules.isEmpty()) { try { parse(); } catch (IOException e) { e.printStackTrace(); } } if (rules.isEmpty()) return false; matched = false; String tar = target.replaceFirst(baseDir.getAbsolutePath(), ""); int i; for (i = rules.size() -1; i > -1; i--) { matched = rules.get(i).isMatch(tar, targetFile.isDirectory()); if (matched) { break; } } if (i > -1 && rules.get(i) != null) { return rules.get(i).getResult(); } return false; }
Source:
protected void handleMergeFailure(@NonNull AuthCredential credential) { IdpResponse failureResponse = new IdpResponse.Builder(credential) .build(); setResult(Resource.<IdpResponse>forFailure(new FirebaseAuthAnonymousUpgradeException( ErrorCodes.ANONYMOUS_UPGRADE_MERGE_CONFLICT, failureResponse))); }

Target:
protected void handleMergeFailure(@NonNull AuthCredential credential) { IdpResponse failureResponse = new IdpResponse.Builder(credential).build(); handleMergeFailure(failureResponse); }
Source:
public void execute() { if (state.getGhost().isPresent() && state.getOriginalParent().isPresent()) { final CaseManagementShapeView ghost = state.getGhost().get(); final WiresContainer originalParent = state.getOriginalParent().get(); reparentDraggedShape(ghost, originalParent); } clearState(); batch(); }

Target:
public void execute() { state.getGhost().ifPresent(ghost -> state.getOriginalParent().ifPresent(originalParent -> reparentDraggedShape(ghost, originalParent) ) ); clearState(); batch(); }
Source:
public static void main(String[] args) { boolean error = false; int minApi = 1; FolderType type = FolderType.SDK; String baseFolder = null; String outPath = null; for (int i = 0; i < args.length && !error; i++) { String arg = args[i]; if (arg.equals("--prebuilt")) { type = FolderType.PREBUILT; } else if (arg.equals("--min-api")) { i++; if (i < args.length) { minApi = Integer.parseInt(args[i]); } else { System.err.println("Missing number >= 1 after " + arg); error = true; } } else if (baseFolder == null) { baseFolder = arg; } else if (outPath == null) { outPath = arg; } else { System.err.println("Unknown argument: " + arg); error = true; } } if (!error && baseFolder == null) { System.err.println("Missing base folder"); error = true; } if (!error && outPath == null) { System.err.println("Missing out file path"); error = true; } if (error) { printUsage(); } AndroidJarReader reader = new AndroidJarReader(type, baseFolder, minApi); Map<String, ApiClass> classes = reader.getClasses(); createApiFile(new File(outPath), classes); }

Target:
public static void main(String[] args) { boolean error = false; int minApi = 1; ArrayList<String> patterns = new ArrayList<String>(); String outPath = null; for (int i = 0; i < args.length && !error; i++) { String arg = args[i]; if (arg.equals("--pattern")) { i++; if (i < args.length) { patterns.add(args[i]); } else { System.err.println("Missing argument after " + arg); error = true; } } else if (arg.equals("--min-api")) { i++; if (i < args.length) { minApi = Integer.parseInt(args[i]); } else { System.err.println("Missing number >= 1 after " + arg); error = true; } } else if (arg.length() >= 2 && arg.substring(0, 2).equals("--")) { System.err.println("Unknown argument: " + arg); error = true; } else if (outPath == null) { outPath = arg; } else if (new File(arg).isDirectory()) { String pattern = arg; if (!pattern.endsWith(File.separator)) { pattern += File.separator; } pattern += "platforms" + File.separator + "android-%" + File.separator + "android.jar"; patterns.add(pattern); } else { System.err.println("Unknown argument: " + arg); error = true; } } if (!error && outPath == null) { System.err.println("Missing out file path"); error = true; } if (!error && patterns.isEmpty()) { System.err.println("Missing SdkFolder or --pattern."); error = true; } if (error) { printUsage(); System.exit(1); } AndroidJarReader reader = new AndroidJarReader(patterns, minApi); Map<String, ApiClass> classes = reader.getClasses(); if (!createApiFile(new File(outPath), classes)) { System.exit(1); } }
Source:
public void updateCache(AttestationValue value) { AttestationValue cacheValue = attestationValues.get(value.getHostName()); if (cacheValue != null) { cacheValue.setTrustLevel(value.getTrustLevel()); } }

Target:
public void updateCache(AttestationValue value) { AttestationValue cacheValue = attestationValues.get(value.getHostName()); if (cacheValue != null) { cacheValue.setTrustLevel(value.getTrustLevel()); }else{ addToCache(value); } }
Source:
public Bitmap getImage(String url) { final File file = storedFile(url); byte[] bytes = null; if (null == file || !file.exists()) { try { bytes = mPoster.performRequest(url, null); } catch (IOException e) { Log.i(LOGTAG, "Can't download bitmap", e); } catch (RemoteService.ServiceUnavailableException e) { Log.i(LOGTAG, "Couldn't download "); } } final Bitmap bitmap; if (null != bytes) { if (null != file && bytes.length < MAX_BITMAP_SIZE) { OutputStream out = null; try { out = new FileOutputStream(file); out.write(bytes); } catch (FileNotFoundException e) { Log.e(LOGTAG, "It appears that ImageStore is misconfigured, or disk storage is unavailable- can't write to bitmap directory", e); } catch (IOException e) { Log.w(LOGTAG, "Can't store bitmap", e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { Log.w(LOGTAG, "Problem closing output file", e); } } } } bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (null == bitmap) { Log.w(LOGTAG, "Downloaded bitmap could not be interpreted"); } } else { bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); if (null == bitmap) { Log.w(LOGTAG, "Bitmap on disk can't be opened or is corrupt"); final boolean ignored = file.delete(); } } return bitmap; }

Target:
public Bitmap getImage(String url) throws CantGetImageException { final File file = storedFile(url); byte[] bytes = null; if (null == file || !file.exists()) { try { bytes = mPoster.performRequest(url, null); } catch (IOException e) { throw new CantGetImageException("Can't download bitmap", e); } catch (RemoteService.ServiceUnavailableException e) { throw new CantGetImageException("Couldn't download image due to service availability", e); } } final Bitmap bitmap; if (null != bytes) { if (null != file && bytes.length < MAX_BITMAP_SIZE) { OutputStream out = null; try { out = new FileOutputStream(file); out.write(bytes); } catch (FileNotFoundException e) { throw new CantGetImageException("It appears that ImageStore is misconfigured, or disk storage is unavailable- can't write to bitmap directory", e); } catch (IOException e) { throw new CantGetImageException("Can't store bitmap", e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { Log.w(LOGTAG, "Problem closing output file", e); } } } } bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (null == bitmap) { throw new CantGetImageException("Downloaded data could not be interpreted as a bitmap"); } } else { bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); if (null == bitmap) { final boolean ignored = file.delete(); throw new CantGetImageException("Bitmap on disk can't be opened or was corrupt"); } } return bitmap; }
Source:
public void test1AUY() throws IOException, StructureException { AtomCache cache = new AtomCache(); StructureIO.setAtomCache(cache); cache.setUseMmCif(true); Structure s1 = StructureIO.getStructure("1AUY"); CrystalBuilder cb = new CrystalBuilder(s1); StructureInterfaceList interfaces = cb.getUniqueInterfaces(5.5); assertTrue(interfaces.size()==12); }

Target:
public void test1AUY() throws IOException, StructureException { AtomCache cache = new AtomCache(); StructureIO.setAtomCache(cache); cache.setUseMmCif(true); Structure s1 = StructureIO.getStructure("1AUY"); CrystalBuilder cb = new CrystalBuilder(s1); StructureInterfaceList interfaces = cb.getUniqueInterfaces(5.5); assertEquals(12,interfaces.size()); s1.getCrystallographicInfo().setCrystalCell(null); cb = new CrystalBuilder(s1); interfaces = cb.getUniqueInterfaces(5.5); assertEquals(12,interfaces.size()); }
Source:
void createTestGraph( GraphDatabaseService graphDb ) { IndexDefinition index; try ( Transaction tx = graphDb.beginTx() ) { index = graphDb.schema().indexFor( label( "Node" ) ).on( "prop" ).create(); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { graphDb.schema().awaitIndexOnline( index, 5, SECONDS ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { graphDb.createNode( label( "Node" ) ).setProperty( "prop", "one" ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", "two" ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", "two" ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", "three" ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", "three" ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", "three" ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 4 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 5 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 6 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 12 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 18 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 24 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 30 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 36 ); graphDb.createNode( label( "Node" ) ).setProperty( "prop", 42 ); tx.success(); } }

Target:
void createTestGraph( GraphDatabaseService graphDb ) { IndexDefinition index; try ( Transaction tx = graphDb.beginTx() ) { index = graphDb.schema().indexFor( label( "Node" ) ).on( "prop" ).create(); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { graphDb.schema().awaitIndexOnline( index, 5, SECONDS ); tx.success(); } try ( Transaction tx = graphDb.beginTx() ) { strOne = nodeWithProp( graphDb, "one" ); strTwo1 = nodeWithProp( graphDb, "two" ); strTwo2 = nodeWithProp( graphDb, "two" ); strThree1 = nodeWithProp( graphDb, "three" ); strThree2 = nodeWithProp( graphDb, "three" ); strThree3 = nodeWithProp( graphDb, "three" ); nodeWithProp( graphDb, false ); boolTrue = nodeWithProp( graphDb, true ); nodeWithProp( graphDb, 4 ); num5 = nodeWithProp( graphDb, 5 ); num6 = nodeWithProp( graphDb, 6 ); num12a = nodeWithProp( graphDb, 12.0 ); num12b = nodeWithProp( graphDb, 12.0 ); nodeWithProp( graphDb, 18 ); nodeWithProp( graphDb, 24 ); nodeWithProp( graphDb, 30 ); nodeWithProp( graphDb, 36 ); nodeWithProp( graphDb, 42 ); tx.success(); } }
Source:
@Override protected void onNewChannelCreated(Channel ch) { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setWantClientAuth(true); sslEngine.setUseClientMode(false); ch.pipeline().addFirst(new SslHandler(sslEngine)); }

Target:
protected void onNewChannelCreated(Channel ch) { SSLEngine sslEngine = createSllEngineForChannel(ch); sslEngine.setWantClientAuth(true); sslEngine.setUseClientMode(false); ch.pipeline().addFirst(new SslHandler(sslEngine)); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } return element.equals(obj); }

Target:
public boolean equals(Object obj) { if (element == null) { return super.equals(obj); } if (this == obj) { return true; } return element.equals(obj); }
Source:
<V> void validate(FieldDescriptor descriptor, V fieldValue, String fieldName) throws ConstraintViolationThrowable; T build() throws ConstraintViolationThrowable; ValidatingBuilder<T, B> mergeFrom(T message); @Internal void setOriginalState(T state); @Internal boolean isDirty(); @Internal void clear(); enum GenericParameter { MESSAGE(0), MESSAGE_BUILDER(1); private final int index; GenericParameter(int index) { this.index = index; } public int getIndex() { return this.index; } }

Target:
<V> void validate(FieldDescriptor descriptor, V fieldValue, String fieldName) throws ConstraintViolationThrowable; T build() throws ConstraintViolationThrowable; ValidatingBuilder<T, B> mergeFrom(T message); @Internal void setOriginalState(T state); @Internal boolean isDirty(); @Internal void clear(); enum GenericParameter implements GenericTypeIndex { MESSAGE(0), MESSAGE_BUILDER(1); private final int index; GenericParameter(int index) { this.index = index; } @Override public int getIndex() { return this.index; } }
Source:
public static <T> SizeEstimator<T> create(DataType<?> type) { switch (type.id()) { case UndefinedType.ID: case ObjectType.ID: case GeoShapeType.ID: return (SizeEstimator<T>) new SamplingSizeEstimator<>(SAMPLE_EVERY_NTH, MapSizeEstimator.INSTANCE); case StringType.ID: case IpType.ID: return (SizeEstimator<T>) StringSizeEstimator.INSTANCE; case ArrayType.ID: var innerEstimator = create(((ArrayType<?>) type).innerType()); return (SizeEstimator<T>) ArraySizeEstimator.create(innerEstimator); default: if (type instanceof FixedWidthType) { return (SizeEstimator<T>) new ConstSizeEstimator(((FixedWidthType) type).fixedSize()); } throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "Cannot get SizeEstimator for type %s", type)); } }

Target:
public static <T> SizeEstimator<T> create(DataType<?> type) { switch (type.id()) { case UndefinedType.ID: return (SizeEstimator<T>) new ConstSizeEstimator(UNKNOWN_DEFAULT_RAM_BYTES_USED); case ObjectType.ID: case GeoShapeType.ID: return (SizeEstimator<T>) new SamplingSizeEstimator<>(SAMPLE_EVERY_NTH, MapSizeEstimator.INSTANCE); case StringType.ID: case IpType.ID: return (SizeEstimator<T>) StringSizeEstimator.INSTANCE; case ArrayType.ID: var innerEstimator = create(((ArrayType<?>) type).innerType()); return (SizeEstimator<T>) ArraySizeEstimator.create(innerEstimator); default: if (type instanceof FixedWidthType) { return (SizeEstimator<T>) new ConstSizeEstimator(((FixedWidthType) type).fixedSize()); } throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "Cannot get SizeEstimator for type %s", type)); } }
Source:
public void testEncodeDecode() { SerializableTestObject b = new SerializableTestObject(); final byte[] encoded = SerializableObjectTranscoder.INSTANCE.encode(b); final SerializableTestObject testObject = (SerializableTestObject) SerializableObjectTranscoder.INSTANCE.decode(encoded); assertEquals("hello", testObject.value1); assertEquals("world", testObject.value2); assertEquals(5, testObject.value3); }

Target:
public void testEncodeDecode() { SerializableTestObject b = new SerializableTestObject(); b.value1 = "hello"; b.value2 = "world"; b.value3 = 5; final byte[] encoded = SerializableObjectTranscoder.INSTANCE.encode(b); final SerializableTestObject testObject = (SerializableTestObject) SerializableObjectTranscoder.INSTANCE.decode(encoded); assertEquals("hello", testObject.value1); assertEquals("world", testObject.value2); assertEquals(5, testObject.value3); }
Source:
public FilterHandler(String unparsedFilters) { String[] rawFilters = unparsedFilters.split(","); filters = new Filter[rawFilters.length]; for (int i = 0; i < rawFilters.length; i++) { String currentFilter = rawFilters[i]; int period = currentFilter.lastIndexOf('.'); Filter filter = new Filter(currentFilter.substring(0, period), currentFilter.substring(period + 1)); filters[i] = filter; } Arrays.sort(filters); }

Target:
public FilterHandler(String unparsedFilters) { String[] rawFilters = unparsedFilters.split(","); filters = new Filter[rawFilters.length]; for (int i = 0; i < rawFilters.length; i++) { String currentFilter = rawFilters[i]; int period = currentFilter.lastIndexOf('.'); if (period < 0) { filters[i] = new Filter(currentFilter); continue; } filters[i] = new Filter(currentFilter.substring(0, period), currentFilter.substring(period + 1)); } Arrays.sort(filters); }
Source:
public void testConflictingPackage001() throws Exception { File outDir = AbstractTestTools.createTempDir(); IToolchain toolchain = AbstractTestTools.getCandidateToolchain(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); toolchain.setOutputStream(out); toolchain.setErrorStream(err); try { toolchain.addToClasspath(toolchain.getDefaultBootClasspath()) .srcToLib( outDir, false, AbstractTestTools.getTestRootDir("com.android.jack.frontend.test002.jack")); Assert.fail(); } catch (FrontendCompilationException e) { Assert.assertEquals(0, out.size()); String errString = err.toString(); Assert.assertTrue(errString.contains("ERROR:")); Assert.assertTrue(errString.contains( "com.android.jack.frontend.test002.jack.PackageName")); Assert.assertTrue(errString.contains("collides")); } }

Target:
public void testConflictingPackage001() throws Exception { File outDir = AbstractTestTools.createTempDir(); JackApiToolchainBase toolchain = AbstractTestTools.getCandidateToolchain(JackApiToolchainBase.class); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); toolchain.setOutputStream(out); toolchain.setErrorStream(err); try { toolchain.addToClasspath(toolchain.getDefaultBootClasspath()) .srcToLib( outDir, false, AbstractTestTools.getTestRootDir("com.android.jack.frontend.test002.jack")); Assert.fail(); } catch (FrontendCompilationException e) { Assert.assertEquals(0, out.size()); String errString = err.toString(); Assert.assertTrue(errString.contains("ERROR:")); Assert.assertTrue(errString.contains( "com.android.jack.frontend.test002.jack.PackageName")); Assert.assertTrue(errString.contains("collides")); } }
Source:
public void testAnnotateWf() throws Exception { Run b = mock(Run.class); when(b.getAction(JiraBuildAction.class)).thenReturn(new JiraBuildAction(b, Collections.singleton(new JiraIssue("DUMMY-1", TITLE)))); MarkupText text = new MarkupText("marking up DUMMY-1."); JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject((AbstractProject<?, ?>) Mockito.any()); annotator.annotate(b, null, text); Assert.assertTrue(text.toString(false).contains(TITLE)); }

Target:
public void testAnnotateWf() throws Exception { Run b = mock(Run.class); when(b.getAction(JiraBuildAction.class)).thenReturn(new JiraBuildAction(b, Collections.singleton(new JiraIssue("DUMMY-1", TITLE)))); MarkupText text = new MarkupText("marking up DUMMY-1."); JiraChangeLogAnnotator annotator = spy(new JiraChangeLogAnnotator()); doReturn(site).when(annotator).getSiteForProject((AbstractProject<?, ?>) Mockito.any()); annotator.annotate(b, null, text); assertThat(text.toString(false), containsString(TITLE)); }
Source:
public void addPending(PendingResource resource) { synchronized (this) { if (pendingResources.containsKey(resource)) { PendingResource old = pendingResources.get(resource); log.warn("Clearing stale pending resource (host: {}, vm: {})", old, old.getHost(), old.getVm()); resourcesByVm.compute(old.getVm(), (vmId, vmResources) ->{ vmResources.remove(old); return vmResources; }); resourcesByHost.compute(old.getHost(), (hostId, hostResources) -> { hostResources.remove(old); return hostResources; }); } log.debug("Adding pending resource (host: {}, vm: {})", resource, resource.getHost(), resource.getVm()); if (!resourcesByVm.containsKey(resource.getVm())) { resourcesByVm.put(resource.getVm(), new HashSet<>()); } if (!resourcesByHost.containsKey(resource.getHost())) { resourcesByHost.put(resource.getHost(), new HashSet<>()); } resourcesByVm.compute(resource.getVm(), (vmId, vmResources) -> { vmResources.add(resource); return vmResources; }); resourcesByHost.compute(resource.getHost(), (vmId, hostResources) -> { hostResources.add(resource); return hostResources; }); pendingResources.put(resource, resource); } }

Target:
public void addPending(PendingResource resource) { synchronized (this) { if (pendingResources.containsKey(resource)) { PendingResource old = pendingResources.get(resource); log.warn("Clearing stale pending resource (host: {}, vm: {})", old, old.getHost(), old.getVm()); removeFromSetMap(resourcesByVm, old.getVm(), old); removeFromSetMap(resourcesByHost, old.getHost(), old); } log.debug("Adding pending resource (host: {}, vm: {})", resource, resource.getHost(), resource.getVm()); resourcesByVm.putIfAbsent(resource.getVm(), new HashSet<>()); resourcesByHost.putIfAbsent(resource.getHost(), new HashSet<>()); addToSetMap(resourcesByVm, resource.getVm(), resource); addToSetMap(resourcesByHost, resource.getHost(), resource); pendingResources.put(resource, resource); } }
Source:
public ComponentDescriptor<?> resolveDescriptor(DataCleanerEnvironment env, String componentName) { ComponentDescriptor<?> descriptor = env.getDescriptorProvider() .getTransformerDescriptorByDisplayName(componentName); if (descriptor == null) { descriptor = env.getDescriptorProvider() .getAnalyzerDescriptorByDisplayName(componentName); } if (descriptor == null) { logger.info("Component not found.", componentName); throw ComponentNotFoundException.createTypeNotFound(componentName); } if (!_remoteComponentsConfiguration.isAllowed(descriptor)) { logger.info("Component is not allowed.", componentName); throw ComponentNotAllowed.createInstanceNotAllowed(componentName); } return descriptor; }

Target:
public ComponentDescriptor<?> resolveDescriptor(DataCleanerEnvironment env, String componentName) { ComponentDescriptor<?> descriptor = env.getDescriptorProvider() .getComponentDescriptorByDisplayName(componentName); if (descriptor == null) { logger.info("Component not found.", componentName); throw ComponentNotFoundException.createTypeNotFound(componentName); } if (!_remoteComponentsConfiguration.isAllowed(descriptor)) { logger.info("Component is not allowed.", componentName); throw ComponentNotAllowed.createInstanceNotAllowed(componentName); } return descriptor; }
Source:
public ElasticSearchAdapter() { if (restClient != null || !elasticSearchConfigured) { return; } if (!isSearchEndpointConfigured()) { LOGGER.info("no valid elasticsearch endpoint configured."); elasticSearchConfigured = false; return; } try { int portSeparator = endpoint.lastIndexOf(':'); String host = endpoint.substring(0, portSeparator); int port = Integer.parseInt(endpoint.substring(portSeparator + 1), 10); restClient = new RestHighLevelClient( RestClient.builder(new HttpHost(InetAddress.getByName(host), port, "http"))); Settings emptySettings = Settings.Builder.EMPTY_SETTINGS; } catch (Throwable e) { LOGGER.error("Could not connect to Elastic Search Engine", e); } }

Target:
public ElasticSearchAdapter() { if (restClient != null || elasticSearchConfigurationMissing) { return; } if (!isSearchEndpointConfigured()) { LOGGER.info("no valid elasticsearch endpoint configured."); elasticSearchConfigurationMissing = true; return; } try { int portSeparator = endpoint.lastIndexOf(':'); String host = endpoint.substring(0, portSeparator); int port = Integer.parseInt(endpoint.substring(portSeparator + 1), 10); restClient = new RestHighLevelClient( RestClient.builder(new HttpHost(InetAddress.getByName(host), port, "http"))); prepareEmptySettingsToAvoidClassloadingDeadlockInElasticSearch(); } catch (Throwable e) { LOGGER.error("Could not connect to Elastic Search Engine", e); } }
Source:
public static Block wrapBlock(Block block, int positionCount, List<Encoding> wrappings) { checkArgument(!wrappings.isEmpty()); Block wrappedBlock = block; for (int i = wrappings.size() - 1; i >= 0; i--) { switch (wrappings.get(i)) { case DICTIONARY: wrappedBlock = createDictionaryBlock(wrappedBlock, positionCount); break; case RUN_LENGTH: wrappedBlock = createRLEBlock(wrappedBlock, positionCount); break; default: throw new IllegalArgumentException(format("wrappings %s is incorrect", wrappings)); } } return wrappedBlock; }

Target:
public static Block wrapBlock(Block block, int positionCount, List<Encoding> wrappings) { checkArgument(!wrappings.isEmpty(), "wrappings is empty"); Block wrappedBlock = block; for (int i = wrappings.size() - 1; i >= 0; i--) { switch (wrappings.get(i)) { case DICTIONARY: wrappedBlock = createRandomDictionaryBlock(wrappedBlock, positionCount); break; case RUN_LENGTH: wrappedBlock = createRleBlockWithRandomValue(wrappedBlock, positionCount); break; default: throw new IllegalArgumentException(format("wrappings %s is incorrect", wrappings)); } } return wrappedBlock; }
Source:
public BeaconMonitoring( boolean runDiscovery, int timeFrequency, Set<BackendlessBeacon> monitoredBeacons ) { if( timeFrequency < 0 ) throw new IllegalArgumentException( ExceptionMessage.INVALID_LOG_POLICY ); if(monitoredBeacons == null) receiveBeaconsInfo(); this.discovery = runDiscovery; super.setTimeFrequency( timeFrequency ); }

Target:
public BeaconMonitoring( boolean runDiscovery, int timeFrequency, Set<BackendlessBeacon> monitoredBeacons ) { if(monitoredBeacons == null) receiveBeaconsInfo(); this.discovery = runDiscovery; super.setTimeFrequency( timeFrequency ); }
Source:
public boolean isValid(List<VdsNetworkInterface> value, ConstraintValidatorContext context) { List<String> staticIps = new ArrayList<String>(); for (VdsNetworkInterface networkInterface : value) { if (NetworkBootProtocol.StaticIp.equals(networkInterface.getBootProtocol())) { if (staticIps.contains(networkInterface.getAddress())) { return false; } else { staticIps.add(networkInterface.getAddress()); } } } return true; }

Target:
public boolean isValid(List<VdsNetworkInterface> value, ConstraintValidatorContext context) { List<String> staticIps = new ArrayList<String>(); for (VdsNetworkInterface networkInterface : value) { if (networkInterface.getBootProtocol() == NetworkBootProtocol.StaticIp && validAddress(networkInterface.getAddress())) { if (staticIps.contains(networkInterface.getAddress())) { return false; } else { staticIps.add(networkInterface.getAddress()); } } } return true; }
Source:
public void setConfig(Conversion config) { this.config = config; }

Target:
public void setConfig(Conversion config) { Assert.notNull(config, "Conversion argument cannot be null."); this.config = config; }
Source:
public void stressCache() throws Exception { StringFactory factory = new StringFactory(); SpatialIndexCache<String,Exception> cache = new SpatialIndexCache<>( factory ); CacheStresser[] stressers = new CacheStresser[100]; for ( int i = 0; i < stressers.length; i++ ) { stressers[i] = new CacheStresser( cache ); stressers[i].start(); } Thread.sleep( 5_000 ); for ( CacheStresser stresser : stressers ) { stresser.interrupt(); } for ( CacheStresser stresser : stressers ) { stresser.join(); } for ( CacheStresser stresser : stressers ) { assertNull( stresser.failed ); } }

Target:
public void stressCache() throws Exception { StringFactory factory = new StringFactory(); SpatialIndexCache<String> cache = new SpatialIndexCache<>( factory ); ExecutorService pool = Executors.newFixedThreadPool( 20 ); Future<?>[] futures = new Future[100]; AtomicBoolean shouldContinue = new AtomicBoolean( true ); try { for ( int i = 0; i < futures.length; i++ ) { futures[i] = pool.submit( new CacheStresser( cache, shouldContinue ) ); } Thread.sleep( 5_000 ); shouldContinue.set( false ); for ( Future<?> future : futures ) { future.get( 10, TimeUnit.SECONDS ); } } finally { pool.shutdown(); } }
Source:
public boolean hasFinishedWonder() { return Asset.getAsset(getAssets(),ASSET_WONDER_STAGES) == wonder.getStages().size(); }

Target:
public boolean hasFinishedWonder() { return wonder.getNextStage() == null; }
Source:
private void normalize(String[] lineValues) throws FormatException { for (int i = 0; i < lineValues.length; i++) { if (lineValues[i] == null) { if ("error".equals(m_blank)) { throw new FormatException("Blank values are not allowed"); } } else { if (m_nowhitespace && (lineValues[i].charAt(0) == ' ' || lineValues[i].charAt(lineValues[i].length() - 1) == ' ')) { throw new FormatException("Whitespace detected--nowhitespace is used"); } else { lineValues[i] = lineValues[i].trim(); } if (!m_customNullString.isEmpty()) { if (m_customNullString.equals(lineValues[i])) { lineValues[i] = null; } } else if (lineValues[i].equals("NULL") || lineValues[i].equals(CSV_NULL) || lineValues[i].equals(QUOTED_CSV_NULL)) { lineValues[i] = null; } } } }

Target:
private void normalize(String[] lineValues) throws FormatException { for (int i = 0; i < lineValues.length; i++) { if (lineValues[i] == null) { if ("error".equals(m_blank)) { throw new FormatException("Blank values are not allowed"); } } else { if (m_nowhitespace && (lineValues[i].charAt(0) == ' ' || lineValues[i].charAt(lineValues[i].length() - 1) == ' ')) { throw new FormatException("Whitespace detected--nowhitespace is used"); } else { lineValues[i] = lineValues[i].trim(); } if (!m_customNullString.isEmpty()) { if (m_customNullString.equals(lineValues[i])) { lineValues[i] = null; } } else if ("NULL".equals(lineValues[i]) || CSV_NULL.equalsIgnoreCase(lineValues[i]) || QUOTED_CSV_NULL.equals(lineValues[i])) { lineValues[i] = null; } } } }
Source:
public void shouldFailWithAdditionalInfosWhenReadingDBlobContent() throws IOException { SimpleManagedBlob mock = Mockito.mock(SimpleManagedBlob.class); when(mock.getEncoding()).thenReturn("UTF-8"); when(mock.getKey()).thenReturn("anyKey:anyKey"); when(mock.getProviderId()).thenReturn("anyProvider:anyProvider"); when(mock.getMimeType()).thenReturn("text/html"); when(mock.getDigest()).thenReturn("anyDigest"); when(mock.getStream()).thenThrow(IOException.class); try { cs.convert("html2text", new SimpleBlobHolder(mock), Collections.emptyMap()); } catch (ConversionException e) { assertTrue(e.getInfos().size() == 2); assertTrue(e.getInfos().get(0).contains("anyProvider:anyProvider")); assertTrue(e.getInfos().get(1).contains("anyKey:anyKey")); } }

Target:
public void shouldFailWithAdditionalInfosWhenReadingDBlobContent() throws IOException { SimpleManagedBlob mock = Mockito.mock(SimpleManagedBlob.class); when(mock.getEncoding()).thenReturn("UTF-8"); when(mock.getKey()).thenReturn("anyKey:anyKey"); when(mock.getProviderId()).thenReturn("anyProvider:anyProvider"); when(mock.getMimeType()).thenReturn("text/html"); when(mock.getDigest()).thenReturn("anyDigest"); when(mock.getStream()).thenThrow(IOException.class); try { cs.convert("html2text", new SimpleBlobHolder(mock), Collections.emptyMap()); fail("Should have raised a ConversionException"); } catch (ConversionException e) { assertEquals(1, e.getInfos().size()); assertTrue(e.getInfos().get(0).contains("anyProvider:anyProvider")); assertTrue(e.getInfos().get(0).contains("anyKey:anyKey")); } }
Source:
public void testSinkTasksHandleCloseErrors() throws Exception { createTask(initialState); expectInitializeTask(); expectTaskGetTopic(true); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.anyObject()); PowerMock.expectLastCall().andVoid(); expectConsumerPoll(1); expectConversionAndTransformation(1); Throwable a = new RuntimeException(); sinkTask.put(EasyMock.anyObject()); PowerMock.expectLastCall().andThrow(a); EasyMock.expect(sinkTask.preCommit(EasyMock.anyObject())) .andStubReturn(Collections.emptyMap()); Throwable b = new RuntimeException(); sinkTask.close(EasyMock.anyObject()); PowerMock.expectLastCall().andThrow(b); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); try { workerTask.execute(); fail(); } catch (Throwable t) { PowerMock.verifyAll(); assertNotEquals(b, t); assertSame(a, t.getCause()); assertTrue(t.getSuppressed().length > 0); assertSame(b, t.getSuppressed()[0]); } }

Target:
public void testSinkTasksHandleCloseErrors() throws Exception { createTask(initialState); expectInitializeTask(); expectTaskGetTopic(true); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.anyObject()); PowerMock.expectLastCall().andVoid(); expectConsumerPoll(1); expectConversionAndTransformation(1); sinkTask.put(EasyMock.anyObject()); PowerMock.expectLastCall().andAnswer(() -> { workerTask.stop(); return null; }); consumer.wakeup(); PowerMock.expectLastCall(); EasyMock.expect(sinkTask.preCommit(EasyMock.anyObject())) .andStubReturn(Collections.emptyMap()); Throwable closeException = new RuntimeException(); sinkTask.close(EasyMock.anyObject()); PowerMock.expectLastCall().andThrow(closeException); PowerMock.replayAll(); workerTask.initialize(TASK_CONFIG); try { workerTask.execute(); fail("workerTask.execute should have thrown an exception"); } catch (RuntimeException e) { PowerMock.verifyAll(); assertSame("Exception from close should propagate as-is", closeException, e); } }
Source:
public Builder withAutoscaleDisabledVmDurationInSecs(long disabledVmDurationInSecs) { if(disabledVmDurationInSecs > 0L) throw new IllegalArgumentException("disabledVmDurationInSecs must be greater than 0: " + disabledVmDurationInSecs); this.disabledVmDurationInSecs = disabledVmDurationInSecs; return this; }

Target:
public Builder withAutoscaleDisabledVmDurationInSecs(long disabledVmDurationInSecs) { if(disabledVmDurationInSecs <= 0L) { throw new IllegalArgumentException("disabledVmDurationInSecs must be greater than 0: " + disabledVmDurationInSecs); } this.disabledVmDurationInSecs = disabledVmDurationInSecs; return this; }
Source:
public void aggregate(final ByteBuffer buf, final int position) { final IndexedInts keys = keySelector.getRow(); if (keys == null) { return; } final WritableMemory mem = WritableMemory.wrap(buf); final WritableMemory region = mem.writableRegion(position, maxIntermediateSize); final ArrayOfDoublesUpdatableSketch sketch = ArrayOfDoublesSketches.wrapUpdatableSketch(region); final double[] values = new double[valueSelectors.size()]; int valueIndex = 0; for (final BaseDoubleColumnValueSelector valueSelector : valueSelectors) { values[valueIndex++] = valueSelector.getDouble(); } for (int i = 0; i < keys.size(); i++) { final String key = keySelector.lookupName(keys.get(i)); sketch.update(key, values); } }

Target:
public void aggregate(final ByteBuffer buf, final int position) { for (int i = 0; i < valueSelectors.length; i++) { values[i] = valueSelectors[i].getDouble(); } final IndexedInts keys = keySelector.getRow(); final WritableMemory mem = WritableMemory.wrap(buf); final WritableMemory region = mem.writableRegion(position, maxIntermediateSize); final Lock lock = stripedLock.getAt(lockIndex(position)).writeLock(); lock.lock(); try { final ArrayOfDoublesUpdatableSketch sketch = ArrayOfDoublesSketches.wrapUpdatableSketch(region); for (int i = 0, keysSize = keys.size(); i < keysSize; i++) { final String key = keySelector.lookupName(keys.get(i)); sketch.update(key, values); } } finally { lock.unlock(); } }
Source:
public EventTypeSchema getSchemaVersion(final String name, final String version) throws NoSuchSchemaException, IllegalVersionNumberException, InternalNakadiException { final Pattern versionPattern = Pattern.compile("\\d+\\.\\d+\\.\\d+"); final Matcher versionMatcher = versionPattern.matcher(version); if (!versionMatcher.matches()) { throw new IllegalVersionNumberException(version); } final String sql = "SELECT ets_schema_object FROM zn_data.event_type_schema " + "WHERE ets_event_type_name = ? AND ets_schema_object ->> 'version' = ?"; try { final List<EventTypeSchema> schemas = jdbcTemplate.query(sql, new Object[]{name, version}, new SchemaRowMapper()); if (schemas.size() != 1) throw new InternalNakadiException( String.format("Unexpected number of schemas with version {}: {}", version, schemas.size())); return schemas.get(0); } catch (EmptyResultDataAccessException e) { throw new NoSuchSchemaException("EventType \"" + name + "\" has no schema with version \"" + version + "\"", e); } }

Target:
public EventTypeSchema getSchemaVersion(final String name, final String version) throws NoSuchSchemaException, InternalNakadiException { final String sql = "SELECT ets_schema_object FROM zn_data.event_type_schema " + "WHERE ets_event_type_name = ? AND ets_schema_object ->> 'version' = ?"; try { final List<EventTypeSchema> schemas = jdbcTemplate.query(sql, new Object[]{name, version}, new SchemaRowMapper()); if (schemas.size() != 1) throw new InternalNakadiException( String.format("Unexpected number of schemas with version {}: {}", version, schemas.size())); return schemas.get(0); } catch (EmptyResultDataAccessException e) { throw new NoSuchSchemaException("EventType \"" + name + "\" has no schema with version \"" + version + "\"", e); } }