auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean checkPermission(String permission) { <START> int res = this.ctx.checkCallingOrSelfPermission(permission); <END> return (res == PackageManager.PERMISSION_GRANTED); }</code><technical_language>// nitpick-mode-on change this.ctx ctx? // nitpick-mode-off</technical_language>

Target:
private boolean checkPermission(String permission) { int res = ctx.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); }
Source:
<code>protected void doAsyncAddEntry(final PendingAddOp op) { if (throttler != null) { throttler.acquire(); } boolean wasClosed = false; synchronized (this) { <START> if (getLedgerMetadata().isClosed() || closing) { <END> wasClosed = true; } else { long currentLength = addToLength(op.payload.readableBytes()); op.setLedgerLength(currentLength); pendingAddOps.add(op); } } if (wasClosed) { try { clientCtx.getMainWorkerPool().submit(new SafeRunnable() { @Override public void safeRun() { LOG.warn("Attempt to add to closed ledger: {}", ledgerId); op.cb.addCompleteWithLatency(BKException.Code.LedgerClosedException, LedgerHandleAdv.this, op.getEntryId(), 0, op.ctx); } @Override public String toString() { return String.format("AsyncAddEntryToClosedLedger(lid=%d)", ledgerId); } }); } catch (RejectedExecutionException e) { op.cb.addCompleteWithLatency(BookKeeper.getReturnRc(clientCtx.getBookieClient(), BKException.Code.InterruptedException), LedgerHandleAdv.this, op.getEntryId(), 0, op.ctx); } return; } if (!waitForWritable(distributionSchedule.getWriteSet(op.getEntryId()), op.getEntryId(), 0, clientCtx.getConf().waitForWriteSetMs)) { op.allowFailFastOnUnwritableChannel(); } try { clientCtx.getMainWorkerPool().executeOrdered(ledgerId, op); } catch (RejectedExecutionException e) { op.cb.addCompleteWithLatency(BookKeeper.getReturnRc(clientCtx.getBookieClient(), BKException.Code.InterruptedException), LedgerHandleAdv.this, op.getEntryId(), 0, op.ctx); } }</code><technical_language>getLedgerMetadata().isClosed() || closing is multiple places, good a function for it</technical_language>

Target:
protected void doAsyncAddEntry(final PendingAddOp op) { if (throttler != null) { throttler.acquire(); } boolean wasClosed = false; synchronized (this) { if (isHandleWritable()) { long currentLength = addToLength(op.payload.readableBytes()); op.setLedgerLength(currentLength); pendingAddOps.add(op); } else { wasClosed = true; } } if (wasClosed) { try { clientCtx.getMainWorkerPool().submit(new SafeRunnable() { @Override public void safeRun() { LOG.warn("Attempt to add to closed ledger: {}", ledgerId); op.cb.addCompleteWithLatency(BKException.Code.LedgerClosedException, LedgerHandleAdv.this, op.getEntryId(), 0, op.ctx); } @Override public String toString() { return String.format("AsyncAddEntryToClosedLedger(lid=%d)", ledgerId); } }); } catch (RejectedExecutionException e) { op.cb.addCompleteWithLatency(BookKeeper.getReturnRc(clientCtx.getBookieClient(), BKException.Code.InterruptedException), LedgerHandleAdv.this, op.getEntryId(), 0, op.ctx); } return; } if (!waitForWritable(distributionSchedule.getWriteSet(op.getEntryId()), op.getEntryId(), 0, clientCtx.getConf().waitForWriteSetMs)) { op.allowFailFastOnUnwritableChannel(); } try { clientCtx.getMainWorkerPool().executeOrdered(ledgerId, op); } catch (RejectedExecutionException e) { op.cb.addCompleteWithLatency(BookKeeper.getReturnRc(clientCtx.getBookieClient(), BKException.Code.InterruptedException), LedgerHandleAdv.this, op.getEntryId(), 0, op.ctx); } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); <START> getActivity().registerReceiver(this.broadCastNewMessage, new IntentFilter("report")); <END> }</code><technical_language>this action in Constants file</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); getActivity().registerReceiver(this.broadCastNewMessage, new IntentFilter(Constants.ACTION_REPORT)); }
Source:
<code>public void useMaster() { boolean legacyMetricsEnabled = cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS); assertTrue(legacyMetricsEnabled); <START> List<SlowOps> tables = new ArrayList<>(); <END> for (int i = 0; i < tableCount; i++) { String uniqueName = getUniqueNames(1)[0] + "_" + i; SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount); tables.add(gen); gen.startCompactTask(); } try { getConnector().instanceOperations().waitForBalance(); Map<String,String> configs = getConnector().instanceOperations().getSystemConfiguration(); assertTrue("master config should not be empty", !configs.isEmpty()); } catch (AccumuloException | AccumuloSecurityException ex) { fail("Could not get config from master"); } for (SlowOps t : tables) { try { getConnector().tableOperations().cancelCompaction(t.getTableName()); boolean cancelled = t.blockWhileCompactionRunning(); if (!cancelled) { log.info("Failed to cancel compaction during multiple compaction test clean-up for {}", t.getTableName()); } } catch (AccumuloSecurityException | TableNotFoundException | AccumuloException ex) { log.debug("Exception thrown during multiple table test clean-up", ex); } } }</code><technical_language>Do need SlowOps verify Master is running? this run longer</technical_language>

