auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getJournalKeyFromDoi(String doi, Site site) { Map<String, Object> journalDoiRegexList = getJournalDoiRegexList(site); for (Map.Entry<String, Object> entry : journalDoiRegexList.entrySet()) { if (doi.matches(entry.getValue().toString())) { return entry.getKey(); } } return null; }

Target:
public String getJournalKeyFromDoi(String doi, Site site) { ImmutableList<DoiJournalRegex> doiJournalRegices = patternCache.computeIfAbsent(site, this::getFromConfig); for (DoiJournalRegex doiJournalRegex : doiJournalRegices) { Pattern pattern = doiJournalRegex.pattern; Matcher matcher = pattern.matcher(doi); if (matcher.matches()) { return doiJournalRegex.journalKey; } } return null; }
Source:
@Override public void draw(Canvas canvas) { if (!animating) { image.draw(canvas); } else { if (placeholder != null) { placeholder.draw(canvas); } float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION; int alpha = (int) (0xFF * normalized); if (normalized >= 1f) { animating = false; placeholder = null; image.setAlpha(0xFF); image.draw(canvas); } else { image.setAlpha(alpha); image.draw(canvas); invalidateSelf(); } } if (debugging) { drawDebugIndicator(canvas); } }

Target:
@Override public void draw(Canvas canvas) { if (!animating) { image.draw(canvas); } else { if (placeholder != null) { placeholder.draw(canvas); } float normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION; int alpha = (int) (0xFF * normalized); if (normalized >= 1f) { animating = false; placeholder = null; image.draw(canvas); } else { image.setAlpha(alpha); image.draw(canvas); image.setAlpha(0xFF); invalidateSelf(); } } if (debugging) { drawDebugIndicator(canvas); } }
Source:
public void addingAStudentAddsThemToTheSortedRoster() { school = new School(); school.add("Aimee", 2); List<String> expected = Arrays.asList("Aimee"); assertEquals(expected,school.roster()); }

Target:
public void addingAStudentAddsThemToTheSortedRoster() { school.add("Aimee", 2); List<String> expected = Arrays.asList("Aimee"); assertEquals(expected, school.roster()); }
Source:
public static <T extends RemoteJsonService> T create(Class<T> serviceClass, GerritHttpClient gerritHttpClient, Version version) { String uri = GerritVersion.isVersion26OrLater(version) ? "/gerrit_ui/rpc/" : "/gerrit/rpc/"; InvocationHandler handler = new GerritService(gerritHttpClient, uri + serviceClass.getSimpleName()); return serviceClass.cast(Proxy.newProxyInstance(GerritService.class.getClassLoader(), new Class<?>[] { serviceClass }, handler)); }

Target:
public static <T extends RemoteJsonService> T create(Class<T> serviceClass, GerritHttpClient gerritHttpClient, Version version) { String uri = GerritVersion.getGerritRpcUri(version); InvocationHandler handler = new GerritService(gerritHttpClient, uri + serviceClass.getSimpleName()); return serviceClass.cast(Proxy.newProxyInstance(GerritService.class.getClassLoader(), new Class<?>[] { serviceClass }, handler)); }
Source:
public V replace(K key, V value) { V v = delegate.replace(key, value); if (v != null) { stats.incrementCacheHits(); } else { stats.incrementCacheMisses(); } stats.incrementCachePuts(); return v; }

Target:
public V replace(K key, V value) { V v = delegate.replace(key, value); if (v != null) { stats.incrementCacheHits(); stats.incrementCachePuts(); } else { stats.incrementCacheMisses(); } return v; }
Source:
public JCloudsSlave( @Nonnull ProvisioningActivity.Id id, @Nonnull Server metadata, @Nonnull String labelString, @Nonnull SlaveOptions slaveOptions ) throws IOException, Descriptor.FormException { super( metadata.getName(), null, slaveOptions.getFsRoot(), slaveOptions.getNumExecutors(), Mode.NORMAL, labelString, null, new JCloudsRetentionStrategy(), Collections.singletonList(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("OPENSTACK_PUBLIC_IP", Openstack.getPublicAddress(metadata)) )) ); this.cloudName = id.getCloudName(); this.provisioningId = id; this.options = slaveOptions; this.nodeId = metadata.getId(); final Map<String, String> instanceMetaData = metadata.getMetadata(); if (instanceMetaData != null && !instanceMetaData.isEmpty()) { this.openstackMetaData = new TreeMap<>(instanceMetaData); } else { this.openstackMetaData = null; } setLauncher(new JCloudsLauncher(getLauncherFactory().createLauncher(this))); }

Target:
public JCloudsSlave( @Nonnull ProvisioningActivity.Id id, @Nonnull Server metadata, @Nonnull String labelString, @Nonnull SlaveOptions slaveOptions ) throws IOException, Descriptor.FormException { super( metadata.getName(), null, slaveOptions.getFsRoot(), slaveOptions.getNumExecutors(), Mode.NORMAL, labelString, null, new JCloudsRetentionStrategy(), Collections.singletonList(new EnvironmentVariablesNodeProperty( new EnvironmentVariablesNodeProperty.Entry("OPENSTACK_PUBLIC_IP", Openstack.getPublicAddress(metadata)) )) ); this.cloudName = id.getCloudName(); this.provisioningId = id; this.options = slaveOptions; this.nodeId = metadata.getId(); this.cache = makeCache(); setLauncher(new JCloudsLauncher(getLauncherFactory().createLauncher(this))); }
Source:
protected List<SurveyGroupDto> parseSurveyGroups(String response) throws Exception { List<SurveyGroupDto> dtoList = new ArrayList<SurveyGroupDto>(); JSONArray jsonArray = getJsonArray(response); if (jsonArray == null) { return dtoList; } for (int i = 0; i < jsonArray.length(); i++) { JSONObject o = jsonArray.getJSONObject(i); if (o != null) { try { SurveyGroupDto dto = new SurveyGroupDto(); if (o.has("name") && o.isNull("name")) { dto.setName(o.getString("name")); } if (!o.has("monitoringGroup") || o.isNull("monitoringGroup")) { dto.setMonitoringGroup(false); } else { dto.setMonitoringGroup(o.getBoolean("monitoringGroup")); } dtoList.add(dto); } catch (Exception e) { System.out.println("Error in json parsing: " + e.getMessage()); e.printStackTrace(); } } } return dtoList; }

