auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getHumanishName() throws IllegalArgumentException { if ("".equals(getPath()) || getPath() == null) throw new IllegalArgumentException(); String s = getPath(); s = s.replace('\\', '/'); String[] elements = s.split("/"); if (elements.length == 0) throw new IllegalArgumentException(); String result = elements[elements.length - 1]; if (Constants.DOT_GIT.equals(result)) result = elements[elements.length - 2]; else if (result.endsWith(Constants.DOT_GIT_EXT)) result = result.substring(0, result.length() - Constants.DOT_GIT_EXT.length()); return result; }

Target:
public String getHumanishName() throws IllegalArgumentException { if ("".equals(getPath()) || getPath() == null) throw new IllegalArgumentException(); String s = getPath(); if (File.separatorChar == '\\') s = s.replace('\\', '/'); String[] elements = s.split("/"); if (elements.length == 0) throw new IllegalArgumentException(); String result = elements[elements.length - 1]; if (Constants.DOT_GIT.equals(result)) result = elements[elements.length - 2]; else if (result.endsWith(Constants.DOT_GIT_EXT)) result = result.substring(0, result.length() - Constants.DOT_GIT_EXT.length()); return result; }
Source:
public void testMessageIsShownIfAccountRequiresAuthorization() throws InterruptedException, UnsupportedEncodingException { MockResponse loginNeedAuthorizationResponse = new MockResponse(); loginNeedAuthorizationResponse.setResponseCode(401); List<RecordedRequest> requests = mockDispatcher.setSignupResponse(loginNeedAuthorizationResponse); String signupText = getResources().getString(R.string.security_signup) + " test@example.com"; signUpUsingEmail("test@example.com"); assertQueryStringEquals(getRequest("test@example.com"), requests.get(0).getUtf8Body()); onView(withText(signupText)).check(matches(isDisplayed())); }

Target:
public void testMessageIsShownIfAccountRequiresAuthorization() throws InterruptedException, UnsupportedEncodingException { MockResponse loginNeedAuthorizationResponse = new MockResponse(); loginNeedAuthorizationResponse.setResponseCode(401); List<RecordedRequest> requests = getMockDispatcher().setSignupResponse(loginNeedAuthorizationResponse); String signupText = getResources().getString(R.string.security_signup) + " test@example.com"; signUpUsingEmail("test@example.com"); assertQueryStringEquals(getRequest("test@example.com"), requests.get(0).getUtf8Body()); onView(withText(signupText)).check(matches(isDisplayed())); }
Source:
public byte[] persistToBytes() { try { return OBJECT_MAPPER.writeValueAsBytes(this); } catch (JsonProcessingException e) { throw new RuntimeException("Exception processing JSON"); } }

Target:
public byte[] persistToBytes() { try { return OBJECT_MAPPER.writeValueAsBytes(this); } catch (JsonProcessingException e) { throw new RuntimeException("Exception processing JSON", e); } }
Source:
public long getSafePointDrId() { synchronized (m_map) { assert (!m_map.isEmpty()); return end(m_map.asRanges().iterator().next()); } }

Target:
public long getSafePointDrId() { assert (!m_map.isEmpty()); return end(m_map.asRanges().iterator().next()); }
Source:
protected <T> void render(Cell.Context context, VM value, SafeHtmlBuilder sb, HasCell<VM, T> hasCell) { Cell<T> cell = hasCell.getCell(); if (cell instanceof StyledImageResourceCell) { ((StyledImageResourceCell) cell).setStyle("display:inline-block;vertical-align:middle;"); } if (cell instanceof TextCellWithTooltip) { ((TextCellWithTooltip) cell).setStyle("display:inline-block;"); } cell.render(context, hasCell.getValue(value), sb); }

Target:
protected <T> void render(Cell.Context context, VM value, SafeHtmlBuilder sb, HasCell<VM, T> hasCell) { Cell<T> cell = hasCell.getCell(); if (cell instanceof StyledImageResourceCell) { ((StyledImageResourceCell) cell).setStyleClass(getTable().getDivImageInlineBlockStyleName()); } if (cell instanceof TextCellWithTooltip) { ((TextCellWithTooltip) cell).setStyleClass(getTable().getDivInlineBlockStyleName()); } cell.render(context, hasCell.getValue(value), sb); }
Source:
public void close() throws Exception { CloseablesListener closeablesListener = new CloseablesListener(); closeablesListener.sample( streamToDisk ); closeablesListener.sample( clientPageCache ); closeablesListener.close(); }

Target:
public void close() throws Exception { IOUtils.closeAll( streamToDisk, clientPageCache ); }
Source:
public HashSet<Project> getProjects() { return projects; }

Target:
public Map<String,Project> getProjects() { return projects; }
Source:
private String result() { return new String(stream.toString()); }

Target:
private String result() { return stream.toString(); }
Source:
private void closeAuthenticatedChannel(boolean signalServer) { mSaslClientHandler.close(); mChannelAuthenticated = false; if (signalServer) { try { mRequestObserver.onCompleted(); } catch (Exception e) { LogUtils.warnWithException(LOG, "Failed signaling server for stream completion.", e); } } }

Target:
private void closeAuthenticatedChannel(boolean signalServer) { mSaslClientHandler.close(); mChannelAuthenticated = false; if (signalServer) { try { mRequestObserver.onCompleted(); } catch (Exception e) { LogUtils.warnWithException(LOG, "Failed signaling server for stream completion for channel: {}.", mChannelKey.toStringShort(), e); } } }
Source:
private DefaultQuerySubmitterImpl(final OperatorChainer operatorChainer, final OperatorChainAllocator chainAllocator, final PhysicalPlanGenerator physicalPlanGenerator, final SSM ssm, final StringIdentifierFactory idfactory, @Parameter(NumSubmitterThreads.class) final int numThreads) { this.tpStage = new ThreadPoolStage<>((tuple) -> { final PhysicalPlan<Operator> physicalPlan = physicalPlanGenerator.generate(tuple); final Iterator<Operator> iterator = GraphUtils.topologicalSort(physicalPlan.getOperators()); final Map<Identifier, OperatorState> operatorStateMap = getInitialStateOfQuery(iterator); final Identifier queryId = idfactory.getNewInstance(tuple.getKey()); ssm.create(queryId, operatorStateMap); final PhysicalPlan<OperatorChain> chainedPlan = operatorChainer.chainOperators(physicalPlan); final DAG<OperatorChain> chainedOperators = chainedPlan.getOperators(); chainAllocator.allocate(chainedOperators); start(chainedPlan); }, numThreads); }

