auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testResolveTools() throws Exception { evalRuleContextCode( createRuleContext(" "inputs, input_manifests = ruleContext.resolve_tools(", " tools=ruleContext.attr.tools)"); assertArtifactFilenames( ((SkylarkNestedSet) lookup("inputs")).getSet(Artifact.class), "mytool.sh", "mytool", "foo_Smytool" + OsUtils.executableExtension() + "-runfiles", "t.exe"); @SuppressWarnings("unchecked") CompositeRunfilesSupplier runfilesSupplier = new CompositeRunfilesSupplier((List<RunfilesSupplier>) lookup("input_manifests")); assertThat(runfilesSupplier.getMappings(ArtifactPathResolver.IDENTITY)).hasSize(1); }

Target:
public void testResolveTools() throws Exception { SkylarkRuleContext ruleContext = createRuleContext(" evalRuleContextCode( ruleContext, "inputs, input_manifests = ruleContext.resolve_tools(tools=ruleContext.attr.tools)", "ruleContext.actions.run(", " outputs = [ruleContext.actions.declare_file('x.out')],", " inputs = inputs,", " input_manifests = input_manifests,", " executable = 'dummy',", ")"); assertArtifactFilenames( ((SkylarkNestedSet) lookup("inputs")).getSet(Artifact.class), "mytool.sh", "mytool", "foo_Smytool" + OsUtils.executableExtension() + "-runfiles", "t.exe"); @SuppressWarnings("unchecked") CompositeRunfilesSupplier runfilesSupplier = new CompositeRunfilesSupplier((List<RunfilesSupplier>) lookup("input_manifests")); assertThat(runfilesSupplier.getMappings(ArtifactPathResolver.IDENTITY)).hasSize(1); SpawnAction action = (SpawnAction) Iterables.getOnlyElement( ruleContext.getRuleContext().getAnalysisEnvironment().getRegisteredActions()); assertThat(ActionsTestUtil.baseArtifactNames(action.getInputs())) .containsAllOf( "mytool.sh", "mytool", "foo_Smytool" + OsUtils.executableExtension() + "-runfiles", "t.exe"); }
Source:
public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { Optional<VehicleData> vehicleData = get(VehicleData.class); if (vehicleData.isPresent()) { manipulators.add(vehicleData.get()); } if (this.fire > 0) { manipulators.add(get(IgniteableData.class).get()); } manipulators.add(new SpongeGravityData()); }

Target:
public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { Optional<VehicleData> vehicleData = get(VehicleData.class); if (vehicleData.isPresent()) { manipulators.add(vehicleData.get()); } if (this.fire > 0) { manipulators.add(get(IgniteableData.class).get()); } manipulators.add(new SpongeGravityData(!this.hasNoGravity())); }
Source:
public void storeLocalMapping(RespondingGatewayPRPAIN201305UV02RequestType request) { LOG.debug("Begin storeLocalMapping"); String hcid = HomeCommunityMap.getLocalHomeCommunityId(); LOG.debug("Begin storeLocalMapping: hcid", hcid); II patId = extractPatientIdFrom201305(request.getPRPAIN201305UV02()); AssigningAuthorityHomeCommunityMappingDAO mappingDao = new AssigningAuthorityHomeCommunityMappingDAO(); if (patId == null) { LOG.warn("AssigningAuthorityHomeCommunityMappingDAO or Local Patient Id was null. Mapping was not stored."); } else { if (!mappingDao.storeMapping(hcid, patId.getRoot())) { LOG.warn("Failed to store home community - assigning authority mapping"); } } LOG.debug("End storeLocalMapping"); }

Target:
public void storeLocalMapping(RespondingGatewayPRPAIN201305UV02RequestType request) { LOG.debug("Begin storeLocalMapping"); String hcid = HomeCommunityMap.getLocalHomeCommunityId(); LOG.debug("Begin storeLocalMapping hcid : ", hcid); II patId = extractPatientIdFrom201305(request.getPRPAIN201305UV02()); AssigningAuthorityHomeCommunityMappingDAO mappingDao = new AssigningAuthorityHomeCommunityMappingDAO(); if (patId == null) { LOG.warn("AssigningAuthorityHomeCommunityMappingDAO or Local Patient Id was null. Mapping was not stored."); } else { if (!mappingDao.storeMapping(hcid, patId.getRoot())) { LOG.warn("Failed to store home community - assigning authority mapping"); } } LOG.debug("End storeLocalMapping"); }
Source:
public void testCheckProjectAdminAccessInvalidUserSession() throws AccessControlException { final TestSession sessions = new TestSession(); final ACDAOFacade acDAOFacade = new DAOFacadeMock(); final ESOrgUnitRepository orgUnitRepository = new ESOrgUnitRepositoryImpl(acDAOFacade); final ESOrgUnitProvider orgUnitProvider = new ESOrgUnitProviderImpl(orgUnitRepository); final ESOrgUnitResolver orgUnitResolver = new DefaultESOrgUnitResolverService(); orgUnitResolver.init(orgUnitProvider); final DefaultESAuthorizationService defaultESAuthorizationService = createServiceUnderTest(sessions, orgUnitProvider, orgUnitResolver); final SessionIdImpl sessionId = (SessionIdImpl) ModelFactory.eINSTANCE.createSessionId(); final ProjectIdImpl projectId = (ProjectIdImpl) ModelFactory.eINSTANCE.createProjectId(); try { defaultESAuthorizationService.checkProjectAdminAccess( sessionId.toAPI(), projectId.toAPI(), ESProjectAdminPrivileges.AssignRoleToOrgUnit); } catch (final SessionTimedOutException ex) { assertEquals(Messages.AccessControlImpl_SessionID_Unknown, ex.getMessage()); throw ex; } }

Target:
public void testCheckProjectAdminAccessInvalidUserSession() throws AccessControlException { final DefaultESAuthorizationService defaultESAuthorizationService = createServiceUnderTest(sessions, orgUnitProvider, orgUnitResolver); try { defaultESAuthorizationService.checkProjectAdminAccess( sessionId.toAPI(), projectId.toAPI(), ESProjectAdminPrivileges.AssignRoleToOrgUnit); } catch (final SessionTimedOutException ex) { assertEquals(Messages.AccessControlImpl_SessionID_Unknown, ex.getMessage()); throw ex; } }
Source:
public boolean isNull(RexNode node) { final Policy policy = MAP.getOrDefault(node.getKind(), Policy.AS_IS); switch (policy) { case NOT_NULL: return false; case ANY: return anyNull(((RexCall) node).getOperands()); default: break; } switch (node.getKind()) { case LITERAL: return ((RexLiteral) node).isNull(); case AND: case OR: case COALESCE: return allNull(((RexCall) node).getOperands()); case NULLIF: return allNull(ImmutableList.of(((RexCall) node).getOperands().get(0))); case INPUT_REF: return isNull((RexInputRef) node); case CASE: final RexCall caseCall = (RexCall) node; final List<RexNode> caseValues = new ArrayList<>(); for (int i = 0; i < caseCall.getOperands().size(); i++) { if (!RexUtil.isCasePredicate(caseCall, i)) { caseValues.add(caseCall.getOperands().get(i)); } } return allNull(caseValues); default: return false; } }

Target:
public boolean isNull(RexNode node) { final Policy policy = policy(node.getKind()); switch (policy) { case NOT_NULL: return false; case ANY: return anyNull(((RexCall) node).getOperands()); default: break; } switch (node.getKind()) { case LITERAL: return ((RexLiteral) node).isNull(); case AND: case OR: case COALESCE: return allNull(((RexCall) node).getOperands()); case NULLIF: return allNull(ImmutableList.of(((RexCall) node).getOperands().get(0))); case INPUT_REF: return isNull((RexInputRef) node); case CASE: final RexCall caseCall = (RexCall) node; final List<RexNode> caseValues = new ArrayList<>(); for (int i = 0; i < caseCall.getOperands().size(); i++) { if (!RexUtil.isCasePredicate(caseCall, i)) { caseValues.add(caseCall.getOperands().get(i)); } } return allNull(caseValues); default: return false; } }
Source:
public void testWriteAttributeWithCredentialReferenceWithStoreOnly() throws Exception { try { getNonEmptyCredentialStore(); addKeyStoreWithCredentialReference(KS_NAME, NON_EMPTY_CS_NAME, EXISTING_ALIAS, null, true); testWriteCredentialReferenceAttribute("key-store", KS_NAME, NON_EMPTY_CS_NAME, null, null, true); assertEquals(null, readAttribute(KS_NAME, CLEAR_TEXT_ATTRIBUTE_NAME)); assertEquals(EXISTING_ALIAS, readAttribute(KS_NAME, ALIAS_ATTRIBUTE_NAME)); assertEquals(NON_EMPTY_CS_NAME, readAttribute(KS_NAME, STORE_ATTRIBUTE_NAME)); } finally { removeKeyStore(KS_NAME); } }

Target:
public void testWriteAttributeWithCredentialReferenceWithStoreOnly() throws Exception { try { getNonEmptyCredentialStore(); addKeyStoreWithCredentialReference(KS_NAME, NON_EMPTY_CS_NAME, EXISTING_ALIAS, null, true); testWriteCredentialReferenceAttribute("key-store", KS_NAME, NON_EMPTY_CS_NAME, null, null, true); assertNull(readAttribute(KS_NAME, CLEAR_TEXT_ATTRIBUTE_NAME)); assertEquals(EXISTING_ALIAS, readAttribute(KS_NAME, ALIAS_ATTRIBUTE_NAME)); assertEquals(NON_EMPTY_CS_NAME, readAttribute(KS_NAME, STORE_ATTRIBUTE_NAME)); } finally { removeKeyStore(KS_NAME); } }
Source:
public boolean isPageComplete() { if (availableBusinessData.isEmpty() && dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; } if (availableDocuments.isEmpty() && !dataTypeSelectionOptions.isBusinessDataTypeSelected()) { return false; } if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); }

Target:
public boolean isPageComplete() { if (availableBusinessData.isEmpty() && isBusinessDataTypeSelected() || availableDocuments.isEmpty() && !isBusinessDataTypeSelected()) { return false; } if (selectedDataObservable.getValue() instanceof BusinessObjectData) { return isNoBusinessDataSelected() ? false : super.isPageComplete(); } if (selectedDataObservable.getValue() instanceof Document) { return super.isPageComplete(); } return super.isPageComplete(); }
Source:
public void addOrUpdateExpression(final Expression expression) { LOGGER.info() .setMessage("This is a read only repository.") .log(); }

Target:
public void addOrUpdateExpression(final Expression expression) { throw new UnsupportedOperationException("This is a read only repository."); }
Source:
public boolean reserveSeatForTicket(String seatGroup, int seatNumber, Long ticketId) { Seat seat = seatRepository.findBySeatGroupAndSeatNumber(seatGroup, seatNumber); if (seat.isTaken()) { return false; } else { reserveSeat(seat, ticketId); return true; } }

Target:
public boolean reserveSeatForTicket(String seatGroup, int seatNumber, Long ticketId) { Seat seat = getSeatBySeatGroupAndSeatNumber(seatGroup, seatNumber); if (seat.isTaken()) { return false; } else { reserveSeat(seat, ticketId); return true; } }
Source:
public void generatesDeclarations(Boolean withExterns, String expected) { Options opts = new Options(!withExterns); List<SourceFile> sourceFiles = new ArrayList<>(); sourceFiles.add(SourceFile.fromFile("src/resources/base.js", UTF_8)); for (File nonroot : getSubject().nonroots) { sourceFiles.add(SourceFile.fromFile(nonroot, UTF_8)); } List<String> roots = new ArrayList<>(); roots.add("src/resources/base.js"); for (File root : getSubject().roots) { sourceFiles.add(SourceFile.fromFile(root, UTF_8)); roots.add(root.getPath()); } String actual = new DeclarationGenerator(opts) .generateDeclarations(sourceFiles, NO_EXTERNS, new Depgraph(roots)); actual = DeclarationGenerator.GOLDEN_FILE_COMMENTS_REGEXP.matcher(actual).replaceAll(""); if (!actual.equals(expected)) { failureStrategy.failComparing("compilation result doesn't match", expected, actual); } }

Target:
public void generatesDeclarations(Boolean withExterns, String expected) { Options opts = new Options(!withExterns); List<SourceFile> sourceFiles = new ArrayList<>(); if (!getSubject().roots.get(0).getName().equals("base.js")) { sourceFiles.add(SourceFile.fromFile("src/test/java/com/google/javascript/clutz/base.js", UTF_8)); } for (File nonroot : getSubject().nonroots) { sourceFiles.add(SourceFile.fromFile(nonroot, UTF_8)); } List<String> roots = new ArrayList<>(); for (File root : getSubject().roots) { sourceFiles.add(SourceFile.fromFile(root, UTF_8)); roots.add(root.getPath()); } String actual = new DeclarationGenerator(opts) .generateDeclarations(sourceFiles, NO_EXTERNS, new Depgraph(roots)); actual = DeclarationGenerator.GOLDEN_FILE_COMMENTS_REGEXP.matcher(actual).replaceAll(""); if (!actual.equals(expected)) { failureStrategy.failComparing("compilation result doesn't match", expected, actual); } }
Source:
private static List<VariableTree> matchingTypesWrongOrder(ParametersList formalParameterList, List<IdentifierTree> argumentList) { Iterator<IdentifierTree> argumentsIterator = argumentList.stream().filter(Objects::nonNull).iterator(); List<VariableTree> misplacedParameters = new ArrayList<>(); while (argumentsIterator.hasNext()) { IdentifierTree argument = argumentsIterator.next(); int index = formalParameterList.indexOf(argument.name().toLowerCase(Locale.ENGLISH)); Type formalType = formalParameterList.typeOfIndex(index); Type argType = argument.symbolType(); if (!formalType.is(argType.fullyQualifiedName()) || formalType.isUnknown() || argType.isUnknown()) { return new ArrayList<>(); } if (argumentList.indexOf(argument) != index) { misplacedParameters.add(formalParameterList.parameterAt(index)); } } if (misplacedParameters.size() >= 2) { return misplacedParameters; } return new ArrayList<>(); }

Target:
private static List<VariableTree> matchingTypesWrongOrder(ParametersList formalParameterList, List<IdentifierTree> argumentList) { Iterator<IdentifierTree> argumentsIterator = argumentList.stream().filter(Objects::nonNull).iterator(); List<VariableTree> misplacedParameters = new ArrayList<>(); while (argumentsIterator.hasNext()) { IdentifierTree argument = argumentsIterator.next(); int index = formalParameterList.indexOf(argument.name().toLowerCase(Locale.ENGLISH)); Type formalType = formalParameterList.typeOfIndex(index); Type argType = argument.symbolType(); if (!formalType.is(argType.fullyQualifiedName()) || formalType.isUnknown() || argType.isUnknown()) { return Collections.emptyList(); } if (argumentList.indexOf(argument) != index) { misplacedParameters.add(formalParameterList.parameterAt(index)); } } if (misplacedParameters.size() >= 2) { return misplacedParameters; } return Collections.emptyList(); }
Source:
public boolean filter(String fromUrl, String toUrl) { if (exemptions != null) { for (Pattern pattern : exemptions) { if (pattern.matcher(toUrl).matches()) { return true; } } } return false; }

Target:
public boolean filter(String fromUrl, String toUrl) { return this.filter(toUrl) != null; }
Source:
public void duplicateForm( ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "formId") Integer formId, @RequestParam(required = true, value = "patientId") Integer patientId, @RequestParam(required = true, value = "date") String date, @RequestParam(required = false, value = "dateFormat") String dateFormat) throws Exception { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); List<Locale> l = new Vector<Locale>(); l.add(Context.getLocale()); List<Encounter> encounters = Context.getEncounterService().getEncountersByPatientId(patientId); SimpleDateFormat dateFormatter; if (dateFormat != null) { dateFormatter = new SimpleDateFormat(dateFormat); } else { dateFormatter = Context.getDateFormat(); } Date dateToCheck = dateFormatter.parse(date); boolean duplicate = false; for(Encounter enc: encounters) { if(enc.getForm() != null) { String encounterDate = dateFormatter.format(enc.getEncounterDatetime()); Form encForm = enc.getForm(); HtmlForm htmlForm = HtmlFormEntryUtil.getService().getHtmlFormByForm(encForm); if(htmlForm != null && htmlForm.getId().equals(formId) && dateToCheck.compareTo(dateFormatter.parse(encounterDate)) == 0) { duplicate = true; } } } if(duplicate) { out.print("true"); } else { out.print("false"); } }

Target:
public void duplicateForm( ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "formId") Integer formId, @RequestParam(required = true, value = "patientId") Integer patientId, @RequestParam(required = true, value = "date") String date, @RequestParam(required = false, value = "dateFormat") String dateFormat) throws Exception { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); List<Locale> l = new Vector<Locale>(); l.add(Context.getLocale()); List<Encounter> encounters = Context.getEncounterService().getEncountersByPatientId(patientId); SimpleDateFormat dateFormatter; if (dateFormat != null) { dateFormatter = new SimpleDateFormat(dateFormat); } else { dateFormatter = Context.getDateFormat(); } Date dateToCheck = dateFormatter.parse(date); boolean duplicate = false; for(Encounter enc: encounters) { Form encForm = enc.getForm(); if(encForm != null) { String encounterDate = dateFormatter.format(enc.getEncounterDatetime()); HtmlForm htmlForm = HtmlFormEntryUtil.getService().getHtmlFormByForm(encForm); if(htmlForm != null && htmlForm.getId().equals(formId) && dateToCheck.compareTo(dateFormatter.parse(encounterDate)) == 0) { duplicate = true; } } } if(duplicate) { out.print("true"); } else { out.print("false"); } }
Source:
public SpoolingResultIterator(ResultIterator scanner, MemoryManager mm, int thresholdBytes, RowCounter rowCounter) throws SQLException { boolean success = false; boolean usedOnDiskIterator = false; final MemoryChunk chunk = mm.allocate(0, thresholdBytes); File tempFile = null; try { int size = (int)chunk.getSize(); tempFile = File.createTempFile("ResultSpooler",".bin"); DeferredFileOutputStream spoolTo = new DeferredFileOutputStream(size, tempFile) { @Override protected void thresholdReached() throws IOException { super.thresholdReached(); chunk.close(); } }; DataOutputStream out = new DataOutputStream(spoolTo); int maxSize = 0; for (Tuple result = scanner.next(); result != null; result = scanner.next()) { int length = TupleUtil.write(result, out); maxSize = Math.max(length, maxSize); rowCount += rowCounter.calculate(result); } spoolTo.close(); if (spoolTo.isInMemory()) { byte[] data = spoolTo.getData(); chunk.resize(data.length); spoolFrom = new InMemoryResultIterator(data, chunk); } else { spoolFrom = new OnDiskResultIterator(maxSize, spoolTo.getFile()); usedOnDiskIterator = true; } success = true; } catch (IOException e) { throw SQLExceptionInfo.getNewInfoObject(SQLExceptionCodeEnum.IO_EXCEPTION).genWrappedException(e); } finally { try { scanner.close(); } finally { try { if (!usedOnDiskIterator) { tempFile.delete(); } } finally { if (!success) { chunk.close(); } } } } }

