auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected final void init(InputStream myIn, OutputStream myOut) { final int timeout = transport.getTimeout(); if (timeout > 0) { final Thread caller = Thread.currentThread(); <START> if (myTimer != null) { myTimer.terminate(); myTimer = null; } myTimer = new InterruptTimer(caller.getName() + "-Timer"); END> timeoutIn = new TimeoutInputStream(myIn, myTimer); timeoutOut = new TimeoutOutputStream(myOut, myTimer); timeoutIn.setTimeout(timeout * 1000); timeoutOut.setTimeout(timeout * 1000); myIn = timeoutIn; myOut = timeoutOut; } in = myIn; out = myOut; pckIn = new PacketLineIn(in); pckOut = new PacketLineOut(out); outNeedsEnd = true; }</code><technical_language>I do this as: if (myTimer == null) { myTimer = ... } create shutdown a thread for reason. Instead create thread. I in timeout code requires throwing in constructor</technical_language>

Target:
protected final void init(InputStream myIn, OutputStream myOut) { final int timeout = transport.getTimeout(); if (timeout > 0) { final Thread caller = Thread.currentThread(); if (myTimer == null) { myTimer = new InterruptTimer(caller.getName() + "-Timer"); } timeoutIn = new TimeoutInputStream(myIn, myTimer); timeoutOut = new TimeoutOutputStream(myOut, myTimer); timeoutIn.setTimeout(timeout * 1000); timeoutOut.setTimeout(timeout * 1000); myIn = timeoutIn; myOut = timeoutOut; } in = myIn; out = myOut; pckIn = new PacketLineIn(in); pckOut = new PacketLineOut(out); outNeedsEnd = true; }
Source:
<code><START> default public boolean isRememberChoice() { <END> return false; }</code><technical_language>methods public default, need provide modifier</technical_language>

Target:
default boolean isRememberChoice() { return false; }
Source:
<code>public String getEventType() { VirtualMachine vm = _entityMgr.findById(VirtualMachine.class, getId()); <START> if (vm.getType() == VirtualMachine.Type.ConsoleProxy) { <END> return EventTypes.EVENT_PROXY_DIAGNOSTICS; } else if (vm.getType() == VirtualMachine.Type.SecondaryStorageVm){ return EventTypes.EVENT_SSVM_DIAGNOSTICS; } else { return EventTypes.EVENT_ROUTER_DIAGNOSTICS; } }</code><technical_language>a switch case instead of multiple if else, especially for comparing multiple enums</technical_language>

Target:
public String getEventType() { VirtualMachine.Type vmType = _entityMgr.findById(VirtualMachine.class, getId()).getType(); String eventType = ""; switch (vmType) { case ConsoleProxy: eventType = EventTypes.EVENT_PROXY_DIAGNOSTICS; break; case SecondaryStorageVm: eventType = EventTypes.EVENT_SSVM_DIAGNOSTICS; break; case DomainRouter: eventType = EventTypes.EVENT_ROUTER_DIAGNOSTICS; break; } return eventType; }
Source:
<code>private Method findClosestMatch(Object[] args, Class<? extends Throwable> cause) { Method result = null; boolean shouldUseRecoverMethodName = !this.recoverMethodName.equals(""); <START> if (shouldUseRecoverMethodName) { <END> for (Method method : this.methods.keySet()) { if (method.getName().equals(this.recoverMethodName)) { SimpleMetadata meta = this.methods.get(method); if (meta.type.isAssignableFrom(cause) && compareParameters(args, meta.getArgCount(), method.getParameterTypes())) { result = method; break; } } } } else { int min = Integer.MAX_VALUE; for (Method method : this.methods.keySet()) { SimpleMetadata meta = this.methods.get(method); Class<? extends Throwable> type = meta.getType(); if (type == null) { type = Throwable.class; } if (type.isAssignableFrom(cause)) { int distance = calculateDistance(cause, type); if (distance < min) { min = distance; result = method; } else if (distance == min) { boolean parametersMatch = compareParameters(args, meta.getArgCount(), method.getParameterTypes()); if (parametersMatch) { result = method; } } } } } return result; }</code><technical_language>need this variable. StringUtils.isEmpty() is friend in this case</technical_language>

