auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject configurationObject = json.getAsJsonObject(); <START> JsonObject propertiesObject = configurationObject.get("properties").getAsJsonObject(); <END> for (Entry<String, JsonElement> entry : propertiesObject.entrySet()) { JsonElement value = entry.getValue(); String key = entry.getKey(); if (value.isJsonPrimitive()) { JsonPrimitive primitive = value.getAsJsonPrimitive(); configuration.put(key, deserialize(primitive)); } else if (value.isJsonArray()) { JsonArray array = value.getAsJsonArray(); configuration.put(key, deserialize(array)); } else { throw new IllegalArgumentException( "Configuration parameters must be primitives or arrays of primities only but was " + value); } } return configuration; }</code><technical_language>"save" test if configurationObject.get("properties") returns null</technical_language>

Target:
public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject configurationObject = json.getAsJsonObject(); if (configurationObject.get("properties") != null) { JsonObject propertiesObject = configurationObject.get("properties").getAsJsonObject(); for (Entry<String, JsonElement> entry : propertiesObject.entrySet()) { JsonElement value = entry.getValue(); String key = entry.getKey(); if (value.isJsonPrimitive()) { JsonPrimitive primitive = value.getAsJsonPrimitive(); configuration.put(key, deserialize(primitive)); } else if (value.isJsonArray()) { JsonArray array = value.getAsJsonArray(); configuration.put(key, deserialize(array)); } else { throw new IllegalArgumentException( "Configuration parameters must be primitives or arrays of primities only but was " + value); } } } return configuration; }
Source:
<code>public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { String vepOutput = getVepOutput(jobExecution); if (getFileSize(vepOutput) <= 0) { <START> logger.info("File is empty so following steps will not run", vepOutput); <END> return new FlowExecutionStatus(STOP_FLOW); } return new FlowExecutionStatus(CONTINUE_FLOW); }</code><technical_language>"subsequent" instead of "following" maybe? @tomdcsmith help</technical_language>

