auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String getSignatureInfo(OperationInfo op, boolean isInput) { List<String> signature = op.getSignature(); if (signature == null || signature.isEmpty()) { return "void"; } List<String> result = new ArrayList<>(); for (int i = (isInput ? 0 : 1); i < signature.size(); i += 2) { result.add(signature.get(i)); } return StringUtils.join(result, ", "); }

Target:
protected String getSignatureInfo(OperationInfo op, boolean isInput) { List<String> signature = op.getSignature(); if (signature == null || signature.isEmpty()) { return "void"; } List<String> result = new ArrayList<>(); for (int i = (isInput ? 0 : 1); i < signature.size(); i += 2) { result.add(signature.get(i)); } return String.join(", ", result); }
Source:
public Response handle() throws JSONException { Date expiry = null; SelendroidLogger.log("set cookie to a session command"); String url = getSelendroidDriver().getCurrentUrl(); JSONObject payload = getPayload(); String name = payload.getJSONObject("cookie").get("name").toString(); String value = payload.getJSONObject("cookie").get("value").toString(); if (payload.getJSONObject("cookie").has("expiry")) { expiry = new Date(new Long(payload.getJSONObject("cookie").get("expiry").toString()).longValue()); } Cookie cookie = new Cookie(name, value, "/" ,expiry); getSelendroidDriver().addCookie(url,cookie); return new SelendroidResponse(getSessionId(),""); }

Target:
public Response handle() throws JSONException { Date expiry = null; SelendroidLogger.log("set cookie to a session command"); String url = getSelendroidDriver().getCurrentUrl(); JSONObject cookie = getPayload().getJSONObject("cookie"); String name = cookie.get("name").toString(); String value = cookie.get("value").toString(); if (cookie.getJSONObject("cookie").has("expiry")) { expiry = new Date(new Long(cookie.get("expiry").toString()).longValue()); } Cookie cookie1 = new Cookie(name, value, "/" ,expiry); getSelendroidDriver().addCookie(url,cookie1); return new SelendroidResponse(getSessionId(),""); }
Source:
public Tuple2<List<T>, List<T>> splitAt(int n) { List<T> head = Nil.instance(); List<T> tail = this; while (n > 0 && !tail.isEmpty()) { head = head.prepend(tail.head()); tail = tail.tail(); n--; } return Tuple.of(head.reverse(), tail); }

Target:
public Tuple2<List<T>, List<T>> splitAt(int n) { List<T> init = Nil.instance(); List<T> tail = this; while (n > 0 && !tail.isEmpty()) { init = init.prepend(tail.head()); tail = tail.tail(); n--; } return Tuple.of(init.reverse(), tail); }
Source:
private Response processResponse(Response connectorResponse) { try { SearchRefundsResponse searchResponse = connectorResponse.readEntity(SearchRefundsResponse.class); List<RefundForSearchRefundsResult> results = searchResponse.getRefunds() .stream() .map(refund -> RefundForSearchRefundsResult.valueOf(refund, publicApiUriGenerator.getPaymentURI(refund.getChargeId()), publicApiUriGenerator.getRefundsURI(refund.getChargeId(), refund.getRefundId()))) .collect(Collectors.toList()); HalRepresentation.HalRepresentationBuilder halRepresentation = HalRepresentation .builder() .addProperty("results", results); return Response.ok().entity( paginationDecorator.decoratePagination(halRepresentation, searchResponse, REFUNDS_PATH).build().toString()) .build(); } catch (ProcessingException ex) { throw new SearchRefundsException(ex); } }

Target:
private Response processResponse(Response connectorResponse) { SearchRefundsResponse searchResponse; try { searchResponse = connectorResponse.readEntity(SearchRefundsResponse.class); } catch (ProcessingException ex) { throw new SearchRefundsException(ex); } List<RefundForSearchRefundsResult> results = searchResponse.getRefunds() .stream() .map(refund -> RefundForSearchRefundsResult.valueOf(refund, publicApiUriGenerator.getPaymentURI(refund.getChargeId()), publicApiUriGenerator.getRefundsURI(refund.getChargeId(), refund.getRefundId()))) .collect(Collectors.toList()); HalRepresentation.HalRepresentationBuilder halRepresentation = HalRepresentation .builder() .addProperty("results", results); return Response.ok().entity( paginationDecorator.decoratePagination(halRepresentation, searchResponse, REFUNDS_PATH).build().toString()) .build(); }
Source:
public List<SubmitRecord> canSubmit(ReviewDb db, PatchSet.Id patchSetId) { if (change.getGroupKey() == null) { return canSubmitAlone(db, patchSetId); } else { ResultSet<Change> groupChanges = null; try { groupChanges = db.changes().byGroupKey(change.getGroupKey()); } catch (OrmException err) { return logRuleError("Cannot read group for change " + change.getChangeId(), err); } final List<SubmitRecord> allOutcomes = new ArrayList<SubmitRecord>(); boolean someChangesUnsubmittable = false; try { for (ChangeControl ctl : factory.controlsFor(groupChanges)) { final List<SubmitRecord> submitOutcome = ctl.canSubmitAlone(db, ctl.change.currentPatchSetId()); allOutcomes.addAll(submitOutcome); for (SubmitRecord sr : submitOutcome) { if (sr.status != SubmitRecord.Status.OK && sr.status != SubmitRecord.Status.CLOSED) { someChangesUnsubmittable = true; } } } } catch (NoSuchChangeException err) { return logRuleError("Not all changes returned by group key were valid"); } if (someChangesUnsubmittable) { for (SubmitRecord sr : allOutcomes) { if (sr.status == SubmitRecord.Status.OK) { sr.status = SubmitRecord.Status.GROUP_NOT_READY; } } } return allOutcomes; } }

