auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void notificationProcessing(Context context, OSNotificationReceived notification) { if (notification.payload.actionButtons != null) { for (OSNotificationPayload.ActionButton button : notification.payload.actionButtons) { System.out.println("button:" + button.toString()); } } OSNotificationExtender.OverrideSettings overrideSettings = new OSNotificationExtender.OverrideSettings(); overrideSettings.extender = new NotificationCompat.Extender() { @Override public NotificationCompat.Builder extend(NotificationCompat.Builder builder) { return builder.setColor(context.getResources().getColor(R.color.colorPrimary)); } }; notification.setModifiedContent(overrideSettings); OSNotificationDisplayedResult notificationDisplayedResult = notification.display(); <START> System.out.println("Android notification id: " + notificationDisplayedResult.androidNotificationId); <END> notification.complete(); }</code><technical_language>Log.i instead of sysout</technical_language>

Target:
public void notificationProcessing(Context context, OSNotificationReceived notification) { if (notification.payload.actionButtons != null) { for (OSNotificationPayload.ActionButton button : notification.payload.actionButtons) { System.out.println("button:" + button.toString()); } } OSNotificationExtender.OverrideSettings overrideSettings = new OSNotificationExtender.OverrideSettings(); overrideSettings.extender = new NotificationCompat.Extender() { @Override public NotificationCompat.Builder extend(NotificationCompat.Builder builder) { return builder.setColor(context.getResources().getColor(R.color.colorPrimary)); } }; notification.setModifiedContent(overrideSettings); OSNotificationDisplayedResult notificationDisplayedResult = notification.display(); Log.i("OneSignal", "Android notification id: " + notificationDisplayedResult.androidNotificationId); notification.complete(); }
Source:
<code>public MapSqlParameterMapper<GlusterVolumeOptionEntity> getBatchMapper() { <START> throw new RuntimeException("Unsupported operation"); <END> }</code><technical_language>please NotImplementedException()</technical_language>

Target:
public MapSqlParameterMapper<GlusterVolumeOptionEntity> getBatchMapper() { throw new NotImplementedException("Unsupported operation"); }
Source:
<code>private void setupLogCollectorForLogDirectory() throws InterruptedException { if (currentLogCollector != null) { currentLogCollector.stopCollecting(); <START> } <END> currentLogCollector = new InterruptibleFileLogCollector(new File(logDirectory)); }</code><technical_language>nit: restore this factory please</technical_language>

Target:
private void setupLogCollectorForLogDirectory() { if (currentLogCollector != null) { currentLogCollector.stopExecutor(); } currentLogCollector = new InterruptibleFileLogCollector(new File(logDirectory)); }
Source:
<code>private void populateList() { try { ArrayList<BlackboardArtifact.Type> doNotReport = new ArrayList<>(); doNotReport.add(new BlackboardArtifact.Type(BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO.getTypeID(), BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO.getLabel(), BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO.getDisplayName())); doNotReport.add(new BlackboardArtifact.Type(BlackboardArtifact.ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getTypeID(), BlackboardArtifact.ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getLabel(), BlackboardArtifact.ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getDisplayName())); artifactTypes = Case.getCurrentCaseThrows().getSleuthkitCase().getArtifactTypesInUse(); artifactTypes.removeAll(doNotReport); Collections.sort(artifactTypes, new Comparator<BlackboardArtifact.Type>() { @Override public int compare(BlackboardArtifact.Type o1, BlackboardArtifact.Type o2) { return o1.getDisplayName().compareTo(o2.getDisplayName()); } }); artifactTypeSelections = new HashMap<>(); for (BlackboardArtifact.Type type : artifactTypes) { artifactTypeSelections.put(type, Boolean.TRUE); } } catch (TskCoreException ex) { Logger.getLogger(ArtifactSelectionDialog.class.getName()).log(Level.SEVERE, "Error getting list of artifacts in use: {0}", ex.getLocalizedMessage()); } catch (NoCurrentCaseException ex) { <START> Logger.getLogger(ArtifactSelectionDialog.class.getName()).log(Level.WARNING, "Exception while getting open case.", ex.getLocalizedMessage()); END> } }</code><technical_language>Case.isCaseOpen remove ambiguity in handling of this exception</technical_language>

Target:
private void populateList() { try { ArrayList<BlackboardArtifact.Type> doNotReport = new ArrayList<>(); doNotReport.add(new BlackboardArtifact.Type(BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO.getTypeID(), BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO.getLabel(), BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO.getDisplayName())); doNotReport.add(new BlackboardArtifact.Type(BlackboardArtifact.ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getTypeID(), BlackboardArtifact.ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getLabel(), BlackboardArtifact.ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getDisplayName())); artifactTypes = Case.getCurrentCaseThrows().getSleuthkitCase().getArtifactTypesInUse(); artifactTypes.removeAll(doNotReport); Collections.sort(artifactTypes, new Comparator<BlackboardArtifact.Type>() { @Override public int compare(BlackboardArtifact.Type o1, BlackboardArtifact.Type o2) { return o1.getDisplayName().compareTo(o2.getDisplayName()); } }); artifactTypeSelections = new HashMap<>(); for (BlackboardArtifact.Type type : artifactTypes) { artifactTypeSelections.put(type, Boolean.TRUE); } } catch (TskCoreException ex) { Logger.getLogger(ArtifactSelectionDialog.class.getName()).log(Level.SEVERE, "Error getting list of artifacts in use: {0}", ex.getLocalizedMessage()); } catch (NoCurrentCaseException ex) { if (Case.isCaseOpen()) { Logger.getLogger(ArtifactSelectionDialog.class.getName()).log(Level.SEVERE, "Exception while getting open case.", ex.getLocalizedMessage()); } } }
Source:
<code>public static <K, V> ConfigurationAdapter<K, V> create(Configuration<K, V> c) { <START> if (c instanceof CompleteConfiguration) { <END> return new ConfigurationAdapter<K, V>( new MutableConfiguration<K, V>((MutableConfiguration<K, V>) c)); } else { MutableConfiguration<K, V> mutableConfiguration = new MutableConfiguration<K, V>(); mutableConfiguration.setStoreByValue(c.isStoreByValue()); mutableConfiguration.setTypes(c.getKeyType(), c.getValueType()); return new ConfigurationAdapter<K, V>( new MutableConfiguration<K, V>(mutableConfiguration)); } }</code><technical_language>c instanceof MutableConfiguration</technical_language>