Target:
public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { String vepOutput = getVepOutput(jobExecution); if (getFileSize(vepOutput) > 0) { return new FlowExecutionStatus(CONTINUE_FLOW); } logger.info("File is empty so subsequent steps will not run", vepOutput); return new FlowExecutionStatus(STOP_FLOW); }
Source:
<code>private void createWarning(final Level level, final ModelNode warning){ final ModelNode warningEntry = new ModelNode(); warningEntry.get(WARNING).set(warning); warningEntry.get(LEVEL).set(level.toString()); final ModelNode operation = activeStep.operation; if(operation != null){ final ModelNode operationEntry = warningEntry.get(OP); operationEntry.get(OP_ADDR).set(operation.get(OP_ADDR)); operationEntry.get(OP).set(operation.get(OP)); } final ModelNode warnings = getResponseHeaders().get(WARNINGS); boolean unique = true; if (warnings.isDefined()) { for (ModelNode existing : warnings.asList()) { <START> if (existing.equals(warning)) { <END> unique = false; break; } } } if (unique) { warnings.add(warningEntry); } }</code><technical_language>Is comparison correct? * existing is item of getResponseHeaders().get(WARNINGS) contains ModelNode of warningEntry type (with warning level properties). * warning field is a ModelNode is stored warning property of warningEntry type. call be: if (existing.get(WARNING).equals(warning)) { // ignore level warning for comparison ... }</technical_language>

Target:
private void createWarning(final Level level, final ModelNode warning){ final ModelNode warningEntry = new ModelNode(); warningEntry.get(WARNING).set(warning); warningEntry.get(LEVEL).set(level.toString()); final ModelNode operation = activeStep.operation; if(operation != null){ final ModelNode operationEntry = warningEntry.get(OP); operationEntry.get(OP_ADDR).set(operation.get(OP_ADDR)); operationEntry.get(OP).set(operation.get(OP)); } final ModelNode warnings = getResponseHeaders().get(WARNINGS); boolean unique = true; if (warnings.isDefined()) { for (ModelNode existing : warnings.asList()) { if (existing.equals(warningEntry)) { unique = false; break; } } } if (unique) { warnings.add(warningEntry); } }
Source:
<code>public static Task<Void> whenAll(Collection<? extends Task<?>> tasks) { if (tasks.size() == 0) { return Task.forResult(null); } final Task<Void>.TaskCompletionSource allFinished = Task.create(); <START> final ArrayList<Throwable> causes = new ArrayList<Throwable>(); <END> final Object errorLock = new Object(); final AtomicInteger count = new AtomicInteger(tasks.size()); final AtomicBoolean isCancelled = new AtomicBoolean(false); for (Task<?> task : tasks) { @SuppressWarnings("unchecked") Task<Object> t = (Task<Object>) task; t.continueWith(new Continuation<Object, Void>() { @Override public Void then(Task<Object> task) { if (task.isFaulted()) { synchronized (errorLock) { causes.add(task.getError()); } } if (task.isCancelled()) { isCancelled.set(true); } if (count.decrementAndGet() == 0) { if (causes.size() != 0) { if (causes.size() == 1) { allFinished.setError((Exception) causes.get(0)); } else { Exception error = new AggregateException( String.format("There were %d exceptions.", causes.size()), causes); allFinished.setError(error); } } else if (isCancelled.get()) { allFinished.setCancelled(); } else { allFinished.setResult(null); } } return null; } }); } return allFinished.getTask(); }</code><technical_language>change this exception avoid cast in allFinished.setError? catch Throwable, Exception</technical_language>

Target:
public static Task<Void> whenAll(Collection<? extends Task<?>> tasks) { if (tasks.size() == 0) { return Task.forResult(null); } final Task<Void>.TaskCompletionSource allFinished = Task.create(); final ArrayList<Exception> causes = new ArrayList<Exception>(); final Object errorLock = new Object(); final AtomicInteger count = new AtomicInteger(tasks.size()); final AtomicBoolean isCancelled = new AtomicBoolean(false); for (Task<?> task : tasks) { @SuppressWarnings("unchecked") Task<Object> t = (Task<Object>) task; t.continueWith(new Continuation<Object, Void>() { @Override public Void then(Task<Object> task) { if (task.isFaulted()) { synchronized (errorLock) { causes.add(task.getError()); } } if (task.isCancelled()) { isCancelled.set(true); } if (count.decrementAndGet() == 0) { if (causes.size() != 0) { if (causes.size() == 1) { allFinished.setError(causes.get(0)); } else { Exception error = new AggregateException( String.format("There were %d exceptions.", causes.size()), causes); allFinished.setError(error); } } else if (isCancelled.get()) { allFinished.setCancelled(); } else { allFinished.setResult(null); } } return null; } }); } return allFinished.getTask(); }
Source:
<code>private void runPushOperation() { pool.notifyStarting(this); if (!canceled) { try { git = gitManager.openRepository(projectName); runImpl(); } catch (RepositoryNotFoundException e) { log.error("Cannot replicate " + projectName + "; " + e.getMessage()); } catch (NoRemoteRepositoryException e) { log.error("Cannot replicate to " + uri + "; repository not found"); } catch (NotSupportedException e) { log.error("Cannot replicate to " + uri, e); } catch (TransportException e) { Throwable cause = e.getCause(); if (cause instanceof JSchException && cause.getMessage().startsWith("UnknownHostKey:")) { log.error("Cannot replicate to " + uri + ": " + cause.getMessage()); } else if (e instanceof LockFailureException) { lockRetry++; log.error("Cannot replicate to " + e.getMessage()); } else { log.error("Cannot replicate to " + uri, e); } <START> if (lockRetry < 10) { <END> pool.reschedule(this); } } catch (IOException e) { log.error("Cannot replicate to " + uri, e); } catch (RuntimeException e) { log.error("Unexpected error during replication to " + uri, e); } catch (Error e) { log.error("Unexpected error during replication to " + uri, e); } finally { if (git != null) { git.close(); } } } }</code><technical_language>10 excessive. 10 surely extreme contention a miss-tuned system. I this a configuration parameter I suggest a default of 3</technical_language>

Target:
private void runPushOperation() { pool.notifyStarting(this); if (!canceled) { try { git = gitManager.openRepository(projectName); runImpl(); } catch (RepositoryNotFoundException e) { log.error("Cannot replicate " + projectName + "; " + e.getMessage()); } catch (NoRemoteRepositoryException e) { log.error("Cannot replicate to " + uri + "; repository not found"); } catch (NotSupportedException e) { log.error("Cannot replicate to " + uri, e); } catch (TransportException e) { Throwable cause = e.getCause(); if (cause instanceof JSchException && cause.getMessage().startsWith("UnknownHostKey:")) { log.error("Cannot replicate to " + uri + ": " + cause.getMessage()); } else if (e instanceof LockFailureException) { lockRetry++; log.error("Cannot replicate to " + e.getMessage()); } else { log.error("Cannot replicate to " + uri, e); } if (lockRetry < MAX_LOCK_TRIES) { pool.reschedule(this); } else { log.error("Giving up after " + MAX_LOCK_TRIES + " attempts to replicate, but still failing due to: " + e.getMessage()); } } catch (IOException e) { log.error("Cannot replicate to " + uri, e); } catch (RuntimeException e) { log.error("Unexpected error during replication to " + uri, e); } catch (Error e) { log.error("Unexpected error during replication to " + uri, e); } finally { if (git != null) { git.close(); } } } }
Source:
<code>protected Set<Type> getFromConversionImportTypes(ConversionContext conversionContext) { return Collections.asSet( <START> conversionContext.getTypeFactory().getType( dateTimeFormatterClass() ) <END> ); }</code><technical_language>getType(String) method avoid throwing RuntimeException. if a class name is classpath</technical_language>

Target:
protected Set<Type> getFromConversionImportTypes(ConversionContext conversionContext) { return Collections.asSet( conversionContext.getTypeFactory().getType( JavaTimeConstants.DATE_TIME_FORMATTER ) ); }
Source:
<code>public static Pair<? extends UndoAction, TheHashinator> updateHashinator( Class<? extends TheHashinator> hashinatorImplementation, long version, byte configBytes[], boolean cooked) { TheHashinator existingHashinator = m_cachedHashinators.get(version); if (existingHashinator == null) { existingHashinator = constructHashinator(hashinatorImplementation, configBytes, cooked); TheHashinator tempVal = m_cachedHashinators.putIfAbsent( version, existingHashinator); if (tempVal != null) existingHashinator = tempVal; } while (true) { final Pair<Long, ? extends TheHashinator> snapshot = instance.get(); if (version > snapshot.getFirst()) { final Pair<Long, ? extends TheHashinator> update = Pair.of(version, existingHashinator); if (instance.compareAndSet(snapshot, update)) { if (!m_elasticallyModified) { if (!update.getSecond().pIsPrestine()) { hostLogger.debug("The Hashinator has been elastically modified. " + "This cluster can no longer operate in DR same-size-cluster mode."); m_elasticallyModified = true; <START> } <END> } return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() { boolean rolledBack = instance.compareAndSet(update, snapshot); if (!rolledBack) { hostLogger.info( "Didn't roll back hashinator because it wasn't set to expected hashinator"); } } }, existingHashinator); } } else { return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() }, existingHashinator); } } }</code><technical_language>Do want rollback m_elasticallyModified in undoAction</technical_language>