Target:
private DefaultQuerySubmitterImpl(final OperatorChainer operatorChainer, final OperatorChainAllocator chainAllocator, final PhysicalPlanGenerator physicalPlanGenerator, final SSM ssm, final StringIdentifierFactory idfactory, @Parameter(NumSubmitterThreads.class) final int numThreads) { this.physicalPlanMap = new ConcurrentHashMap<>(); this.tpStage = new ThreadPoolStage<>((tuple) -> { final PhysicalPlan<Operator> physicalPlan = physicalPlanGenerator.generate(tuple); final Iterator<Operator> iterator = GraphUtils.topologicalSort(physicalPlan.getOperators()); final Map<Identifier, OperatorState> operatorStateMap = getInitialQueryState(iterator); final Identifier queryId = idfactory.getNewInstance(tuple.getKey()); ssm.create(queryId, operatorStateMap); final PhysicalPlan<OperatorChain> chainedPlan = operatorChainer.chainOperators(physicalPlan); physicalPlanMap.putIfAbsent(tuple.getKey(), chainedPlan); final DAG<OperatorChain> chainedOperators = chainedPlan.getOperators(); chainAllocator.allocate(chainedOperators); start(chainedPlan); }, numThreads); }
Source:
private static int getHttpServicePortProperty(final BundleContext bc, final String propertyName) { Object value; int port = -1; try { int candidate = Integer.MIN_VALUE; final ServiceReference[] refs = bc.getAllServiceReferences("org.osgi.service.http.HttpService", null); for (final ServiceReference ref : refs) { value = ref.getProperty(propertyName); if (value == null) { continue; } final int servicePort; try { servicePort = Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { continue; } value = ref.getProperty(Constants.SERVICE_RANKING); final int serviceRanking; if (value == null || !(value instanceof Integer)) { serviceRanking = 0; } else { serviceRanking = (Integer) value; } if (serviceRanking >= candidate) { candidate = serviceRanking; port = servicePort; } } } catch (final InvalidSyntaxException ex) { } if (port > 0) { return port; } value = bc.getProperty(propertyName); if (value != null) { if (value instanceof String) { try { return Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { } } else if (value instanceof Integer) { return (Integer) value; } } return -1; }

Target:
private static int getHttpServicePortProperty(final BundleContext bc, final String propertyName) { Object value; int port = -1; try { int candidate = Integer.MIN_VALUE; final ServiceReference[] refs = bc.getAllServiceReferences("org.osgi.service.http.HttpService", null); for (final ServiceReference ref : refs) { value = ref.getProperty(propertyName); if (value == null) { continue; } final int servicePort; try { servicePort = Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { continue; } value = ref.getProperty(Constants.SERVICE_RANKING); final int serviceRanking; if (value == null || !(value instanceof Integer)) { serviceRanking = 0; } else { serviceRanking = (Integer) value; } if (serviceRanking >= candidate) { candidate = serviceRanking; port = servicePort; } } } catch (final InvalidSyntaxException ex) { final Logger logger = LoggerFactory.getLogger(HttpServiceUtil.class); logger.warn("This error should only be thrown if a filter could not be parsed. We don't use a filter..."); } if (port > 0) { return port; } value = bc.getProperty(propertyName); if (value != null) { if (value instanceof String) { try { return Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { } } else if (value instanceof Integer) { return (Integer) value; } } return -1; }
Source:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { ITask updatedReview = (ITask) delta.getElement(); if (updatedReview != null && isTaskAssosciatedWithReviewConnector(updatedReview)) { SynchronizationState taskState = updatedReview.getSynchronizationState(); if (taskState.isIncoming()) { ITask assosciatedTask = getTasksAssociatedWithReviewTask(updatedReview); if (assosciatedTask != null) { updateTaskWithIncomingReviewState(assosciatedTask, true); } } else { forceFullRefreshFor(updatedReview); } } } }

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { if (delta.getElement() instanceof ITask) { ITask updatedReview = (ITask) delta.getElement(); if (updatedReview != null && isTaskAssosciatedWithReviewConnector(updatedReview)) { SynchronizationState taskState = updatedReview.getSynchronizationState(); if (taskState.isIncoming()) { ITask assosciatedTask = getTasksAssociatedWithReviewTask(updatedReview); if (assosciatedTask != null) { updateTaskWithIncomingReviewState(assosciatedTask, true); } } else { forceFullRefreshFor(updatedReview); } } } } }
Source:
protected void assignPIDs(Document mets) { int count = 0; Iterator<Element> divs = mets.getDescendants(new ElementFilter("div", JDOMNamespaceUtil.METS_NS)); while(divs.hasNext()) { Element div = divs.next(); String cids = div.getAttributeValue("CONTENTIDS"); if(cids != null && cids.contains("info:fedora/")) continue; PID pid = repository.mintContentPid(); if(cids == null) { div.setAttribute("CONTENTIDS", pid.getURI()); } else { StringBuilder sb = new StringBuilder(pid.getURI()); for(String s : cids.split("\\s")) { sb.append(" ").append(s); } div.setAttribute("CONTENTIDS", sb.toString()); } PremisLogger premisLogger = premisLoggerFactory.createPremisLogger(pid); Resource premisEvent = premisLogger.buildEvent(Premis.Normalization) .addEventDetail("Assigned PID, {0}, to object defined in a METS div", pid) .addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .create(); premisLogger.writeEvent(premisEvent); count++; } log.info(count + " PIDs assigned"); PID depositPID = getDepositPID(); PremisLogger premisDepositLogger = premisLoggerFactory.createPremisLogger(depositPID); Resource premisDepositEvent = premisDepositLogger.buildEvent(Premis.Normalization) .addEventDetail("Assigned {0,choice,1#PID|2#PIDs} to {0,choice,1#one object|2#{0,number} objects} ", count) .create(); premisDepositLogger.writeEvent(premisDepositEvent); }

Target:
protected void assignPIDs(Document mets) { int count = 0; Iterator<Element> divs = mets.getDescendants(new ElementFilter("div", JDOMNamespaceUtil.METS_NS)); while(divs.hasNext()) { Element div = divs.next(); String cids = div.getAttributeValue("CONTENTIDS"); if(cids != null && cids.contains("info:fedora/")) continue; PID pid = repository.mintContentPid(); if(cids == null) { div.setAttribute("CONTENTIDS", pid.getURI()); } else { StringBuilder sb = new StringBuilder(pid.getURI()); for(String s : cids.split("\\s")) { sb.append(" ").append(s); } div.setAttribute("CONTENTIDS", sb.toString()); } PremisLogger premisLogger = getPremisLogger(pid); Resource premisEvent = premisLogger.buildEvent(Premis.Normalization) .addEventDetail("Assigned PID, {0}, to object defined in a METS div", pid) .addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .create(); premisLogger.writeEvent(premisEvent); count++; } log.info(count + " PIDs assigned"); PID depositPID = getDepositPID(); PremisLogger premisDepositLogger = getPremisLogger(depositPID); Resource premisDepositEvent = premisDepositLogger.buildEvent(Premis.Normalization) .addEventDetail("Assigned {0,choice,1#PID|2#PIDs} to {0,choice,1#one object|2#{0,number} objects} ", count) .create(); premisDepositLogger.writeEvent(premisDepositEvent); }
Source:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { synchronized (q) { long now = System.nanoTime(); long end = now + unit.toNanos(timeout); while (isAlive() && (end - now > 0L)) { q.wait((end - now) / 1000L); now = System.nanoTime(); } } return isTerminated(); }

Target:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { synchronized (q) { long now = System.nanoTime(); long end = now + unit.toNanos(timeout); while (isAlive() && (end - now > 0L)) { q.wait(TimeUnit.NANOSECONDS.toMillis(end - now)); now = System.nanoTime(); } } return isTerminated(); }
Source:
public void testExecuteSimpleRuleFlowProcessWithFireAndForgetResponseHandler() throws InterruptedException { List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(commandsFactory.newSetGlobal(LIST_NAME, new ArrayList<String>(), LIST_OUTPUT_NAME)); commands.add(commandsFactory.newStartProcess(PROCESS_ID)); commands.add(commandsFactory.newFireAllRules()); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands, KIE_SESSION); ruleClient.setResponseHandler(new FireAndForgetResponseHandler()); assertNoResponse(ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution)); Thread.sleep(5000); Command getGlobalCommand = commandsFactory.newGetGlobal(LIST_NAME, LIST_OUTPUT_NAME); ruleClient.setResponseHandler(new RequestReplyResponseHandler()); ServiceResponse<ExecutionResults> response = ruleClient.executeCommandsWithResults(CONTAINER_ID, getGlobalCommand); KieServerAssert.assertSuccess(response); ExecutionResults result = response.getResult(); List<String> outcome = (List<String>) result.getValue(LIST_OUTPUT_NAME); assertThat(outcome).isNotNull(); assertThat(outcome).containsExactly("Rule from first ruleflow group executed", "Rule from second ruleflow group executed"); }

