auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void invokeCommand(String itemName) { GC100ItemBean itemBean = getGC100ItemBean(itemName); String preparedCode = GC100ItemUtility.prepareCode(itemBean); String result = gc100ControlPoint.doAction(gc100.getHostname(), itemBean.getModule(), itemBean.getConnector(), preparedCode); if (!result.contains("complete")) { logger.warn("Failed to execute command over GC100: " + gc100.getHostname() + " with Module: " <START> + itemBean.getModule() + " of Connector: " + itemBean.getConnector() + " to Item: " + itemName); <END> return; } logger.info("Successfully executed command over GC100: " + gc100.getHostname() + " with Module: " + itemBean.getModule() + " of Connector: " + itemBean.getConnector() + " to Item: " + itemName); }</code><technical_language>parameterized logging throughout, in this case: java logger.warn("Failed execute command GC100: Module: of Connector: Item: {}", gc100.getHostname(), itemBean.getModule(), itemBean.getConnector(), itemName);</technical_language>

Target:
public void invokeCommand(String itemName) { GC100ItemBean itemBean = getGC100ItemBean(itemName); String preparedCode = gc100ItemUtility.prepareCode(itemBean); GC100IRCommand result = gc100ControlPoint.doAction(gc100.getHostname(), itemBean.getModule(), itemBean.getConnector(), preparedCode); if (GC100IRCommandCode.COMPLETED_SUCCESSFULLY != result.getCommandCode()) { logger.warn( "Failed to execute command over GC100: with Module: of Connector: to Item: {}, the response was {}", gc100.getHostname(), itemBean.getModule(), itemBean.getConnector(), itemName, result); return; } logger.info( "Successfully executed command over GC100: with Module: of Connector: to Item: {}, the response was {}", gc100.getHostname(), itemBean.getModule(), itemBean.getConnector(), itemName, result); }
Source:
<code>public void testFilterParams() { startHumanTaskProcess(10, "john's task", "john"); Map<String, Object> parameters = new HashMap<String, Object>(); <START> parameters.put("id", 1); <END> parameters.put("priority", 0); QueryFilter queryFilter = new QueryFilter("t.id=:id AND t.priority=:priority", parameters, "t.name", true); List<TaskSummary> taskList = taskService.getTasksAssignedAsPotentialOwner("john", null, null, queryFilter); logger.debug("### Potential owner task list: " + taskList); Assertions.assertThat(taskList).hasSize(1); abortHumanTaskProcess(10); }</code><technical_language>"1L"</technical_language>

Target:
public void testFilterParams() { startHumanTaskProcess(10, "john's task", "john"); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("id", 1L); parameters.put("priority", 0); QueryFilter queryFilter = new QueryFilter("t.id=:id AND t.priority=:priority", parameters, "t.name", true); List<TaskSummary> taskList = taskService.getTasksAssignedAsPotentialOwner("john", null, null, queryFilter); logger.debug("### Potential owner task list: " + taskList); Assertions.assertThat(taskList).hasSize(1); abortHumanTaskProcess(10); }
Source:
<code><START> public static Result<String, String> getRunBundles(Project project, boolean resolveIfNecessary) { <END> try { File f = getCacheFile(project); if (f.isFile()) { try { CacheDTO dto = JSON_CODEC.dec() .from(f) .get(CacheDTO.class); if (dto.checksum.equals(project.getChecksum())) { logger.info("read cache for {}", project); return Ok.result(HeaderClause.toParameters(dto.runbundles) .toString()); } } catch (Exception e) { logger.warn("{} getRunBundles exception in reading cache {}, ignoring", project, e); IO.delete(f); } } if (!resolveIfNecessary) { return Ok.result(null); } logger.info("resolve {}", project); Result<RunResolution, String> r = resolve(project, project, null).asResult(); logger.debug("resolve {}", project, r); return r.then(rr -> { logger.info("saving cache {}", project); rr.cache(); return Ok.result(rr); }) .map(RunResolution::getRunBundlesAsString); } catch (Exception e) { throw Exceptions.duck(e); } }</code><technical_language>Promise hold result/failure information here? adding a new, similar package</technical_language>

Target:
public static Result<String, String> getRunBundles(Project project, boolean resolveIfNecessary) { try { File f = getCacheFile(project); if (f.isFile()) { try { CacheDTO dto = JSON_CODEC.dec() .from(f) .get(CacheDTO.class); if (dto.checksum.equals(project.getChecksum())) { logger.info("read cache for {}", project); return Ok.result(HeaderClause.toParameters(dto.runbundles) .toString()); } } catch (Exception e) { logger.warn("{} getRunBundles exception in reading cache {}, ignoring", project, e); IO.delete(f); } } if (!resolveIfNecessary) { return Ok.result(null); } logger.info("resolve {}", project); Result<RunResolution, String> r = resolve(project, project, null).asResult(); logger.debug("resolve {}", project, r); return r.flatMap(rr -> { logger.info("saving cache {}", project); rr.cache(); return Ok.result(rr); }) .map(RunResolution::getRunBundlesAsString); } catch (Exception e) { throw Exceptions.duck(e); } }
Source:
<code>public Expression generateIL(GenContext ctx, ValueType expectedType) { CallableExprGenerator exprGen = function.getCallableExpr(ctx); List<FormalArg> formals = exprGen.getExpectedArgTypes(ctx); int offset = 0; List<Expression> args = new LinkedList<Expression>(); if(!this.generics.isEmpty()) { for(String generic : this.generics) { <START> args.add(new wyvern.target.corewyvernIL.expression.New(new TypeDeclaration(DefDeclaration.GENERIC_MEMBER, new NominalType("", generic), this.location))); <END> offset++; } } if (argument instanceof TupleObject) { ExpressionAST[] raw_args = ((TupleObject) argument).getObjects(); for (int i = 0; i < raw_args.length; i++) { ValueType expectedArgType = formals.get(i + offset).getType(); ExpressionAST ast = raw_args[i]; args.add(ast.generateIL(ctx, expectedArgType)); } } else if (argument instanceof UnitVal) { } else { if (formals.size() != 1 + offset) { ToolError.reportError(ErrorMessage.WRONG_NUMBER_OF_ARGUMENTS, this, ""+formals.size()); } args.add(argument.generateIL(ctx, formals.get(0).getType())); } return exprGen.genExprWithArgs(args, this); }</code><technical_language>Instead of GENERIC_MEMBER, formals.get(i) extract name, remove GENERIC_PREFIX prefix it. name of type member. Instead of new NominalType("", generic), follow code in UnresolvedType.getILType() generate ValueType properly</technical_language>

