auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void setResult(Collection<T> newUserSelection) { <START> if (newUserSelection == null) { <END> result = Collections.emptyList(); } else { result = newUserSelection; } }</code><technical_language>simply do "result = newUserSelection" changed getResult() mehtod, manage null</technical_language>

Target:
protected void setResult(Collection<T> newUserSelection) { if (newUserSelection == null) { result = null; } else { result = newUserSelection; } }
Source:
<code>public Context(PageContext pageContext) { <START> this(pageContext.getServletContext(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), null, null, null); <END> }</code><technical_language>delegate argument pageContext.getOut()</technical_language>

Target:
public Context(PageContext pageContext) { this(pageContext.getServletContext(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), pageContext.getOut(), null, null); }
Source:
<code>public ResourceMapping[] getMappings(IResource resource, ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { if (context instanceof GitSubscriberResourceMappingContext && resource instanceof IProject) { GitSubscriberResourceMappingContext gitContext = (GitSubscriberResourceMappingContext) context; GitSynchronizeDataSet gsds = gitContext.getSyncData(); <START> GitSynchronizeData data = gsds.getData((IProject)resource); <END> if (data != null) { GitModelObject object = null; try { object = GitModelObject.createRoot(data); } catch (IOException e) { Activator.logError(e.getMessage(), e); } if (object != null) { ResourceMapping rm = (ResourceMapping) object .getAdapter(ResourceMapping.class); return new ResourceMapping[] { rm }; } } } return super.getMappings(resource, context, monitor); }</code><technical_language>This in a separate patch in bug report, right? Please move a separate change explain done</technical_language>

Target:
public ResourceMapping[] getMappings(IResource resource, ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { if (context instanceof GitSubscriberResourceMappingContext) { GitSubscriberResourceMappingContext gitContext = (GitSubscriberResourceMappingContext) context; GitSynchronizeDataSet gsds = gitContext.getSyncData(); GitSynchronizeData data = gsds.getData(resource.getProject()); if (data != null) { GitModelObject object = null; try { object = GitModelObject.createRoot(data); } catch (IOException e) { Activator.logError(e.getMessage(), e); } if (object != null) { ResourceMapping rm = (ResourceMapping) object .getAdapter(ResourceMapping.class); return new ResourceMapping[] { rm }; } } } return super.getMappings(resource, context, monitor); }
Source:
<code>public void onMessage(org.springframework.amqp.core.Message amqpMessage, Channel channel) throws Exception { Message<?> message = toMessagingMessage(amqpMessage); if (logger.isDebugEnabled()) { logger.debug("Processing [" + message + "]"); } try { Object result = invokeHandler(amqpMessage, channel, message); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("No result object given - no result to handle"); } } catch (ListenerExecutionFailedException e) { if (this.errorHandler != null) { try { Object result = this.errorHandler.handleError(amqpMessage, message, e); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("Error handler returned no result"); } } catch (Exception ex) { if (!this.propagateExceptions) { throw ex; } <START> handleResult(new RemoteInvocationResult(ex), amqpMessage, channel, message); <END> } } else { if (!this.propagateExceptions) { throw e; } handleResult(new RemoteInvocationResult(e.getCause()), amqpMessage, channel, message); } } }</code><technical_language>mind explaining reason of RemoteInvocationResult layer? get a gain recreate() ability rethrow? equip SimpleMessageConverter a flag rethrowResult, this feature deserialize Exception is</technical_language>

Target:
public void onMessage(org.springframework.amqp.core.Message amqpMessage, Channel channel) throws Exception { Message<?> message = toMessagingMessage(amqpMessage); if (logger.isDebugEnabled()) { logger.debug("Processing [" + message + "]"); } try { Object result = invokeHandler(amqpMessage, channel, message); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("No result object given - no result to handle"); } } catch (ListenerExecutionFailedException e) { if (this.errorHandler != null) { try { Object result = this.errorHandler.handleError(amqpMessage, message, e); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("Error handler returned no result"); } } catch (Exception ex) { if (!this.returnExceptions) { throw ex; } handleResult(new RemoteInvocationResult(ex), amqpMessage, channel, message); } } else { if (!this.returnExceptions) { throw e; } handleResult(new RemoteInvocationResult(e.getCause()), amqpMessage, channel, message); } } }
Source:
<code>protected List<MethodMatcher> getMethodInvocationMatchers() { <START> return ImmutableList.of(MethodMatcher.create().typeDefinition("java.util.stream.Stream").name("peek").withAnyParameters()); <END> }</code><technical_language>I include primitive-based streams IntStream.peek(IntConsumer), LongStream.peek(LongConsumer) DoubleStream.peek(DoubleConsumer)</technical_language>