Target:
protected List<SurveyGroupDto> parseSurveyGroups(String response) throws Exception { List<SurveyGroupDto> dtoList = new ArrayList<SurveyGroupDto>(); JSONArray jsonArray = getJsonArray(response); if (jsonArray == null) { return dtoList; } for (int i = 0; i < jsonArray.length(); i++) { JSONObject o = jsonArray.getJSONObject(i); if (o != null) { try { SurveyGroupDto dto = new SurveyGroupDto(); if (!o.isNull("name")) { dto.setName(o.getString("name")); } if (o.isNull("monitoringGroup")) { dto.setMonitoringGroup(false); } else { dto.setMonitoringGroup(o.getBoolean("monitoringGroup")); } dtoList.add(dto); } catch (Exception e) { System.out.println("Error in json parsing: " + e.getMessage()); e.printStackTrace(); } } } return dtoList; }
Source:
public Factory build() { BitSet redacted = new BitSet(); List<String> fields = new ArrayList<>(), keys = new ArrayList<>(); List<Integer> keyToFieldList = new ArrayList<>(); int i = 0; for (String fieldName : fieldNames) { if (redactedFieldNames.contains(fieldName)) redacted.set(i); fields.add(fieldName); keys.add(fieldName); keyToFieldList.add(i++); } for (Map.Entry<String, String[]> entry : prefixedNames.entrySet()) { String nextPrefix = entry.getKey(); String[] nextFieldNames = entry.getValue(); for (i = 0; i < nextFieldNames.length; i++) { String nextFieldName = nextFieldNames[i]; int index = fields.indexOf(nextFieldName); if (index == -1) { index = fields.size(); fields.add(nextFieldName); } keys.add(nextPrefix + nextFieldName); keyToFieldList.add(index); } } int[] keyToField = new int[keys.size()]; for (i = 0; i < keyToField.length; i++) { keyToField[i] = keyToFieldList.get(i); } String[] validated = fields.toArray(new String[0]); if (validated.length == 0) return new Factory(delegate); return new RealFactory(delegate, validated, keys.toArray(new String[0]), keyToField, redacted); }

Target:
public Factory build() { BitSet redacted = new BitSet(); List<String> fields = new ArrayList<>(), keys = new ArrayList<>(); List<Integer> keyToFieldList = new ArrayList<>(); int i = 0; for (String fieldName : fieldNames) { if (redactedFieldNames.contains(fieldName)) redacted.set(i); fields.add(fieldName); keys.add(fieldName); keyToFieldList.add(i++); } for (Map.Entry<String, String[]> entry : prefixedNames.entrySet()) { String nextPrefix = entry.getKey(); String[] nextFieldNames = entry.getValue(); for (i = 0; i < nextFieldNames.length; i++) { String nextFieldName = nextFieldNames[i]; int index = fields.indexOf(nextFieldName); if (index == -1) { index = fields.size(); fields.add(nextFieldName); } keys.add(nextPrefix + nextFieldName); keyToFieldList.add(index); } } int[] keyToField = new int[keys.size()]; for (i = 0; i < keyToField.length; i++) { keyToField[i] = keyToFieldList.get(i); } if (fields.isEmpty()) return new Factory(delegate); return new RealFactory(delegate, fields.toArray(new String[0]), keys.toArray(new String[0]), keyToField, redacted); }
Source:
public static String minimalEscape(Object content) { if (content == null) { return null; } String str = String.valueOf(content); StringBuilder result = new StringBuilder((int) (str.length() * 1.1)); int length = str.length(); char c; for (int i = 0; i < length; ++i) { c = str.charAt(i); switch (c) { case '&': result.append(AMP); break; case '<': result.append(LT); break; default: result.append(c); } } return result.toString(); }

Target:
public static String minimalEscape(Object content) { if (content == null) { return null; } String str = String.valueOf(content); int contentLength = str.length(); StringBuilder result = new StringBuilder((int) (contentLength * 1.1)); for (int i = 0; i < contentLength; ++i) { char c = str.charAt(i); switch (c) { case '&': result.append(AMP); break; case '<': result.append(LT); break; default: result.append(c); } } return result.toString(); }
Source:
public void overloadedMethodsGetResolved() throws Exception { provider = new ExtensionAwareEvaluationContextProvider( Collections.singletonList(new DummyExtension("_first", "first") { @Override public Object getRootObject() { return new RootWithOverloads(); } })); assertThat(evaluateExpression("method()")).isEqualTo("zero"); assertThat(evaluateExpression("method(23)")).isEqualTo("single-int"); assertThat(evaluateExpression("method('hello')")).isEqualTo("single-string"); assertThat(evaluateExpression("method('one', 'two')")).isEqualTo("two"); assertThat(evaluateExpression("method(1, 2)")).isEqualTo("two-ints"); assertThat(evaluateExpression("method(1, 'two')")).isEqualTo("int-and-string"); }