Target:
public void useMaster() { boolean legacyMetricsEnabled = cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS); assertTrue(legacyMetricsEnabled); List<String> tables = new ArrayList<>(); int tableCount = 4; for (int i = 0; i < tableCount; i++) { String uniqueName = getUniqueNames(1)[0] + "_" + i; tables.add(uniqueName); try { getConnector().tableOperations().create(uniqueName); } catch (AccumuloException | AccumuloSecurityException | TableExistsException ex) { log.debug("Failed to create table: {}", uniqueName, ex); fail("failed to create table: " + uniqueName); } } try { getConnector().instanceOperations().waitForBalance(); Map<String,String> configs = getConnector().instanceOperations().getSystemConfiguration(); assertFalse("master config should not be empty", configs.isEmpty()); } catch (AccumuloException | AccumuloSecurityException ex) { fail("Could not get config from master"); } for (String t : tables) { try { log.debug("Delete test table: {}", t); getConnector().tableOperations().delete(t); } catch (AccumuloSecurityException | TableNotFoundException | AccumuloException ex) { log.debug("Exception thrown deleting table during test clean-up", ex); } } }
Source:
<code>private static double estimateMinorAlleleFraction(final int a, final int r, final double bias) { final double altFraction = (double) a / (a + r); final double initialEstimate = altFraction < 0.5 ? altFraction : 1. - altFraction; final Function<Double, Double> objective = f -> { final double logf = Math.log(f); final double logOneMinusf = Math.log(1. - f); final double logBias = Math.log(bias); final double logAltMinorDenominatorTerm = Math.log(f + (1. - f)*bias); final double logRefMinorDenominatorTerm = Math.log(1. - f + f*bias); final double altMinorLogLikelihood = a * logf + r * (logOneMinusf + logBias) - (a + r) * logAltMinorDenominatorTerm; final double refMinorLogLikelihood = r * (logf + logBias) + a * logOneMinusf - (a + r) * logRefMinorDenominatorTerm; return GATKProtectedMathUtils.logSumExp(altMinorLogLikelihood, refMinorLogLikelihood); }; <START> return OptimizationUtils.argmax(objective, 0.0, 0.5, initialEstimate); <END> }</code><technical_language>extract 0.5 (to consistent done in AlleleFractionSamplers), I a strong opinion</technical_language>

Target:
private static double estimateMinorAlleleFraction(final int a, final int r, final double bias) { final double altFraction = (double) a / (a + r); final double initialEstimate = altFraction < 0.5 ? altFraction : 1. - altFraction; final Function<Double, Double> objective = f -> { final double logf = Math.log(f); final double logOneMinusf = Math.log(1. - f); final double logBias = Math.log(bias); final double logAltMinorDenominatorTerm = Math.log(f + (1. - f)*bias); final double logRefMinorDenominatorTerm = Math.log(1. - f + f*bias); final double altMinorLogLikelihood = a * logf + r * (logOneMinusf + logBias) - (a + r) * logAltMinorDenominatorTerm; final double refMinorLogLikelihood = r * (logf + logBias) + a * logOneMinusf - (a + r) * logRefMinorDenominatorTerm; return GATKProtectedMathUtils.logSumExp(altMinorLogLikelihood, refMinorLogLikelihood); }; return OptimizationUtils.argmax(objective, AlleleFractionState.MIN_MINOR_FRACTION, AlleleFractionState.MAX_MINOR_FRACTION, initialEstimate); }
Source:
<code>public Object parse(ElementInstance instance, Node node, Object value) throws Exception { Object o = node.getChildValue("exterior"); LinearRing exterior = null; <START> if(o instanceof String){ <END> LineString ls =(LineString)(((Node)node.getChildren().get(0)).getChildValue(LineString.class)); return gFactory.createPolygon(ls.getCoordinateSequence()); }else{ exterior = (LinearRing) node.getChildValue("exterior"); } LinearRing[] interior = null; if (node.hasChild("interior")) { List list = node.getChildValues("interior"); List interiors = new ArrayList(); for (int i = 0; i < list.size(); i++) { Object obj = list.get(i); LinearRing lr = null; if (obj instanceof String) { LineString ls = (LineString) (((Node) node.getChildren().get(i+1)).getChildValue(LineString.class)); lr = gFactory.createLinearRing(ls.getCoordinateSequence()) ; } else { lr = (LinearRing)obj; } interiors.add(lr); } interior = (LinearRing[]) interiors.toArray(new LinearRing[interiors.size()]); } if(exterior == null && interior == null){ return null; }else{ return gFactory.createPolygon(exterior, interior); } }</code><technical_language>confused, happen a String instead a geometry? tests ring case, more of issue in another binding working should.. like, a RingBinding returning a LinearRing, bug imho searched in and/or in CurvedGeometryFactory, this more of a workaround</technical_language>

Target:
public Object parse(ElementInstance instance, Node node, Object value) throws Exception { LinearRing exterior = (LinearRing) node.getChildValue("exterior"); LinearRing[] interior = null; if (node.hasChild("interior")) { List list = node.getChildValues("interior"); interior = (LinearRing[]) list.toArray(new LinearRing[list.size()]); } return gFactory.createPolygon(exterior, interior); }
Source:
<code>private void uploadToRPubs(RSConnectPublishInput input, RSConnectPublishResult result, final ProgressIndicator indicator) { if (input.getContentType() == CONTENT_TYPE_DOCUMENT && (!input.hasDocOutput() || !supportedRPubsDocExtension(input.getDocOutput()))) { <START> display_.showErrorMessage("Publish Document", <END> "Only rendered R Markdown documents can be published to RPubs. " + "To publish this document, click Knit to render it to HTML, then " + "click the Publish button above the rendered document."); indicator.onCompleted(); return; } RPubsUploader uploader = new RPubsUploader(rpubsServer_, display_, events_, "rpubs-" + rpubsCount_++); String contentType = contentTypeDesc(input.getContentType()); indicator.onProgress("Uploading " + contentType); uploader.setOnUploadComplete(new CommandWithArg<Boolean>() { @Override public void execute(Boolean arg) { indicator.onCompleted(); } }); uploader.performUpload(contentType, input.getSourceRmd() == null ? null : input.getSourceRmd().getPath(), input.getOriginatingEvent().getHtmlFile(), input.getOriginatingEvent().getFromPrevious() == null ? "" : input.getOriginatingEvent().getFromPrevious().getBundleId(), false); }</code><technical_language>Nit: earlier, I a separate error message for unsupported extensions</technical_language>