Target:
private Method findClosestMatch(Object[] args, Class<? extends Throwable> cause) { Method result = null; if (StringUtils.isEmpty(recoverMethodName)) { int min = Integer.MAX_VALUE; for (Map.Entry<Method, SimpleMetadata> entry : this.methods.entrySet()) { Method method = entry.getKey(); SimpleMetadata meta = entry.getValue(); Class<? extends Throwable> type = meta.getType(); if (type == null) { type = Throwable.class; } if (type.isAssignableFrom(cause)) { int distance = calculateDistance(cause, type); if (distance < min) { min = distance; result = method; } else if (distance == min) { boolean parametersMatch = compareParameters(args, meta.getArgCount(), method.getParameterTypes()); if (parametersMatch) { result = method; } } } } } else { for (Map.Entry<Method, SimpleMetadata> entry : this.methods.entrySet()) { Method method = entry.getKey(); if (method.getName().equals(this.recoverMethodName)) { SimpleMetadata meta = entry.getValue(); if (meta.type.isAssignableFrom(cause) && compareParameters(args, meta.getArgCount(), method.getParameterTypes())) { result = method; break; } } } } return result; }
Source:
<code>public CacheKey( ItemStack input ) { Preconditions.checkNotNull( input ); Preconditions.checkNotNull( input.getItem() ); <START> this.item = input.getItem(); <END> this.damage = input.getItemDamage(); }</code><technical_language>![MAJOR](<LINK_0> Method new appeng.core.features.registries.GrinderRecipeManager$CacheKey(ItemStack) appears call method object redundantly [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
CacheKey( ItemStack input ) { Preconditions.checkNotNull( input ); Preconditions.checkNotNull( input.getItem() ); this.item = input.getItem(); this.damage = input.getItemDamage(); }
Source:
<code>private void initFields() { when(labelField.getWidget()).thenReturn(mock(Label.class)); when(labelField.isRequired()).thenReturn(true); when(labelField.isContentValid()).thenReturn(true); when(textBoxField.getWidget()).thenReturn(mock(TextBox.class)); when(textBoxField.isRequired()).thenReturn(true); when(textBoxField.isContentValid()).thenReturn(true); when(valueLabelField.getWidget()).thenReturn(mock(ValueLabel.class)); when(valueLabelField.isRequired()).thenReturn(true); when(valueLabelField.isContentValid()).thenReturn(true); fieldCollection = new ArrayList<>(); fieldCollection.add(labelField); fieldCollection.add(textBoxField); <START> fieldCollection.add(valueLabelField); <END> }</code><technical_language>Consider replacing Arrays.asList(labelField, textBoxField, valueLabelField)</technical_language>

Target:
private void initFields() { when(labelField.getWidget()).thenReturn(mock(Label.class)); when(labelField.isRequired()).thenReturn(true); when(labelField.isContentValid()).thenReturn(true); when(textBoxField.getWidget()).thenReturn(mock(TextBox.class)); when(textBoxField.isRequired()).thenReturn(true); when(textBoxField.isContentValid()).thenReturn(true); when(valueLabelField.getWidget()).thenReturn(mock(ValueLabel.class)); when(valueLabelField.isRequired()).thenReturn(true); when(valueLabelField.isContentValid()).thenReturn(true); fieldCollection = Arrays.asList(labelField, textBoxField, valueLabelField); }
Source:
<code><START> public Collection<LockState<OBJECT, CONTEXT>> getLockStates() <END> { return new ArrayList<RWOLockManager.LockState<OBJECT, CONTEXT>>(objectToLockStateMap.values()); }</code><technical_language>safer synchronize this method! other methods return a List<...></technical_language>

Target:
public synchronized List<LockState<OBJECT, CONTEXT>> getLockStates() { return new ArrayList<RWOLockManager.LockState<OBJECT, CONTEXT>>(objectToLockStateMap.values()); }
Source:
<code>public void rewriteAddFilterWithMultipleFilters() { assertPlan( "SELECT sum(totalprice) FILTER(WHERE totalprice > 0), sum(custkey) FILTER(WHERE custkey > 0) FROM orders", anyTree( aggregation( ImmutableMap.of("sum_3", functionCall("sum", ImmutableList.of("sum_15")), "sum", functionCall("sum", ImmutableList.of("sum_14"))), exchange( aggregation( ImmutableMap.of("sum_14", functionCall("sum", ImmutableList.of("totalprice")), "sum_15", functionCall("sum", ImmutableList.of("custkey"))), project( filter( <START> "(\"totalprice\" > 0E0 OR \"custkey\" > BIGINT '0')", <END> tableScan( "orders", ImmutableMap.of("totalprice", "totalprice", "custkey", "custkey"))))))))); }</code><technical_language>0E0 DOUBLE '0'</technical_language>

Target:
public void rewriteAddFilterWithMultipleFilters() { assertPlan( "SELECT sum(totalprice) FILTER(WHERE totalprice > 0), sum(custkey) FILTER(WHERE custkey > 0) FROM orders", anyTree( filter( "(\"totalprice\" > 0E0 OR \"custkey\" > BIGINT '0')", tableScan( "orders", ImmutableMap.of("totalprice", "totalprice", "custkey", "custkey"))))); }
Source:
<code><START> public void endWithFailure() { <END> TransactionSupport.executeInNewTransaction(() -> { if (!getParameters().isLeaveLocked()) { DiskImage diskImage = getDestinationDiskImage(); if (diskImage != null) { imageDao.updateStatus(diskImage.getImage().getId(), ImageStatus.OK); } unLockImage(); } return null; }); }</code><technical_language>missing setSucceeded(true);</technical_language>

Target:
public void endWithFailure() { setSucceeded(true); TransactionSupport.executeInNewTransaction(() -> { if (!getParameters().isLeaveLocked()) { DiskImage diskImage = getDestinationDiskImage(); if (diskImage != null) { imageDao.updateStatus(diskImage.getImage().getId(), ImageStatus.OK); } } return null; }); }
Source:
<code>public void toggleProfilesVisibility(boolean visible) { <START> if (profilesTab.isVisible() != visible) { <END> profilesTab.setVisible(visible); } }</code><technical_language>is this required</technical_language>

Target:
public void toggleProfilesVisibility(boolean visible) { profilesTab.setVisible(visible); }
Source:
<code>public ShapelessResearchRecipe(@Nonnull ItemStack result, TriPredicate<InventoryCrafting, EntityPlayer, World> matcher, Object... recipe) { <START> super(new ResourceLocation(Constants.EI_MODID, "shapeless_research"), result, recipe); <END> this.matcher = matcher; }</code><technical_language>This API mod ID this is API feature</technical_language>

Target:
public ShapelessResearchRecipe(@Nonnull ItemStack result, TriPredicate<InventoryCrafting, EntityPlayer, World> matcher, Object... recipe) { super(new ResourceLocation(Constants.API_MODID, "shapeless_research"), result, recipe); this.matcher = matcher; }
Source:
<code>public void testFormat() { ChatComponent cc = ChatComponent.fromFormat("\u00A7k\u00A7eHello! \u00A7r\u00A7cNice to meet you! :)"); cc.setHoverEvent(HoverEvent.text("Hey there!")); cc.setClickEvent(ClickEvent.of(ClickAction.SUGGEST_COMMAND, "/yolo")); <START> System.out.println(cc); <END> }</code><technical_language>Debug line needed</technical_language>

Target:
public void testFormat() { ChatComponent cc = ChatComponent.fromFormat("\u00A7k\u00A7eHello! \u00A7r\u00A7cNice to meet you! :)"); assertEquals("{\"text\":\"Hello! \",\"extra\":[{\"text\":\"Nice to meet you! :)\",\"obfuscated\":false,\"color\":\"red\"}],\"obfuscated\":true,\"color\":\"yellow\"}", cc.toString()); }
Source:
<code>protected org.ovirt.engine.core.common.businessentities.network.VnicProfile getVnicProfile(String id) { return getEntity(org.ovirt.engine.core.common.businessentities.network.VnicProfile.class, VdcQueryType.GetVnicProfileById, <START> new IdQueryParameters(asGuidOr404(id)), <END> "VnicProfiles"); }</code><technical_language>"guid" instead of "asGuidOr404(id)"</technical_language>

Target:
protected org.ovirt.engine.core.common.businessentities.network.VnicProfile getVnicProfile(String id) { return getEntity(org.ovirt.engine.core.common.businessentities.network.VnicProfile.class, VdcQueryType.GetVnicProfileById, new IdQueryParameters(guid), "VnicProfiles"); }
Source:
<code>private Set<I> dispatchAll(List<Event> events, Set<I> targets) { if (events.isEmpty()) { <START> return ImmutableSet.of(); <END> } Set<I> actualTargets = new HashSet<>(); @Nullable Set<I> targetsForDispatch = targets.isEmpty() ? null : targets; for (Event event : events) { Set<I> targetsOfThisDispatch = dispatchOperation.perform(event, targetsForDispatch); actualTargets.addAll(targetsOfThisDispatch); } if (!actualTargets.isEmpty()) { recordAffectedShards(actualTargets); } return actualTargets; }</code><technical_language>Assuming return empty set twice, consider a private static method (e.g. nobody()) finding cases this class</technical_language>

Target:
private Set<I> dispatchAll(List<Event> events, Set<I> targets) { if (events.isEmpty()) { return noTargets(); } Set<I> actualTargets = new HashSet<>(); @Nullable Set<I> targetsForDispatch = targets.isEmpty() ? null : targets; for (Event event : events) { Set<I> targetsOfThisDispatch = dispatchOperation.perform(event, targetsForDispatch); actualTargets.addAll(targetsOfThisDispatch); } if (!actualTargets.isEmpty()) { recordAffectedShards(actualTargets); } return actualTargets; }
Source:
<code>public void processSample() throws Exception { LanguageDetectorModel model = LanguageDetectorMETest.trainModel(); LanguageDetectorME langdetector = new LanguageDetectorME(model); final AtomicInteger correctCount = new AtomicInteger(); final AtomicInteger incorrectCount = new AtomicInteger(); LanguageDetectorEvaluator evaluator = new LanguageDetectorEvaluator(langdetector, <START> new LanguageDetectorEvaluationMonitor() { <END> @Override public void correctlyClassified(LanguageDetectorSample reference, LanguageDetectorSample prediction) { correctCount.incrementAndGet(); } @Override public void missclassified(LanguageDetectorSample reference, LanguageDetectorSample prediction) { incorrectCount.incrementAndGet(); } }); evaluator.evaluateSample(new LanguageDetectorSample(new Language("pob"), "escreve e faz palestras pelo mundo inteiro sobre anjos")); evaluator.evaluateSample(new LanguageDetectorSample(new Language("fra"), "escreve e faz palestras pelo mundo inteiro sobre anjos")); evaluator.evaluateSample(new LanguageDetectorSample(new Language("fra"), "escreve e faz palestras pelo mundo inteiro sobre anjos")); Assert.assertEquals(1, correctCount.get()); Assert.assertEquals(2, incorrectCount.get()); Assert.assertEquals(3, evaluator.getDocumentCount()); Assert.assertEquals(0.33, evaluator.getAccuracy(), 0.01); }</code><technical_language>yeah correct, misread</technical_language>

Target:
public void processSample() throws Exception { LanguageDetectorModel model = LanguageDetectorMETest.trainModel(); LanguageDetectorME langdetector = new LanguageDetectorME(model); final AtomicInteger correctCount = new AtomicInteger(); final AtomicInteger incorrectCount = new AtomicInteger(); LanguageDetectorEvaluator evaluator = new LanguageDetectorEvaluator(langdetector, new LanguageDetectorEvaluationMonitor() { @Override public void correctlyClassified(LanguageSample reference, LanguageSample prediction) { correctCount.incrementAndGet(); } @Override public void missclassified(LanguageSample reference, LanguageSample prediction) { incorrectCount.incrementAndGet(); } }); evaluator.evaluateSample(new LanguageSample(new Language("pob"), "escreve e faz palestras pelo mundo inteiro sobre anjos")); evaluator.evaluateSample(new LanguageSample(new Language("fra"), "escreve e faz palestras pelo mundo inteiro sobre anjos")); evaluator.evaluateSample(new LanguageSample(new Language("fra"), "escreve e faz palestras pelo mundo inteiro sobre anjos")); Assert.assertEquals(1, correctCount.get()); Assert.assertEquals(2, incorrectCount.get()); Assert.assertEquals(3, evaluator.getDocumentCount()); Assert.assertEquals(0.33, evaluator.getAccuracy(), 0.01); }
Source:
<code>public BasicAuthenticatorCredentials( @JsonProperty("salt") byte[] salt, @JsonProperty("hash") byte[] hash, @JsonProperty("iterations") int iterations ) { this.salt = salt; <START> this.hash = hash; <END> this.iterations = iterations; }</code><technical_language>Please add Preconditions.notNull() check for variables</technical_language>

Target:
public BasicAuthenticatorCredentials( @JsonProperty("salt") byte[] salt, @JsonProperty("hash") byte[] hash, @JsonProperty("iterations") int iterations ) { Preconditions.checkNotNull(salt); Preconditions.checkNotNull(hash); this.salt = salt; this.hash = hash; this.iterations = iterations; }
Source:
<code>public static void clear() { <START> nativeClearLoggers(); <END> }</code><technical_language>clear LoggerAdaptor#loggerMap here</technical_language>

Target:
public static void clear() { synchronized (LoggerAdapter.class) { nativeClearLoggers(); LoggerAdapter.clear(); } }
Source:
<code>public void setUp() { Project project = new Project(InstrumentationRegistry.getTargetContext(), projectName); ProjectManager.getInstance().setCurrentProject(project); fileGenerator = new DSTFileGenerator(); <START> dstFile = new File(Constants.CACHE_DIR + "/" + projectName + ".dst"); <END> }</code><technical_language>please dstFile = new File(Constants.CACHE_DIR, projectName + ".dst") instead</technical_language>

Target:
public void setUp() { Project project = new Project(InstrumentationRegistry.getTargetContext(), projectName); ProjectManager.getInstance().setCurrentProject(project); fileGenerator = new DSTFileGenerator(); }
Source:
<code>protected void configureHttpResponsHeaderFilter(ServletContextHandler context) { String headerConfig = config.getString(WorkerConfig.RESPONSE_HTTP_HEADERS_CONFIG); <START> log.debug("headerConfig : " + headerConfig); <END> String[] configs = StringUtil.csvSplit(headerConfig); Arrays.stream(configs) .forEach(WorkerConfig::validateHttpResponseHeaderConfig); FilterHolder headerFilterHolder = new FilterHolder(HeaderFilter.class); headerFilterHolder.setInitParameter("headerConfig", headerConfig); context.addFilter(headerFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST)); }</code><technical_language>Is this line necessary? response.http.headers.config property logged INFO level worker starts up, WorkerConfig (or DistributedConfig StandaloneConfig) constructor</technical_language>

Target:
protected void configureHttpResponsHeaderFilter(ServletContextHandler context) { String headerConfig = config.getString(WorkerConfig.RESPONSE_HTTP_HEADERS_CONFIG); FilterHolder headerFilterHolder = new FilterHolder(HeaderFilter.class); headerFilterHolder.setInitParameter("headerConfig", headerConfig); context.addFilter(headerFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST)); }
Source:
<code>public BoundFilter(final BoundDimFilter boundDimFilter) { super( boundDimFilter.getDimension(), new Predicate<String>() { @Override public boolean apply(String input) { if (input == null) { return false; } Comparator<String> comparator; if (boundDimFilter.isAlphaNumeric()) { comparator = new AlphaNumericTopNMetricSpec(null).getComparator(null, null); } else { comparator = new LexicographicTopNMetricSpec(null).getComparator(null, null); } int lowerComparing = comparator.compare(input, boundDimFilter.getLower()); int upperComparing = comparator.compare(input, boundDimFilter.getUpper()); <START> boolean lowerIsNull = boundDimFilter.getLower() == null; <END> boolean upperIsNull = boundDimFilter.getUpper() == null; if (boundDimFilter.isLowerStrict() && boundDimFilter.isUpperStrict()) { return (lowerIsNull || (lowerComparing > 0)) && (upperIsNull || upperComparing < 0); } else if (boundDimFilter.isLowerStrict()) { return (lowerIsNull || lowerComparing > 0) && (upperIsNull || upperComparing <= 0); } else if (boundDimFilter.isUpperStrict()) { return (lowerIsNull || lowerComparing >= 0) && (upperIsNull || upperComparing < 0); } return (lowerIsNull || upperComparing <= 0) && (upperIsNull || lowerComparing >= 0); } } ); }</code><technical_language>hoping comparator.compare(..) throw NPE if arg null</technical_language>

