auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Object handleAll(InvocationContext ctx, VisitableCommand command) throws Throwable { boolean suppressExceptions = false; ComponentStatus status = componentRegistry.getStatus(); if (status.isTerminated()) { throw new IllegalStateException(String.format( "%s is in 'TERMINATED' state and so it does not accept new invocations. " + "Either restart it or recreate the cache container.", getCacheNamePrefix())); } else if (stoppingAndNotAllowed(status, ctx)) { throw new IllegalStateException(String.format( "%s is in 'STOPPING' state and this is an invocation not belonging to an on-going transaction, so it does not accept new invocations. " + "Either restart it or recreate the cache container.", getCacheNamePrefix())); } NDC.push(componentRegistry.getCacheName()); try { if (trace) log.tracef("Invoked with command %s and InvocationContext [%s]", command, ctx); if (ctx == null) throw new IllegalStateException("Null context not allowed!!"); if (ctx.hasFlag(Flag.FAIL_SILENTLY)) { suppressExceptions = true; } try { return invokeNextInterceptor(ctx, command); } catch (Throwable th) { if (suppressExceptions) { log.trace("Exception while executing code, failing silently...", th); return null; } else { log.executionError(th); if (ctx.isInTxScope() && ctx.isOriginLocal()) { if (trace) log.trace("Transaction marked for rollback as exception was received."); markTxForRollbackAndRethrow(ctx, th); throw new IllegalStateException("This should not be reached"); } throw th; } } finally { ctx.reset(); } } finally { NDC.pop(); } }

Target:
private Object handleAll(InvocationContext ctx, VisitableCommand command) throws Throwable { boolean suppressExceptions = false; ComponentStatus status = componentRegistry.getStatus(); if (status.isTerminated()) { throw new IllegalStateException(String.format( "%s is in 'TERMINATED' state and so it does not accept new invocations. " + "Either restart it or recreate the cache container.", getCacheNamePrefix())); } else if (stoppingAndNotAllowed(status, ctx)) { throw new IllegalStateException(String.format( "%s is in 'STOPPING' state and this is an invocation not belonging to an on-going transaction, so it does not accept new invocations. " + "Either restart it or recreate the cache container.", getCacheNamePrefix())); } LogFactory.pushNDC(componentRegistry.getCacheName(), trace); try { if (trace) log.tracef("Invoked with command %s and InvocationContext [%s]", command, ctx); if (ctx == null) throw new IllegalStateException("Null context not allowed!!"); if (ctx.hasFlag(Flag.FAIL_SILENTLY)) { suppressExceptions = true; } try { return invokeNextInterceptor(ctx, command); } catch (Throwable th) { if (suppressExceptions) { log.trace("Exception while executing code, failing silently...", th); return null; } else { log.executionError(th); if (ctx.isInTxScope() && ctx.isOriginLocal()) { if (trace) log.trace("Transaction marked for rollback as exception was received."); markTxForRollbackAndRethrow(ctx, th); throw new IllegalStateException("This should not be reached"); } throw th; } } finally { ctx.reset(); } } finally { LogFactory.popNDC(trace); } }
Source:
public int update(final String updateClause, final Object... params) throws SQLException { int retry = 0; SQLException exception; String errorMsg = "Update failed: Reached maximum number of retries: " + AzDBUtil.MAX_RETRIES_ON_DEADLOCK; do { try { return this.queryRunner.update(updateClause, params); } catch (final SQLException ex) { exception = ex; if (ex.getErrorCode() == 1213) { retry++; logger.warn("Deadlock detected when trying to execute: " + updateClause + " with values: " + Arrays.toString(params)); try { Thread.sleep(AzDBUtil.RETRY_WAIT_TIME); } catch (InterruptedException e) { logger.info("Sleep interrupted"); } } else { errorMsg = "update failed"; break; } } } while (retry < AzDBUtil.MAX_RETRIES_ON_DEADLOCK); logger.error(errorMsg, exception); if (this.dbMetrics != null) { this.dbMetrics.markDBFailUpdate(); } throw exception; }

Target:
public int update(final String updateClause, final Object... params) throws SQLException { int retryCount = 0; SQLException exception; String errorMsg = "Update failed: Reached maximum number of retries: " + AzDBUtil.MAX_RETRIES_ON_DEADLOCK; do { try { return this.queryRunner.update(updateClause, params); } catch (final SQLException ex) { exception = ex; if (queryRunner.getDataSource() instanceof MySQLDataSource && ex.getErrorCode() == MySQLDataSource.MYSQL_ER_LOCK_DEADLOCK) { retryCount++; logger.warn("Deadlock detected when trying to execute: " + updateClause + " with values: " + Arrays.toString(params)); try { Thread.sleep(AzDBUtil.RETRY_WAIT_TIME); } catch (InterruptedException e) { logger.info("Sleep during DB operation retry interrupted."); } } else { errorMsg = "update failed"; break; } } } while (retryCount < AzDBUtil.MAX_RETRIES_ON_DEADLOCK); logger.error(errorMsg, exception); if (this.dbMetrics != null) { this.dbMetrics.markDBFailUpdate(); } throw exception; }
Source:
public void testListNumeric() { builder.beginDocument(); builder.beginBlock(BlockType.NUMERIC_LIST, new Attributes()); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("One"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Two"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Three"); builder.endBlock(); builder.endBlock(); builder.endDocument(); assertMarkup("1. One\n1. Two\n1. Three\n\n"); }

