auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void findAll() throws Exception { getClient().perform(get("/api/config/submissionforms")) .andExpect(status().isForbidden()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissionforms")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.page.size", is(20))) .andExpect(jsonPath("$.page.totalElements", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.totalPages", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.number", is(0))) .andExpect( jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "config/submissionforms"))) .andExpect(jsonPath("$._embedded.submissionforms", hasSize(greaterThanOrEqualTo(1)))) ; }

Target:
public void findAll() throws Exception { getClient().perform(get("/api/config/submissionforms")) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/config/submissionforms")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.page.size", is(20))) .andExpect(jsonPath("$.page.totalElements", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.totalPages", greaterThanOrEqualTo(1))) .andExpect(jsonPath("$.page.number", is(0))) .andExpect( jsonPath("$._links.self.href", Matchers.startsWith(REST_SERVER_URL + "config/submissionforms"))) .andExpect(jsonPath("$._embedded.submissionforms", hasSize(greaterThanOrEqualTo(1)))) ; }
Source:
public synchronized int abortRunning(int number) throws IllegalAccessException { int aborted = 0; Computer[] computers = getJenkinsInstance().getComputers(); for (Computer computer : computers) { if (isNull(computer)) { continue; } List<Executor> executors = computer.getExecutors(); executors.addAll(computer.getOneOffExecutors()); for (Executor executor : executors) { if (isNull(executor) || !executor.isBusy() || nonNull(executor.getCauseOfDeath()) || !getInterruptCauses(executor).isEmpty() || getInterruptStatus(executor) == Result.ABORTED) { continue; } Queue.Executable executable = executor.getCurrentExecutable(); final SubTask parent = executable.getParent(); if (executable instanceof Run && parent instanceof Job && ( (Job) parent).getFullName().equals(job.getFullName()) ) { final Run executableRun = (Run) executable; if (executableRun.getResult() == Result.ABORTED) { continue; } final GitHubPRCause causeAction = (GitHubPRCause) executableRun.getCause(GitHubPRCause.class); if (nonNull(causeAction) && causeAction.getNumber() == number) { LOGGER.info("Aborting {}", executableRun); executor.interrupt(Result.ABORTED, new CauseOfInterruption() { @Override public String getShortDescription() { return "Newer PR will be scheduled."; } }); aborted++; } } } } return aborted; }

Target:
public synchronized int abortRunning(int number) throws IllegalAccessException { int aborted = 0; Computer[] computers = getJenkinsInstance().getComputers(); for (Computer computer : computers) { if (isNull(computer)) { continue; } List<Executor> executors = computer.getExecutors(); executors.addAll(computer.getOneOffExecutors()); for (Executor executor : executors) { if (isNull(executor) || !executor.isBusy() || nonNull(executor.getCauseOfDeath()) || !getInterruptCauses(executor).isEmpty() || getInterruptStatus(executor) == Result.ABORTED) { continue; } Queue.Executable executable = executor.getCurrentExecutable(); final SubTask parent = executable.getParent(); if (!(executable instanceof Run)) { continue; } final Run executableRun = (Run) executable; if (!(parent instanceof Job)) { continue; } final Job parentJob = (Job) parent; if (!parentJob.getFullName().equals(job.getFullName())) { continue; } if (executableRun.getResult() == Result.ABORTED) { continue; } if (executableRun instanceof MatrixRun) { continue; } final GitHubPRCause causeAction = (GitHubPRCause) executableRun.getCause(GitHubPRCause.class); if (nonNull(causeAction) && causeAction.getNumber() == number) { LOGGER.info("Aborting '{}', by interrupting '{}'", executableRun, executor); executor.interrupt(Result.ABORTED, new NewPRInterruptCause()); aborted++; } } } return aborted; }
Source:
private void saveStateAsLast(URL url) { File lastBundlesTxt = getLastBundleInfo(); try (OutputStream destinationStream = new FileOutputStream(lastBundlesTxt)) { ArrayList<File> sourcesLocation = SimpleConfiguratorUtils.getInfoFiles(); List<InputStream> sourceStreams = new ArrayList<>(sourcesLocation.size() + 1); sourceStreams.add(url.openStream()); if (Activator.EXTENDED) { for (File element : sourcesLocation) { sourceStreams.add(new FileInputStream(element)); } } SimpleConfiguratorUtils.transferStreams(sourceStreams, destinationStream); } catch (URISyntaxException e) { } catch (IOException e) { } }

Target:
private void saveStateAsLast(URL url) { File lastBundlesTxt = getLastBundleInfo(); try (OutputStream destinationStream = new FileOutputStream(lastBundlesTxt)) { ArrayList<File> sourcesLocation = SimpleConfiguratorUtils.getInfoFiles(); List<InputStream> sourceStreams = new ArrayList<>(sourcesLocation.size() + 1); sourceStreams.add(url.openStream()); if (Activator.EXTENDED) { for (File source : sourcesLocation) { sourceStreams.add(new FileInputStream(source)); } } SimpleConfiguratorUtils.transferStreams(sourceStreams, destinationStream); } catch (URISyntaxException e) { } catch (IOException e) { } }
Source:
public String toString() { return "[ProductContent, product = " + ((getProduct() == null) ? "null" : getProduct().getName()) + ", content = " + ((content == null) ? "null" : content.getLabel()) + ", enabled = " + enabled + "]"; }

Target:
public String toString() { return "ProductContent [product = " + getProduct() + ", content = " + content + ", enabled = " + enabled + "]"; }
Source:
public void testEntrySetValueFromEntryCollections() { final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three"; Map<String, String> m = new HashMap<>(); m.put(key1, value1); m.put(key2, value2); m.put(key3, value3); cache(0, "replSync").putAll(m); Cache<Object, Object> replSync = cache(0, "replSync"); Set<Map.Entry<Object, Object>> entries = replSync.entrySet(); String newString = "new-value"; for (Map.Entry<Object, Object> entry : entries) { entry.setValue(newString); } assertEquals(3, cache(0, "replSync").size()); assertEquals(newString, cache(0, "replSync").get(key1)); assertEquals(newString, cache(0, "replSync").get(key2)); assertEquals(newString, cache(0, "replSync").get(key3)); }

Target:
public void testEntrySetValueFromEntryCollections() { final String key1 = "1", value1 = "one", key2 = "2", value2 = "two", key3 = "3", value3 = "three"; Map<String, String> m = new HashMap<>(); m.put(key1, value1); m.put(key2, value2); m.put(key3, value3); cache(0, "replSync").putAll(m); Set<Map.Entry<Object, Object>> entries = cache(0, "replSync").entrySet(); String newString = "new-value"; for (Map.Entry<Object, Object> entry : entries) { entry.setValue(newString); } assertEquals(3, cache(0, "replSync").size()); assertEquals(newString, cache(0, "replSync").get(key1)); assertEquals(newString, cache(0, "replSync").get(key2)); assertEquals(newString, cache(0, "replSync").get(key3)); }
Source:
public List<KijiRegion> getRegions() throws IOException { final HBaseAdmin hbaseAdmin = ((HBaseKiji) getKiji()).getHBaseAdmin(); final HTableInterface hbaseTable = HBaseKijiTable.downcast(this).getHTable(); final List<HRegionInfo> regions = hbaseAdmin.getTableRegions(hbaseTable.getTableName()); final HTable concreteHBaseTable = hbaseTable instanceof HTable ? (HTable) hbaseTable : null; final List<KijiRegion> result = Lists.newArrayList(); for (HRegionInfo region: regions) { if (concreteHBaseTable != null) { List<HRegionLocation> hLocations = concreteHBaseTable.getRegionsInRange(region.getStartKey(), region.getEndKey()); result.add(new HBaseKijiRegion(region, hLocations)); } else { result.add(new HBaseKijiRegion(region)); } } IOUtils.closeQuietly(concreteHBaseTable); return result; }

Target:
public List<KijiRegion> getRegions() throws IOException { final HBaseAdmin hbaseAdmin = ((HBaseKiji) getKiji()).getHBaseAdmin(); final HTableInterface hbaseTable = getHTable(); final List<HRegionInfo> regions = hbaseAdmin.getTableRegions(hbaseTable.getTableName()); final List<KijiRegion> result = Lists.newArrayList(); if (hbaseTable instanceof HTable) { LOG.debug("Casting HTableInterface to an HTable."); final HTable concreteHBaseTable = (HTable) hbaseTable; try { for (HRegionInfo region: regions) { List<HRegionLocation> hLocations = concreteHBaseTable.getRegionsInRange(region.getStartKey(), region.getEndKey()); result.add(new HBaseKijiRegion(region, hLocations)); } } finally { ResourceUtils.closeOrLog(concreteHBaseTable); } } else { LOG.warn("Unable to cast HTableInterface to an HTable. " + "Creating Kiji regions without location info.", getURI()); for (HRegionInfo region: regions) { result.add(new HBaseKijiRegion(region)); } } return result; }
Source:
public boolean matchesCodeVerifier(String codeVerifier, String code) { MessageDigest digester = null; try { digester = MessageDigest.getInstance("SHA-256"); } catch (Exception e) { e.printStackTrace(); } digester.update(codeVerifier.getBytes(StandardCharsets.UTF_8)); String codeChallenge = Base64.getEncoder().encodeToString(digester.digest()); String userId = OAuthUtils.getUserIdFromCode(code, getCodeSecret()); User user = User.findByUsername(userId); Optional<ApplicationUserAuthorization> authOptional = user.getApplicationUserAuthorizationSet().stream().filter(s -> s.getApplication().getOid().equals(getOid())).findFirst(); if(authOptional.isPresent()) { ApplicationUserAuthorization auth = authOptional.get(); Optional<ApplicationUserSession> session = auth.getSessionSet().stream().filter(s -> s.getUserPKCEInfoAuthorizationSession() != null && s.getUserPKCEInfoAuthorizationSession().getCodeChanllenge().equals(codeChallenge)).findFirst(); return !Strings.isNullOrEmpty(codeVerifier) && session.isPresent(); } else { return false; } }

Target:
public boolean matchesCodeVerifier(String codeVerifier, String code) { MessageDigest digester = null; try { digester = MessageDigest.getInstance("SHA-256"); } catch (Exception e) { throw new RuntimeException("Not possible to get instance of SHA-256"); } digester.update(codeVerifier.getBytes(StandardCharsets.US_ASCII)); String codeChallenge = Base64.getEncoder().encodeToString(digester.digest()); String userId = OAuthUtils.getUserIdFromCode(code, getCodeSecret()); User user = User.findByUsername(userId); Optional<ApplicationUserAuthorization> authOptional = user.getApplicationUserAuthorizationSet().stream().filter(s -> s.getApplication().getOid().equals(getOid())).findFirst(); if(authOptional.isPresent()) { ApplicationUserAuthorization auth = authOptional.get(); Optional<ApplicationUserSession> session = auth.getSessionSet().stream().filter(s -> s.getUserPKCEInfoAuthorizationSession() != null && s.getUserPKCEInfoAuthorizationSession().getCodeChallenge().equals(codeChallenge)).findFirst(); return !Strings.isNullOrEmpty(codeVerifier) && session.isPresent(); } else { return false; } }
Source:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().permitAll() .accessDecisionManager(new AffirmativeBased(Collections.singletonList(new WebExpressionVoter()))) .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess( O fsi) { fsi.setPublishAuthorizationSuccess(true); return fsi; } }); }