Target:
public static <K, V> ConfigurationAdapter<K, V> create(Configuration<K, V> c) { if (c instanceof CompleteConfiguration) { return new ConfigurationAdapter<K, V>( new MutableConfiguration<K, V>((CompleteConfiguration<K, V>) c)); } else { MutableConfiguration<K, V> mutableConfiguration = new MutableConfiguration<K, V>(); mutableConfiguration.setStoreByValue(c.isStoreByValue()); mutableConfiguration.setTypes(c.getKeyType(), c.getValueType()); return new ConfigurationAdapter<K, V>( new MutableConfiguration<K, V>(mutableConfiguration)); } }
Source:
<code>public void init() { super.init(); <START> if(userLayerDbService == null) { <END> userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); } }</code><technical_language>set userLayerDbService this true</technical_language>

Target:
public void init() { userLayerDbService = OskariComponentManager.getComponentOfType(UserLayerDbService.class); }
Source:
<code>public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) { if (networkEnvelope instanceof GetBlocksResponse) { if (stopped) { log.warn("We have stopped already. We ignore that onDataRequest call."); return; } Optional<NodeAddress> optionalNodeAddress = connection.getPeersNodeAddressOptional(); if (!optionalNodeAddress.isPresent()) { log.warn("Peers node address is not present, that is not expected."); } else if (!optionalNodeAddress.get().equals(nodeAddress)) { log.warn("Peers node address is the same we requested. We ignore that message."); return; } GetBlocksResponse getBlocksResponse = (GetBlocksResponse) networkEnvelope; if (getBlocksResponse.getRequestNonce() != nonce) { log.warn("Nonce not matching. That can happen rarely if we get a response after a canceled " + "handshake (timeout causes connection close but peer might have sent a msg before " + "connection was closed).\n\t" + "We drop that message. nonce={} / requestNonce={}", nonce, getBlocksResponse.getRequestNonce()); return; } <START> cleanup(); <END> log.info("We received from peer a BlocksResponse with blocks", nodeAddress.getFullAddress(), getBlocksResponse.getBlocks().size()); listener.onComplete(getBlocksResponse); } }</code><technical_language>timeoutTimer need stopped before? stopTimeoutTimer();</technical_language>

Target:
public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) { if (networkEnvelope instanceof GetBlocksResponse) { if (stopped) { log.warn("We have stopped already. We ignore that onDataRequest call."); return; } Optional<NodeAddress> optionalNodeAddress = connection.getPeersNodeAddressOptional(); if (!optionalNodeAddress.isPresent()) { log.warn("Peers node address is not present, that is not expected."); } else if (!optionalNodeAddress.get().equals(nodeAddress)) { log.warn("Peers node address is not the same we used for the request. This is not expected. We ignore that message."); return; } GetBlocksResponse getBlocksResponse = (GetBlocksResponse) networkEnvelope; if (getBlocksResponse.getRequestNonce() != nonce) { log.warn("Nonce not matching. That can happen rarely if we get a response after a canceled " + "handshake (timeout causes connection close but peer might have sent a msg before " + "connection was closed).\n\t" + "We drop that message. nonce={} / requestNonce={}", nonce, getBlocksResponse.getRequestNonce()); return; } terminate(); log.info("We received from peer a BlocksResponse with blocks", nodeAddress.getFullAddress(), getBlocksResponse.getBlocks().size()); listener.onComplete(getBlocksResponse); } }
Source:
<code>public Collection<ResourceLocation> getTextures() { if(model.getParentLocation() != null && model.parent == null) { if(model.getParentLocation().getResourcePath().equals("builtin/generated")) { model.parent = MODEL_GENERATED; } else { IModel parent = ModelLoaderRegistry.getModelOrLogError(model.getParentLocation(), "Could not load vanilla model parent '" + model.getParentLocation() + "' for '" + model); <START> if (parent instanceof FancyMissingModel) <END> { parent = getMissingModel(); } if(parent instanceof VanillaModelWrapper) { model.parent = ((VanillaModelWrapper) parent).model; } else { throw new IllegalStateException("vanilla model '" + model + "' can't have non-vanilla parent"); } } } ImmutableSet.Builder<ResourceLocation> builder = ImmutableSet.builder(); if(hasItemModel(model)) { for(String s : ItemModelGenerator.LAYERS) { String r = model.resolveTextureName(s); ResourceLocation loc = new ResourceLocation(r); if(!r.equals(s)) { builder.add(loc); } } } for(String s : model.textures.values()) { if(!s.startsWith("#")) { builder.add(new ResourceLocation(s)); } } return builder.build(); }</code><technical_language>Formatting Consistency suggestion if(parent instanceof FancyMissingModel)</technical_language>