Target:
public void testListNumeric() { builder.beginDocument(); builder.beginBlock(BlockType.NUMERIC_LIST, new Attributes()); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("One"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Two"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Three"); builder.endBlock(); builder.endBlock(); builder.endDocument(); assertMarkup("1. One\n2. Two\n3. Three\n\n"); }
Source:
public List<Issue> getRelatedIssues(final PullRequest pullRequest) throws MalformedURLException, NotFoundException { Objects.requireNonNull(pullRequest, "url cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final String[] urls = extractURLs(body, RELATED_ISSUES, true); if (urls == null || urls.length == 0 || urls[0] == null) { return null; } else { List<Issue> issues = new ArrayList<>(urls.length); for (String url : urls) { issues.add(getIssue(new URL(url))); } return issues; } }

Target:
public List<Issue> getRelatedIssues(final PullRequest pullRequest) throws MalformedURLException, NotFoundException { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final String[] urls = extractURLs(body, RELATED_ISSUES, true); if (urls == null || urls.length == 0 || urls[0] == null) { return null; } else { List<Issue> issues = new ArrayList<>(urls.length); for (String url : urls) { issues.add(getIssue(new URL(url))); } return issues; } }
Source:
protected Message(Message original) { this.decryptionInfo = original.decryptionInfo; this.relatedUserAnonymizedId = original.relatedUserAnonymizedId; this.threadHeadMessage = null; this.messagesInThread = new ArrayList<>(); this.repliedMessage = null; this.replies = new ArrayList<>(); this.messageDestination = null; this.creationTime = original.creationTime; this.isSentItem = original.isSentItem; this.isRead = original.isRead; }

Target:
protected Message(Message original) { this.decryptionInfo = null; this.relatedUserAnonymizedId = original.relatedUserAnonymizedId; this.threadHeadMessage = null; this.messagesInThread = new ArrayList<>(); this.repliedMessage = null; this.replies = new ArrayList<>(); this.messageDestination = null; this.creationTime = original.creationTime; this.isSentItem = original.isSentItem; this.isRead = original.isRead; }
Source:
public void createReviewClientWithConfiguration() { Project project = new Project(new NameKey("name")); TaskRepository repository = new TaskRepository(GerritConnector.CONNECTOR_KIND, "http://repository"); GerritConfiguration configuration = new GerritConfiguration(new GerritConfigX(), Collections.singletonList(project), null); connector.saveConfiguration(repository, configuration); GerritClient client = connector.createReviewClient(repository, true); assertNotNull(client.getConfiguration().getProjects()); assertNotNull(client.getGerritConfig()); }

Target:
public void createReviewClientWithConfiguration() { Project project = new Project(new NameKey("name")); TaskRepository repository = new TaskRepository(GerritConnector.CONNECTOR_KIND, "http://repository"); GerritConfiguration configuration = new GerritConfiguration(new GerritConfigX(), Collections.singletonList(project), null); connector.saveConfiguration(repository, configuration); GerritClient client = connector.createReviewClient(repository, true); List<Project> projects = client.getConfiguration().getProjects(); assertNotNull(projects); assertEquals(1, projects.size()); assertEquals(project.getNameKey(), projects.get(0).getNameKey()); assertNotNull(client.getGerritConfig()); }
Source:
private static void clearTomcatCache() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class cl = loader.getClass(); if ("org.apache.catalina.loader.WebappClassLoader".equals(cl.getName())) { ArrayList<Field> fields = new ArrayList<Field>(Arrays.asList(cl.getDeclaredFields())); boolean found = false; for (Field field : fields) { if ("resourceEntries".equals(field.getName())) { found = true; } } if (found) { clearMap(cl, loader, "resourceEntries"); } else { Object obj = loader.getClass().getSuperclass().cast(loader); clearMap(cl.getSuperclass(), obj, "resourceEntries"); } } else { LOGGER.debug("class loader " + cl.getName() + " is not tomcat loader."); } }

Target:
private static void clearTomcatCache() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class cl = loader.getClass(); if ("org.apache.catalina.loader.WebappClassLoader".equals(cl.getName())) { clearMap(cl, loader, "resourceEntries"); } else { LOGGER.debug("class loader " + cl.getName() + " is not tomcat loader."); } }
Source:
public ActivateMavenProfileJob(Action action, IProject project) { super(NLS.bind("{0} maven profile \"openshift\" for project {1}", action == Action.ACTIVATE? "Activating" : "Deactivating", project.getName())); this.action = action; this.project = project; setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())); }

Target:
public ActivateMavenProfileJob(Action action, IProject project) { super(NLS.bind("{0} maven profile \"openshift\" for project {1}", action == Action.ACTIVATE? "Activating" : "Deactivating", project.getName())); this.action = action; this.project = project; setRule(ResourcesPlugin.getWorkspace().getRoot()); }
Source:
private void generateImages(GenerationMode mode, String messageKey) { Folder generatorSource = myProcess.getProject().getGeneratorSource(); List<Folder> contentFolders = currentTask.getContentFolders(); if (Objects.isNull(generatorSource)) { Helper.setErrorMessage("noSourceFolderConfiguredInProject"); } if(Objects.isNull(contentFolders)){ Helper.setErrorMessage("noImageFolderConfiguredInProject"); } Integer numberOfFiles = 0; try { String uri = ServiceManager.getFileService().getProcessBaseUriForExistingProcess(myProcess).toString() + myProcess.getProject().getGeneratorSource(); numberOfFiles = ServiceManager.getFileService().getNumberOfFiles(new URI(uri)); if (numberOfFiles > 0) { Subfolder sourceFolder = new Subfolder(myProcess, generatorSource); List<Subfolder> outputs = SubfolderFactoryService.createAll(myProcess, contentFolders); ImageGenerator imageGenerator = new ImageGenerator(sourceFolder, mode, outputs); TaskManager.addTask(new TaskImageGeneratorThread(myProcess.getTitle(), imageGenerator)); Helper.setMessage(messageKey); } else { Helper.setErrorMessage("emptySourceFolder"); } } catch (RuntimeException | URISyntaxException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } }

Target:
private void generateImages(GenerationMode mode, String messageKey) { Folder generatorSource = myProcess.getProject().getGeneratorSource(); List<Folder> contentFolders = currentTask.getContentFolders(); if (Objects.isNull(generatorSource)) { Helper.setErrorMessage("noSourceFolderConfiguredInProject"); return; } if(Objects.isNull(contentFolders)){ Helper.setErrorMessage("noImageFolderConfiguredInProject"); return; } Integer numberOfFiles = 0; try { String uri = ServiceManager.getFileService().getProcessBaseUriForExistingProcess(myProcess).toString() + myProcess.getProject().getGeneratorSource(); numberOfFiles = ServiceManager.getFileService().getNumberOfFiles(new URI(uri)); if (numberOfFiles > 0) { Subfolder sourceFolder = new Subfolder(myProcess, generatorSource); List<Subfolder> outputs = SubfolderFactoryService.createAll(myProcess, contentFolders); ImageGenerator imageGenerator = new ImageGenerator(sourceFolder, mode, outputs); TaskManager.addTask(new TaskImageGeneratorThread(myProcess.getTitle(), imageGenerator)); Helper.setMessage(messageKey); } else { Helper.setErrorMessage("emptySourceFolder"); } } catch (RuntimeException | URISyntaxException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } }
Source:
protected void updateExpiryPolicyOfRecord(CacheRecord record, Object expiryPolicy) { Object inMemoryExpiryPolicy; switch (cacheConfig.getInMemoryFormat()) { case OBJECT: if (expiryPolicy instanceof Data) { inMemoryExpiryPolicy = dataToValue((Data) expiryPolicy); } else { inMemoryExpiryPolicy = expiryPolicy; } break; case BINARY: case NATIVE: inMemoryExpiryPolicy = toData(expiryPolicy); break; default: throw new IllegalArgumentException("Invalid storage format: " + cacheConfig.getInMemoryFormat()); } record.setExpiryPolicy(inMemoryExpiryPolicy); }

Target:
protected void updateExpiryPolicyOfRecord(CacheRecord record, Object expiryPolicy) { Object inMemoryExpiryPolicy; switch (cacheConfig.getInMemoryFormat()) { case OBJECT: inMemoryExpiryPolicy = toValue(expiryPolicy); break; case BINARY: case NATIVE: inMemoryExpiryPolicy = toData(expiryPolicy); break; default: throw new IllegalArgumentException("Invalid storage format: " + cacheConfig.getInMemoryFormat()); } record.setExpiryPolicy(inMemoryExpiryPolicy); }
Source:
private void stateTransition(State newState, UnaryOperator<CircuitBreakerState> newStateGenerator) { CircuitBreakerState previousState = stateReference.getAndUpdate(currentState -> { StateTransition.transitionBetween(getName(), currentState.getState(), newState); if (currentState instanceof OpenState) { ((OpenState) currentState).cancelAutomaticTransitionToHalfOpen(); } return newStateGenerator.apply(currentState); }); publishStateTransitionEvent( StateTransition.transitionBetween(getName(), previousState.getState(), newState)); }

Target:
private void stateTransition(State newState, UnaryOperator<CircuitBreakerState> newStateGenerator) { CircuitBreakerState previousState = stateReference.getAndUpdate(currentState -> { StateTransition.transitionBetween(getName(), currentState.getState(), newState); currentState.preTransitionHook(); return newStateGenerator.apply(currentState); }); publishStateTransitionEvent( StateTransition.transitionBetween(getName(), previousState.getState(), newState)); }
Source:
public Server choose(Object key) { if (loadBalancerStats == null) { return super.choose(key); } List<Server> serverList = getLoadBalancer().getAllServers(); int minimalConcurrentConnections = Integer.MAX_VALUE; long currentTime = System.currentTimeMillis(); Server chosen = null; for (Server server: serverList) { ServerStats serverStats = loadBalancerStats.getSingleServerStat(server); if (!serverStats.isCircuitBreakerTripped(currentTime) && server.isAlive() && server.isReadyToServe()) { int concurrentConnections = serverStats.getActiveRequestsCount(currentTime); if (concurrentConnections < minimalConcurrentConnections) { minimalConcurrentConnections = concurrentConnections; chosen = server; } } } if (chosen == null) { return super.choose(key); } else { return chosen; } }

Target:
public Server choose(Object key) { if (loadBalancerStats == null) { return super.choose(key); } List<Server> serverList = getLoadBalancer().getReachableServers(); int minimalConcurrentConnections = Integer.MAX_VALUE; long currentTime = System.currentTimeMillis(); Server chosen = null; for (Server server: serverList) { ServerStats serverStats = loadBalancerStats.getSingleServerStat(server); if (!serverStats.isCircuitBreakerTripped(currentTime) && server.isReadyToServe()) { int concurrentConnections = serverStats.getActiveRequestsCount(currentTime); if (concurrentConnections < minimalConcurrentConnections) { minimalConcurrentConnections = concurrentConnections; chosen = server; } } } if (chosen == null) { return super.choose(key); } else { return chosen; } }
Source:
public boolean select(Viewer viewer, Object parentElement, Object element) { ChangeMessageInfoImpl row = (ChangeMessageInfoImpl) element; if (row != null && row.getAuthor() != null) { if (fIsMachine) { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return true; } return false; } else { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return false; } return true; } } else if (fIsMachine) { return false; } else { return true; } }