Target:
public BoundFilter(final BoundDimFilter boundDimFilter) { super( boundDimFilter.getDimension(), new Predicate<String>() { @Override public boolean apply(String input) { if (input == null) { return false; } Comparator<String> comparator; if (boundDimFilter.isAlphaNumeric()) { comparator = new AlphaNumericTopNMetricSpec(null).getComparator(null, null); } else { comparator = new LexicographicTopNMetricSpec(null).getComparator(null, null); } int lowerComparing = 1; int upperComparing = 1; if (boundDimFilter.getLower() != null) { lowerComparing = comparator.compare(input, boundDimFilter.getLower()); } if (boundDimFilter.getUpper() != null) { upperComparing = comparator.compare(boundDimFilter.getUpper(), input); } if (boundDimFilter.isLowerStrict() && boundDimFilter.isUpperStrict()) { return ((lowerComparing > 0)) && ( upperComparing > 0); } else if (boundDimFilter.isLowerStrict()) { return (lowerComparing > 0) && (upperComparing >= 0); } else if (boundDimFilter.isUpperStrict()) { return (lowerComparing >= 0) && (upperComparing > 0); } return (lowerComparing >= 0) && (upperComparing >= 0); } } ); }
Source:
<code>public String getTopCommitComment() { loader.waitOnClosed(); return seleniumWebDriverHelper .waitVisibility(revertPanel, ELEMENT_TIMEOUT_SEC) <START> .getText() <END> .split("\n")[4]; }</code><technical_language>complex procedure of revision number. IMHO usage of regex more obvious</technical_language>

