auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public PrimitiveLongIterator query( IndexQuery... predicates ) throws IndexNotApplicableKernelException { if ( predicates.length != 1 ) { throw new UnsupportedOperationException(); } <START> ensureOpenSeekerClosed(); <END> IndexQuery predicate = predicates[0]; switch ( predicate.type() ) { case exists: treeKeyFrom.initAsLowest(); treeKeyTo.initAsHighest(); return startSeekForInitializedRange(); case exact: ExactPredicate exactPredicate = (ExactPredicate) predicate; Object[] values = new Object[] {exactPredicate.value()}; treeKeyFrom.from( Long.MIN_VALUE, values ); treeKeyTo.from( Long.MAX_VALUE, values ); return startSeekForInitializedRange(); case rangeNumeric: NumberRangePredicate rangePredicate = (NumberRangePredicate) predicate; treeKeyFrom.from( rangePredicate.fromInclusive() ? Long.MIN_VALUE : Long.MAX_VALUE, new Object[] {rangePredicate.from()} ); treeKeyFrom.entityIdIsSpecialTieBreaker = true; treeKeyTo.from( rangePredicate.toInclusive() ? Long.MAX_VALUE : Long.MIN_VALUE, new Object[] {rangePredicate.to()} ); treeKeyTo.entityIdIsSpecialTieBreaker = true; return startSeekForInitializedRange(); default: throw new IllegalArgumentException( "IndexQuery of type " + predicate.type() + " is not supported." ); } }</code><technical_language>is reason of this limitation</technical_language>

Target:
public PrimitiveLongIterator query( IndexQuery... predicates ) throws IndexNotApplicableKernelException { if ( predicates.length != 1 ) { throw new UnsupportedOperationException(); } IndexQuery predicate = predicates[0]; switch ( predicate.type() ) { case exists: treeKeyFrom.initAsLowest(); treeKeyTo.initAsHighest(); return startSeekForInitializedRange(); case exact: ExactPredicate exactPredicate = (ExactPredicate) predicate; Value[] values = new Value[] {exactPredicate.value()}; treeKeyFrom.from( Long.MIN_VALUE, values ); treeKeyTo.from( Long.MAX_VALUE, values ); return startSeekForInitializedRange(); case rangeNumeric: NumberRangePredicate rangePredicate = (NumberRangePredicate) predicate; treeKeyFrom.from( rangePredicate.fromInclusive() ? Long.MIN_VALUE : Long.MAX_VALUE, new Value[] {Values.of( rangePredicate.from() )} ); treeKeyFrom.entityIdIsSpecialTieBreaker = true; treeKeyTo.from( rangePredicate.toInclusive() ? Long.MAX_VALUE : Long.MIN_VALUE, new Value[] {Values.of( rangePredicate.to() )} ); treeKeyTo.entityIdIsSpecialTieBreaker = true; return startSeekForInitializedRange(); default: throw new IllegalArgumentException( "IndexQuery of type " + predicate.type() + " is not supported." ); } }
Source:
<code>public Optional<MovementSpeedData> build(DataView container) throws InvalidDataException { <START> double walkSpeed = getData(container, Keys.WALKING_SPEED); <END> double flySpeed = getData(container, Keys.FLYING_SPEED); MovementSpeedData movementSpeedData = new SpongeMovementSpeedData(walkSpeed, flySpeed); return Optional.of(movementSpeedData); }</code><technical_language>If container values, return empty</technical_language>

Target:
public Optional<MovementSpeedData> build(DataView container) throws InvalidDataException { if (container.contains(Keys.WALKING_SPEED.getQuery()) && container.contains(Keys.FLYING_SPEED.getQuery())) { double walkSpeed = getData(container, Keys.WALKING_SPEED); double flySpeed = getData(container, Keys.FLYING_SPEED); MovementSpeedData movementSpeedData = new SpongeMovementSpeedData(walkSpeed, flySpeed); return Optional.of(movementSpeedData); } return Optional.empty(); }
Source:
<code>protected View getWelcomeView() { <START> return new MultiBranchProjectEmptyView(this); <END> }</code><technical_language>bug: I meant new OrganizationFolderEmptyView(this), getPrimaryView use</technical_language>

Target:
protected View getWelcomeView() { return new OrganizationFolderEmptyView(this); }
Source:
<code>public void visitJsonResultForm(Query query) { <START> out.print("JSON {"); <END> List<String> terms = new ArrayList<>(); for (Map.Entry<String, Object> entry : query.jsonMapping.entrySet()) { terms.add(String.format("\"%s\" : %s ", entry.getKey(), entry.getValue())); } out.print(String.join(",", terms)); out.print(" }"); out.newline(); }</code><technical_language>qparse tool serialization (and parses result again)</technical_language>

Target:
public void visitJsonResultForm(Query query) { out.println("JSON {"); out.incIndent(BLOCK_INDENT); out.incIndent(BLOCK_INDENT); boolean first = true; for (Map.Entry<String, Node> entry : query.getJsonMapping().entrySet()) { String field = entry.getKey(); Node value = entry.getValue(); if ( ! first ) out.println(" ,"); first = false; out.print('"'); out.print(field); out.print('"'); out.print(" : "); out.pad(15); out.print(FmtUtils.stringForNode(value, prologue)); } out.decIndent(BLOCK_INDENT); out.decIndent(BLOCK_INDENT); out.print(" }"); out.newline(); }
Source:
<code>private void checkSetClazz(PortContext context) { <START> if (clazz != null) { <END> clazz = context.getValue(Context.PortContext.TUPLE_CLASS); } else if (clazz != context.getValue(Context.PortContext.TUPLE_CLASS)) { logger.error("Input/Output ports must have same schema class. != {}", clazz, context.getValue(Context.PortContext.TUPLE_CLASS)); } }</code><technical_language>clazz==null?</technical_language>