Target:
public void overloadedMethodsGetResolved() throws Exception { provider = createContextProviderWithOverloads(); assertThat(evaluateExpression("method()")).isEqualTo("zero"); assertThat(evaluateExpression("method(23)")).isEqualTo("single-int"); assertThat(evaluateExpression("method('hello')")).isEqualTo("single-string"); assertThat(evaluateExpression("method('one', 'two')")).isEqualTo("two"); assertThat(evaluateExpression("method(1, 2)")).isEqualTo("two-ints"); assertThat(evaluateExpression("method(1, 'two')")).isEqualTo("int-and-string"); }
Source:
public static String getPreferredVariable(IPath[] paths, IContainer target) { IPath commonRoot = null; for (IPath path : paths) { if (path != null) { if (commonRoot == null) commonRoot = path; else { int count = commonRoot.matchingFirstSegments(path); int remainingSegments = commonRoot.segmentCount() - count; if (remainingSegments <= 0) return null; commonRoot = commonRoot.removeLastSegments(remainingSegments); } } } String mostAppropriate = null; String mostAppropriateToParent = null; int mostAppropriateCount = Integer.MAX_VALUE; int mostAppropriateCountToParent = Integer.MAX_VALUE; IPathVariableManager pathVariableManager = target.getPathVariableManager(); for (String variable : pathVariableManager.getPathVariableNames()) { if (isPreferred(variable)) { URI rawValue = pathVariableManager.getURIValue(variable); URI value = pathVariableManager.resolveURI(rawValue); if (value != null) { IPath path = URIUtil.toPath(value); if (path != null) { int difference = path.matchingFirstSegments(commonRoot); if (difference > 0) { if (difference < mostAppropriateCount) { mostAppropriateCount = difference; mostAppropriate = variable; } } else { difference = commonRoot.matchingFirstSegments(path); if (difference > 0) { if (difference < mostAppropriateCountToParent) { mostAppropriateCountToParent = difference; mostAppropriateToParent = variable; } } } } } } } if (mostAppropriate == null) { if (mostAppropriateToParent == null) return "PROJECT_LOC"; return mostAppropriateToParent; } return mostAppropriate; }

Target:
public static String getPreferredVariable(IPath[] paths, IContainer target) { IPath commonRoot = null; for (IPath path : paths) { if (path != null) { if (commonRoot == null) commonRoot = path; else { int count = commonRoot.matchingFirstSegments(path); int remainingSegments = commonRoot.segmentCount() - count; if (remainingSegments <= 0) return null; commonRoot = commonRoot.removeLastSegments(remainingSegments); } } } String mostAppropriate = null; String mostAppropriateToParent = null; int mostAppropriateCount = Integer.MAX_VALUE; int mostAppropriateCountToParent = Integer.MAX_VALUE; IPathVariableManager pathVariableManager = target.getPathVariableManager(); for (String variableName : pathVariableManager.getPathVariableNames()) { if (isPreferred(variableName)) { URI rawValue = pathVariableManager.getURIValue(variableName); URI value = pathVariableManager.resolveURI(rawValue); if (value != null) { IPath path = URIUtil.toPath(value); if (path != null) { int difference = path.matchingFirstSegments(commonRoot); if (difference > 0) { if (difference < mostAppropriateCount) { mostAppropriateCount = difference; mostAppropriate = variableName; } } else { difference = commonRoot.matchingFirstSegments(path); if (difference > 0) { if (difference < mostAppropriateCountToParent) { mostAppropriateCountToParent = difference; mostAppropriateToParent = variableName; } } } } } } } if (mostAppropriate == null) { if (mostAppropriateToParent == null) return "PROJECT_LOC"; return mostAppropriateToParent; } return mostAppropriate; }
Source:
public void deleteStorage(final String id, final Optional<String> user) throws DbWriteOperationsBlockedException, NoSuchStorageException, StorageIsUsedException, InternalNakadiException { if (featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.DISABLE_DB_WRITE_OPERATIONS)) { throw new DbWriteOperationsBlockedException("Cannot delete storage: write operations on DB " + "are blocked by feature flag."); } try { final Optional<Object> storageOrNone = storageDbRepository.getStorage(id) .map(Function.identity()); storageDbRepository.deleteStorage(id); auditLogPublisher.publish( Optional.empty(), storageOrNone, NakadiAuditLogPublisher.ResourceType.STORAGE, NakadiAuditLogPublisher.ActionType.DELETED, id, user); } catch (final RepositoryProblemException e) { LOG.error("DB error occurred when deleting storage", e); throw new InternalNakadiException(e.getMessage()); } catch (final TransactionException e) { LOG.error("Error with transaction handling when deleting storage", e); throw new InternalNakadiException("Transaction error occurred when deleting storage"); } }

Target:
public void deleteStorage(final String id, final Optional<String> user) throws DbWriteOperationsBlockedException, NoSuchStorageException, StorageIsUsedException, InternalNakadiException { if (featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.DISABLE_DB_WRITE_OPERATIONS)) { throw new DbWriteOperationsBlockedException("Cannot delete storage: write operations on DB " + "are blocked by feature flag."); } try { final Optional<Object> storageOrNone = storageDbRepository.getStorage(id) .map(Function.identity()); storageDbRepository.deleteStorage(id); auditLogPublisher.publish( storageOrNone, Optional.empty(), NakadiAuditLogPublisher.ResourceType.STORAGE, NakadiAuditLogPublisher.ActionType.DELETED, id, user); } catch (final RepositoryProblemException e) { LOG.error("DB error occurred when deleting storage", e); throw new InternalNakadiException(e.getMessage()); } catch (final TransactionException e) { LOG.error("Error with transaction handling when deleting storage", e); throw new InternalNakadiException("Transaction error occurred when deleting storage"); } }
Source:
private static String loadFile(String fileName) { String content = ""; fileName = ConfigUtil.resolvePath(getSysprepDir(), fileName); File file = new File(fileName); if (file.exists()) { try { content = new String(Files.readAllBytes(file.toPath())); } catch (Exception e) { log.error("Failed to read sysprep template '{}': {}", fileName, e.getMessage()); log.debug("Exception", e); } } else { log.error("Sysprep template: '{}' not found", fileName); } return content; }