Target:
public List<SubmitRecord> canSubmit(ReviewDb db, PatchSet.Id patchSetId) { if (change.getGroupKey() == null) { return canSubmitAlone(db, patchSetId); } ResultSet<Change> groupChanges = null; try { groupChanges = db.changes().byGroupKey(change.getGroupKey()); } catch (OrmException err) { return logRuleError( "Cannot read group " + change.getGroupKey().toString() + " for change " + change.getChangeId(), err); } final List<SubmitRecord> allSubmitRecords = new ArrayList<SubmitRecord>(); boolean groupNotReady = false; try { for (ChangeControl ctl : factory.controlsFor(groupChanges)) { final List<SubmitRecord> submitRecords = ctl.canSubmitAlone(db, ctl.change.currentPatchSetId()); allSubmitRecords.addAll(submitRecords); for (SubmitRecord sr : submitRecords) { if (sr.status != SubmitRecord.Status.OK && sr.status != SubmitRecord.Status.CLOSED) { groupNotReady = true; } } } } catch (NoSuchChangeException err) { return logRuleError("You may not have permissions to all the changes in the group"); } if (groupNotReady) { for (SubmitRecord sr : allSubmitRecords) { if (sr.status == SubmitRecord.Status.OK) { sr.status = SubmitRecord.Status.GROUP_NOT_READY; } } } return allSubmitRecords; }
Source:
public static Properties getProxySettings() throws FileNotFoundException, IOException { Properties properties = new Properties(); File iniFile = getIniFile(); if (iniFile == null) { properties.put(RuntimeFieldEditor.PROXYHOST, System.getProperty(RuntimeFieldEditor.PROXYHOST)); properties.put(RuntimeFieldEditor.PROXYPORT, System.getProperty(RuntimeFieldEditor.PROXYPORT)); properties.put(RuntimeFieldEditor.PROXYNONHOSTS, System.getProperty(RuntimeFieldEditor.PROXYNONHOSTS)); } else { BufferedReader bR = new BufferedReader(new FileReader(iniFile)); String line = null; while( (line = bR.readLine()) != null ) { if (line.matches(".*D" + RuntimeFieldEditor.PROXYHOST + ".*")) { String proxyHost = line.split("=")[1].trim(); properties.put(RuntimeFieldEditor.PROXYHOST, proxyHost); } if (line.matches(".*D" + RuntimeFieldEditor.PROXYPORT + ".*")) { String proxyPort = line.split("=")[1].trim(); properties.put(RuntimeFieldEditor.PROXYPORT, proxyPort); } if (line.matches(".*D" + RuntimeFieldEditor.PROXYNONHOSTS + ".*")) { String proxyNonHosts = line.split("=")[1].trim(); proxyNonHosts = proxyNonHosts.replaceAll(PROXYQUOTES, ""); properties.put(RuntimeFieldEditor.PROXYNONHOSTS, proxyNonHosts); } } bR.close(); } return properties; }

Target:
public static Properties getProxySettings() throws FileNotFoundException, IOException { Properties properties = new Properties(); File iniFile = getIniFile(); if (iniFile == null) { String host = System.getProperty(RuntimeFieldEditor.PROXYHOST); if (host != null) { properties.put(RuntimeFieldEditor.PROXYHOST, host); } String port = System.getProperty(RuntimeFieldEditor.PROXYPORT); if (port != null) { properties.put(RuntimeFieldEditor.PROXYPORT, port); } String nonHosts = System.getProperty(RuntimeFieldEditor.PROXYNONHOSTS); if (nonHosts != null) { properties.put(RuntimeFieldEditor.PROXYNONHOSTS, nonHosts); } } else { BufferedReader bR = new BufferedReader(new FileReader(iniFile)); String line = null; while( (line = bR.readLine()) != null ) { if (line.matches(".*D" + RuntimeFieldEditor.PROXYHOST + ".*")) { String proxyHost = line.split("=")[1].trim(); properties.put(RuntimeFieldEditor.PROXYHOST, proxyHost); } if (line.matches(".*D" + RuntimeFieldEditor.PROXYPORT + ".*")) { String proxyPort = line.split("=")[1].trim(); properties.put(RuntimeFieldEditor.PROXYPORT, proxyPort); } if (line.matches(".*D" + RuntimeFieldEditor.PROXYNONHOSTS + ".*")) { String proxyNonHosts = line.split("=")[1].trim(); proxyNonHosts = proxyNonHosts.replaceAll(PROXYQUOTES, ""); properties.put(RuntimeFieldEditor.PROXYNONHOSTS, proxyNonHosts); } } bR.close(); } return properties; }
Source:
public MergedSelectionSet collectFields(FieldCollectorParameters parameters, SelectionSet selectionSet) { Map<String, MergedField> subFields = new LinkedHashMap<>(); Set<String> visitedFragments = new HashSet<>(); this.collectFields(parameters, selectionSet, visitedFragments, subFields); return newMergedSelectionSet().subFields(subFields).build(); }

Target:
public MergedSelectionSet collectFields(FieldCollectorParameters parameters, SelectionSet selectionSet) { Map<String, MergedField> subFields = new LinkedHashMap<>(); Set<String> visitedFragments = new LinkedHashSet<>(); this.collectFields(parameters, selectionSet, visitedFragments, subFields); return newMergedSelectionSet().subFields(subFields).build(); }
Source:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.helper == null) ? 0 : this.helper.hashCode()); return result; }

Target:
public int hashCode() { return super.hashCode() + Objects.hash(this.helper); }
Source:
protected String getPath(String filename) throws IOException { return super.getPath("checks"+File.separator+"whitespace"+File.separator+"nolinewrap"+File.separator+filename); }

Target:
protected String getPath(String filename) throws IOException { return super.getPath("checks" + File.separator + "whitespace" + File.separator + "noLineWrap" + File.separator + filename); }
Source:
public static StageExecutionDescriptor dynamicLifespanScheduleGroupedExecution(List<PlanNodeId> capableScanNodes) { requireNonNull(capableScanNodes, "capableScanNodes is null"); checkArgument(!capableScanNodes.isEmpty()); return new StageExecutionDescriptor(DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION, ImmutableSet.copyOf(capableScanNodes)); }