Target:
private void checkSetClazz(PortContext context) { if (clazz == null) { clazz = context.getValue(Context.PortContext.TUPLE_CLASS); } else if (clazz != context.getValue(Context.PortContext.TUPLE_CLASS)) { logger.error("Input/Output ports must have same schema class. != {}", clazz, context.getValue(Context.PortContext.TUPLE_CLASS)); } }
Source:
<code>private PlaylistTab() { <START> this.playlistName = "<no-name>"; this.playlistId = -1; this.playlistType = LocalItemType.PLAYLIST_LOCAL_ITEM; this.playlistServiceId = -1; this.playlistUrl = "<no-url>"; <END> }</code><technical_language>suggestion this(-1, "<no-name>")</technical_language>

Target:
private PlaylistTab() { this(-1, "<no-name>"); }
Source:
<code>static ImmutableSet.Builder<Type> omitIllegalBeanTypes(Set<Type> types, EnhancedAnnotated<?, ?> annotated) { <START> ImmutableSet.Builder<Type> builder = ImmutableSet.builder(); <END> for (Type type : types) { if (isIllegalBeanType(type)) { MetadataLogger.LOG.illegalBeanTypeIgnored(type, annotated); } else { builder.add(type); } } return builder; }</code><technical_language>This a premature optimization this: case of illegal bean type is rare (the input set is returned of time) default iterating types checking if of is invalid. If invalid type is start building new set</technical_language>

Target:
static ImmutableSet.Builder<Type> omitIllegalBeanTypes(Set<Type> types, EnhancedAnnotated<?, ?> annotated) { ImmutableSet.Builder<Type> builder = ImmutableSet.builder(); for (Type type : types) { if (Types.isIllegalBeanType(type)) { MetadataLogger.LOG.illegalBeanTypeIgnored(type, annotated); } else { builder.add(type); } } return builder; }
Source:
<code>private static StepVideo parseVideo(JSONObject jVideo) throws JSONException { StepVideo video = new StepVideo(); try { JSONArray jEncodings = jVideo.getJSONArray("encoding"); for (int i = 0; i < jEncodings.length(); i++) { video.addEncoding(parseVideoEncoding(jEncodings.getJSONObject(i))); } } catch (JSONException e) { <START> e.printStackTrace(); <END> } video.setThumbnail(parseVideoThumbnail(jVideo.getJSONObject("thumbnail"))); return video; }</code><technical_language>Log</technical_language>

Target:
private static StepVideo parseVideo(JSONObject jVideo) throws JSONException { StepVideo video = new StepVideo(); try { JSONArray jEncodings = jVideo.getJSONArray("encoding"); for (int i = 0; i < jEncodings.length(); i++) { video.addEncoding(parseVideoEncoding(jEncodings.getJSONObject(i))); } } catch (JSONException e) { e.printStackTrace(); Log.e("JSONHelper parseVideo", "Error parsing video API response"); } video.setThumbnail(parseVideoThumbnail(jVideo.getJSONObject("thumbnail"))); return video; }
Source:
<code>static void asyncDml(DatabaseClient client) throws InterruptedException, ExecutionException, TimeoutException { ExecutorService executor = Executors.newSingleThreadExecutor(); ApiFuture<Long> rowCount = client <START> .runAsync() .runAsync( <END> new AsyncWork<Long>() { @Override public ApiFuture<Long> doWorkAsync(TransactionContext txn) { String sql = "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES " + "(12, 'Melissa', 'Garcia'), " + "(13, 'Russell', 'Morales'), " + "(14, 'Jacqueline', 'Long'), " + "(15, 'Dylan', 'Shaw')"; return txn.executeUpdateAsync(Statement.of(sql)); } }, executor); System.out.printf("%d records inserted.%n", rowCount.get()); executor.shutdown(); }</code><technical_language>Do want 2 of these</technical_language>

Target:
static void asyncDml(DatabaseClient client) throws InterruptedException, ExecutionException, TimeoutException { ExecutorService executor = Executors.newSingleThreadExecutor(); AsyncRunner runner = client.runAsync(); ApiFuture<Long> rowCount = runner.runAsync( new AsyncWork<Long>() { @Override public ApiFuture<Long> doWorkAsync(TransactionContext txn) { String sql = "INSERT INTO Singers (SingerId, FirstName, LastName) VALUES " + "(12, 'Melissa', 'Garcia'), " + "(13, 'Russell', 'Morales'), " + "(14, 'Jacqueline', 'Long'), " + "(15, 'Dylan', 'Shaw')"; return txn.executeUpdateAsync(Statement.of(sql)); } }, executor); System.out.printf("%d records inserted.%n", rowCount.get()); executor.shutdown(); }
Source:
<code>public OrcUpdatablePageSource( Optional<ShardRewriter> shardRewriter, OrcBatchRecordReader recordReader, OrcPageSource parentPageSource) { <START> this.rowsToDelete = new BitSet(toIntExact(recordReader.getFileRowCount())); <END> this.shardRewriter = requireNonNull(shardRewriter, "shardRewriter is null"); this.parentPageSource = requireNonNull(parentPageSource, "parentPageSource is null"); }</code><technical_language>move assignment shardRewriter align on-stack declaration. requireNonNull recordReader</technical_language>