Target:
protected List<MethodMatcher> getMethodInvocationMatchers() { return ImmutableList.of( MethodMatcher.create().typeDefinition("java.util.stream.Stream").name("peek").withAnyParameters(), MethodMatcher.create().typeDefinition("java.util.stream.IntStream").name("peek").withAnyParameters(), MethodMatcher.create().typeDefinition("java.util.stream.LongStream").name("peek").withAnyParameters(), MethodMatcher.create().typeDefinition("java.util.stream.DoubleStream").name("peek").withAnyParameters() ); }
Source:
<code>public boolean equals(Object o) { <START> if ( o == null || getClass() != o.getClass() ) { <END> return false; } Mapping mapping = (Mapping) o; return targetName.equals( mapping.targetName ); }</code><technical_language>remove this? This is a shortcut check instance</technical_language>

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Mapping mapping = (Mapping) o; return targetName.equals( mapping.targetName ); }
Source:
<code>public String toString() { StringBuilder s = new StringBuilder(super.toString()); switch (useFlag){ case USED: s.append("[pos: "); <START> s.append(String.valueOf(resolvedPosition)); <END> s.append("]"); break; case UNUSED: s.append("[pos: unused]"); break; case FAKE_USED: s.append("[pos: fake_used]"); break; } s.append("[id:"); s.append(String.valueOf(id)); s.append("]"); if (initializationCount > 0) { s.append("[pc: "); for (int i = 0; i < initializationCount; i++) { if (i > 0) { s.append(", "); } s.append(String.valueOf(initializationPCs[i << 1])); s.append("-"); s.append( ((initializationPCs[(i << 1) + 1] == -1) ? "?" : String.valueOf(initializationPCs[(i<< 1) + 1]))); } s.append("]"); } return s.toString(); }</code><technical_language>String.valueOf(..) is required</technical_language>

Target:
public String toString() { StringBuilder s = new StringBuilder(super.toString()); switch (useFlag){ case USED: s.append("[pos: "); s.append(resolvedPosition); s.append("]"); break; case UNUSED: s.append("[pos: unused]"); break; case FAKE_USED: s.append("[pos: fake_used]"); break; } s.append("[id:"); s.append(id); s.append("]"); if (initializationCount > 0) { s.append("[pc: "); for (int i = 0; i < initializationCount; i++) { if (i > 0) { s.append(", "); } s.append(initializationPCs[i << 1]); s.append("-"); if (initializationPCs[(i << 1) + 1] == -1) { s.append("?"); } else { s.append(initializationPCs[(i<< 1) + 1]); } } s.append("]"); } return s.toString(); }
Source:
<code>private static Split createRemoteSplitFor(TaskId taskId, URI remoteSourceTaskLocation, TaskId remoteSourceTaskId) { <START> String splitLocation = remoteSourceTaskLocation.toASCIIString() + "/results/" + taskId.getId(); <END> return new Split(REMOTE_CONNECTOR_ID, new RemoteTransactionHandle(), new RemoteSplit(splitLocation, remoteSourceTaskId)); }</code><technical_language>other string options ASCII String? :P</technical_language>

Target:
private static Split createRemoteSplitFor(TaskId taskId, URI remoteSourceTaskLocation, TaskId remoteSourceTaskId) { String splitLocation = remoteSourceTaskLocation.toASCIIString() + "/results/" + taskId.getId(); return new Split(REMOTE_CONNECTOR_ID, new RemoteTransactionHandle(), new RemoteSplit(new Location(splitLocation), remoteSourceTaskId)); }
Source:
<code>public Client updateClient(ClientUpdate update) { try (Jedis j = pool.getResource()) { byte[] ep = j.get(toRegKey(update.getRegistrationId())); if (ep == null) { return null; } <START> byte[] data = j.get(ByteArrayUtils.concatenate(EP_CLIENT.getBytes(UTF_8), ep)); <END> if (data == null) { return null; } Client c = deserialize(data); byte[] lockValue = null; byte[] lockKey = toLockKey(c.getEndpoint()); try { lockValue = RedisLock.acquire(j, lockKey); Client clientUpdated = update.updateClient(c); j.set(toEndpointKey(clientUpdated.getEndpoint()), serialize(clientUpdated)); for (ClientRegistryListener l : listeners) { l.updated(update, clientUpdated); } return clientUpdated; } finally { RedisLock.release(j, lockKey, lockValue); } } }</code><technical_language>helper method build this key ? toEndpointKey(byte[])</technical_language>

Target:
public Client updateClient(ClientUpdate update) { try (Jedis j = pool.getResource()) { byte[] ep = j.get(toRegKey(update.getRegistrationId())); if (ep == null) { return null; } byte[] data = j.get(toEndpointKey(ep)); if (data == null) { return null; } Client c = deserialize(data); byte[] lockValue = null; byte[] lockKey = toLockKey(c.getEndpoint()); try { lockValue = RedisLock.acquire(j, lockKey); Client clientUpdated = update.updateClient(c); j.set(toEndpointKey(clientUpdated.getEndpoint()), serialize(clientUpdated)); for (ClientRegistryListener l : listeners) { l.updated(update, clientUpdated); } return clientUpdated; } finally { RedisLock.release(j, lockKey, lockValue); } } }
Source:
<code>public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { pool = new ThreadLocal<NonBlockingSslBufferPoll>() { @Override protected NonBlockingSslBufferPoll initialValue() { int threadLocalMaxPoolSize = maxPoolSize / DEFAULT_WORKER_THREAD_COUNT; if (threadLocalMaxPoolSize % DEFAULT_WORKER_THREAD_COUNT != 0) { <START> threadLocalMaxPoolSize ++; <END> } return new NonBlockingSslBufferPoll(threadLocalMaxPoolSize, preallocate, allocateDirect); } }; }</code><technical_language>nit: threadLocalMaxPoolSize++</technical_language>