Target:
public static StageExecutionDescriptor dynamicLifespanScheduleGroupedExecution(List<PlanNodeId> capableScanNodes) { requireNonNull(capableScanNodes, "capableScanNodes is null"); checkArgument(!capableScanNodes.isEmpty(), "capableScanNodes cannot be empty if stage execution strategy is grouped execution"); return new StageExecutionDescriptor(DYNAMIC_LIFESPAN_SCHEDULE_GROUPED_EXECUTION, ImmutableSet.copyOf(capableScanNodes)); }
Source:
public static StageExecutionDescriptor fixedLifespanScheduleGroupedExecution(List<PlanNodeId> capableScanNodes) { requireNonNull(capableScanNodes, "capableScanNodes is null"); checkArgument(!capableScanNodes.isEmpty()); return new StageExecutionDescriptor(FIXED_LIFESPAN_SCHEDULE_GROUPED_EXECUTION, ImmutableSet.copyOf(capableScanNodes)); }

Target:
public static StageExecutionDescriptor fixedLifespanScheduleGroupedExecution(List<PlanNodeId> capableScanNodes) { requireNonNull(capableScanNodes, "capableScanNodes is null"); checkArgument(!capableScanNodes.isEmpty(), "capableScanNodes cannot be empty if stage execution strategy is grouped execution"); return new StageExecutionDescriptor(FIXED_LIFESPAN_SCHEDULE_GROUPED_EXECUTION, ImmutableSet.copyOf(capableScanNodes)); }
Source:
public synchronized void close() { if (status == TrackerStatus.CLOSED) { log.error("TimestampTracker was previously closed!"); return; } status = TrackerStatus.CLOSED; timer.cancel(); closeZkNode(); }