Target:
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().permitAll() .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess( O fsi) { fsi.setPublishAuthorizationSuccess(true); return fsi; } }); }
Source:
public void renameTo(String tagOld, String tagNew, int index, Bucket<Note> notesBucket) throws BucketObjectNameInvalid { if (!getSimperiumKey().equals(TagUtils.hashTag(tagNew))) { TagUtils.createTag((Bucket<Tag>) getBucket(), tagNew, index); ObjectCursor<Note> notesCursor = findNotes(notesBucket, tagOld); while (notesCursor.moveToNext()) { Note note = notesCursor.getObject(); List<String> tags = new ArrayList<>(note.getTags()); List<String> newTags = new ArrayList<>(tags.size()); for (String tag : tags) { if (getSimperiumKey().equals(TagUtils.hashTag(tag)) && !tags.contains(tagNew)) { newTags.add(tagNew); } else if (!tag.equals(tagOld)) { newTags.add(tag); } } note.setTags(newTags); note.save(); } notesCursor.close(); delete(); } else if (!getName().equals(tagNew)) { setName(tagNew); save(); } }

Target:
public void renameTo(String tagOld, String tagNew, int index, Bucket<Note> notesBucket) throws BucketObjectNameInvalid { boolean isOldIdEqualToNewHash = getSimperiumKey().equals(TagUtils.hashTag(tagNew)); Bucket<Tag> tagsBucket = (Bucket<Tag>) getBucket(); ObjectCursor<Note> notes = findNotes(notesBucket, tagOld); while (notes.moveToNext()) { Note note = notes.getObject(); List<String> tagsNew = new ArrayList<>(); List<String> tagsHash = new ArrayList<>(); for (String tag : note.getTags()) { if (!tag.equals(tagOld)) { tagsNew.add(tag); tagsHash.add(TagUtils.hashTag(tag)); } } if (isOldIdEqualToNewHash) { tagsNew.add(tagNew); if (!getName().equals(tagNew)) { setName(tagNew); save(); } } else { if (!tagsHash.contains(TagUtils.hashTag(tagNew))) { tagsNew.add(TagUtils.getCanonicalFromLexical(tagsBucket, tagNew)); } if (!TagUtils.hasCanonicalOfLexical(tagsBucket, tagNew)) { TagUtils.createTag(tagsBucket, tagNew, index); } delete(); } note.setTags(tagsNew); note.save(); } notes.close(); }
Source:
public UpdateVmTemplateCommand(T parameters) { super(parameters); setVmTemplate(parameters.getVmTemplateData()); setVmTemplateId(getVmTemplate().getId()); setVdsGroupId(getVmTemplate().getVdsGroupId()); oldTemplate = DbFacade.getInstance().getVmTemplateDao().get(getVmTemplate().getId()); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId() != null ? getVdsGroup().getStoragePoolId() : Guid.Empty); } Version compatibilityVersion = isBlankTemplate() || isInstanceType() ? Version.getLast() : getVmTemplate().getCompatibilityVersion(); if (getVdsGroup() != null || isBlankTemplate()) { getVmPropertiesUtils().separateCustomPropertiesToUserAndPredefined(compatibilityVersion, parameters.getVmTemplateData()); if (oldTemplate != null) { getVmPropertiesUtils().separateCustomPropertiesToUserAndPredefined(compatibilityVersion, oldTemplate); } } VmHandler.autoSelectUsbPolicy(getParameters().getVmTemplateData(), getVdsGroup()); VmHandler.updateDefaultTimeZone(parameters.getVmTemplateData()); VmHandler.autoSelectDefaultDisplayType(getVmTemplateId(), getParameters().getVmTemplateData(), getVdsGroup(), getParameters().getGraphicsDevices()); }