Target:
private static String loadFile(String fileName) { String content = ""; fileName = ConfigUtil.resolvePath(getSysprepDir(), fileName); Path path = Paths.get(fileName); if (Files.exists(path)) { try { content = new String(Files.readAllBytes(path)); } catch (Exception e) { log.error("Failed to read sysprep template '{}': {}", fileName, e.getMessage()); log.debug("Exception", e); } } else { log.error("Sysprep template: '{}' not found", fileName); } return content; }
Source:
public boolean invalidateIfNecessary(BaragonRequest request) { if (request.getLoadBalancerService().getOptions().get("edgeCacheDNS") == null) { return false; } try { String edgeCacheDNS = ((String) request.getLoadBalancerService().getOptions().get("edgeCacheDNS")); Optional<CloudflareZone> matchingZone = getCloudflareZone(edgeCacheDNS); if (!matchingZone.isPresent()) { LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare Zone was found!"); return false; } String zoneId = matchingZone.get().getId(); Optional<CloudflareDnsRecord> matchingDnsRecord = getCloudflareDnsRecord(edgeCacheDNS, zoneId); if (!matchingDnsRecord.isPresent()) { LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare DNS Record was found!"); return false; } if (!matchingDnsRecord.get().isProxied()) { LOG.warn("`edgeCacheDNS` was defined on the request, but is not a proxied DNS record!", edgeCacheDNS); return false; } return cf.purgeCache( zoneId, Collections.singletonList( String.format(CACHE_TAG_FORMAT, request.getLoadBalancerService().getServiceId(), environment.getName()) ) ); } catch (CloudflareClientException e) { LOG.error("Unable to invalidate Cloudflare cache for request {}", request, e); return false; } }

Target:
public boolean invalidateIfNecessary(BaragonRequest request) { if (!request.getLoadBalancerService().getEdgeCacheDNS().isPresent()) { return false; } try { String edgeCacheDNS = request.getLoadBalancerService().getEdgeCacheDNS().get(); Optional<CloudflareZone> matchingZone = getCloudflareZone(edgeCacheDNS); if (!matchingZone.isPresent()) { LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare Zone was found!"); return false; } String zoneId = matchingZone.get().getId(); Optional<CloudflareDnsRecord> matchingDnsRecord = getCloudflareDnsRecord(edgeCacheDNS, zoneId); if (!matchingDnsRecord.isPresent()) { LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare DNS Record was found!"); return false; } if (!matchingDnsRecord.get().isProxied()) { LOG.warn("`edgeCacheDNS` was defined on the request, but is not a proxied DNS record!", edgeCacheDNS); return false; } String cacheTag = String.format( edgeCacheConfiguration.getIntegrationSettings().get("cacheTagFormat"), request.getLoadBalancerService().getServiceId() ); LOG.debug("Sending cache purge request against for to Cloudflare...", matchingDnsRecord.get().getName(), cacheTag); return cf.purgeEdgeCache(zoneId, Collections.singletonList(cacheTag)); } catch (CloudflareClientException e) { LOG.error("Unable to invalidate Cloudflare cache for request {}", request, e); return false; } }
Source:
private <V> void addCallback(CompletableFuture<V> cfuture, CommitData cd, OnSuccessInterface<V> onSuccessInterface) { cfuture.handleAsync((result, exception) -> { if (result != null) { try { onSuccessInterface.onSuccess(cd, result); return null; } catch (Exception e) { cd.commitObserver.failed(e); return null; } } else { cd.commitObserver.failed(exception); return null; } }, env.getSharedResources().getAsyncCommitExecutor()); }

Target:
private <V> void addCallback(CompletableFuture<V> cfuture, CommitData cd, OnSuccessInterface<V> onSuccessInterface) { cfuture.handleAsync((result, exception) -> { if (exception != null) { cd.commitObserver.failed(exception); return null; } else { try { onSuccessInterface.onSuccess(result); return null; } catch (Exception e) { cd.commitObserver.failed(e); return null; } } }, env.getSharedResources().getAsyncCommitExecutor()); }
Source:
public Collection<AsyncQuery> deleteAsyncQueryAndResultCollection(FilterExpression filterExpression) { log.debug("deleteAsyncQueryAndResultCollection"); Collection<AsyncQuery> asyncQueryList = null; try { asyncQueryList = (Collection<AsyncQuery>) executeInTransaction(dataStore, (tx, scope) -> { EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .filterExpression(filterExpression) .build(); Iterable<Object> loaded = tx.loadObjects(asyncQueryCollection, scope); Iterator<Object> itr = loaded.iterator(); while (itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); if (query != null) { tx.delete(query, scope); } } return loaded; }); } catch (Exception e) { log.error("Exception: {}", e); } return asyncQueryList; }

Target:
public Collection<AsyncQuery> deleteAsyncQueryAndResultCollection(FilterExpression filterExpression) { log.debug("deleteAsyncQueryAndResultCollection"); Collection<AsyncQuery> asyncQueryList = null; asyncQueryList = (Collection<AsyncQuery>) executeInTransaction(dataStore, (tx, scope) -> { EntityProjection asyncQueryCollection = EntityProjection.builder() .type(AsyncQuery.class) .filterExpression(filterExpression) .build(); Iterable<Object> loaded = tx.loadObjects(asyncQueryCollection, scope); Iterator<Object> itr = loaded.iterator(); while (itr.hasNext()) { AsyncQuery query = (AsyncQuery) itr.next(); if (query != null) { tx.delete(query, scope); } } return loaded; }); return asyncQueryList; }
Source:
public static void markNoteAsRead(final Note note) { if (note == null) { return; } if (note.isUnread()) { WordPress.getRestClientUtilsV1_1().decrementUnreadCount(note.getId(), "10", new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { note.setRead(); NotificationsTable.saveNote(note); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.NOTIFS, "Could not mark note as read via API."); } }); } }