Target:
public synchronized void close() { Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker already closed"); status = TrackerStatus.CLOSED; timer.cancel(); closeZkNode(); }
Source:
public EList<Diff> getDifferences() { return new BasicEList<Diff>(this.diffs); }

Target:
public EList<Diff> getDifferences() { return this.diffs; }
Source:
private void startRootElement(String uri, String localName, String qName, Attributes attributes) { elementStack.push(localName); if ("feed".equals(localName)) { delegate = new AtomHandler(url, elementStack, strict); } else if ("rss".equals(localName)) { return; } else if ("channel".equals(localName)) { delegate = new RSSHandler(url, elementStack, strict); } else if ("sitemapindex".equals(localName)) { delegate = new XMLIndexHandler(url, elementStack, strict); } else if ("urlset".equals(localName)) { delegate = new XMLHandler(url, elementStack, strict); } else { LOG.debug("Skipped unknown root element <{}> in {}", localName, url); return; } delegate.setStrictNamespace(isStrictNamespace()); delegate.setAcceptedNamespaces(acceptedNamespaces); if (isStrictNamespace()) { if (delegate instanceof AtomHandler || delegate instanceof RSSHandler) { return; } if (!isAcceptedNamespace(uri) && uri.startsWith("/")) { try { URL u = new URL(url, uri); uri = u.toString(); } catch (MalformedURLException e) { LOG.warn("Failed to resolve relative namespace URI in sitemap {}", uri, url); } } if (!isAcceptedNamespace(uri)) { String msg; if (!Namespace.isSupported(uri)) { msg = "Unsupported namespace <" + uri + ">"; } else { msg = "Namespace <" + uri + "> not accepted"; } setException(new UnknownFormatException(msg)); delegate = null; return; } } }

Target:
private void startRootElement(String uri, String localName, String qName, Attributes attributes) { elementStack.push(localName); if ("feed".equals(localName)) { delegate = new AtomHandler(url, elementStack, strict); } else if ("channel".equals(localName)) { delegate = new RSSHandler(url, elementStack, strict); } else if ("sitemapindex".equals(localName)) { delegate = new XMLIndexHandler(url, elementStack, strict); } else if ("urlset".equals(localName)) { delegate = new XMLHandler(url, elementStack, strict); } else { LOG.debug("Skipped unknown root element <{}> in {}", localName, url); return; } delegate.setStrictNamespace(isStrictNamespace()); delegate.setAcceptedNamespaces(acceptedNamespaces); if (isStrictNamespace()) { if (delegate instanceof AtomHandler || delegate instanceof RSSHandler) { return; } if (!isAcceptedNamespace(uri) && uri.startsWith("/")) { try { URL u = new URL(url, uri); uri = u.toString(); } catch (MalformedURLException e) { LOG.warn("Failed to resolve relative namespace URI in sitemap {}", uri, url); } } if (!isAcceptedNamespace(uri)) { String msg; if (!Namespace.isSupported(uri)) { msg = "Unsupported namespace <" + uri + ">"; } else { msg = "Namespace <" + uri + "> not accepted"; } setException(new UnknownFormatException(msg)); delegate = null; return; } } }
Source:
public void testUsedPropertiesWithFailure() { Map<String, String> properties = new TreeMap<>(); properties.put("string-value", "some value"); properties.put("boolean-value", "invalid"); ConfigurationFactory configurationFactory = new ConfigurationFactory(properties, null, new TestMonitor()); configurationFactory.registerConfigurationClasses(ImmutableList.of(binder -> configBinder(binder).bindConfig(AnnotatedSetter.class))); List<Message> messages = configurationFactory.validateRegisteredConfigurationProvider(); assertEquals(messages.size(), 1); assertEquals(configurationFactory.getUsedProperties(), ImmutableSet.of("string-value", "boolean-value")); }

Target:
public void testUsedPropertiesWithFailure() { Map<String, String> properties = new TreeMap<>(); properties.put("string-value", "some value"); properties.put("boolean-value", "invalid"); ConfigurationFactory configurationFactory = new ConfigurationFactory(properties, null, new TestMonitor()); configurationFactory.registerConfigurationClasses(ImmutableList.of(binder -> configBinder(binder).bindConfig(AnnotatedSetter.class))); List<Message> messages = configurationFactory.validateRegisteredConfigurationProvider(); assertMessagesMatch(messages, ImmutableList.of(".*Invalid value 'invalid' for type boolean \\(property 'boolean-value'\\).*AnnotatedSetter.*")); assertEquals(configurationFactory.getUsedProperties(), properties.keySet()); }
Source:
protected String searchTrace(String parentId, String traceId, String logic) { String json = null; String query = null; try { if (parentId != null) { Long.parseLong(parentId); } if (traceId != null) { Long.parseLong(traceId); } } catch (NumberFormatException e) { throw new RuntimeException("The passed parentId/traceId is not a number.", e); } if (logic != null && (!logic.equals(LOGIC_AND) && !logic.equals(LOGIC_OR))) { throw new RuntimeException("Wrong logical operator passed to the query. Only " + LOGIC_AND + "," + LOGIC_OR + " are allowed."); } if (parentId != null && traceId != null) { query = "SELECT * FROM " + TRACING_TABLE + " WHERE parent_id=" + parentId + " " + logic + " trace_id=" + traceId; } else if (parentId != null && traceId == null) { query = "SELECT * FROM " + TRACING_TABLE + " WHERE parent_id=" + parentId; } else if (parentId == null && traceId != null) { query = "SELECT * FROM " + TRACING_TABLE + " WHERE trace_id=" + traceId; } json = getResults(query); return getJson(json); }

Target:
protected String searchTrace(String parentId, String traceId, String logic) { String json = null; String query = null; try { if (parentId != null) { Long.parseLong(parentId); } if (traceId != null) { Long.parseLong(traceId); } } catch (NumberFormatException e) { throw new RuntimeException("The passed parentId/traceId is not a number.", e); } if (logic != null && !logic.equals(LOGIC_AND) && !logic.equals(LOGIC_OR)) { throw new RuntimeException("Wrong logical operator passed to the query. Only " + LOGIC_AND + "," + LOGIC_OR + " are allowed."); } if (parentId != null && traceId != null) { query = "SELECT * FROM " + TRACING_TABLE + " WHERE parent_id=" + parentId + " " + logic + " trace_id=" + traceId; } else if (parentId != null && traceId == null) { query = "SELECT * FROM " + TRACING_TABLE + " WHERE parent_id=" + parentId; } else if (parentId == null && traceId != null) { query = "SELECT * FROM " + TRACING_TABLE + " WHERE trace_id=" + traceId; } json = getResults(query); return getJson(json); }
Source:
public AS71Manager(IAS7ManagementDetails details) throws JBoss7ManangerException { try { this.details = details; Object timeout = details.getProperty(IAS7ManagementDetails.PROPERTY_TIMEOUT); int timeout2 = timeout == null || !(timeout instanceof Integer) ? 5000 : ((Integer)timeout).intValue(); this.client = ModelControllerClient.Factory.create( details.getHost(), details.getManagementPort(), getCallbackHandler(), null, timeout2); this.manager = ServerDeploymentManager.Factory.create(client); } catch(UnknownHostException uhe) { throw new JBoss7ManangerException(uhe); } }

Target:
public AS71Manager(IAS7ManagementDetails details) throws JBoss7ManangerException { try { this.details = details; Object timeout = details.getProperty(IAS7ManagementDetails.PROPERTY_TIMEOUT); int timeout2 = !(timeout instanceof Integer) ? DEFAULT_REQUEST_TIMEOUT : ((Integer)timeout).intValue(); this.client = ModelControllerClient.Factory.create( details.getHost(), details.getManagementPort(), getCallbackHandler(), null, timeout2); this.manager = ServerDeploymentManager.Factory.create(client); } catch(UnknownHostException uhe) { throw new JBoss7ManangerException(uhe); } }
Source:
public SnapshotDataStoreVO findParent(DataStoreRole role, Long storeId, Long volumeId) { SearchCriteria<SnapshotDataStoreVO> sc = parentSnapshotSearch.create(); sc.setParameters("volume_id", volumeId); sc.setParameters("store_role", role.toString()); sc.setParameters("state", ObjectInDataStoreStateMachine.State.Ready.name()); sc.setParameters("store_id", storeId); sc.setJoinParameters("snapshotVOSearch", "hypervisorType", Hypervisor.HypervisorType.XenServer); List<SnapshotDataStoreVO> snapshotList = listBy(sc, new Filter(SnapshotDataStoreVO.class, "created", false, null, null)); if (snapshotList != null && snapshotList.size() != 0) { return snapshotList.get(0); } return null; }

Target:
public SnapshotDataStoreVO findParent(DataStoreRole role, Long storeId, Long volumeId) { if(isSnapshotChainingRequired(volumeId)) { SearchCriteria<SnapshotDataStoreVO> sc = parentSnapshotSearch.create(); sc.setParameters("volume_id", volumeId); sc.setParameters("store_role", role.toString()); sc.setParameters("state", ObjectInDataStoreStateMachine.State.Ready.name()); sc.setParameters("store_id", storeId); List<SnapshotDataStoreVO> snapshotList = listBy(sc, new Filter(SnapshotDataStoreVO.class, "created", false, null, null)); if (snapshotList != null && snapshotList.size() != 0) { return snapshotList.get(0); } } return null; }
Source:
public synchronized void flush() throws InterruptedException { isFlushing.set(true); boolean performedWarning = false; while (true) { cleanupFinishedOperations(); if (pendingOperationsWithSize.isEmpty()) { break; } if (!performedWarning && requiresWarning()) { warn(); performedWarning = true; } wait(FINISH_WAIT_MILLIS); } if (performedWarning) { LOG.info("flush() completed"); } isFlushing.set(false); }

Target:
public void flush() throws InterruptedException { isFlushing.set(true); boolean performedWarning = false; while (true) { synchronized (pendingOperationsWithSize) { cleanupFinishedOperations(); if (pendingOperationsWithSize.isEmpty()) { break; } } if (!performedWarning && requiresWarning()) { warn(); performedWarning = true; } synchronized (this) { wait(FINISH_WAIT_MILLIS); } } if (performedWarning) { LOG.info("flush() completed. See the log for previous warnings."); } isFlushing.set(false); }
Source:
public String getDescriptionUsage() { return "Check the correctness of Attribute values under a specified Folder Artifact."; }

Target:
public String getDescriptionUsage() { return "Check the consitency of Attribute values under a specified Folder Artifact."; }
Source:
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException e) { Parser parser = (Parser) recognizer; ATN atn = parser.getATN(); ATNState currentState = atn.states.get(parser.getState()); Analyzer analyzer = new Analyzer(parser.getTokenStream(), atn, parser.getVocabulary(), specialRules, specialTokens, ignoredRules); Map<Integer, Set<String>> candidates = new HashMap<>(); analyzer.process(candidates, currentState, parser.getCurrentToken().getTokenIndex(), parser.getContext()); String expected = candidates.entrySet().stream() .max(Comparator.comparing(Map.Entry::getKey)) .get() .getValue().stream() .sorted() .collect(Collectors.joining(", ")); throw new ParsingException( String.format("mismatched input '%s'. Expecting: %s", ((Token) offendingSymbol).getText(), expected), e, line, charPositionInLine); }