Target:
public SpoolingResultIterator(ResultIterator scanner, MemoryManager mm, int thresholdBytes, RowCounter rowCounter) throws SQLException { boolean success = false; boolean usedOnDiskIterator = false; final MemoryChunk chunk = mm.allocate(0, thresholdBytes); File tempFile = null; try { int size = (int)chunk.getSize(); tempFile = File.createTempFile("ResultSpooler",".bin"); DeferredFileOutputStream spoolTo = new DeferredFileOutputStream(size, tempFile) { @Override protected void thresholdReached() throws IOException { super.thresholdReached(); chunk.close(); } }; DataOutputStream out = new DataOutputStream(spoolTo); int maxSize = 0; for (Tuple result = scanner.next(); result != null; result = scanner.next()) { int length = TupleUtil.write(result, out); maxSize = Math.max(length, maxSize); rowCount += rowCounter.calculate(result); } spoolTo.close(); if (spoolTo.isInMemory()) { byte[] data = spoolTo.getData(); chunk.resize(data.length); spoolFrom = new InMemoryResultIterator(data, chunk); } else { spoolFrom = new OnDiskResultIterator(maxSize, spoolTo.getFile()); usedOnDiskIterator = true; } success = true; } catch (IOException e) { throw new PhoenixIOException(e); } finally { try { scanner.close(); } finally { try { if (!usedOnDiskIterator) { tempFile.delete(); } } finally { if (!success) { chunk.close(); } } } } }
Source:
public boolean looselyMatch(URIish url, URIish urIish) { LOGGER.log(Level.FINE, "repo scheme: {0}", urIish.getScheme()); if ("ssh".equalsIgnoreCase(urIish.getScheme().toLowerCase())) { int indexOfLastSlash = url.getPath().lastIndexOf('/'); int indexOfLastButOneSlash = url.getPath().lastIndexOf('/', indexOfLastSlash - 1); String projectRepoPath = url.getPath().substring(indexOfLastButOneSlash); url = url.setPath(projectRepoPath); } else { urIish = urIish.setPath(urIish.getPath().replaceFirst("/scm", "")); } LOGGER.log(Level.FINE, "Trying to match {0} ", urIish.toString() + "<-->" + url.toString()); return GitStatus.looselyMatches(urIish, url); }