Target:
public static Pair<? extends UndoAction, TheHashinator> updateHashinator( Class<? extends TheHashinator> hashinatorImplementation, long version, byte configBytes[], boolean cooked) { TheHashinator existingHashinator = m_cachedHashinators.get(version); if (existingHashinator == null) { existingHashinator = constructHashinator(hashinatorImplementation, configBytes, cooked); TheHashinator tempVal = m_cachedHashinators.putIfAbsent( version, existingHashinator); if (tempVal != null) existingHashinator = tempVal; } while (true) { final Pair<Long, ? extends TheHashinator> snapshot = instance.get(); if (version > snapshot.getFirst()) { final Pair<Long, ? extends TheHashinator> update = Pair.of(version, existingHashinator); if (instance.compareAndSet(snapshot, update)) { if (!m_elasticallyModified) { if (!update.getSecond().pIsPristine()) { hostLogger.debug("The Hashinator has been elastically modified. " + "This cluster can no longer operate in DR same-size-cluster mode."); m_elasticallyModified = true; } } return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() { boolean rolledBack = instance.compareAndSet(update, snapshot); if (!rolledBack) { hostLogger.info( "Didn't roll back hashinator because it wasn't set to expected hashinator"); } } }, existingHashinator); } } else { return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() }, existingHashinator); } } }
Source:
<code>private String checkURL(String url) { url = url.replace("\\", "/"); if (url.startsWith("file:")) { return url; } File file = new File(url); if (file.exists()) { try { <START> return file.toURL().toExternalForm(); <END> } catch (MalformedURLException e) { return url; } } return url; }</code><technical_language>Note File.toURL() is deprecated issues (though I recall ones). recommended do this is File.toURI().toURL()</technical_language>

Target:
private String checkURL(String url) { url = url.replace("\\", "/"); if (url.startsWith("file:")) { return url; } File file = new File(url); if (file.exists()) { try { return file.toURI().toURL().toExternalForm(); } catch (MalformedURLException e) { return url; } } return url; }
Source:
<code>public void onResponse(Map<String, Object> response) { try { VDSReturnValue caps = (VDSReturnValue) response.get("result"); if (caps.getSucceeded()) { getHardwareInfo(vds); } <START> continueRefreshCapabilities(new AtomicBoolean(), vds, oldVDS, caps); <END> } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }</code><technical_language>this fit in a single line (according formatter 120 chars limitation)</technical_language>

Target:
public void onResponse(Map<String, Object> response) { try { VDSReturnValue caps = (VDSReturnValue) response.get("result"); invokeGetHardwareInfo(vds, caps); processRefreshCapabilitiesResponse(new AtomicBoolean(), vds, vds.clone(), caps); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }
Source:
<code>private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); String i18nCommitEncoding = rc.getString( ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); if (i18nCommitEncoding != null) { <START> commitMessageEncoding = Charset.forName(i18nCommitEncoding); <END> } }</code><technical_language>if this throws exception? mapped a ConfigInvalidException, caller report error</technical_language>

Target:
private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); i18nCommitEncoding = rc.getString(ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); }
Source:
<code>private boolean isFileNameAccepted( String name ) { if ( name != null && name.trim().length() > 0 ) { Set<String> exts = getExtensionsAccepted(); <START> for ( String ext : exts ) { <END> if ( name.endsWith( "." + ext ) ) { return true; } } } return null != name && name.endsWith( "." + METADATA_EXTENSION ); }</code><technical_language>Java8 stream anyMatch() instead of this loop</technical_language>

Target:
private boolean isFileNameAccepted( String name ) { if ( name != null && name.trim().length() > 0 ) { return getExtensionsAccepted().stream().anyMatch( s -> name.endsWith( "." + s ) ); } return null != name && name.endsWith( "." + METADATA_EXTENSION ); }
Source:
<code>public ValueProcessor<?, ?> getDelegate(Key<?> key) { if (this.tempRegistry != null) { <START> if (this.tempRegistry.valueProcessorMap.containsKey(key)) { <END> return new ValueProcessorDelegate(key, ImmutableList.copyOf(this.tempRegistry.valueProcessorMap.get(key))); } else { return null; } } return this.valueDelegates.get(key); }</code><technical_language>faster simply calling get checking if processor is null</technical_language>

Target:
public ValueProcessor<?, ?> getDelegate(Key<?> key) { if (this.tempRegistry != null) { List<ValueProcessor<?, ?>> list = this.tempRegistry.valueProcessorMap.get(key); if (list == null) { return null; } return new ValueProcessorDelegate(key, ImmutableList.copyOf(list)); } return this.valueDelegates.get(key); }
Source:
<code>public void testOverrideBundleAnnotationsInstruction_success() throws Exception { try (Builder b = new Builder()) { b.addClasspath(IO.getFile("bin_test")); b.setPrivatePackage("test.annotationheaders.attrs.std.activator"); b.setProperty(Constants.BUNDLE_ACTIVATOR, "test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); <START> b.setProperty("-bundleannotations", "!test.annotationheaders.attrs.std.activator.TypeInVersionedPackage"); <END> b.build(); assertTrue(b.check()); Manifest manifest = b.getJar() .getManifest(); manifest.write(System.out); Attributes mainAttributes = manifest.getMainAttributes(); Header repeated = Header.parseHeader(mainAttributes.getValue(Constants.BUNDLE_ACTIVATOR)); assertThat(repeated).containsOnlyKeys("test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); } }</code><technical_language>this a ,* end</technical_language>