Target:
public OrcUpdatablePageSource( Optional<ShardRewriter> shardRewriter, OrcBatchRecordReader recordReader, OrcPageSource parentPageSource) { this.shardRewriter = requireNonNull(shardRewriter, "shardRewriter is null"); requireNonNull(recordReader, "recordReader is null"); this.parentPageSource = requireNonNull(parentPageSource, "parentPageSource is null"); this.rowsToDelete = new BitSet(toIntExact(recordReader.getFileRowCount())); }
Source:
<code>public VdTree parse(InputStream is, StringBuilder vdErrorLog) { try { final VdTree tree = new VdTree(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(new ContentHandler() { String space = " "; @Override public void setDocumentLocator(Locator locator) { } @Override public void startDocument() throws SAXException { } @Override public void endDocument() throws SAXException { } @Override public void startPrefixMapping(String s, String s2) throws SAXException { } @Override public void endPrefixMapping(String s) throws SAXException { } @Override public void startElement(String s, String s2, String s3, Attributes attributes) throws SAXException { String name = s3; if (tagSwitch.containsKey(name)) { tagSwitch.get(name).parse(tree, attributes); } space += " "; } @Override public void endElement(String s, String s2, String s3) throws SAXException { space = space.substring(1); } @Override public void characters(char[] chars, int i, int i2) throws SAXException { } @Override public void ignorableWhitespace(char[] chars, int i, int i2) throws SAXException { } @Override public void processingInstruction(String s, String s2) throws SAXException { } @Override public void skippedEntity(String s) throws SAXException { } }); xr.parse(new InputSource(is)); tree.parseFinish(); return tree; } catch (Exception e) { <START> vdErrorLog.append("Exception in parsing XML file " + e.getMessage()); <END> return null; } }</code><technical_language>colon newline exception: Exception while parsing XML file:\n</technical_language>

Target:
public VdTree parse(InputStream is, StringBuilder vdErrorLog) { try { final VdTree tree = new VdTree(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(new ContentHandler() { String space = " "; @Override public void setDocumentLocator(Locator locator) { } @Override public void startDocument() throws SAXException { } @Override public void endDocument() throws SAXException { } @Override public void startPrefixMapping(String s, String s2) throws SAXException { } @Override public void endPrefixMapping(String s) throws SAXException { } @Override public void startElement(String s, String s2, String s3, Attributes attributes) throws SAXException { String name = s3; if (tagSwitch.containsKey(name)) { tagSwitch.get(name).parse(tree, attributes); } space += " "; } @Override public void endElement(String s, String s2, String s3) throws SAXException { space = space.substring(1); } @Override public void characters(char[] chars, int i, int i2) throws SAXException { } @Override public void ignorableWhitespace(char[] chars, int i, int i2) throws SAXException { } @Override public void processingInstruction(String s, String s2) throws SAXException { } @Override public void skippedEntity(String s) throws SAXException { } }); xr.parse(new InputSource(is)); tree.parseFinish(); return tree; } catch (Exception e) { vdErrorLog.append("Exception while parsing XML file:\n" + e.getMessage()); return null; } }
Source:
<code>public Object methodInvoke(Method method, Object instance, Object... convertedArgs) throws Throwable { try { return method.invoke(instance, convertedArgs); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } else { throw e.getTargetException(); } } catch (IllegalArgumentException e) { throw new RuntimeException("Bad call of: " + method.getDeclaringClass().getName() + "." + method.getName() <START> + ". On instance of: " + ((instance == null) ? "null" : instance.getClass().getName()), e); <END> } }</code><technical_language>I nicer generate a String 'On instance of...' 'Of class: ...' add message</technical_language>

Target:
public Object methodInvoke(Method method, Object instance, Object... convertedArgs) throws Throwable { try { return method.invoke(instance, convertedArgs); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw e.getCause(); } else { throw e.getTargetException(); } } catch (IllegalArgumentException e) { throw new RuntimeException("Bad call of: " + method.getDeclaringClass().getName() + "." + method.getName() + "." + ((instance == null) ? "" : " On instance of: " + instance.getClass().getName()), e); } catch (Exception e){ String methodName = MethodExecutionResult.methodToString(method); throw new RuntimeException("Exception when invoking: " + method.getDeclaringClass().getName() + "." + methodName + "." + ((instance == null) ? "" : " On instance of: " + instance.getClass().getName()), e); } }
Source:
<code>public Server gRpcServer( @Value("${grpc.server.port:0}") final int port, final Set<BindableService> services, final List<ServerInterceptor> serverInterceptors ) { final NettyServerBuilder builder = NettyServerBuilder.forPort( port == RANDOM_PORT <START> ? SocketUtils.findAvailableTcpPort() <END> : port ); services .stream() .map(BindableService::bindService) .map(serviceDefinition -> ServerInterceptors.intercept(serviceDefinition, serverInterceptors)) .forEach(builder::addService); return builder.build(); }</code><technical_language>prefer set port 0 socket bind ephemeral port. chance of collision way</technical_language>

Target:
public Server gRpcServer( @Value("${grpc.server.port:0}") final int port, final Set<BindableService> services, final List<ServerInterceptor> serverInterceptors ) { final NettyServerBuilder builder = NettyServerBuilder.forPort(port); services .stream() .map(BindableService::bindService) .map(serviceDefinition -> ServerInterceptors.intercept(serviceDefinition, serverInterceptors)) .forEach(builder::addService); return builder.build(); }
Source:
<code>public boolean hasSpaceForSnapthosts(VM vm) { Map<storage_domains, Integer> map = mapStorageDomainsToNumOfDisks(vm); Integer minSnapshotSize = Config.<Integer> GetValue(ConfigValues.InitStorageSparseSizeInGB); <START> for (storage_domains domain : map.keySet()) { <END> if (!StorageDomainSpaceChecker.hasSpaceForRequest(domain, minSnapshotSize * map.get(domain))) { log.error("not enough space to create snapshot on domain " + domain.getId()); return false; } } return true; }</code><technical_language>Please iterate entrySet</technical_language>

Target:
public boolean hasSpaceForSnapthosts(VM vm) { Integer minSnapshotSize = Config.<Integer> GetValue(ConfigValues.InitStorageSparseSizeInGB); for (Entry<storage_domains, Integer> e : mapStorageDomainsToNumOfDisks(vm).entrySet()) { if (!StorageDomainSpaceChecker.hasSpaceForRequest(e.getKey(), minSnapshotSize * e.getValue())) { log.error("not enough space to create snapshot on domain " + e.getKey().getId()); return false; } } return true; }
Source:
<code>@Override public Future<RecordMetadata> send(ProducerRecord<K, V> record, @Nullable Callback callback) { <START> TraceContextOrSamplingFlags traceContextOrSamplingFlags = extractor.extract(record.headers()); <END> final Span span; if (traceContextOrSamplingFlags != null) { span = tracing.tracer().nextSpan(traceContextOrSamplingFlags); } else { span = tracing.tracer().nextSpan(); } tracing.propagation().keys().forEach(key -> record.headers().remove(key)); injector.inject(span.context(), record.headers()); if (!span.isNoop()) { if (record.key() instanceof String && !"".equals(record.key())) { span.tag(KafkaTags.KAFKA_KEY_TAG, record.key().toString()); } if (remoteServiceName != null) { span.remoteServiceName(remoteServiceName); } span.tag(KafkaTags.KAFKA_TOPIC_TAG, record.topic()).name("send").kind(Kind.PRODUCER).start(); } try (Tracer.SpanInScope ws = tracing.tracer().withSpanInScope(span)) { return delegate.send(record, new TracingCallback(span, callback)); } catch (RuntimeException | Error e) { span.error(e).finish(); throw e; } }</code><technical_language>hmm this for producer? This adds overhead..</technical_language>