Target:
public Expression generateIL(GenContext ctx, ValueType expectedType) { CallableExprGenerator exprGen = function.getCallableExpr(ctx); List<FormalArg> formals = exprGen.getExpectedArgTypes(ctx); int offset = 0; List<Expression> args = new LinkedList<Expression>(); for(int i = 0; i < generics.size(); i++) { String generic = generics.get(i); String formalName = formals.get(i).getName(); if(formalName.startsWith(DefDeclaration.GENERIC_PREFIX)) { String genericName = formalName.substring(DefDeclaration.GENERIC_PREFIX.length()); ValueType vt = getILTypeForGeneric(ctx, generic); args.add(new wyvern.target.corewyvernIL.expression.New(new TypeDeclaration(genericName, vt, this.location))); } else { ToolError.reportError(ErrorMessage.EXTRA_GENERICS_AT_CALL_SITE, this); } offset++; } if (argument instanceof TupleObject) { ExpressionAST[] raw_args = ((TupleObject) argument).getObjects(); if (formals.size() != raw_args.length + offset) ToolError.reportError(ErrorMessage.WRONG_NUMBER_OF_ARGUMENTS, this, ""+formals.size()); for (int i = 0; i < raw_args.length; i++) { ValueType expectedArgType = formals.get(i + offset).getType(); ExpressionAST ast = raw_args[i]; args.add(ast.generateIL(ctx, expectedArgType)); } } else if (argument instanceof UnitVal) { } else { if (formals.size() != 1 + offset) { ToolError.reportError(ErrorMessage.WRONG_NUMBER_OF_ARGUMENTS, this, ""+formals.size()); } args.add(argument.generateIL(ctx, formals.get(0).getType())); } return exprGen.genExprWithArgs(args, this); }
Source:
<code>private void writeRecord(SinkRecord record) throws IOException { long expectedOffset = offset + recordCounter; if (offset == -1) { offset = record.kafkaOffset(); <START> } else if (record.kafkaOffset() < expectedOffset) { <END> if (!sawStaleOffset) { log.info( "Ignoring stale out-of-order record in {}-{}. Has offset instead of expected offset {}", record.topic(), record.kafkaPartition(), record.kafkaOffset(), expectedOffset); } sawStaleOffset = true; return; } if (sawStaleOffset) { log.info( "Recovered from stale out-of-order records in {}-{} with offset {}", record.topic(), record.kafkaPartition(), expectedOffset); sawStaleOffset = false; } String encodedPartition = partitioner.encodePartition(record); RecordWriter<SinkRecord> writer = getWriter(record, encodedPartition); writer.write(record); if (!startOffsets.containsKey(encodedPartition)) { startOffsets.put(encodedPartition, record.kafkaOffset()); offsets.put(encodedPartition, record.kafkaOffset()); } else { offsets.put(encodedPartition, record.kafkaOffset()); } recordCounter++; }</code><technical_language>Hmm, 2 things. First, I if change this want expectedOffset computed differently. Right adds record count, sense anymore. Secondly, remove this entirely? move check a config flag a turn if need it? underlying issue required this check is fixed in 0.10.1.0, removing this put folks run a newer version of connector in older cluster risk</technical_language>

Target:
private void writeRecord(SinkRecord record) throws IOException { long expectedOffset = offset + recordCounter; if (offset == -1) { offset = record.kafkaOffset(); } else if (checkStaleOffsets && record.kafkaOffset() != expectedOffset) { if (!sawInvalidOffset) { log.info( "Ignoring stale out-of-order record in {}-{}. Has offset instead of expected offset {}", record.topic(), record.kafkaPartition(), record.kafkaOffset(), expectedOffset); } sawInvalidOffset = true; return; } if (sawInvalidOffset) { log.info( "Recovered from stale out-of-order records in {}-{} with offset {}", record.topic(), record.kafkaPartition(), expectedOffset); sawInvalidOffset = false; } String encodedPartition = partitioner.encodePartition(record); RecordWriter<SinkRecord> writer = getWriter(record, encodedPartition); writer.write(record); if (!startOffsets.containsKey(encodedPartition)) { startOffsets.put(encodedPartition, record.kafkaOffset()); offsets.put(encodedPartition, record.kafkaOffset()); } else { offsets.put(encodedPartition, record.kafkaOffset()); } recordCounter++; }
Source:
<code>public abstract boolean delete(Path f, boolean recursive) throws IOException; public abstract boolean mkdirs(Path f) throws IOException; public abstract FSDataOutputStream create(Path f, boolean overwrite, int bufferSize, short replication, long blockSize) throws IOException; public abstract FSDataOutputStream create(Path f, boolean overwrite) throws IOException; public abstract boolean rename(Path src, Path dst) throws IOException; <START> public boolean initOutPathLocalFS(Path outPath, WriteMode writeMode, boolean parallelOutput) throws IOException { <END> if(this.isDistributedFS()) { return false; } if(this.exists(outPath)) { switch(writeMode) { case CREATE: if(this.getFileStatus(outPath).isDir()) { return true; } else { throw new IOException("Existing file or directory on output path may not be overwritten in CREATE write mode."); } case OVERWRITE: if(this.getFileStatus(outPath).isDir()) { if(parallelOutput) { return true; } else { try { this.delete(outPath, true); } catch(IOException ioe) { throw new IOException("Could not prepare output path. ",ioe); } } } else { try { this.delete(outPath, false); } catch(IOException ioe) { } } break; default: throw new IllegalArgumentException("Invalid write mode: "+writeMode); } } if(parallelOutput) { try { if(!this.exists(outPath)) { this.mkdirs(outPath); } } catch(IOException ioe) { } return this.exists(outPath) && this.getFileStatus(outPath).isDir(); } else { return !this.exists(outPath); } }</code><technical_language>I read changes suggest but: sense a abstract initOutPath(..) in FileSystems implement cases for local distributed in respective classes. current approach, add a method for new file system add system</technical_language>