Target:
public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { this(maxPoolSize, preallocate, allocateDirect, DEFAULT_WORKER_THREAD_COUNT); }
Source:
<code>public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = call.rel(1); final RelMetadataQuery mq = call.getMetadataQuery(); if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) { return; } final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder(); final List<RexNode> projects = new LinkedList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final SqlAggFunction aggregation = aggCall.getAggregation(); final SqlSplittableAggFunction splitter = Objects.requireNonNull( aggregation.unwrap(SqlSplittableAggFunction.class)); final RexNode singleton = splitter.singleton( rexBuilder, input.getRowType(), aggCall); projects.add(singleton); } final RelNode newInput = convert(input, aggregate.getTraitSet().simplify()); final RelBuilder relBuilder = call.builder(); relBuilder.push(newInput); if (!projects.isEmpty()) { projects.addAll(0, relBuilder.fields(aggregate.getGroupSet().asList())); relBuilder.project(projects); } else if (newInput.getRowType().getFieldCount() > aggregate.getRowType().getFieldCount()) { relBuilder.project(relBuilder.fields(aggregate.getGroupSet().asList())); } final RelNode newRel = relBuilder.build(); <START> call.transformTo(newRel); <END> }</code><technical_language>variable necessary</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = aggregate.getInput(); final RelMetadataQuery mq = call.getMetadataQuery(); if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) { return; } final RelBuilder relBuilder = call.builder(); final RexBuilder rexBuilder = relBuilder.getRexBuilder(); final List<RexNode> projects = new ArrayList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final SqlAggFunction aggregation = aggCall.getAggregation(); if (aggregation.getKind() == SqlKind.SUM0) { return; } final SqlSplittableAggFunction splitter = Objects.requireNonNull( aggregation.unwrap(SqlSplittableAggFunction.class)); final RexNode singleton = splitter.singleton( rexBuilder, input.getRowType(), aggCall); projects.add(singleton); } final RelNode newInput = convert(input, aggregate.getTraitSet().simplify()); relBuilder.push(newInput); if (!projects.isEmpty()) { projects.addAll(0, relBuilder.fields(aggregate.getGroupSet().asList())); relBuilder.project(projects); } else if (newInput.getRowType().getFieldCount() > aggregate.getRowType().getFieldCount()) { relBuilder.project(relBuilder.fields(aggregate.getGroupSet().asList())); } call.transformTo(relBuilder.build()); }
Source:
<code>default <U> Seq<U> flatMap(Function<? super Tuple2<K, V>, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); <START> return iterator().flatMap(mapper).toStream(); <END> }</code><technical_language>if Eclipse somehow, compiles, _probably_ safe remove</technical_language>

Target:
default <U> Seq<U> flatMap(Function<? super Tuple2<K, V>, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return (Seq<U>) iterator().flatMap(mapper).toStream(); }
Source:
<code>private void endRequest(String requestId, Exception failure) { if (requestId != null) { <START> Session session = null; <END> List<RequestInterceptor> interceptors = getInterceptors(true); for (RequestInterceptor requestInterceptor : interceptors) { if (requestInterceptor != null) { try { requestInterceptor.onEnd(requestId, session, (failure == null), failure); } catch (RequestInterruptionException e) { log.warn("Attempt to stop request from ending by an exception from the interceptor ("+requestInterceptor+"), cannot stop requests from ending though so request end continues, this may be an error: " + e.getMessage()); } catch (Exception e) { log.warn("Request interceptor ("+requestInterceptor+") failed to execute on end ("+requestId+"): " + e.getMessage()); } } } } }</code><technical_language>this removed</technical_language>

Target:
private void endRequest(String requestId, Exception failure) { if (requestId != null) { List<RequestInterceptor> interceptors = getInterceptors(true); for (RequestInterceptor requestInterceptor : interceptors) { if (requestInterceptor != null) { try { requestInterceptor.onEnd(requestId, (failure == null), failure); } catch (RequestInterruptionException e) { log.warn("Attempt to stop request from ending by an exception from the interceptor ("+requestInterceptor+"), cannot stop requests from ending though so request end continues, this may be an error: " + e.getMessage()); } catch (Exception e) { log.warn("Request interceptor ("+requestInterceptor+") failed to execute on end ("+requestId+"): " + e.getMessage()); } } } } }
Source:
<code>public Response getResponse(String descriptorAbsolutePathString) throws IOException { Response response = new Response(); response.setClonedRepositoryAbsolutePath(descriptorAbsolutePathString); List<String> commandLineArgs = Arrays.asList("validate", "-l", descriptorAbsolutePathString); try { WomtoolMain.Termination termination = WomtoolMain .runWomtool(JavaConverters.collectionAsScalaIterableConverter(commandLineArgs).asScala().toSeq()); <START> Option<String> stdout = termination.stdout(); <END> String[] split = stdout.get().split(System.lineSeparator()); List<String> strings = new ArrayList<>(); Collections.addAll(strings, split); if (strings.get(0).equals("Success!") && strings.get(1).equals("List of Workflow dependencies is:")) { response.setValid(true); handleSuccessResponse(response, strings); return response; } else { response.setValid(false); throw new IOException(); } } catch (StackOverflowError e) { response.setValid(false); return response; } }</code><technical_language>Formatting</technical_language>

Target:
public static LanguageParsingResponse getResponse(String descriptorAbsolutePathString) { LanguageParsingResponse response = new LanguageParsingResponse(); response.setClonedRepositoryAbsolutePath(descriptorAbsolutePathString); List<String> commandLineArgs = Arrays.asList("validate", "-l", descriptorAbsolutePathString); try { WomtoolMain.Termination termination = WomtoolMain.runWomtool( JavaConverters.collectionAsScalaIterableConverter(commandLineArgs).asScala().toSeq()); Option<String> stdout = termination.stdout(); String[] split = stdout.get().split(System.lineSeparator()); List<String> strings = new ArrayList<>(); Collections.addAll(strings, split); VersionTypeValidation versionTypeValidation = new VersionTypeValidation(); if (strings.get(0).equals("Success!") && strings.get(1).equals("List of Workflow dependencies is:")) { versionTypeValidation.setValid(true); response.setVersionTypeValidation(versionTypeValidation); handleSuccessResponse(response, strings); } else { versionTypeValidation.setValid(false); response.setVersionTypeValidation(versionTypeValidation); } return response; } catch (StackOverflowError e) { VersionTypeValidation versionTypeValidation = new VersionTypeValidation(); versionTypeValidation.setValid(false); response.setVersionTypeValidation(versionTypeValidation); return response; } }
Source:
<code><START> public XYPair getRightVector() { <END> return new XYPair(this.x * (xRightInverted ? -1 : 1), this.y * (yRightInverted ? -1 : 1)); }</code><technical_language>getters handle inversion... here</technical_language>