Target:
@Override public Future<RecordMetadata> send(ProducerRecord<K, V> record, @Nullable Callback callback) { final Span span; final TraceContext maybeParent = tracing.currentTraceContext().get(); if (maybeParent == null && record.headers().toArray().length > 0) { TraceContextOrSamplingFlags traceContextOrSamplingFlags = extractor.extract(record.headers()); span = tracing.tracer().nextSpan(traceContextOrSamplingFlags); } else { span = tracing.tracer().nextSpan(); } tracing.propagation().keys().forEach(key -> record.headers().remove(key)); injector.inject(span.context(), record.headers()); if (!span.isNoop()) { if (record.key() instanceof String && !"".equals(record.key())) { span.tag(KafkaTags.KAFKA_KEY_TAG, record.key().toString()); } if (remoteServiceName != null) span.remoteServiceName(remoteServiceName); span.tag(KafkaTags.KAFKA_TOPIC_TAG, record.topic()).name("send").kind(Kind.PRODUCER).start(); } try (Tracer.SpanInScope ws = tracing.tracer().withSpanInScope(span)) { return delegate.send(record, new TracingCallback(span, callback)); } catch (RuntimeException | Error e) { span.error(e).finish(); throw e; } }
Source:
<code>public CookieBuilder withCustomValue( String name, String value ) { <START> this.custom = StringUtils.isNoneBlank( name, value ) ? name + "=" + value : null; <END> return this; }</code><technical_language>a user I expect next code work: cb.withCustomValue("key1", "val1").withCustomValue("key2", "val2") 2nd invocation override</technical_language>

Target:
public CookieBuilder withCustomValue( String name, String value ) { if( StringUtils.isNoneBlank( name, value ) ) { this.customs.add( name + "=" + value ); } return this; }
Source:
<code>public void seekToSegment(long entryId, SeekErrorRule errorRule) throws NoSuchOffsetException, IOException { assert(entryId >= 0); synchronized(PersistentBinaryDeque.this) { PBDSegment<M> seekSegment = findSegmentWithEntry(entryId, errorRule); moveToValidSegment(); if (m_segment.segmentIndex() == seekSegment.segmentIndex()) { <START> if (m_segment != null && m_segment.getReader(m_cursorId) != null) { <END> m_numRead -= m_segment.getReader(m_cursorId).readIndex(); m_segment.getReader(m_cursorId).close(); m_segment.openForRead(m_cursorId); } } else { if (m_segment.segmentIndex() > seekSegment.segmentIndex()) { for (PBDSegment<M> curr : m_segments.tailMap(seekSegment.segmentIndex(), true).values()) { if (curr.segmentIndex() > m_segment.segmentIndex()) { break; } PBDSegmentReader<M> currReader = curr.getReader(m_cursorId); if (curr.segmentIndex() == m_segment.segmentIndex()) { if (currReader != null) { m_numRead -= currReader.readIndex(); } } else { m_numRead -= curr.getNumEntries(); } if (currReader != null) { currReader.close(); } } } else { PBDSegmentReader<M> segmentReader = m_segment.getReader(m_cursorId); m_numRead += m_segment.getNumEntries(); if (segmentReader != null) { m_numRead -= segmentReader.readIndex(); segmentReader.close(); } for (PBDSegment<M> curr : m_segments.tailMap(m_segment.segmentIndex(), false).values()) { if (curr.segmentIndex() == seekSegment.segmentIndex()) { break; } m_numRead += curr.getNumEntries(); } } m_segment = seekSegment; } } }</code><technical_language>m_segment null here? check this invoking m_segment.segmentIndex</technical_language>

Target:
public void seekToSegment(long entryId, SeekErrorRule errorRule) throws NoSuchOffsetException, IOException { assert(entryId >= 0); synchronized(PersistentBinaryDeque.this) { PBDSegment<M> seekSegment = findSegmentWithEntry(entryId, errorRule); moveToValidSegment(); if (m_segment.segmentIndex() == seekSegment.segmentIndex()) { if (m_segment.getReader(m_cursorId) != null) { m_numRead -= m_segment.getReader(m_cursorId).readIndex(); m_segment.getReader(m_cursorId).close(); m_segment.openForRead(m_cursorId); } } else { if (m_segment.segmentIndex() > seekSegment.segmentIndex()) { for (PBDSegment<M> curr : m_segments.tailMap(seekSegment.segmentIndex(), true).values()) { if (curr.segmentIndex() > m_segment.segmentIndex()) { break; } PBDSegmentReader<M> currReader = curr.getReader(m_cursorId); if (curr.segmentIndex() == m_segment.segmentIndex()) { if (currReader != null) { m_numRead -= currReader.readIndex(); } } else { m_numRead -= curr.getNumEntries(); } if (currReader != null) { currReader.close(); } } } else { PBDSegmentReader<M> segmentReader = m_segment.getReader(m_cursorId); m_numRead += m_segment.getNumEntries(); if (segmentReader != null) { m_numRead -= segmentReader.readIndex(); segmentReader.close(); } for (PBDSegment<M> curr : m_segments.tailMap(m_segment.segmentIndex(), false).values()) { if (curr.segmentIndex() == seekSegment.segmentIndex()) { break; } m_numRead += curr.getNumEntries(); } } m_segment = seekSegment; } } }
Source:
<code>public int getInt(int col) { <START> return col == 0 ? PG_TYPE_OIDS.get(row) : col == 4 ? PgOIDs.PG_PUBLIC_OID : 0; <END> }</code><technical_language>sparse array</technical_language>