Target:
public String getTopCommitComment() { loader.waitOnClosed(); int numberOfTopCommitCell = 4; return getRevertCommitTableContent().split("\n")[numberOfTopCommitCell]; }
Source:
<code>private Session newSession(IProgressMonitor monitor) throws RemoteConnectionException { SubMonitor progress = SubMonitor.convert(monitor, 10); try { Session session = fJSchService.createSession(getHostname(), getPort(), getUsername()); session.setUserInfo(new JSchUserInfo()); if (isPasswordAuth()) { session.setConfig("PreferredAuthentications", "password,keyboard-interactive,gssapi-with-mic,publickey"); session.setPassword(getPassword()); } else { session.setConfig("PreferredAuthentications", "publickey,gssapi-with-mic,password,keyboard-interactive"); <START> session.setPassword(getPassword()); <END> } if (getProxyCommand().isEmpty() && getProxyConnectionName().isEmpty()) { fJSchService.connect(session, getTimeout() * 1000, progress.newChild(10)); } else { if (getProxyCommand().isEmpty()) { session.setProxy(JSchConnectionProxyFactory.createForwardProxy(getProxyConnection(), progress.newChild(10))); fJSchService.connect(session, getTimeout() * 1000, progress.newChild(10)); } else { session.setProxy(JSchConnectionProxyFactory.createCommandProxy(getProxyConnection(), getProxyCommand(), progress.newChild(10))); session.connect(getTimeout() * 1000); } } if (!progress.isCanceled()) { fSessions.add(session); return session; } return null; } catch (JSchException e) { throw new RemoteConnectionException(e.getMessage()); } }</code><technical_language>If branches of "if" do thing, code moved outside</technical_language>