Target:
public void testOverrideBundleAnnotationsInstruction_success() throws Exception { try (Builder b = new Builder()) { b.addClasspath(IO.getFile("bin_test")); b.setPrivatePackage("test.annotationheaders.attrs.std.activator"); b.setProperty(Constants.BUNDLE_ACTIVATOR, "test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); b.setProperty("-bundleannotations", "!test.annotationheaders.attrs.std.activator.TypeInVersionedPackage,*"); b.build(); assertTrue(b.check()); Manifest manifest = b.getJar() .getManifest(); manifest.write(System.out); Attributes mainAttributes = manifest.getMainAttributes(); Header repeated = Header.parseHeader(mainAttributes.getValue(Constants.BUNDLE_ACTIVATOR)); assertThat(repeated).containsOnlyKeys("test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); } }
Source:
<code>public void testAverageSince() { item.setState(new DecimalType(3025)); DateMidnight startStored = new DateMidnight(2003, 1, 1); DateMidnight endStored = new DateMidnight(2012, 1, 1); long storedInterval = endStored.getMillis() - startStored.getMillis(); long recentInterval = DateTime.now().getMillis() - endStored.getMillis(); double expected = (2007.4994 * storedInterval + 2518.5 * recentInterval) / (storedInterval + recentInterval); DecimalType average = PersistenceExtensions.averageSince(item, startStored, "test"); <START> assertEquals(expected, average.doubleValue(), 0.001); <END> }</code><technical_language>Is this test stable enough? If execution is slow, average calculated a bigger recentInterval results differ, right</technical_language>

Target:
public void testAverageSince() { item.setState(new DecimalType(3025)); DateMidnight startStored = new DateMidnight(2003, 1, 1); DateMidnight endStored = new DateMidnight(2012, 1, 1); long storedInterval = endStored.getMillis() - startStored.getMillis(); long recentInterval = DateTime.now().getMillis() - endStored.getMillis(); double expected = (2007.4994 * storedInterval + 2518.5 * recentInterval) / (storedInterval + recentInterval); DecimalType average = PersistenceExtensions.averageSince(item, startStored, "test"); assertEquals(expected, average.doubleValue(), 0.01); }
Source:
<code>public void listenerOnLogout(L2PcInstance player) { if (_currentEvent == null) { if (_state == EventEngineState.REGISTER || _state == EventEngineState.VOTING) { L2GameClient client = player.getClient(); <START> DualBoxProtection.getInstance().removeConnection(client); <END> removeVote(player); unRegisterPlayer(player); return; } } else { try { _currentEvent.listenerOnLogout(player); } catch (Exception e) { LOGGER.warning(EventEngineManager.class.getSimpleName() + ": -> listenerOnLogout() " + e); e.printStackTrace(); } } }</code><technical_language>single line: DualBoxProtection.getInstance().removeConnection(player.getClient()); add a method handles a player client. Btw, client null</technical_language>

Target:
public void listenerOnLogout(L2PcInstance player) { if (_currentEvent == null) { if (_state == EventEngineState.REGISTER || _state == EventEngineState.VOTING) { DualBoxProtection.getInstance().removeConnection(player.getClient()); removeVote(player); unRegisterPlayer(player); return; } } else { try { _currentEvent.listenerOnLogout(player); } catch (Exception e) { LOGGER.warning(EventEngineManager.class.getSimpleName() + ": -> listenerOnLogout() " + e); e.printStackTrace(); } } }
Source:
<code>public static int getOrdinalFromId(final Activity activity, final Resources res, final int id) { int ordinal = 0; <START> for (NavigationApp app : getNavigationApps(res)) { <END> if (app.isInstalled(activity)) { if (app.getId() == id) { return ordinal; } ordinal++; } } return 0; }</code><technical_language>This new method getInstalledNavigationApps instead of checking installation itself. please new method in addMenuItems(...)</technical_language>

Target:
public static int getOrdinalFromId(final Activity activity, final Resources res, final int id) { int ordinal = 0; for (NavigationApp app : getInstalledNavigationApps(activity, res)) { if (app.getId() == id) { return ordinal; } ordinal++; } return 0; }
Source:
<code>public void writeToLog(String subDir,String orginalFileName, String headerLine,String msg,UserAccountBean userBean) { BufferedWriter bw = null; FileWriter fw = null; boolean isNewFile = false; String logFileName; if(orginalFileName == null) { <START> ; <END> }else { try { int count =1; File logFile; String importFileDir = this.getPersonalLogFileDir(userBean,subDir); logFileName = importFileDir + orginalFileName; logFile = new File(logFileName); if(!logFile.exists()) { logFile.createNewFile(); isNewFile = true; } fw = new FileWriter(logFile.getAbsoluteFile(), true); bw = new BufferedWriter(fw); if(isNewFile) { bw.write(headerLine); bw.write("\n"); } if(msg != null) { bw.write(msg); bw.write("\n"); } bw.close(); } catch (Exception e) { e.printStackTrace(); }finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }</code><technical_language>Log some message here</technical_language>

Target:
public void writeToLog(String subDir,String orginalFileName, String headerLine,String msg,UserAccountBean userBean) throws OpenClinicaException { BufferedWriter bw = null; FileWriter fw = null; boolean isNewFile = false; String logFileName; if(orginalFileName == null) { logger.info("errorCode.emptyFile -- The file is null "); }else { try { int count =1; File logFile; String importFileDir = this.getPersonalLogFileDir(userBean,subDir); logFileName = importFileDir + orginalFileName; logFile = new File(logFileName); if(!logFile.exists()) { logFile.createNewFile(); isNewFile = true; } fw = new FileWriter(logFile.getAbsoluteFile(), true); bw = new BufferedWriter(fw); if(isNewFile) { bw.write(headerLine); bw.write("\n"); } if(msg != null) { bw.write(msg); bw.write("\n"); } bw.close(); } catch (Exception e) { logger.error("Log File error " + e.getMessage()); throw new OpenClinicaException("Write to log file error", ErrorConstants.ERR_LOG_FILE); }finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { logger.error("Log File error " + ex.getMessage()); throw new OpenClinicaException("Write to log file error", ErrorConstants.ERR_LOG_FILE); } } } }
Source:
<code>public static String getResponseFromServer(final URL constructedUrl, final String encoding) { <START> return getResponseFromServer(constructedUrl, HttpsURLConnection.getDefaultHostnameVerifier(), null, encoding); <END> }</code><technical_language>nan</technical_language>