Target:
public int getInt(int col) { return intValues[col]; }
Source:
<code>public void visit(final SnmpConfigVisitor visitor) { <START> if ((visitor.getLocation() != null) && (!visitor.getLocation().equals(m_location))) { <END> return; } visitor.visitDefinition(this); visitor.visitSpecifics(this.getSpecifics()); visitor.visitSpecificsFinished(); visitor.visitRanges(this.getRanges()); visitor.visitRangesFinished(); visitor.visitIpMatches(this.getIpMatches()); visitor.visitIpMatchesFinished(); visitor.visitDefinitionFinished(); }</code><technical_language>This logic is in wrong place, visitor implementation decide if wants visit a definition not</technical_language>

Target:
public void visit(final SnmpConfigVisitor visitor) { visitor.visitDefinition(this); visitor.visitSpecifics(this.getSpecifics()); visitor.visitSpecificsFinished(); visitor.visitRanges(this.getRanges()); visitor.visitRangesFinished(); visitor.visitIpMatches(this.getIpMatches()); visitor.visitIpMatchesFinished(); visitor.visitDefinitionFinished(); }
Source:
<code><START> public ReusableSubprocessTaskExecutionSet() { <END> this(new CalledElement(), new IsCase(), new Independent(), new WaitForCompletion(), new IsAsync(), new SLADueDate(), new AdHocAutostart(), new IsMultipleInstance(false), new MultipleInstanceExecutionMode(false), new MultipleInstanceCollectionInput(), new MultipleInstanceDataInput(), new MultipleInstanceCollectionOutput(), new MultipleInstanceDataOutput(), new MultipleInstanceCompletionCondition(), new OnEntryAction(new ScriptTypeListValue().addValue(new ScriptTypeValue("java", ""))), new OnExitAction(new ScriptTypeListValue().addValue(new ScriptTypeValue("java", "")))); }</code><technical_language>extend BaseSubprocessExecutionSet? a query</technical_language>

Target:
public ReusableSubprocessTaskExecutionSet() { this(new CalledElement(), new IsCase(), new Independent(), new AbortParent(), new WaitForCompletion(), new IsAsync(), new AdHocAutostart(), new IsMultipleInstance(false), new MultipleInstanceExecutionMode(false), new MultipleInstanceCollectionInput(), new MultipleInstanceDataInput(), new MultipleInstanceCollectionOutput(), new MultipleInstanceDataOutput(), new MultipleInstanceCompletionCondition(), new OnEntryAction(new ScriptTypeListValue().addValue(new ScriptTypeValue("java", ""))), new OnExitAction(new ScriptTypeListValue().addValue(new ScriptTypeValue("java", ""))), new SLADueDate()); }
Source:
<code>public LocalDB readLocalDB(final Path localDBFile) throws Exception { <START> if (localDBFile.toFile().isDirectory()) <END> throw new Exception("Invalid Arguments: Path provided is directory and not a file: " + localDBFile.toString()); if (!localDBFile.toFile().exists()) return new LocalDB(new ArrayList<>()); try (FileReader reader = new FileReader(localDBFile.toFile())) { LocalDB localDB = GsonJsonSerializer.getGson().fromJson(reader, LocalDB.class); String columnfamilyName = localDBFile.getParent().toFile().getName(); String keyspaceName = localDBFile.getParent().getParent().toFile().getName(); localDB.getLocalDb().stream().forEach(localDBEntry -> { localDBEntry.getFileUploadResult().setColumnFamilyName(columnfamilyName); localDBEntry.getFileUploadResult().setKeyspaceName(keyspaceName); }); if (logger.isDebugEnabled()) logger.debug("Local DB: {}", localDB); return localDB; } }</code><technical_language>Do need throw this exception ourselves, Java throw exception for attempt construct a FileReader below</technical_language>

Target:
public LocalDB readLocalDB(final Path localDBFile) throws Exception { if (!localDBFile.toFile().exists()) return new LocalDB(new ArrayList<>()); try (FileReader reader = new FileReader(localDBFile.toFile())) { LocalDB localDB = GsonJsonSerializer.getGson().fromJson(reader, LocalDB.class); String columnfamilyName = localDBFile.getParent().toFile().getName(); String keyspaceName = localDBFile.getParent().getParent().toFile().getName(); localDB.getLocalDBEntries().forEach(localDBEntry -> { localDBEntry.getFileUploadResult().setColumnFamilyName(columnfamilyName); localDBEntry.getFileUploadResult().setKeyspaceName(keyspaceName); }); if (logger.isDebugEnabled()) logger.debug("Local DB: {}", localDB); return localDB; } }
Source:
<code>private static boolean isOptionalPrimitive(Schema schema) { return schema.getType().equals(Schema.Type.UNION) && schema.getTypes().size() == 2 && <START> schema.getTypes().get(0).getType().equals(Schema.Type.NULL) && <END> (isPrimitive(schema.getTypes().get(1)) || isPrimitiveArray(schema.getTypes().get(1))); }</code><technical_language>in union types, is NULL type guaranteed actual type</technical_language>

Target:
public static boolean isOptionalPrimitive(Schema schema) { return schema.getType().equals(Schema.Type.UNION) && schema.getTypes().size() == 2 && ( (schema.getTypes().get(0).getType().equals(Schema.Type.NULL) && (isPrimitive(schema.getTypes().get(1)) || isPrimitiveArray(schema.getTypes().get(1)))) || (schema.getTypes().get(1).getType().equals(Schema.Type.NULL) && (isPrimitive(schema.getTypes().get(0)) || isPrimitiveArray(schema.getTypes().get(0)))) ); }
Source:
<code>public void deserializeAndAddExtension(WalletExtension extension, byte[] data) throws Exception { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { <START> if (extensions.containsKey(id)) <END> return; else { extension.deserializeWalletExtension(this, data); addExtension(extension); } } finally { lock.unlock(); } }</code><technical_language>Missing { }</technical_language>