Target:
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException e) { try { Parser parser = (Parser) recognizer; ATN atn = parser.getATN(); ATNState currentState = atn.states.get(parser.getState()); Multimap<Integer, String> candidates = HashMultimap.create(); Analyzer analyzer = new Analyzer(atn, parser.getVocabulary(), specialRules, specialTokens, ignoredRules, parser.getTokenStream(), candidates); analyzer.process(currentState, parser.getCurrentToken().getTokenIndex(), parser.getContext()); String expected = candidates.asMap().entrySet().stream() .max(Comparator.comparing(Map.Entry::getKey)) .get() .getValue().stream() .sorted() .collect(Collectors.joining(", ")); message = String.format("mismatched input '%s'. Expecting: %s", ((Token) offendingSymbol).getText(), expected); } catch (Exception exception) { LOG.error(e, "Unexpected failure when handling parsing error. This is likely a bug in the implementation"); } throw new ParsingException(message, e, line, charPositionInLine); }
Source:
public IndexDiffCacheEntry(Repository repository) { this.repository = repository; repository.getListenerList().addIndexChangedListener( new IndexChangedListener() { public void onIndexChanged(IndexChangedEvent event) { refreshIndexDelta(); } }); repository.getListenerList().addRefsChangedListener( new RefsChangedListener() { public void onRefsChanged(RefsChangedEvent event) { scheduleReloadJob("RefsChanged"); } }); scheduleReloadJob("IndexDiffCacheEntry construction"); createResourceChangeListener(); if(!repository.isBare()) { try { lastIndex = DirCache.read(repository); } catch(IOException ex) { Activator.error(String.format(CoreText.IndexDiffCacheEntry_failed_index_load, repository), ex); } } }

Target:
public IndexDiffCacheEntry(Repository repository) { this.repository = repository; repository.getListenerList().addIndexChangedListener( new IndexChangedListener() { public void onIndexChanged(IndexChangedEvent event) { refreshIndexDelta(); } }); repository.getListenerList().addRefsChangedListener( new RefsChangedListener() { public void onRefsChanged(RefsChangedEvent event) { scheduleReloadJob("RefsChanged"); } }); scheduleReloadJob("IndexDiffCacheEntry construction"); createResourceChangeListener(); if (!repository.isBare()) { try { lastIndex = repository.readDirCache(); } catch(IOException ex) { Activator.error(String.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex); } } }
Source:
public void run() { while (!context.executor.isShutdown()) { try { Thread.sleep(context.getProgressReporterSleepTime()); } catch (InterruptedException e) { LOG.warn("interrupt discarded"); } try { for (ScheduledQueryExecutor worker : runningWorkers) { worker.reportQueryProgress(); } } catch (Exception e) { LOG.error("ProgressReporter encountered exception ", e); } } }

Target:
public void run() { try (NamedThread namedThread = new NamedThread("Scheduled Query Progress Reporter")) { while (!context.executor.isShutdown()) { try { Thread.sleep(context.getProgressReporterSleepTime()); } catch (InterruptedException e) { LOG.warn("interrupt discarded"); } try { for (ScheduledQueryExecutor worker : runningExecutors) { worker.reportQueryProgress(); } } catch (Exception e) { LOG.error("ProgressReporter encountered exception ", e); } } } }
Source:
public String reportProblemForSingle() { this.myDav.uploadFromHome(this.currentStep.getProcess()); serviceManager.getWorkflowService().setProblem(getProblem()); try { this.currentStep = serviceManager.getWorkflowService().reportProblem(this.currentStep, this.problemTask); } catch (DataException e) { logger.error("Problem couldn't be reported: " + e); } this.problem.setMessage(""); this.problemTask = ""; saveStep(); AktuelleSchritteForm asf = (AktuelleSchritteForm) Helper.getManagedBeanValue("#{AktuelleSchritteForm}"); return asf.filterAll(); }

Target:
public String reportProblemForSingle() { this.myDav.uploadFromHome(this.currentStep.getProcess()); serviceManager.getWorkflowService().setProblem(getProblem()); try { this.currentStep = serviceManager.getWorkflowService().reportProblem(this.currentStep, this.problemTask); saveStep(); } catch (DataException e) { logger.error("Problem couldn't be reported: " + e); } this.problem.setMessage(""); this.problemTask = ""; AktuelleSchritteForm asf = (AktuelleSchritteForm) Helper.getManagedBeanValue("#{AktuelleSchritteForm}"); return asf.filterAll(); }
Source:
public String lookupEntityName(EntityEnum entityType, String entityId) { if (entityType != null && (!StringUtils.isEmpty(entityId))) { IEntityNameFinder finder; if (entityType.isGroup()) { finder = EntityNameFinderService.instance().getNameFinder(IEntityGroup.class); } else { finder = EntityNameFinderService.instance().getNameFinder(entityType.getClazz()); } try { return finder.getName(entityId); } catch (Exception e) { log.warn("Couldn't find name for entity " + entityId, e); return null; } } return null; }

Target:
public String lookupEntityName(EntityEnum entityType, String entityId) { if (entityType == null && (StringUtils.isBlank(entityId))) { return null; } IEntityNameFinder finder; if (entityType.isGroup()) { finder = EntityNameFinderService.instance().getNameFinder(IEntityGroup.class); } else { finder = EntityNameFinderService.instance().getNameFinder(entityType.getClazz()); } try { return finder.getName(entityId); } catch (Exception e) { log.warn("Couldn't find name for entity " + entityId, e); return null; } }
Source:
public JsonObject toJson() { final JsonObject root = new JsonObject(); root.add("uuid", uuid); root.add("address", address); root.add("clientType", clientType); root.add("name", name); JsonObject labelsObject = Json.object(); for (String label : labels) { labelsObject.add("label", label); } root.add("labels", labelsObject); return root; }

