auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldSetMongoPrefsOnScanResult() throws Exception { SharedPreferences sharedPrefs = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext()); <START> String mongoUri = "mongodb://user:pass@test.com/cgm_data"; <END> String mongoCollection = "cgm_data"; String deviceStatusCollection = "devicestatus"; JSONObject json = new JSONObject(); JSONObject child = new JSONObject(); child.put(NSBarcodeConfigKeys.MONGO_URI,mongoUri); child.put(NSBarcodeConfigKeys.MONGO_COLLECTION, mongoCollection); child.put(NSBarcodeConfigKeys.MONGO_DEVICE_STATUS_COLLECTION,deviceStatusCollection); json.put(NSBarcodeConfigKeys.MONGO_CONFIG,child); System.out.println(json.toString()); Intent intent = createFakeScanIntent(json.toString()); new SettingsActivity().onActivityResult(IntentIntegrator.REQUEST_CODE,Activity.RESULT_OK, intent); assertThat(sharedPrefs.getBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED,false),is(true)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_URI,null),is(mongoUri)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_COLLECTION,null),is(mongoCollection)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_DEVICE_STATUS_COLLECTION,null),is(deviceStatusCollection)); assertThat(sharedPrefs.getBoolean(PreferenceKeys.API_UPLOADER_ENABLED,true),is(false)); }</code><technical_language>easier hardcode entire json string, pass createFakeScanIntent</technical_language>

Target:
public void shouldSetMongoPrefsOnScanResult() throws Exception { String mongoUri = "mongodb://user:pass@test.com/cgm_data"; String mongoCollection = "cgm_data"; String deviceStatusCollection = "devicestatus"; JSONObject json = new JSONObject(); JSONObject child = new JSONObject(); child.put(NSBarcodeConfigKeys.MONGO_URI, mongoUri); child.put(NSBarcodeConfigKeys.MONGO_COLLECTION, mongoCollection); child.put(NSBarcodeConfigKeys.MONGO_DEVICE_STATUS_COLLECTION, deviceStatusCollection); json.put(NSBarcodeConfigKeys.MONGO_CONFIG,child); System.out.println(json.toString()); Intent intent = createFakeScanIntent(json.toString()); new SettingsActivity().onActivityResult(IntentIntegrator.REQUEST_CODE, Activity.RESULT_OK, intent); assertThat(sharedPrefs.getBoolean(PreferenceKeys.MONGO_UPLOADER_ENABLED, false), is(true)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_URI, null), is(mongoUri)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_COLLECTION, null), is(mongoCollection)); assertThat(sharedPrefs.getString(PreferenceKeys.MONGO_DEVICE_STATUS_COLLECTION, null), is(deviceStatusCollection)); assertThat(sharedPrefs.getBoolean(PreferenceKeys.API_UPLOADER_ENABLED, true), is(false)); }
Source:
<code>public void testCaseWithBoundaryTimerFiredAtStage() throws InterruptedException { ByteArrayOutputStream outContent = new ByteArrayOutputStream(); PrintStream originalOut = System.out; System.setOut(new PrintStream(outContent)); String caseId = caseService.startCase(deploymentUnit.getIdentifier(), "CaseWithBoundaryTimerStage"); assertNotNull(caseId); assertEquals(FIRST_CASE_ID, caseId); <START> Thread.sleep(3000); <END> try { Collection<CaseStageInstance> stages = caseRuntimeDataService.getCaseInstanceStages(caseId, false, null); assertThat(stages).isNotNull().hasSize(2); Iterator<CaseStageInstance> iterator = stages.iterator(); CaseStageInstance stage1 = iterator.next(); assertThat(stage1.getName()).isEqualTo("Stage 1"); assertThat(stage1.getStatus()).isEqualTo(StageStatus.Completed); CaseStageInstance stage2 = iterator.next(); assertThat(stage2.getName()).isEqualTo("Stage 2"); assertThat(stage2.getStatus()).isEqualTo(StageStatus.Active); assertThat(outContent.toString(), containsString("timer on stage")); assertThat(outContent.toString(), containsString("timer on task")); caseService.cancelCase(caseId); CaseInstance instance = caseService.getCaseInstance(caseId); assertThat(instance.getStatus()).isEqualTo(CaseStatus.CANCELLED.getId()); caseId = null; } catch (Exception e) { logger.error("Unexpected error {}", e.getMessage(), e); fail("Unexpected exception " + e.getMessage()); } finally { if (caseId != null) { caseService.cancelCase(caseId); } System.setOut(originalOut); } }</code><technical_language>event listeners countdown latch instead of thread sleep. other timer related tests</technical_language>

Target:
public void testCaseWithBoundaryTimerFiredAtStage() throws InterruptedException { String caseId = caseService.startCase(deploymentUnit.getIdentifier(), "CaseWithBoundaryTimerStage"); assertNotNull(caseId); assertEquals(FIRST_CASE_ID, caseId); ((NodeLeftCountDownProcessEventListener) CountDownListenerFactory.getExisting(getClass().getSimpleName() + "2")).waitTillCompleted(); try { Collection<CaseStageInstance> stages = caseRuntimeDataService.getCaseInstanceStages(caseId, false, null); assertThat(stages).isNotNull().hasSize(2); Iterator<CaseStageInstance> iterator = stages.iterator(); CaseStageInstance stage1 = iterator.next(); assertThat(stage1.getName()).isEqualTo("Stage 1"); assertThat(stage1.getStatus()).isEqualTo(StageStatus.Completed); CaseStageInstance stage2 = iterator.next(); assertThat(stage2.getName()).isEqualTo("Stage 2"); assertThat(stage2.getStatus()).isEqualTo(StageStatus.Active); caseService.cancelCase(caseId); CaseInstance instance = caseService.getCaseInstance(caseId); assertThat(instance.getStatus()).isEqualTo(CaseStatus.CANCELLED.getId()); caseId = null; } catch (Exception e) { logger.error("Unexpected error {}", e.getMessage(), e); fail("Unexpected exception " + e.getMessage()); } finally { if (caseId != null) { caseService.cancelCase(caseId); } } }
Source:
<code>public <T extends Entity> T spawn(Location location, Class<T> clazz) throws IllegalArgumentException { if (location == null || clazz == null) { throw new IllegalArgumentException("Location or entity class cannot be null"); } Entity entity = null; Class<? extends GlowEntity> entityClass = ENTITY_REGISTRY.get(clazz); try { entity = entityClass.getConstructor(Location.class).newInstance(location); } catch (Exception e) { e.printStackTrace(); } if (entity != null) { return (T) entity; } <START> throw new IllegalArgumentException("Cannot spawn an entity for " + clazz.getName()); <END> }</code><technical_language>I feel this of catch including e a cause</technical_language>