Target:
public void deserializeAndAddExtension(WalletExtension extension, byte[] data) throws Exception { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { if (extensions.containsKey(id)) { return; } else { extension.deserializeWalletExtension(this, data); addExtension(extension); } } finally { lock.unlock(); } }
Source:
<code>private synchronized void solvingTerminated() { <START> solverManager.getProblemIdToSolverJobMap().remove(problemId); solverStatus = SolverStatus.NOT_SOLVING; terminatedLatch.countDown(); <END> }</code><technical_language>suggestion SolverStatus previousSolverStatus = solverStatus.getAndSet(NOT_SOLVING); if (previousSolverStatus != NOT_SOLVING) { solverManager.getProblemIdToSolverJobMap().remove(problemId); terminatedLatch.countDown(); }</technical_language>

Target:
private void solvingTerminated() { solverStatusReference.set(SolverStatus.NOT_SOLVING); solverManager.getProblemIdToSolverJobMap().remove(problemId); terminatedLatch.countDown(); }
Source:
<code>private String retrievePomContentFromHpi() throws PluginSourcesUnavailableException { InputStream pluginUrlStream = null; ZipInputStream zin = null; try { pluginUrlStream = new URL(hpiRemoteUrl).openStream(); zin = new ZipInputStream(pluginUrlStream); ZipEntry zipEntry = zin.getNextEntry(); while(!zipEntry.getName().startsWith("META-INF/maven") || !zipEntry.getName().endsWith("pom.xml")){ zin.closeEntry(); zipEntry = zin.getNextEntry(); } StringBuilder sb = new StringBuilder(); byte[] buf = new byte[1024]; int n; while ((n = zin.read(buf, 0, 1024)) > -1) sb.append(new String(buf, 0, n)); return sb.toString(); } catch (Exception e) { System.err.println("Error : " + e.getMessage()); throw new PluginSourcesUnavailableException("Problem while retrieving pom content in hpi !", e); } finally { <START> IOUtils.closeQuietly(pluginUrlStream); <END> IOUtils.closeQuietly(zin); } }</code><technical_language>closeQuietly a good in Java 6, try-with-resources</technical_language>

Target:
private String retrievePomContentFromHpi() throws PluginSourcesUnavailableException { try (InputStream pluginUrlStream = new URL(hpiRemoteUrl).openStream(); ZipInputStream zin = new ZipInputStream(pluginUrlStream)) { ZipEntry zipEntry = zin.getNextEntry(); while(!zipEntry.getName().startsWith("META-INF/maven") || !zipEntry.getName().endsWith("pom.xml")){ zin.closeEntry(); zipEntry = zin.getNextEntry(); } StringBuilder sb = new StringBuilder(); byte[] buf = new byte[1024]; int n; while ((n = zin.read(buf, 0, 1024)) > -1) sb.append(new String(buf, 0, n)); return sb.toString(); } catch (Exception e) { System.err.println("Error : " + e.getMessage()); throw new PluginSourcesUnavailableException("Problem while retrieving pom content in hpi !", e); } }
Source:
<code>public void setBinaryData(Object answer) { stringAnswer = (String) answer; if (stringAnswer != null && !stringAnswer.isEmpty()) { String[] parts = stringAnswer.split(" "); answerDisplay.setText(getContext().getString( R.string.gps_result, formatGps(Double.parseDouble(parts[0]), "lat"), formatGps(Double.parseDouble(parts[1]), "lon"), truncateDouble(parts[2]), truncateDouble(parts[3]) )); <START> answerDisplay.setText(String.format(getContext().getString(R.string.gps_result), <END> formatGps(Double.parseDouble(parts[0]), "lat"), formatGps(Double.parseDouble(parts[1]), "lon"), truncateDouble(parts[2]), truncateDouble(parts[3]))); } else { answerDisplay.setText(""); } updateButtonLabelsAndVisibility(true); widgetValueChanged(); }</code><technical_language>This a copy-pasta issue -- call twice, right</technical_language>

Target:
public void setBinaryData(Object answer) { stringAnswer = (String) answer; if (stringAnswer != null && !stringAnswer.isEmpty()) { String[] parts = stringAnswer.split(" "); answerDisplay.setText(getContext().getString( R.string.gps_result, formatGps(Double.parseDouble(parts[0]), "lat"), formatGps(Double.parseDouble(parts[1]), "lon"), truncateDouble(parts[2]), truncateDouble(parts[3]) )); } else { answerDisplay.setText(""); } updateButtonLabelsAndVisibility(true); widgetValueChanged(); }
Source:
<code>public static boolean isEntityInsideOfMaterial(Entity entity, Predicate<Material> predicate) { if (entity.getRidingEntity() instanceof EntityBoat) { return false; } else { BlockPos pos = new BlockPos(entity.posX, entity.posY + entity.getEyeHeight(), entity.posZ); Material material = entity.world.getBlockState(pos).getMaterial(); if (predicate.test(material)) { <START> if (entity instanceof EntityPlayer) System.out.println("Passed predicate test"); <END> return isInsideOfMaterial(material, entity, pos); } else { return false; } } }</code><technical_language>This debug statement log removed, hidden a public static boolean flag is set false default</technical_language>

Target:
public static boolean isEntityInsideOfMaterial(Entity entity, Predicate<Material> predicate) { if (entity.getRidingEntity() instanceof EntityBoat) { return false; } else { double eyePosY = entity.posY + entity.getEyeHeight(); BlockPos pos = new BlockPos(entity.posX, eyePosY, entity.posZ); IBlockState iBlockState = entity.world.getBlockState(pos); Material material = iBlockState.getMaterial(); Boolean result = iBlockState.getBlock().isEntityInsideMaterial(entity.world, pos, iBlockState, entity, eyePosY, material, true); if (result != null) return result; if (predicate.test(material)) { return isInsideOfMaterial(material, entity, pos); } else { return false; } } }
Source:
<code>public ProjectDetail call() throws NoSuchProjectException { final ProjectControl pc = projectControlFactory.validateFor(projectName, ProjectControl.OWNER | ProjectControl.VISIBLE); final ProjectState projectState = pc.getProjectState(); final ProjectDetail detail = new ProjectDetail(); final Project p = projectState.getProject(); boolean setDefaultMergeStrategy = true; for (MergeStrategySection section : projectState.getLocalMergeStrategySections()) { if (section.getName().equals(RefConfigSection.ALL)) { p.setSubmitType(section.getSubmitType().name()); p.setUseContentMerge(section.isUseContentMerge()); setDefaultMergeStrategy = false; break; } } if (setDefaultMergeStrategy) { <START> p.setSubmitType(MergeStrategySection.SubmitType.MERGE_IF_NECESSARY.name()); <END> } detail.setProject(p); final boolean userIsOwner = pc.isOwner(); final boolean userIsOwnerAnyRef = pc.isOwnerAnyRef(); detail.setCanModifyAccess(userIsOwnerAnyRef); detail.setCanModifyAgreements(userIsOwner); detail.setCanModifyDescription(userIsOwner); detail.setCanModifyMergeType(userIsOwner); return detail; }</code><technical_language>replace line 57 line 69 eliminate line 62 68</technical_language>