Target:
public boolean select(Viewer viewer, Object parentElement, Object element) { ChangeMessageInfoImpl row = (ChangeMessageInfoImpl) element; if (row != null && row.getAuthor() != null) { if (fIsMachine) { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return true; } return false; } else { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return false; } return true; } } else { return true; } }
Source:
public void testImmediatePruning() throws Exception { BranchBuilder bb = tr.branch("refs/heads/master"); bb.commit().message("M").add("M", "M").create(); String tempRef = "refs/heads/soon-to-be-unreferenced"; BranchBuilder bb2 = tr.branch(tempRef); bb2.commit().message("M").add("M", "M").create(); gc.setExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); fsTick(); RefUpdate update = tr.getRepository().getRefDatabase().newUpdate(tempRef, false); update.setForceUpdate(true); update.delete(); bb.commit().message("B").add("B", "Q").create(); FileBasedConfig config = repo.getConfig(); config.setString(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_PRUNEEXPIRE, "now"); config.save(); gc.setPackExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); assertEquals(0, stats.numberOfLooseObjects); assertEquals(6, stats.numberOfPackedObjects); assertEquals(1, stats.numberOfPackFiles); assertEquals(0, stats.numberOfLooseObjects); }

Target:
public void testImmediatePruning() throws Exception { BranchBuilder bb = tr.branch("refs/heads/master"); bb.commit().message("M").add("M", "M").create(); String tempRef = "refs/heads/soon-to-be-unreferenced"; BranchBuilder bb2 = tr.branch(tempRef); bb2.commit().message("M").add("M", "M").create(); gc.setExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); fsTick(); RefUpdate update = tr.getRepository().getRefDatabase().newUpdate(tempRef, false); update.setForceUpdate(true); update.delete(); bb.commit().message("B").add("B", "Q").create(); FileBasedConfig config = repo.getConfig(); config.setString(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_PRUNEEXPIRE, "now"); config.save(); gc.setPackExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); assertEquals(0, stats.numberOfLooseObjects); assertEquals(6, stats.numberOfPackedObjects); assertEquals(1, stats.numberOfPackFiles); }
Source:
public void testDoesNotRegisterTwiceOnRegister() { monitor.register(); monitor.register(); assertThat(harness.getNetworkCall()).contains(monitor.callback); }

Target:
public void testDoesNotRegisterTwiceOnRegister() { monitor.register(); monitor.register(); assertThat(harness.getNetworkCall()).containsExactly(monitor.callback); }
Source:
public static Task<OsDetails> getOsDetails(final Entity entity) { Optional<SshMachineLocation> location = Locations.findUniqueSshMachineLocation(entity.getLocations()); if (!location.isPresent()) { throw new IllegalStateException("Entity "+entity+" has no SSH location to gather OS details. Locations: "+entity.getLocations()); } final SshMachineLocation sshLocation = location.get(); return Tasks.<OsDetails>builder() .name("Get OsDetails for " + entity) .body(new Callable<OsDetails>() { @Override public OsDetails call() throws Exception { String architecture = DynamicTasks.queue(SshEffectorTasks.ssh("uname -m") .machine(sshLocation) .requiringZeroAndReturningStdout()).get().trim(); BufferedReader reader = new BufferedReader(Streams.reader( new ResourceUtils(this).getResourceFromUrl("classpath://brooklyn/entity/software/os-and-version.sh"))); List<String> script = Lists.newArrayList(); for (String line; (line = reader.readLine()) != null; ) { script.add(line); } String[] nameAndVersion = DynamicTasks.queue(SshEffectorTasks.ssh(script.toArray(new String[script.size()])) .machine(sshLocation) .requiringZeroAndReturningStdout()) .get() .split("\\r?\\n"); String name = nameAndVersion.length > 0 ? nameAndVersion[0] : "unknown"; String version = nameAndVersion.length > 1 ? nameAndVersion[1] : "unknown"; OsDetails details = new BasicOsDetails(name, architecture, version); if (LOG.isDebugEnabled()) LOG.debug("OsDetails for {}: {}", entity, details); return details; } }) .build(); }

Target:
public static Task<OsDetails> getOsDetails(final Entity entity) { Optional<SshMachineLocation> location = Locations.findUniqueSshMachineLocation(entity.getLocations()); if (!location.isPresent()) { throw new IllegalStateException("Entity "+entity+" has no SSH location to gather OS details. Locations: "+entity.getLocations()); } return getOsDetails(location.get()); }
Source:
public int createDownloadNotification(Context context, String programName) { if (context == null || programName == null) { return -1; } initNotificationManager(context); Intent downloadIntent = new Intent(context, MainMenuActivity.class); downloadIntent.setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(EXTRA_PROJECT_NAME, programName); PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, downloadIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationData data = new NotificationData(pendingIntent, R.drawable.ic_stat, programName, context.getString(R.string.notification_download_title_pending), context.getString(R.string.notification_title_open), context.getString(R.string.notification_download_pending), context.getString(R.string.notification_download_finished), 0, 100, false, false); return createNotification(context, data); }

Target:
public int createDownloadNotification(Context context, String programName) { if (context == null || programName == null) { return -1; } initNotificationManager(context); Intent downloadIntent = new Intent(context, MainMenuActivity.class); downloadIntent.setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(EXTRA_PROJECT_NAME, programName); PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, downloadIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationData data = new NotificationData(pendingIntent, R.drawable.ic_stat, programName, context.getString(R.string.notification_download_title_pending), context.getString(R.string.notification_title_open), context.getString(R.string.notification_download_pending), context.getString(R.string.notification_download_finished), 0, MAX_PERCENT, false, false); return createNotification(context, data); }
Source:
public Application beforeApprove(PerunSession session, Application app) throws PerunException { User user = app.getUser(); Group group = app.getGroup(); AttributesManager am = session.getPerun().getAttributesManager(); Attribute attestation = am.getAttribute(session, group, A_G_D_groupAttestation); if (attestation == null) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation attribute set."); } String newValue = attestation.valueAsString(); if (newValue == null || newValue.isEmpty()) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation value set."); } return app; }