Target:
public XYPair getRightVector() { return new XYPair( this.rightJoystickAxis.x * (getRightStickXInversion() ? -1 : 1), this.rightJoystickAxis.y * (getRightStickYInversion() ? -1 : 1)); }
Source:
<code><START> public ResponseEntity<Resources<Resource<Component>>> getComponents(@RequestParam(value = "name", required = false) String name, <END> OAuth2Authentication oAuth2Authentication) { User user = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); List<Component> components = new ArrayList<>(); if ((name != null) && (!name.isEmpty())) { components.addAll(searchComponentByName(name, user)); } else { components.addAll(componentService.getComponentsForUser(user)); } List<Resource<Component>> componentResources = new ArrayList<>(); for (Component component : components) { component.setDescription(null); component.setType(null); component.setCreatedOn(null); component.setVendorNames(null); component.setReleaseIds(null); Resource<Component> componentResource = new Resource<>(component); componentResources.add(componentResource); } Resources<Resource<Component>> resources = new Resources<>(componentResources); return new ResponseEntity<>(resources, HttpStatus.OK); }</code><technical_language>information for me. parameter exact name name is working. add parameters maintain in future</technical_language>

Target:
public ResponseEntity<Resources<Resource<Component>>> getComponents(@RequestParam(value = "name", required = false) String name, OAuth2Authentication oAuth2Authentication) { User user = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); List<Component> components = new ArrayList<>(); if ((name != null) && (!name.isEmpty())) { components.addAll(searchComponentByName(name)); } else { components.addAll(componentService.getComponentsForUser(user)); } List<Resource<Component>> componentResources = new ArrayList<>(); for (Component component : components) { component.setDescription(null); component.setType(null); component.setCreatedOn(null); component.setVendorNames(null); component.setReleaseIds(null); Resource<Component> componentResource = new Resource<>(component); componentResources.add(componentResource); } Resources<Resource<Component>> resources = new Resources<>(componentResources); return new ResponseEntity<>(resources, HttpStatus.OK); }
Source:
<code>private List<BrickDetails> getBrickDetails(int size, int clientListSize, int memPoolSize) { ArrayList<BrickDetails> list = new ArrayList<BrickDetails>(); for(int i=0; i < size ; i++) { BrickDetails details = new BrickDetails(); BrickProperties props = new BrickProperties(); props.setBlockSize(blockSize); props.setPid(88888); <START> props.setMntOptions("mntOption1"); <END> details.setBrickProperties(props); details.setClients(getClientList(clientListSize)); details.setMemoryStatus(getMemoryStatus(memPoolSize)); list.add(details); } return list; }</code><technical_language>minor: create constants for pid mntOptions well, similar blockSize. remove blockSize hard coded here, if once</technical_language>

Target:
private List<BrickDetails> getBrickDetails(int size, int clientListSize, int memPoolSize) { ArrayList<BrickDetails> list = new ArrayList<BrickDetails>(); for(int i=0; i < size ; i++) { BrickDetails details = new BrickDetails(); BrickProperties props = new BrickProperties(); props.setBlockSize(14556); props.setPid(88888); props.setMntOptions("rw"); details.setBrickProperties(props); details.setClients(getClientList(clientListSize)); details.setMemoryStatus(getMemoryStatus(memPoolSize)); list.add(details); } return list; }
Source:
<code><START> public <T> ProxyableIteratorAssert<T> assertThat(Iterator<? extends T> actual) { <END> return proxy(ProxyableIteratorAssert.class, Iterator.class, actual); }</code><technical_language>return IteratorAssert, ProxyableIteratorAssert is needed Iterator assertions change object test (like extracting do Iterable assertions)</technical_language>

Target:
public <T> IteratorAssert<T> assertThat(Iterator<? extends T> actual) { return proxy(IteratorAssert.class, Iterator.class, actual); }
Source:
<code>public IBlockStateMatcher allowValuesForProperty(String name, String... values) { <START> return null; <END> }</code><technical_language>Some sort of message returned here. null return itself. a message mentioning null</technical_language>