Target:
public ProjectDetail call() throws NoSuchProjectException { final ProjectControl pc = projectControlFactory.validateFor(projectName, ProjectControl.OWNER | ProjectControl.VISIBLE); final ProjectState projectState = pc.getProjectState(); final ProjectDetail detail = new ProjectDetail(); final Project p = projectState.getProject(); p.setSubmitType(MergeStrategySection.SubmitType.MERGE_IF_NECESSARY.name()); for (MergeStrategySection section : projectState .getLocalMergeStrategySections()) { if (section.getName() != null && section.getName().equals(RefConfigSection.ALL)) { if (section.getSubmitType() != null) { p.setSubmitType(section.getSubmitType().name()); } if (section.isUseContentMerge() != null) { p.setUseContentMerge( section.isUseContentMerge() == MergeStrategySection.UseContentMerge.TRUE ? true : false); } break; } } detail.setProject(p); final boolean userIsOwner = pc.isOwner(); final boolean userIsOwnerAnyRef = pc.isOwnerAnyRef(); detail.setCanModifyAccess(userIsOwnerAnyRef); detail.setCanModifyAgreements(userIsOwner); detail.setCanModifyDescription(userIsOwner); detail.setCanModifyMergeType(userIsOwner); detail.setCanModifyState(userIsOwner); final Project.NameKey projectName = projectState.getProject().getNameKey(); Repository git; try { git = gitRepositoryManager.openRepository(projectName); } catch (RepositoryNotFoundException err) { throw new NoSuchProjectException(projectName); } try { Ref head = git.getRef(Constants.HEAD); if (head != null && head.isSymbolic() && GitRepositoryManager.REF_CONFIG.equals(head.getLeaf().getName())) { detail.setPermissionOnly(true); } } catch (IOException err) { throw new NoSuchProjectException(projectName); } finally { git.close(); } return detail; }
Source:
<code>void unregisterSourceReader(int subtaskId) { Preconditions.checkNotNull(registeredReaders.remove(subtaskId), <START> "Failed to unregister source reader of id " + subtaskId + " because it is not registered."); <END> }</code><technical_language>Avoid string concatenation in Preconditions, eagerly happen, "happy path". %s a placeholder, similar in log statements</technical_language>

Target:
void unregisterSourceReader(int subtaskId) { Preconditions.checkNotNull(registeredReaders.remove(subtaskId), String.format( "Failed to unregister source reader of id %s because it is not registered.", subtaskId)); }
Source:
<code>public String getUnifiedDiff() { PatchList patchList; try { patchList = getPatchList(); if (patchList.getOldId() == null) { return "[There is no diff output.\n" + " Reason: This change has more than two parents.\n" <START> + " Gerrit does not support for generating diff output\n" <END> + " between this kind change and its parents by far.]\n"; } } catch (PatchListNotAvailableException e) { log.error("Cannot format patch", e); return ""; } TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(args.settings.maximumDiffSize); DiffFormatter fmt = new DiffFormatter(buf); Repository git; try { git = args.server.openRepository(change.getProject()); } catch (IOException e) { log.error("Cannot open repository to format patch", e); return ""; } try { fmt.setRepository(git); fmt.setDetectRenames(true); fmt.format(patchList.getOldId(), patchList.getNewId()); return RawParseUtils.decode(buf.toByteArray()); } catch (IOException e) { if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) { return ""; } log.error("Cannot format patch", e); return ""; } finally { fmt.release(); git.close(); } }</code><technical_language>"Gerrit currently support generating diff output for this kind of change."</technical_language>

Target:
public String getUnifiedDiff() { PatchList patchList; try { patchList = getPatchList(); if (patchList.getOldId() == null) { return "[There is no diff output.\n" + " Reason: This change has more than two parents.\n" + " Gerrit does not currently support generating\n" + " diff output for this kind of change."; } } catch (PatchListNotAvailableException e) { log.error("Cannot format patch", e); return ""; } TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(args.settings.maximumDiffSize); DiffFormatter fmt = new DiffFormatter(buf); Repository git; try { git = args.server.openRepository(change.getProject()); } catch (IOException e) { log.error("Cannot open repository to format patch", e); return ""; } try { fmt.setRepository(git); fmt.setDetectRenames(true); fmt.format(patchList.getOldId(), patchList.getNewId()); return RawParseUtils.decode(buf.toByteArray()); } catch (IOException e) { if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) { return ""; } log.error("Cannot format patch", e); return ""; } finally { fmt.release(); git.close(); } }
Source:
<code>protected void initMiningFieldMap() throws Exception { MiningSchema schema = getMiningSchema(); boolean addExternalBeanRefs = isUseExternalBeanRefs(schema); miningFieldMap = new HashMap<>(); externalMiningFields = new ArrayList<>(); for (MiningField field : schema.getMiningFields()) { miningFieldMap.put(field.getName(), field); if (addExternalBeanRefs) { Extension ext = getExternalClassInfo(field.getExtensions()); if (ext != null) { ExternalBeanRef ref; <START> try { <END> ref = new ExternalBeanRef(field.getName(), ext.getValue(), ModelUsage.MINING); externalMiningFields.add(ref); } catch (Exception e) { throw new Exception("Error while initializing the MiningField map. ",e); } } } } }</code><technical_language>Please reformat this try-catch</technical_language>