Target:
public abstract boolean delete(Path f, boolean recursive) throws IOException; public abstract boolean mkdirs(Path f) throws IOException; public abstract FSDataOutputStream create(Path f, boolean overwrite, int bufferSize, short replication, long blockSize) throws IOException; public abstract FSDataOutputStream create(Path f, boolean overwrite) throws IOException; public abstract boolean rename(Path src, Path dst) throws IOException; public boolean initOutPathLocalFS(Path outPath, WriteMode writeMode, boolean createDirectory) throws IOException { if(this.isDistributedFS()) { return false; } if(this.exists(outPath)) { switch(writeMode) { case CREATE: if(this.getFileStatus(outPath).isDir()) { return true; } else { throw new IOException("Existing file or directory on output path may not be overwritten in CREATE write mode."); } case OVERWRITE: if(this.getFileStatus(outPath).isDir()) { if(createDirectory) { return true; } else { try { this.delete(outPath, true); } catch(IOException ioe) { throw new IOException("Could not prepare output path. ",ioe); } } } else { try { this.delete(outPath, false); } catch(IOException ioe) { } } break; default: throw new IllegalArgumentException("Invalid write mode: "+writeMode); } } if(createDirectory) { try { if(!this.exists(outPath)) { this.mkdirs(outPath); } } catch(IOException ioe) { } return this.exists(outPath) && this.getFileStatus(outPath).isDir(); } else { return !this.exists(outPath); } }
Source:
<code>public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); <START> setupContent((ViewGroup) getView().getRootView()); <END> Toolbar toolbar = view.findViewById(R.id.toolbar_main); ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getScreenTitle()); getActivity().setTitle(getScreenTitle()); } }</code><technical_language>view argument instead? is complaining a potential NPE here. suggestion setupContent((ViewGroup) view);</technical_language>

Target:
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupContent((ViewGroup) getView().getRootView()); Toolbar toolbar = view.findViewById(R.id.toolbar_main); ((AppCompatActivity) requireActivity()).setSupportActionBar(toolbar); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getScreenTitle()); getActivity().setTitle(getScreenTitle()); } }
Source:
<code>public ExternalIdSearch withExternalIdRemoved(ExternalId externalId) { if (externalId == null || contains(externalId) == false) { return this; } <START> Set<ExternalId> ids = Sets.newHashSet(this.externalIds); <END> ids.remove(externalId); return new ExternalIdSearch(searchType, ImmutableSet.copyOf(ids)); }</code><technical_language>reason newHashSet new HashSet<>? Alternatively, of Guava Collections methods do this job for us</technical_language>

Target:
public ExternalIdSearch withExternalIdRemoved(ExternalId externalId) { if (externalId == null || contains(externalId) == false) { return this; } Set<ExternalId> ids = new HashSet<>(this.externalIds); ids.remove(externalId); return new ExternalIdSearch(searchType, ImmutableSet.copyOf(ids)); }
Source:
<code>public void preStart() { LOGGER.info().setMessage("Starting execution timer") .addData("schema", _schema) .addData("table", _table) .addData("lookahead", _lookahead) .log(); getSelf().tell(TICK, getSelf()); <START> getTimers().startPeriodicTimer(TICKER_NAME, TICK, TICK_INTERVAL); <END> }</code><technical_language>I assume this cancelled base class AbstractActorWithTimers</technical_language>

Target:
public void preStart() { LOGGER.info().setMessage("Starting execution timer") .addData("schema", _schema) .addData("table", _table) .addData("lookahead", _lookaheadDays) .log(); getSelf().tell(TICK, getSelf()); getTimers().startPeriodicTimer(TICKER_NAME, TICK, TICK_INTERVAL); }
Source:
<code>public void testAlterFunctionInvalidFunctionName() { assertQueryFails( "ALTER FUNCTION testing.tan CALLED ON NULL INPUT", ".*Function name should be in the form of catalog\\.schema\\.function_name, found: testing\\.tan"); assertQueryFails( "ALTER FUNCTION presto.default.tan RETURNS NULL ON NULL INPUT", "Cannot alter function in built-in function namespace: presto\\.default\\.tan"); <START> } <END></code><technical_language>testing ALTER FUNCTION sin ... instead</technical_language>

Target:
public void testAlterFunctionInvalidFunctionName() { assertQueryFails( "ALTER FUNCTION tan CALLED ON NULL INPUT", ".*Function name should be in the form of catalog\\.schema\\.function_name, found: tan"); assertQueryFails( "ALTER FUNCTION testing.tan CALLED ON NULL INPUT", ".*Function name should be in the form of catalog\\.schema\\.function_name, found: testing\\.tan"); assertQueryFails( "ALTER FUNCTION presto.default.sin RETURNS NULL ON NULL INPUT", "Cannot alter function in built-in function namespace: presto\\.default\\.sin"); }
Source:
<code>private BulkActionsResultView fireBulkActionsTaskForQuery(final WorkflowAction action, final User user, final String luceneQuery, final Set<String> workflowAssociatedStepsIds, final AdditionalParamsBean additionalParamsBean) throws DotDataException { try { final String sanitizedQuery = LuceneQueryUtils .sanitizeBulkActionsQuery(luceneQuery); <START> Logger.debug(getClass(), "luceneQuery: " + sanitizedQuery); <END> final List<Contentlet> contentlets = findContentletsToProcess(sanitizedQuery, workflowAssociatedStepsIds, user); final Long skipsCount = computeSkippedContentletsCount(sanitizedQuery, workflowAssociatedStepsIds, user); return distributeWorkAndProcess(action, user, contentlets, skipsCount, additionalParamsBean); } catch (Exception e) { Logger.error(getClass(), "Error firing actions in bulk.", e); throw new DotDataException(e); } }</code><technical_language>remember Logger.debug(getClass(), ()->"luceneQuery: " + sanitizedQuery);</technical_language>