Target:
public <T extends Entity> T spawn(Location location, Class<T> clazz) throws IllegalArgumentException { if (location == null || clazz == null) { throw new IllegalArgumentException("Location or entity class cannot be null"); } Entity entity = null; Class<? extends GlowEntity> entityClass = ENTITY_REGISTRY.get(clazz); try { entity = entityClass.getConstructor(Location.class).newInstance(location); } catch (Exception e) { throw new IllegalArgumentException("Cannot spawn an entity for " + clazz.getName(), e); } return (T) entity; }
Source:
<code>protected boolean checkIfCpusSameManufacture(Cluster group) { <START> if (!cpuFlagsManagerHandler.checkIfCpusExist(group.getCpuName(), <END> getParameters().getCluster().getCompatibilityVersion())) { return true; } return cpuFlagsManagerHandler.checkIfCpusSameManufacture(group.getCpuName(), getCluster().getCpuName(), getCluster().getCompatibilityVersion()); }</code><technical_language>check getCluster().getCpuName() too</technical_language>

Target:
protected boolean checkIfCpusSameManufacture(Cluster group) { if (!cpuFlagsManagerHandler.checkIfCpusExist(group.getCpuName(), getParameters().getCluster().getCompatibilityVersion()) || !cpuFlagsManagerHandler.checkIfCpusExist(getCluster().getCpuName(), getParameters().getCluster().getCompatibilityVersion())) { return true; } return cpuFlagsManagerHandler.checkIfCpusSameManufacture(group.getCpuName(), getCluster().getCpuName(), getCluster().getCompatibilityVersion()); }
Source:
<code>public static void printStateGraph(PrintWriter pw, boolean breakStateName) throws XmppStringprepException { ModularXmppClientToServerConnectionConfiguration.Builder configurationBuilder = ModularXmppClientToServerConnectionConfiguration.builder() .setUsernameAndPassword("user", "password") .setXmppDomain("example.org") <START> .removeModule(XmppWebsocketTransportModuleDescriptor.class); <END> ModularXmppClientToServerConnectionConfiguration configuration = configurationBuilder.build(); configuration.printStateGraphInDotFormat(pw, breakStateName); pw.flush(); }</code><technical_language>This method output complete state graph produced connection modules Smack</technical_language>

Target:
public static void printStateGraph(PrintWriter pw, boolean breakStateName) throws XmppStringprepException { ModularXmppClientToServerConnectionConfiguration.Builder configurationBuilder = ModularXmppClientToServerConnectionConfiguration.builder() .setUsernameAndPassword("user", "password") .setXmppDomain("example.org"); ModularXmppClientToServerConnectionConfiguration configuration = configurationBuilder.build(); configuration.printStateGraphInDotFormat(pw, breakStateName); pw.flush(); }
Source:
<code>public void handleEvent(ITmfEvent event, Map<String, TmfXmlTest> transitionMap) { if (!validatePreconditions(event, transitionMap)) { return; } <START> for (TmfXmlScenario scenario : fNewScenariosList) { <END> fActiveScenariosList.add(scenario); } for (Iterator<TmfXmlScenario> currentItr = fActiveScenariosList.iterator(); currentItr.hasNext();) { TmfXmlScenario scenario = currentItr.next(); if (!scenario.isActive()) { currentItr.remove(); } else { handleScenario(scenario, event); } } fNewScenariosList.clear(); }</code><technical_language>need fNewScnariosList</technical_language>

Target:
public void handleEvent(ITmfEvent event, Map<String, TmfXmlTest> transitionMap) { if (!validatePreconditions(event, transitionMap)) { return; } for (Iterator<TmfXmlScenario> currentItr = fActiveScenariosList.iterator(); currentItr.hasNext();) { TmfXmlScenario scenario = currentItr.next(); if (!scenario.isActive()) { currentItr.remove(); } else { handleScenario(scenario, event); } } }
Source:
<code>public void setWorld(World p_70029_1_) { Log.warn("Ender IO Farming station fake player is being transfered to world '" + p_70029_1_ + "'. Trying to reject transfer. Call stack follows:"); <START> (new Exception()).printStackTrace(); <END> }</code><technical_language>Heh, I read source, more principle, no? :P</technical_language>