Target:
public boolean looselyMatch(URIish url, URIish urIish) { LOGGER.log(Level.FINE, "repo scheme: {0}", urIish.getScheme()); if ("ssh".equalsIgnoreCase(urIish.getScheme().toLowerCase())) { int indexOfLastSlash = url.getPath().lastIndexOf('/'); int indexOfLastButOneSlash = url.getPath().lastIndexOf('/', indexOfLastSlash - 1); String projectRepoPath = url.getPath().substring(indexOfLastButOneSlash); url = url.setPath(projectRepoPath); } else { urIish = urIish.setPath(urIish.getPath().replaceFirst("/scm/", "/")); if (StringUtils.isEmpty(url.getHost())) { urIish = urIish.setHost(url.getHost()); } } LOGGER.log(Level.FINE, "Trying to match {0} ", urIish.toString() + "<-->" + url.toString()); return GitStatus.looselyMatches(urIish, url); }
Source:
protected void firstListenerAdded() { if (!isDisposed()) { if (listener == null) { listener = property .adaptListener(new ISimplePropertyListener<SetDiff<E>>() { @Override public void handleEvent( final SimplePropertyEvent<SetDiff<E>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { modCount++; notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedSet = new HashSet<>(getSet()); stale = false; if (listener != null) listener.addTo(source); } }); } }

Target:
protected void firstListenerAdded() { if (!isDisposed() && listener == null) { listener = property.adaptListener(new ISimplePropertyListener<SetDiff<E>>() { @Override public void handleEvent(final SimplePropertyEvent<SetDiff<E>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { modCount++; notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedSet = new HashSet<>(getSet()); stale = false; if (listener != null) listener.addTo(source); } }); }
Source:
public RMStateDelta getRMStateDelta(@HeaderParam("sessionid") String sessionId, @HeaderParam("clientCounter") @DefaultValue("-1") String clientCounter) throws NotConnectedException { checkAccess(sessionId); long counter = Integer.valueOf(clientCounter); return RMStateCaching.getRMInitialState(counter); }

Target:
public RMStateDelta getRMStateDelta(@HeaderParam("sessionid") String sessionId, @HeaderParam("clientCounter") @DefaultValue("-1") String clientCounter) throws NotConnectedException { checkAccess(sessionId); long counter = Integer.valueOf(clientCounter); return RMStateCaching.getRMStateDelta(counter); }
Source:
private PAPropertyString createNodeSourceProperty() { PAPropertyString nodeSourceNameProperty = new PAPropertyString("proactive.node.nodesource", false, "local"); nodeSourceNameProperty.setValue(System.getProperty("proactive.node.nodesource")); return nodeSourceNameProperty; }

Target:
private PAPropertyString createNodeSourceProperty() { PAPropertyString nodeSourceNameProperty = new PAPropertyString("proactive.node.nodesource", false, "Default"); try { nodeSourceNameProperty.setValue(System.getProperty("proactive.node.nodesource")); } catch (NullPointerException npe) { logger.warn("System property proactive.node.nodesource can't be found."); } return nodeSourceNameProperty; }
Source:
public FieldSolver clone() { SimpleSolver clone = new SimpleSolver(); clone.copyBaseClassFields(this); clone.solveForE = solveForE; clone.solveForB = solveForB; return clone; }

Target:
public FieldSolver clone() { SimpleSolver clone = new SimpleSolver(); clone.copyBaseClassFields(this); clone.timeStep = timeStep; clone.solveForE = solveForE; clone.solveForB = solveForB; return clone; }
Source:
public static String toJSONStringV2(ClientResponse clientResponse) { JSONStringer js = new JSONStringer(); try { js.object(); js.keySymbolValuePair(JSON_STATUS_KEY, clientResponse.getStatus()); js.keySymbolValuePair(JSON_APPSTATUS_KEY, clientResponse.getAppStatus()); js.keySymbolValuePair(JSON_STATUSSTRING_KEY, clientResponse.getStatusString()); js.keySymbolValuePair(JSON_APPSTATUSSTRING_KEY, clientResponse.getAppStatusString()); js.key(JSON_RESULTS_KEY); js.object(); VoltTable[] results = clientResponse.getResults(); for (int i=0; i<results.length; i++) { js.key(String.valueOf(i)); VoltTable o = results[i]; o.toJSONStringerV2(js); } js.endObject(); js.endObject(); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException("Failed to serialize a parameter set to JSON.", e); } return js.toString(); }

Target:
public static String toJSONStringV2(ClientResponse clientResponse) throws JSONException { JSONStringer js = new JSONStringer(); js.object(); js.keySymbolValuePair(JSON_STATUS_KEY, clientResponse.getStatus()); js.keySymbolValuePair(JSON_APPSTATUS_KEY, clientResponse.getAppStatus()); js.keySymbolValuePair(JSON_STATUSSTRING_KEY, clientResponse.getStatusString()); js.keySymbolValuePair(JSON_APPSTATUSSTRING_KEY, clientResponse.getAppStatusString()); js.key(JSON_RESULTS_KEY); js.object(); VoltTable[] results = clientResponse.getResults(); for (int i=0; i<results.length; i++) { js.key(String.valueOf(i)); VoltTable o = results[i]; o.toJSONStringerV2(js); } js.endObject(); js.endObject(); return js.toString(); }
Source:
protected boolean canDoAction() { VDS vds = getVds(); if (vds == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); return false; } if (!ObjectIdentityChecker.CanUpdateField(vds, "vds_group_id", vds.getstatus())) { addCanDoActionMessage(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE); return false; } VDSGroup targetCluster = DbFacade.getInstance().getVdsGroupDAO().get(getParameters().getClusterId()); if (targetCluster == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); return false; } if (getVdsGroup().getstorage_pool_id() != null && isNumberOfVdsInStoragePoolExceed(getVdsGroup().getstorage_pool_id().getValue())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_EXCEEDED_MAXIMUM_NUMBER_OF_HOSTS_IN_DATA_CENTER); return false; } targetStoragePool = DbFacade.getInstance().getStoragePoolDAO().getForVdsGroup(targetCluster.getId()); if (targetStoragePool != null && targetStoragePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getParameters().getClusterId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE); return false; } } return true; }