Target:
public Application beforeApprove(PerunSession session, Application app) throws PerunException { Group group = app.getGroup(); if (group == null) { throw new CantBeApprovedException("This module can be set only for registration to Group."); } AttributesManager am = session.getPerun().getAttributesManager(); Attribute attestation = am.getAttribute(session, group, A_G_D_groupAttestation); if (attestation == null) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation attribute set."); } String newValue = attestation.valueAsString(); if (newValue == null || newValue.isEmpty()) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation value set."); } return app; }
Source:
public ChannelHandlerContext firstContext() { synchronized (handlers) { if (handlers.isEmpty()) { return null; } return handlers.get(0); } }

Target:
public ChannelHandlerContext firstContext() { synchronized (handlers) { return handlers.isEmpty() ? null : handlers.get(0); } }
Source:
void setupIndentationLevel() { final int indentationLevel = presenter.getLevel(); final int pixelsPerLevel = 35; final int marginPixels = pixelsPerLevel * indentationLevel; this.level.style.marginLeft = margin(marginPixels); }

Target:
void setupIndentationLevel() { final int indentationLevel = presenter.getLevel(); final int marginPixels = PIXELS_PER_LEVEL * indentationLevel; this.level.style.marginLeft = margin(marginPixels); }
Source:
public void testParseString(String input, String scheme, String host, Integer port, String path, String param, String query, String fragment) throws Exception { HttpURI httpUri = HttpURI.from(input); try { new URI(input); assertThat("[" + input + "] expected path (test case) cannot be null", path, notNullValue()); assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(scheme)); assertThat("[" + input + "] .host", httpUri.getHost(), is(host)); assertThat("[" + input + "] .port", httpUri.getPort(), is(port == null ? -1 : port)); assertThat("[" + input + "] .path", httpUri.getPath(), is(path)); assertThat("[" + input + "] .param", httpUri.getParam(), is(param)); assertThat("[" + input + "] .query", httpUri.getQuery(), is(query)); if (input.indexOf('#') >= 0) input = input.substring(0, input.indexOf('#')); assertThat("[" + input + "] .toString", httpUri.toString(), is(input)); } catch (URISyntaxException e) { assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(nullValue())); assertThat("[" + input + "] .host", httpUri.getHost(), is(nullValue())); assertThat("[" + input + "] .port", httpUri.getPort(), is(-1)); assertThat("[" + input + "] .path", httpUri.getPath(), is(nullValue())); assertThat("[" + input + "] .param", httpUri.getParam(), is(nullValue())); assertThat("[" + input + "] .query", httpUri.getQuery(), is(nullValue())); } }

Target:
public void testParseString(String input, String scheme, String host, Integer port, String path, String param, String query, String fragment) throws Exception { HttpURI httpUri = HttpURI.from(input); try { new URI(input); assertThat("[" + input + "] expected path (test case) cannot be null", path, notNullValue()); assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(scheme)); assertThat("[" + input + "] .host", httpUri.getHost(), is(host)); assertThat("[" + input + "] .port", httpUri.getPort(), is(port == null ? -1 : port)); assertThat("[" + input + "] .path", httpUri.getPath(), is(path)); assertThat("[" + input + "] .param", httpUri.getParam(), is(param)); assertThat("[" + input + "] .query", httpUri.getQuery(), is(query)); assertThat("[" + input + "] .fragment", httpUri.getFragment(), is(fragment)); assertThat("[" + input + "] .toString", httpUri.toString(), is(input)); } catch (URISyntaxException e) { assertThat("[" + input + "] .scheme", httpUri.getScheme(), is(nullValue())); assertThat("[" + input + "] .host", httpUri.getHost(), is(nullValue())); assertThat("[" + input + "] .port", httpUri.getPort(), is(-1)); assertThat("[" + input + "] .path", httpUri.getPath(), is(nullValue())); assertThat("[" + input + "] .param", httpUri.getParam(), is(nullValue())); assertThat("[" + input + "] .query", httpUri.getQuery(), is(nullValue())); assertThat("[" + input + "] .fragment", httpUri.getFragment(), is(nullValue())); } }
Source:
public List<EmailWrapper> generateFeedbackSessionClosingEmails(FeedbackSessionAttributes session) { List<StudentAttributes> students = new ArrayList<>(); boolean isEmailNeeded = fsLogic.isFeedbackSessionForStudentsToAnswer(session); if (isEmailNeeded) { List<StudentAttributes> studentsForCourse = studentsLogic.getStudentsForCourse(session.getCourseId()); for (StudentAttributes student : studentsForCourse) { try { if (!fsLogic.isFeedbackSessionFullyCompletedByStudent(session.getFeedbackSessionName(), session.getCourseId(), student.email)) { students.add(student); } } catch (EntityDoesNotExistException e) { log.severe("Course " + session.getCourseId() + " does not exist or " + "session " + session.getFeedbackSessionName() + " does not exist"); break; } } } String template = EmailTemplates.USER_FEEDBACK_SESSION_CLOSING .replace("${status}", "is closing soon"); CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); List<InstructorAttributes> instructors = isEmailNeeded ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<InstructorAttributes>(); return generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_CLOSING.getSubject()); }