Target:
public void setWorld(World p_70029_1_) { Log.warn("Ender IO Farming station fake player is being transfered to world '" + p_70029_1_ + "'. Trying to reject transfer. Call stack follows:"); Thread.dumpStack(); }
Source:
<code>private static boolean mayHaveValidDate(final String value) { List<String> matches = fetchDateStrings(value); if (!matches.isEmpty()) { try { DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM-dd"); matches.forEach(dateTimeFormat::parseStrict); <START> } catch (Exception e) { <END> return false; } } return true; }</code><technical_language>I understand key point is of DateTimeFormat.parseStrict method. calling it, if execptoin occurs, assume date is valid. more specific exception type catched this assumption - sense assuming "generic" exception occurs is due date is valid (eg: leap days)? Is other Exception subtype for catch block instead? brainstorming, asking :)</technical_language>

Target:
private static boolean mayHaveValidDate(final String value) { List<String> matches = fetchDateStrings(value); if (!matches.isEmpty()) { try { DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM-dd"); matches.forEach(dateTimeFormat::parseStrict); } catch (IllegalArgumentException e) { return false; } } return true; }
Source:
<code><START> public static String getTracingInfoFormat(HttpRequest request) { <END> return getHeaderString(request, RESTEasyTracing.HEADER_ACCEPT_FORMAT); }</code><technical_language>This package protected instead of public</technical_language>

Target:
protected static String getTracingInfoFormat(HttpRequest request) { return getHeaderString(request, RESTEasyTracing.HEADER_ACCEPT_FORMAT); }
Source:
<code>public CloseableIterator<InputRow> read() throws IOException { final CloseableIterator<T> intermediateRowIterator = intermediateRowIterator(); return new CloseableIterator<InputRow>() { Iterator<InputRow> rows = null; @Override public boolean hasNext() { if (rows == null || !rows.hasNext()) { if (!intermediateRowIterator.hasNext()) { return false; } final T row = intermediateRowIterator.next(); try { rows = parseInputRows(row).iterator(); } catch (IOException e) { throw new ParseException(e, "Unable to parse row [%s]", row); } } <START> return rows.hasNext() || intermediateRowIterator.hasNext(); <END> } @Override public InputRow next() { if (!hasNext()) { throw new NoSuchElementException(); } return rows.next(); } @Override public void close() throws IOException { intermediateRowIterator.close(); } }; }</code><technical_language>I rows a next this point in code</technical_language>

Target:
public CloseableIterator<InputRow> read() throws IOException { final CloseableIterator<T> intermediateRowIterator = intermediateRowIterator(); return new CloseableIterator<InputRow>() { Iterator<InputRow> rows = null; @Override public boolean hasNext() { if (rows == null || !rows.hasNext()) { if (!intermediateRowIterator.hasNext()) { return false; } final T row = intermediateRowIterator.next(); try { rows = parseInputRows(row).iterator(); } catch (IOException e) { rows = new ExceptionThrowingIterator(new ParseException(e, "Unable to parse row [%s]", row)); } catch (ParseException e) { rows = new ExceptionThrowingIterator(e); } } return true; } @Override public InputRow next() { if (!hasNext()) { throw new NoSuchElementException(); } return rows.next(); } @Override public void close() throws IOException { intermediateRowIterator.close(); } }; }
Source:
<code>public KeyMaterialFactory newKeyMaterialFactory(final URL endpoint, @Nonnull VirtualChannel target) throws InterruptedException, IOException { target.call(new Callable<Void, IOException>() { @Override public Void call() throws IOException { JSONObject json; JSONObject auths; synchronized (DockerRegistryToken.class) { File config = new File(System.getProperty("user.home"), ".docker/config.json"); if (config.exists()) { json = JSONObject.fromObject(FileUtils.readFileToString(config, "UTF-8")); auths = json.getJSONObject("auths"); } else { File dockercfg = new File(System.getProperty("user.home"), ".dockercfg"); <START> config = dockercfg; <END> if (dockercfg.exists()) { auths = json = JSONObject.fromObject(FileUtils.readFileToString(dockercfg, "UTF-8")); } else { auths = json = new JSONObject(); } } auths.put(endpoint.toString(), new JSONObject() .accumulate("auth", getToken()) .accumulate("email", getEmail())); FileUtils.writeStringToFile(config, json.toString(2), "UTF-8"); } return null; } }); return KeyMaterialFactory.NULL; }</code><technical_language>fully remove dockercfg variable</technical_language>

Target:
public KeyMaterialFactory newKeyMaterialFactory(final URL endpoint, @Nonnull VirtualChannel target) throws InterruptedException, IOException { target.call(new Callable<Void, IOException>() { @Override public Void call() throws IOException { JSONObject json; JSONObject auths; synchronized (DockerRegistryToken.class) { File config = new File(System.getProperty("user.home"), ".docker/config.json"); if (config.exists()) { json = JSONObject.fromObject(FileUtils.readFileToString(config, "UTF-8")); auths = json.getJSONObject("auths"); } else { config = new File(System.getProperty("user.home"), ".dockercfg"); if (config.exists()) { auths = json = JSONObject.fromObject(FileUtils.readFileToString(config, "UTF-8")); } else { auths = json = new JSONObject(); } } auths.put(endpoint.toString(), new JSONObject() .accumulate("auth", getToken()) .accumulate("email", getEmail())); FileUtils.writeStringToFile(config, json.toString(2), "UTF-8"); } return null; } }); return KeyMaterialFactory.NULL; }
Source:
<code>public MISTCepQuery<T> build() { <START> return new MISTCepQuery(groupId, cepInput, cepEventSequence, cepQualifier, windowTime, cepAction); <END> }</code><technical_language>I guess is necessary check necessary parameters set building it</technical_language>

Target:
public MISTCepQuery<T> build() { if (groupId == null || cepInput == null || cepEventSequence == null || cepQualifier == null || windowTime < 0 || cepAction == null) { throw new IllegalStateException( "One of group id, input, event sequence, qualifier, window, or action is not set!"); } return new MISTCepQuery(groupId, cepInput, cepEventSequence, cepQualifier, windowTime, cepAction); }
Source:
<code>public boolean process(AudioEvent audioEvent) { currentTime = audioEvent.getTimeStamp(); if (transitionTime == 0) { return true; } if (!hasTransitioned && currentTime > transitionTime) { <START> System.out.println(transitionTime); <END> System.out.println("what"); new Thread(transition).start(); hasTransitioned = true; } return true; }</code><technical_language>if this system.out is needed please add a logger, if please remove</technical_language>

Target:
public boolean process(AudioEvent audioEvent) { currentTime = audioEvent.getTimeStamp(); if (transitionTime == 0) { return true; } if (!hasTransitioned && currentTime > transitionTime) { new Thread(transition).start(); hasTransitioned = true; } return true; }
Source:
<code>private boolean isAPSJournal(BibEntry entry, String doiAsString) { if (!entry.getType().equals(StandardEntryType.Article)) { return false; } <START> Pattern apsJournalSuffixPattern = Pattern.compile("([\\w]+\\.)([\\w]+\\.)([\\w]+)"); <END> String suffix = doiAsString.substring(doiAsString.lastIndexOf('/') + 1); return apsJournalSuffixPattern.matcher(suffix).matches(); }</code><technical_language>I thinking if sense check for strig "phys" well? etract Pattern a static string, get advantages</technical_language>

Target:
private boolean isAPSJournal(BibEntry entry, String doiAsString) { if (!entry.getType().equals(StandardEntryType.Article)) { return false; } String suffix = doiAsString.substring(doiAsString.lastIndexOf('/') + 1); String organizationId = doiAsString.substring(doiAsString.indexOf('.') + 1, doiAsString.indexOf('/')); return organizationId.equals(APS_JOURNAL_ORG_DOI_ID) && APS_SUFFIX_PATTERN.matcher(suffix).matches(); }
Source:
<code>private int[][] calculateResponseFrequency(List<FeedbackResponseAttributes> responses, FeedbackRubricQuestionDetails fqd) { int[][] responseFrequency = new int[fqd.numOfRubricSubQuestions][]; <START> int totalNumberPosition = fqd.numOfRubricChoices; <END> for (int i = 0; i < responseFrequency.length; i++) { responseFrequency[i] = new int[fqd.numOfRubricChoices + 1]; for (int j = 0; j < responseFrequency[i].length; j++) { responseFrequency[i][j] = 0; } } for (FeedbackResponseAttributes response : responses) { FeedbackRubricResponseDetails frd = (FeedbackRubricResponseDetails) response.getResponseDetails(); for (int i = 0; i < fqd.numOfRubricSubQuestions; i++) { int chosenChoice = frd.getAnswer(i); if (chosenChoice != -1) { responseFrequency[i][chosenChoice] += 1; responseFrequency[i][totalNumberPosition] += 1; } } } return responseFrequency; }</code><technical_language>responseTotalIndex</technical_language>

Target:
private int[][] calculateResponseFrequency(List<FeedbackResponseAttributes> responses, FeedbackRubricQuestionDetails fqd) { int[][] responseFrequency = new int[fqd.numOfRubricSubQuestions][fqd.numOfRubricChoices + 1]; int responseTotalIndex = fqd.numOfRubricChoices; for (FeedbackResponseAttributes response : responses) { FeedbackRubricResponseDetails frd = (FeedbackRubricResponseDetails) response.getResponseDetails(); for (int i = 0; i < fqd.numOfRubricSubQuestions; i++) { int chosenChoice = frd.getAnswer(i); if (chosenChoice != -1) { responseFrequency[i][chosenChoice] += 1; responseFrequency[i][responseTotalIndex] += 1; } } } return responseFrequency; }
Source:
<code>private ServerConfiguration toServerConfiguration(Node node) { NodeContext nodeContext = nodeContextSupplier.get(); return new ServerConfiguration() { @Override public InetSocketAddress getTsaPort() { return InetSocketAddress.createUnresolved(substitutor.substitute(node.getNodeBindAddress()), node.getNodePort()); } @Override public InetSocketAddress getGroupPort() { return InetSocketAddress.createUnresolved(substitutor.substitute(node.getNodeGroupBindAddress()), node.getNodeGroupPort()); } @Override public String getHost() { return node.getNodeHostname(); } @Override public String getName() { return node.getNodeName(); } @Override public int getClientReconnectWindow() { return nodeContext.getCluster().getClientReconnectWindow().getExactQuantity(TimeUnit.SECONDS).intValueExact(); } <START> public void setClientReconnectWindow(int value) { <END> nodeContext.getCluster().setClientReconnectWindow(value, TimeUnit.SECONDS); } @Override public File getLogsLocation() { String sanitizedNodeName = node.getNodeName().replace(":", "-"); return (unConfigured) ? null : substitutor.substitute(pathResolver.resolve(node.getNodeLogDir().resolve(sanitizedNodeName))).toFile(); } @Override public String toString() { return node.getNodeName() + "@" + node.getNodeAddress(); } }; }</code><technical_language>method removed if anymore in api</technical_language>

Target:
private ServerConfiguration toServerConfiguration(Node node) { NodeContext nodeContext = nodeContextSupplier.get(); return new ServerConfiguration() { @Override public InetSocketAddress getTsaPort() { return InetSocketAddress.createUnresolved(substitutor.substitute(node.getNodeBindAddress()), node.getNodePort()); } @Override public InetSocketAddress getGroupPort() { return InetSocketAddress.createUnresolved(substitutor.substitute(node.getNodeGroupBindAddress()), node.getNodeGroupPort()); } @Override public String getHost() { return node.getNodeHostname(); } @Override public String getName() { return node.getNodeName(); } @Override public int getClientReconnectWindow() { return nodeContext.getCluster().getClientReconnectWindow().getExactQuantity(TimeUnit.SECONDS).intValueExact(); } @Override public File getLogsLocation() { String sanitizedNodeName = node.getNodeName().replace(":", "-"); return (unConfigured) ? null : substitutor.substitute(pathResolver.resolve(node.getNodeLogDir().resolve(sanitizedNodeName))).toFile(); } @Override public String toString() { return node.getNodeName() + "@" + node.getNodeAddress(); } }; }
Source:
<code>public Builder mergeFrom(io.netty.example.worldclock.WorldClockProtocol.LocalTime other) { if (other == io.netty.example.worldclock.WorldClockProtocol.LocalTime.getDefaultInstance()) { <START> return this; <END> } if (other.hasYear()) { setYear(other.getYear()); } if (other.hasMonth()) { setMonth(other.getMonth()); } if (other.hasDayOfMonth()) { setDayOfMonth(other.getDayOfMonth()); } if (other.hasDayOfWeek()) { setDayOfWeek(other.getDayOfWeek()); } if (other.hasHour()) { setHour(other.getHour()); } if (other.hasMinute()) { setMinute(other.getMinute()); } if (other.hasSecond()) { setSecond(other.getSecond()); } this.mergeUnknownFields(other.getUnknownFields()); return this; }</code><technical_language>4 spaces</technical_language>

Target:
public Builder mergeFrom(io.netty.example.worldclock.WorldClockProtocol.LocalTime other) { if (other == io.netty.example.worldclock.WorldClockProtocol.LocalTime.getDefaultInstance()) return this; if (other.hasYear()) { setYear(other.getYear()); } if (other.hasMonth()) { setMonth(other.getMonth()); } if (other.hasDayOfMonth()) { setDayOfMonth(other.getDayOfMonth()); } if (other.hasDayOfWeek()) { setDayOfWeek(other.getDayOfWeek()); } if (other.hasHour()) { setHour(other.getHour()); } if (other.hasMinute()) { setMinute(other.getMinute()); } if (other.hasSecond()) { setSecond(other.getSecond()); } this.mergeUnknownFields(other.getUnknownFields()); return this; }
Source:
<code>public TableViewer <START> createTableViewer(Composite <END> parent, int style, EClass type) { Composite viewerContainer = new Composite(parent, SWT.NONE); TableColumnLayout layout = new TableColumnLayout(); viewerContainer.setLayout(layout); TableViewer tableViewer = new TableViewer(viewerContainer, style); build2(tableViewer, type); return tableViewer; }</code><technical_language>lots of duplicated lines in methods</technical_language>

Target:
public TableViewer createTableViewer(Composite parent, int style, EClass type) { TableViewer tableViewer = internal_createTableViewer(parent, style); build2(tableViewer, type); return tableViewer; }
Source:
<code>public void updateDrawState(TextPaint textPaint) { <START> textPaint.setColor(itemView.getContext().getResources().getColor(R.color.primary)); <END> }</code><technical_language>getContext().getResources() -> getResources()</technical_language>

Target:
public void updateDrawState(TextPaint textPaint) { textPaint.setColor(itemView.getResources().getColor(R.color.primary)); }
Source:
<code>public void testDeleteAccount() { CreateAccount createAccount = new CreateAccount(1); createAccount.exe(); long id = createAccount.getAccountList().get(0).getId(); boolean result = mAccountMapper.deleteAccount(id); <START> assertTrue(result); <END> }</code><technical_language>assert get account null</technical_language>

Target:
public void testDeleteAccount() { CreateAccount createAccount = new CreateAccount(1); createAccount.exe(); long id = createAccount.getAccountList().get(0).getId(); boolean result = mAccountMapper.deleteAccount(id); assertTrue(result); assertNull(mAccountMapper.getAccount(id)); }
Source:
<code>public void testEquals() { String rawText = "some raw text"; int position = 1; List<TypedId> identifiers = Lists.newArrayList(new TypedId("someValue", "someType", 0.9f)); BlobCitationEntry blobCitationEntry = new BlobCitationEntry(rawText); blobCitationEntry.setPosition(position); blobCitationEntry.setIdentifiers(identifiers); <START> assertNotEquals(null, blobCitationEntry); <END> assertNotEquals("string", blobCitationEntry); BlobCitationEntry otherBlobCitationEntry = new BlobCitationEntry("other raw text"); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry, otherBlobCitationEntry); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(2); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry, otherBlobCitationEntry); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(Lists.newArrayList(new TypedId("someOtherValue", "someType", 0.9f))); assertNotEquals(blobCitationEntry, otherBlobCitationEntry); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertEquals(blobCitationEntry, otherBlobCitationEntry); }</code><technical_language>I code previously defined expression I guess simplify this assertNotNull</technical_language>

Target:
public void testEquals() { String rawText = "some raw text"; int position = 1; List<TypedId> identifiers = Lists.newArrayList(new TypedId("someValue", "someType", 0.9f)); BlobCitationEntry blobCitationEntry = new BlobCitationEntry(rawText); blobCitationEntry.setPosition(position); blobCitationEntry.setIdentifiers(identifiers); assertNotNull(blobCitationEntry); assertNotEquals("string", blobCitationEntry); BlobCitationEntry otherBlobCitationEntry = new BlobCitationEntry("other raw text"); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry, otherBlobCitationEntry); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(2); otherBlobCitationEntry.setIdentifiers(identifiers); assertNotEquals(blobCitationEntry, otherBlobCitationEntry); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(Lists.newArrayList(new TypedId("someOtherValue", "someType", 0.9f))); assertNotEquals(blobCitationEntry, otherBlobCitationEntry); otherBlobCitationEntry = new BlobCitationEntry(rawText); otherBlobCitationEntry.setPosition(position); otherBlobCitationEntry.setIdentifiers(identifiers); assertEquals(blobCitationEntry, otherBlobCitationEntry); }
Source:
<code>protected void getCommentsList(@NonNull final InfiniteScrollUtils.PageLoadCallback<DiscussionComment> callback) { if (getCommentsListCall != null) { getCommentsListCall.cancel(); } final List<String> requestedFields = Collections.singletonList( DiscussionRequestFields.PROFILE_IMAGE.getQueryParamValue()); getCommentsListCall = discussionService.getCommentsList( discussionResponse.getIdentifier(), nextPage, requestedFields); getCommentsListCall.enqueue(new ErrorHandlingCallback<Page<DiscussionComment>>( <START> getActivity(), null, new SnackbarErrorNotification(discussionCommentsListView)) { <END> @Override protected void onResponse(@NonNull final Page<DiscussionComment> threadCommentsPage) { ++nextPage; callback.onPageLoaded(threadCommentsPage); discussionCommentsAdapter.notifyDataSetChanged(); hasMorePages = threadCommentsPage.hasNext(); } @Override protected void onFailure(@NonNull final Throwable error) { callback.onError(); nextPage = 1; hasMorePages = false; } }); }</code><technical_language>**Issue:** describe above. I error in case of Offline mode. <img src="<LINK_0>" width="200"> I error i hard codedly throw exception in this call. <img src="<LINK_1>" width="200"> means showing server exception message in snackbar is new design</technical_language>

Target:
protected void getCommentsList(@NonNull final InfiniteScrollUtils.PageLoadCallback<DiscussionComment> callback) { if (getCommentsListCall != null) { getCommentsListCall.cancel(); } final List<String> requestedFields = Collections.singletonList( DiscussionRequestFields.PROFILE_IMAGE.getQueryParamValue()); getCommentsListCall = discussionService.getCommentsList( discussionResponse.getIdentifier(), nextPage, requestedFields); final Activity activity = getActivity(); final TaskMessageCallback mCallback = activity instanceof TaskMessageCallback ? (TaskMessageCallback) activity : null; getCommentsListCall.enqueue(new ErrorHandlingCallback<Page<DiscussionComment>>(activity, null, mCallback, CallTrigger.LOADING_UNCACHED) { @Override protected void onResponse(@NonNull final Page<DiscussionComment> threadCommentsPage) { ++nextPage; callback.onPageLoaded(threadCommentsPage); discussionCommentsAdapter.notifyDataSetChanged(); hasMorePages = threadCommentsPage.hasNext(); } @Override protected void onFailure(@NonNull final Throwable error) { callback.onError(); nextPage = 1; hasMorePages = false; } }); }
Source:
<code>public void removeResourceSelfServiceUser(PerunSession sess, Resource resource, User user) throws InternalErrorException, PrivilegeException, UserNotAdminException { Utils.checkPerunSession(sess); Vo vo; Facility facility; try { facility = sess.getPerun().getFacilitiesManager().getFacilityById(sess, resource.getFacilityId()); } catch (FacilityNotExistsException e) { throw new InternalErrorException("Failed to find facility for given resource."); } try { vo = sess.getPerun().getVosManager().getVoById(sess, resource.getVoId()); } catch (VoNotExistsException e) { throw new InternalErrorException("Failed to find vo for given resource."); } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { <START> throw new PrivilegeException(sess, "addResourceSelfServiceUser"); <END> } getResourcesManagerBl().removeResourceSelfServiceUser(sess, resource, user); }</code><technical_language>parameter "removeResourceSelfServiceUser"</technical_language>

Target:
public void removeResourceSelfServiceUser(PerunSession sess, Resource resource, User user) throws InternalErrorException, PrivilegeException, UserNotAdminException { Utils.checkPerunSession(sess); Vo vo; Facility facility; try { facility = sess.getPerun().getFacilitiesManager().getFacilityById(sess, resource.getFacilityId()); } catch (FacilityNotExistsException e) { throw new InternalErrorException("Failed to find facility for given resource."); } try { vo = sess.getPerun().getVosManager().getVoById(sess, resource.getVoId()); } catch (VoNotExistsException e) { throw new InternalErrorException("Failed to find vo for given resource."); } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) && !AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { throw new PrivilegeException(sess, "removeResourceSelfServiceUser"); } getResourcesManagerBl().removeResourceSelfServiceUser(sess, resource, user); }
Source:
<code>void testRetryService() throws Exception { MockConnectedThriftServiceProvider mockServiceProvider = new MockConnectedThriftServiceProvider(); ThriftConnectorConfig config = new ThriftConnectorConfig() .setMaxRetryAttempts(3) .setMinRetrySleepTime(new Duration(10, MILLISECONDS)) .setMaxRetrySleepTime(new Duration(20, MILLISECONDS)); RetryingPrestoThriftServiceProvider retryingServiceProvider = new RetryingPrestoThriftServiceProvider(mockServiceProvider, retryExecutor, config); <START> mockServiceProvider.setPendingFailuresToGenerate(2); <END> retryingServiceProvider.runOnAnyHost(PrestoThriftService::listSchemaNames); assertEquals(mockServiceProvider.getOpenServiceCount(), 0); }</code><technical_language>move pending failuresToGenerate initialization constructor</technical_language>

Target:
void testRetryService() { TestingConnectedThriftServiceProvider testingServiceProvider = new TestingConnectedThriftServiceProvider(2); ThriftConnectorConfig config = new ThriftConnectorConfig() .setMaxRetryAttempts(3) .setMinRetrySleepTime(new Duration(10, MILLISECONDS)) .setMaxRetrySleepTime(new Duration(20, MILLISECONDS)); RetryingPrestoThriftServiceProvider retryingServiceProvider = new RetryingPrestoThriftServiceProvider(testingServiceProvider, retryExecutor, config); retryingServiceProvider.runOnAnyHost(PrestoThriftService::listSchemaNames); assertEquals(testingServiceProvider.getOpenServiceCount(), 3, "Must open thrift connections for 3 times"); assertEquals(testingServiceProvider.getCloseServiceCount(), 3, "Must close all 3 opened connections"); }
Source:
<code><START> public ChangeVmClusterValidator(VmCommand <END> parentCommand, Guid targetClusterId, Version vmCustomCompatibilityVersion) { this.parentCommand = parentCommand; this.targetClusterId = targetClusterId; this.vmCompatibilityVersion = vmCustomCompatibilityVersion; }</code><technical_language>constructor private protected</technical_language>

Target:
private ChangeVmClusterValidator(VmCommand parentCommand, Guid targetClusterId, Version vmCustomCompatibilityVersion) { this.parentCommand = parentCommand; this.targetClusterId = targetClusterId; this.vmCompatibilityVersion = vmCustomCompatibilityVersion; }
Source:
<code>public void testUnzipInsecureFile() throws IOException { final File zipFile = new File("myTest.zip"); final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); <START> final ZipEntry entry = new ZipEntry("../../../../../evil.txt"); <END> out.putNextEntry(entry); out.close(); final ZipFile source = new ZipFile(zipFile); final File dest = Utils.createTempDir(); assertThatThrownBy(() -> Utils.unzip(source, dest)).isInstanceOf(IOException.class) .hasMessageContaining("Extracting zip entry would have resulted in a file outside the " + "specified destination directory."); }</code><technical_language>Nice. intent is more clear a file in previous version</technical_language>

Target:
public void testUnzipInsecureFile() throws IOException { final File zipFile = new File("myTest.zip"); try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) { final ZipEntry entry = new ZipEntry("../../../../../evil.txt"); out.putNextEntry(entry); } final ZipFile source = new ZipFile(zipFile); final File dest = Utils.createTempDir(); assertThatThrownBy(() -> Utils.unzip(source, dest)).isInstanceOf(IOException.class) .hasMessageContaining("Extracting zip entry would have resulted in a file outside the " + "specified destination directory."); }
Source:
<code>private static void filteringSimpleProbableThreats() { LOGGER.info(" ### Filtering ProbabilisticThreatAwareSystem by probability ###"); <START> ProbableThreat trojanArcBomb = <END> new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99); ProbableThreat rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8); List<ProbableThreat> probableThreats = List.of(trojanArcBomb, rootkit); ProbabilisticThreatAwareSystem probabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("System-1", probableThreats); LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : " + probabilisticThreatAwareSystem); ProbabilisticThreatAwareSystem filtered = probabilisticThreatAwareSystem.filtered() .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); LOGGER.info("Filtered by probability = 0.99 : " + filtered); }</code><technical_language>In cases local variable type inferred context. try var in cases (Java 10 feature). Please check this code</technical_language>