Target:
private Session newSession(IProgressMonitor monitor) throws RemoteConnectionException { SubMonitor progress = SubMonitor.convert(monitor, 10); try { Session session = fJSchService.createSession(getHostname(), getPort(), getUsername()); session.setUserInfo(new JSchUserInfo()); if (isPasswordAuth()) { session.setConfig("PreferredAuthentications", "password,keyboard-interactive,gssapi-with-mic,publickey"); } else { session.setConfig("PreferredAuthentications", "publickey,gssapi-with-mic,password,keyboard-interactive"); } String password = getPassword(); if (!password.isEmpty()) { session.setPassword(password); } if (getProxyCommand().isEmpty() && getProxyConnectionName().isEmpty()) { fJSchService.connect(session, getTimeout() * 1000, progress.newChild(10)); } else { if (getProxyCommand().isEmpty()) { session.setProxy(JSchConnectionProxyFactory.createForwardProxy(getProxyConnection(), progress.newChild(10))); fJSchService.connect(session, getTimeout() * 1000, progress.newChild(10)); } else { session.setProxy(JSchConnectionProxyFactory.createCommandProxy(getProxyConnection(), getProxyCommand(), progress.newChild(10))); session.connect(getTimeout() * 1000); } } if (!progress.isCanceled()) { fSessions.add(session); return session; } return null; } catch (JSchException e) { throw new RemoteConnectionException(e.getMessage()); } }
Source:
<code>static <T, F extends Future<T>> Supplier<F> decorateFuture( RateLimiter rateLimiter, int permits, Supplier<? extends F> supplier ) { return () -> { waitForPermission(rateLimiter, permits); try { F result = supplier.get(); <START> drainIfNeeded(rateLimiter, CallsResult.success(result)); <END> return result; } catch (Exception exception) { drainIfNeeded(rateLimiter, CallsResult.failure(exception)); throw exception; } }; }</code><technical_language>Please introduce onResult hook</technical_language>

Target:
static <T, F extends Future<T>> Supplier<F> decorateFuture( RateLimiter rateLimiter, int permits, Supplier<? extends F> supplier ) { return () -> { waitForPermission(rateLimiter, permits); try { F result = supplier.get(); rateLimiter.onResult(result); return result; } catch (Exception exception) { rateLimiter.onError(exception); throw exception; } }; }
Source:
<code>public static CoordinateReferenceSystem crs( CRS crs ) { if ( crs.getHref().equals( CoordinateReferenceSystem.WGS84.href ) ) { return CoordinateReferenceSystem.WGS84; } else if ( crs.getHref().equals( CoordinateReferenceSystem.Cartesian.href ) ) <START> { <END> return CoordinateReferenceSystem.Cartesian; } else { throw new UnsupportedOperationException( "Unknown CRS: " + crs ); } }</code><technical_language>".getCoordinate().getCoordinate()" strange</technical_language>

Target:
public static CoordinateReferenceSystem crs( CRS crs ) { return CoordinateReferenceSystem.get( crs ); }
Source:
<code>public boolean beginUpdatingLogsUsed(InMemoryMap memTable, DfsLogger more, boolean mincFinish) { boolean releaseLock = true; logLock.lock(); try { synchronized (this) { if (isCloseComplete()) { throw new IllegalStateException("Can not update logs of closed tablet " + extent); } boolean addToOther; if (memTable == getTabletMemory().getMinCMemTable()) addToOther = true; else if (memTable == getTabletMemory().getMemTable()) addToOther = false; else throw new IllegalArgumentException("passed in memtable that is not in use"); if (mincFinish) { if (addToOther) throw new IllegalStateException("Adding to other logs for mincFinish"); if (otherLogs.size() != 0) throw new IllegalStateException( "Expect other logs to be 0 when min finish, but its " + otherLogs); if (currentLogs.size() == 0) return !releaseLock; } int numAdded = 0; int numContained = 0; if (addToOther) { if (otherLogs.add(more)) numAdded++; if (currentLogs.contains(more)) numContained++; } else { if (currentLogs.add(more)) numAdded++; if (otherLogs.contains(more)) numContained++; } if (numAdded > 0) { rebuildReferencedLogs(); } <START> if (numAdded > 0 && numContained == 0) { <END> releaseLock = false; } return !releaseLock; } } finally { if (releaseLock) logLock.unlock(); } }</code><technical_language>other conditions removed (because happen), valid values for 0 1. If so, this code dramatically simplified if change type boolean assignments set values directly, if blocks</technical_language>

Target:
public boolean beginUpdatingLogsUsed(InMemoryMap memTable, DfsLogger more, boolean mincFinish) { boolean releaseLock = true; logLock.lock(); try { synchronized (this) { if (isCloseComplete()) { throw new IllegalStateException("Can not update logs of closed tablet " + extent); } boolean addToOther; if (memTable == getTabletMemory().getMinCMemTable()) addToOther = true; else if (memTable == getTabletMemory().getMemTable()) addToOther = false; else throw new IllegalArgumentException("passed in memtable that is not in use"); if (mincFinish) { if (addToOther) throw new IllegalStateException("Adding to other logs for mincFinish"); if (otherLogs.size() != 0) throw new IllegalStateException( "Expect other logs to be 0 when min finish, but its " + otherLogs); if (currentLogs.size() == 0) return !releaseLock; } boolean added; boolean contained; if (addToOther) { added = otherLogs.add(more); contained = currentLogs.contains(more); } else { added = currentLogs.add(more); contained = otherLogs.contains(more); } if (added) { rebuildReferencedLogs(); } if (added && !contained) { releaseLock = false; } return !releaseLock; } } finally { if (releaseLock) logLock.unlock(); } }
Source:
<code>public void testMd5Hash() throws Exception { String fingerprint1 = "1b:d3:aa:c3:67:4b:b5:55:a9:ff:19:0c:16:7e:d1:de"; <START> String goodfingerprint1 = "MD5:1b:d3:aa:c3:67:4b:b5:55:a9:ff:19:0c:16:7e:d1:de"; <END> assertEquals(goodfingerprint1, OpenSSHUtils.fixupKeyFingerprintHash(fingerprint1)); assertEquals(goodfingerprint1, OpenSSHUtils.fixupKeyFingerprintHash(goodfingerprint1)); }</code><technical_language>reuse fingerprint1 build good fingerprint</technical_language>