Target:
private void uploadToRPubs(RSConnectPublishInput input, RSConnectPublishResult result, final ProgressIndicator indicator) { if (input.getContentType() == CONTENT_TYPE_DOCUMENT) { if (!input.hasDocOutput()) { display_.showErrorMessage("Publish Document", "Only rendered documents can be published to RPubs. " + "To publish this document, click Knit or Preview to render it to HTML, then " + "click the Publish button above the rendered document."); indicator.onCompleted(); return; } else if (!supportedRPubsDocExtension(input.getDocOutput())) { showUnsupportedRPubsFormatMessage(); indicator.onCompleted(); return; } } RPubsUploader uploader = new RPubsUploader(rpubsServer_, display_, events_, "rpubs-" + rpubsCount_++); String contentType = contentTypeDesc(input.getContentType()); indicator.onProgress("Uploading " + contentType); uploader.setOnUploadComplete(new CommandWithArg<Boolean>() { @Override public void execute(Boolean arg) { indicator.onCompleted(); } }); uploader.performUpload(contentType, input.getSourceRmd() == null ? null : input.getSourceRmd().getPath(), input.getOriginatingEvent().getHtmlFile(), input.getOriginatingEvent().getFromPrevious() == null ? "" : input.getOriginatingEvent().getFromPrevious().getBundleId(), false); }
Source:
<code>protected void commitSingleEntry(CacheEntry entry, Metadata metadata, FlagAffectedCommand command, InvocationContext ctx, Flag trackFlag, boolean l1Invalidation) { boolean created = entry.isCreated(); boolean removed = entry.isRemoved(); boolean expired; <START> if (entry instanceof MVCCEntry) { <END> expired = ((MVCCEntry) entry).isExpired(); } else { expired = false; } InternalCacheEntry previousEntry = dataContainer.peek(entry.getKey()); Object previousValue = null; Metadata previousMetadata = null; if (previousEntry != null) { previousValue = previousEntry.getValue(); previousMetadata = previousEntry.getMetadata(); } commitManager.commit(entry, metadata, trackFlag, l1Invalidation); notifyCommitEntry(created, removed, expired, entry, ctx, command, previousValue, previousMetadata); }</code><technical_language>this measurable performance impact, do instanceof check if !created && !removed</technical_language>

Target:
protected void commitSingleEntry(CacheEntry entry, Metadata metadata, FlagAffectedCommand command, InvocationContext ctx, Flag trackFlag, boolean l1Invalidation) { boolean created = entry.isCreated(); boolean removed = entry.isRemoved(); boolean expired; if (removed && entry instanceof MVCCEntry) { expired = ((MVCCEntry) entry).isExpired(); } else { expired = false; } InternalCacheEntry previousEntry = dataContainer.peek(entry.getKey()); Object previousValue = null; Metadata previousMetadata = null; if (previousEntry != null) { previousValue = previousEntry.getValue(); previousMetadata = previousEntry.getMetadata(); } commitManager.commit(entry, metadata, trackFlag, l1Invalidation); notifyCommitEntry(created, removed, expired, entry, ctx, command, previousValue, previousMetadata); }
Source:
<code>public void setValue(Number value) { checkForLock(); if (value == null) { <START> _actual_type = IntegerType.INT; <END> doSetValue(0, true); } else { if (value instanceof BigInteger) { _actual_type = IntegerType.BIG_INTEGER; BigInteger big = (BigInteger) value; doSetValue(big); } else if (value instanceof BigDecimal) { _actual_type = IntegerType.BIG_INTEGER; BigDecimal bd = (BigDecimal) value; doSetValue(bd.toBigInteger()); } else { _actual_type = IntegerType.LONG; doSetValue(value.longValue(), false); } } }</code><technical_language>incorrect. This is setting null.int. Missing unit test</technical_language>