Target:
private static void filteringSimpleProbableThreats() { LOGGER.info(" ### Filtering ProbabilisticThreatAwareSystem by probability ###"); var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99); var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8); List<ProbableThreat> probableThreats = List.of(trojanArcBomb, rootkit); var probabilisticThreatAwareSystem = new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats); LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : " + probabilisticThreatAwareSystem); var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered() .by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0); LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem); }
Source:
<code>protected void executeQueryCommand() { try { VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(VDSCommandType.GetPasswordlessSshStatus, new PasswordlessSshVDSParameters(getParameters().getServerId(), getParameters().getRemoteServerName(), getParameters().getRemoteServerFingerpirnt(), getParameters().getUserName())); getQueryReturnValue().setSucceeded(returnValue.getSucceeded()); if (!returnValue.getSucceeded()) { <START> getQueryReturnValue().setExceptionString(returnValue.getVdsError().getMessage()); <END> } } catch (Exception e) { log.error(e.getMessage()); getQueryReturnValue().setSucceeded(false); getQueryReturnValue().setExceptionString(e.getMessage()); } }</code><technical_language>QueriesCommandBase#ExecuteCommand() logic log failure set exception string if encounters exception. I suggest like: if (!returnValue.getSucceeded()) { throw new VdcBllException(returnValue.getVdsError().getCode(), returnValue.getVdsError().getMessage()) }</technical_language>