Target:
public static void markNoteAsRead(final Note note) { if (note == null) { return; } if (note.isUnread()) { WordPress.getRestClientUtilsV1_1().decrementUnreadCount(note.getId(), "9999", new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { note.setRead(); NotificationsTable.saveNote(note); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.e(AppLog.T.NOTIFS, "Could not mark note as read via API."); } }); } }
Source:
public Set<String> map(Set<String> genres) { Set<String> tags = Sets.newHashSet(); for (String genre : genres) { if (genre.contains("<LINK_0>")) { tags.add(paTagMap.get(genre)); } } if (tags.size() == 1 && tags.contains("film")) { tags.add("action"); } return tags; }

Target:
public Set<TopicRef> map(Set<String> genres) { Set<String> tags = Sets.newHashSet(); for (String genre : genres) { if (genre.contains("<LINK_0>")) { String tag = paTagMap.get(genre); if (tag != null) { tags.add(tag); } } } if (tags.size() == 1 && tags.contains("film")) { tags.add("action"); } return getTopicRefFromTags(tags); }
Source:
public void checkWebJavaSpringCommands() { consoles.startCommandAndCheckResult(WEB_JAVA_SPRING, BUILD, "build", BUILD_SUCCESS); consoles.startCommandAndCheckResult( WEB_JAVA_SPRING, BUILD, "web-java-spring:build", BUILD_SUCCESS); consoles.startCommandAndCheckResult( WEB_JAVA_SPRING, RUN, "web-java-spring:build and run", "Server startup in"); consoles.startCommandAndCheckApp(currentWindow, " consoles.closeProcessTabWithAskDialog("web-java-spring:build and run"); consoles.startCommandAndCheckResult( WEB_JAVA_SPRING, RUN, "web-java-spring:run tomcat", "Server startup in"); consoles.startCommandAndCheckApp(currentWindow, " projectExplorer.invokeCommandWithContextMenu( RUN, WEB_JAVA_SPRING, "web-java-spring:stop tomcat"); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal("/bin/bash -c $TOMCAT_HOME/bin/catalina.sh"); consoles.startCommandAndCheckResult( WEB_JAVA_SPRING, DEBUG, "web-java-spring:debug", "Listening for transport dt_socket at address: 8000"); }

Target:
public void checkWebJavaSpringCommands() { consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, BUILD_GOAL, BUILD_COMMAND, BUILD_SUCCESS); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), BUILD_SUCCESS); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, RUN_GOAL, BUILD_AND_RUN_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), SERVER_STARTUP_IN); consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" consoles.closeProcessTabWithAskDialog(BUILD_AND_RUN_COMMAND_ITEM.getItem(WEB_JAVA_SPRING)); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, RUN_GOAL, RUN_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), SERVER_STARTUP_IN); consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_SPRING, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_SPRING)); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal("/bin/bash -c $TOMCAT_HOME/bin/catalina.sh"); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), LISTENING_AT_ADDRESS_8000); }
Source:
public abstract BufferedSink valueSink() throws IOException; public final JsonWriter jsonValue(@Nullable Object value) throws IOException { if (value instanceof Map<?, ?>) { beginObject(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { Object key = entry.getKey(); if (!(key instanceof String)) { throw new IllegalArgumentException( "Map keys must be of type String: " + key.getClass().getName()); } name(((String) key)); jsonValue(entry.getValue()); } endObject(); } else if (value instanceof List<?>) { beginArray(); for (Object element : ((List<?>) value)) { jsonValue(element); } endArray(); } else if (value instanceof String) { value(((String) value)); } else if (value instanceof Boolean) { value(((Boolean) value).booleanValue()); } else if (value instanceof Double) { value(((Double) value).doubleValue()); } else if (value instanceof Long) { value(((Long) value).longValue()); } else if (value instanceof Number) { value(((Number) value)); } else if (value == null) { nullValue(); } else { throw new IllegalArgumentException("Unsupported type: " + value.getClass().getName()); } return this; }

Target:
public abstract BufferedSink valueSink() throws IOException; public final JsonWriter jsonValue(@Nullable Object value) throws IOException { if (value instanceof Map<?, ?>) { beginObject(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { Object key = entry.getKey(); if (!(key instanceof String)) { throw new IllegalArgumentException(key == null ? "Map keys must be non-null" : "Map keys must be of type String: " + key.getClass().getName()); } name(((String) key)); jsonValue(entry.getValue()); } endObject(); } else if (value instanceof List<?>) { beginArray(); for (Object element : ((List<?>) value)) { jsonValue(element); } endArray(); } else if (value instanceof String) { value(((String) value)); } else if (value instanceof Boolean) { value(((Boolean) value).booleanValue()); } else if (value instanceof Double) { value(((Double) value).doubleValue()); } else if (value instanceof Long) { value(((Long) value).longValue()); } else if (value instanceof Number) { value(((Number) value)); } else if (value == null) { nullValue(); } else { throw new IllegalArgumentException("Unsupported type: " + value.getClass().getName()); } return this; }
Source:
void process(Content dataSource, IngestJobContext context, DataSourceIngestModuleProgress progressBar) { this.context = context; String modOutPath = Case.getCurrentCase().getModuleDirectory() + File.separator + PREFETCH_DIR_NAME; File dir = new File(modOutPath); if (dir.exists() == false) { dir.mkdirs(); } extractPrefetchFiles(dataSource); final String prefetchDumper = getPathForPrefetchDumper(); if (prefetchDumper == null) { logger.log(Level.SEVERE, "Error finding parse_prefetch program"); return; } if (context.dataSourceIngestIsCancelled()) { return; } String modOutFile = modOutPath + File.separator + PREFETCH_PARSER_DB_FILE; try { String tempDirPath = RAImageIngestModule.getRATempPath(Case.getCurrentCase(), PREFETCH_DIR_NAME ); parsePrefetchFiles(prefetchDumper, tempDirPath, modOutFile, modOutPath); createAppExecArtifacts(modOutFile); } catch (IOException ex) { logger.log(Level.WARNING, "Error runing parse_prefetch or creating artifacts.", ex); } }

Target:
void process(Content dataSource, IngestJobContext context, DataSourceIngestModuleProgress progressBar) { this.context = context; String modOutPath = Case.getCurrentCase().getModuleDirectory() + File.separator + PREFETCH_DIR_NAME; File dir = new File(modOutPath); if (dir.exists() == false) { boolean dirMade = dir.mkdirs(); if (!dirMade) { logger.log(Level.SEVERE, "Error creating directory to store prefetch output database"); return; } } extractPrefetchFiles(dataSource); final String prefetchDumper = getPathForPrefetchDumper(); if (prefetchDumper == null) { logger.log(Level.SEVERE, "Error finding parse_prefetch program"); return; } if (context.dataSourceIngestIsCancelled()) { return; } String modOutFile = modOutPath + File.separator + PREFETCH_PARSER_DB_FILE; try { String tempDirPath = RAImageIngestModule.getRATempPath(Case.getCurrentCase(), PREFETCH_DIR_NAME ); parsePrefetchFiles(prefetchDumper, tempDirPath, modOutFile, modOutPath); createAppExecArtifacts(modOutFile, dataSource); } catch (IOException ex) { logger.log(Level.WARNING, "Error runing parse_prefetch or creating artifacts.", ex); } }
Source:
public void parsesInvalidIdField() throws IOException { final MemberProfileJson memberprofilejson = Mockito.mock(MemberProfileJson.class); Mockito.when( memberprofilejson.fetch( Mockito.anyString(), Mockito.anyString(), Mockito.any(Href.class) ) ).thenReturn( Json.createReader( new FileInputStream( PsLinkedinTest.class.getResource( "linkedinTestUserInvalidId.json" ).getPath() ) ).readObject() ); try { new PsLinkedin(memberprofilejson) .enter(REQUEST); } catch (final ClassCastException ex) { MatcherAssert.assertThat( ex.getMessage(), Matchers.containsString("cannot be cast to") ); throw ex; } }

Target:
public void parsesInvalidIdField() throws IOException { try { new PsLinkedin( this.mockRequest( "linkedinTestUserInvalidId.json" ), "appTest", "keyTest" ).enter(REQUEST); } catch (final ClassCastException ex) { MatcherAssert.assertThat( ex.getMessage(), Matchers.containsString("cannot be cast to") ); throw ex; } }
Source:
public Matcher<View> atPositionOnView(final int position, final int targetViewId) { return new TypeSafeMatcher<View>() { Resources resources = null; View childView; public void describeTo(Description description) { String idDescription = Integer.toString(recyclerViewId); if (this.resources != null) { try { idDescription = this.resources.getResourceName(recyclerViewId); } catch (Resources.NotFoundException var4) { idDescription = String.format("%s (resource name not found)", recyclerViewId); } } description.appendText("with id: " + idDescription); } public boolean matchesSafely(View view) { this.resources = view.getResources(); if (childView == null) { RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId); if (recyclerView != null && recyclerView.getId() == recyclerViewId) { childView = recyclerView.findViewHolderForAdapterPosition(position).itemView; } else { return false; } } if (targetViewId == -1) { return view == childView; } else { View targetView = childView.findViewById(targetViewId); return view == targetView; } } }; }

Target:
public Matcher<View> atPositionOnView(final int position, final int targetViewId) { return new TypeSafeMatcher<View>() { Resources resources = null; View childView; public void describeTo(Description description) { String idDescription = Integer.toString(recyclerViewId); if (this.resources != null) { try { idDescription = this.resources.getResourceName(recyclerViewId); } catch (Resources.NotFoundException ignored) { idDescription = String.format("%s (resource name not found)", recyclerViewId); } } description.appendText("with id: " + idDescription); } public boolean matchesSafely(View view) { this.resources = view.getResources(); if (childView == null) { RecyclerView recyclerView = (RecyclerView) view.getRootView().findViewById(recyclerViewId); if (recyclerView != null && recyclerView.getId() == recyclerViewId) { childView = recyclerView.findViewHolderForAdapterPosition(position).itemView; } else { return false; } } if (targetViewId == -1) { return view == childView; } else { View targetView = childView.findViewById(targetViewId); return view == targetView; } } }; }
Source:
public I setContext(HttpRequest request) { this.request = GeneratedHttpRequest.class.cast(request); return (I) this; }

Target:
public I setContext(HttpRequest request) { checkArgument(request instanceof GeneratedHttpRequest, "ArgsToPagedIterable only supports a GeneratedHttpRequest"); this.request = GeneratedHttpRequest.class.cast(request); return (I) this; }
Source:
private <T extends Enum<T>> void registerStatistic(String statNameSuffix, StatisticType type, final OperationStatisticDescriptor<T> descriptor, final EnumSet<T> outcomes) { if (contextObject == null) { return; } Set<TreeNode> result = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf( hasAttribute("type", descriptor.getType()), hasAttribute("name", descriptor.getObserverName()), hasAttribute("tags", new Matcher<Set<String>>() { @Override protected boolean matchesSafely(Set<String> object) { return object.containsAll(descriptor.getTags()); } }))))) .filter(context(identifier(subclassOf(OperationStatistic.class)))) .build().execute(Collections.singleton(ContextManager.nodeFor(contextObject))); if (!result.isEmpty()) { for (TreeNode node : result) { String discriminator = null; Map<String, Object> properties = (Map<String, Object>) node.getContext().attributes().get("properties"); if (properties != null && properties.containsKey("discriminator")) { discriminator = properties.get("discriminator").toString(); } String fullStatName = (discriminator == null ? "" : (discriminator + ":")) + statNameSuffix; final OperationStatistic<T> statistic = (OperationStatistic<T>) node.getContext().attributes().get("this"); registerStatistic(fullStatName, type, new ValueStatistic<Number>() { @Override public Number value() { return statistic.sum(outcomes); } }); } } }