Target:
public void testExecuteSimpleRuleFlowProcessWithFireAndForgetResponseHandler() throws Exception { List<Command<?>> commands = new ArrayList<Command<?>>(); commands.add(commandsFactory.newSetGlobal(LIST_NAME, new ArrayList<String>(), LIST_OUTPUT_NAME)); commands.add(commandsFactory.newStartProcess(PROCESS_ID)); commands.add(commandsFactory.newFireAllRules()); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands, KIE_SESSION); ruleClient.setResponseHandler(new FireAndForgetResponseHandler()); ServiceResponse<?> response = ruleClient.executeCommandsWithResults(CONTAINER_ID, batchExecution); assertThat(response).isNull(); ruleClient.setResponseHandler(new RequestReplyResponseHandler()); Command getGlobalCommand = commandsFactory.newGetGlobal(LIST_NAME, LIST_OUTPUT_NAME); List<String> value = new ArrayList<String>(); value.add("Rule from first ruleflow group executed"); value.add("Rule from second ruleflow group executed"); KieServerSynchronization.waitForCommandResult(ruleClient, CONTAINER_ID, getGlobalCommand, LIST_OUTPUT_NAME, value); }
Source:
public void dispose() { fCurrentEntries = checkNotNull(Collections.emptyList()); fTableViewer = null; fComparator = null; }

Target:
public void dispose() { fCurrentEntries = Collections.emptyList(); fTableViewer = null; fComparator = null; }
Source:
public void mouseDown(@Nullable MouseEvent event) { if (event == null || event.button != 1) { return; } int xMouseLocation = event.x; int yMouseLocation = event.y; boolean ctrlMode = false; ISeries[] series = getChart().getSeriesSet().getSeries(); Set<Integer> selections = getSelection(); if ((event.stateMask & SWT.CTRL) != 0) { selections = getSelection(); ctrlMode = true; } else { unsetSelection(); selections = new HashSet<>(); } for (ISeries oneSeries : series) { ILineSeries lineSerie = (ILineSeries) oneSeries; int closest = -1; double closestDistance = -1; for (int i = 0; i < lineSerie.getXSeries().length; i++) { Point dataPoint = lineSerie.getPixelCoordinates(i); double distance = Math.hypot(dataPoint.x - xMouseLocation, dataPoint.y - yMouseLocation); int snapRangeRadius = lineSerie.getSymbolSize() * SELECTION_SNAP_RANGE_MULTIPLIER; if (distance < snapRangeRadius) { if (closestDistance == -1 || distance < closestDistance) { closest = i; closestDistance = distance; } } } if (closest != -1) { int tableEntryIndex = getTableEntryIndexFromGraphIndex(checkNotNull(oneSeries), closest); if (tableEntryIndex < 0) { continue; } LamiTableEntry entry = getResultTable().getEntries().get(tableEntryIndex); int index = getResultTable().getEntries().indexOf(entry); if (!ctrlMode || !selections.remove(index)) { selections.add(index); } break; } } setSelection(selections); LamiSelectionUpdateSignal signal = new LamiSelectionUpdateSignal(this, selections, checkNotNull(getPage())); TmfSignalManager.dispatchSignal(signal); refresh(); }