Target:
public JsonObject toJson() { final JsonObject root = Json.object(); root.add("uuid", uuid); root.add("address", address); root.add("clientType", clientType); root.add("name", name); JsonArray labelsObject = Json.array(); for (String label : labels) { labelsObject.add(label); } root.add("labels", labelsObject); return root; }
Source:
public static void unzipFile(File zipFile, File unzipDirectory, boolean deleteZip) throws IOException { ZipFile zipFileActual = new ZipFile(zipFile); zipFileActual.stream().forEach((ZipEntry zipEntry) -> { if (!zipEntry.isDirectory()) { String fileName = zipEntry.getName(); File newFile = new File(unzipDirectory, fileName); try { newFile.getParentFile().mkdirs(); FileUtils.copyInputStreamToFile(zipFileActual.getInputStream(zipEntry), newFile); } catch (IOException e) { throw new RuntimeException(e); } } }); if (deleteZip) { FileUtils.deleteQuietly(zipFile); } }

Target:
public static void unzipFile(File zipFile, File unzipDirectory, boolean deleteZip) throws IOException { try (ZipFile zipFileActual = new ZipFile(zipFile)) { zipFileActual.stream().forEach((ZipEntry zipEntry) -> { if (!zipEntry.isDirectory()) { String fileName = zipEntry.getName(); File newFile = new File(unzipDirectory, fileName); try { newFile.getParentFile().mkdirs(); FileUtils.copyInputStreamToFile(zipFileActual.getInputStream(zipEntry), newFile); } catch (IOException e) { throw new RuntimeException(e); } finally { if (deleteZip) { FileUtils.deleteQuietly(zipFile); } } } }); } }
Source:
public static void sortSummarizedCoursesByCourseName(List<CourseSummaryBundle> courses) { courses.sort((CourseSummaryBundle obj1, CourseSummaryBundle obj2) -> { String courseName1 = obj1.course.getName(); String courseName2 = obj2.course.getName(); courseName1 = SanitizationHelper.desanitizeIfHtmlSanitized(courseName1); courseName2 = SanitizationHelper.desanitizeFromHtml(courseName2); return courseName1.compareTo(courseName2); }); }

Target:
public static void sortSummarizedCoursesByCourseName(List<CourseSummaryBundle> courses) { courses.sort(Comparator.comparing(obj -> SanitizationHelper.desanitizeFromHtml(obj.course.getName()))); }
Source:
protected void doRemoveRepository(final OrganizationalUnit orgUnit, final String alias, final Optional<org.guvnor.structure.organizationalunit.config.RepositoryInfo> thisRepositoryConfig, final Consumer<Repository> notification, final boolean lock) { SpaceConfigStorage configStorage = this.spaceConfigStorage.get(orgUnit.getName()); try { if (lock) { configStorage.startBatch(); } Optional<Repository> repo = Optional.ofNullable(this.configuredRepositories.getRepositoryByRepositoryAlias(orgUnit.getSpace(), alias)); repo.ifPresent(r -> this.close(r.getDefaultBranch())); for (Repository repository : orgUnit.getRepositories()) { if (repository.getAlias().equals(alias)) { configStorage.deleteRepository(alias); organizationalUnitService.removeRepository(orgUnit, repository); metadataStore.delete(alias); } } repo.ifPresent(r -> notification.accept(r)); } finally { if (lock) { configStorage.endBatch(); } } }

Target:
protected void doRemoveRepository(final OrganizationalUnit orgUnit, final String alias, final Optional<org.guvnor.structure.organizationalunit.config.RepositoryInfo> thisRepositoryConfig, final Consumer<Repository> notification, final boolean lock) { SpaceConfigStorage configStorage = this.spaceConfigStorage.get(orgUnit.getName()); try { if (lock) { configStorage.startBatch(); } Optional<Repository> repo = Optional.ofNullable(this.configuredRepositories.getRepositoryByRepositoryAlias(orgUnit.getSpace(), alias)); repo.ifPresent(r -> this.close(r.getDefaultBranch())); for (Repository repository : orgUnit.getRepositories()) { if (repository.getAlias().equals(alias)) { organizationalUnitService.removeRepository(orgUnit, repository); metadataStore.delete(alias); } } repo.ifPresent(r -> notification.accept(r)); } finally { if (lock) { configStorage.endBatch(); } } }
Source:
public void deleteBy() throws JSONException, AlgoliaException { JSONObject task = index.addObjects(new JSONArray().put(new JSONObject() .put("name", "Washington")) .put(new JSONObject().put("name", "San Francisco")) .put(new JSONObject().put("name", "San Jose"))); index.waitTask(task.getString("taskID")); index.deleteBy(new Query("San")); JSONObject res = index.search(new Query("")); assertEquals(1, res.getInt("nbHits")); }

Target:
public void deleteBy() throws JSONException, AlgoliaException { JSONObject task = index.addObjects( new JSONArray() .put(new JSONObject().put("name", "Washington")) .put(new JSONObject().put("name", "San Francisco")) .put(new JSONObject().put("name", "San Jose")) ); index.waitTask(task.getString("taskID")); task = index.deleteBy(new Query().setTagFilters("a")); index.waitTask(task.getString("taskID")); JSONObject res = index.search(new Query("")); assertEquals(3, res.getInt("nbHits")); }
Source:
public boolean checkAccount(HttpServletRequest request) { HttpSession session = request.getSession(); IProject project = (IProject) session.getAttribute("Project"); IUserSession userSession = (IUserSession) session.getAttribute("UserSession"); AccountObject acc = userSession.getAccount(); if (!acc.getEnable()) { return false; } ScrumRole sr = SessionManager.getScrumRole(request, project, acc); if (sr == null) { return false; } if (sr.isGuest()) { return false; } if (sr.isAdmin()) { return true; } return true; }