Target:
public UpdateVmTemplateCommand(T parameters) { super(parameters); setVmTemplate(parameters.getVmTemplateData()); setVmTemplateId(getVmTemplate().getId()); setVdsGroupId(getVmTemplate().getVdsGroupId()); oldTemplate = DbFacade.getInstance().getVmTemplateDao().get(getVmTemplate().getId()); if (getVdsGroup() != null) { setStoragePoolId(getVdsGroup().getStoragePoolId() != null ? getVdsGroup().getStoragePoolId() : Guid.Empty); } Version compatibilityVersion = isBlankTemplate() || isInstanceType() ? Version.getLast() : CompatibilityVersionUtils.getEffective(getVmTemplate(), this::getVdsGroup); if (getVdsGroup() != null || isBlankTemplate()) { getVmPropertiesUtils().separateCustomPropertiesToUserAndPredefined(compatibilityVersion, parameters.getVmTemplateData()); if (oldTemplate != null) { getVmPropertiesUtils().separateCustomPropertiesToUserAndPredefined(compatibilityVersion, oldTemplate); } } VmHandler.autoSelectUsbPolicy(getParameters().getVmTemplateData(), getVdsGroup()); VmHandler.updateDefaultTimeZone(parameters.getVmTemplateData()); VmHandler.autoSelectDefaultDisplayType(getVmTemplateId(), getParameters().getVmTemplateData(), getVdsGroup(), getParameters().getGraphicsDevices()); }
Source:
protected void writeSpecificHeader(ByteBuffer buffer) { int size = getConfig().getMaxChildren(); buffer.putInt(extension); buffer.putInt(nbChildren); for (int i = 0; i < nbChildren; i++) { buffer.putInt(children[i]); } for (int i = nbChildren; i < size; i++) { buffer.putInt(0); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childStart[i]); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childEnd[i]); } for (int i = nbChildren; i < size; i++) { buffer.putLong(0); } }

Target:
protected void writeSpecificHeader(ByteBuffer buffer) { int size = getConfig().getMaxChildren(); buffer.putInt(extension); buffer.putInt(nbChildren); for (int i = 0; i < nbChildren; i++) { buffer.putInt(children[i]); } for (int i = nbChildren; i < size; i++) { buffer.putInt(0); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childStart[i]); } for (int i = nbChildren; i < size; i++) { buffer.putLong(0); } for (int i = 0; i < nbChildren; i++) { buffer.putLong(childEnd[i]); } for (int i = nbChildren; i < size; i++) { buffer.putLong(Long.MAX_VALUE); } }
Source:
public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); final K key = entry.getKey(); final Collection<V> value = entry.getValue(); return new UnmodifiableMapEntry<>(key, value); }

Target:
public Map.Entry<K, Collection<V>> next() { final Map.Entry<K, Collection<V>> entry = super.next(); return new UnmodifiableMapEntry<>(entry.getKey(), entry.getValue()); }
Source:
private String getRtmpUrlParameters(String rtmpUrl) { final String OldPattern= "rtmp:\\/\\/.+\\.kaltura\\.com:1935\\/kLive\\/\\?(p=[0-9]+)&(e=[01]_[\\d\\w]{8})&(i=0)&(t=[\\d\\w]+)"; final String NewPattern= "rtmp:\\/\\/([01]_[\\d\\w]{8}).([pb])\\.kpublish\\.kaltura\\.com:\\d*\\/kLive\\/\\?(p=[0-9]+)&(t=[\\d\\w]+)"; Matcher matcher; matcher = getMatches(rtmpUrl, OldPattern); if (matcher != null && matcher.groupCount() ==4) { return matcher.group(1)+'&'+matcher.group(2)+'&'+matcher.group(3)+'&'+matcher.group(4); } else{ matcher = getMatches(rtmpUrl, NewPattern); if (matcher != null && matcher.groupCount() ==4) { String i= matcher.group(2).equals("p") ? "i=1" : "i=0" ; return "e="+matcher.group(1)+'&'+i+'&'+matcher.group(3)+'&'+matcher.group(4); } } return null; }