Target:
public void mouseDown(@Nullable MouseEvent event) { if (event == null || event.button != 1) { return; } int xMouseLocation = event.x; int yMouseLocation = event.y; boolean ctrlMode = false; ISeries[] series = getChart().getSeriesSet().getSeries(); Set<Integer> selections = getSelection(); if ((event.stateMask & SWT.CTRL) != 0) { selections = getSelection(); ctrlMode = true; } else { unsetSelection(); selections = new HashSet<>(); } for (ISeries oneSeries : series) { ILineSeries lineSerie = (ILineSeries) oneSeries; int closest = -1; double closestDistance = -1; for (int i = 0; i < lineSerie.getXSeries().length; i++) { Point dataPoint = lineSerie.getPixelCoordinates(i); double distance = Math.hypot(dataPoint.x - xMouseLocation, dataPoint.y - yMouseLocation); int snapRangeRadius = lineSerie.getSymbolSize() * SELECTION_SNAP_RANGE_MULTIPLIER; if (distance < snapRangeRadius) { if (closestDistance == -1 || distance < closestDistance) { closest = i; closestDistance = distance; } } } if (closest != -1) { int tableEntryIndex = getTableEntryIndexFromGraphIndex(checkNotNull(oneSeries), closest); if (tableEntryIndex < 0) { continue; } LamiTableEntry entry = getResultTable().getEntries().get(tableEntryIndex); int index = getResultTable().getEntries().indexOf(entry); if (!ctrlMode || !selections.remove(index)) { selections.add(index); } break; } } setSelection(selections); LamiSelectionUpdateSignal signal = new LamiSelectionUpdateSignal(this, selections, getPage()); TmfSignalManager.dispatchSignal(signal); refresh(); }
Source:
private void setOperationObjectFromApiOperationAnnotation(Operation operation, io.swagger.oas.annotations.Operation apiOperation) { if (StringUtils.isNotBlank(apiOperation.summary())) { operation.setSummary(apiOperation.summary()); } if (StringUtils.isNotBlank(apiOperation.description())) { operation.setDescription(apiOperation.description()); } if (StringUtils.isNotBlank(apiOperation.operationId())) { operation.setOperationId(getOperationId(apiOperation.operationId())); } if (apiOperation.deprecated()) { operation.setDeprecated(apiOperation.deprecated()); } ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(operation::setTags); OperationParser.getTags(apiOperation.tags()).ifPresent(tag -> openApiTags.addAll(tag)); OperationParser.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(operation::setExternalDocs); OperationParser.getRequestBody(apiOperation.requestBody()).ifPresent(operation::setRequestBody); OperationParser.getApiResponses(apiOperation.responses()).ifPresent(operation::setResponses); OperationParser.getServers(apiOperation.servers()).ifPresent(operation::setServers); OperationParser.getParametersList(apiOperation.parameters()).ifPresent(operation::setParameters); }

Target:
private void setOperationObjectFromApiOperationAnnotation(Operation operation, io.swagger.oas.annotations.Operation apiOperation) { if (StringUtils.isNotBlank(apiOperation.summary())) { operation.setSummary(apiOperation.summary()); } if (StringUtils.isNotBlank(apiOperation.description())) { operation.setDescription(apiOperation.description()); } if (StringUtils.isNotBlank(apiOperation.operationId())) { operation.setOperationId(getOperationId(apiOperation.operationId())); } if (apiOperation.deprecated()) { operation.setDeprecated(apiOperation.deprecated()); } ReaderUtils.getStringListFromStringArray(apiOperation.tags()).ifPresent(operation::setTags); OperationParser.getTags(apiOperation.tags()).ifPresent(tag -> openApiTags.addAll(tag)); OperationParser.getExternalDocumentation(apiOperation.externalDocs()).ifPresent(operation::setExternalDocs); OperationParser.getRequestBody(apiOperation.requestBody(), components).ifPresent(operation::setRequestBody); OperationParser.getApiResponses(apiOperation.responses(), components).ifPresent(operation::setResponses); OperationParser.getServers(apiOperation.servers()).ifPresent(operation::setServers); OperationParser.getParametersList(apiOperation.parameters(), components).ifPresent(operation::setParameters); }
Source:
public void deleteAll(){ for (Subject subject : subjectDataService.retrieveAll()){ delete(subject); } }

Target:
public void deleteAll(){ subjectDataService.deleteAll(); }
Source:
public Object readResolve() throws ObjectStreamException { try { Constructor<? extends SerializableObject> constructor = this.getClass().getConstructor(this.getClass()); try { constructor.setAccessible(true); } catch (SecurityException ex) { logger.warn("Accessing copy constructor failed.", constructor, ex); } try { return constructor.newInstance(this); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new RuntimeException("Instantiation using copy constructor failed!", ex); } } catch (NoSuchMethodException snme) { logger.debug("No copy constructor detected for class {}, trying default constructor.", this.getClass() .getSimpleName()); try { SerializableObject newInstance = this.getClass().newInstance(); transferStateTo(newInstance); return newInstance; } catch (IllegalAccessException | InstantiationException ex) { throw new RuntimeException("Deserialization using default constructor failed!", ex); } } }