Target:
public boolean checkAccount(HttpServletRequest request) { HttpSession session = request.getSession(); IProject project = (IProject) session.getAttribute("Project"); IUserSession userSession = (IUserSession) session.getAttribute("UserSession"); AccountObject account = userSession.getAccount(); if (!account.getEnable()) { return false; } ScrumRole sr = SessionManager.getScrumRole(request, project, account); if (sr == null) { return false; } if (sr.isGuest()) { return false; } if (sr.isAdmin()) { return true; } return true; }
Source:
public boolean refreshCommittedOffsetsIfNeeded(Timer timer) { final Set<TopicPartition> missingFetchPositions = subscriptions.missingFetchPositions(); final Map<TopicPartition, OffsetAndMetadata> offsets = fetchCommittedOffsets(missingFetchPositions, timer); if (offsets == null) return false; for (final Map.Entry<TopicPartition, OffsetAndMetadata> entry : offsets.entrySet()) { final TopicPartition tp = entry.getKey(); final OffsetAndMetadata offsetAndMetadata = entry.getValue(); if (offsetAndMetadata != null) { final ConsumerMetadata.LeaderAndEpoch leaderAndEpoch = metadata.leaderAndEpoch(tp); final SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetAndMetadata.offset(), offsetAndMetadata.leaderEpoch(), leaderAndEpoch); log.info("Setting offset for partition to the committed offset {}", tp, position); entry.getValue().leaderEpoch().ifPresent(epoch -> this.metadata.updateLastSeenEpochIfNewer(entry.getKey(), epoch)); if (this.subscriptions.isAssigned(tp)) this.subscriptions.seekUnvalidated(tp, position); } } return true; }

Target:
public boolean refreshCommittedOffsetsIfNeeded(Timer timer) { final Set<TopicPartition> missingFetchPositions = subscriptions.missingFetchPositions(); final Map<TopicPartition, OffsetAndMetadata> offsets = fetchCommittedOffsets(missingFetchPositions, timer); if (offsets == null) return false; for (final Map.Entry<TopicPartition, OffsetAndMetadata> entry : offsets.entrySet()) { final TopicPartition tp = entry.getKey(); final OffsetAndMetadata offsetAndMetadata = entry.getValue(); if (offsetAndMetadata != null) { entry.getValue().leaderEpoch().ifPresent(epoch -> this.metadata.updateLastSeenEpochIfNewer(entry.getKey(), epoch)); if (this.subscriptions.isAssigned(tp)) { final ConsumerMetadata.LeaderAndEpoch leaderAndEpoch = metadata.leaderAndEpoch(tp); final SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetAndMetadata.offset(), offsetAndMetadata.leaderEpoch(), leaderAndEpoch); this.subscriptions.seekUnvalidated(tp, position); log.info("Setting offset for partition to the committed offset {}", tp, position); } else { log.info("Ignoring the returned since its partition is no longer assigned", offsetAndMetadata, tp); } } } return true; }
Source:
private int calculateStackTraceLevels(ITestResult testResult) { int stackTraceoutputMethod = config.getStackTraceOutputMethod(); if (testResult.isSuccess()) { stackTraceoutputMethod = config.getStackTraceOutputLevelForPassedTests(); } if ((stackTraceoutputMethod & XMLReporterConfig.STACKTRACE_SHORT) == XMLReporterConfig.STACKTRACE_SHORT) { return XMLReporterConfig.STACKTRACE_SHORT; } if ((stackTraceoutputMethod & XMLReporterConfig.STACKTRACE_FULL) == XMLReporterConfig.STACKTRACE_FULL) { return XMLReporterConfig.STACKTRACE_FULL; } return XMLReporterConfig.STACKTRACE_BOTH; }

Target:
private XMLReporterConfig.StackTraceLevels calculateStackTraceLevels(ITestResult testResult) { XMLReporterConfig.StackTraceLevels stackTraceoutputMethod = config.getStackTraceOutput(); if (testResult.isSuccess()) { stackTraceoutputMethod = config.getStackTraceOutputLevelForPassedTests(); } return stackTraceoutputMethod; }
Source:
public Metadata getMetadata(String metadataName) { for (Metadata meta: this.metadatas) { if (meta.getKey().equals(metadataName)) { return meta; } } return null; }

Target:
public Metadata getMetadata(String metadataName) throws EntityNotFoundException { Metadata aux = null; for (Metadata meta: this.metadatas) { if (meta.getKey().equals(metadataName)) { aux = meta; } } if (aux == null) { throw new EntityNotFoundException("Not metadata found: " + metadataName); } return aux; }
Source:
public ResourceAssignment computeBestPossiblePartitionState( T cache, IdealState idealState, Resource resource, CurrentStateOutput currentStateOutput) { System.out.println("Abstract computeBestPossiblePartitionState"); if (LOG.isDebugEnabled()) { LOG.debug("Processing resource:" + resource.getResourceName()); } String stateModelDefName = idealState.getStateModelDefRef(); StateModelDefinition stateModelDef = cache.getStateModelDef(stateModelDefName); ResourceAssignment partitionMapping = new ResourceAssignment(resource.getResourceName()); for (Partition partition : resource.getPartitions()) { Set<String> disabledInstancesForPartition = cache.getDisabledInstancesForPartition(resource.getResourceName(), partition.toString()); List<String> preferenceList = getPreferenceList(partition, idealState, Collections.unmodifiableSet(cache.getLiveInstances().keySet())); Map<String, String> bestStateForPartition = computeBestPossibleStateForPartition(cache.getLiveInstances().keySet(), stateModelDef, preferenceList, currentStateOutput, disabledInstancesForPartition, idealState, cache.getClusterConfig(), partition); partitionMapping.addReplicaMap(partition, bestStateForPartition); } return partitionMapping; }