Target:
public IBlockStateMatcher allowValuesForProperty(String name, String... values) { CraftTweakerAPI.logWarning("Cannot change allowed values for a compound blockstate matcher"); return this; }
Source:
<code>private synchronized void purge() { List<Entry> entriesToPurge = new ArrayList<>(map.values()); <START> Collections.sort(entriesToPurge, <END> Comparator.comparingLong(o -> -o.lastAccessed)); for (int index = purgeSize; index < entriesToPurge.size(); index++) { map.remove(entriesToPurge.get(index).key); } }</code><technical_language>A multi-threaded "stress test" revealed a concurrency-related problem (quite reliably -- do for previous review). work stable copies of lastAccess timestamps: private synchronized void purge() { List<Entry> entriesToPurge = new ArrayList<>(map.values()); // copy temporary field avoid concurrent updates entry.lastAccessed result in TimSort // java.lang.IllegalArgumentException: Comparison method violates general contract! for (Entry entry : entriesToPurge) { entry.lastAccessedSorting = entry.lastAccessed; } Collections.sort(entriesToPurge, Comparator.comparingLong(o -> -o.lastAccessedSorting)); for (int index = purgeSize; index < entriesToPurge.size(); index++) { map.remove(entriesToPurge.get(index).key); } }</technical_language>

Target:
private void purge() { if (lock.tryLock()) { try { List<Entry> entriesToPurge = new ArrayList<>(map.values()); for (Entry e : entriesToPurge) { e.copyAccessTime(); } Collections.sort(entriesToPurge, Comparator.comparingLong(o -> -o.lastAccessedSorting)); for (int index = purgeSize; index < entriesToPurge .size(); index++) { map.remove(entriesToPurge.get(index).key); } } finally { lock.unlock(); } } }
Source:
<code>private void drawInputLine(UiDrawer uiDrawer, float textX) { StringBuilder stringBuilder = new StringBuilder(); int width = 0; for (char c : inputLine.reverse().toString().toCharArray()) { try { <START> width += (c == ' ' ? 3 : 1) * font.getData().getGlyph(c).width; <END> if (width > MAX_WIDTH_OF_LINE) { break; } stringBuilder.append(c); } catch (NullPointerException e) { inputLine.deleteCharAt(0); } } uiDrawer.drawString(stringBuilder.reverse().toString(), textX, getLineY(20.666f), 0.5f, UiDrawer.TextAlignment.LEFT, false, Color.WHITE); inputLine.reverse(); }</code><technical_language>This line is kinda scary. condensed more readily understandable</technical_language>

Target:
private void drawInputLine(UiDrawer uiDrawer, float textX) { StringBuilder stringBuilder = new StringBuilder(); if (System.currentTimeMillis() % 2000 > 1000) { stringBuilder.append('_'); } int width = font.getData().getGlyph('_').width; for (char c : inputLine.reverse().toString().toCharArray()) { final BitmapFont.Glyph glyph = font.getData().getGlyph(c); if (glyph != null) { width += (c == ' ' ? 3 : 1) * glyph.width; if (width > MAX_WIDTH_OF_LINE) { break; } stringBuilder.append(c); } else { inputLine.deleteCharAt(0); } } uiDrawer.drawString(stringBuilder.reverse().toString(), textX, getLineY(INPUT_LINE_Y), 0.5f, UiDrawer.TextAlignment.LEFT, false, Color.WHITE); inputLine.reverse(); }
Source:
<code>public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) <START> .marshaller(ProtoStreamMarshaller.class); END> RemoteCacheManager client = new RemoteCacheManager(builder.build()); RemoteCache<String, Person> personsCache = client.administration().getOrCreateCache("people", "default"); Map<String, Person> persons = Stream.of(new Object[][]{ {"1", new Person("Oihana", "Rossignol", 2016, "Paris")}, {"2", new Person("Elaia", "Rossignol", 2018, "Paris")}, {"3", new Person("Yago", "Steiner", 2013, "Saint-Mandé")}, {"4", new Person("Alberto", "Steiner", 2016, "Paris")}}) .collect(Collectors.toMap(data -> (String) data[0], data -> (Person) data[1])); addPersonSchema(client); personsCache.putAll(persons); QueryFactory queryFactory = Search.getQueryFactory(personsCache); Query query = queryFactory.create("FROM tutorial.Person p where p.lastName = :lastName"); query.setParameter("lastName", "Rossignol"); List<Person> rossignols = query.list(); System.out.println(rossignols); client.stop(); }</code><technical_language>// need marshaller -> // need marshaller for remote query</technical_language>

Target:
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .marshaller(ProtoStreamMarshaller.class); RemoteCacheManager client = new RemoteCacheManager(builder.build()); RemoteCache<String, Person> personsCache = client.administration().getOrCreateCache("people", "default"); Map<String, Person> persons = new HashMap<>(); persons.put("1", new Person("Oihana", "Rossignol", 2016, "Paris")); persons.put("2", new Person("Elaia", "Rossignol", 2018, "Paris")); persons.put("3", new Person("Yago", "Steiner", 2013, "Saint-Mandé")); persons.put("4", new Person("Alberto", "Steiner", 2016, "Paris")); addPersonSchema(client); personsCache.putAll(persons); QueryFactory queryFactory = Search.getQueryFactory(personsCache); Query query = queryFactory.create("FROM tutorial.Person p where p.lastName = :lastName"); query.setParameter("lastName", "Rossignol"); List<Person> rossignols = query.list(); System.out.println(rossignols); client.stop(); }
Source:
<code>public ExternalIdBundle withoutScheme(ExternalScheme scheme) { Set<ExternalId> ids = new HashSet<>(externalIds.size()); <START> for (ExternalId id : externalIds) { <END> if (id.isScheme(scheme) == false) { ids.add(id); } } return create(ids); }</code><technical_language>a filtered steeam here</technical_language>