Target:
private String getRtmpUrlParameters(String rtmpUrl) { final String OldPattern= "\\/kLive\\/\\?(p=[0-9]+)&(e=[01]_[\\d\\w]{8})&(i=[01])&(t=[\\d\\w]+)"; final String NewPattern= "rtmp:\\/\\/([01]_[\\d\\w]{8}).([pb])\\.kpublish\\.kaltura\\.com:\\d*\\/kLive\\/\\?(p=[0-9]+)&(t=[\\d\\w]+)"; Matcher matcher; matcher = getMatches(rtmpUrl, OldPattern); if (matcher != null && matcher.groupCount() ==4) { return matcher.group(1)+'&'+matcher.group(2)+'&'+matcher.group(3)+'&'+matcher.group(4); } else{ matcher = getMatches(rtmpUrl, NewPattern); if (matcher != null && matcher.groupCount() ==4) { String i= matcher.group(2).equals("p") ? "i=0" : "i=1" ; return "e="+matcher.group(1)+'&'+i+'&'+matcher.group(3)+'&'+matcher.group(4); } } return null; }
Source:
public static void main(String[] args) throws Exception { System.out.println(); System.out.println(">>> Model training over cached dataset with binary objects usage example started."); try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteCache<Integer, BinaryObject> dataCache = populateCache(ignite); CacheBasedDatasetBuilder<Integer, BinaryObject> datasetBuilder = new CacheBasedDatasetBuilder<>(ignite, dataCache).withKeepBinary(true); Vectorizer<Integer, BinaryObject, String, Double> vectorizer = new BinaryObjectVectorizer<Integer>("feature1").labeled("label"); KMeansTrainer trainer = new KMeansTrainer(); KMeansModel kmdl = trainer.fit(datasetBuilder, vectorizer); System.out.println(">>> Model trained over binary objects. Model " + kmdl); dataCache.destroy(); } }

Target:
public static void main(String[] args) throws Exception { System.out.println(); System.out.println(">>> Model training over cached dataset with binary objects usage example started."); try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(">>> Ignite grid started."); IgniteCache<Integer, BinaryObject> dataCache = null; try { dataCache = populateCache(ignite); CacheBasedDatasetBuilder<Integer, BinaryObject> datasetBuilder = new CacheBasedDatasetBuilder<>(ignite, dataCache).withKeepBinary(true); Vectorizer<Integer, BinaryObject, String, Double> vectorizer = new BinaryObjectVectorizer<Integer>("feature1").labeled("label"); KMeansTrainer trainer = new KMeansTrainer(); KMeansModel kmdl = trainer.fit(datasetBuilder, vectorizer); System.out.println(">>> Model trained over binary objects. Model " + kmdl); } finally { dataCache.destroy(); } } }
Source:
private static Manifest readManifestFile(final File manifestFile) { Manifest manifest = null; FileInputStream fis = null; try { if (manifestFile.exists()) { fis = new FileInputStream(manifestFile); manifest = new Manifest(fis); } } catch (IOException e) { } finally { StreamUtil.safeClose(fis); } return manifest; }

Target:
private static Manifest readManifestFile(final File manifestFile) { try { if (manifestFile.isFile()) { try (FileInputStream fis = new FileInputStream(manifestFile)) { return new Manifest(fis); } } } catch (IOException e) { } return null; }
Source:
public String name() { return null; }

Target:
public String name() { return name; }
Source:
public void addValidationResults(ValidationResults value) { if (value == null || value.isEmpty()) { return; } Map<String, ValidationResult> allValidationResults = value.getAllValidationResults(); if (allValidationResults != null) { for (Entry<String, ValidationResult> validationResult : allValidationResults.entrySet()) { addValidationResult(validationResult.getKey(), validationResult.getValue()); } } }

Target:
public void addValidationResults(ValidationResults value) { if (value == null || value.isEmpty()) { return; } Map<String, ValidationResult> allValidationResults = value.getAll(); for (Entry<String, ValidationResult> validationResult : allValidationResults.entrySet()) { addValidationResult(validationResult.getKey(), validationResult.getValue()); } }
Source:
public LilianaWakerOfTheDead(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.PLANESWALKER}, "{2}{B}{B}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.LILIANA); this.addAbility(new PlaneswalkerEntersWithLoyaltyCountersAbility(4)); this.addAbility(new LoyaltyAbility(new LilianaWakerOfTheDeadDiscardEffect(), 1)); Ability ability = new LoyaltyAbility(new BoostTargetEffect( xValue, xValue, Duration.EndOfTurn, true ).setText("target creature gets -X/-X until end of turn, where X is the number of cards in your graveyard"), -3); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(ability); this.addAbility(new LoyaltyAbility(new GetEmblemEffect(new LilianaWakerOfTheDeadEmblem()), -7)); }

Target:
public LilianaWakerOfTheDead(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.PLANESWALKER}, "{2}{B}{B}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.LILIANA); this.addAbility(new PlaneswalkerEntersWithLoyaltyCountersAbility(4)); this.addAbility(new LoyaltyAbility(new LilianaWakerOfTheDeadDiscardEffect(), 1)); Ability ability = new LoyaltyAbility(new BoostTargetEffect( xValue, xValue, Duration.EndOfTurn, true ).setText("target creature gets -X/-X until end of turn, where X is the number of cards in your graveyard"), -3) .addHint(new ValueHint("Cards in your graveyard", xValue_hint)); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(ability); this.addAbility(new LoyaltyAbility(new GetEmblemEffect(new LilianaWakerOfTheDeadEmblem()), -7)); }
Source:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { throw new TemporalParseException( "Wrong header information type: " + fieldsFromHeader ); } defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); }

Target:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { throw new IllegalStateException( "Wrong header information type: " + fieldsFromHeader ); } defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); }
Source:
public static void main(String[] args) { System.setProperty("hazelcast.jcache.provider.type", "client"); ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); calculateInvocationTime(applicationContext); HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); }