Target:
public List<EmailWrapper> generateFeedbackSessionClosingEmails(FeedbackSessionAttributes session) { List<StudentAttributes> students = new ArrayList<>(); boolean isEmailNeeded = fsLogic.isFeedbackSessionForStudentsToAnswer(session); if (isEmailNeeded) { List<StudentAttributes> studentsForCourse = studentsLogic.getStudentsForCourse(session.getCourseId()); for (StudentAttributes student : studentsForCourse) { try { if (!fsLogic.isFeedbackSessionFullyCompletedByStudent(session.getFeedbackSessionName(), session.getCourseId(), student.email)) { students.add(student); } } catch (EntityDoesNotExistException e) { log.severe("Course " + session.getCourseId() + " does not exist or " + "session " + session.getFeedbackSessionName() + " does not exist"); break; } } } String template = EmailTemplates.USER_FEEDBACK_SESSION_CLOSING .replace("${status}", FEEDBACK_STATUS_SESSION_CLOSING); CourseAttributes course = coursesLogic.getCourse(session.getCourseId()); List<InstructorAttributes> instructors = isEmailNeeded ? instructorsLogic.getInstructorsForCourse(session.getCourseId()) : new ArrayList<InstructorAttributes>(); return generateFeedbackSessionEmailBases(course, session, students, instructors, template, EmailType.FEEDBACK_CLOSING.getSubject()); }
Source:
public void addConverter(ConverterDescriptor desc) { List<String> sMts = desc.getSourceMimeTypes(); String dMt = desc.getDestinationMimeType(); List<ConvertOption> dco = dstMappings.computeIfAbsent(dMt, (key) -> new ArrayList<>()); for (String sMT : sMts) { List<ConvertOption> sco = srcMappings.computeIfAbsent(sMT, (key) -> new ArrayList<>()); sco.add(new ConvertOption(desc.getConverterName(), dMt)); dco.add(new ConvertOption(desc.getConverterName(), sMT)); } log.debug("Added converter to {}", desc::getSourceMimeTypes, desc::getDestinationMimeType); }

Target:
public void addConverter(ConverterDescriptor desc) { List<String> sMts = desc.getSourceMimeTypes(); String dMt = desc.getDestinationMimeType(); List<ConvertOption> dco = dstMappings.computeIfAbsent(dMt, key -> new ArrayList<>()); for (String sMT : sMts) { List<ConvertOption> sco = srcMappings.computeIfAbsent(sMT, key -> new ArrayList<>()); sco.add(new ConvertOption(desc.getConverterName(), dMt)); dco.add(new ConvertOption(desc.getConverterName(), sMT)); } log.debug("Added converter to {}", desc::getSourceMimeTypes, desc::getDestinationMimeType); }
Source:
public Map<Long, ILogData> read(Iterable<Long> addresses) { Map<Long, ILogData> addressesMap = new HashMap<>(); if (!runtime.getParameters().isCacheDisabled()) { try { Set<Long> addressesToLoadFetch = new HashSet(); for(Long address : addresses) { ILogData val = readCache.getIfPresent(address); if (val == null) { addressesToLoadFetch.add(address); } else { addressesMap.put(address, val); } } if (!addressesToLoadFetch.isEmpty()) { Map<Long, ILogData> fetchedAddresses = this.cacheFetch(addressesToLoadFetch); for (Map.Entry<Long, ILogData> entry : fetchedAddresses.entrySet()) { addressesMap.put(entry.getKey(), readCache.asMap().computeIfAbsent(entry.getKey(), (k) -> entry.getValue())); } } return addressesMap; } catch (UncheckedExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw new RuntimeException(cause); } } } else { addressesMap = this.cacheFetch(addresses); } for (ILogData logData : addressesMap.values()) { if (logData.isTrimmed()) { throw new TrimmedException(); } } return addressesMap; }

Target:
public Map<Long, ILogData> read(Iterable<Long> addresses) { if (!runtime.getParameters().isCacheDisabled()) { Map<Long, ILogData> result = new HashMap<>(); Set<Long> addressesToFetch = new HashSet<>(); for (Long address : addresses) { ILogData val = readCache.getIfPresent(address); if (val == null) { addressesToFetch.add(address); } else { result.put(address, val); } } if (!addressesToFetch.isEmpty()) { Map<Long, ILogData> fetchedAddresses = fetchAll(addressesToFetch); for (Map.Entry<Long, ILogData> entry : fetchedAddresses.entrySet()) { result.put(entry.getKey(), readCache.asMap() .computeIfAbsent(entry.getKey(), (k) -> entry.getValue())); } } return result; } else { return fetchAll(addresses); } }
Source:
public void process(CommandLine cl, @SuppressWarnings("rawtypes") Map stormConf) throws Exception { String appName = cl.getOptionValue("appname", "Storm-on-Yarn"); String queue = cl.getOptionValue("queue", "default"); String schedulerAddr = cl.getOptionValue("schedulerAddr"); String yarnRMaddr_str = cl.getOptionValue("rmAddr"); InetSocketAddress yarnRMaddr = null; if (yarnRMaddr_str != null) yarnRMaddr = NetUtils.createSocketAddr(yarnRMaddr_str); String storm_zip_location = cl.getOptionValue("stormZip"); Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB); if (amSize == null) { amSize = 4096; } StormOnYarn storm = null; try { LOG.debug("yarnRMaddr:"+yarnRMaddr); LOG.debug("appName:"+appName); storm = StormOnYarn.launchApplication(yarnRMaddr, schedulerAddr, appName, queue, amSize, stormConf, storm_zip_location); LOG.debug("Submitted application's ID:" + storm.getAppId()); String output = cl.getOptionValue("output"); PrintStream os = (output!=null? new PrintStream(output) : System.out); os.println(storm.getAppId()); if (output != null) os.close(); } finally { if (storm != null) { storm.stop(); } } }

Target:
public void process(CommandLine cl, @SuppressWarnings("rawtypes") Map stormConf) throws Exception { String appName = cl.getOptionValue("appname", "Storm-on-Yarn"); String queue = cl.getOptionValue("queue", "default"); String storm_zip_location = cl.getOptionValue("stormZip"); Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB); if (amSize == null) { amSize = 4096; } StormOnYarn storm = null; try { storm = StormOnYarn.launchApplication(appName, queue, amSize, stormConf, storm_zip_location); LOG.debug("Submitted application's ID:" + storm.getAppId()); String output = cl.getOptionValue("output"); if (output == null) System.out.println(storm.getAppId()); else { PrintStream os = new PrintStream(output); os.println(storm.getAppId()); os.flush(); os.close(); } } finally { if (storm != null) { storm.stop(); } } }
Source:
void closeSocket() { if (closeSocketAsync) { new Thread(new Runnable() { @Override public void run() { closeSock(); } }).start(); } else { closeSock(); } }