Target:
public Collection<ResourceLocation> getTextures() { ResourceLocation parentLocation = model.getParentLocation(); if(parentLocation != null && model.parent == null) { if(parentLocation.getResourcePath().equals("builtin/generated")) { model.parent = MODEL_GENERATED; } else { model.parent = ModelLoaderRegistry.getModelOrLogError(parentLocation, "Could not load vanilla model parent '" + parentLocation + "' for '" + model + "'") .asVanillaModel().orElseThrow(() -> new IllegalStateException("vanilla model '" + model + "' can't have non-vanilla parent")); } } ImmutableSet.Builder<ResourceLocation> builder = ImmutableSet.builder(); if(hasItemModel(model)) { for(String s : ItemModelGenerator.LAYERS) { String r = model.resolveTextureName(s); ResourceLocation loc = new ResourceLocation(r); if(!r.equals(s)) { builder.add(loc); } } } for(String s : model.textures.values()) { if(!s.startsWith("#")) { builder.add(new ResourceLocation(s)); } } return builder.build(); }
Source:
<code>public void testPostDataAndGetDataWithInvalidParams()throws IOException, JSONException{ thrown.expect(IOException.class); thrown.expectMessage("invalid input of date or or sensorID or sessionID"); String session_id = proxy.loginUser(newUser.get("username"), newUser.get("password")); String name = "test"; String displayName = "test"; String deviceType = "deviceType"; String dataType = "json"; String sessionID = session_id; String value = "{\"interval\":0,\"data\":[2.23, 19.45, 20.2]}"; String dataStructure = createDataStructure(value); JSONObject sensor = proxy.createSensor(name, displayName, deviceType, dataType, dataStructure, sessionID); assertNotNull("Failed to create a sensor", sensor); String sensorId = sensor.get("sensor_id").toString(); assertEquals("The new sensorid returned from the server is empty",false, sensorId.isEmpty()); JSONArray postData = createDataPoint(sensorId); float fromDate = System.currentTimeMillis()/1000; boolean result = proxy.postData(postData,sessionID); assertEquals("Failed to post data to the server",true, result); JSONArray getData = proxy.getData(sensorId, fromDate, null); <START> assertEquals("Failed to get data from the server", true, (getData.length()!=0)); <END> }</code><technical_language>@excaliburnan length 0 right</technical_language>