Target:
public static void main(String[] args) { System.setProperty("hazelcast.jcache.provider.type", "client"); ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); doInvocation(applicationContext); HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); }
Source:
public void upgradeOutcomeTableRevision2To3(SQLiteDatabase db) { String commonColumns = OutcomeEventsTable._ID + "," + OutcomeEventsTable.COLUMN_NAME_NAME + "," + OutcomeEventsTable.COLUMN_NAME_TIMESTAMP + "," + OutcomeEventsTable.COLUMN_NAME_NOTIFICATION_IDS + "," + OutcomeEventsTable.COLUMN_NAME_WEIGHT; String commonColumnsWithSessionColumn = commonColumns + "," + OutcomeEventsTable.COLUMN_NAME_SESSION; String commonColumnsWithNewSessionColumn = commonColumns + "," + OutcomeEventsTable.COLUMN_NAME_NOTIFICATION_INFLUENCE_TYPE; String auxOutcomeTableName = OutcomeEventsTable.TABLE_NAME + "_aux"; try { db.execSQL("BEGIN TRANSACTION;"); db.execSQL("ALTER TABLE " + OutcomeEventsTable.TABLE_NAME + " RENAME TO " + auxOutcomeTableName + ";"); db.execSQL(getSqlCreateOutcomeEntries()); db.execSQL("INSERT INTO " + OutcomeEventsTable.TABLE_NAME + "(" + commonColumnsWithNewSessionColumn + ")" + " SELECT " + commonColumnsWithSessionColumn + " FROM " + auxOutcomeTableName + ";"); db.execSQL("DROP TABLE " + auxOutcomeTableName + ";"); db.execSQL("COMMIT;"); } catch (SQLiteException e) { e.printStackTrace(); } finally { db.execSQL("COMMIT;"); } }

Target:
public void upgradeOutcomeTableRevision2To3(SQLiteDatabase db) { String commonColumns = OutcomeEventsTable._ID + "," + OutcomeEventsTable.COLUMN_NAME_NAME + "," + OutcomeEventsTable.COLUMN_NAME_TIMESTAMP + "," + OutcomeEventsTable.COLUMN_NAME_NOTIFICATION_IDS + "," + OutcomeEventsTable.COLUMN_NAME_WEIGHT; String commonColumnsWithSessionColumn = commonColumns + "," + OutcomeEventsTable.COLUMN_NAME_SESSION; String commonColumnsWithNewSessionColumn = commonColumns + "," + OutcomeEventsTable.COLUMN_NAME_NOTIFICATION_INFLUENCE_TYPE; String auxOutcomeTableName = OutcomeEventsTable.TABLE_NAME + "_aux"; try { db.execSQL("BEGIN TRANSACTION;"); db.execSQL("ALTER TABLE " + OutcomeEventsTable.TABLE_NAME + " RENAME TO " + auxOutcomeTableName + ";"); db.execSQL(getSqlCreateOutcomeEntries()); db.execSQL("INSERT INTO " + OutcomeEventsTable.TABLE_NAME + "(" + commonColumnsWithNewSessionColumn + ")" + " SELECT " + commonColumnsWithSessionColumn + " FROM " + auxOutcomeTableName + ";"); db.execSQL("DROP TABLE " + auxOutcomeTableName + ";"); } catch (SQLiteException e) { e.printStackTrace(); } finally { db.execSQL("COMMIT;"); } }
Source:
public static List<Integer> getThreadIds(int pid) { File threadDir = new File(String.format(ProcPath.TASK_PATH, pid)); File[] threads = threadDir .listFiles(file -> DIGITS.matcher(file.getName()).matches() && Integer.valueOf(file.getName()) != pid); List<Integer> threadIDs = new ArrayList<>(); for (File thread : threads) { int tid = ParseUtil.parseIntOrDefault(thread.getName(), 0); threadIDs.add(tid); } return threadIDs; }

Target:
public static List<Integer> getThreadIds(int pid) { File threadDir = new File(String.format(ProcPath.TASK_PATH, pid)); File[] threads = threadDir .listFiles(file -> DIGITS.matcher(file.getName()).matches() && Integer.valueOf(file.getName()) != pid); return (threads != null) ? Arrays.stream(threads) .map(thread -> ParseUtil.parseIntOrDefault(thread.getName(), 0)).collect(Collectors.toList()) : Collections.emptyList(); }
Source:
public void init() throws Exception { if (processedFiles.isEmpty()) { return; } processedFiles .entrySet() .stream() .forEach( entry -> entry .getValue() .forEach( routeDefinition -> { try { camelContext.addRouteDefinition(routeDefinition); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } })); }

Target:
public void init() { processedFiles.values().forEach(this::addRouteDefinitions); }
Source:
public TransportChannel(final TransportConnection connection, final CloseableHttpResponse response) throws IOException { super(); this.connection = connection; this.response = response; this.responseHttpEntity = response.getEntity(); this.streamParser = new TransportEventStreamParser( this.responseHttpEntity.getContent()); this.iterator = this.streamParser; if (log.isDebugEnabled()) { log.debug( "constructed " + this.toString() + " of type " + this.getClass().getName()); } }

Target:
public TransportChannel(final TransportConnection connection, final CloseableHttpResponse response) throws IOException { super(); this.connection = connection; this.response = response; this.responseHttpEntity = response.getEntity(); this.streamParser = new TransportEventStreamParser( this.responseHttpEntity.getContent()); this.iterator = this.streamParser; log.debug("constructed of type {}", this, this.getClass().getName()); }
Source:
public ArrayList<String> getPeriod(String hostname, String service){ if (service.equals("SRMv2")) { service = "SRM"; } ArrayList<String> period = new ArrayList<String>(); for (DowntimeItem item : this.list) { if (item.hostname.equals(hostname)) { if (item.service.equals(service)) { period.add(item.startTime); period.add(item.endTime); return period; } } } return null; }