Target:
protected void executeQueryCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetPasswordlessSshStatus, new PasswordlessSshVDSParameters(getParameters().getServerId(), getParameters().getRemoteServerName(), getParameters().getRemoteServerFingerpirnt(), getParameters().getUserName())); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); }
Source:
<code>public static void testPutObject(String testTags, PutObjectArgs args, String errorCode) throws Exception { String methodName = "putObject()"; long startTime = System.currentTimeMillis(); ObjectWriteResponse objectInfo = null; try { <START> try { <END> objectInfo = client.putObject(args); } catch (ErrorResponseException e) { if (errorCode == null || !e.errorResponse().code().equals(errorCode)) { throw e; } } if (testTags.equals("[With Retention]")) { client.setObjectRetention( SetObjectRetentionArgs.builder() .bucket(args.bucket()) .object(args.object()) .config(new Retention()) .bypassGovernanceMode(true) .build()); } client.removeObject( RemoveObjectArgs.builder() .bucket(args.bucket()) .object(args.object()) .versionId(objectInfo != null ? objectInfo.versionId() : null) .build()); mintSuccessLog(methodName, testTags, startTime); } catch (Exception e) { handleException(methodName, testTags, startTime, e); } }</code><technical_language>Move ObjectWriteResponse objectInfo = null; here</technical_language>