Target:
public void testMd5Hash() throws Exception { String fingerprint1 = "1b:d3:aa:c3:67:4b:b5:55:a9:ff:19:0c:16:7e:d1:de"; String goodfingerprint1 = "MD5:" + fingerprint1; assertEquals(goodfingerprint1, OpenSSHUtils.fixupKeyFingerprintHash(fingerprint1)); assertEquals(goodfingerprint1, OpenSSHUtils.fixupKeyFingerprintHash(goodfingerprint1)); }
Source:
<code>private List<String> getOverwriteUserAttributesListFromExtSource(ExtSource membersSource) throws InternalErrorException { Map<String, String> membersSourceAttributes = getPerunBl().getExtSourcesManagerBl().getAttributes(membersSource); List<String> overwriteUserAttributesList = new ArrayList<>(); String overwriteUserAttributes = membersSourceAttributes.get("overwriteUserAttributes"); if(overwriteUserAttributes != null && !overwriteUserAttributes.isEmpty()) { overwriteUserAttributes = overwriteUserAttributes.replaceAll("\\s", ""); <START> overwriteUserAttributesList = asList(overwriteUserAttributes.split(",")); <END> } return overwriteUserAttributesList; }</code><technical_language>is reason for this? I prefer Arrays.asList, is easier for human read</technical_language>

Target:
private List<String> getOverwriteUserAttributesListFromExtSource(ExtSource membersSource) throws InternalErrorException { Map<String, String> membersSourceAttributes = getPerunBl().getExtSourcesManagerBl().getAttributes(membersSource); List<String> overwriteUserAttributesList = new ArrayList<>(); String overwriteUserAttributes = membersSourceAttributes.get("overwriteUserAttributes"); if(overwriteUserAttributes != null && !overwriteUserAttributes.isEmpty()) { overwriteUserAttributes = overwriteUserAttributes.replaceAll("\\s", ""); overwriteUserAttributesList = Arrays.asList(overwriteUserAttributes.split(",")); } return overwriteUserAttributesList; }
Source:
<code>public void stop() throws ConnectException { try { running.set(false); if (cachedConnectionProvider != null) { cachedConnectionProvider.close(); } } finally { cachedConnectionProvider = null; try { if (dialect != null) { <START> dialect.close(); <END> } } finally { dialect = null; } } }</code><technical_language>org.apache.kafka.common.utils.Utils.closeQuietly</technical_language>

Target:
public void stop() throws ConnectException { try { running.set(false); if (cachedConnectionProvider != null) { cachedConnectionProvider.close(); } } finally { cachedConnectionProvider = null; try { if (dialect != null) { dialect.close(); } } catch (Throwable t) { log.warn("Error while closing the dialect: ", dialect, t); } finally { dialect = null; } } }
Source:
<code>public CompletableFuture<JobClient> execute(final Pipeline pipeline, final Configuration configuration) { requireNonNull(pipeline); requireNonNull(configuration); final JobGraph jobGraph = PipelineExecutorUtils.getJobGraph(pipeline, configuration); final JobID actualJobId = jobGraph.getJobID(); this.applicationJobIds.add(actualJobId); <START> LOG.info("Job is submitted.", actualJobId); <END> final EmbeddedClient embeddedClient = new EmbeddedClient(actualJobId, configuration, dispatcherGateway); return embeddedClient .submitJob(jobGraph) .thenApplyAsync(jobID -> embeddedClient); }</code><technical_language>This a good case for executor listener, listen submitted job ids, a future change</technical_language>

Target:
public CompletableFuture<JobClient> execute(final Pipeline pipeline, final Configuration configuration) { checkNotNull(pipeline); checkNotNull(configuration); final JobGraph jobGraph = PipelineExecutorUtils.getJobGraph(pipeline, configuration); final JobID actualJobId = jobGraph.getJobID(); this.submittedJobIds.add(actualJobId); LOG.info("Job is submitted.", actualJobId); final Time timeout = Time.milliseconds(configuration.getLong(WebOptions.TIMEOUT)); final CompletableFuture<JobID> jobSubmissionFuture = submitJob( dispatcherGateway, blobServerAddress -> new BlobClient(blobServerAddress, configuration), jobGraph, timeout); final EmbeddedJobClient embeddedClient = new EmbeddedJobClient( actualJobId, dispatcherGateway, timeout); return jobSubmissionFuture .thenApplyAsync(jobID -> embeddedClient); }
Source:
<code>public Collection<Partition<AbstractCouchBaseInputOperator<T>>> definePartitions(Collection<Partition<AbstractCouchBaseInputOperator<T>>> partitions, PartitioningContext incrementalCapacity) { conf = store.getConf(); int numPartitions = conf.getServers().size(); List<String> list = conf.getServers(); Collection<Partition<AbstractCouchBaseInputOperator<T>>> newPartitions = Lists.newArrayListWithExpectedSize(numPartitions); for (int i = 0; i < numPartitions; i++) { <START> AbstractCouchBaseInputOperator<T> oper = PartitionerUtils.cloneOperatorByKryo(this); <END> oper.setServerIndex(i); oper.setServerURIString(list.get(i)); logger.debug("oper urlstring is {}", i, oper.getServerURIString()); newPartitions.add(new DefaultPartition<AbstractCouchBaseInputOperator<T>>(oper)); } return newPartitions; }</code><technical_language>create a separate Kryo instance for partition</technical_language>