Target:
private BulkActionsResultView fireBulkActionsTaskForQuery(final WorkflowAction action, final User user, final String luceneQuery, final Set<String> workflowAssociatedStepsIds, final AdditionalParamsBean additionalParamsBean) throws DotDataException { try { final String sanitizedQuery = LuceneQueryUtils .sanitizeBulkActionsQuery(luceneQuery); Logger.debug(getClass(), ()->"luceneQuery: " + sanitizedQuery); final List<Contentlet> contentlets = findContentletsToProcess(sanitizedQuery, workflowAssociatedStepsIds, user); final Long skipsCount = computeSkippedContentletsCount(sanitizedQuery, workflowAssociatedStepsIds, user); return distributeWorkAndProcess(action, user, contentlets, skipsCount, additionalParamsBean); } catch (Exception e) { Logger.error(getClass(), "Error firing actions in bulk.", e); throw new DotDataException(e); } }
Source:
<code>private String generateDefaultFilename() { String result = ""; if (bamFilePath.trim().isEmpty()) { <START> <END> result = filePath + File.separator + metaQuery.getFilename(); } else { String fileName = new File(bamFilePath).getName(); result = filePath + File.separator + "extract-" + fileName; } return result; }</code><technical_language>Remove new line</technical_language>

Target:
private String generateDefaultFilename() { String result = ""; if (bamFilePath.trim().isEmpty()) { result = filePath + File.separator + metaQuery.getFileName(); } else { String fileName = new File(bamFilePath).getName(); result = filePath + File.separator + "extract-" + fileName; } return result; }
Source:
<code><START> public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { <END> super.configurePipeline(pipelineConfigurer); parseConfiguration(config.decompressor); try { Schema outputSchema = Schema.parseJson(config.schema); List<Field> outFields = outputSchema.getFields(); for (Field field : outFields) { outSchemaMap.put(field.getName(), field.getSchema().getType()); } } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } for (Map.Entry<String, DecompressorType> entry : deCompMap.entrySet()) { if (!outSchemaMap.containsKey(entry.getKey())) { throw new IllegalArgumentException("Field '" + entry.getKey() + "' specified to be decompresed is not " + "present in the output schema. Please add field '" + entry.getKey() + "'" + "to output schema or remove it from decompress"); } if (outSchemaMap.get(entry.getKey()) != Schema.Type.BYTES && outSchemaMap.get(entry.getKey()) != Schema.Type.STRING) { throw new IllegalArgumentException("Field '" + entry.getKey() + "' should be of type BYTES or STRING in " + "output schema."); } } }</code><technical_language>need throws declaration</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.decompressor); try { Schema outputSchema = Schema.parseJson(config.schema); List<Field> outFields = outputSchema.getFields(); for (Field field : outFields) { outSchemaMap.put(field.getName(), field.getSchema().getType()); } } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format. " + e.getMessage()); } for (Map.Entry<String, DecompressorType> entry : deCompMap.entrySet()) { if (!outSchemaMap.containsKey(entry.getKey())) { throw new IllegalArgumentException("Field '" + entry.getKey() + "' specified to be decompresed is not " + "present in the output schema. Please add field '" + entry.getKey() + "'" + "to output schema or remove it from decompress"); } if (outSchemaMap.get(entry.getKey()) != Schema.Type.BYTES && outSchemaMap.get(entry.getKey()) != Schema.Type.STRING) { throw new IllegalArgumentException("Field '" + entry.getKey() + "' should be of type BYTES or STRING in " + "output schema."); } } }
Source:
<code>public FileSystemResourceReference(String name, Path path) { <START> super(Args.notNull(name, "name")); <END> Args.notNull(path, "path"); this.path = path; }</code><technical_language>org.apache.wicket.request.resource.ResourceReference#ResourceReference(java.lang.Class<?>, java.lang.String, java.util.Locale, java.lang.String, java.lang.String) cares non-null name. need check too</technical_language>

Target:
public FileSystemResourceReference(String name, Path path) { super(name); Args.notNull(path, "path"); this.path = path; }
Source:
<code>protected void init() { this.guiLeft = (this.width - this.xSize) / 2; this.guiTop = (this.height - this.ySize) / 2; this.addButton(new Button(this.guiLeft + ((this.xSize - 80) / 2), this.guiTop + 152, 80, 20, UtilLib.translate("gui.done"), (context) -> { this.onClose(); })); for (int i = 0; i < statCount; i++) { int finalI = i; <START> statButtons.add(this.addButton(new Button(guiLeft + 225, guiTop + 43 + 26 * i, 20, 20, "+", (button) -> VampirismMod.dispatcher.sendToServer(new UpgradeMinionStatPacket(entity.getEntityId(), finalI))))); <END> } }</code><technical_language>invisible creation. if minion is full level buttons shown for a moment hiding suggestion Button button = this.addButton(new Button(guiLeft + 225, guiTop + 43 + 26 * i, 20, 20, "+", (button) -> VampirismMod.dispatcher.sendToServer(new UpgradeMinionStatPacket(entity.getEntityId(), finalI)))); statButtons.add(button); button.visible = false;</technical_language>