Target:
public ResourceAssignment computeBestPossiblePartitionState( T cache, IdealState idealState, Resource resource, CurrentStateOutput currentStateOutput) { if (LOG.isDebugEnabled()) { LOG.debug("Processing resource:" + resource.getResourceName()); } String stateModelDefName = idealState.getStateModelDefRef(); StateModelDefinition stateModelDef = cache.getStateModelDef(stateModelDefName); ResourceAssignment partitionMapping = new ResourceAssignment(resource.getResourceName()); for (Partition partition : resource.getPartitions()) { Set<String> disabledInstancesForPartition = cache.getDisabledInstancesForPartition(resource.getResourceName(), partition.toString()); List<String> preferenceList = getPreferenceList(partition, idealState, Collections.unmodifiableSet(cache.getLiveInstances().keySet())); Map<String, String> bestStateForPartition = computeBestPossibleStateForPartition(cache.getLiveInstances().keySet(), stateModelDef, preferenceList, currentStateOutput, disabledInstancesForPartition, idealState, cache.getClusterConfig(), partition); partitionMapping.addReplicaMap(partition, bestStateForPartition); } return partitionMapping; }
Source:
Mono<Response<AnalyzeSentimentResult>> analyzeSentimentWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return analyzeBatchSentimentWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(response -> processSingleResponseErrorResult(response)); }

Target:
Mono<Response<AnalyzeSentimentResult>> analyzeSentimentWithResponse(String text, String language, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); return analyzeBatchSentimentWithResponse( Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) .map(Transforms::processSingleResponseErrorResult); }
Source:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { if (!(node instanceof TopNNode)) { return Optional.empty(); } TopNNode parent = (TopNNode) node; if (!parent.getStep().equals(SINGLE)) { return Optional.empty(); } PlanNode source = lookup.resolve(parent.getSource()); TopNNode result = new TopNNode( idAllocator.getNextId(), source, parent.getCount(), parent.getOrderBy(), parent.getOrderings(), PARTIAL); return Optional.of(new TopNNode( idAllocator.getNextId(), result, parent.getCount(), parent.getOrderBy(), parent.getOrderings(), FINAL)); }

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { if (!(node instanceof TopNNode)) { return Optional.empty(); } TopNNode single = (TopNNode) node; if (!single.getStep().equals(SINGLE)) { return Optional.empty(); } PlanNode source = lookup.resolve(single.getSource()); TopNNode partial = new TopNNode( idAllocator.getNextId(), source, single.getCount(), single.getOrderBy(), single.getOrderings(), PARTIAL); return Optional.of(new TopNNode( idAllocator.getNextId(), partial, single.getCount(), single.getOrderBy(), single.getOrderings(), FINAL)); }
Source:
protected void doExecute() { EObject applyStereotype = element.applyStereotype(stereotypeInTargetContext); EList<EStructuralFeature> eStructuralFeatures = applyStereotype.eClass().getEStructuralFeatures(); for(EStructuralFeature eStructuralFeature : eStructuralFeatures) { String name = eStructuralFeature.getName(); if(!BASE_CLASS.equals(name) && eStructuralFeature.isChangeable()) { applyStereotype.eSet(eStructuralFeature, stereotypeApplication.eGet(eStructuralFeature)); } } }

Target:
protected void doExecute() { EObject applyStereotype = element.applyStereotype(stereotypeInTargetContext); EList<EStructuralFeature> eStructuralFeatures = applyStereotype.eClass().getEStructuralFeatures(); for(EStructuralFeature eStructuralFeature : eStructuralFeatures) { String name = eStructuralFeature.getName(); if(!name.startsWith(Extension.METACLASS_ROLE_PREFIX) && eStructuralFeature.isChangeable()) { applyStereotype.eSet(eStructuralFeature, stereotypeApplication.eGet(eStructuralFeature)); } } }
Source:
public void setName(String name) { Matcher matcher = NPM_NAME_PATTERN.matcher(name); Assert.isTrue(matcher.matches(), "NPM artifact name shoud fit specification (<LINK_0>"); setCoordinate(NAME, name); }

Target:
public void setName(String name) { Matcher matcher = NPM_NAME_PATTERN.matcher(name); Assert.isTrue(matcher.matches(), "The artifact's name should follow the NPM specification (<LINK_0>"); setCoordinate(NAME, name); }
Source:
public void testAdd() throws Exception { BulkReadVeneerApi bulkReadWrapper = new BulkReadVeneerApi(BigtableDataClient.create(settingsBuilder.build()), TABLE_ID); ApiFuture<Result> resultFuture = bulkReadWrapper.add(ByteString.copyFromUtf8("one"), null); assertFalse(resultFuture.isDone()); resultFuture.get(); Filters.Filter filter = Filters.FILTERS.key().regex("cf"); ApiFuture<Result> secBatchResult = bulkReadWrapper.add(ByteString.copyFromUtf8("1"), filter); secBatchResult.get(); assertTrue(resultFuture.isDone()); assertTrue(secBatchResult.isDone()); assertEquals(2, fakeDataService.getReadRowsCount()); }

Target:
public void testAdd() throws Exception { dataClient = BigtableDataClient.create(settingsBuilder.build()); BulkReadWrapper bulkReadWrapper = new BulkReadVeneerApi(dataClient, TABLE_ID); ApiFuture<Result> resultFuture1_1 = bulkReadWrapper.add(ByteString.copyFromUtf8("one"), null); ApiFuture<Result> resultFuture1_2 = bulkReadWrapper.add(ByteString.copyFromUtf8("two"), null); assertFalse(resultFuture1_1.isDone()); Filters.Filter filter = Filters.FILTERS.key().regex("cf"); ApiFuture<Result> secBatchResult1 = bulkReadWrapper.add(ByteString.copyFromUtf8("1"), filter); ApiFuture<Result> secBatchResult2 = bulkReadWrapper.add(ByteString.copyFromUtf8("2"), filter); bulkReadWrapper.sendOutstanding(); resultFuture1_1.get(); resultFuture1_2.get(); secBatchResult1.get(); secBatchResult2.get(); assertTrue(resultFuture1_1.isDone()); assertTrue(resultFuture1_2.isDone()); assertTrue(secBatchResult1.isDone()); assertTrue(secBatchResult2.isDone()); assertEquals(2, fakeDataService.getReadRowsBatchCount()); }