Target:
protected boolean canDoAction() { VDS vds = getVds(); if (vds == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); return false; } if (!ObjectIdentityChecker.CanUpdateField(vds, "vds_group_id", vds.getstatus())) { addCanDoActionMessage(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE); return false; } if (getTargetCluster() == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); return false; } if (getVdsGroup().getstorage_pool_id() != null && !getVdsGroup().getstorage_pool_id().equals(getTargetCluster().getId()) && reachedMaxNumOfVdsInPool(getTargetCluster().getId().getValue())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_EXCEEDED_MAXIMUM_NUMBER_OF_HOSTS_IN_DATA_CENTER); return false; } targetStoragePool = DbFacade.getInstance().getStoragePoolDAO().getForVdsGroup(getTargetCluster().getId()); if (targetStoragePool != null && targetStoragePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getParameters().getClusterId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE); return false; } } if (getVdsGroup().supportsGlusterService()) { if (getGlusterUtils().hasBricks(getSourceCluster().getId())) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); return false; } if (!hasUpServer(getSourceCluster())) { return false; } } if (getTargetCluster().supportsGlusterService() && !hasUpServer(getTargetCluster())) { return false; } return true; }
Source:
public static Block registerBlock(Block block, ItemBlock item, String name) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { assert block != null : "registerBlock: block cannot be null"; GameData.getMain().registerBlock(block, name); if (item != null) { GameData.getMain().registerItem(item, name); GameData.getBlockItemMap().put(block, item); } return block; } catch (Exception e) { FMLLog.log(Level.ERROR, e, "Caught an exception during block registration"); throw new LoaderException(e); } }