Target:
public static String getResponseFromServer(final URL constructedUrl, final String encoding) { return getResponseFromServer(constructedUrl, HttpsURLConnection.getDefaultHostnameVerifier(), new Properties(), encoding); }
Source:
<code><START> public void start(BundleContext bc) throws Exception { <END> bc.registerService(DockingPanel.class, new GroovyConsolePanel(), null); }</code><technical_language>useful put this here: java LOGGER.info("Groovy console starting...");</technical_language>

Target:
public void start(BundleContext bc) throws Exception { LOGGER.info(I18N.tr("Groovy console starting...")); bc.registerService(DockingPanel.class, new GroovyConsolePanel(), null); }
Source:
<code>private void processUpdates(List<ClusterMember> updates, boolean spreadGossip) { if (updates.isEmpty()) { return; } Collection<Address> members = membership.getTrustedOrSuspectedMembers(); failureDetector.setMembers(members); gossipProtocol.setMembers(members); if (spreadGossip) { gossipProtocol.spread(Message.fromData(new ClusterMembershipData(updates, syncGroup))); } for (ClusterMember update : updates) { subject.onNext(update); } for (final ClusterMember member : updates) { LOGGER.debug("Member became {}", member.address(), member.status()); switch (member.status()) { <START> case SUSPECTED: { <END> failureDetector.suspect(member.address()); suspectedMembersSchedule.get(member.id(), new ComputableSuspectedMembersSchedule()); break; } case TRUSTED: { failureDetector.trust(member.address()); ScheduledFuture<?> future = suspectedMembersSchedule.remove(member.id()); if (future != null) { future.cancel(true); } break; } case SHUTDOWN: { suspectedMembersTimer.schedule(new Runnable() { @Override public void run() { LOGGER.debug("Time to remove SHUTDOWN member={} from membership table", member.address()); membership.remove(member.id()); } }, maxShutdownTime, TimeUnit.MILLISECONDS); break; } default: } } }</code><technical_language>need brackets here</technical_language>

Target:
private void processUpdates(List<ClusterMember> updates, boolean spreadGossip) { if (updates.isEmpty()) { return; } Collection<Address> members = membership.getTrustedOrSuspectedMembers(); failureDetector.setMembers(members); gossipProtocol.setMembers(members); if (spreadGossip) { gossipProtocol.spread(Message.fromData(new ClusterMembershipData(updates, syncGroup))); } for (ClusterMember update : updates) { subject.onNext(update); } for (final ClusterMember member : updates) { LOGGER.debug("Member became {}", member.address(), member.status()); switch (member.status()) { case SUSPECTED: failureDetector.suspect(member.address()); suspectedMembersSchedule.get(member.id(), new ComputableSuspectedMembersSchedule()); break; case TRUSTED: ScheduledFuture<?> future = suspectedMembersSchedule.remove(member.id()); if (future == null || future.cancel(true)) { failureDetector.trust(member.address()); } break; case SHUTDOWN: executor.schedule(new Runnable() { @Override public void run() { LOGGER.debug("Time to remove SHUTDOWN member={} from membership table", member.address()); membership.remove(member.id()); } }, maxShutdownTime, TimeUnit.MILLISECONDS); break; default: } } }
Source:
<code><START> private String generateData(){ <END> StringBuilder data = new StringBuilder(); for(int i =0; i< 200; i++) { String uuid = UUID.randomUUID().toString(); Random random = new Random(); int value = random.nextInt(50); data.append(uuid).append(":").append(Integer.toString(value)).append("_"); } return StringUtils.chop(data.toString()); }</code><technical_language>I reuse this logic: <LINK_0></technical_language>

Target:
private String generateData() { StringBuilder data = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 200; i++) { String uuid = RandomStringUtils.randomAlphanumeric(10); int value = random.nextInt(50); data.append(uuid).append(":").append(value).append("_"); } return StringUtils.chop(data.toString()); }
Source:
<code>public Builder(HttpResponse response) { this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); try { InputStream inputStream = response.getContent(); if (inputStream != null) { <START> content = ByteStreams.toByteArray(response.getContent()); <END> } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } StringBuilder builder = computeMessageBuffer(response); if (content != null) { try { charset = response.getContentCharset(); String strContent = getContent(); if (strContent != null) { builder.append(StringUtils.LINE_SEPARATOR).append(strContent); } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } } message = builder.toString(); }</code><technical_language>nit: this ByteStreams.toByteArray(inputStream)</technical_language>