Target:
public Object readResolve() throws ObjectStreamException { try { Constructor<? extends SerializableObject> constructor = this.getClass().getConstructor(this.getClass()); try { constructor.setAccessible(true); } catch (SecurityException ex) { logger.warn("Accessing copy constructor failed.", constructor, ex); } try { return constructor.newInstance(this); } catch (ReflectiveOperationException ex) { throw new RuntimeException("Instantiation using copy constructor failed!", ex); } } catch (NoSuchMethodException snme) { logger.debug("No copy constructor detected for class {}, trying default constructor.", this.getClass().getSimpleName()); try { SerializableObject newInstance = this.getClass().newInstance(); transferStateTo(newInstance); return newInstance; } catch (IllegalAccessException | InstantiationException ex) { throw new RuntimeException("Deserialization using default constructor failed!", ex); } } }
Source:
public ToolBar createControl(Composite parent, int orientation) { if (parent != null) { if (toolBarExist() && (parent != toolBar.getParent() || (orientation & toolBar.getStyle()) == 0)) { dispose(); } if (!toolBarExist()) { int style = itemStyle; if ((style & orientation) == 0) { style &= ~SWT.HORIZONTAL & ~SWT.VERTICAL; style |= orientation; } toolBar = new ToolBar(parent, style); toolBar.setMenu(getContextMenuControl()); update(true); toolBar.getAccessible().addAccessibleListener(getAccessibleListener()); } } return toolBar; }

Target:
public ToolBar createControl(Composite parent, int orientation) { if (parent != null) { boolean orientationChanged = (itemStyle & orientation) == 0; if (toolBarExist() && (parent != toolBar.getParent() || orientationChanged)) { dispose(); } if (!toolBarExist()) { if (orientationChanged) { itemStyle &= ~SWT.HORIZONTAL & ~SWT.VERTICAL; itemStyle |= orientation; } toolBar = new ToolBar(parent, itemStyle); toolBar.setMenu(getContextMenuControl()); update(true); toolBar.getAccessible().addAccessibleListener(getAccessibleListener()); } } return toolBar; }
Source:
public Response undeployApiPost(String apiName, String version , String tenantDomain, MessageContext messageContext) { InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer(); if (tenantDomain == null){ tenantDomain =SUPER_TENAT_DOMAIN; } Map<String, String> apiAttributes = inMemoryApiDeployer.getGatewayAPIAttributes(apiName, version, tenantDomain); String apiId = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.API_ID); String label = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.LABEL); boolean status = inMemoryApiDeployer.unDeployAPI(apiId, label); JSONObject responseObj = new JSONObject(); if (status) { responseObj.put("Message", "Success"); String responseStringObj = String.valueOf(responseObj); return Response.ok().entity(responseStringObj).build(); } else { responseObj.put("Message", "Error"); String responseStringObj = String.valueOf(responseObj); return Response.serverError().entity(responseStringObj).build(); } }

Target:
public Response undeployApiPost(String apiName, String version , String tenantDomain, MessageContext messageContext) { InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer(); if (tenantDomain == null) { tenantDomain = APIConstants.SUPER_TENANT_DOMAIN; } Map<String, String> apiAttributes = inMemoryApiDeployer.getGatewayAPIAttributes(apiName, version, tenantDomain); String apiId = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.API_ID); String label = apiAttributes.get(APIConstants.GatewayArtifactSynchronizer.LABEL); boolean status = inMemoryApiDeployer.unDeployAPI(apiId, label); JSONObject responseObj = new JSONObject(); if (status) { responseObj.put("Message", "Success"); String responseStringObj = String.valueOf(responseObj); return Response.ok().entity(responseStringObj).build(); } else { responseObj.put("Message", "Error"); String responseStringObj = String.valueOf(responseObj); return Response.serverError().entity(responseStringObj).build(); } }
Source:
public void placeVisually() { AppCompatActivity activity = UiUtils.getActivityFromView(view); if (!(activity instanceof SpriteActivity)) { return; } Sprite currentSprite = ProjectManager.getInstance().getCurrentSprite(); Formula formulax = getFormulaWithBrickField(BrickField.X_POSITION); Formula formulay = getFormulaWithBrickField(BrickField.Y_POSITION); Intent intent = new Intent(view.getContext(), VisualPlacementActivity.class); intent.putExtra(EXTRA_BRICK_HASH, hashCode()); try { intent.putExtra("X", formulax.interpretInteger(currentSprite)); intent.putExtra("Y", formulay.interpretInteger(currentSprite)); } catch (InterpretationException interpretationException) { intent.putExtra("X", 0); intent.putExtra("Y", 0); } activity.startActivityForResult(intent, REQUEST_CODE_VISUAL_PLACEMENT); }

Target:
public void placeVisually() { AppCompatActivity activity = UiUtils.getActivityFromView(view); if (!(activity instanceof SpriteActivity)) { return; } Sprite currentSprite = ProjectManager.getInstance().getCurrentSprite(); Formula formulax = getFormulaWithBrickField(BrickField.X_POSITION); Formula formulay = getFormulaWithBrickField(BrickField.Y_POSITION); Intent intent = new Intent(view.getContext(), VisualPlacementActivity.class); intent.putExtra(EXTRA_BRICK_HASH, hashCode()); int xValue; int yValue; try { xValue = formulax.interpretInteger(currentSprite); yValue = formulay.interpretInteger(currentSprite); } catch (InterpretationException interpretationException) { xValue = 0; yValue = 0; } intent.putExtra(EXTRA_X_TRANSFORM, xValue); intent.putExtra(EXTRA_Y_TRANSFORM, yValue); activity.startActivityForResult(intent, REQUEST_CODE_VISUAL_PLACEMENT); }
Source:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.setLockingEnabled(false); if (oldVersion == 1) { SmartStore.createLongOperationsStatusTable(db); } }