Target:
public static void testPutObject(String testTags, PutObjectArgs args, String errorCode) throws Exception { String methodName = "putObject()"; long startTime = System.currentTimeMillis(); try { ObjectWriteResponse objectInfo = null; try { objectInfo = client.putObject(args); } catch (ErrorResponseException e) { if (errorCode == null || !e.errorResponse().code().equals(errorCode)) { throw e; } } if (args.retention() != null) { client.setObjectRetention( SetObjectRetentionArgs.builder() .bucket(args.bucket()) .object(args.object()) .config(new Retention()) .bypassGovernanceMode(true) .build()); } client.removeObject( RemoveObjectArgs.builder() .bucket(args.bucket()) .object(args.object()) .versionId(objectInfo != null ? objectInfo.versionId() : null) .build()); mintSuccessLog(methodName, testTags, startTime); } catch (Exception e) { handleException(methodName, testTags, startTime, e); } }
Source:
<code>private void serveCheckComponentName(ResourceRequest request, ResourceResponse response) throws IOException { <START> JSONObject responseJson; <END> List<Component> resultComponents = new ArrayList<>(); List<String> errors = new ArrayList<>(); String cName = request.getParameter(PortalConstants.COMPONENT_NAME); if (cName != null && !cName.isEmpty()) { List<Component> similarComponents = new ArrayList<>(); Map<String, Set<String>> filterMap = new HashMap<>(); Set<String> splittedCName = Sets.newHashSet(cName.split("\\W")); Set<String> splittedExtendedCName = splittedCName.stream().map(v -> v + "*").collect(Collectors.toSet()); try { ComponentService.Iface cClient = thriftClients.makeComponentClient(); filterMap.put(Component._Fields.NAME.getFieldName(), splittedExtendedCName); similarComponents.addAll(cClient.refineSearch(null, filterMap)); filterMap.remove(Component._Fields.NAME.getFieldName()); filterMap.put(Component._Fields.VENDOR_NAMES.getFieldName(), splittedExtendedCName); similarComponents.addAll(cClient.refineSearch(null, filterMap)); resultComponents = similarComponents.stream().distinct().sorted(Comparator.comparing(c -> c.getName())) .collect(Collectors.toList()); } catch (TException e) { log.error("Error getting similar components from backend", e); errors.add(e.getMessage()); } } responseJson = createSimilarComponentsResponseJson(request, resultComponents, errors); writeJSON(request, response, responseJson); }</code><technical_language>if possible, please jackson-databind instead of Liferay's library for generating JSON</technical_language>