Target:
public Builder(HttpResponse response) { this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); try { InputStream inputStream = response.getContent(); if (inputStream != null) { content = ByteStreams.toByteArray(inputStream); } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } StringBuilder builder = computeMessageBuffer(response); if (content != null) { try { charset = response.getContentCharset(); String strContent = getContent(); if (strContent != null) { builder.append(StringUtils.LINE_SEPARATOR).append(strContent); } } catch (IOException exception) { builder .append(StringUtils.LINE_SEPARATOR) .append("Content could not be retrieved") .append(StringUtils.LINE_SEPARATOR) .append(exception.getMessage()); } catch (IllegalArgumentException exception) { builder .append(StringUtils.LINE_SEPARATOR) .append("Content could not be retrieved") .append(StringUtils.LINE_SEPARATOR) .append(exception.getMessage()); } } message = builder.toString(); }
Source:
<code>public static CharSequence getRelativeDateTimeString ( Context c, long time, long minResolution, long transitionResolution, int flags ){ CharSequence dateString = ""; if (time > System.currentTimeMillis()){ return DisplayUtils.unixTimeToHumanReadable(time); } else if ((System.currentTimeMillis() - time) < 60 * 1000) { return c.getString(R.string.file_list_seconds_ago); } else { if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB && (System.currentTimeMillis() - time) > 24 * 60 * 60 * 1000 ) { Date date = new Date(time); date.setHours(0); date.setMinutes(0); date.setSeconds(0); dateString = DateUtils.getRelativeDateTimeString( c, date.getTime(), minResolution, transitionResolution, flags ); } else { dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags); } } String[] parts = dateString.toString().split(","); if (parts.length == 2) { if(parts[0].contains(":") && !parts[1].contains(":")) { return parts[1]; } else if(parts[1].contains(":") && !parts[0].contains(":")) { return parts[0]; <START> } <END> } return DisplayUtils.unixTimeToHumanReadable(time); }</code><technical_language>else if branch is expected executed of times. Swapping if else if branches bring a tiny performance increase. (It is contains marginal logic operators less, this code is executed for _every_ file in current directory...)</technical_language>