Target:
protected void initMiningFieldMap() throws IllegalArgumentException { MiningSchema schema = getMiningSchema(); boolean addExternalBeanRefs = isUseExternalBeanRefs(schema); miningFieldMap = new HashMap<>(); externalMiningFields = new ArrayList<>(); for (MiningField field : schema.getMiningFields()) { miningFieldMap.put(field.getName(), field); if (addExternalBeanRefs) { Extension ext = getExternalClassInfo(field.getExtensions()); if (ext != null) { ExternalBeanRef ref; try { ref = new ExternalBeanRef(field.getName(), ext.getValue(), ModelUsage.MINING); externalMiningFields.add(ref); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Error while initializing the MiningField map. ",e); } } } } }
Source:
<code>public Device searchActiveDevice(@Identification final String deviceIdentification) throws UnregisteredDeviceException, InactiveDeviceException, UnknownEntityException { final Device device = this.searchDevice(deviceIdentification); final Ssld ssld = this.ssldRepository.findOne(device.getId()); <START> if (!device.isActive()) { <END> throw new InactiveDeviceException(deviceIdentification); } if (ssld != null && !ssld.isPublicKeyPresent()) { throw new UnregisteredDeviceException(deviceIdentification); } return device; }</code><technical_language>This changes logic paths for SSLD devices well. Some time UnregisteredDeviceException thrown a device _activated_. change in behavior throw InactiveDeviceException in cases discussed @kevinsmeets. check a device is _active_ logic for throwing exception _activated_ account. Updating keeping a proper (and meaning) for status fields (here isActive isActivated) clear (and tested) domains</technical_language>

Target:
public Device searchActiveDevice(@Identification final String deviceIdentification) throws UnregisteredDeviceException, InactiveDeviceException, UnknownEntityException { final Device device = this.searchDevice(deviceIdentification); final Ssld ssld = this.ssldRepository.findOne(device.getId()); if (!device.isActivated() || !device.isActive()) { throw new InactiveDeviceException(deviceIdentification); } if (ssld != null && !ssld.isPublicKeyPresent()) { throw new UnregisteredDeviceException(deviceIdentification); } return device; }
Source:
<code>public PublicKey getRawPublicKey(String keyType, Buffer buffer) throws GeneralSecurityException { byte[] nonce = buffer.getBytes(); String rawKeyType = OpenSshCertificate.getRawKeyType(keyType); PublicKey publicKey = DEFAULT.getRawPublicKey(rawKeyType, buffer); long serial = buffer.getLong(); int userOrHostType = buffer.getInt(); String id = buffer.getString(); List<String> vPrincipals = new ByteArrayBuffer(buffer.getBytes()).getNameList(); long vAfter = buffer.getLong(); long vBefore = buffer.getLong(); List<String> criticalOptions = buffer.getNameList(); List<String> extensions = buffer.getNameList(); String reserved = buffer.getString(); PublicKey signatureKey; try { signatureKey = buffer.getPublicKey(); } catch (SshException ex) { <START> throw new GeneralSecurityException("Could not parse public CA key.", ex); <END> } byte[] message = buffer.getBytesConsumed(); byte[] signature = buffer.getBytes(); if (buffer.rpos() != buffer.wpos()) { throw new GeneralSecurityException("KeyExchange signature verification failed, got more data than expected: " + buffer.rpos() + ", actual: " + buffer.wpos()); } return OpenSshCertificate.OpenSshPublicKeyBuilder.anOpenSshCertificate() .withKeyType(keyType) .withNonce(nonce) .withServerHostPublicKey(publicKey) .withSerial(serial) .withType(userOrHostType) .withId(id) .withPrincipals(vPrincipals) .withValidAfter(vAfter) .withValidBefore(vBefore) .withCriticalOptions(criticalOptions) .withExtensions(extensions) .withReserved(reserved) .withCaPubKey(signatureKey) .withMessage(message) .withSignature(signature) .build(); }</code><technical_language>add ID of key parse message for debugging purposes</technical_language>

Target:
public PublicKey getRawPublicKey(String keyType, Buffer buffer) throws GeneralSecurityException { OpenSshCertificateImpl certificate = new OpenSshCertificateImpl(); certificate.setKeyType(keyType); certificate.setNonce(buffer.getBytes()); String rawKeyType = certificate.getRawKeyType(); certificate.setServerHostKey(DEFAULT.getRawPublicKey(rawKeyType, buffer)); certificate.setSerial(buffer.getLong()); certificate.setType(buffer.getInt()); certificate.setId(buffer.getString()); certificate.setPrincipals(new ByteArrayBuffer(buffer.getBytes()).getStringList(false)); certificate.setValidAfter(buffer.getLong()); certificate.setValidBefore(buffer.getLong()); certificate.setCriticalOptions(buffer.getNameList()); certificate.setExtensions(buffer.getNameList()); certificate.setReserved(buffer.getString()); try { certificate.setCaPubKey(buffer.getPublicKey()); } catch (SshException ex) { throw new GeneralSecurityException("Could not parse public CA key with ID: " + certificate.getId(), ex); } certificate.setMessage(buffer.getBytesConsumed()); certificate.setSignature(buffer.getBytes()); if (buffer.rpos() != buffer.wpos()) { throw new GeneralSecurityException("KeyExchange signature verification failed, got more data than expected: " + buffer.rpos() + ", actual: " + buffer.wpos() + ". ID of the ca certificate: " + certificate.getId()); } return certificate; }
Source:
<code>protected BlockingQueue<IncomingMessageEnvelope> newBlockingQueue() { <START> return new LinkedBlockingQueue<>(config.getConsumerBufferCapacity()); <END> }</code><technical_language>a separate config, a fetchThreshold Samza config</technical_language>

Target:
protected BlockingQueue<IncomingMessageEnvelope> newBlockingQueue() { return new LinkedBlockingQueue<>(config.getConsumerBufferCapacity(systemName)); }
Source:
<code>public CookieCsrfTokenRepository() { <START> this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class); <END> }</code><technical_language>for understanding: reason Reflection here? Support of older servlet specs</technical_language>

Target:
public CookieCsrfTokenRepository() { this.setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class); if (this.setHttpOnlyMethod != null) { this.cookieHttpOnly = true; } }