Target:
public Collection<Partition<AbstractCouchBaseInputOperator<T>>> definePartitions(Collection<Partition<AbstractCouchBaseInputOperator<T>>> partitions, PartitioningContext incrementalCapacity) { conf = store.getConf(); int numPartitions = conf.getServers().size(); List<String> list = conf.getServers(); Collection<Partition<AbstractCouchBaseInputOperator<T>>> newPartitions = Lists.newArrayListWithExpectedSize(numPartitions); KryoCloneUtils<AbstractCouchBaseInputOperator<T>> cloneUtils = KryoCloneUtils.createCloneUtils(this); for (int i = 0; i < numPartitions; i++) { AbstractCouchBaseInputOperator<T> oper = cloneUtils.getClone(); oper.setServerIndex(i); oper.setServerURIString(list.get(i)); logger.debug("oper urlstring is {}", i, oper.getServerURIString()); newPartitions.add(new DefaultPartition<>(oper)); } return newPartitions; }
Source:
<code><START> public <T> Query<T> mapTo(Type resultType) { <END> return this.map(new RegisteredRowMapper<>(resultType, config.mappingRegistry)); }</code><technical_language>return Query<?> shenanigans this get compiler: Type type = int.class; String result = handle.createQuery("...").mapTo(type).findOnly();</technical_language>

Target:
public Query<?> mapTo(Type resultType) { return this.map(new RegisteredRowMapper<>(resultType, config.mappingRegistry)); }
Source:
<code>private void startDownloadTask() { downloading = true; bukkitService.runTaskAsynchronously(() -> { try { Path tempFile = Files.createTempFile(ARCHIVE_FILE, null); try (OutputStream out = Files.newOutputStream(tempFile)) { Resources.copy(new URL(ARCHIVE_URL), out); } String targetChecksum = Resources.toString(new URL(CHECKSUM_URL), StandardCharsets.UTF_8); if (!verifyChecksum(Hashing.md5(), tempFile, targetChecksum)) { return; } if (!extractDatabase(tempFile, dataFile)) { <START> ConsoleLogger.warning("Cannot find database inside downloaded GEO IP file at " + tempFile); <END> } downloading = false; } catch (IOException ioEx) { ConsoleLogger.logException("Could not download GeoLiteAPI database", ioEx); } }); }</code><technical_language>return; this downloading set false in this case</technical_language>

Target:
private void startDownloadTask() { downloading = true; bukkitService.runTaskAsynchronously(() -> { ConsoleLogger.info("Downloading GEO IP database, because the old database is outdated or doesn't exist"); Path tempFile = null; try { tempFile = Files.createTempFile(ARCHIVE_FILE, null); try (OutputStream out = Files.newOutputStream(tempFile)) { Resources.copy(new URL(ARCHIVE_URL), out); } String targetChecksum = Resources.toString(new URL(CHECKSUM_URL), StandardCharsets.UTF_8); if (!verifyChecksum(Hashing.md5(), tempFile, targetChecksum)) { return; } if (!extractDatabase(tempFile, dataFile)) { ConsoleLogger.warning("Cannot find database inside downloaded GEO IP file at " + tempFile); return; } ConsoleLogger.info("Successfully downloaded new GEO IP database to " + dataFile); downloading = false; } catch (IOException ioEx) { ConsoleLogger.logException("Could not download GeoLiteAPI database", ioEx); } finally { if (tempFile != null) { FileUtils.delete(tempFile.toFile()); } } }); }
Source:
<code>private List<EnricherSpec<?>> buildEnricherSpecs(Object enrichers) { <START> List<EnricherSpec<?>> enricherSpecs = new ArrayList<EnricherSpec<? extends Enricher>>(); <END> if (enrichers instanceof Iterable) { for (Object enricher : (Iterable<Object>)enrichers) { if (enricher instanceof Map) { String enricherTypeName = ((Map<?, ?>) enricher).get("enricherType").toString(); Class<? extends Enricher> enricherType = null; try { enricherType = ((Class<? extends Enricher>) Class.forName(enricherTypeName)); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } enricherSpecs.add(toCoreEnricherSpec(enricherType, (Map<?, ?>) ((Map<?, ?>) enricher).get("brooklyn.config"))); } else { throw new IllegalArgumentException("enricher should be map, not " + enricher.getClass()); } } } else if (enrichers != null) { throw new IllegalArgumentException("enrichers body should be iterable, not " + enrichers.getClass()); } return enricherSpecs; }</code><technical_language>If do = Lists.newArrayList() need repeat generics (importing guava Lists)</technical_language>

Target:
private List<EnricherSpec<?>> buildEnricherSpecs(Object enrichers) { List<EnricherSpec<?>> enricherSpecs = Lists.newArrayList(); if (enrichers instanceof Iterable) { for (Object enricher : (Iterable<Object>)enrichers) { if (enricher instanceof Map) { String enricherTypeName = ((Map<?, ?>) enricher).get("enricherType").toString(); Class<? extends Enricher> enricherType = null; try { enricherType = ((Class<? extends Enricher>) Class.forName(enricherTypeName)); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } enricherSpecs.add(toCoreEnricherSpec(enricherType, (Map<?, ?>) ((Map<?, ?>) enricher).get("brooklyn.config"))); } else { throw new IllegalArgumentException("enricher should be map, not " + enricher.getClass()); } } } else if (enrichers != null) { throw new IllegalArgumentException("enrichers body should be iterable, not " + enrichers.getClass()); } return enricherSpecs; }
Source:
<code>public String[] getLocations(InputSplit split) throws IOException { if (!(split instanceof FileSplit)) { if (isDebugEnabled) { LOG.debug("Split: " + split + " is not a FileSplit. Using default locations"); } return split.getLocations(); } FileSplit fsplit = (FileSplit) split; String splitDesc = "Split at " + fsplit.getPath() + " with offset= " + fsplit.getStart() + ", length=" + fsplit.getLength(); <START> List<String> preferredLocations = new ArrayList<>(preferLocations(fsplit)); <END> List<String> finalLocations = new ArrayList<>(numberOfLocations); while (finalLocations.size() < numberOfLocations && preferredLocations.size() > 0) { String nextLocation = preferredLocations.get(determineLocation(preferredLocations, fsplit.getPath().toString(), fsplit.getStart(), splitDesc)); finalLocations.add(nextLocation); preferredLocations.remove(nextLocation); } return finalLocations.toArray(new String[0]); }</code><technical_language>I think, want consider rolling patch introduced preferred locations in place (HIVE-21232). This caused noticeable skew LLAP cluster. verify @t3rmin4t0r I assume original behavior, locations</technical_language>