Target:
public static Block registerBlock(Block block, ItemBlock item, String name) { if (Loader.instance().isInState(LoaderState.CONSTRUCTING)) { FMLLog.warning("The mod %s is attempting to register a block whilst it it being constructed. This is bad modding practice - please use a proper mod lifecycle event.", Loader.instance().activeModContainer()); } try { Preconditions.checkNotNull(block, "block cannot be null"); GameData.getMain().registerBlock(block, name); if (item != null) { GameData.getMain().registerItem(item, name); GameData.getBlockItemMap().put(block, item); } return block; } catch (Exception e) { FMLLog.log(Level.ERROR, e, "Caught an exception during block registration"); throw new LoaderException(e); } }
Source:
public GroupInfo format(GroupDescription.Basic group) throws ResourceNotFoundException, OrmException { GroupInfo info = new GroupInfo(); info.id = Url.encode(group.getGroupUUID().get()); info.name = Strings.emptyToNull(group.getName()); info.url = Strings.emptyToNull(group.getUrl()); info.options = new GroupOptionsInfo(group); AccountGroup g = GroupDescriptions.toAccountGroup(group); if (g != null) { info.description = Strings.emptyToNull(g.getDescription()); info.groupId = g.getId().get(); if (g.getOwnerGroupUUID() != null) { info.ownerId = Url.encode(g.getOwnerGroupUUID().get()); AccountGroup o = groupCache.get(g.getOwnerGroupUUID()); if (o != null) { info.owner = o.getName(); } } if (options.contains(MEMBERS) || options.contains(INCLUDES)) { GroupResource r = new GroupResource(groupControlFactory.controlFor(group)); if (options.contains(MEMBERS)) { info.members = listMembers.get().apply(r); } if (options.contains(INCLUDES)) { info.includes = listIncludes.get().apply(r); } } } return info; }