Target:
private <T extends Enum<T>> void registerStatistic(String statNameSuffix, StatisticType type, final OperationStatisticDescriptor<T> descriptor, final EnumSet<T> outcomes) { if (contextObject == null) { return; } Set<TreeNode> result = queryBuilder() .descendants() .filter(context(attributes(Matchers.<Map<String, Object>>allOf( hasAttribute("type", descriptor.getType()), hasAttribute("name", descriptor.getObserverName()), hasTags(descriptor.getTags()))))) .filter(context(identifier(subclassOf(OperationStatistic.class)))) .build().execute(Collections.singleton(ContextManager.nodeFor(contextObject))); if (!result.isEmpty()) { for (TreeNode node : result) { String discriminator = null; Map<String, Object> properties = (Map<String, Object>) node.getContext().attributes().get("properties"); if (properties != null && properties.containsKey("discriminator")) { discriminator = properties.get("discriminator").toString(); } String fullStatName = (discriminator == null ? "" : (discriminator + ":")) + statNameSuffix; final OperationStatistic<T> statistic = (OperationStatistic<T>) node.getContext().attributes().get("this"); registerStatistic(fullStatName, type, new ValueStatistic<Number>() { @Override public Number value() { return statistic.sum(outcomes); } }); } } }
Source:
private void setPublicURIs(final FileSystem fileSystem) { final String[] uris = fileSystem.toString().split("\\r?\\n"); final List<PublicURI> publicURIs = new ArrayList<>(uris.length); for (final String s : uris) { final int protocolStart = s.indexOf("://"); publicURIs.add(getPublicURI(s, protocolStart)); } repo.setPublicURIs(publicURIs); }