Target:
public ArrayList<String> getPeriod(String hostname, String service){ ArrayList<String> period = new ArrayList<String>(); for (DowntimeItem item : this.list) { if (item.hostname.equals(hostname)) { if (item.service.equals(service)) { period.add(item.startTime); period.add(item.endTime); return period; } } } return null; }
Source:
void assignResourceRequests() { while (hasReadyPendingRequest()) { SamzaResourceRequest request = peekReadyPendingRequest().get(); String processorId = request.getProcessorId(); String preferredHost = hostAffinityEnabled ? request.getPreferredHost() : ResourceRequestState.ANY_HOST; Instant requestCreationTime = request.getRequestTimestamp(); LOG.info("Handling assignment request for Processor ID: on host: {}.", processorId, preferredHost); if (hasAllocatedResource(preferredHost)) { LOG.info("Found an available container for Processor ID: on the host: {}", processorId, preferredHost); if (hostAffinityEnabled) { state.matchedResourceRequests.incrementAndGet(); } containerManager.handleContainerLaunch(request, preferredHost, peekAllocatedResource(preferredHost), resourceRequestState, this); } else { LOG.info("Did not find any allocated containers for running Processor ID: on the host: {}.", processorId, preferredHost); if (isRequestExpired(request)) { updateExpiryMetrics(request); containerManager.handleExpiredRequestForControlActionOrHostAffinityEnabled(processorId, preferredHost, request, this, resourceRequestState); } else { LOG.info("Request for Processor ID: on preferred host has not expired yet." + "Request creation time: {}. Current Time: {}. Request timeout: ms", processorId, preferredHost, requestCreationTime, System.currentTimeMillis(), getRequestTimeout(request)); break; } } } }

Target:
void assignResourceRequests() { while (hasReadyPendingRequest()) { SamzaResourceRequest request = peekReadyPendingRequest().get(); String processorId = request.getProcessorId(); String preferredHost = hostAffinityEnabled ? request.getPreferredHost() : ResourceRequestState.ANY_HOST; Instant requestCreationTime = request.getRequestTimestamp(); LOG.info("Handling assignment for Processor ID: with request {}", processorId, request); if (hasAllocatedResource(preferredHost)) { LOG.info("Found an available container for Processor ID: on the host: {}", processorId, preferredHost); if (hostAffinityEnabled) { state.matchedResourceRequests.incrementAndGet(); } boolean containerLaunchComplete = containerManager.handleContainerLaunch(request, preferredHost, peekAllocatedResource(preferredHost), resourceRequestState, this); if (!containerLaunchComplete) { break; } } else { LOG.info("Did not find any allocated containers for running Processor ID: on the host: {}.", processorId, preferredHost); if (isRequestExpired(request)) { updateExpiryMetrics(request); containerManager.handleExpiredRequest(processorId, preferredHost, request, this, resourceRequestState); } else { LOG.info("Request for Processor ID: on preferred host has not expired yet." + "Request creation time: {}. Current Time: {}. Request timeout: ms", processorId, preferredHost, requestCreationTime, System.currentTimeMillis(), getRequestTimeout(request).toMillis()); break; } } } }
Source:
public int compareOrder(NodeInfo other) { int result = 0; if (other instanceof ElementNode) { result = Integer.compare(depth, ((ElementNode) other).depth); if (result == 0) { result = compareCommonAncestorChildrenOrder(this, other); } } return result; }

Target:
public int compareOrder(NodeInfo other) { int result = 0; if (other instanceof AbstractNode) { result = Integer.compare(depth, ((AbstractNode) other).getDepth()); if (result == 0) { result = compareCommonAncestorChildrenOrder(this, other); } } return result; }
Source:
public SecureStore get() { String secureStore = getCurrentSecureStoreName(); if (DefaultSecureStore.NAME.equals(secureStore)) { return defaultSecureStore; } int separatorPosition = secureStore.lastIndexOf("/"); String storeName = secureStore.substring(separatorPosition + 1); String pluginName = secureStore.substring(0, separatorPosition); Set<SecureStoreData> stores = getSecureStores(pluginName); for (SecureStoreData store : stores) { if (store.getStoreName().equals(secureStore)) { Class<? extends SecureStore> secureStoreImpl = store.load(); return new SecureStoreWrapper(injector.getInstance(secureStoreImpl)); } } throw new SecureStoreException(String.format( "Cannot find secure store with name %s in plugin %s", storeName, pluginName)); }

Target:
public DynamicItem<SecureStore> get() { String secureStore = getCurrentSecureStoreName(); if (DefaultSecureStore.NAME.equals(secureStore)) { return DynamicItem.<SecureStore> of(defaultSecureStore); } int separatorPosition = secureStore.lastIndexOf("/"); if (separatorPosition < 0) { throw new SecureStoreException(String.format( "Unsupported secure store format %s." + "Proper format is: $plugin_name/$secure_store_name", secureStore)); } String storeName = secureStore.substring(separatorPosition + 1); String pluginName = secureStore.substring(0, separatorPosition); Set<SecureStoreData> stores = getSecureStores(pluginName); for (SecureStoreData store : stores) { if (store.getStoreName().equals(secureStore)) { Class<? extends SecureStore> secureStoreImpl = store.load(); return DynamicItem.<SecureStore> of(new SecureStoreWrapper(injector .getInstance(secureStoreImpl))); } } throw new SecureStoreException(String.format( "Cannot find secure store with name %s in plugin %s", storeName, pluginName)); }
Source:
public void testQuotedIdentifiers() throws Throwable { Schema schema = new Schema(); schema.addColumn("컬럼1", TEXT); schema.addColumn("컬럼2", TEXT); testEval(schema, "테이블1", "123,234", "select \"컬럼1\"::float, cast (\"컬럼2\" as float4) as a from \"테이블1\"", new String[]{"123.0", "234.0"}); testEval(schema, "테이블1", "123,234", "select char_length(\"컬럼1\"), \"컬럼2\"::float4 as \"별명1\" from \"테이블1\"", new String[]{"3", "234.0"}); }

Target:
public void testQuotedIdentifiers() throws TajoException { Schema schema = new Schema(); schema.addColumn("컬럼1", TEXT); schema.addColumn("컬럼2", TEXT); testEval(schema, "테이블1", "123,234", "select \"컬럼1\"::float, cast (\"컬럼2\" as float4) as a from \"테이블1\"", new String[]{"123.0", "234.0"}); testEval(schema, "테이블1", "123,234", "select char_length(\"컬럼1\"), \"컬럼2\"::float4 as \"별명1\" from \"테이블1\"", new String[]{"3", "234.0"}); }
Source:
public long getEstimatedSize() { return strategy.getEstimatedSize(); }