Target:
public GroupInfo format(GroupDescription.Basic group) throws ResourceNotFoundException, OrmException { GroupInfo info = init(group); if (options.contains(MEMBERS) || options.contains(INCLUDES)) { GroupResource rsrc = new GroupResource(groupControlFactory.controlFor(group)); initMembersAndIncludes(rsrc, info); } return info; }
Source:
public void call(final Subscriber<? super T> subscriber) { lock.writeLock().lock(); if (subscriptionCount.incrementAndGet() == 1) { source.connect(new Action1<Subscription>() { @Override public void call(Subscription subscription) { baseSubscription = subscription; subscriber.add(disconnect()); source.unsafeSubscribe(subscriber); lock.writeLock().unlock(); } }); } else { lock.writeLock().unlock(); lock.readLock().lock(); subscriber.add(disconnect()); source.unsafeSubscribe(subscriber); lock.readLock().unlock(); } }

Target:
public void call(final Subscriber<? super T> subscriber) { lock.lock(); if (subscriptionCount.incrementAndGet() == 1) { final AtomicBoolean writeLocked = new AtomicBoolean(true); try { source.connect(onSubscribe(subscriber, writeLocked)); } finally { if (writeLocked.get()) { lock.unlock(); } } } else { try { subscriber.add(disconnect()); source.unsafeSubscribe(subscriber); } finally { lock.unlock(); } } }
Source:
public static IntervalList overlaps(final Collection<IntervalList> lists1, final Collection<IntervalList> lists2) { final SAMFileHeader header = lists1.iterator().next().getHeader().clone(); header.setSortOrder(SAMFileHeader.SortOrder.unsorted); final IntervalList overlapIntervals = new IntervalList(header); for (final IntervalList list : lists2) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); overlapIntervals.addall(list.getIntervals()); } final OverlapDetector<Interval> detector = new OverlapDetector<>(0, 0); for (final Interval interval : overlapIntervals.sorted().uniqued()) { detector.addLhs(interval, interval); } final IntervalList merged = new IntervalList(header); for (final IntervalList list : lists1) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); for (final Interval interval : list.getIntervals()) { if (detector.overlapsAny(interval)) { merged.add(interval); } } } return merged; }

Target:
public static IntervalList overlaps(final Collection<IntervalList> lists1, final Collection<IntervalList> lists2) { if(lists1.isEmpty()){ throw new SAMException("Cannot call overlaps with the first collection having empty list of IntervalLists."); } final SAMFileHeader header = lists1.iterator().next().getHeader().clone(); header.setSortOrder(SAMFileHeader.SortOrder.unsorted); final IntervalList overlapIntervals = new IntervalList(header); for (final IntervalList list : lists2) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); overlapIntervals.addall(list.getIntervals()); } final OverlapDetector<Integer> detector = new OverlapDetector<>(0, 0); final int dummy = -1; for (final Interval interval : overlapIntervals.sorted().uniqued()) { detector.addLhs(dummy, interval); } final IntervalList merged = new IntervalList(header); for (final IntervalList list : lists1) { SequenceUtil.assertSequenceDictionariesEqual(header.getSequenceDictionary(), list.getHeader().getSequenceDictionary()); for (final Interval interval : list.getIntervals()) { if (detector.overlapsAny(interval)) { merged.add(interval); } } } return merged; }
Source:
public Sort sort() { return KSorts.MAP; }

Target:
public Sort sort() { return Sort.MAP; }
Source:
private static boolean search(DetailAST root, String xpath, Deque<DetailAST> nodes) { boolean result = false; if (xpath.equals(XpathQueryGenerator.generateXpathQuery(root))) { nodes.push(root); result = true; } else { if (root.hasChildren()) { DetailAST child = root.getFirstChild(); while (child != null) { if (search(child, xpath, nodes)) { nodes.push(root); result = true; break; } child = child.getNextSibling(); } } } return result; }