Target:
protected void init() { this.statButtons.clear(); this.guiLeft = (this.width - this.xSize) / 2; this.guiTop = (this.height - this.ySize) / 2; this.addButton(new Button(this.guiLeft + this.xSize - 80 - 20, this.guiTop + 152, 80, 20, UtilLib.translate("gui.done"), (context) -> { this.onClose(); })); if (backScreen != null) { this.addButton(new Button(this.guiLeft + 20, this.guiTop + 152, 80, 20, UtilLib.translate("gui.back"), (context) -> { Minecraft.getInstance().displayGuiScreen(this.backScreen); })); } for (int i = 0; i < statCount; i++) { int finalI = i; Button button = this.addButton(new Button(guiLeft + 225, guiTop + 43 + 26 * i, 20, 20, "+", (b) -> VampirismMod.dispatcher.sendToServer(new UpgradeMinionStatPacket(entity.getEntityId(), finalI)))); statButtons.add(button); button.visible = false; } }
Source:
<code>public File getDownloadFolder() { PrefManager pref = new PrefManager(context, PrefManager.Pref.LOGIN); ProfileModel profile = pref.getCurrentUserProfile(); File android = new File(Environment.getExternalStorageDirectory(), "Android"); File downloadsDir = new File(android, "data"); File packDir = new File(downloadsDir, context.getPackageName()); File edxDir = new File(packDir, profile.username); edxDir.mkdirs(); try { File noMediaFile = new File(edxDir, ".nomedia"); if (!noMediaFile.createNewFile()) { logger.debug(".NoMedia file not created"); <START> } <END> }catch (IOException ioException){ logger.error(ioException); } return edxDir; }</code><technical_language>wrap this if-condition block <code> if ( ! noMediaFile.exists() ) </code></technical_language>

Target:
public File getDownloadFolder() { PrefManager pref = new PrefManager(context, PrefManager.Pref.LOGIN); ProfileModel profile = pref.getCurrentUserProfile(); File android = new File(Environment.getExternalStorageDirectory(), "Android"); File downloadsDir = new File(android, "data"); File packDir = new File(downloadsDir, context.getPackageName()); File edxDir = new File(packDir, profile.username); edxDir.mkdirs(); try { File noMediaFile = new File(edxDir, ".nomedia"); noMediaFile.createNewFile(); }catch (IOException ioException){ logger.error(ioException); } return edxDir; }
Source:
<code>protected void reduce(ImmutableBytesWritable arg0, Iterable<IntWritable> arg1, Reducer<ImmutableBytesWritable, IntWritable, NullWritable, NullWritable>.Context context) throws IOException, InterruptedException { if (!calledOnce.compareAndSet(false, true)) { return; } try { IndexTool.IndexVerifyType verifyType = getIndexVerifyType(configuration); if (verifyType != IndexTool.IndexVerifyType.NONE) { updateCounters(verifyType, context); } IndexToolUtil.updateIndexState(configuration, PIndexState.ACTIVE); } catch (SQLException e) { LOGGER.error(" Failed to update the status to Active"); throw new RuntimeException(e.getMessage()); } <START> } <END></code><technical_language>This log statement correct if getIndexVerifyType updateCounters throw exception</technical_language>

Target:
protected void reduce(ImmutableBytesWritable arg0, Iterable<IntWritable> arg1, Reducer<ImmutableBytesWritable, IntWritable, NullWritable, NullWritable>.Context context) throws IOException, InterruptedException { if (!calledOnce.compareAndSet(false, true)) { return; } IndexTool.IndexVerifyType verifyType = getIndexVerifyType(context.getConfiguration()); if (verifyType != IndexTool.IndexVerifyType.NONE) { updateCounters(verifyType, context); } try { IndexToolUtil.updateIndexState(context.getConfiguration(), PIndexState.ACTIVE); } catch (SQLException e) { LOGGER.error(" Failed to update the status to Active"); throw new RuntimeException(e.getMessage()); } }
Source:
<code>public Set<DownloadRequest> getDownloadList(String typeName, String timeField, String sizeField, String urlField, SubsetParameters subset) throws GoGoDuckException { Set<DownloadRequest> result = new LinkedHashSet<>(); Query query = new Query(); if (subset.getTimeRange() != null) { String timeCoverageStart = subset.getTimeRange().getStart().toString(); String timeCoverageEnd = subset.getTimeRange().getEnd().toString(); Filter cqlFilter; try { cqlFilter = CQL.toFilter( String.format("%s >= '%s' AND %s <= '%s'", timeField, timeCoverageStart, timeField, timeCoverageEnd) ); query = new Query(typeName, cqlFilter, new String[]{urlField, sizeField}); } catch (CQLException e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(e.getMessage()); } } <START> if (query == null) { <END> query = new Query(typeName, null, new String[]{urlField}); } FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints()); SortBy sortByTimeAscending = ff.sort(timeField, SortOrder.ASCENDING); query.setSortBy(new SortBy[]{sortByTimeAscending}); try (SimpleFeatureIterator iterator = getFeatures(typeName, query)) { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); String url = (String) feature.getAttribute(urlField); long size = 0; if (feature.getAttribute(sizeField) != null ){ size = Math.round((Double)feature.getAttribute(sizeField)); } logger.info(String.format("Processing url '%s'", url)); result.add(new DownloadRequest(urlMangler.mangle(new URI(url)), size)); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(String.format("Could not obtain list of downloads: '%s'", e.getMessage())); } return result; }</code><technical_language>This null - assign - this code path get executed</technical_language>