Target:
public String[] getLocations(InputSplit split) throws IOException { if (!(split instanceof FileSplit)) { if (isDebugEnabled) { LOG.debug("Split: " + split + " is not a FileSplit. Using default locations"); } return split.getLocations(); } FileSplit fsplit = (FileSplit) split; String splitDesc = "Split at " + fsplit.getPath() + " with offset= " + fsplit.getStart() + ", length=" + fsplit.getLength(); List<String> locationsToCheck = (useLocality ? preferLocations(fsplit) : locations); return determineLocation(locationsToCheck, numberOfLocations, fsplit.getPath().toString(), fsplit.getStart(), splitDesc); }
Source:
<code>public static void main(String[] args) { var data1 = new Data(1, "data1", Data.DataType.type1); var data2 = new Data(2, "data2", Data.DataType.type2); var data3 = new Data(3, "data3", Data.DataType.type3); var data4 = new Data(4, "data4", Data.DataType.type1); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); ShardManager manager = new LookupShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new RangeShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new HashShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); <START> return; <END> }</code><technical_language>Return is unnecessary</technical_language>

Target:
public static void main(String[] args) { var data1 = new Data(1, "data1", Data.DataType.type1); var data2 = new Data(2, "data2", Data.DataType.type2); var data3 = new Data(3, "data3", Data.DataType.type3); var data4 = new Data(4, "data4", Data.DataType.type1); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); ShardManager manager = new LookupShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new RangeShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new HashShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); }
Source:
<code>public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); <START> Collections.addAll(this.injectionPoints, injectionPoints.toArray(new InjectionPoint[injectionPoints.size()])); <END> return this; }</code><technical_language>this.injectionPoints.addAll(injectionPoints)</technical_language>

Target:
public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); this.injectionPoints.addAll(injectionPoints); return this; }
Source:
<code><START> public ResteasyProviderFactory getProviderFactory() <END> { return providerFactory; }</code><technical_language>ClientConfiguration addHeaderDelegate() method. add one? I add one. I advantages of this approach: * easier adding of HeaderDelegate client * provide access ResteasyProviderFactory methods, method, is needed (addHeaderDelegate) I currently disadvantage of this approach. Do some? WDYT</technical_language>

Target:
protected ResteasyProviderFactory getProviderFactory() { return providerFactory; }
Source:
<code>public void testSerialization() throws IOException, ClassNotFoundException{ byte[] startRow = "aa".getBytes(); byte[] stopRow = "zz".getBytes(); String projectId = "project"; String zone = "zone"; String cluster = "cluster"; String table = "table"; CloudBigtableScanConfiguration config = new CloudBigtableScanConfiguration.Builder() .withProjectId(projectId) .withZone(zone) .withCluster(cluster) .withTable(table) .withScan(new Scan(startRow, stopRow)) .build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); <START> ObjectOutputStream oos = new ObjectOutputStream(bos); <END> oos.writeObject(config); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); CloudBigtableScanConfiguration serialized = (CloudBigtableScanConfiguration) ois.readObject(); Assert.assertEquals(projectId, serialized.getProjectId()); Assert.assertEquals(zone, serialized.getZone()); Assert.assertEquals(cluster, serialized.getCluster()); Assert.assertEquals(table, serialized.getTable()); Scan scan = serialized.getScan(); Assert.assertArrayEquals(startRow, scan.getStartRow()); Assert.assertArrayEquals(stopRow, scan.getStopRow()); }</code><technical_language>[SerializableUtils](<LINK_0> for helpers test serializability</technical_language>

Target:
public void testSerialization() throws IOException, ClassNotFoundException{ byte[] startRow = "aa".getBytes(); byte[] stopRow = "zz".getBytes(); String projectId = "project"; String zone = "zone"; String cluster = "cluster"; String table = "table"; CloudBigtableScanConfiguration config = new CloudBigtableScanConfiguration.Builder() .withProjectId(projectId) .withZoneId(zone) .withClusterId(cluster) .withTableId(table) .withScan(new Scan(startRow, stopRow)) .build(); CloudBigtableScanConfiguration serialized = SerializableUtils.ensureSerializable(config); Assert.assertEquals(projectId, serialized.getProjectId()); Assert.assertEquals(zone, serialized.getZoneId()); Assert.assertEquals(cluster, serialized.getClusterId()); Assert.assertEquals(table, serialized.getTableId()); Scan scan = serialized.getScan(); Assert.assertArrayEquals(startRow, scan.getStartRow()); Assert.assertArrayEquals(stopRow, scan.getStopRow()); }
Source:
<code>public static IResource convertToResource( @NotNull VirtualFile virtualFile, @NotNull IProject project) { <START> IntelliJProjectImplV2 module = (IntelliJProjectImplV2) project <END> .getAdapter(IntelliJProjectImplV2.class); return module.getResource(virtualFile); }</code><technical_language>module this "fancy" sarosXYZ name, do mix up, other methods</technical_language>

Target:
public static IResource convertToResource( @NotNull VirtualFile virtualFile, @NotNull IProject project) { IntelliJProjectImplV2 wrappedModule = (IntelliJProjectImplV2) project .getAdapter(IntelliJProjectImplV2.class); return wrappedModule.getResource(virtualFile); }