Target:
void closeSocket() { if (sock != null) { if (sockBeingClosed.compareAndSet(false, true)) { if (closeSocketAsync) { final Thread closingThread = new Thread(() -> closeSockSync(), "CloseSocketThread(sid:" + zk.getServerId()); closingThread.setDaemon(true); closingThread.start(); } else { closeSockSync(); } } } }
Source:
protected void onStart() throws PluginStartupException { try { addPath(Info.PATHS.PATH_DEVICES_FOLDER + System.getProperty("file.separator") + "marytts/lib/" + VOICE_JAR_FILE); System.setProperty("mary.base", Info.PATHS.PATH_DEVICES_FOLDER + System.getProperty("file.separator") + "marytts"); marytts = new LocalMaryInterface(); getInfo(); defaultVoice = Voice.getVoice("cmu-slt-hsmm"); } catch (MaryConfigurationException ex) { throw new PluginStartupException("Plugin can't start for " + ex.getMessage()); } catch (Exception ex) { LOG.log(Level.SEVERE, "Impossible to modify classpath for ''{0}''", Freedomotic.getStackTraceInfo(ex)); } }

Target:
protected void onStart() throws PluginStartupException { try { addPath(Info.PATHS.PATH_DEVICES_FOLDER + System.getProperty("file.separator") + "marytts" + System.getProperty("file.separator") + "lib" + System.getProperty("file.separator") + VOICE_JAR_FILE); System.setProperty("mary.base", Info.PATHS.PATH_DEVICES_FOLDER + System.getProperty("file.separator") + "marytts"); marytts = new LocalMaryInterface(); LOG.log(Level.INFO, "Available voices: ''{0}''", marytts.getAvailableVoices()); LOG.log(Level.INFO, "Available languages: ''{0}''", marytts.getAvailableLocales()); defaultVoice = Voice.getVoice("cmu-slt-hsmm"); } catch (MaryConfigurationException ex) { throw new PluginStartupException("Plugin can't start for a configuration problem.", ex); } catch (Exception ex) { LOG.log(Level.SEVERE, "Impossible to modify classpath to add voice file ''{0}''", VOICE_JAR_FILE); } }
Source:
protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; String path = mFile.getRemotePath(); if (mFile.isFolder()) { path = path.substring(0, path.length()-1); } OCShare share = getStorageManager().getShareByPath(path); if (share != null) { UnshareLinkRemoteOperation operation = new UnshareLinkRemoteOperation((int) share.getIdRemoteShared()); result = operation.execute(client); if (result.isSuccess()) { Log_OC.d(TAG, "Share id = " + share.getIdRemoteShared() + " deleted"); mFile.setShareByLink(false); mFile.setPublicLink(""); getStorageManager().saveFile(mFile); getStorageManager().removeShare(share); } } else { result = new RemoteOperationResult(ResultCode.FILE_NOT_FOUND); } return result; }

Target:
protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; String path = mFile.getRemotePath(); if (mFile.isFolder()) { path = path.substring(0, path.length()-1); } OCShare share = getStorageManager().getShareByPath(path); if (share != null) { RemoveRemoteShareOperation operation = new RemoveRemoteShareOperation((int) share.getIdRemoteShared()); result = operation.execute(client); if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) { Log_OC.d(TAG, "Share id = " + share.getIdRemoteShared() + " deleted"); mFile.setShareByLink(false); mFile.setPublicLink(""); getStorageManager().saveFile(mFile); getStorageManager().removeShare(share); if (result.getCode() == ResultCode.SHARE_NOT_FOUND) { if (existsFile(client, mFile.getRemotePath())) { result = new RemoteOperationResult(ResultCode.OK); } else { getStorageManager().removeFile(mFile, true, true); } } } } else { result = new RemoteOperationResult(ResultCode.SHARE_NOT_FOUND); } return result; }
Source:
public void truncate(long index) { if (index >= getLastIndex()) { return; } lastEntry = null; try { this.index.truncate(index); if (index < segment.index()) { channel.position(JournalSegmentDescriptor.BYTES); memory.clear(); for (int i = 0; i < memory.limit(); i++) { memory.put(i, (byte) 0); } channel.write(memory); channel.position(JournalSegmentDescriptor.BYTES); } else { reset(index); long position = channel.position(); memory.clear(); for (int i = 0; i < memory.limit(); i++) { memory.put(i, (byte) 0); } channel.write(memory); channel.position(position); } } catch (IOException e) { throw new StorageException(e); } }

Target:
public void truncate(long index) { if (index >= getLastIndex()) { return; } lastEntry = null; try { this.index.truncate(index); if (index < segment.index()) { channel.position(JournalSegmentDescriptor.BYTES); channel.write(zero()); channel.position(JournalSegmentDescriptor.BYTES); } else { reset(index); long position = channel.position(); channel.write(zero()); channel.position(position); } } catch (IOException e) { throw new StorageException(e); } }
Source:
private static void addPamCrops() { if (!Loader.isModLoaded("harvestcraft")) return; try { ClassLoader loader = HarvestHandlerPlantable.class.getClassLoader(); String className = "com.pam.harvestcraft.blocks.CropRegistry"; Class<?> registry = ReflectionHelper.getClass(loader, className); Field names = ReflectionHelper.findField(registry, "cropNames"); Method getCrop = registry.getMethod("getCrop", String.class); for (String name : (String[])names.get(null)) { Block crop = (Block) getCrop.invoke(null, name); HarvestRegistry.registerStandardCrop(crop, 3); } } catch (NoSuchMethodException e) { FMLLog.warning("HarvestCraft integration cancelled; unable to find crop name mapper"); return; } catch (IllegalAccessException e) { FMLLog.warning("HarvestCraft integration cancelled; crop name lookup broke"); return; } catch (InvocationTargetException e) { FMLLog.warning("HarvestCraft integration cancelled; crop name lookup broke"); return; } catch (ReflectionHelper.UnableToFindClassException e) { FMLLog.warning("HarvestCraft integration cancelled; unable to find crop registry"); return; } catch (ReflectionHelper.UnableToFindFieldException e) { FMLLog.warning("HarvestCraft integration cancelled; unable to find crop names in registry"); return; } }