Target:
public Set<DownloadRequest> getDownloadList(String typeName, String timeField, String sizeField, String urlField, SubsetParameters subset) throws GoGoDuckException { Set<DownloadRequest> result = new LinkedHashSet<>(); Filter cqlFilter = getFilter(timeField, subset.getTimeRange()); Query query = new Query(typeName, cqlFilter, new String[]{urlField, sizeField}); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints()); SortBy sortByTimeAscending = ff.sort(timeField, SortOrder.ASCENDING); query.setSortBy(new SortBy[]{sortByTimeAscending}); try (SimpleFeatureIterator iterator = getFeatures(typeName, query)) { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); String url = (String) feature.getAttribute(urlField); long size = Math.round((Double)feature.getAttribute(sizeField)); logger.info(String.format("Processing url '%s'", url)); result.add(new DownloadRequest(urlMangler.mangle(new URI(url)), size)); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(String.format("Could not obtain list of downloads: '%s'", e.getMessage())); } return result; }
Source:
<code>public void visitReturnStatement(ReturnStatementTree syntaxNode) { SymbolicValue currentVal = programState.peekValue(); <START> if (currentVal != null) { <END> final ExpressionTree expression = syntaxNode.expression(); if (expression != null) { if (expression.is(Tree.Kind.IDENTIFIER)) { final IdentifierTree identifier = (IdentifierTree) expression; currentVal = programState.getValue(identifier.symbol()); } else { currentVal = programState.peekValue(); } closeResource(currentVal); } } }</code><technical_language>currentVal null ? if is some other problems, I this check is necessary</technical_language>