Target:
public long getEstimatedSize() { return strategy == null ? 0 : strategy.getEstimatedSize(); }
Source:
public void afterNavigateTo(String url, WebDriver driver) { StringBuilder builder = new StringBuilder(); if (!AlertHandler.isAlertPresent(driver)) { if (url.equals(driver.getCurrentUrl())) { builder.append("<tr class=\"success\"><td>Url after navigation</td><td>" + "<a href='" + driver.getCurrentUrl() + "'>" + driver.getCurrentUrl() + "</a></td><td> <br/> &nbsp;</td></tr>"); CommonUtils.appendTextToFile(logPath, builder.toString()); } else { if (driver.getCurrentUrl().contains("data:text/html,chromewebdata ")) { driver.get(url); } logWarning("Url after navigation", driver.getCurrentUrl()); } } else { logWarning("Url after navigation", "Unable to check URL after navigation - alert present"); } Method method = TestContext.getCurrentTestMethod(); if (method.isAnnotationPresent(Execute.class) && TestContext.isIsFirstLoad()) { TestContext.setFirstLoad(false); User user = method.getAnnotation(Execute.class).asUser(); if (user == User.ANONYMOUS) { } else { new WikiBasePageObject(driver).loginAs(user); driver.get(url); } } logJSError(driver); }

Target:
public void afterNavigateTo(String url, WebDriver driver) { StringBuilder builder = new StringBuilder(); if (!AlertHandler.isAlertPresent(driver)) { if (url.equals(driver.getCurrentUrl())) { builder.append("<tr class=\"success\"><td>Url after navigation</td><td>" + "<a href='" + driver.getCurrentUrl() + "'>" + driver.getCurrentUrl() + "</a></td><td> <br/> &nbsp;</td></tr>"); CommonUtils.appendTextToFile(logPath, builder.toString()); } else { if (driver.getCurrentUrl().contains("data:text/html,chromewebdata ")) { driver.get(url); } logWarning("Url after navigation", driver.getCurrentUrl()); } } else { logWarning("Url after navigation", "Unable to check URL after navigation - alert present"); } Method method = TestContext.getCurrentTestMethod(); if (method.isAnnotationPresent(Execute.class) && TestContext.isIsFirstLoad()) { TestContext.setFirstLoad(false); User user = method.getAnnotation(Execute.class).asUser(); if (user == User.ANONYMOUS) { } else { new WikiBasePageObject(driver).loginAs(user.getUserName(), user.getPassword(), url); } } logJSError(driver); }
Source:
private void outputLine(String line, ProblemMarkerInfo marker) { String l = line + "\n"; if ( outputStream == null ) return; try { if ( marker != null && outputStream instanceof IErrorMarkeredOutputStream ) { IErrorMarkeredOutputStream s = (IErrorMarkeredOutputStream) outputStream; s.write(l, marker); } else { byte[] b = l.getBytes(); outputStream.write(b, 0, b.length); } } catch (IOException e) { CCorePlugin.log(e); } }

Target:
private void outputLine(String line, ProblemMarkerInfo marker) { String l = line + "\n"; if ( outputStream == null ) { return; } try { if ( marker != null && outputStream instanceof IErrorMarkeredOutputStream ) { IErrorMarkeredOutputStream s = (IErrorMarkeredOutputStream) outputStream; s.write(l, marker); } else { byte[] b = l.getBytes(); outputStream.write(b, 0, b.length); } } catch (IOException e) { CCorePlugin.log(e); } }
Source:
public RegisteredServiceMultifactorPolicy.FailureModes determineFailureMode(final RegisteredService service) { RegisteredServiceMultifactorPolicy.FailureModes failureMode = CLOSED; if (StringUtils.isNotBlank(this.globalFailureMode)) { failureMode = RegisteredServiceMultifactorPolicy.FailureModes.valueOf(this.globalFailureMode); LOGGER.debug("Using global multi-factor failure mode for defined as [{}]", service, failureMode); } if (service != null) { LOGGER.debug("Evaluating multifactor authentication policy for service [{}}", service); final RegisteredServiceMultifactorPolicy policy = service.getMultifactorPolicy(); if (policy != null && policy.getFailureMode() != NOT_SET) { failureMode = policy.getFailureMode(); LOGGER.debug("Multi-factor failure mode for is defined as [{}]", service.getServiceId(), failureMode); } } return failureMode; }

Target:
public RegisteredServiceMultifactorPolicy.FailureModes determineFailureMode(final RegisteredService service) { RegisteredServiceMultifactorPolicy.FailureModes failureMode = CLOSED; if (StringUtils.isNotBlank(this.globalFailureMode)) { failureMode = RegisteredServiceMultifactorPolicy.FailureModes.valueOf(this.globalFailureMode); LOGGER.debug("Using global multi-factor failure mode for defined as [{}]", service, failureMode); } if (service != null) { LOGGER.debug("Evaluating multifactor authentication policy for service [{}]", service); final RegisteredServiceMultifactorPolicy policy = service.getMultifactorPolicy(); if (policy != null && policy.getFailureMode() != NOT_SET) { failureMode = policy.getFailureMode(); LOGGER.debug("Multi-factor failure mode for is defined as [{}]", service.getServiceId(), failureMode); } } LOGGER.debug("Final failure mode has been determined to be [{}]", failureMode); return failureMode; }
Source:
public Asset updateAssetInventory(String capitalAssetNumber, String conditionCode, String buildingCode, String roomNumber, String netid) { Asset asset = businessObjectService.findBySinglePrimaryKey(Asset.class, capitalAssetNumber); if (ObjectUtils.isNull(asset)) { return null; } asset.setConditionCode(conditionCode); asset.setBuildingCode(buildingCode); asset.setBuildingRoomNumber(roomNumber); Timestamp currentTimestamp = dateTimeService.getCurrentTimestamp(); asset.setLastInventoryDate(currentTimestamp); asset.setLastUpdatedTimestamp(currentTimestamp); asset = businessObjectService.save(asset); AssetExtension assetExtension = businessObjectService.findBySinglePrimaryKey(AssetExtension.class, capitalAssetNumber); if (ObjectUtils.isNull(asset)) { LOG.error("updateAssetInventory: Asset Extension #[" + capitalAssetNumber + "] not found "); return null; } assetExtension.setLastScannedNetid(netid); assetExtension.setLastScannedDate(currentTimestamp); businessObjectService.save(assetExtension); return asset; }