Target:
public ExternalIdBundle withoutScheme(ExternalScheme scheme) { Set<ExternalId> ids = externalIds.stream() .filter(id -> id.isNotScheme(scheme)) .collect(Collectors.toSet()); return create(ids); }
Source:
<code><START> protected boolean isShowingOnlyAvailableOffline() { <END> Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); }</code><technical_language>protected needed. Android Studio warns that. ![Screenshot 2019-03-13 17 28 17](<LINK_0></technical_language>

Target:
boolean isShowingOnlyAvailableOffline() { Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); }
Source:
<code>public void configureForMapReduce(Job job, PType<?> ptype, Path outputPath, String name) { Converter converter = getConverter(ptype); Class<?> keyClass = converter.getKeyClass(); Class<?> valueClass = Void.class; <START> if (name == null) { END> job.setOutputKeyClass(keyClass); job.setOutputValueClass(valueClass); } else { CrunchOutputs.addNamedOutput(job, name, formatBundle, keyClass, valueClass); } job.setOutputFormatClass(formatBundle.getFormatClass()); formatBundle.configure(job.getConfiguration()); }</code><technical_language>is this related [CRUNCH-82](<LINK_0> good note is safer this conditions removed</technical_language>

Target:
public void configureForMapReduce(Job job, PType<?> ptype, Path outputPath, String name) { Preconditions.checkNotNull(name, "Output name should not be null"); Converter converter = getConverter(ptype); Class<?> keyClass = converter.getKeyClass(); Class<?> valueClass = Void.class; CrunchOutputs.addNamedOutput(job, name, formatBundle, keyClass, valueClass); job.setOutputFormatClass(formatBundle.getFormatClass()); formatBundle.configure(job.getConfiguration()); }
Source:
<code><START> MolgenisValidationException translateValueTooLongViolation() <END> { ConstraintViolation constraintViolation = new ConstraintViolation("One of the values being added is too long."); return new MolgenisValidationException(singleton(constraintViolation)); }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove this of "MolgenisValidationException"; is deprecated. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
MolgenisValidationException translateValueTooLongViolation() { ConstraintViolation constraintViolation = new ConstraintViolation(VALUE_TOO_LONG_MSG); return new MolgenisValidationException(singleton(constraintViolation)); }
Source:
<code><START> public void testsHeaderNotAvailable() throws IOException { <END> MatcherAssert.assertThat( new RqFake( Arrays.asList( "GET /f?a=3", "Host: www.example.com", "Accept: text/json" ), "" ), new HmRqHeader( Matchers.not( Matchers.hasEntry("host", "fake.org") ) ) ); }</code><technical_language>@ekondrashev too, throws Exception [coding standards](www.yegor256.com/2014/04/27/typical-mistakes-in-java-code.html#test-method-names)</technical_language>

Target:
public void testsHeaderNotAvailable() throws Exception { MatcherAssert.assertThat( new RqFake( Arrays.asList( "GET /f?a=3", "Host: www.example.com", "Accept: text/json" ), "" ), new HmRqHeader( Matchers.not( Matchers.hasEntry("host", "fake.org") ) ) ); }
Source:
<code>public Object[] factory() { return new Object[] { new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OBJECT), <START> new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OFF_HEAP) <END> }; }</code><technical_language>for completeness, add BINARY</technical_language>

Target:
public Object[] factory() { return new Object[] { new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.BINARY), new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OBJECT), new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OFF_HEAP) }; }
Source:
<code>synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { <START> log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); <END> subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}updating builder with topic(s) with possible matching regex subscription(s)", logPrefix, subscriptionUpdates.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }</code><technical_language>Thanks for PR! I noticed log messages completely redundant; remove of them, combine a single log</technical_language>

Target:
synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }
Source:
<code>public int hashCode() { int hash = 7; hash = 71 * hash + (this.name != null ? this.name.hashCode() : 0); <START> return hash; <END> }</code><technical_language>Please check hashCode implementations. Please return hash code of a single referenced object HashCode.compute</technical_language>