Target:
private void serveCheckComponentName(ResourceRequest request, ResourceResponse response) throws IOException { List<Component> resultComponents = new ArrayList<>(); List<String> errors = new ArrayList<>(); String cName = request.getParameter(PortalConstants.COMPONENT_NAME); if (cName != null && !cName.isEmpty()) { List<Component> similarComponents = new ArrayList<>(); Map<String, Set<String>> filterMap = new HashMap<>(); Set<String> splitCName = Sets.newHashSet(cName.split("\\W")); Set<String> splitExtendedCName = splitCName.stream().map(v -> v + "*").collect(Collectors.toSet()); try { ComponentService.Iface cClient = thriftClients.makeComponentClient(); filterMap.put(Component._Fields.NAME.getFieldName(), splitExtendedCName); similarComponents.addAll(cClient.refineSearch(null, filterMap)); filterMap.remove(Component._Fields.NAME.getFieldName()); filterMap.put(Component._Fields.VENDOR_NAMES.getFieldName(), splitExtendedCName); similarComponents.addAll(cClient.refineSearch(null, filterMap)); resultComponents = similarComponents.stream().distinct().sorted(Comparator.comparing(c -> c.getName())) .collect(Collectors.toList()); } catch (TException e) { log.error("Error getting similar components from backend", e); errors.add(e.getMessage()); } } respondSimilarComponentsResponseJson(request, response, resultComponents, errors); }
Source:
<code>public static Text getLittleLight() { return new Text("Hello, Darkness", <START> "You don't have a light on. Good." <END> ); }</code><technical_language>text</technical_language>