Target:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.setLockingEnabled(false); }
Source:
public void testScalarFunctionConcat() throws Exception { MockDataContext dc = new MockDataContext("sch", "tab", "1"); Table table = dc.getDefaultSchema().getTables()[0]; MutableColumn col = new MutableColumn("foo").setTable(table); MutableColumn col2 = new MutableColumn("bar").setTable(table); Object[] functionParams = new Object[3]; functionParams[0] = col; functionParams[1] = "$"; functionParams[2] = col2; Query query = dc.query() .from(table) .select(col, FunctionType.CONCAT, functionParams) .where("bar") .eq("hello") .toQuery(); assertEquals("SELECT CONCAT(tab.foo,'$',tab.bar) FROM sch.tab WHERE tab.bar = 'hello'", query.toSql()); DataSet ds = dc.executeQuery(query); assertTrue(ds.next()); assertEquals("Row[values=[1$hello]]", ds.getRow().toString()); assertFalse(ds.next()); }

Target:
public void testScalarFunctionConcat() throws Exception { MockDataContext dc = new MockDataContext("sch", "tab", "1"); Table table = dc.getDefaultSchema().getTables()[0]; MutableColumn col = new MutableColumn("foo").setTable(table); MutableColumn col2 = new MutableColumn("bar").setTable(table); Object[] functionParams = new Object[3]; functionParams[0] = col; functionParams[1] = "$"; functionParams[2] = col2; Query query = dc.query() .from(table) .select(FunctionType.CONCAT, col, functionParams) .where("bar") .eq("hello") .toQuery(); assertEquals("SELECT CONCAT(tab.foo,'$',tab.bar) FROM sch.tab WHERE tab.bar = 'hello'", query.toSql()); DataSet ds = dc.executeQuery(query); assertTrue(ds.next()); assertEquals("Row[values=[1$hello]]", ds.getRow().toString()); assertFalse(ds.next()); }
Source:
public void register(SystemStreamPartition systemStreamPartition, String offset) { if (started.get()) { String msg = String.format("Trying to register partition after consumer has been started. sn=%s, ssp=%s", systemName, systemStreamPartition); LOG.error(msg); throw new SamzaException(msg); } if (!systemStreamPartition.getSystem().equals(systemName)) { LOG.warn("ignoring SSP " + systemStreamPartition + ", because this consumer's system is " + systemName); return; } super.register(systemStreamPartition, offset); TopicPartition tp = toTopicPartition(systemStreamPartition); topicPartitions2SSP.put(tp, systemStreamPartition); LOG.info("Registering ssp = " + systemStreamPartition + " with offset " + offset); String existingOffset = topicPartitions2Offset.get(tp); if (existingOffset == null || compareOffsets(existingOffset, offset) > 0) { topicPartitions2Offset.put(tp, offset); } samzaConsumerMetrics.registerTopicAndPartition(toTopicAndPartition(tp)); }

Target:
public void register(SystemStreamPartition systemStreamPartition, String offset) { if (started.get()) { String msg = String.format("%s: Trying to register partition after consumer has been started. ssp=%s", this, systemStreamPartition); throw new SamzaException(msg); } if (!systemStreamPartition.getSystem().equals(systemName)) { LOG.warn("{}: ignoring SSP {}, because this consumer's system doesn't match.", this, systemStreamPartition); return; } LOG.info("{}: Registering ssp = with offset {}", this, systemStreamPartition, offset); super.register(systemStreamPartition, offset); TopicPartition tp = toTopicPartition(systemStreamPartition); topicPartitionsToSSP.put(tp, systemStreamPartition); String existingOffset = topicPartitionsToOffset.get(tp); if (existingOffset == null || compareOffsets(existingOffset, offset) > 0) { topicPartitionsToOffset.put(tp, offset); } metrics.registerTopicAndPartition(toTopicAndPartition(tp)); }
Source:
protected void closeChannel() { final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { if (lock.tryLock()) { try { if (channel != null) { channel.close(); } } catch (IOException e) { } finally { channel = null; lock.unlock(); } } else { scheduleTask(this); } return null; } }; try { callable.call(); } catch (Exception e) { log.warn("Closing channel faild ", e); } }

Target:
protected void closeChannel() { final Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { if (lock.tryLock()) { try { if (channel != null) { channel.close(); } } catch (IOException e) { } finally { channel = null; lock.unlock(); } } else { scheduleTask(this); } return null; } }; try { callable.call(); } catch (Exception e) { log.warn("Closing channel failed", e); } }
Source:
public boolean isCoercibleTo(PDataType targetType, Object value) { return true; }

Target:
public boolean isCoercibleTo(PDataType targetType, Object value) { return targetType.isCoercibleTo(targetType, value); }
Source:
public void startImport(final Range<DateTime> dateRange, final String configName) { validateNoImportInProgress(); validateDateRange(dateRange); LOGGER.info("Initiating form import for historical forms from to [config: {}]", dateRange.getMin(), dateRange.getMax(), configName); initForImport(dateRange, configName); importThread = new Thread(new Runnable() { @Override public void run() { boolean hasMore = false; LOGGER.debug("Import thread started"); final FormListRequestBuilder requestBuilder = formListRequestBuilder(dateRange, fetchSize, pageCount); do { try { FormListRequest request = requestBuilder.build(); LOGGER.debug("Retrieving forms from page {}, with page size {}", request.getPageNumber(), request.getPageSize()); CommcareFormList formList = formService.retrieveFormList(request, configName); LOGGER.debug("Retrieved a list of forms", formList.getObjects().size()); importFormList(formList); LOGGER.debug("Imported forms", formList.getObjects().size()); hasMore = request.getPageNumber() > 1; if (hasMore) { LOGGER.debug("Proceeding to the next batch of forms"); requestBuilder.withPreviousPage(); } } catch (RuntimeException e) { LOGGER.error("Error while importing forms", e); LOGGER.error("{} of forms imported.", importCount, totalCount); handleImportError(e, configName); } } while (importInProgress && hasMore); LOGGER.info("Form import finished. of forms imported. Last form xmlns to be imported was {}", importCount, totalCount, lastFormXMLNSToBeImported); importInProgress = false; } }); LOGGER.debug("Starting import thread"); importThread.start(); }