Target:
public void testPostDataAndGetDataWithInvalidParams()throws RuntimeException, IOException{ thrown.expect(IllegalArgumentException.class); thrown.expectMessage("invalid input of date or or sensorID or sessionID"); String session_id = proxy.loginUser(newUser.get("username"), newUser.get("password")); String name = "test"; String displayName = "test"; String deviceType = "deviceType"; String dataType = "json"; String sessionID = session_id; String value = "{\"interval\":0,\"data\":[2.23, 19.45, 20.2]}"; String dataStructure = createDataStructure(value); JSONObject sensor = proxy.createSensor(name, displayName, deviceType, dataType, dataStructure, sessionID); assertNotNull("Failed to create a sensor", sensor); String sensorId; try { sensorId = sensor.get("sensor_id").toString(); }catch(JSONException js){ throw new RuntimeException("Failed to get the sensor id from sensor object"); } assertEquals("The new sensorid returned from the server is empty",false, sensorId.isEmpty()); JSONArray postData = createDataPoint(sensorId); SNTP sntp = new SNTP(); float fromDate = sntp.getTime()/1000; boolean result = proxy.postData(postData,sessionID); assertEquals("Failed to post data to the server",true, result); JSONArray getData = proxy.getData(sensorId, fromDate, null); assertEquals("No data should be returned from the server with null session id", true, (getData.length()==0)); }
Source:
<code>public Mono<Boolean> markInitialized() { String markerDocId = this.getStoreMarkerName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(markerDocId), false) .map( item -> true) .onErrorResume(throwable -> { if (throwable instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) throwable; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was created by a different instance"); return Mono.just(true); } } <START> logger.warn("Unexpected exception thrown", throwable); <END> return Mono.just(false); }); }</code><technical_language>error for this other places</technical_language>

Target:
public Mono<Boolean> markInitialized() { String markerDocId = this.getStoreMarkerName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(markerDocId), false) .map( item -> true) .onErrorResume(throwable -> { if (throwable instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) throwable; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was created by a different instance"); return Mono.just(true); } } logger.error("Unexpected exception thrown", throwable); return Mono.just(false); }); }
Source:
<code>public void stop() { netty.ifPresent(NettyJaxrsServer::stop); netty = Optional.empty(); <START> server = Optional.empty(); <END> }</code><technical_language>need server.get().stop() well</technical_language>

Target:
public void stop() { if(netty != null) { netty.stop(); } netty = null; server = null; }
Source:
<code>public List<String> toSimpleList(List<String> elements) { if(elements == null) <START> elements = Collections.emptyList(); <END> return elements; }</code><technical_language>Missing {}</technical_language>

Target:
public List<String> toSimpleList(List<String> elements) { if(elements == null) { elements = Collections.emptyList(); } return elements; }
Source:
<code>boolean isVariableHeight(StyleRange style) { <START> return style.isVariableHeight(isWordWrap()); <END> }</code><technical_language>Here, override depending wordwrap not. if (!isWordWrap()) { return style.isVariableHeight(); // care style } else { //.. other logic is word wrap. }</technical_language>

Target:
boolean isVariableHeight(StyleRange style) { if (!isWordWrap()) { return style.isVariableHeight(); } return style.isVariableHeight() || (style.metrics != null && style.metrics.width != 0); }
Source:
<code>public ContainerManager(ZKDatabase zkDb, RequestProcessor requestProcessor, int checkIntervalMs, int maxPerMinute, long maxNeverUsedIntervalMs) { this.zkDb = zkDb; this.requestProcessor = requestProcessor; this.checkIntervalMs = checkIntervalMs; this.maxPerMinute = maxPerMinute; this.maxNeverUsedIntervalMs = maxNeverUsedIntervalMs; timer = new Timer("ContainerManagerTask", true); <START> LOG.info("Using checkIntervalMs={} maxPerMinute={}", checkIntervalMs, maxPerMinute); <END> }</code><technical_language>maxNeverUsedIntervalMs needs logged</technical_language>

Target:
public ContainerManager(ZKDatabase zkDb, RequestProcessor requestProcessor, int checkIntervalMs, int maxPerMinute, long maxNeverUsedIntervalMs) { this.zkDb = zkDb; this.requestProcessor = requestProcessor; this.checkIntervalMs = checkIntervalMs; this.maxPerMinute = maxPerMinute; this.maxNeverUsedIntervalMs = maxNeverUsedIntervalMs; timer = new Timer("ContainerManagerTask", true); LOG.info("Using checkIntervalMs={} maxPerMinute={} maxNeverUsedIntervalMs={}", checkIntervalMs, maxPerMinute, maxNeverUsedIntervalMs); }
Source:
<code>private boolean checkForTargetUsage(String target, Node baseNode) { boolean match = false; if (target != null && baseNode != null) { List<ASTName> nameNodes = baseNode.findDescendantsOfType(ASTName.class); for (ASTName nameNode : nameNodes) { if (target.equals(nameNode.getImage())) { boolean isPartOfStringConcatenation = <START> (nameNode.jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTAdditiveExpression); <END> if (!isPartOfStringConcatenation) { match = true; break; } } } } return match; }</code><technical_language>This a cornercase, code handle useless parentheses, eg: java throw new Exception("something bad:" + (e));</technical_language>

Target:
private boolean checkForTargetUsage(String target, Node baseNode) { boolean match = false; if (target != null && baseNode != null) { List<ASTName> nameNodes = baseNode.findDescendantsOfType(ASTName.class); for (ASTName nameNode : nameNodes) { if (target.equals(nameNode.getImage())) { boolean isPartOfStringConcatenation = isStringConcat(nameNode, baseNode); if (!isPartOfStringConcatenation) { match = true; break; } } } } return match; }
Source:
<code>public String toString() { <START> return toJson(); <END> }</code><technical_language>Do Variable.this.toString();</technical_language>

Target:
public String toString() { return Variable.this.toString(); }
Source:
<code>public Object decode(ReadBuffer readBuffer) { <START> readBuffer.getVlqInt(); <END> return readBuffer.getInt(); }</code><technical_language>If write lengths for primitives validate decode? If not, optional</technical_language>

Target:
public Integer decode(ReadBuffer readBuffer) { int size = readBuffer.getVlqInt(); if (size != 4) { throw new CorruptDataException("Expected field size of 4, read : " + size); } return readBuffer.getInt(); }
Source:
<code>public void showLegend() { <START> Composite timeAlignedComposite = getControl(); if (timeAlignedComposite == null || timeAlignedComposite.isDisposed()) { return; } <END> ITimeGraphLegendProvider legendProvider = fLegendProvider; if (legendProvider == null) { TimeGraphLegend.open(timeAlignedComposite.getShell(), getTimeGraphProvider()); } else { legendProvider.showLegend(timeAlignedComposite.getShell(), getTimeGraphProvider()); } }</code><technical_language>this change? do Composite timeAlignedComposite = fTimeAlignedComposite;</technical_language>

Target:
public void showLegend() { Control tgControl = getControl(); if (tgControl == null || tgControl.isDisposed()) { return; } ITimeGraphLegendProvider legendProvider = fLegendProvider; if (legendProvider == null) { TimeGraphLegend.open(tgControl.getShell(), getTimeGraphProvider()); } else { legendProvider.showLegend(tgControl.getShell(), getTimeGraphProvider()); } }
Source:
<code>public List<Entry<String, String>> load(PID pid) { List<Entry<String, String>> valueResults = new ArrayList<>(); RepositoryObject repoObj = repositoryObjectCacheLoader.load(pid); Model model = repoObj.getModel(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement stmt = it.next(); Property property = stmt.getPredicate(); if (CdrAcl.NS.equals(property.getNameSpace()) <START> || RDF.type.equals(property) && Cdr.Tombstone.equals(stmt.getResource())) { <END> RDFNode valueNode = stmt.getObject(); String valueString; if (valueNode.isLiteral()) { valueString = valueNode.asLiteral().getLexicalForm(); } else { valueString = valueNode.asResource().getURI(); } valueResults.add(new SimpleEntry<> (property.getURI(), valueString)); } } return valueResults; }</code><technical_language>this need another set of () it</technical_language>

Target:
public List<Entry<String, String>> load(PID pid) { List<Entry<String, String>> valueResults = new ArrayList<>(); RepositoryObject repoObj = repositoryObjectCacheLoader.load(pid); Model model = repoObj.getModel(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement stmt = it.next(); Property property = stmt.getPredicate(); if (CdrAcl.NS.equals(property.getNameSpace()) || (RDF.type.equals(property) && Cdr.Tombstone.equals(stmt.getResource()))) { RDFNode valueNode = stmt.getObject(); String valueString; if (valueNode.isLiteral()) { valueString = valueNode.asLiteral().getLexicalForm(); } else { valueString = valueNode.asResource().getURI(); } valueResults.add(new SimpleEntry<> (property.getURI(), valueString)); } } return valueResults; }
Source:
<code>public Set<Statement> deserialize(final String topic, final byte[] data) { if(data == null || data.length == 0) { return null; } try { final RDFParser parser = PARSER_FACTORY.getParser(); final Set<Statement> statements = new HashSet<>(); parser.setRDFHandler(new RDFHandler() { @Override public void handleStatement(final Statement statement) throws RDFHandlerException { log.debug("Statement: " + statement); statements.add( statement ); } @Override public void startRDF() throws RDFHandlerException { } @Override public void handleNamespace(final String arg0, final String arg1) throws RDFHandlerException { } @Override public void handleComment(final String arg0) throws RDFHandlerException { } @Override public void endRDF() throws RDFHandlerException { } }); parser.parse(new ByteArrayInputStream(data), null); return statements; } catch(final RDFParseException | RDFHandlerException | IOException e) { <START> log.error("Could not deserialize a Set of VisibilityStatement objects using the RDF4J Rio Binray format.", e); <END> return null; } }</code><technical_language>typo. Binary</technical_language>

Target:
public Set<Statement> deserialize(final String topic, final byte[] data) { if(data == null || data.length == 0) { return null; } try { final RDFParser parser = PARSER_FACTORY.getParser(); final Set<Statement> statements = new HashSet<>(); parser.setRDFHandler(new AbstractRDFHandler() { @Override public void handleStatement(final Statement statement) throws RDFHandlerException { log.debug("Statement: " + statement); statements.add( statement ); } }); parser.parse(new ByteArrayInputStream(data), null); return statements; } catch(final RDFParseException | RDFHandlerException | IOException e) { log.error("Could not deserialize a Set of VisibilityStatement objects using the RDF4J Rio Binary format.", e); return null; } }
Source:
<code>public float getInterpolation(float v) { <START> return (float) Math.pow(v, factor) * (end - start) + start; <END> }</code><technical_language>Linear acceleration is quadratic in terms of position (i.e. interpolated value). I suggest a multiplicate factor instead. This avoid comparatively costly call Math.pow()</technical_language>

Target:
public float getInterpolation(float v) { return (float) v * v; }
Source:
<code>public IResource resolve(String relative) { IResource result = null; if (ref == null) { <START> result = factory.newResource(getURI().resolve(relative)); <END> } else { result = factory.newResource(ref.resolve(relative)); } return result; }</code><technical_language>This work factory is null if ref is null</technical_language>

Target:
public IResource resolve(String relative) { IResource result = null; if (ref == null) { try { result = (IResource) this.getClass() .getConstructor(URI.class).newInstance(getURI().resolve(relative)); } catch (Throwable t) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.WARNING, t.getMessage(), t); } throw new RuntimeException(t); } } else { result = factory.newResource(ref.resolve(relative)); } return result; }
Source:
<code>public void onMatch(RelOptRuleCall call) { AbstractVoltPhysicalAggregate aggregate = call.rel(0); VoltPhysicalTableScan scan = call.rel(1); <START> RelNode newScan = scan.copyWithAggregate(scan.getTraitSet(), aggregate); <END> call.transformTo(newScan); }</code><technical_language>I traits for a new node (or merged with) top node preserve equivalence in inline rules. RelTraitSet newTraits = botomNode.getTraitSet().merge(topNode.getTraitSet()); For example, a scan a collation a hash aggregate is unordered</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { AbstractVoltPhysicalAggregate aggregate = call.rel(0); VoltPhysicalTableScan scan = call.rel(1); RelNode newScan = scan.copyWithAggregate(scan.getTraitSet().merge(aggregate.getTraitSet()), aggregate); call.transformTo(newScan); }
Source:
<code>private Datastore createDatastore(String dbName) { try { String dbDirectory = this.getDatastoreDirectory(dbName); boolean dbDirectoryExist = new File(dbDirectory).exists(); logger.fine("path: " + this.path); logger.fine("dbDirectory: " + dbDirectory); <START> logger.fine("dbDirectoryExist: " + dbDirectoryExist); <END> BasicDatastore ds = new BasicDatastore(dbDirectory, dbName); if(!dbDirectoryExist) { this.eventBus.post(new DatabaseCreated(dbName)); } eventBus.post(new DatabaseOpened(dbName)); return ds; } catch (IOException e) { throw new DatabaseNotCreatedException("Database not found: " + dbName, e); } catch (SQLException e) { throw new SQLRuntimeException("Database not initialized correctly: " + dbName, e); } }</code><technical_language>fine for Log.d Log.i here, in other places .finer for .d -- is this a typo? would've good intended mapping in description -- enough info for intent here</technical_language>

Target:
private Datastore createDatastore(String dbName) { try { String dbDirectory = this.getDatastoreDirectory(dbName); boolean dbDirectoryExist = new File(dbDirectory).exists(); logger.info("path: " + this.path); logger.info("dbDirectory: " + dbDirectory); logger.info("dbDirectoryExist: " + dbDirectoryExist); BasicDatastore ds = new BasicDatastore(dbDirectory, dbName); if(!dbDirectoryExist) { this.eventBus.post(new DatabaseCreated(dbName)); } eventBus.post(new DatabaseOpened(dbName)); return ds; } catch (IOException e) { throw new DatabaseNotCreatedException("Database not found: " + dbName, e); } catch (SQLException e) { throw new SQLRuntimeException("Database not initialized correctly: " + dbName, e); } }
Source:
<code>public LOCData apply(String input) { String[] parts = input.split(" "); <START> checkArgument(parts.length == 12, "record must have exactly twelve parts"); <END> String latitude = parts[0] + " " + parts[1] + " " + parts[2] + " " + parts[3]; String longitude = parts[4] + " " + parts[5] + " " + parts[6] + " " + parts[7]; return LOCData.builder().latitude(latitude) .longitude(longitude) .altitude(parts[8]) .diameter(parts[9]) .hprecision(parts[10]) .vprecision(parts[11]) .build(); }</code><technical_language>above, some of parts optional for a loc record default rfc, if providers give parts require all</technical_language>

Target:
public LOCData apply(String input) { return LOCData.create(input); }
Source:
<code>protected void internalInit(final WebContext context) { CommonHelper.assertNotNull("configuration", getConfiguration()); <START> String baseUri = getConfiguration().getCustomParam("authUrl"); <END> CommonHelper.assertNotNull("authUrl", baseUri); String realm = getConfiguration().getCustomParam("realm"); CommonHelper.assertNotNull("realm", realm); getConfiguration().setDiscoveryURI(baseUri+"/realms/"+realm+"/.well-known/openid-configuration"); final OidcProfileCreator<KeycloakOidcProfile> profileCreator = new OidcProfileCreator<>(getConfiguration()); profileCreator.setProfileDefinition(new OidcProfileDefinition<>(x -> new KeycloakOidcProfile())); setProfileCreator(profileCreator); super.internalInit(context); }</code><technical_language>In spirit for GenericOAuth20Client, specific properties: authUrl realm for parameters? Thanks</technical_language>

Target:
protected void internalInit(final WebContext context) { CommonHelper.assertNotNull("configuration", getConfiguration()); final OidcProfileCreator<KeycloakOidcProfile> profileCreator = new OidcProfileCreator<>(getConfiguration()); profileCreator.setProfileDefinition(new OidcProfileDefinition<>(x -> new KeycloakOidcProfile())); setProfileCreator(profileCreator); super.internalInit(context); }
Source:
<code>public PhysicalOperation visitTableScan(TableScanNode node, LocalExecutionPlanContext context) { List<ColumnHandle> columns = new ArrayList<>(); for (VariableReferenceExpression variable : node.getOutputVariables()) { columns.add(node.getAssignments().get(variable)); } <START> TableHandle tableHandle = node.getIsDelete() ? context.tableWriteInfo.getDeleteScanTableHandle().orElseThrow(() -> new IllegalStateException("deleteScanTableHandle is absent")) : node.getTable(); <END> OperatorFactory operatorFactory = new TableScanOperatorFactory(context.getNextOperatorId(), node.getId(), pageSourceProvider, tableHandle, columns); return new PhysicalOperation(operatorFactory, makeLayout(node), context, stageExecutionDescriptor.isScanGroupedExecution(node.getId()) ? GROUPED_EXECUTION : UNGROUPED_EXECUTION); }</code><technical_language>nit: IllegalStateException -> IllegalArgumentException/VerifyException</technical_language>

Target:
public PhysicalOperation visitTableScan(TableScanNode node, LocalExecutionPlanContext context) { List<ColumnHandle> columns = new ArrayList<>(); for (VariableReferenceExpression variable : node.getOutputVariables()) { columns.add(node.getAssignments().get(variable)); } TableHandle tableHandle; Optional<DeleteScanInfo> deleteScanInfo = context.getTableWriteInfo().getDeleteScanInfo(); if (deleteScanInfo.isPresent() && deleteScanInfo.get().getId() == node.getId()) { tableHandle = deleteScanInfo.get().getTableHandle(); } else { tableHandle = node.getTable(); } OperatorFactory operatorFactory = new TableScanOperatorFactory(context.getNextOperatorId(), node.getId(), pageSourceProvider, tableHandle, columns); return new PhysicalOperation(operatorFactory, makeLayout(node), context, stageExecutionDescriptor.isScanGroupedExecution(node.getId()) ? GROUPED_EXECUTION : UNGROUPED_EXECUTION); }
Source:
<code>private Set<String> validateCreateUserFromInvitationRequest(final CreateUserFromInvitationRequest request) { Set<String> validationErrors = new HashSet<String>(); if (request.getUser().getSubjectName().length() > getMaxLength("subjectName")) { validationErrors.add(errorMessageUtil.getMessage("user.subjectName.maxlength", getMaxLength("subjectName"))); } if (request.getUser().getFullName().length() > getMaxLength("fullName")) { validationErrors.add(errorMessageUtil.getMessage("user.fullName.maxlength", getMaxLength("fullName"))); } <START> if (!StringUtils.isEmpty(request.getUser().getFriendlyName())) { <END> if (request.getUser().getFriendlyName().length() > getMaxLength("friendlyName")) { validationErrors.add(errorMessageUtil.getMessage("user.friendlyName.maxlength", getMaxLength("friendlyName"))); } } if (!StringUtils.isEmpty(request.getUser().getTitle())) { if (request.getUser().getTitle().length() > getMaxLength("title")) { validationErrors.add(errorMessageUtil.getMessage("user.title.maxlength", getMaxLength("title"))); } } if (request.getUser().getEmail().length() > getMaxLength("email")) { validationErrors.add(errorMessageUtil.getMessage("user.email.maxlength", getMaxLength("email"))); } if (request.getUser().getPhoneNumber().length() > getMaxLength("phoneNumber")) { validationErrors.add(errorMessageUtil.getMessage("user.phoneNumber.maxlength", getMaxLength("phoneNumber"))); } return validationErrors; }</code><technical_language>do this &&, one? suggestion if (!StringUtils.isEmpty(request.getUser().getFriendlyName())</technical_language>

Target:
private Set<String> validateCreateUserFromInvitationRequest(final CreateUserFromInvitationRequest request) { Set<String> validationErrors = new HashSet<String>(); if (request.getUser().getSubjectName().length() > getMaxLength("subjectName")) { validationErrors.add(errorMessageUtil.getMessage("user.subjectName.maxlength", getMaxLength("subjectName"))); } if (request.getUser().getFullName().length() > getMaxLength("fullName")) { validationErrors.add(errorMessageUtil.getMessage("user.fullName.maxlength", getMaxLength("fullName"))); } if (!StringUtils.isEmpty(request.getUser().getFriendlyName()) && request.getUser().getFriendlyName().length() > getMaxLength("friendlyName")) { validationErrors.add(errorMessageUtil.getMessage("user.friendlyName.maxlength", getMaxLength("friendlyName"))); } if (!StringUtils.isEmpty(request.getUser().getTitle()) && request.getUser().getTitle().length() > getMaxLength("title")) { validationErrors.add(errorMessageUtil.getMessage("user.title.maxlength", getMaxLength("title"))); } if (request.getUser().getEmail().length() > getMaxLength("email")) { validationErrors.add(errorMessageUtil.getMessage("user.email.maxlength", getMaxLength("email"))); } if (request.getUser().getPhoneNumber().length() > getMaxLength("phoneNumber")) { validationErrors.add(errorMessageUtil.getMessage("user.phoneNumber.maxlength", getMaxLength("phoneNumber"))); } return validationErrors; }
Source:
<code>Lt(Column<T> column, T value) { super(column, value); <START> Preconditions.checkNotNull(value, "value"); <END> }</code><technical_language>write: super(column, checkNotNull(value, "value"));</technical_language>

Target:
Lt(Column<T> column, T value) { super(column, checkNotNull(value, "value")); }
Source:
<code>static boolean isQueryable(final File vcf){ <START> final VCFFileReader reader = new VCFFileReader(vcf, false); <END> try { reader.query(reader.getFileHeader().getSequenceDictionary().getSequence(0).getSequenceName(),1,1); } catch (final TribbleException e) { return false; } return true; }</code><technical_language>this in try-resources block closed</technical_language>

Target:
static boolean isQueryable(final File vcf) { if (!vcf.isFile()) return false; try (final VCFFileReader reader = new VCFFileReader(vcf, false)) { reader.query(reader.getFileHeader().getSequenceDictionary().getSequence(0).getSequenceName(), 1, 1); } catch (final TribbleException e) { return false; } return true; }
Source:
<code>public static void createDbExportDump(FileSystem fs, Path metadataPath, Database dbObj, ReplicationSpec replicationSpec) throws IOException, SemanticException { Map<String, String> parameters = dbObj.getParameters(); if (parameters != null) { parameters.entrySet() .removeIf(e -> e.getKey().startsWith(Utils.BOOTSTRAP_DUMP_STATE_KEY_PREFIX)); dbObj.setParameters(parameters); <START> } <END> try (JsonWriter jsonWriter = new JsonWriter(fs, metadataPath)) { new DBSerializer(dbObj).writeTo(jsonWriter, replicationSpec); } }</code><technical_language>reset parameters object in dbObj object is pass reference export of properties object else need access original properties</technical_language>

Target:
public static void createDbExportDump(FileSystem fs, Path metadataPath, Database dbObj, ReplicationSpec replicationSpec) throws IOException, SemanticException { Map<String, String> parameters = dbObj.getParameters(); Map<String, String> tmpParameters = new HashMap<>(); if (parameters != null) { tmpParameters.putAll(parameters); tmpParameters.entrySet() .removeIf(e -> e.getKey().startsWith(Utils.BOOTSTRAP_DUMP_STATE_KEY_PREFIX)); dbObj.setParameters(tmpParameters); } try (JsonWriter jsonWriter = new JsonWriter(fs, metadataPath)) { new DBSerializer(dbObj).writeTo(jsonWriter, replicationSpec); } if (parameters != null) { dbObj.setParameters(parameters); } }
Source:
<code>private static List<Object> createParams(String name, String prefix, String methodAnnotation, Class<?>[] parameterTypes, String[] optionalValues, String[] parameterNames, MethodParameters params, XmlSuite xmlSuite) { List<Object> vResult = Lists.newArrayList(); if (isInjected) { <START> FilterOutInJectedTypesResult filterOutResult = FilterOutInJectedTypesFromOptionalValues(parameterTypes, optionalValues); <END> optionalValues = filterOutResult.getOptionalValues(); parameterTypes = filterOutResult.getParameterTypes(); } for (int i = 0; i < parameterNames.length; i++) { String p = parameterNames[i]; String value = params.xmlParameters.get(p); if (null == value) { value = System.getProperty(p); } if (null == value) { if (optionalValues != null) { value = optionalValues[i]; } if (null == value) { throw new TestNGException("Parameter '" + p + "' is required by " + methodAnnotation + " on " + prefix + " " + name + " but has not been marked @Optional or defined\n" + (xmlSuite.getFileName() != null ? "in " + xmlSuite.getFileName() : "")); } } vResult.add(convertType(parameterTypes[i], value, p)); } return vResult; }</code><technical_language>a method, start a lowercase: filterOutInjectedTypesFromOptionalValues()</technical_language>

Target:
private static List<Object> createParams(String name, String prefix, String methodAnnotation, Class<?>[] parameterTypes, String[] optionalValues, String[] parameterNames, MethodParameters params, XmlSuite xmlSuite) { List<Object> vResult = Lists.newArrayList(); if (optionalValues.length != parameterNames.length) { FilterOutInJectedTypesResult filterOutResult = filterOutInJectedTypesFromOptionalValues(parameterTypes, optionalValues); optionalValues = filterOutResult.getOptionalValues(); parameterTypes = filterOutResult.getParameterTypes(); } for (int i = 0; i < parameterNames.length; i++) { String p = parameterNames[i]; String value = params.xmlParameters.get(p); if (null == value) { value = System.getProperty(p); } if (null == value) { if (optionalValues != null) { value = optionalValues[i]; } if (null == value) { throw new TestNGException("Parameter '" + p + "' is required by " + methodAnnotation + " on " + prefix + " " + name + " but has not been marked @Optional or defined\n" + (xmlSuite.getFileName() != null ? "in " + xmlSuite.getFileName() : "")); } } vResult.add(convertType(parameterTypes[i], value, p)); } return vResult; }
Source:
<code>public Snapshot getSnapshot() { rescaleIfNeeded(); <START> lockForRescale(); <END> try { Snapshot snapshot = new WeightedSnapshot(values.values()); values.clear(); count.set(0); return snapshot; } finally { unlockForRescale(); } }</code><technical_language>Actually, avoid releasing lock twice, else potentially in middle, lockForRescale() rescaleIfNeeded()? rescale() (re-entrant) lock, a no-op it</technical_language>

Target:
public Snapshot getSnapshot() { lockForRescale(); rescaleIfNeeded(); try { Snapshot snapshot = new WeightedSnapshot(values.values()); values.clear(); count.set(0); return snapshot; } finally { unlockForRescale(); } }
Source:
<code>public CommandController createCommandController(String name, Resource<?>... initialSelection) throws Exception { CommandController result = null; Iterable<UICommand> commands = commandFactory.getCommands(); <START> try (UIContextImpl context = getUIContextInstance(initialSelection)) { <END> for (UICommand command : commands) { UICommandMetadata metadata = command.getMetadata(context); if (name.equals(metadata.getName())) { result = factory.createSingleController(context, getUIRuntimeInstance(), command); break; } } Assert.notNull(result, "Command " + name + " not found"); return result; } }</code><technical_language>UIContext closed in afaik</technical_language>

Target:
public CommandController createCommandController(String name, Resource<?>... initialSelection) throws Exception { CommandController result = null; Iterable<UICommand> commands = commandFactory.getCommands(); UIContextImpl context = getUIContextInstance(initialSelection); for (UICommand command : commands) { UICommandMetadata metadata = command.getMetadata(context); if (name.equals(metadata.getName())) { result = factory.createSingleController(context, getUIRuntimeInstance(), command); break; } } Assert.notNull(result, "Command " + name + " not found"); return result; }
Source:
<code>public TaskCreationTask(YouViewLastUpdatedStore lastUpdatedStore, Publisher publisher, ContentHierarchyExpander hierarchyExpander, IdGenerator idGenerator, TaskStore taskStore, TaskCreator taskCreator, PayloadCreator payloadCreator, YouViewPayloadHashStore payloadHashStore, HashCheck hashCheckMode) { this.lastUpdatedStore = checkNotNull(lastUpdatedStore); this.publisher = checkNotNull(publisher); this.hierarchyExpander = checkNotNull(hierarchyExpander); this.idGenerator = checkNotNull(idGenerator); this.taskStore = checkNotNull(taskStore); this.taskCreator = checkNotNull(taskCreator); this.payloadCreator = checkNotNull(payloadCreator); <START> this.payloadHashStore = payloadHashStore; <END> this.hashCheckMode = hashCheckMode; }</code><technical_language>_cough_ checkNotNull _cough_</technical_language>

Target:
public TaskCreationTask(YouViewLastUpdatedStore lastUpdatedStore, Publisher publisher, ContentHierarchyExpander hierarchyExpander, IdGenerator idGenerator, TaskStore taskStore, TaskCreator taskCreator, PayloadCreator payloadCreator, YouViewPayloadHashStore payloadHashStore, HashCheck hashCheckMode) { this.lastUpdatedStore = checkNotNull(lastUpdatedStore); this.publisher = checkNotNull(publisher); this.hierarchyExpander = checkNotNull(hierarchyExpander); this.idGenerator = checkNotNull(idGenerator); this.taskStore = checkNotNull(taskStore); this.taskCreator = checkNotNull(taskCreator); this.payloadCreator = checkNotNull(payloadCreator); this.payloadHashStore = checkNotNull(payloadHashStore); this.hashCheckMode = hashCheckMode; }
Source:
<code>public S3AFileStatus next() throws IOException { final S3AFileStatus status; if (sourceHasNext()) { status = statusBatchIterator.next(); <START> Optional<S3AFileStatus> provided = <END> StreamSupport.stream(providedStatus.spliterator(), false) .filter(element -> status.equals(element)).findFirst(); if (provided.isPresent()) { providedStatus.remove(status); LOG.debug( "Removed and returned the status from provided file status {}", status); return provided.get(); } } else { if (providedStatusIterator.hasNext()) { status = providedStatusIterator.next(); LOG.debug("Returning provided file status {}", status); } else { throw new NoSuchElementException(); } } return status; }</code><technical_language>status2 = providedStatus.remove(status); if (status2 != null) { return status; } way: need scan list for a entry remove operation anyway</technical_language>

Target:
public S3AFileStatus next() throws IOException { final S3AFileStatus status; if (sourceHasNext()) { status = statusBatchIterator.next(); S3AFileStatus provided = providedStatus.remove(status.getPath()); if (provided != null) { LOG.debug( "Removed and returned the status from provided file status {}", status); return provided; } } else { if (providedStatusIterator.hasNext()) { status = providedStatusIterator.next(); LOG.debug("Returning provided file status {}", status); } else { throw new NoSuchElementException(); } } return status; }
Source:
<code>private boolean buildJavaCommand(String pa_home, String[] jvmArgs) { String javaCmd = pa_home + separator + "jre" + separator + "bin" + separator + "java"; if (new File(javaCmd).exists()) { command.add(javaCmd); command.add("-jar"); command.addAll(Arrays.asList(jvmArgs)); return true; } else { <START> System.out.println("Java command not found when starting IAM microservice"); <END> return false; } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Replace this of System.out System.err a logger. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static boolean buildJavaCommand(String pa_home, String[] jvmArgs) { String javaCmd = pa_home + SEPARATOR + "jre" + SEPARATOR + "bin" + SEPARATOR + "java"; if (new File(javaCmd).exists()) { command.add(javaCmd); command.add("-jar"); command.addAll(Arrays.asList(jvmArgs)); return true; } else { System.out.println("Java command not found when starting IAM microservice"); return false; } }
Source:
<code>public JSONArray(Collection<?> collection) { <START> this.myArrayList = new ArrayList<Object>(collection == null ? 0 : collection.size()); <END> if (collection != null) { for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } } }</code><technical_language>if/else statement instead of 0 initial capacity</technical_language>

Target:
public JSONArray(Collection<?> collection) { if (collection == null) { this.myArrayList = new ArrayList<Object>(); } else { this.myArrayList = new ArrayList<Object>(collection.size()); for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } } }
Source:
<code>@Test public void testWrite() { when(options.get(Documentor.DOC_OUTPUT_PROPERTY_NAME)).thenReturn(FILE_PATH); Documentor documentor = new Documentor(processingEnv); documentor.write(getElements()); try { String actual = Files.toString(new File(FILE_PATH), Charsets.UTF_8); String expected = "airbnb://example.com/{foo}/bar\\n|#|\\nSample doc\\n|#|\\nDocClass\\n|##|\\n" + "airbnb://example.com/{foo}/bar\\n|#|\\n\\n|#|\\nDocClass#DocMethod\\n|##|\\n"; assertEquals(expected, actual); <START> } catch (IOException e) { <END> fail(); } }</code><technical_language>dont need catch exception, right? if test throws something, automatically fail</technical_language>

Target:
@Test public void testWrite() throws IOException { when(options.get(Documentor.DOC_OUTPUT_PROPERTY_NAME)).thenReturn(FILE_PATH); Documentor documentor = new Documentor(processingEnv); documentor.write(getElements()); String actual = Files.toString(new File(FILE_PATH), Charsets.UTF_8); String expected = "airbnb://example.com/{foo}/bar\\n|#|\\nSample doc\\n|#|\\nDocClass\\" + "n|##|\\nairbnb://example.com/{foo}/bar\\n|#|\\n\\n|#|\\nDocClass#DocMethod\\n|##|\\n"; assertEquals(expected, actual); }
Source:
<code>public void add(Activity activity) { Util.throwIfNull(activity); <START> Util.throwIfNot(Looper.myLooper() == Looper.getMainLooper()); <END> mActivities.add(activity); mObservable.notifyActivityAdded(activity); }</code><technical_language>want wrap this pattern a utility method, e.g. public static LooperUtil { public static void throwIfNotMainThread() { Util.throwIfNot(Looper.myLooper() == Looper.getMainLooper()); } }</technical_language>

Target:
public void add(Activity activity) { Util.throwIfNull(activity); Util.throwIfNot(Looper.myLooper() == Looper.getMainLooper()); mActivities.add(activity); for (Listener listener : mListeners) { listener.onActivityAdded(activity); } }