Target:
public static Text getLittleLight() { return new Text("Doing well", "Your bedroom is dim at night, which is great for your sleep." ); }
Source:
<code>protected void executeQueryCommand() { VM vm = getVm(); if (vm == null) { return; } <START> VM nextRunVm = vmHandler.getNextRunVmConfiguration(getParameters().getId(), getUserID(), getParameters().isFiltered()); <END> if (nextRunVm != null) { vm.setCustomCompatibilityVersion(nextRunVm.getCustomCompatibilityVersion()); } updateVMDetails(vm); getQueryReturnValue().setReturnValue(vm); }</code><technical_language>customCompatibilityVersion is NEXT_RUN configuration. VmHandler#getNextRunVmConfiguration() load disks, network interfaces etc. pass additional parameter flag load this information</technical_language>

Target:
protected void executeQueryCommand() { VM vm = getVm(); if (vm == null) { return; } VM nextRunVm = vmHandler.getNextRunVmConfiguration(getParameters().getId(), getUserID(), getParameters().isFiltered(), false); if (nextRunVm != null) { vm.setCustomCompatibilityVersion(nextRunVm.getCustomCompatibilityVersion()); } updateVMDetails(vm); getQueryReturnValue().setReturnValue(vm); }
Source:
<code>protected static String getZookeeperQuorum(String url) throws SQLException { int endIndex = url.indexOf(';'); endIndex = endIndex == -1 ? url.length() : endIndex; int begIndex = PhoenixRuntime.EMBEDDED_JDBC_PROTOCOL.length(); if (endIndex > begIndex) { return url.substring(begIndex, endIndex); } <START> throw new SQLExceptionInfo.Builder(SQLExceptionCodeEnum.CANNOT_CONNECT_TO_ZOOKEEPER) <END> .setMessage("connection url: " + url).build().buildException(); }</code><technical_language>Is a standard connection failed sqlstate</technical_language>

Target:
protected static String getZookeeperQuorum(String url) throws SQLException { int endIndex = url.indexOf(';'); endIndex = endIndex == -1 ? url.length() : endIndex; int begIndex = PhoenixRuntime.EMBEDDED_JDBC_PROTOCOL.length(); if (endIndex > begIndex) { return url.substring(begIndex, endIndex); } throw new SQLExceptionInfo.Builder(SQLExceptionCode.MALFORMED_ZOOKEEPER_URL) .setMessage(url).build().buildException(); }