Target:
private void setPublicURIs(final FileSystem fileSystem) { final String[] uris = fileSystem.toString().split("\\r?\\n"); final List<PublicURI> publicURIs = new ArrayList<>(uris.length); for (final String s : uris) { final int protocolStart = s.indexOf(PROTOCOL_SEPARATOR); publicURIs.add(getPublicURI(s, protocolStart)); } repo.setPublicURIs(publicURIs); }
Source:
private void handleRelatedAlarms(OnmsAlarm situation) { if (!situation.isSituation()) { return; } alarmAssociationById.putIfAbsent(situation.getId(), new HashMap<>()); final Map<Integer, AlarmAssociationAndFact> associationFacts = alarmAssociationById.get(situation.getId()); for (AlarmAssociation association : situation.getAssociatedAlarms()) { Integer alarmId = association.getRelatedAlarm().getId(); AlarmAssociationAndFact assocationFact = associationFacts.get(alarmId); if (assocationFact == null) { LOG.debug("Inserting alarm association into session: {}", association); final FactHandle fact = getKieSession().insert(association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } else { FactHandle fact = assocationFact.getFact(); LOG.trace("Updating alarm assocation in session: {}", assocationFact); getKieSession().update(fact, association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } } Set<Integer> deletedAlarmIds = associationFacts.values().stream() .map(fact -> fact.getAlarmAssociation().getRelatedAlarm().getId()) .filter(alarmId -> !situation.getRelatedAlarmIds().contains(alarmId)) .collect(Collectors.toSet()); deletedAlarmIds.stream().forEach(alarmId -> { final AlarmAssociationAndFact associationAndFact = associationFacts.remove(alarmId); if (associationAndFact != null) { LOG.debug("Deleting AlarmAssociationAndFact from session: {}", associationAndFact.getAlarmAssociation()); getKieSession().delete(associationAndFact.getFact()); } }); }

Target:
private void handleRelatedAlarms(OnmsAlarm situation) { if (!situation.isSituation()) { return; } alarmAssociationById.putIfAbsent(situation.getId(), new HashMap<>()); final Map<Integer, AlarmAssociationAndFact> associationFacts = alarmAssociationById.get(situation.getId()); for (AlarmAssociation association : situation.getAssociatedAlarms()) { Integer alarmId = association.getRelatedAlarm().getId(); AlarmAssociationAndFact assocationFact = associationFacts.get(alarmId); if (assocationFact == null) { LOG.debug("Inserting alarm association into session: {}", association); final FactHandle fact = getKieSession().insert(association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } else { FactHandle fact = assocationFact.getFact(); LOG.trace("Updating alarm assocation in session: {}", assocationFact); getKieSession().update(fact, association); associationFacts.put(alarmId, new AlarmAssociationAndFact(association, fact)); } } Set<Integer> deletedAlarmIds = associationFacts.values().stream() .map(fact -> fact.getAlarmAssociation().getRelatedAlarm().getId()) .filter(alarmId -> !situation.getRelatedAlarmIds().contains(alarmId)) .collect(Collectors.toSet()); deletedAlarmIds.forEach(alarmId -> { final AlarmAssociationAndFact associationAndFact = associationFacts.remove(alarmId); if (associationAndFact != null) { LOG.debug("Deleting AlarmAssociationAndFact from session: {}", associationAndFact.getAlarmAssociation()); getKieSession().delete(associationAndFact.getFact()); } }); }
Source:
public Obs saveObs(Obs obs, String changeMessage) throws APIException { if(obs == null){ throw new APIException("Obs.error.cannot.be.null", (Object[]) null); } if(obs.getId() != null && changeMessage == null){ throw new APIException("Obs.error.ChangeMessage.required", (Object[]) null); } handleExistingObsWithComplexConcept(obs); ensureRequirePrivilege(obs); if (obs.getObsId() == null || obs.getVoided()) { return saveNewOrVoidedObs(obs,changeMessage); } else if(!obs.isDirty()){ setPersonFromEncounter(obs); return saveObsNotDirty(obs, changeMessage); } else { Errors errors = new BindException(obs, "obs"); new ObsValidator().validate(obs, errors); if (!errors.hasFieldErrors("person")){ setPersonFromEncounter(obs); return saveExistingObs(obs,changeMessage); } else{ throw new APIException("Obs.error.PersonId.mismatch", (Object[]) null); } } }

Target:
public Obs saveObs(Obs obs, String changeMessage) throws APIException { if(obs == null){ throw new APIException("Obs.error.cannot.be.null", (Object[]) null); } if(obs.getId() != null && changeMessage == null){ throw new APIException("Obs.error.ChangeMessage.required", (Object[]) null); } handleExistingObsWithComplexConcept(obs); ensureRequirePrivilege(obs); if (obs.getObsId() == null || obs.getVoided()) { return saveNewOrVoidedObs(obs,changeMessage); } else if(!obs.isDirty()){ setPersonFromEncounter(obs); return saveObsNotDirty(obs, changeMessage); } else { setPersonFromEncounter(obs); return saveExistingObs(obs,changeMessage); } }
Source:
protected void onExportChanged() { boolean externalNetwork = (Boolean) getExport().getEntity(); getQos().setIsChangable(!externalNetwork); getAddQosCommand().setIsExecutionAllowed(!externalNetwork); String label = getNetworkLabel().getSelectedItem(); if (externalNetwork) { getNetworkLabel().setItems(new HashSet<String>()); } else { getNetworkLabel().setItems(dcLabels); } getNetworkLabel().setSelectedItem(label); }

Target:
protected void onExportChanged() { boolean externalNetwork = (Boolean) getExport().getEntity(); getQos().setIsChangable(!externalNetwork); getAddQosCommand().setIsExecutionAllowed(!externalNetwork); String label = getNetworkLabel().getSelectedItem(); getNetworkLabel().setItems(externalNetwork ? new HashSet<String>() : dcLabels); getNetworkLabel().setSelectedItem(label); }
Source:
protected void executeCommand() { setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("SSH powerdown will not be executed on host {0}({1}) since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } if (getVds().getStatus() != VDSStatus.Maintenance) { setCommandShouldBeLogged(false); log.infoFormat("SSH powerdown will not be executed on host {0}({1}) since it is not in Maintenance.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } boolean result = executeSshPowerdown(getVds().getVdsGroupCompatibilityVersion().toString()); if (result) { getVds().setStatus(VDSStatus.Down); if (!getParameters().getKeepPolicyPMEnabled()) { getVds().setPowerManagementControlledByPolicy(false); } getDbFacade().getVdsDynamicDao().update(getVds().getDynamicData()); } else if (getParameters().getFallbackToPowerManagement() && getVds().getpm_enabled()) { FenceVdsActionParameters parameters = new FenceVdsActionParameters(getVds().getId(), FenceActionType.Stop); parameters.setKeepPolicyPMEnabled(getParameters().getKeepPolicyPMEnabled()); Backend.getInstance().runInternalAction(VdcActionType.StopVds, parameters, ExecutionHandler.createInternalJobContext()); } getReturnValue().setSucceeded(result); }

Target:
protected void executeCommand() { setVds(null); if (getVds() == null) { handleError("SSH power down will not be executed on host {0} ({1}) since it doesn't exist anymore."); return; } if (getVds().getStatus() != VDSStatus.Maintenance) { handleError("SSH power down will not be executed on host {0} ({1}) since it is not in Maintenance."); return; } boolean result = executeSshPowerdown(getVds().getVdsGroupCompatibilityVersion().toString()); if (result) { getVds().setStatus(VDSStatus.Down); if (!getParameters().getKeepPolicyPMEnabled()) { getVds().setPowerManagementControlledByPolicy(false); } getDbFacade().getVdsDynamicDao().update(getVds().getDynamicData()); } else if (getParameters().getFallbackToPowerManagement() && getVds().getpm_enabled()) { FenceVdsActionParameters parameters = new FenceVdsActionParameters(getVds().getId(), FenceActionType.Stop); parameters.setKeepPolicyPMEnabled(getParameters().getKeepPolicyPMEnabled()); Backend.getInstance().runInternalAction(VdcActionType.StopVds, parameters, ExecutionHandler.createInternalJobContext()); } getReturnValue().setSucceeded(result); }
Source:
public Optional<Symbol> resolveMember(String memberName) { if (types.stream().anyMatch(type -> type instanceof RuntimeType && ((RuntimeType) type).hasUnresolvedHierarchy())) { return Optional.empty(); } Set<Optional<Symbol>> resolved = types.stream() .map(t -> t.resolveMember(memberName)) .filter(Optional::isPresent) .collect(Collectors.toSet()); if (resolved.isEmpty()) { return Optional.empty(); } else if (resolved.size() == 1) { return resolved.iterator().next(); } return Optional.of(AmbiguousSymbolImpl.create(resolved.stream().map(s -> s.orElse(null)).filter(Objects::nonNull).collect(Collectors.toSet()))); }

Target:
public Optional<Symbol> resolveMember(String memberName) { if (types.stream().anyMatch(type -> type instanceof RuntimeType && ((RuntimeType) type).hasUnresolvedHierarchy())) { return Optional.empty(); } Set<Optional<Symbol>> resolved = types.stream() .map(t -> t.resolveMember(memberName)) .filter(Optional::isPresent) .collect(Collectors.toSet()); return resolved.size() == 1 ? resolved.iterator().next() : Optional.empty(); }