Target:
public void visitReturnStatement(ReturnStatementTree syntaxNode) { ExpressionTree expression = syntaxNode.expression(); if (expression != null) { SymbolicValue currentVal = programState.peekValue(); if (expression.is(Tree.Kind.IDENTIFIER)) { IdentifierTree identifier = (IdentifierTree) expression; currentVal = programState.getValue(identifier.symbol()); } closeResource(currentVal); } }
Source:
<code>private boolean updateBlobMetadata(BlobId blobId, String fieldName, Object value) throws CloudStorageException { Objects.requireNonNull(blobId, "BlobId cannot be null"); Objects.requireNonNull(fieldName, "Field name cannot be null"); try { <START> boolean updatedStorage, updatedCosmos = false; <END> AzureBlobDataAccessor.UpdateResponse updateResponse = azureBlobDataAccessor.updateBlobMetadata(blobId, fieldName, value); Map<String, String> metadataMap = updateResponse.metadata; updatedStorage = updateResponse.wasUpdated; try { ResourceResponse<Document> response = cosmosDataAccessor.updateMetadata(blobId, fieldName, value); updatedCosmos = response != null; } catch (DocumentClientException dex) { if (dex.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { cosmosDataAccessor.upsertMetadata(CloudBlobMetadata.fromMap(metadataMap)); azureMetrics.blobUpdateRecoverCount.inc(); updatedCosmos = true; } else { throw dex; } } if (updatedStorage || updatedCosmos) { logger.debug("Updated blob metadata set to {}.", blobId, fieldName, value); azureMetrics.blobUpdatedCount.inc(); return true; } else { logger.debug("Blob already has = in ABS and Cosmos", blobId, fieldName, value); return false; } } catch (Exception e) { azureMetrics.blobUpdateErrorCount.inc(); throw toCloudStorageException("Error updating blob metadata: " + blobId, e); } }</code><technical_language>nit: separate assignments separate lines? a confusing of values is assigned/mutated other is assigned line 265</technical_language>

Target:
private boolean updateBlobMetadata(BlobId blobId, String fieldName, Object value) throws CloudStorageException { Objects.requireNonNull(blobId, "BlobId cannot be null"); Objects.requireNonNull(fieldName, "Field name cannot be null"); try { AzureBlobDataAccessor.UpdateResponse updateResponse = azureBlobDataAccessor.updateBlobMetadata(blobId, fieldName, value); Map<String, String> metadataMap = updateResponse.metadata; boolean updatedStorage = updateResponse.wasUpdated; boolean updatedCosmos = false; try { ResourceResponse<Document> response = cosmosDataAccessor.updateMetadata(blobId, fieldName, value); updatedCosmos = response != null; } catch (DocumentClientException dex) { if (dex.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { cosmosDataAccessor.upsertMetadata(CloudBlobMetadata.fromMap(metadataMap)); azureMetrics.blobUpdateRecoverCount.inc(); updatedCosmos = true; } else { throw dex; } } if (updatedStorage || updatedCosmos) { logger.debug("Updated blob metadata set to {}.", blobId, fieldName, value); azureMetrics.blobUpdatedCount.inc(); return true; } else { logger.debug("Blob already has = in ABS and Cosmos", blobId, fieldName, value); return false; } } catch (Exception e) { azureMetrics.blobUpdateErrorCount.inc(); throw toCloudStorageException("Error updating blob metadata: " + blobId, e); } }
Source:
<code><START> protected boolean validateQuota() { <END> getParameters().setQuotaId(QuotaHelper.getInstance().getQuotaIdToConsume(getQuotaId(), getStoragePool())); setStorageDomainId(_oldDisk.getstorage_ids().get(0).getValue()); return (QuotaManager.validateStorageQuota(getStorageDomainId().getValue(), getParameters().getQuotaId(), getStoragePool().getQuotaEnforcementType(), new Double(getParameters().getDiskInfo().getSizeInGigabytes()), getCommandId(), getReturnValue().getCanDoActionMessages())); }</code><technical_language>this validate if i change quota</technical_language>

Target:
protected boolean validateQuota() { boolean quotaValid = true; if (!_oldDisk.getQuotaId().equals(getQuotaId())) { getParameters().setQuotaId(QuotaHelper.getInstance().getQuotaIdToConsume(getQuotaId(), getStoragePool())); setStorageDomainId(_oldDisk.getstorage_ids().get(0).getValue()); quotaValid = (QuotaManager.validateStorageQuota(getStorageDomainId().getValue(), getParameters().getQuotaId(), getStoragePool().getQuotaEnforcementType(), new Double(getParameters().getDiskInfo().getSizeInGigabytes()), getCommandId(), getReturnValue().getCanDoActionMessages())); } return quotaValid; }
Source:
<code>public static void combine(HistogramState state, HistogramState otherState) { <START> requireNonNull(state.get() != null, "this.typedHistogram should always be non-null"); <END> requireNonNull(otherState.get() != null, "scratch state should always be non-null"); TypedHistogram typedHistogram = state.get(); long startSize = typedHistogram.getEstimatedSize(); typedHistogram.addAll(otherState.get()); state.addMemoryUsage(typedHistogram.getEstimatedSize() - startSize); }</code><technical_language>nit: current merged state non-null</technical_language>

Target:
public static void combine(HistogramState state, HistogramState otherState) { requireNonNull(otherState.get() != null, "scratch state should always be non-null"); TypedHistogram typedHistogram = state.get(); long startSize = typedHistogram.getEstimatedSize(); typedHistogram.addAll(otherState.get()); state.addMemoryUsage(typedHistogram.getEstimatedSize() - startSize); }
Source:
<code><START> public ArrayEncoder<Integer> int32s(String name) { <END> final Field field = findMetadataFor(name, ArrayField.class); List<DataHolder> values = new ArrayList<DataHolder>(); data.add(new ArrayDataHolder(values, field.index())); return new ArrayEncoder<Integer>(values, this) { @Override protected DataHolder buildDataHolder(Integer value) { return new Int32DataHolder(value, field.index()); } }; }</code><technical_language>Please refactor int32s int64s share common code</technical_language>

Target:
public ArrayEncoder<Integer> int32s(String name) { final Field field = fieldSearcher.findField(name, ArrayField.class, Int32Field.class); List<DataHolder> values = new ArrayList<DataHolder>(); data.add(new ArrayDataHolder(values, field.index())); return new ArrayEncoder<Integer>(values, this) { @Override protected DataHolder buildDataHolder(Integer value) { return new Int32DataHolder(value, field.index()); } }; }
Source:
<code>public void put(String name, List<String> list) { <START> Objects.requireNonNull(name, "name"); <END> remove(name); if (list == null) return; for (String v : list) { if (v != null) add(name, v); } }</code><technical_language>"name null"</technical_language>

Target:
public void put(String name, List<String> list) { Objects.requireNonNull(name, "name must not be null"); remove(name); if (list == null) return; for (String v : list) { if (v != null) add(name, v); } }
Source:
<code>@Test public void unusedArguments() { try { CodeBlock.builder().add("", "foo"); fail(); } catch (IllegalArgumentException expected) { <START> assertThat(expected).hasMessage("Too many parameters were given; parameters [foo] were unused"); <END> } }</code><technical_language>I this message is a bit much. match? > "Expected 1, 0" > "Expected 0, 1"</technical_language>

Target:
@Test public void unusedArguments() { try { CodeBlock.builder().add("", "foo"); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("Too many parameters were given; expected 0, got 1"); } }
Source:
<code>public BPUserLibraryElement getNewLibrary() { BPListElement[] entries = null; Map<String, String> attributes = null; if (fElementToEdit != null) { entries = fElementToEdit.getChildren(); IBuildpathContainer buildpathContainer = fElementToEdit .getUpdatedContainer(); if (buildpathContainer instanceof IBuildpathContainerExtension3) { IBuildpathContainerExtension3 buildpathContainer3 = (IBuildpathContainerExtension3) buildpathContainer; <START> attributes = buildpathContainer3.getAttributes(); <END> } } return new BPUserLibraryElement(fNameField.getText(), fIsSystemField.isSelected(), entries, attributes); }</code><technical_language>I suggest access attributes in a more direct way, involving IBuildpathContainerExtension3 unnecessary</technical_language>

Target:
public BPUserLibraryElement getNewLibrary() { BPListElement[] entries = null; Map<String, String> attributes = null; if (fElementToEdit != null) { entries = fElementToEdit.getChildren(); attributes = fElementToEdit.getAttributes(); } return new BPUserLibraryElement(fNameField.getText(), fIsSystemField.isSelected(), entries, attributes); }
Source:
<code>public PostDonationCounselling flagForCounselling(long id) { PostDonationCounselling postDonationCounselling = postDonationCounsellingRepository.findById(id); postDonationCounselling.setFlaggedForCounselling(Boolean.TRUE); postDonationCounselling.setCounsellingDate(null); postDonationCounselling.setCounsellingStatus(null); postDonationCounselling.getDonation().setNotes(null); postDonationCounselling.setIsDeleted(Boolean.FALSE); return postDonationCounsellingRepository.update(postDonationCounselling); <START> } <END></code><technical_language>updated fields set</technical_language>

Target:
public PostDonationCounselling flagForCounselling(long id) { PostDonationCounselling postDonationCounselling = postDonationCounsellingRepository.findById(id); postDonationCounselling.setFlaggedForCounselling(Boolean.TRUE); postDonationCounselling.setCounsellingDate(null); postDonationCounselling.setCounsellingStatus(null); postDonationCounselling.getDonation().setNotes(null); postDonationCounselling.setIsDeleted(Boolean.FALSE); postDonationCounselling.setLastUpdated(dateGeneratorService.generateDate()); postDonationCounselling.setLastUpdatedBy(utilController.getCurrentUser()); return postDonationCounsellingRepository.update(postDonationCounselling); }
Source:
<code>public OrderedPartitionableRecord( String stream, PartitionIdType partitionId, SequenceOffsetType sequenceNumber, List<byte[]> data ) { this.stream = stream; this.partitionId = partitionId; <START> this.sequenceNumber = sequenceNumber; <END> this.data = data; }</code><technical_language>Please add null checks for variables this.stream = Preconditions.checkNotNull(stream, "stream")</technical_language>

Target:
public OrderedPartitionableRecord( String stream, PartitionIdType partitionId, SequenceOffsetType sequenceNumber, List<byte[]> data ) { Preconditions.checkNotNull(stream, "stream"); Preconditions.checkNotNull(partitionId, "partitionId"); Preconditions.checkNotNull(sequenceNumber, "sequenceNumber"); this.stream = stream; this.partitionId = partitionId; this.sequenceNumber = sequenceNumber; this.data = data == null ? ImmutableList.of() : data; }
Source:
<code>public void findByLocationNearWithDistance() { final City mumbai = new City("1001", "Mumbai", new Point(19.0990358,72.9612976)); final City pune = new City("1002", "Pune", new Point(18.5247663,73.792756)); final City bangalore = new City("1003", "Bangalore", new Point(12.9542944,77.4905127)); Point solapur = new Point(17.661548,75.8835121); this.cityMap.put(mumbai.getId(), mumbai); this.cityMap.put(pune.getId(), pune); this.cityMap.put(bangalore.getId(), bangalore); List<City> matches = this.cityRepository.findByLocationNear(solapur, new Distance(100, Metrics.KILOMETERS)); int len = matches.size(); assertThat("Nothing should returned", len, equalTo(0)); matches = this.cityRepository.findByLocationNear(solapur, new Distance(250, Metrics.KILOMETERS)); len = matches.size(); assertThat("Pune should return", len, equalTo(1)); assertThat("Pune should return", matches.get(0), hasProperty("name", equalTo("Pune"))); matches = this.cityRepository.findByLocationNear(solapur, new Distance(350, Metrics.KILOMETERS)); len = matches.size(); assertThat("Pune and Mumbai should return", len, equalTo(2)); <START> assertThat("Pune and Mumbai should return", matches, containsInAnyOrder(hasProperty("name", equalTo("Pune")), hasProperty("name", equalTo("Mumbai")))); <END> this.cityMap.remove(mumbai.getId()); this.cityMap.remove(pune.getId()); this.cityMap.remove(bangalore.getId()); }</code><technical_language>changing this line following? assertThat("Pune Mumbai return", matches, containsInAnyOrder(pune, mumbai)); This test less-reflective style is in general. apply tests wrote</technical_language>

Target:
public void findByLocationNearWithDistance() { final City mumbai = new City("1001", "Mumbai", new Point(19.0990358,72.9612976)); final City pune = new City("1002", "Pune", new Point(18.5247663,73.792756)); final City bangalore = new City("1003", "Bangalore", new Point(12.9542944,77.4905127)); Point solapur = new Point(17.661548,75.8835121); this.cityMap.put(mumbai.getId(), mumbai); this.cityMap.put(pune.getId(), pune); this.cityMap.put(bangalore.getId(), bangalore); List<City> matches = this.cityRepository.findByLocationNear(solapur, new Distance(100, Metrics.KILOMETERS)); int len = matches.size(); assertThat("Nothing should returned", len, equalTo(0)); matches = this.cityRepository.findByLocationNear(solapur, new Distance(250, Metrics.KILOMETERS)); len = matches.size(); assertThat("Pune should return", len, equalTo(1)); assertThat("Pune should return", matches.get(0), equalTo(pune)); matches = this.cityRepository.findByLocationNear(solapur, new Distance(350, Metrics.KILOMETERS)); len = matches.size(); assertThat("Pune and Mumbai should return", len, equalTo(2)); assertThat("Pune and Mumbai should return", matches, containsInAnyOrder(pune, mumbai)); this.cityMap.remove(mumbai.getId()); this.cityMap.remove(pune.getId()); this.cityMap.remove(bangalore.getId()); }
Source:
<code>protected List<ResultSetFuture> fetchLabelIds(final Iterator<String> ngrams) { List<ResultSetFuture> resultSets = new ArrayList<>(); while (ngrams.hasNext()) { String ngram = ngrams.next(); if (ngram.isEmpty()) { return resultSets; } ResultSetFuture metricResult = labelIdQuery(ngram, LabelType.METRIC); ResultSetFuture tagkResult = labelIdQuery(ngram, LabelType.TAGK); <START> ResultSetFuture tagvResult = labelIdQuery(ngram, LabelType.TAGV); <END> resultSets.add(metricResult); resultSets.add(tagkResult); resultSets.add(tagvResult); } return resultSets; }</code><technical_language>local variables final</technical_language>

Target:
protected List<ResultSetFuture> fetchLabelIds(final Iterator<String> ngrams) { final List<ResultSetFuture> resultSets = new ArrayList<>(); while (ngrams.hasNext()) { final String ngram = ngrams.next(); if (ngram.isEmpty()) { return resultSets; } final ResultSetFuture metricResult = labelIdQuery(ngram, LabelType.METRIC); final ResultSetFuture tagkResult = labelIdQuery(ngram, LabelType.TAGK); final ResultSetFuture tagvResult = labelIdQuery(ngram, LabelType.TAGV); resultSets.add(metricResult); resultSets.add(tagkResult); resultSets.add(tagvResult); } return resultSets; }
Source:
<code>public String createNewAuthToken(String email) { User user = userService.getUserByEmail(email); List<AuthenticationToken> existingTokens = authenticationTokenRepository.findByUserEmail(email); if (existingTokens.size() >= 4) { <START> authenticationTokenRepository.deleteAll(existingTokens); <END> } return authenticationTokenRepository.saveAndFlush(new AuthenticationToken(user)).getToken(); }</code><technical_language>if more 4 tokens, deleting all? more sense delete oldest right? Deleting introduces a sort of random factor for users. time logged in, other time devices signed out</technical_language>

Target:
public String createNewAuthToken(String email) { User user = userService.getUserByEmail(email); List<AuthenticationToken> existingTokens = authenticationTokenRepository.findByUserEmailOrderByExpiryDate(email); if (existingTokens.size() >= 4) { authenticationTokenRepository.delete(existingTokens.get(0)); } return authenticationTokenRepository.saveAndFlush(new AuthenticationToken(user)).getToken(); }