Target:
private static boolean search(DetailAST root, String xpath, Deque<DetailAST> nodes) { boolean result = false; if (xpath.equals(XpathQueryGenerator.generateXpathQuery(root))) { nodes.push(root); result = true; } else { DetailAST child = root.getFirstChild(); while (child != null) { if (search(child, xpath, nodes)) { nodes.push(root); result = true; break; } child = child.getNextSibling(); } } return result; }
Source:
private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); if (availabilityZoneId != null) options = options.availabilityZone(availabilityZoneId); ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server); return serverApi.get(server.getId()); }

Target:
private Server createServer(String zoneId, String availabilityZoneId) { ServerApi serverApi = api.getServerApiForZone(zoneId); CreateServerOptions options = new CreateServerOptions(); if (availabilityZoneId != null) { options = options.availabilityZone(availabilityZoneId); } ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId), options); awaitActive(serverApi).apply(server.getId()); return serverApi.get(server.getId()); }
Source:
public long getLastExtentIndexId() throws Exception{ long lastIndex; Connection connection = connect(); String sql = "SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE; try (PreparedStatement getLastIndex = connection.prepareStatement(sql)) { ResultSet results = getLastIndex.executeQuery(); if (results.next()) { lastIndex = results.getLong(EXTENT_INDEX_ID); } else { lastIndex = 0; } } catch (SQLiteException e) { throw new SQLiteException(e.getMessage() + ". SQL query was: " + sql, e.getResultCode()); } return lastIndex; }

Target:
public long getLastExtentIndexId() throws Exception { long lastIndex; Connection connection = connect(); String sql = "SELECT MAX(" + EXTENT_INDEX_ID + ") AS " + EXTENT_INDEX_ID + " FROM " + EXTENT_TABLE; try (PreparedStatement getLastIndex = connection.prepareStatement(sql)) { ResultSet results = getLastIndex.executeQuery(); if (results.next()) { lastIndex = results.getLong(EXTENT_INDEX_ID); } else { lastIndex = 0; } } catch (SQLException e) { throw new SQLException(e.getMessage() + ". SQL query was: " + sql, e); } return lastIndex; }
Source:
public void areUniqueAndOrderedUUID() { final int iterations = PARAMETERS.NUM_ITERATIONS_MODERATE; OrderedGuidGenerator guidGenerator = new CorfuGuidGenerator(getDefaultRuntime()); UUID lastValue = new UUID(0,0); HashSet<UUID> uniq = new HashSet<>(iterations); for (int i = 0; i < iterations; i++) { UUID current = guidGenerator.nextUUID(); lastValue = current; assertThat(uniq).doesNotContain(current); uniq.add(current); } }

Target:
public void areUniqueAndOrderedUUID() { final int iterations = PARAMETERS.NUM_ITERATIONS_MODERATE; OrderedGuidGenerator guidGenerator = new CorfuGuidGenerator(getDefaultRuntime().connect()); UUID lastValue = new UUID(0,0); HashSet<UUID> uniq = new HashSet<>(iterations); for (int i = 0; i < iterations; i++) { UUID current = guidGenerator.nextUUID(); assertThat(uniq).doesNotContain(current); assertThat(current).isGreaterThan(lastValue); lastValue = current; uniq.add(current); } }
Source:
private void convertStitchPointsUnit(ArrayList<PointF> stitchPoints) { DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics(); Project project = ProjectManager.getInstance().getCurrentProject(); Float inchMmFactor = 25.4f; Float dotOneMmFactor = 10.0f; Float aspectRatioMultiplierX = (float) metrics.widthPixels / project.getXmlHeader().getVirtualScreenWidth(); Float aspectRatioMultiplierY = (float) metrics.heightPixels / project.getXmlHeader().getVirtualScreenHeight(); if (project.getScreenMode() == ScreenModes.MAXIMIZE) { if (aspectRatioMultiplierX > aspectRatioMultiplierY) { aspectRatioMultiplierX = aspectRatioMultiplierY; } else { aspectRatioMultiplierY = aspectRatioMultiplierX; } } for (PointF stitch: stitchPoints) { PointF stitchUnitMm = new PointF(); stitchUnitMm.x = stitch.x * inchMmFactor * dotOneMmFactor * aspectRatioMultiplierX / metrics.densityDpi; stitchUnitMm.y = stitch.y * inchMmFactor * dotOneMmFactor * aspectRatioMultiplierY / metrics.densityDpi; this.stitchPoints.add(stitchUnitMm); } }

Target:
private ArrayList<PointF> convertStitchPointsUnit(ArrayList<PointF> stitchPoints) { ArrayList<PointF> convertedStitchPoints = new ArrayList<>(); for (PointF stitch: stitchPoints) { PointF stitchUnitMm = new PointF(); stitchUnitMm.x = Math.round(stitch.x * STITCH_POINT_UNIT_FACTOR); stitchUnitMm.y = Math.round(stitch.y * STITCH_POINT_UNIT_FACTOR); convertedStitchPoints.add(stitchUnitMm); } return convertedStitchPoints; }
Source:
private PushShuffleReceiverImpl( final ShuffleDescription shuffleDescription, final DataReceiver<K, V> dataReceiver, final ESControlMessageSender controlMessageSender, @Parameter(ReceiverTimeout.class) final long receiverTimeout) { dataReceiver.registerTupleMessageHandler(new TupleMessageHandler()); this.shuffleDescription = shuffleDescription; this.controlMessageSender = controlMessageSender; this.synchronizer = new ControlMessageSynchronizer(); this.receiverTimeout = receiverTimeout; this.completedSenderCount = new AtomicInteger(); final List<String> senderIdList = shuffleDescription.getSenderIdList(); this.senderNum = senderIdList.size(); this.senderStateMachineMap = new HashMap<>(senderNum); for (final String senderId : senderIdList) { final StateMachine senderStateMachine = PushShuffleSenderImpl.createStateMachine(); senderStateMachine.setState("SENDING"); senderStateMachineMap.put(senderId, senderStateMachine); } this.stateMachine = createStateMachine(); controlMessageSender.sendToManager(PushShuffleCode.RECEIVER_INITIALIZED); }

Target:
private PushShuffleReceiverImpl( final ShuffleDescription shuffleDescription, final DataReceiver<K, V> dataReceiver, final ESControlMessageSender controlMessageSender, @Parameter(ReceiverTimeout.class) final long receiverTimeout) { dataReceiver.registerTupleMessageHandler(new TupleMessageHandler()); this.shuffleDescription = shuffleDescription; this.controlMessageSender = controlMessageSender; this.synchronizer = new ControlMessageSynchronizer(); this.receiverTimeout = receiverTimeout; this.completedSenderCount = new AtomicInteger(); final List<String> senderIdList = shuffleDescription.getSenderIdList(); this.totalNumSenders = senderIdList.size(); this.senderStateMachineMap = new HashMap<>(totalNumSenders); for (final String senderId : senderIdList) { final StateMachine senderStateMachine = PushShuffleSenderState.createStateMachine(); senderStateMachine.setState(PushShuffleSenderState.SENDING); senderStateMachineMap.put(senderId, senderStateMachine); } this.stateMachine = PushShuffleReceiverState.createStateMachine(); controlMessageSender.sendToManager(PushShuffleCode.RECEIVER_INITIALIZED); }
Source:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } long currentTimeMillis = timeService.wallClockTime(); for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.iteratorIncludingExpired(); purgeCandidates.hasNext();) { InternalCacheEntry<K, V> e = purgeCandidates.next(); if (e.canExpire()) { synchronized (e) { long lifespan = e.getLifespan(); if (ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), currentTimeMillis)) { handleLifespanExpireEntry(e.getKey(), e.getValue(), lifespan, true); } else if (ExpiryHelper.isExpiredTransient(e.getMaxIdle(), e.getLastUsed(), currentTimeMillis)) { super.handleInMemoryExpiration(e, currentTimeMillis); } } } } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }

Target:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } long currentTimeMillis = timeService.wallClockTime(); for (Iterator<InternalCacheEntry<K, V>> purgeCandidates = dataContainer.iteratorIncludingExpired(); purgeCandidates.hasNext();) { InternalCacheEntry<K, V> e = purgeCandidates.next(); if (e.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; synchronized (e) { value = e.getValue(); lifespan = e.getLifespan(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, e.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(e.getMaxIdle(), e.getLastUsed(), currentTimeMillis); } if (expiredMortal) { handleLifespanExpireEntry(e.getKey(), value, lifespan, true); } else if (expiredTransient) { super.handleInMemoryExpiration(e, currentTimeMillis); } } } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }
Source:
public void onItemClick(@ButtonId int id) { switch (id) { case CONTINUE: ProjectLoaderTask loaderTask = new ProjectLoaderTask(getActivity(), this); setShowProgressBar(true); loaderTask.execute(Utils.getCurrentProjectName(getActivity())); break; case NEW: new NewProjectDialogFragment().show(getFragmentManager(), NewProjectDialogFragment.TAG); break; case PROGRAMS: setShowProgressBar(true); startActivity(new Intent(getActivity(), ProjectListActivity.class)); break; case HELP: setShowProgressBar(true); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.CATROBAT_HELP_URL))); break; case EXPLORE: setShowProgressBar(true); startActivity(new Intent(getActivity(), WebViewActivity.class)); break; case UPLOAD: Project currentProject = null; try { currentProject = XstreamSerializer.getInstance().loadProject(Utils.getCurrentProjectName(getActivity()), getActivity()); } catch (IOException | LoadingProjectException e) { Log.e(TAG, e.getMessage()); } if (Utils.isDefaultProject(currentProject, getActivity())) { ToastUtil.showError(getActivity(), R.string.error_upload_default_project); } else { setShowProgressBar(true); Intent intent = new Intent(getActivity(), ProjectUploadActivity.class) .putExtra(ProjectUploadActivity.PROJECT_NAME, Utils.getCurrentProjectName(getActivity())); startActivity(intent); } break; } }

Target:
public void onItemClick(@ButtonId int id) { switch (id) { case CONTINUE: ProjectLoaderTask loaderTask = new ProjectLoaderTask(getActivity(), this); setShowProgressBar(true); loaderTask.execute(Utils.getCurrentProjectName(getActivity())); break; case NEW: new NewProjectDialogFragment().show(getFragmentManager(), NewProjectDialogFragment.TAG); break; case PROGRAMS: setShowProgressBar(true); startActivity(new Intent(getActivity(), ProjectListActivity.class)); break; case HELP: setShowProgressBar(true); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.CATROBAT_HELP_URL))); break; case EXPLORE: setShowProgressBar(true); startActivity(new Intent(getActivity(), WebViewActivity.class)); break; case UPLOAD: String currentProjectName = Utils.getCurrentProjectName(getActivity()); try { Project currentProject = XstreamSerializer.getInstance().loadProject(currentProjectName, getActivity()); if (Utils.isDefaultProject(currentProject, getActivity())) { ToastUtil.showError(getActivity(), R.string.error_upload_default_project); } else { setShowProgressBar(true); Intent intent = new Intent(getActivity(), ProjectUploadActivity.class) .putExtra(ProjectUploadActivity.PROJECT_NAME, currentProjectName); startActivity(intent); } } catch (IOException | LoadingProjectException e) { Log.e(TAG, e.getMessage()); } break; } }
Source:
public void testIndexExpressionIsNotInteger() throws Exception { expectedException.expectMessage("No cast function found for return type undefined"); assertNormalize("subscript(['Youri', 'Ruben'], '1')", isLiteral("Ruben")); }

Target:
public void testIndexExpressionIsNotInteger() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Base argument to subscript must be an object, not [Youri, Ruben]"); assertNormalize("subscript(['Youri', 'Ruben'], '1')", isLiteral("Ruben")); }
Source:
private void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "org/apache/tajo/storage/text/plain; charset=UTF-8"); response.setContent( ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8)); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); }

Target:
private void sendError(ChannelHandlerContext ctx, String message, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent( ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8)); ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); }