Target:
public void setValue(Number value) { checkForLock(); if (value == null) { doSetValue(0, true); } else if (value instanceof BigInteger) { BigInteger big = (BigInteger) value; doSetValue(big); } else if (value instanceof BigDecimal) { BigDecimal bd = (BigDecimal) value; doSetValue(bd.toBigInteger()); } else { doSetValue(value.longValue(), false); } }
Source:
<code>public Object invoke(StaplerRequest request, StaplerResponse response, Object instance, Object[] arguments) throws IllegalAccessException, InvocationTargetException, ServletException { if (!request.getMethod().equals("POST")) { <START> for (ErrorCustomizer handler : ServiceLoader.load(ErrorCustomizer.class)) { <END> ForwardToView forwardToView = handler.getForwardView(); if (forwardToView != null) { throw new InvocationTargetException(forwardToView.with("requestURL", request.getRequestURLWithQueryString().toString())); } } throw new InvocationTargetException(new HttpResponses.HttpResponseException() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); rsp.addHeader("Allow", "POST"); rsp.setContentType("text/html"); PrintWriter w = rsp.getWriter(); w.println("<html><head><title>POST required</title></head><body>"); w.println("POST is required for " + target.getQualifiedName() + "<br>"); w.println("<form method='POST'><input type='submit' value='Try POSTing'></form>"); w.println("</body></html>"); } }); } return target.invoke(request, response, instance, arguments); }</code><technical_language>Note this context class loader. is _probably_ OK, typically loader of Jenkins core (jenkins.war!/WEB-INF/lib/*.jar). I recommend explicitly request.getWebApp().getClassLoader(), UberClassLoader (includes plugins)</technical_language>

Target:
public Object invoke(StaplerRequest request, StaplerResponse response, Object instance, Object[] arguments) throws IllegalAccessException, InvocationTargetException, ServletException { if (!request.getMethod().equals("POST")) { for (ErrorCustomizer handler : ServiceLoader.load(ErrorCustomizer.class, request.getWebApp().getClassLoader())) { ForwardToView forwardToView = handler.getForwardView(); if (forwardToView != null) { throw new InvocationTargetException(forwardToView.with("requestURL", request.getRequestURLWithQueryString().toString())); } } throw new InvocationTargetException(new HttpResponses.HttpResponseException() { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); rsp.addHeader("Allow", "POST"); rsp.setContentType("text/html"); PrintWriter w = rsp.getWriter(); w.println("<html><head><title>POST required</title></head><body>"); w.println("POST is required for " + target.getQualifiedName() + "<br>"); w.println("<form method='POST'><input type='submit' value='Try POSTing'></form>"); w.println("</body></html>"); } }); } return target.invoke(request, response, instance, arguments); }
Source:
<code>public MapsforgeOSMTileSource(final Context context, final String name, final String attribution, final boolean upSize) { name_ = name; attribution_ = attribution; tileSize_ = upSize ? 512 : 256; displayModel_ = new FixedTileSizeDisplayModel(tileSize_); if (firstTime) { Application app = (Application)context.getApplicationContext(); AndroidGraphicFactory.createInstance(app); firstTime = false; <START> } <END> }</code><technical_language>wondering want pull this out initialise method called CycleStreetsAppSupport.initialise(). I guess initialised if downloaded maps, want. this is musings</technical_language>

Target:
public MapsforgeOSMTileSource(final Context context, final String name, final String attribution, final boolean upSize) { name_ = name; attribution_ = attribution; tileSize_ = upSize ? 512 : 256; displayModel_ = new FixedTileSizeDisplayModel(tileSize_); setupGraphicsFactory(context); }
Source:
<code>public void testTSVBundle() throws Exception { ServiceReference refs[] = m_bundle.getRegisteredServices(); ServiceReference<AbstractFormatterFactory> reference = refs[0]; AbstractFormatterFactory o = m_bundle.getBundleContext().getService(reference); Properties prop = new Properties(); prop.setProperty("format", "tsv"); AbstractFormatter formatter = o.create(prop); Object[] results = formatter.transform("12\t10.05\ttest"); <START> assertEquals(results.length, 3); <END> }</code><technical_language>here. null test for in formatter code</technical_language>

Target:
public void testTSVBundle() throws Exception { ServiceReference refs[] = m_bundle.getRegisteredServices(); ServiceReference<AbstractFormatterFactory> reference = refs[0]; AbstractFormatterFactory o = m_bundle.getBundleContext().getService(reference); Properties prop = new Properties(); Formatter formatter = o.create("tsv", prop); Object[] results = formatter.transform("12\t10.05\ttest"); assertEquals(results.length, 3); assertEquals(results[0], "12"); assertEquals(results[1], "10.05"); assertEquals(results[2], "test"); }
Source:
<code>private void cleanup(File execDir) { if (execDir != null) { try { FileUtils.deleteDirectory(execDir); } catch (IOException e) { <START> Throwables.propagate(e); <END> } } }</code><technical_language>this anti-pattern <LINK_0> move a deprecated method in general</technical_language>

Target:
private void cleanup(File execDir) { if (execDir != null) { try { FileUtils.deleteDirectory(execDir); } catch (IOException e) { throw new RuntimeException(e); } } }
Source:
<code>public ElasticsearchTableDescription getTable(String schemaName, String tableName) { requireNonNull(schemaName, "schemaName is null"); requireNonNull(tableName, "tableName is null"); for (Entry<SchemaTableName, ElasticsearchTableDescription> entry : tableDescriptions.entrySet()) { ElasticsearchTableDescription table = entry.getValue(); <START> if (table.getColumns() == null) { <END> buildColumns(table); } if (!table.isMetadataSet()) { table.setColumnsMetadata(table.getColumns().stream() .map(ElasticsearchColumnMetadata::new) .collect(Collectors.toList())); } } return tableDescriptions.get(new SchemaTableName(schemaName, tableName)); }</code><technical_language>Please clean map of clients closed</technical_language>

Target:
public ElasticsearchTableDescription getTable(String schemaName, String tableName) { requireNonNull(schemaName, "schemaName is null"); requireNonNull(tableName, "tableName is null"); ElasticsearchTableDescription table = tableDescriptions.get(new SchemaTableName(schemaName, tableName)); if (table == null) { return null; } if (table.getColumns().isPresent()) { return table; } List<ElasticsearchColumn> columns = buildColumns(table); ElasticsearchTableDescription result = new ElasticsearchTableDescription( table.getTableName(), table.getSchemaName(), table.getHost(), table.getPort(), table.getClusterName(), table.getIndex(), table.getIndexExactMatch(), table.getType(), Optional.of(columns)); return result; }
Source:
<code>public void setUp() throws Exception { if (repl == null) { intpGroup = new InterpreterGroup(); intpGroup.put("note", new LinkedList<Interpreter>()); repl = new ScioInterpreter(getScioTestProperties()); repl.setInterpreterGroup(intpGroup); intpGroup.get("note").add(repl); repl.open(); } <START> context = new InterpreterContext("note", "id", "title", "text", <END> new AuthenticationInfo(), new HashMap<String, Object>(), new GUI(), new AngularObjectRegistry(intpGroup.getId(), null), new LocalResourcePool("id"), new LinkedList<InterpreterContextRunner>(), new InterpreterOutput(new InterpreterOutputListener() { @Override public void onAppend(InterpreterOutput out, byte[] line) @Override public void onUpdate(InterpreterOutput out, byte[] output) })); }</code><technical_language>@ravwojdyla Zeppelin's java code block indentation is "2" space :)</technical_language>

Target:
public void setUp() throws Exception { if (repl == null) { intpGroup = new InterpreterGroup(); intpGroup.put("note", new LinkedList<Interpreter>()); repl = new ScioInterpreter(new Properties()); repl.setInterpreterGroup(intpGroup); intpGroup.get("note").add(repl); repl.open(); } context = getNewContext(); }
Source:
<code>public boolean performDrop(Object data) { final Object target = getCurrentTarget(); IPath targetNode = null; if (target == null) targetNode = Path.ROOT; if (target instanceof Variable) return false; else if (target instanceof IPath) targetNode = (IPath) target; final AbstractTreeViewer viewer = (AbstractTreeViewer) super.getViewer(); final IStructuredSelection selection = (IStructuredSelection) data; final VariablesTreeContentProvider treeContentProvider = (VariablesTreeContentProvider) viewer.getContentProvider(); for (final Object element : selection.toArray()) { if (element instanceof Variable) { final Variable currentVariable = (Variable) element; <START> if (currentVariable != null) <END> currentVariable.setPath(targetNode); } else if (element instanceof IPath) { final IPath node = (IPath) element; final List<Variable> variables = fModel.getVariables(); targetNode = targetNode.append(node.lastSegment()); treeContentProvider.updatePathGroup(variables, targetNode, node); treeContentProvider.moveSelectedPath(targetNode.makeRelative(), node); } } final Object[] elements = viewer.getExpandedElements(); viewer.refresh(); viewer.setExpandedElements(elements); return true; }</code><technical_language>this null</technical_language>

Target:
public boolean performDrop(Object data) { final Object target = getCurrentTarget(); IPath targetNode = null; if (target == null) targetNode = Path.ROOT; if (target instanceof Variable) return false; else if (target instanceof IPath) targetNode = (IPath) target; final AbstractTreeViewer viewer = (AbstractTreeViewer) super.getViewer(); final IStructuredSelection selection = (IStructuredSelection) data; final VariablesTreeContentProvider treeContentProvider = (VariablesTreeContentProvider) viewer.getContentProvider(); for (final Object element : selection.toArray()) { if (element instanceof Variable) { final Variable currentVariable = (Variable) element; currentVariable.setPath(targetNode); } else if (element instanceof IPath) { final IPath node = (IPath) element; final List<Variable> variables = fModel.getVariables(); targetNode = targetNode.append(node.lastSegment()); VariablesTreeContentProvider.updatePathGroup(variables, targetNode, node); treeContentProvider.moveSelectedPath(targetNode.makeRelative(), node); } } final Object[] elements = viewer.getExpandedElements(); viewer.refresh(); viewer.setExpandedElements(elements); return true; }
Source:
<code>public synchronized void updateVariables(Map<String, String> variablesToUpdate) throws IOException { <START> Map<String, String> rollBackVariables = new HashMap<>(variablesToUpdate.size()); <END> try { for (Map.Entry<String, String> entry : variablesToUpdate.entrySet()) { String oldValue = updateVariableInternal(entry.getKey(), entry.getValue()); rollBackVariables.putIfAbsent(entry.getKey(), oldValue); } refreshCache(); } catch (NoResultException ex) { logger.log(Level.WARNING, "Error while updating variables", ex); for (Map.Entry<String, String> rollback : rollBackVariables.entrySet()) { updateVariableInternal(rollback.getKey(), rollback.getValue()); } throw new IOException(ex); } }</code><technical_language>ok for now, do a review of code in places rollback in application level</technical_language>

Target:
public synchronized void updateVariables(Map<String, String> variablesToUpdate) { for (Map.Entry<String, String> entry : variablesToUpdate.entrySet()) { updateVariableInternal(entry.getKey(), entry.getValue()); } refreshCache(); }
Source:
<code><START> public void testDatastaxDriverConfig() { <END> when(mockConfiguration.getStringProperty(eq(CoreConfig.CASSANDRA_DRIVER))).thenReturn("datastax"); when(mockConfiguration.getBooleanProperty(eq(CoreConfig.STRING_METRICS_DROPPED))).thenReturn(Boolean.TRUE); when(mockConfiguration.getListProperty(eq(CoreConfig.TENANTIDS_TO_KEEP))).thenReturn(new ArrayList<String>()); when(mockConfiguration.getStringProperty(eq(CoreConfig.DELAYED_METRICS_STORAGE_GRANULARITY))).thenReturn("20m"); IOContainer.resetInstance(); IOContainer ioContainer = IOContainer.fromConfig(); ShardStateIO shardStateIO = ioContainer.getShardStateIO(); assertTrue("ShardStateIO instance is Datastax", shardStateIO instanceof DShardStateIO); MetadataIO metadataIO = ioContainer.getMetadataIO(); assertTrue("MetadataIO instance is Datastax", metadataIO instanceof DMetadataIO); }</code><technical_language>lol I guess I debug this a bit</technical_language>

Target:
public void testDatastaxDriverConfig() { when(mockConfiguration.getStringProperty(eq(CoreConfig.CASSANDRA_DRIVER))).thenReturn("datastax"); when(mockConfiguration.getBooleanProperty(eq(CoreConfig.STRING_METRICS_DROPPED))).thenReturn(Boolean.TRUE); when(mockConfiguration.getListProperty(eq(CoreConfig.TENANTIDS_TO_KEEP))).thenReturn(new ArrayList<String>()); IOContainer.resetInstance(); IOContainer ioContainer = IOContainer.fromConfig(); ShardStateIO shardStateIO = ioContainer.getShardStateIO(); assertTrue("ShardStateIO instance is Datastax", shardStateIO instanceof DShardStateIO); MetadataIO metadataIO = ioContainer.getMetadataIO(); assertTrue("MetadataIO instance is Datastax", metadataIO instanceof DMetadataIO); }
Source:
<code>private Resource getPom(PutOptions options, ReleaseDTO instructions, Jar binary) throws Exception, IOException { Resource pom = null; if (instructions.pom.path != null) { if (instructions.pom.path.equals("JAR")) { pom = binary.getPomXmlResources() .findFirst() .orElse(null); } else { pom = createPomFromFile(options.context.getFile(instructions.pom.path)); if (pom == null) { logger.warn( "A pom path was set in the -maven-release instuction, but no file could be found in (base path: {}) ", <START> instructions.pom.path, options.context.getBaseURI() <END> .toString()); } } } else { if (!configuration.ignore_metainf_maven()) { if (options.context.is(Constants.POM)) { pom = binary.getPomXmlResources() .findFirst() .orElse(null); } else { pom = createPomFromFirstMavenPropertiesInJar(binary, options.context); } } if (pom == null) { logger.info("No properties in binary or invalid GAV"); pom = createPomFromContextAndManifest(binary.getManifest(), options.context); } if (pom == null) { pom = createPomFromFirstMavenPropertiesInJar(binary, options.context); } } return pom; }</code><technical_language>I 2nd arg options.context.getBase(). I want a URI here</technical_language>

Target:
private Resource getPom(PutOptions options, ReleaseDTO instructions, Jar binary) throws Exception, IOException { Resource pom = null; if (instructions.pom.path != null) { if (instructions.pom.path.equals("JAR")) { pom = binary.getPomXmlResources() .findFirst() .orElse(null); } else { pom = createPomFromFile(options.context.getFile(instructions.pom.path)); if (pom == null) { logger.warn( "A pom path was set in the -maven-release instuction, but no file could be found in (base path: {}) ", instructions.pom.path, options.context.getBase()); } } } else { if (!configuration.ignore_metainf_maven()) { if (options.context.is(Constants.POM)) { pom = binary.getPomXmlResources() .findFirst() .orElse(null); } else { pom = createPomFromFirstMavenPropertiesInJar(binary, options.context); } } if (pom == null) { logger.info("No properties in binary or invalid GAV"); pom = createPomFromContextAndManifest(binary.getManifest(), options.context); } if (pom == null) { pom = createPomFromFirstMavenPropertiesInJar(binary, options.context); } } return pom; }
Source:
<code>public boolean sendCommand(Command command) throws Exception { long deviceId = command.getDeviceId(); if (command.getId() != 0) { command = getById(command.getId()).clone(); command.setDeviceId(deviceId); } if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); String phone = Context.getIdentityManager().getById(deviceId).getPhone(); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); protocol.sendTextCommand(phone, command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { if (Context.getSmppManager() != null) { Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else { throw new RuntimeException("SMPP client is not enabled"); } } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); } } else { ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); if (activeDevice != null) { activeDevice.sendCommand(command); } else if (!queueing) { <START> throw new RuntimeException("Commands queueing is not enabled"); <END> } else { getDeviceQueue(deviceId).add(command); return false; } } return true; }</code><technical_language>return "Device is offline"</technical_language>

Target:
public boolean sendCommand(Command command) throws Exception { long deviceId = command.getDeviceId(); if (command.getId() != 0) { command = getById(command.getId()).clone(); command.setDeviceId(deviceId); } if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); String phone = Context.getIdentityManager().getById(deviceId).getPhone(); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); protocol.sendTextCommand(phone, command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { if (Context.getSmppManager() != null) { Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else { throw new RuntimeException("SMPP client is not enabled"); } } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); } } else { ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); if (activeDevice != null) { activeDevice.sendCommand(command); } else if (!queueing) { throw new RuntimeException("Device is not online"); } else { getDeviceQueue(deviceId).add(command); return false; } } return true; }
Source:
<code>public boolean equals(Object object) { <START> if (object == null && object.getClass() != getClass()) { <END> return false; } if (object == this) { return true; } TestData rhs = (TestData) object; return new EqualsBuilder() .append(this.syntaxId, rhs.syntaxId) .append(this.prefix, rhs.prefix) .append(this.syntaxExtension, rhs.syntaxExtension) .append(this.ctsExtension, rhs.ctsExtension) .append(this.isSyntaxInputTest, rhs.isSyntaxInputTest) .append(this.ctsData, rhs.ctsData) .append(this.syntaxData, rhs.syntaxData) .append(this.configuration, rhs.configuration) .isEquals(); }</code><technical_language>TestData is designed extended replace this if if (!(object instanceof TestData)). I move if (object == this)</technical_language>

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof TestData)) { return false; } TestData rhs = (TestData) object; return new EqualsBuilder() .append(this.syntaxId, rhs.syntaxId) .append(this.prefix, rhs.prefix) .append(this.syntaxExtension, rhs.syntaxExtension) .append(this.ctsExtension, rhs.ctsExtension) .append(this.isSyntaxInputTest, rhs.isSyntaxInputTest) .append(this.ctsData, rhs.ctsData) .append(this.syntaxData, rhs.syntaxData) .append(this.configuration, rhs.configuration) .isEquals(); }
Source:
<code>public void handleRegularMessage(final Message msg) { if (waitDialog != null) { if (msg.what == UPDATE_PROGRESS) { final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); <START> assert detailProgress > 0; <END> final int secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { final int minsRemaining = secondsRemaining / 60; waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining)); } } else if (msg.what == FINISHED_LOADING_DETAILS) { waitDialog.dismiss(); waitDialog.setOnCancelListener(null); } } }</code><technical_language>generally Java assert statements (except for helping null analysis in some cases). _are_ code reach deleted else, assert is needed. sure, refactoring is wrong</technical_language>

Target:
public void handleRegularMessage(final Message msg) { if (waitDialog != null) { if (msg.what == UPDATE_PROGRESS) { final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); final int secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { final int minsRemaining = secondsRemaining / 60; waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining)); } } else if (msg.what == FINISHED_LOADING_DETAILS) { waitDialog.dismiss(); waitDialog.setOnCancelListener(null); } } }
Source:
<code>public Response updateCredentials(UserCredentials userCredentialChange) { User user = userSchoolDataController.findUser(sessionController.getLoggedUserSchoolDataSource(), sessionController.getLoggedUserIdentifier()); try { userSchoolDataController.updateUserCredentials(user, userCredentialChange.getOldPassword(), userCredentialChange.getUsername(), userCredentialChange.getNewPassword()); return Response.noContent().build(); } catch (SchoolDataBridgeUnauthorizedException e) { return Response.status(Status.FORBIDDEN).build(); } catch (SchoolDataBridgeException e) { <START> return Response.status(Status.BAD_REQUEST).build(); <END> } }</code><technical_language>SchoolDataBridgeException contains a (HTTP) statusCode, this catch block combined one: catch (SchoolDataBridgeException e) { return Response.status(e.getStatusCode()).build(); } In addition that, places in PyramusRestClient throw SchoolDataBridgeInternalException. If of rewritten as... throw new SchoolDataBridgeException(response.getStatus(), String.format("Received http error %d (%s) requesting %s", response.getStatus(), response.getEntity(), path)); ...then HTTP error code REST call Pyramus passed in SchoolDataBridgeException</technical_language>

Target:
public Response updateCredentials(UserCredentials userCredentialChange) { User user = userSchoolDataController.findUser(sessionController.getLoggedUserSchoolDataSource(), sessionController.getLoggedUserIdentifier()); try { userSchoolDataController.updateUserCredentials(user, userCredentialChange.getOldPassword(), userCredentialChange.getUsername(), userCredentialChange.getNewPassword()); return Response.noContent().build(); } catch (SchoolDataBridgeException e) { return Response.status(e.getStatusCode()).build(); } }
Source:
<code>public ObjectColumnSelector makeObjectColumnSelector( DimensionSpec spec, IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerObjectColumnSelector implements ObjectColumnSelector { @Override public Class classOfObject() { return Double.class; } @Override public Object get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { <START> return 0.0; <END> } return dims[dimIndex]; } } return new IndexerObjectColumnSelector(); }</code><technical_language>ZERO_DOUBLE</technical_language>

Target:
public ObjectColumnSelector makeObjectColumnSelector( DimensionSpec spec, IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerObjectColumnSelector implements ObjectColumnSelector { @Override public Class classOfObject() { return Double.class; } @Override public Object get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return DimensionHandlerUtils.ZERO_DOUBLE; } return dims[dimIndex]; } } return new IndexerObjectColumnSelector(); }
Source:
<code>public LocalDate getEnd() { <START> return LocalDate.of(2019, 4, 10); <END> }</code><technical_language>IMO, :man_shrugging:</technical_language>

Target:
public LocalDate getEnd() { return LocalDate.of(2019, 12, 31); }
Source:
<code>public static final void assertJenkinsNotInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) <START> .until(() -> !j.jenkins.get().getQueue().isBlockedByShutdown(task)); <END> }</code><technical_language>suggestion .until(() -> !j.jenkins.getQueue().isBlockedByShutdown(task));</technical_language>

Target:
public static final void assertJenkinsNotInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) .until(() -> !j.jenkins.getQueue().isBlockedByShutdown(task)); }
Source:
<code>private MapSqlParameterSource createBrickParams(GlusterBrickEntity brick) { return getCustomMapSqlParameterSource().addValue("id", brick.getId()) .addValue("volume_id", brick.getVolumeId()) .addValue("server_id", brick.getServerId()) .addValue("brick_dir", brick.getBrickDirectory()) <START> .addValue("brick_order", (brick.getBrickOrder() == null) ? new Integer(0) : brick.getBrickOrder()) <END> .addValue("status", EnumUtils.nameOrNull(brick.getStatus())); }</code><technical_language>Integer.valueOf(0)</technical_language>

Target:
private MapSqlParameterSource createBrickParams(GlusterBrickEntity brick) { return getCustomMapSqlParameterSource().addValue("id", brick.getId()) .addValue("volume_id", brick.getVolumeId()) .addValue("server_id", brick.getServerId()) .addValue("brick_dir", brick.getBrickDirectory()) .addValue("brick_order", (brick.getBrickOrder() == null) ? Integer.valueOf(0) : brick.getBrickOrder()) .addValue("status", EnumUtils.nameOrNull(brick.getStatus())); }
Source:
<code>public XAResourceRecovery createXAResourceRecovery(ResourceAdapter rar, ActivationSpec as, String productName, String productVersion) { <START> throw new UnsupportedOperationException("Operation is not supported!"); <END> }</code><technical_language>This needs a localized message, more detail good</technical_language>

Target:
public XAResourceRecovery createXAResourceRecovery(ResourceAdapter rar, ActivationSpec as, String productName, String productVersion) { throw ROOT_LOGGER.noSupportedOperation("createXAResourceRecovery"); }
Source:
<code>public Button(String name, Controller controller, int id) { this.name = name; this.controller = controller; this.id = id; String skn = Options.get("joyb_"+controller.getIndex()+"_"+id); if (skn != null) { try { Keys keys = MojamComponent.instance.keys; for (Keys.Key key : keys.getAll()) { <START> if (simulKey != null) continue; <END> if (key.name.equals(skn)) { simulKey = key; } } } catch (NullPointerException e) { e.printStackTrace(); } } }</code><technical_language>I assume this break out of for loop find key is supposed simulated. Is right? If remove this add a break assignment in next if statement</technical_language>

Target:
public Button(String name, Controller controller, int id) { this.name = name; this.controller = controller; this.id = id; String skn = Options.get("joyb_"+controller.getIndex()+"_"+id); if (skn != null) { try { Keys keys = MojamComponent.instance.keys; for (Keys.Key key : keys.getAll()) { if (key.name.equals(skn)) { simulKey = key; break; } } } catch (NullPointerException e) { e.printStackTrace(); } } }
Source:
<code>public String getTermNameFromOntology(final OntologyDataManager ontologyDataManager) { <START> if (this.termId != null) { <END> final Term term = ontologyDataManager.getTermById(this.termId.getId()); if (term != null && !StringUtil.isEmpty(term.getName())) { return term.getName(); } else { return this.name; } } else { return this.name; } }</code><technical_language>eliminate repetition - please check this logic if public String getTermNameFromOntology(final OntologyDataManager ontologyDataManager) { if (this.termId != null) { final Term term = ontologyDataManager.getTermById(this.termId.getId()); if (term != null && !StringUtil.isEmpty(term.getName())) { return term.getName(); } } return this.name; }</technical_language>

Target:
public String getTermNameFromOntology(final OntologyDataManager ontologyDataManager) { if (this.termId != null) { final Term term = ontologyDataManager.getTermById(this.termId.getId()); if (term != null && !StringUtil.isEmpty(term.getName())) { return term.getName(); } } return this.name; }
Source:
<code>public synchronized byte[] getEventPayLoad() { if (count >=2 && this.buf[count-2] == this.buf[count-1]) { return Arrays.copyOf(buf, count -1); } if (count >= 2 && buf[count-2] == '\r' && buf[count-1] == '\n') { <START> Arrays.copyOf(buf, count-2); <END> } return Arrays.copyOf(buf, count); }</code><technical_language>return Arrays.copyOf(buf, count-2)</technical_language>

Target:
public synchronized byte[] getEventPayLoad() { if (count >=2 && this.buf[count-2] == this.buf[count-1]) { return Arrays.copyOf(buf, count -1); } if (count >= 2 && buf[count-2] == '\r' && buf[count-1] == '\n') { return Arrays.copyOf(buf, count-2); } return Arrays.copyOf(buf, count); }
Source:
<code>public static String formatDateWithNoYear(long millis) { try { return new SimpleDateFormat("MMMM d").format(millis); <START> } catch (Exception e) { <END> logger.error(e); return null; } }</code><technical_language>catching exception, thrown</technical_language>

Target:
public static String formatDateWithNoYear(long millis) { try { return new SimpleDateFormat("MMMM d").format(millis); } catch (IllegalArgumentException e) { logger.error(e); return null; } }
Source:
<code>public static void requestName(Team team) { sendMsg(team, NAME); String s = null; long start = System.currentTimeMillis(); while((System.currentTimeMillis() - start < 5000) && team.getLastInput() == null) { s = team.read().substring(0, 5); team.setLastInput(s); team.setName(s); } if(team.getLastInput() == null) { } <START> team.setLastInput(null); <END> }</code><technical_language>selbes wie in requestDecision</technical_language>

Target:
public static void requestName(Team team) { team.setLastInput(null); sendMsg(team, NAME); String s = null; long start = System.currentTimeMillis(); while((System.currentTimeMillis() - start < 5000) && team.getLastInput() == null) { s = team.read().substring(0, 5); team.setLastInput(s); team.setName(s); } if(team.getLastInput() == null) { } }
Source:
<code>public Object getPropertyValue(Object id) { if (id instanceof String) { String id2 = (String) id; final ITmfEventField content = fEvent.getContent(); switch (id2) { case ID_EVENT_SOURCE: String source = fEvent.getSource(); ITmfEventField sourceInstance = content.getField(BtfColumnNames.SOURCE_INSTANCE.toString()); <START> return sourceInstance == null ? null : new EntityPropertySource(source, sourceInstance.getValue().toString()); <END> case ID_EVENT_TYPE: return new TypePropertySource(fEvent.getType().getName(), fEvent.getEventDescription()); case ID_EVENT_TARGET: String target = fEvent.getTarget(); ITmfEventField targetInstance = content.getField(BtfColumnNames.TARGET_INSTANCE.toString()); return targetInstance == null ? null : new EntityPropertySource(target, targetInstance.getValue().toString()); case ID_EVENT_EVENT: ITmfEventField event = content.getField(BtfColumnNames.EVENT.toString()); return event == null ? null : new EventPropertySource(event); case ID_EVENT_NOTES: ITmfEventField notes = content.getField(BtfColumnNames.NOTES.toString()); return notes == null ? null : notes.getValue(); default: break; } } return super.getPropertyValue(id); }</code><technical_language>a note, safe return null in a property provider. If entry is null throws exception in face of user. argue done in this file below... longer-term a of handling "return null"</technical_language>

Target:
public Object getPropertyValue(Object id) { if (id instanceof String) { String id2 = (String) id; final ITmfEventField content = fEvent.getContent(); switch (id2) { case ID_EVENT_SOURCE: String source = fEvent.getSource(); ITmfEventField sourceInstance = content.getField(BtfColumnNames.SOURCE_INSTANCE.toString()); return sourceInstance == null ? "null" : new EntityPropertySource(source, sourceInstance.getValue().toString()); case ID_EVENT_TYPE: return new TypePropertySource(fEvent.getType().getName(), fEvent.getEventDescription()); case ID_EVENT_TARGET: String target = fEvent.getTarget(); ITmfEventField targetInstance = content.getField(BtfColumnNames.TARGET_INSTANCE.toString()); return targetInstance == null ? "null" : new EntityPropertySource(target, targetInstance.getValue().toString()); case ID_EVENT_EVENT: ITmfEventField event = content.getField(BtfColumnNames.EVENT.toString()); return event == null ? null : new EventPropertySource(event); case ID_EVENT_NOTES: ITmfEventField notes = content.getField(BtfColumnNames.NOTES.toString()); return notes == null ? null : notes.getValue(); default: break; } } return super.getPropertyValue(id); }