Target:
public int hashCode() { return name.hashCode(); }
Source:
<code>private void updateCachedList(List list, List newList, String repoId){ HashMap<String, HashSet> changes = CollectionUtilities.getChangesToList(list, newList); HashSet removed = changes.get(CollectionUtilities.REMOVED_TAG); Platform.runLater(new Runnable() { @Override public void run() { list.removeAll(removed); Listable listItem = (Listable)newList.get(0); if (listItem.getClass() == TurboMilestone.class) { logNumOfUpdates(newList, "milestone(s)"); } else if (listItem.getClass() == TurboLabel.class) { logNumOfUpdates(newList, "label(s)"); } else if (listItem.getClass() == TurboUser.class) { logNumOfUpdates(newList, "collaborator(s)"); <START> } <END> ArrayList<Object> buffer = new ArrayList<>(); for (Object item : newList) { int index = list.indexOf(item); if(index != -1){ Listable old = (Listable)list.get(index); old.copyValues(item); }else{ buffer.add(item); } } list.addAll(buffer); dcHandler.writeToFile(repoId, issuesETag, collabsETag, labelsETag, milestonesETag, issueCheckTime, collaborators, labels, milestones, issues); } private void logNumOfUpdates(List newList, String type) { logger.info("Retrieved " + newList.size() + " updated " + type + " since last sync"); } }); }</code><technical_language>instanceof is better, brittle (it'll work if subclass of Turbo* classes)</technical_language>

Target:
private void updateCachedList(List list, List newList, String repoId){ HashMap<String, HashSet> changes = CollectionUtilities.getChangesToList(list, newList); HashSet removed = changes.get(CollectionUtilities.REMOVED_TAG); Platform.runLater(new Runnable() { @Override public void run() { list.removeAll(removed); Listable listItem = (Listable)newList.get(0); if (listItem instanceof TurboMilestone) { logNumOfUpdates(newList, "milestone(s)"); } else if (listItem instanceof TurboLabel) { logNumOfUpdates(newList, "label(s)"); } else if (listItem instanceof TurboUser) { logNumOfUpdates(newList, "collaborator(s)"); } ArrayList<Object> buffer = new ArrayList<>(); for (Object item : newList) { int index = list.indexOf(item); if(index != -1){ Listable old = (Listable)list.get(index); old.copyValues(item); }else{ buffer.add(item); } } list.addAll(buffer); dcHandler.writeToFile(repoId, issuesETag, collabsETag, labelsETag, milestonesETag, issueCheckTime, collaborators, labels, milestones, issues); } private void logNumOfUpdates(List newList, String type) { logger.info("Retrieved " + newList.size() + " updated " + type + " since last sync"); } }); }
Source:
<code>public void testContainerSortOnId() { <START> PackingPlan packingPlan = getFirstFitDecreasingPackingPlan(topology); <END> Assert.assertEquals(packingPlan.getContainers().size(), 2); Assert.assertEquals((long) packingPlan.getInstanceCount(), totalInstances); AssertPacking.assertNumInstances(packingPlan.getContainers(), BOLT_NAME, boltParallelism); AssertPacking.assertNumInstances(packingPlan.getContainers(), SPOUT_NAME, spoutParallelism); PackingPlan.ContainerPlan[] currentContainers = packingPlan.getContainers().toArray( new PackingPlan.ContainerPlan[1]); Assert.assertEquals(currentContainers.length, packingPlan.getContainers().size()); for (int i = 0; i < currentContainers.length; i++) { Assert.assertEquals((currentContainers[i]).getId(), i + 1); } }</code><technical_language>This is indirect test container sorting. instead write this test a dep FirstFitDecreasingPacking pass a Set of containers sortOnContainerId assert returned ordering? test utility method FirstFitDecreasingPacking code, tested in test suite/class</technical_language>

Target:
public void testContainerSortOnId() { Integer[] containerIds = {5, 4, 1, 2, 3}; Integer[] instanceIds = {1, 2, 3}; Set<PackingPlan.ContainerPlan> containers = generateContainers(containerIds, instanceIds); PackingPlan.ContainerPlan[] currentContainers = PackingUtils.sortOnContainerId(containers); Assert.assertEquals(containerIds.length, currentContainers.length); for (int i = 0; i < currentContainers.length; i++) { Assert.assertEquals((currentContainers[i]).getId(), i + 1); } }
Source:
<code><START> public void checkCompatibility() throws ServerException { <END> try { Version versionInfo = dockerConnector.getVersion(); if (!supportedVersions.contains(versionInfo.getVersion())) { throw new ServerException("Unsupported docker version " + versionInfo.getVersion()); } } catch (IOException e) { throw new ServerException("Impossible to get docker version", e); } }</code><technical_language>is public? package-private</technical_language>

Target:
void checkCompatibility() throws ServerException { try { Version versionInfo = dockerConnector.getVersion(); if (!supportedVersions.contains(versionInfo.getVersion())) { throw new ServerException("Unsupported docker version " + versionInfo.getVersion()); } } catch (IOException e) { throw new ServerException("Impossible to get docker version", e); } }
Source:
<code>private void createRepository() { if (pool.isCreateMissingRepos()) { try { final Ref head = git.getRef(Constants.HEAD); NewProjectCreatedListener.Event event = new NewProjectCreatedListener.Event() { @Override public String getProjectName() { return projectName.get(); } @Override public String getHeadName() { return head != null ? head.getName() : null; } }; <START> if (replicationQueue.onNewProjectCreated(event)) { <END> repLog.warn("Missing repository created; retry replication to " + uri); pool.reschedule(this, Destination.RetryReason.REPOSITORY_MISSING); } else { repLog.warn("Missing repository could not be created when replicating " + uri + ". You can only create missing repositories locally, over SSH or when " + "using adminUrl in replication.config. See documentation for more information."); } } catch (IOException ioe) { stateLog.error("Cannot replicate to " + uri + "; failed to create missing repository", ioe, getStatesAsArray()); } } else { stateLog.error("Cannot replicate to " + uri + "; repository not found", getStatesAsArray()); } }</code><technical_language>Call createProject instead of onNewProjectCreated</technical_language>

Target:
private void createRepository() { if (pool.isCreateMissingRepos()) { try { final Ref head = git.getRef(Constants.HEAD); if (replicationQueue.createProject(projectName, head != null ? head.getName() : null)) { repLog.warn("Missing repository created; retry replication to " + uri); pool.reschedule(this, Destination.RetryReason.REPOSITORY_MISSING); } else { repLog.warn("Missing repository could not be created when replicating " + uri + ". You can only create missing repositories locally, over SSH or when " + "using adminUrl in replication.config. See documentation for more information."); } } catch (IOException ioe) { stateLog.error("Cannot replicate to " + uri + "; failed to create missing repository", ioe, getStatesAsArray()); } } else { stateLog.error("Cannot replicate to " + uri + "; repository not found", getStatesAsArray()); } }
Source:
<code>private void close(SelectionKey key) { Transmission transmission = getTransmission(key); if (transmission != null) { logger.debug("Closing connection from {}", transmission.getConnectionId()); this.disconnected.add(transmission.getConnectionId()); this.keyMap.remove(transmission.getConnectionId()); activeConnections.set(this.keyMap.size()); try { transmission.clearReceive(); <START> transmission.clearSend(); <END> transmission.close(); } catch (IOException e) { logger.error("IOException thrown during closing of transmission with connectionId :", transmission.getConnectionId(), e); } } else { key.attach(null); key.cancel(); SocketAddress address = null; try { SocketChannel socketChannel = channel(key); address = socketChannel.socket().getRemoteSocketAddress(); socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { metrics.selectorCloseSocketErrorCount.inc(); logger.error("Exception closing connection to remote host :", address, e); } } this.metrics.selectorConnectionClosed.inc(); }</code><technical_language>I understand is else clause in line 437 below? is else</technical_language>

Target:
private void close(SelectionKey key) { Transmission transmission = getTransmission(key); if (transmission != null) { logger.debug("Closing connection from {}", transmission.getConnectionId()); this.disconnected.add(transmission.getConnectionId()); this.keyMap.remove(transmission.getConnectionId()); activeConnections.set(this.keyMap.size()); try { transmission.close(); } catch (IOException e) { logger.error("IOException thrown during closing of transmission with connectionId :", transmission.getConnectionId(), e); } } else { key.attach(null); key.cancel(); SocketAddress address = null; try { SocketChannel socketChannel = channel(key); address = socketChannel.socket().getRemoteSocketAddress(); socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { metrics.selectorCloseSocketErrorCount.inc(); logger.error("Exception closing connection to remote host :", address, e); } } this.metrics.selectorConnectionClosed.inc(); }
Source:
<code>private static void executeDeleteQuery(Connection conn, String query, int tenantId) throws SQLException { <START> <END> try (PreparedStatement ps = conn.prepareStatement(query)) { ps.setInt(1, tenantId); ps.executeUpdate(); } catch (SQLException e) { String errMsg = "Error executing query " + query + " for tenant: " + tenantId; throw new SQLException(errMsg, e); } }</code><technical_language>Remove unnecessary new line beginning of method</technical_language>

Target:
private static void executeDeleteQuery(Connection conn, String query, int tenantId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(query)) { ps.setInt(1, tenantId); ps.executeUpdate(); if (log.isDebugEnabled()) { log.debug("Deletion query : " + query + "executed for tenant :" + tenantId); } } catch (SQLException e) { String errMsg = "Error executing query " + query + " for tenant: " + tenantId; throw new SQLException(errMsg, e); } }
Source:
<code>protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); attributes.add(getTaskData().getRoot() .getMappedAttribute(BugzillaRestTaskSchema.getDefault().RESET_ASSIGNED_TO.getKey())); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); <START> if (!getTaskData().isNew()) { <END> addSelfToCC(attributes); } attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_CC)); for (TaskAttribute attribute : allAttributes.values()) { TaskAttributeMetaData properties = attribute.getMetaData(); if (TaskAttribute.KIND_PEOPLE.equals(properties.getKind())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } return attributes; }</code><technical_language>roll isNew check addSelfToCC method</technical_language>