Target:
private static void addPamCrops() { if (!Loader.isModLoaded("harvestcraft")) return; try { ClassLoader loader = HarvestHandlerPlantable.class.getClassLoader(); String className = "com.pam.harvestcraft.blocks.CropRegistry"; Class<?> registry = ReflectionHelper.getClass(loader, className); Field names = ReflectionHelper.findField(registry, "cropNames"); Method getCrop = registry.getMethod("getCrop", String.class); for (String name : (String[])names.get(null)) { BlockCrops crop = (BlockCrops) getCrop.invoke(null, name); HarvestRegistry.registerStandardCrop(crop, crop.getMaxAge()); } } catch (NoSuchMethodException e) { BloodMagic.instance.getLogger().error("HarvestCraft integration cancelled; unable to find crop name mapper"); return; } catch (IllegalAccessException e) { BloodMagic.instance.getLogger().error("HarvestCraft integration cancelled; crop name lookup broke"); return; } catch (InvocationTargetException e) { BloodMagic.instance.getLogger().error("HarvestCraft integration cancelled; crop name lookup broke"); return; } catch (ReflectionHelper.UnableToFindClassException e) { BloodMagic.instance.getLogger().error("HarvestCraft integration cancelled; unable to find crop registry"); return; } catch (ReflectionHelper.UnableToFindFieldException e) { BloodMagic.instance.getLogger().error("HarvestCraft integration cancelled; unable to find crop names in registry"); return; } }
Source:
private CacheConfiguration cacheConfiguration(int cacheIdx) { return new CacheConfiguration(CACHE_NAME + cacheIdx) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL) .setCacheMode(CacheMode.REPLICATED) .setBackups(0) .setRebalanceDelay(Long.MAX_VALUE); }

Target:
private CacheConfiguration cacheConfiguration(int cacheIdx) { CacheConfiguration ccfg = new CacheConfiguration(CACHE_NAME + cacheIdx) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL) .setCacheMode(CacheMode.REPLICATED) .setBackups(0); if (MvccFeatureChecker.forcedMvcc()) ccfg.setRebalanceDelay(Long.MAX_VALUE); else ccfg.setRebalanceMode(CacheRebalanceMode.NONE); return ccfg; }
Source:
public void setUuid(String Uuid) { this.Uuid = Uuid; }

Target:
public void setUuid(String Uuid) { this.uuid = Uuid; }
Source:
private void delete(String projectName, OpenShiftClient osClient) throws InfrastructureException { try { osClient.projects().withName(projectName).delete(); } catch (KubernetesClientException e) { if (e.getCode() == 404) { LOG.warn( format( "Tried to delete project '%s' but it doesn't exist in the cluster.", projectName), e); } else { throw new KubernetesInfrastructureException(e); } } }

Target:
private void delete(String projectName, OpenShiftClient osClient) throws InfrastructureException { try { osClient.projects().withName(projectName).delete(); } catch (KubernetesClientException e) { if (e.getCode() == 404) { LOG.warn( format( "Tried to delete project '%s' but it doesn't exist in the cluster.", projectName), e); } else if (e.getCode() == 409) { LOG.info(format("The project '%s' is currently being deleted.", projectName), e); } else { throw new KubernetesInfrastructureException(e); } } }
Source:
public CompletionStage<MemcacheStatus> set(String key, V value, int ttl, long cas) { checkNotNull(value); final byte[] valueBytes = valueTranscoder.encode(value); byte[] byteKey = encodeKey(key, charset, maxKeyLength); SetRequest request = SetRequest.casSet(byteKey, valueBytes, ttl, cas); CompletionStage<MemcacheStatus> future = rawMemcacheClient.send(request); metrics.measureSetFuture(future); tracer.span("folsom.set", future, "set", key); return future; }

Target:
public CompletionStage<MemcacheStatus> set(String key, V value, int ttl, long cas) { checkNotNull(value); final byte[] valueBytes = valueTranscoder.encode(value); byte[] byteKey = encodeKey(key, charset, maxKeyLength); SetRequest request = SetRequest.casSet(byteKey, valueBytes, ttl, cas); CompletionStage<MemcacheStatus> future = rawMemcacheClient.send(request); metrics.measureSetFuture(future); tracer.span("folsom.set", future, "set", key, valueBytes); return future; }
Source:
public static String[] getMyanmarMonthsArray(int myanmarYear) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return MyanmarDateKernel .getMyanmarMonth(myanmarYear, 1) .getMonthNameList(new LanguageCatalog(Language.MYANMAR)) .toArray(new String[0]); } else { return MyanmarDateKernel .getMyanmarMonth(myanmarYear, 1) .getMonthNameList(new LanguageCatalog(Language.ENGLISH)) .toArray(new String[0]); } }

Target:
public static String[] getMyanmarMonthsArray(int myanmarYear) { return MyanmarDateKernel .getMyanmarMonth(myanmarYear, 1) .getMonthNameList(getLanguageCatalog()) .toArray(new String[0]); }