Target:
public void startImport(final Range<DateTime> dateRange, final String configName) { validateNoImportInProgress(); validateDateRange(dateRange); LOGGER.info("Initiating form import for historical forms from to [config: {}]", dateRange.getMin(), dateRange.getMax(), configName); initForImport(dateRange, configName); importThread = new Thread(new Runnable() { @Override public void run() { boolean hasMore = false; LOGGER.debug("Import thread started"); final FormListRequestBuilder requestBuilder = formListRequestBuilder(dateRange, fetchSize, pageCount); do { try { FormListRequest request = requestBuilder.build(); LOGGER.debug("Retrieving forms from page {}, with page size {}", request.getPageNumber(), request.getPageSize()); CommcareFormList formList = formService.retrieveFormList(request, configName); LOGGER.debug("Retrieved a list of forms", formList.getObjects().size()); importFormList(formList); LOGGER.debug("Imported forms", formList.getObjects().size()); hasMore = request.getPageNumber() > 1; if (hasMore) { LOGGER.debug("Proceeding to the next batch of forms"); requestBuilder.withPreviousPage(); } } catch (RuntimeException e) { LOGGER.error("Error while importing forms", e); LOGGER.error("{} of forms imported. Last form xmlns to be imported was {}", importCount, totalCount, lastFormXMLNSToBeImported); handleImportError(e, configName); } } while (importInProgress && hasMore); LOGGER.info("Form import finished. of forms imported. ", importCount, totalCount); importInProgress = false; } }); LOGGER.debug("Starting import thread"); importThread.start(); }
Source:
protected ICommand getSetCommand(SetRequest req) { ICommand cmd = super.getSetCommand(req); if (req.getElementToEdit() instanceof Interaction && req.getValue() instanceof List<?>) { if (UMLPackage.eINSTANCE.getInteraction_Fragment() == req.getFeature()) { Interaction interaction = ((Interaction) req.getElementToEdit()); EList<InteractionFragment> currentList = interaction.getFragments(); List<InteractionFragment> newList = (List<InteractionFragment>) req.getValue(); if (hasNewFragment(currentList, newList)) { InteractionFragment newFragment = getNewFragment(currentList, newList); if (newFragment instanceof MessageOccurrenceSpecification) { cmd = UnexecutableCommand.INSTANCE; } } } } return cmd; }

Target:
protected ICommand getSetCommand(SetRequest req) { ICommand cmd = super.getSetCommand(req); if (null != req && req.getElementToEdit() instanceof Interaction && req.getValue() instanceof List<?>) { if (UMLPackage.eINSTANCE.getInteraction_Fragment() == req.getFeature()) { Interaction interaction = ((Interaction) req.getElementToEdit()); EList<InteractionFragment> currentList = interaction.getFragments(); List<InteractionFragment> newList = (List<InteractionFragment>) req.getValue(); if (hasNewFragment(currentList, newList)) { InteractionFragment newFragment = getNewFragment(currentList, newList); if (newFragment instanceof MessageOccurrenceSpecification) { cmd = UnexecutableCommand.INSTANCE; } } } } return cmd; }
Source:
public void start() { scheduler = Schedulers.newElastic("EventProcessorAsyncClient"); disposable = scheduler.schedule(this::run); }

Target:
public synchronized void start() { if (!started.compareAndSet(false, true)) { logger.info("Event processor is already running"); return; } logger.info("Starting a new event processor instance with id {}", this.identifier); scheduler = Schedulers.newElastic("EventProcessorAsyncClient"); runner = scheduler.schedulePeriodically(this::run, INITIAL_DELAY, INTERVAL_IN_SECONDS, TimeUnit.SECONDS); }
Source:
public boolean updateAccounts(Collection<Account> accounts) { Objects.requireNonNull(accounts, "accounts cannot be null"); if (accounts.isEmpty()) { logger.debug("Empty account collection to update."); return false; } if (mySqlAccountStore == null) { logger.info("MySql Account DB store is not accessible"); return false; } if (config.updateDisabled) { logger.info("Updates has been disabled"); return false; } if (hasDuplicateAccountIdOrName(accounts)) { logger.error("Duplicate account id or name exist in the accounts to update"); return false; } rwLock.readLock().lock(); try { if (accountInfoMap.hasConflictingAccount(accounts)) { logger.error("Accounts={} conflict with the accounts in local cache. Cancel the update operation.", accounts); return false; } } finally { rwLock.readLock().unlock(); } try { updateAccountsWithMySqlStore(accounts); } catch (SQLException e) { logger.error("Failed updating accounts={} in MySql DB", accounts, e); return false; } rwLock.writeLock().lock(); try { accountInfoMap.updateAccounts(accounts); } finally { rwLock.writeLock().unlock(); } return true; }

Target:
public boolean updateAccounts(Collection<Account> accounts) { Objects.requireNonNull(accounts, "accounts cannot be null"); if (accounts.isEmpty()) { logger.debug("Empty account collection to update."); return false; } if (mySqlAccountStore == null) { logger.warn("MySql Account DB store is not accessible"); return false; } if (config.updateDisabled) { logger.info("Updates have been disabled"); return false; } if (hasDuplicateAccountIdOrName(accounts)) { logger.error("Duplicate account id or name exist in the accounts to update"); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } infoMapLock.readLock().lock(); try { if (accountInfoMap.hasConflictingAccount(accounts)) { logger.error("Accounts={} conflict with the accounts in local cache. Cancel the update operation.", accounts); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } for (Account account : accounts) { if (accountInfoMap.hasConflictingContainer(account.getAllContainers(), account.getId())) { logger.error( "Containers={} under Account={} conflict with the containers in local cache. Cancel the update operation.", account.getAllContainers(), account.getId()); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } } } finally { infoMapLock.readLock().unlock(); } try { updateAccountsWithMySqlStore(accounts); } catch (SQLException e) { logger.error("Failed updating accounts={} in MySql DB", accounts, e); accountServiceMetrics.updateAccountErrorCount.inc(); return false; } infoMapLock.writeLock().lock(); try { accountInfoMap.updateAccounts(accounts); } finally { infoMapLock.writeLock().unlock(); } return true; }
Source:
private void mockValidateCustomProperties() { doReturn(Collections.EMPTY_LIST).when(command).validateCustomProperties(any(VmStatic.class)); }