Target:
public Asset updateAssetInventory(String capitalAssetNumber, String conditionCode, String buildingCode, String roomNumber, String netid) { Asset asset = businessObjectService.findBySinglePrimaryKey(Asset.class, capitalAssetNumber); if (ObjectUtils.isNull(asset)) { return null; } asset.setConditionCode(conditionCode); asset.setBuildingCode(buildingCode); asset.setBuildingRoomNumber(roomNumber); Timestamp currentTimestamp = dateTimeService.getCurrentTimestamp(); asset.setLastInventoryDate(currentTimestamp); asset.setLastUpdatedTimestamp(currentTimestamp); AssetExtension assetExtension = (AssetExtension) asset.getExtension(); if (ObjectUtils.isNull(assetExtension)) { assetExtension = new AssetExtension(); asset.setExtension(assetExtension); } Person person = personService.getPersonByPrincipalName(netid); String lastScannedBy = person.getFirstName() + " " + person.getLastName() + " (" + netid + ")"; assetExtension.setLastScannedBy(lastScannedBy); assetExtension.setLastScannedDate(currentTimestamp); asset = businessObjectService.save(asset); return asset; }
Source:
public boolean check(VM vm) { if (vm.getStatus() == VMStatus.Suspended || vm.getStatus() == VMStatus.SavingState || vm.getStatus() == VMStatus.RestoringState) { return vm.getCustomCompatibilityVersion() != null; } return true; }

Target:
public boolean check(VM vm) { if (EnumSet.of(VMStatus.Suspended, VMStatus.SavingState, VMStatus.RestoringState).contains(vm.getStatus())) { return vm.getCustomCompatibilityVersion() != null; } return true; }
Source:
public void setUp() throws Exception { super.setUp(); mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE); mCm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE); PackageManager packageManager = mContext.getPackageManager(); mHasWifi = packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI); mHasTelephony = packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY); mBuilder = new JobInfo.Builder(CONNECTIVITY_JOB_ID, kJobServiceComponent); mInitialRestrictBackground = SystemUtil .runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_GET_CMD) .contains("enabled"); if(!mHasWifi) { return; } mInitialWiFiState = mWifiManager.isWifiEnabled(); }

Target:
public void setUp() throws Exception { super.setUp(); mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE); mCm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE); PackageManager packageManager = mContext.getPackageManager(); mHasWifi = packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI); mHasTelephony = packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY); mBuilder = new JobInfo.Builder(CONNECTIVITY_JOB_ID, kJobServiceComponent); mInitialRestrictBackground = SystemUtil .runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_GET_CMD) .contains("enabled"); if (mHasWifi) { mInitialWiFiState = mWifiManager.isWifiEnabled(); } }
Source:
public void prepareRun(BatchJoinerContext context) { if (conf.getNumPartitions() != null) { context.setNumPartitions(conf.getNumPartitions()); if (conf.getDistributionFactor() != null && conf.getDistributionFactor() < conf.getNumPartitions()) { LOG.warn(String.format( "Number of partitions (currently %d) should be greater than or equal to distribution factor (currently %d) " + "for optimal results.", conf.getNumPartitions(), conf.getDistributionFactor())); } } FailureCollector collector = context.getFailureCollector(); context.record(createFieldOperations(conf.getSelectedFields(collector), conf.getJoinKeys(collector))); }

Target:
public void prepareRun(BatchJoinerContext context) { if (conf.getNumPartitions() != null) { context.setNumPartitions(conf.getNumPartitions()); if (conf.getDistributionFactor() != null && conf.getDistributionFactor() < conf.getNumPartitions()) { LOG.warn("Number of partitions ({}) should be greater than or equal to distribution factor ({}) for optimal " + "results.", conf.getNumPartitions(), conf.getDistributionFactor()); } } FailureCollector collector = context.getFailureCollector(); context.record(createFieldOperations(conf.getSelectedFields(collector), conf.getJoinKeys(collector))); }
Source:
public final TaskResult run() { boolean isThisNextJob = getUserContent(WORKFLOW_STARTED, Scope.WORKFLOW) == null || this.callbackContext.getJobConfig().getJobId() .equals(this.callbackContext.getJobConfig().getWorkflow() + "_" + getUserContent(NEXT_JOB, Scope.WORKFLOW)); TaskResult result = isThisNextJob ? onRun(this.taskHelper) : new TaskResult(TaskResult.Status.COMPLETED, "Not a target job"); if (participant != null) { participant.unregisterRunningTask(this); } return result; }

Target:
public final TaskResult run() { try { boolean isThisNextJob = getUserContent(WORKFLOW_STARTED, Scope.WORKFLOW) == null || this.callbackContext.getJobConfig().getJobId() .equals(this.callbackContext.getJobConfig().getWorkflow() + "_" + getUserContent(NEXT_JOB, Scope.WORKFLOW)); return isThisNextJob ? onRun(this.taskHelper) : new TaskResult(TaskResult.Status.COMPLETED, "Not a target job"); } finally { if (participant != null) { participant.unregisterRunningTask(this); } else { logger.warn("Task with id: " + taskId + " is not unregistered since the participant is not set"); } } }
Source:
public void setUp() { repository = mock(Repository.class); entityType = mock(EntityType.class); repositoryCollection = mock(RepositoryCollection.class); dataService = mock(DataService.class); decoratorConfiguration = mock(DecoratorConfiguration.class); dynamicRepositoryDecoratorFactory = mock(DynamicRepositoryDecoratorFactory.class); when(entityType.getId()).thenReturn("entityTypeId"); when(repositoryCollection.hasRepository(decoratorConfigurationMetadata)).thenReturn(true); when(repository.getEntityType()).thenReturn(entityType); }

Target:
public void setUp() { when(entityType.getId()).thenReturn("entityTypeId"); when(repositoryCollection.hasRepository(decoratorConfigurationMetadata)).thenReturn(true); when(repository.getEntityType()).thenReturn(entityType); }