Target:
public static CharSequence getRelativeDateTimeString ( Context c, long time, long minResolution, long transitionResolution, int flags ){ CharSequence dateString = ""; if (time > System.currentTimeMillis()){ return DisplayUtils.unixTimeToHumanReadable(time); } else if ((System.currentTimeMillis() - time) < 60 * 1000) { return c.getString(R.string.file_list_seconds_ago); } else { dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags); } String[] parts = dateString.toString().split(","); if (parts.length == 2) { if (parts[1].contains(":") && !parts[0].contains(":")) { return parts[0]; } else if (parts[0].contains(":") && !parts[1].contains(":")) { return parts[1]; } } return dateString.toString(); }
Source:
<code>public String removeProtocol(String hdfsUrl) { String newUrl = hdfsUrl.replaceAll("/$", ""); if (newUrl.startsWith("hdfs://")) { return "/" + newUrl.replaceAll("^hdfs://", "").split("/", 2)[1]; } else <START> return newUrl; <END> }</code><technical_language>Please, code [project style guide](<LINK_0></technical_language>

Target:
public String removeProtocol(String hdfsUrl) { String newUrl = hdfsUrl.replaceAll("/$", ""); if (newUrl.startsWith("hdfs://")) { return "/" + newUrl.replaceAll("^hdfs://", "").split("/", 2)[1]; } else { return newUrl; } }
Source:
<code>public String toString() { <START> if (parent != null && parent.getResource() instanceof IProject) { <END> return resource.getProjectRelativePath().toString(); } return resource.getName(); }</code><technical_language>style nit: braces</technical_language>

Target:
public String toString() { if (parent != null && parent.getResource() instanceof IProject) return resource.getProjectRelativePath().toString(); return resource.getName(); }
Source:
<code>public void peekOneMessage() { final int numberOfEvents = 1; String connectionString = System.getenv("AZURE_SERVICEBUS_CONNECTION_STRING") + ";EntityPath=hemant-test1"; log(connectionString); ServiceBusReceiverAsyncClient queueReceiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .scheduler(Schedulers.parallel()) .buildAsyncReceiverClient(); queueReceiverAsyncClient.peek() .doOnNext(receivedMessage -> { System.out.println("!!!!!! doOnNext Got message from queue: " + receivedMessage.getBodyAsString()); }) .subscribe(receivedMessage -> { System.out.println("!!!!!! subscribe Got message from queue: " + receivedMessage.getBodyAsString()); }, error -> { System.err.println("!!!!!! Error occurred while consuming messages: " + error); }); try { <START> Thread.sleep(90000); <END> } catch (Exception ex) { } System.out.println("!!!!!! Completed."); }</code><technical_language>Move tests stepverifier</technical_language>

Target:
public void peekOneMessage() { final int numberOfEvents = 1; StepVerifier.create(consumer.peek()) .then(() -> sendMessages(numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, times(1)); }
Source:
<code>private static OsObjectSchemaInfo createExpectedObjectSchemaInfo() { OsObjectSchemaInfo info = new OsObjectSchemaInfo("AllTypes");; info.add("columnString", RealmFieldType.STRING, Property.PRIMARY_KEY, Property.INDEXED, !Property.REQUIRED); info.add("columnLong", RealmFieldType.INTEGER, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); info.add("columnFloat", RealmFieldType.FLOAT, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); info.add("columnDouble", RealmFieldType.DOUBLE, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); info.add("columnBoolean", RealmFieldType.BOOLEAN, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); info.add("columnDate", RealmFieldType.DATE, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); info.add("columnBinary", RealmFieldType.BINARY, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); <START> info.add("columnObject", RealmFieldType.OBJECT, "AllTypes"); <END> info.add("columnRealmList", RealmFieldType.LIST, "AllTypes"); return info; }</code><technical_language>overloads a bit dangerous me. addField addLink sense</technical_language>

Target:
private static OsObjectSchemaInfo createExpectedObjectSchemaInfo() { OsObjectSchemaInfo.Builder builder = new OsObjectSchemaInfo.Builder("AllTypes"); builder.addProperty("columnString", RealmFieldType.STRING, Property.PRIMARY_KEY, Property.INDEXED, !Property.REQUIRED); builder.addProperty("columnLong", RealmFieldType.INTEGER, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); builder.addProperty("columnFloat", RealmFieldType.FLOAT, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); builder.addProperty("columnDouble", RealmFieldType.DOUBLE, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); builder.addProperty("columnBoolean", RealmFieldType.BOOLEAN, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); builder.addProperty("columnDate", RealmFieldType.DATE, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); builder.addProperty("columnBinary", RealmFieldType.BINARY, !Property.PRIMARY_KEY, !Property.INDEXED, Property.REQUIRED); builder.addLinkedProperty("columnObject", RealmFieldType.OBJECT, "AllTypes"); builder.addLinkedProperty("columnRealmList", RealmFieldType.LIST, "AllTypes"); return builder.build(); }
Source:
<code>public void perform(Run build, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { TestResultAction action = parseAndAttach(this, null, build, workspace, launcher, listener); if (action != null && action.getResult().getFailCount() > 0) build.setResult(Result.UNSTABLE); <START> listener.getLogger().println(Messages.JUnitResultArchiver_ChangeState("UNSTABLE")); <END> }</code><technical_language>I conditional need braces this is considered of block execute, intent due indentation. If want execute, update indentation reflect that</technical_language>

Target:
public void perform(Run build, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { TestResultAction action = parseAndAttach(this, null, build, workspace, launcher, listener); if ((action != null) && (action.getResult().getFailCount() > 0)) build.setResult(Result.UNSTABLE); listener.getLogger().println(Messages.JUnitResultArchiver_ChangeState("UNSTABLE")); }
Source:
<code>public void clearContainer(String container, ListContainerOptions options) { filesystemContainerNameValidator.validate(container); String optsPrefix; optsPrefix = options.getDir() == null ? options.getPrefix() : options.getDir(); optsPrefix = optsPrefix == null ? "" : optsPrefix; String normalizedOptsPath = normalize(optsPrefix); String basePath = buildPathStartingFromBaseDir(container, normalizedOptsPath); filesystemBlobKeyValidator.validate(basePath); try { File object = new File(basePath); if (object.isFile()) { delete(object); } <START> else if (object.isDirectory() & (optsPrefix.endsWith(File.separator) | isNullOrEmpty(optsPrefix))) { <END> File containerFile = openFolder(container + File.separator + normalizedOptsPath); File[] children = containerFile.listFiles(); if (null != children) { for (File child : children) { if (options.isRecursive()) { Utils.deleteRecursively(child); } else { if (child.isFile()) { Utils.delete(child); } } } } if (!isNullOrEmpty(optsPrefix)) { if (options.isRecursive()) { deleteDirectory(container, optsPrefix); } removeDirectoriesTreeOfBlobKey(container, optsPrefix); } } } catch (IOException e) { logger.error(e, "An error occurred while clearing container %s", container); Throwables.propagate(e); } }</code><technical_language>Prefer short-circuit boolean && ||</technical_language>

Target:
public void clearContainer(String container, ListContainerOptions options) { filesystemContainerNameValidator.validate(container); checkArgument((options.getDir() == null) || (options.getPrefix() == null), "cannot specify both directory and prefix"); String optsPrefix; optsPrefix = options.getDir() == null ? options.getPrefix() : options.getDir(); optsPrefix = Strings.nullToEmpty(optsPrefix); String normalizedOptsPath = normalize(optsPrefix); String basePath = buildPathStartingFromBaseDir(container, normalizedOptsPath); filesystemBlobKeyValidator.validate(basePath); try { File object = new File(basePath); if (object.isFile()) { delete(object); } else if (object.isDirectory() && (optsPrefix.endsWith(File.separator) || isNullOrEmpty(optsPrefix))) { File containerFile = openFolder(container + File.separator + normalizedOptsPath); File[] children = containerFile.listFiles(); if (null != children) { for (File child : children) { if (options.isRecursive()) { Utils.deleteRecursively(child); } else { if (child.isFile()) { Utils.delete(child); } } } } if (!optsPrefix.isEmpty()) { if (options.isRecursive()) { deleteDirectory(container, optsPrefix); } removeDirectoriesTreeOfBlobKey(container, optsPrefix); } } } catch (IOException e) { logger.error(e, "An error occurred while clearing container %s", container); Throwables.propagate(e); } }
Source:
<code>public void addChildrenCounts(List<BriefObjectMetadata> containers, AccessGroupSet principals, String countKey, SolrQuery baseQuery) { Assert.notNull(containers); if (containers.size() == 0) { return; } log.debug("Adding child counts of type to result list", countKey); SolrQuery solrQuery; if (baseQuery == null) { solrQuery = createBaseQuery(principals); } else { solrQuery = baseQuery.getCopy(); solrQuery.setRows(0); <START> if (solrQuery.getFacetFields() != null) { <END> for (String facetField : solrQuery.getFacetFields()) { solrQuery.removeFacetField(facetField); } } } String ancestorPathField = solrField(ANCESTOR_PATH); solrQuery.setFacetMinCount(1); solrQuery.addFacetField(ancestorPathField); solrQuery.add("f." + ancestorPathField + ".facet.limit", Integer.toString(Integer.MAX_VALUE)); solrQuery.setFacetSort("index"); try { QueryResponse queryResponse = this.executeQuery(solrQuery); assignChildrenCounts(queryResponse.getFacetField(ancestorPathField), containers, countKey); } catch (SolrServerException e) { throw new SolrRuntimeException(e); } }</code><technical_language>store result of solrQuery.getFacetFields() in a variable avoid repeated calls</technical_language>

Target:
public void addChildrenCounts(List<BriefObjectMetadata> containers, AccessGroupSet principals, String countKey, SolrQuery baseQuery) { Assert.notNull(containers); if (containers.size() == 0) { return; } log.debug("Adding child counts of type to result list", countKey); SolrQuery solrQuery; if (baseQuery == null) { solrQuery = createBaseQuery(principals); } else { solrQuery = baseQuery.getCopy(); solrQuery.setRows(0); String[] facetFields = solrQuery.getFacetFields(); if (facetFields != null) { for (String facetField : facetFields) { solrQuery.removeFacetField(facetField); } } } String ancestorPathField = solrField(ANCESTOR_PATH); solrQuery.setFacetMinCount(1); solrQuery.addFacetField(ancestorPathField); solrQuery.add("f." + ancestorPathField + ".facet.limit", Integer.toString(Integer.MAX_VALUE)); solrQuery.setFacetSort("index"); try { QueryResponse queryResponse = this.executeQuery(solrQuery); assignChildrenCounts(queryResponse.getFacetField(ancestorPathField), containers, countKey); } catch (SolrServerException e) { throw new SolrRuntimeException(e); } }
Source:
<code>public String getOffsetsStorage() { <START> return getStringLastValue("kafka.offsets.storage", "zookeeper"); <END> }</code><technical_language>default in property file</technical_language>

Target:
public String getOffsetsStorage() { return getString("kafka.offsets.storage"); }
Source:
<code>public void setLives(int l) { lives = l; <START> addToLog("The player's current amount of lives is now: " + lives); <END> }</code><technical_language>Please, logger format of: [CLASS_NAME]\t[Additional Note if applicable]\t<"Message"> In other words add: [PLAYER]\t front of String. <naming,organisation</technical_language>

Target:
public void setLives(int l) { lives = l; addToLog("[PLAYER]\t Player's current amount of lives is now: " + lives); }
Source:
<code>private void initViewModel() { mFloatingActionButton = findViewById(R.id.fab_button); mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WPMainActivityViewModel.class); if (BuildConfig.INFORMATION_ARCHITECTURE_AVAILABLE) { mViewModel.getShowMainActionFab().observe(this, shouldShow -> { if (shouldShow) { mFloatingActionButton.show(); } else { mFloatingActionButton.hide(); } }); mViewModel.getCreateAction().observe(this, createAction -> { switch (createAction) { case CREATE_NEW_POST: handleNewPostAction(PagePostCreationSourcesDetail.POST_FROM_MY_SITE); break; case CREATE_NEW_PAGE: handleNewPageAction(PagePostCreationSourcesDetail.PAGE_FROM_MY_SITE); break; } }); mFloatingActionButton.setOnClickListener(v -> { MainBottomSheetFragment bottomSheet = new MainBottomSheetFragment(); bottomSheet.show(getSupportFragmentManager(), MAIN_BOTTOM_SHEET_TAG); mViewModel.setIsBottomSheetShowing(true); }); mViewModel.isBottomSheetShowing().observe(this, isShowing -> { if (!isShowing) { FragmentManager fm = getSupportFragmentManager(); if (fm != null) { MainBottomSheetFragment bottomSheet = (MainBottomSheetFragment) fm.findFragmentByTag(MAIN_BOTTOM_SHEET_TAG); <START> if (bottomSheet != null) { <END> bottomSheet.dismiss(); } } } }); } mViewModel.start(mBottomNav.getCurrentSelectedPage() == PageType.MY_SITE); }</code><technical_language>do moving construction of fragment here? logic like: if (isShowing && bottomSheet == null) { MainBottomSheetFragment bottomSheet = new MainBottomSheetFragment(); bottomSheet.show(getSupportFragmentManager(), MAIN_BOTTOM_SHEET_TAG); } else if (!isShowing && bottomSheet != null) { bottomSheet.dismiss(); } this mFloatingActionButton.setOnClickListener simple (just mViewModel.setIsBottomSheetShowing(true);</technical_language>

Target:
private void initViewModel() { mFloatingActionButton = findViewById(R.id.fab_button); mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(WPMainActivityViewModel.class); if (BuildConfig.INFORMATION_ARCHITECTURE_AVAILABLE) { mViewModel.getShowMainActionFab().observe(this, shouldShow -> { if (shouldShow) { mFloatingActionButton.show(); } else { mFloatingActionButton.hide(); } }); mViewModel.getCreateAction().observe(this, createAction -> { switch (createAction) { case CREATE_NEW_POST: handleNewPostAction(PagePostCreationSourcesDetail.POST_FROM_MY_SITE); break; case CREATE_NEW_PAGE: handleNewPageAction(PagePostCreationSourcesDetail.PAGE_FROM_MY_SITE); break; } }); mFloatingActionButton.setOnClickListener(v -> { mViewModel.setIsBottomSheetShowing(true); }); mViewModel.isBottomSheetShowing().observe(this, isShowing -> { FragmentManager fm = getSupportFragmentManager(); if (fm != null) { MainBottomSheetFragment bottomSheet = (MainBottomSheetFragment) fm.findFragmentByTag(MAIN_BOTTOM_SHEET_TAG); if (isShowing && bottomSheet == null) { bottomSheet = new MainBottomSheetFragment(); bottomSheet.show(getSupportFragmentManager(), MAIN_BOTTOM_SHEET_TAG); } else if (!isShowing && bottomSheet != null) { bottomSheet.dismiss(); } } }); } mViewModel.start(mBottomNav.getCurrentSelectedPage() == PageType.MY_SITE); }