Target:
private void mockValidateCustomProperties() { doReturn(Collections.<ValidationError>emptyList()).when(command).validateCustomProperties(any(VmStatic.class)); }
Source:
public void onCompletion(Void result, Exception exception) { long processingStartTimeMs = SystemTime.getInstance().milliseconds(); metrics.getPeersSecurityRequestTimeInMs.update(processingStartTimeMs - operationStartTimeMs); ReadableStreamChannel channel = null; try { if (exception == null) { securityService.postProcessRequest(restRequest, new SecurityPostProcessRequestCallback(restRequest, restResponseChannel, callback)); } } catch (Exception e) { exception = e; } finally { metrics.getPeersSecurityRequestCallbackProcessingTimeInMs.update( SystemTime.getInstance().milliseconds() - processingStartTimeMs); if (exception != null) { callback.onCompletion(null, exception); } } }

Target:
public void onCompletion(Void result, Exception exception) { long processingStartTimeMs = SystemTime.getInstance().milliseconds(); metrics.getPeersSecurityRequestTimeInMs.update(processingStartTimeMs - operationStartTimeMs); try { if (exception == null) { securityService.postProcessRequest(restRequest, new SecurityPostProcessRequestCallback(restRequest, restResponseChannel, callback)); } } catch (Exception e) { exception = e; } finally { metrics.getPeersSecurityRequestCallbackProcessingTimeInMs.update( SystemTime.getInstance().milliseconds() - processingStartTimeMs); if (exception != null) { callback.onCompletion(null, exception); } } }
Source:
int getDayOfMonth() { if (isYearDay() || isLeapDay()) { return 0; } int doy = getDayOfYearAdjusted() - 1; return 1 + (doy % InternationalFixedChronology.DAYS_IN_MONTH); }

Target:
int getDayOfMonth() { return this.day; }
Source:
public synchronized IAntClasspathEntry[] getDefaultAntHomeEntries() { if (defaultAntHomeEntries == null) { ServiceTracker<?, ?> tracker = new ServiceTracker<>(AntCorePlugin.getPlugin().getBundle().getBundleContext(), PackageAdmin.class.getName(), null); tracker.open(); try { List<AntClasspathEntry> result = new ArrayList<>(29); PackageAdmin packageAdmin = (PackageAdmin) tracker.getService(); if (packageAdmin != null) { ExportedPackage[] packages = packageAdmin.getExportedPackages("org.apache.tools.ant"); Bundle bundle = findHighestAntVersion(packages); if (bundle == null) { for (ExportedPackage package1 : packages) { bundle = package1.getExportingBundle(); if (bundle == null) { continue; } try { addLibraries(bundle, result); if (result.size() > 0) { break; } } catch (IOException ioe) { AntCorePlugin.log(ioe); result.clear(); } } } else { try { addLibraries(bundle, result); } catch (IOException ioe) { AntCorePlugin.log(ioe); } } } defaultAntHomeEntries = result.toArray(new IAntClasspathEntry[result.size()]); } finally { tracker.close(); } } return defaultAntHomeEntries; }

Target:
public synchronized IAntClasspathEntry[] getDefaultAntHomeEntries() { if (defaultAntHomeEntries == null) { ServiceTracker<?, ?> tracker = new ServiceTracker<>(AntCorePlugin.getPlugin().getBundle().getBundleContext(), PackageAdmin.class.getName(), null); tracker.open(); try { List<AntClasspathEntry> result = new ArrayList<>(29); PackageAdmin packageAdmin = (PackageAdmin) tracker.getService(); if (packageAdmin != null) { ExportedPackage[] packages = packageAdmin.getExportedPackages("org.apache.tools.ant"); Bundle bundle = findHighestAntVersion(packages); if (bundle == null) { for (ExportedPackage pckg : packages) { bundle = pckg.getExportingBundle(); if (bundle == null) { continue; } try { addLibraries(bundle, result); if (result.size() > 0) { break; } } catch (IOException ioe) { AntCorePlugin.log(ioe); result.clear(); } } } else { try { addLibraries(bundle, result); } catch (IOException ioe) { AntCorePlugin.log(ioe); } } } defaultAntHomeEntries = result.toArray(new IAntClasspathEntry[result.size()]); } finally { tracker.close(); } } return defaultAntHomeEntries; }
Source:
private void deleteOldSchemas(Long currentSchemaId) throws SQLException { Long toDelete = currentSchemaId - SCHEMAS_TO_KEEP; while ( toDelete > 0 && schemaExists(toDelete) ) { new SchemaStore(connection, toDelete).destroy(); } }

Target:
private void deleteOldSchemas(Long currentSchemaId) throws SQLException { Long toDelete = currentSchemaId - SCHEMAS_TO_KEEP; while ( toDelete > 0 && schemaExists(toDelete) ) { new SchemaStore(connection, toDelete).destroy(); toDelete--; } }
Source:
protected void onPostExecute(String s) { super.onPostExecute(s); if(onFinishRequest_callback != null){ onFinishRequest_callback.then(s); } try { if ((progress != null) && progress.isShowing()) { progress.dismiss(); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } finally { progress = null; } output_result = s; new MaterialDialog.Builder(context) .content(s) .title(R.string.result) .neutralText(R.string.OK) .positiveText(R.string.copy_text) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { copyToClipboard(context, output_result); Api.toast(context, context.getString(R.string.result_copied_to_clipboard)); } }) .show(); }

Target:
protected void onPostExecute(String s) { super.onPostExecute(s); if(onFinishRequest_callback != null){ onFinishRequest_callback.then(s); } try { if ((progress != null) && progress.isShowing()) { progress.dismiss(); } } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage()); } catch (final Exception e) { Log.e(TAG, e.getMessage()); } finally { progress = null; } output_result = s; new MaterialDialog.Builder(context) .content(s) .title(R.string.result) .neutralText(R.string.OK) .positiveText(R.string.copy_text) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { copyToClipboard(context, output_result); Api.toast(context, context.getString(R.string.result_copied_to_clipboard)); } }) .show(); }