Target:
protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); attributes.add(getTaskData().getRoot() .getMappedAttribute(BugzillaRestTaskSchema.getDefault().RESET_ASSIGNED_TO.getKey())); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); addSelfToCC(attributes); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_CC)); for (TaskAttribute attribute : allAttributes.values()) { TaskAttributeMetaData properties = attribute.getMetaData(); if (TaskAttribute.KIND_PEOPLE.equals(properties.getKind())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } return attributes; }
Source:
<code>public void testRestartFailedTask() throws Exception { int numTasks = 1; Map<String, String> connectorProps = new HashMap<>(); connectorProps.put(CONNECTOR_CLASS_CONFIG, MonitorableSourceConnector.class.getName()); connectorProps.put(TASKS_MAX_CONFIG, Objects.toString(numTasks)); connectorProps.put(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG, "nobrokerrunningatthisaddress"); waitForCondition(() -> assertWorkersUp(NUM_WORKERS).orElse(false), <START> WORKER_SETUP_DURATION_MS, "Initial group of workers di not start in time."); <END> connect.configureConnector(CONNECTOR_NAME, connectorProps); waitForCondition(() -> assertConnectorTasksFailed(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks did not fail in time"); connectorProps.remove(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG); connect.configureConnector(CONNECTOR_NAME, connectorProps); String taskRestartEndpoint = connect.endpointForResource( String.format("connectors/%s/tasks/0/restart", CONNECTOR_NAME)); connect.executePost(taskRestartEndpoint, "", Collections.emptyMap()); waitForCondition(() -> assertConnectorAndTasksRunning(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks are not all in running state."); }</code><technical_language>suggestion WORKER_SETUP_DURATION_MS, "Initial group of workers start in time.");</technical_language>

Target:
public void testRestartFailedTask() throws Exception { int numTasks = 1; Map<String, String> connectorProps = new HashMap<>(); connectorProps.put(CONNECTOR_CLASS_CONFIG, MonitorableSourceConnector.class.getName()); connectorProps.put(TASKS_MAX_CONFIG, Objects.toString(numTasks)); connectorProps.put(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG, "nobrokerrunningatthisaddress"); waitForCondition(() -> assertWorkersUp(NUM_WORKERS).orElse(false), WORKER_SETUP_DURATION_MS, "Initial group of workers did not start in time."); connect.configureConnector(CONNECTOR_NAME, connectorProps); waitForCondition(() -> assertConnectorTasksFailed(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks did not fail in time"); connectorProps.remove(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG); connect.configureConnector(CONNECTOR_NAME, connectorProps); String taskRestartEndpoint = connect.endpointForResource( String.format("connectors/%s/tasks/0/restart", CONNECTOR_NAME)); connect.executePost(taskRestartEndpoint, "", Collections.emptyMap()); waitForCondition(() -> assertConnectorAndTasksRunning(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks are not all in running state."); }