auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private synchronized void handleExperimentResult(String testID) { logger.info("handleExperimentResult with testID: " + testID); HandleExperimentResultTask task = new HandleExperimentResultTask(testID); Future<Boolean> future = taskExecutorService.submit(task); testTasks.put(testID, future); try { Boolean hasRegressionModel = future.get(); TestRunningState nextState = hasRegressionModel ? DERIVE_PREDICTION_FUNCTION : VALIDATE_TERMINATION_CRITERIA; testModelDAO.setTestRunningState(testID, nextState); handleTestState(testID); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (BenchFlowTestIDDoesNotExistException e) { logger.error("test ID does not exist - should not happen"); } }

Target:
private synchronized void handleExperimentResult(String testID) { logger.info("handleExperimentResult with testID: " + testID); HandleExperimentResultTask task = new HandleExperimentResultTask(testID); Future<?> future = taskExecutorService.submit(task); testTasks.put(testID, future); try { future.get(); Boolean hasRegressionModel = explorationModelDAO.hasRegressionModel(testID); TestRunningState nextState = hasRegressionModel ? DERIVE_PREDICTION_FUNCTION : VALIDATE_TERMINATION_CRITERIA; testModelDAO.setTestRunningState(testID, nextState); handleTestState(testID); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (BenchFlowTestIDDoesNotExistException e) { logger.error("test ID does not exist - should not happen"); } }
Source:
private void doSingleParseHttpClientExecuteWithGzipResponse( int responseCode, String responseStatus, final String responseContent, ParseHttpClient client) throws Exception { MockWebServer server = new MockWebServer(); Buffer buffer = new Buffer(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut); gzipOut.write(responseContent.getBytes()); gzipOut.close(); buffer.write(byteOut.toByteArray()); MockResponse mockResponse = new MockResponse() .setStatus("HTTP/1.1 " + responseCode + " " + responseStatus) .setBody(buffer) .setHeader("Content-Encoding", "gzip"); server.enqueue(mockResponse); server.start(); String requestUrl = server.getUrl("/").toString(); ParseHttpRequest parseRequest = new ParseHttpRequest.Builder() .setUrl(requestUrl) .setMethod(ParseRequest.Method.GET) .build(); client.addInternalInterceptor(new ParseDecompressInterceptor()); client.addExternalInterceptor(new ParseNetworkInterceptor() { @Override public ParseHttpResponse intercept(Chain chain) throws IOException { return chain.proceed(chain.getRequest()); } }); ParseHttpResponse parseResponse = client.execute(parseRequest); RecordedRequest recordedRequest = server.takeRequest(); assertEquals(ParseRequest.Method.GET.toString(), recordedRequest.getMethod()); Headers recordedHeaders = recordedRequest.getHeaders(); assertEquals("gzip", recordedHeaders.get("Accept-Encoding")); assertNull(parseResponse.getHeader("Content-Encoding")); byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent()); assertArrayEquals(responseContent.getBytes(), content); server.shutdown(); }

Target:
private void doSingleParseHttpClientExecuteWithGzipResponse( int responseCode, String responseStatus, final String responseContent, ParseHttpClient client) throws Exception { MockWebServer server = new MockWebServer(); Buffer buffer = new Buffer(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut); gzipOut.write(responseContent.getBytes()); gzipOut.close(); buffer.write(byteOut.toByteArray()); MockResponse mockResponse = new MockResponse() .setStatus("HTTP/1.1 " + responseCode + " " + responseStatus) .setBody(buffer) .setHeader("Content-Encoding", "gzip"); server.enqueue(mockResponse); server.start(); String requestUrl = server.getUrl("/").toString(); ParseHttpRequest parseRequest = new ParseHttpRequest.Builder() .setUrl(requestUrl) .setMethod(ParseRequest.Method.GET) .build(); ParseHttpResponse parseResponse = client.execute(parseRequest); RecordedRequest recordedRequest = server.takeRequest(); assertEquals(ParseRequest.Method.GET.toString(), recordedRequest.getMethod()); Headers recordedHeaders = recordedRequest.getHeaders(); assertEquals("gzip", recordedHeaders.get("Accept-Encoding")); byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent()); assertArrayEquals(responseContent.getBytes(), content); server.shutdown(); }
Source:
public void layerRemoved(LayerCollectionEvent listener) { for (ILayer layer : listener.getAffected()) { removeLayerListenerRecursively(layer, this); if(!mapContext.isLayerModelSpatial()){ mapTransform.setExtent(null); } invalidateImage(); } }

Target:
public void layerRemoved(LayerCollectionEvent listener) { for (ILayer layer : listener.getAffected()) { removeLayerListenerRecursively(layer, this); if(!mapContext.isLayerModelSpatial()){ mapTransform.setAdjustExtent(false); mapTransform.setExtent(new Envelope()); } invalidateImage(); } }
Source:
public String createMoveRefactoring(CreateMoveRefactoring cmr) throws JavaModelException, RefactoringException { LOG.info( "createMoveRefactoring started in " + System.currentTimeMillis() + " ms with " + cmr.toString()); IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath()); IJavaElement[] javaElements; try { Function<ElementToMove, IJavaElement> map = javaElement -> { try { if (javaElement.isPack()) { return javaProject.findPackageFragment( new org.eclipse.core.runtime.Path(javaElement.getPath())); } else { IType type = javaProject.findType(javaElement.getPath()); if (type == null) { throw new IllegalArgumentException("Can't find type: " + javaElement.getPath()); } return type.getCompilationUnit(); } } catch (JavaModelException e) { throw new IllegalArgumentException(e); } }; javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new); } catch (IllegalArgumentException e) { LOG.error( "createMoveRefactoring fail in " + System.currentTimeMillis() + " ms with exception " + e.getMessage()); if (e.getCause() instanceof JavaModelException) { throw (JavaModelException) e.getCause(); } else { throw e; } } if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) { String moveRefactoringSession = manager.createMoveRefactoringSession(javaElements); LOG.info( "createMoveRefactoring finished in " + System.currentTimeMillis() + " ms with session id " + moveRefactoringSession); return moveRefactoringSession; } LOG.error( "createMoveRefactoring finished in " + System.currentTimeMillis() + " ms with with RefactoringException"); throw new RefactoringException("Can't create move refactoring."); }

Target:
public String createMoveRefactoring(CreateMoveRefactoring cmr) throws JavaModelException, RefactoringException { IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath()); IJavaElement[] javaElements; try { Function<ElementToMove, IJavaElement> map = javaElement -> { try { if (javaElement.isPack()) { return javaProject.findPackageFragment( new org.eclipse.core.runtime.Path(javaElement.getPath())); } else { IType type = javaProject.findType(javaElement.getPath()); if (type == null) { throw new IllegalArgumentException("Can't find type: " + javaElement.getPath()); } return type.getCompilationUnit(); } } catch (JavaModelException e) { throw new IllegalArgumentException(e); } }; javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new); } catch (IllegalArgumentException e) { if (e.getCause() instanceof JavaModelException) { throw (JavaModelException) e.getCause(); } else { throw e; } } if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) { return manager.createMoveRefactoringSession(javaElements); } throw new RefactoringException("Can't create move refactoring."); }
Source:
private static void testEncodingAndDecodingWebException(Class<? extends WebApplicationException> exceptionClass, Status status) { WebApplicationException exceptionToProcess; try { exceptionToProcess = exceptionClass.getConstructor(String.class, Status.class).newInstance(message, status); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } RemoteException exception = (RemoteException) encodeAndDecode(exceptionToProcess); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getStatus(), is(status.getStatusCode())); assertThat(exception.getRemoteException().getExceptionName(), is(exceptionClass.getName())); assertThat(exception.getMessage(), is(message)); }

Target:
private static void testEncodingAndDecodingWebException(Class<? extends WebApplicationException> exceptionClass, Status status) { WebApplicationException exceptionToProcess; try { exceptionToProcess = exceptionClass.getConstructor(String.class, Status.class).newInstance(message, status); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } RemoteException exception = (RemoteException) encodeAndDecode(exceptionToProcess); assertThat(exception.getCause(), is(nullValue())); assertThat(exception.getStatus(), is(status.getStatusCode())); assertThat(exception.getRemoteException().getErrorName(), is(exceptionClass.getName())); assertThat(exception.getMessage(), is(message)); }
Source:
public ScrambleLogic( final GameData data, final PlayerId player, final Set<Territory> territoriesWithBattles, final BattleTracker battleTracker) { this.data = data; this.player = player; this.territoriesWithBattles = territoriesWithBattles; this.battleTracker = battleTracker; this.airbaseThatCanScramblePredicate = Matches.unitIsEnemyOf(data, player) .and(Matches.unitIsAirBase()) .and(Matches.unitIsNotDisabled()) .and(Matches.unitIsBeingTransported().negate()); this.canScrambleFromPredicate = PredicateBuilder.of(Matches.territoryIsWater().or(Matches.isTerritoryEnemy(player, data))) .and( Matches.territoryHasUnitsThatMatch( Matches.unitCanScramble() .and(Matches.unitIsEnemyOf(data, player)) .and(Matches.unitIsNotDisabled()))) .and(Matches.territoryHasUnitsThatMatch(airbaseThatCanScramblePredicate)) .andIf(Properties.getScrambleFromIslandOnly(data), Matches.territoryIsIsland()) .build(); this.maxScrambleDistance = computeMaxScrambleDistance(data); }

Target:
public ScrambleLogic( final GameData data, final PlayerId player, final Set<Territory> territoriesWithBattles, final BattleTracker battleTracker) { if (!Properties.getScrambleRulesInEffect(data)) { throw new IllegalStateException("Scrambling not supported"); } this.data = data; this.player = player; this.territoriesWithBattles = territoriesWithBattles; this.battleTracker = battleTracker; this.airbaseThatCanScramblePredicate = Matches.unitIsEnemyOf(data, player) .and(Matches.unitIsAirBase()) .and(Matches.unitIsNotDisabled()) .and(Matches.unitIsBeingTransported().negate()); this.canScrambleFromPredicate = PredicateBuilder.of(Matches.territoryIsWater().or(Matches.isTerritoryEnemy(player, data))) .and( Matches.territoryHasUnitsThatMatch( Matches.unitCanScramble() .and(Matches.unitIsEnemyOf(data, player)) .and(Matches.unitIsNotDisabled()))) .and(Matches.territoryHasUnitsThatMatch(airbaseThatCanScramblePredicate)) .andIf(Properties.getScrambleFromIslandOnly(data), Matches.territoryIsIsland()) .build(); this.maxScrambleDistance = computeMaxScrambleDistance(data); }
Source:
public void register() { if (m_registered) { return; } try { m_topologyDao.register(this); m_registered = true; LOG.info("register: protocol:{}", getProtocol().getId()); } catch (Exception e) { LOG.error("register: {}", e.getMessage()); } }

Target:
public void register() { if (m_registered) { return; } try { m_topologyDao.register(this); m_registered = true; LOG.info("register: protocol:{}", getProtocol().getId()); } catch (Exception e) { LOG.error("register", e); } }
Source:
public void initializeState(FunctionInitializationContext context) throws Exception { Preconditions.checkState(this.checkpointedState == null, "The " + getClass().getSimpleName() + " has already been initialized."); this.checkpointedState = context.getOperatorStateStore().getListState( new ListStateDescriptor<>( "arrow-source-state", new TupleSerializer<>( (Class<Tuple2<Integer, Integer>>) (Class<?>) Tuple2.class, new TypeSerializer[]{IntSerializer.INSTANCE, IntSerializer.INSTANCE}) ) ); this.indexesToEmit = new ArrayDeque<>(); if (context.isRestored()) { for (Tuple2<Integer, Integer> v : this.checkpointedState.get()) { this.indexesToEmit.add(v); } } else { final int stepSize = getRuntimeContext().getNumberOfParallelSubtasks(); final int taskIdx = getRuntimeContext().getIndexOfThisSubtask(); for (int i = taskIdx; i < arrowData.length; i += stepSize) { this.indexesToEmit.add(Tuple2.of(i, 0)); } } }

Target:
public void initializeState(FunctionInitializationContext context) throws Exception { Preconditions.checkState(this.checkpointedState == null, "The " + getClass().getSimpleName() + " has already been initialized."); this.checkpointedState = context.getOperatorStateStore().getListState( new ListStateDescriptor<>( "arrow-source-state", new TupleSerializer<>( (Class<Tuple2<Integer, Integer>>) (Class<?>) Tuple2.class, new TypeSerializer[]{IntSerializer.INSTANCE, IntSerializer.INSTANCE}) ) ); this.indexesToEmit = new ArrayDeque<>(); if (context.isRestored()) { for (Tuple2<Integer, Integer> v : this.checkpointedState.get()) { this.indexesToEmit.add(v); } LOG.info("Subtask restored state: {}.", getRuntimeContext().getIndexOfThisSubtask(), indexesToEmit); } else { final int stepSize = getRuntimeContext().getNumberOfParallelSubtasks(); final int taskIdx = getRuntimeContext().getIndexOfThisSubtask(); for (int i = taskIdx; i < arrowData.length; i += stepSize) { this.indexesToEmit.add(Tuple2.of(i, 0)); } LOG.info("Subtask has no restore state, initialized with {}.", taskIdx, indexesToEmit); } }
Source:
public void warning(String message){ AeroGearLogger.logger.warn(format(message)); }

Target:
public void warning(String message){ AeroGearLogger.logger.warn(message); }
Source:
public RegistrationUpdateEvent(String address, List<RegistrationInfo> registrations) { this.address = address; if (registrations == null || registrations.isEmpty()) { this.registrations = Collections.emptyList(); } else { this.registrations = Collections.unmodifiableList(registrations); } }

Target:
public RegistrationUpdateEvent(String address, List<RegistrationInfo> registrations) { this.address = address; this.registrations = registrations == null ? Collections.emptyList() : registrations; }
Source:
boolean retryCallAfterBackoff( final RequestT payload, final Metadata requestHeaders, final Listener<ResponseT> listener) { long sleepTimeout = BackOff.STOP; if (backOff == null) { backOff = retryOptions.createBackoff(); } try { sleepTimeout = backOff.nextBackOffMillis(); } catch (IOException e) { } if (sleepTimeout != BackOff.STOP) { scheduledExecutorService.schedule(new Runnable() { @Override public void run() { try { retryCall(payload, requestHeaders, listener); } catch (RuntimeException e) { Metadata trailers = new Metadata(); listener.onClose(Status.fromThrowable(e), trailers); } } }, sleepTimeout, TimeUnit.MILLISECONDS); return true; } return false; }

Target:
synchronized boolean retryCallAfterBackoff( final RequestT payload, final Metadata requestHeaders, final Listener<ResponseT> listener) { long sleepTimeout = BackOff.STOP; if (backOff == null) { backOff = retryOptions.createBackoff(); } try { sleepTimeout = backOff.nextBackOffMillis(); } catch (IOException e) { } if (sleepTimeout != BackOff.STOP) { scheduledExecutorService.schedule(new Runnable() { @Override public void run() { try { retryCall(payload, requestHeaders, listener); } catch (RuntimeException e) { Metadata trailers = new Metadata(); listener.onClose(Status.fromThrowable(e), trailers); } } }, sleepTimeout, TimeUnit.MILLISECONDS); return true; } return false; }
Source:
public void registerCache(String name, int maxSize, int timeout) { registerCache(name, maxSize, timeout, new CacheDescriptor()); }

Target:
public void registerCache(String name, int maxSize, int timeout) { registerCache(name); }
Source:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(1, 1, null, null, null); List<MonitoringCenter> resultWithQuery = monitoringCenterApi().list(options); assertNotNull(resultWithQuery); }

Target:
public void testListWithOption() { GenericQueryOptions options = new GenericQueryOptions(); options.options(1, 1, null, null, null); List<MonitoringCenter> resultWithQuery = monitoringCenterApi().list(options); assertNotNull(resultWithQuery); Assert.assertTrue(resultWithQuery.size() >= 1); }
Source:
public void should_not_print_any_output_when_quiet_option_is_given() throws Exception { execute("version", "-quiet"); assertOk(); assertNoOutput(out); assertNoOutput(err); }

Target:
public void should_not_print_any_output_when_quiet_option_is_given() throws Exception { execute("version", "--quiet"); assertOk(); assertNoOutput(out); assertNoOutput(err); }
Source:
public void destroyCache(final String alias) { final CacheHolder cacheHolder = caches.get(alias); if(cacheHolder == null) { throw new IllegalArgumentException("No Cache associated with alias " + alias); } final Ehcache<?, ?> ehcache = cacheHolder.retrieve(cacheHolder.keyType, cacheHolder.valueType); if(ehcache.getStatus() == Status.AVAILABLE) { ehcache.close(); } ehcache.toMaintenance().destroy(); }

Target:
public void destroyCache(final String alias) { final CacheHolder cacheHolder = caches.remove(alias); if(cacheHolder == null) { throw new IllegalArgumentException("No Cache associated with alias " + alias); } final Ehcache<?, ?> ehcache = cacheHolder.retrieve(cacheHolder.keyType, cacheHolder.valueType); if(ehcache.getStatus() == Status.AVAILABLE) { ehcache.close(); } ehcache.toMaintenance().destroy(); }
Source:
public void testOCDMarshallUnmarshall() throws Exception { XmlMarshallUnmarshallImpl xmlMarshallerImpl = new XmlMarshallUnmarshallImpl(); String pid = "org.eclipse.kura.cloud.CloudService"; Tocd definition = ComponentUtil.readObjectClassDefinition(pid); Map<String, Object> properties = new HashMap<>(); properties.put("prop.string", new String("prop.value")); properties.put("prop.long", Long.MAX_VALUE); properties.put("prop.double", Double.MAX_VALUE); properties.put("prop.float", Float.MAX_VALUE); properties.put("prop.integer", Integer.MAX_VALUE); properties.put("prop.byte", Byte.MAX_VALUE); properties.put("prop.character", 'a'); properties.put("prop.short", Short.MAX_VALUE); XmlComponentConfigurations xcc = new XmlComponentConfigurations(); List<ComponentConfiguration> ccis = new ArrayList<>(); ComponentConfigurationImpl config = new ComponentConfigurationImpl(pid, definition, properties); ccis.add(config); xcc.setConfigurations(ccis); String s = xmlMarshallerImpl.marshal(xcc); System.err.println(s); XmlComponentConfigurations config1 = xmlMarshallerImpl.unmarshal(s, XmlComponentConfigurations.class); String s1 = xmlMarshallerImpl.marshal(config1); System.err.println(s1); Map<String, Object> properties1 = config1.getConfigurations().get(0).getConfigurationProperties(); assertEquals(properties, properties1); }

Target:
public void testOCDMarshallUnmarshall() throws Exception { XmlMarshallUnmarshallImpl xmlMarshallerImpl = new XmlMarshallUnmarshallImpl(); String pid = "org.eclipse.kura.cloud.CloudService"; Tocd definition = ComponentUtil.readObjectClassDefinition(pid); Map<String, Object> properties = new HashMap<>(); properties.put("prop.string", new String("prop.value")); properties.put("prop.long", Long.MAX_VALUE); properties.put("prop.double", Double.MAX_VALUE); properties.put("prop.float", Float.MAX_VALUE); properties.put("prop.integer", Integer.MAX_VALUE); properties.put("prop.byte", Byte.MAX_VALUE); properties.put("prop.character", 'a'); properties.put("prop.short", Short.MAX_VALUE); XmlComponentConfigurations xcc = new XmlComponentConfigurations(); List<ComponentConfiguration> ccis = new ArrayList<>(); ComponentConfigurationImpl config = new ComponentConfigurationImpl(pid, definition, properties); ccis.add(config); xcc.setConfigurations(ccis); String s = xmlMarshallerImpl.marshal(xcc); logger.info(s); XmlComponentConfigurations config1 = xmlMarshallerImpl.unmarshal(s, XmlComponentConfigurations.class); String s1 = xmlMarshallerImpl.marshal(config1); logger.info(s1); Map<String, Object> properties1 = config1.getConfigurations().get(0).getConfigurationProperties(); assertEquals(properties, properties1); }
Source:
protected boolean canDoAction() { if (!FeatureSupported.isRefreshLunsSupported(getStoragePool().getCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_REFRESH_LUNS_UNSUPPORTED_ACTION); } if (!(checkStorageDomain() && checkStorageDomainStatus(StorageDomainStatus.Active))) { return false; } if ((getStorageDomain().getStorageType() == StorageType.NFS || getStorageDomain().getStorageType() == StorageType.UNKNOWN)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); return false; } if (!checkStorageDomainStatusNotEqual(StorageDomainStatus.Locked)) { return false; } return true; }

Target:
protected boolean canDoAction() { if (!FeatureSupported.refreshLunSupported(getStoragePool().getCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_REFRESH_LUNS_UNSUPPORTED_ACTION); } if (!(checkStorageDomain() && checkStorageDomainStatus(StorageDomainStatus.Active))) { return false; } if (!getStorageDomain().getStorageType().isBlockDomain()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL); return false; } if (!checkStorageDomainStatusNotEqual(StorageDomainStatus.Locked)) { return false; } return true; }
Source:
public String getJavaExpressionWithAppend(final Schema inputSchema, final Schema stateSchema) { return new StringBuilder().append("result.append").append(getOutputType(inputSchema, stateSchema).getName()) .append("(").append(getJavaExpression(inputSchema, stateSchema)).append(")").toString(); }

Target:
public String getJavaExpressionWithAppend(final Schema inputSchema, final Schema stateSchema) { return new StringBuilder(RESULT).append(".append").append(getOutputType(inputSchema, stateSchema).getName()) .append("(").append(getJavaExpression(inputSchema, stateSchema)).append(")").toString(); }
Source:
public OrganisationIdFilter(@Memoized Supplier<String> organisationIdSupplier) { this.organisationIdSupplier = organisationIdSupplier; }

Target:
OrganisationIdFilter(@Memoized Supplier<String> organisationIdSupplier) { this.organisationIdSupplier = organisationIdSupplier; }
Source:
public static void main(String[] args) { if (args.length < 3) { System.err.println("ERROR - Expected at least two arguments. " + "Usage: MiniFluoCommand <fluoHomeDir> <command> <appName> ..."); System.exit(-1); } String fluoHomeDir = args[0]; String command = args[1]; String appName = args[2]; String[] remainArgs = Arrays.copyOfRange(args, 3, args.length); if (command.equalsIgnoreCase("scan")) { for (String logger : new String[] {Logger.ROOT_LOGGER_NAME, "io.fluo"}) { ((Logger) LoggerFactory.getLogger(logger)).setLevel(Level.ERROR); } } else if (command.equalsIgnoreCase("wait")) { ((Logger) LoggerFactory.getLogger(FluoConfiguration.class)).setLevel(Level.ERROR); } FluoInstall fluoInstall = new FluoInstall(fluoHomeDir); MiniAppRunner runner = new MiniAppRunner(); switch (command.toLowerCase()) { case "classpath": runner.classpath(fluoHomeDir, remainArgs); break; case "scan": runner.scan(chooseConfig(fluoInstall.resolveFluoConfiguration(appName)), remainArgs); break; case "cleanup": runner.cleanup(fluoInstall.resolveFluoConfiguration(appName)); break; case "wait": runner.waitUntilFinished(chooseConfig(fluoInstall.resolveFluoConfiguration(appName))); break; default: System.err.println("Unknown command: " + command); break; } }

Target:
public static void main(String[] args) { if (args.length < 3) { System.err.println("ERROR - Expected at least two arguments. " + "Usage: MiniFluoCommand <fluoHomeDir> <command> <appName> ..."); System.exit(-1); } String fluoHomeDir = args[0]; String command = args[1]; String appName = args[2]; String[] remainArgs = Arrays.copyOfRange(args, 3, args.length); if (command.equalsIgnoreCase("scan")) { for (String logger : new String[] {Logger.ROOT_LOGGER_NAME, "io.fluo"}) { ((Logger) LoggerFactory.getLogger(logger)).setLevel(Level.ERROR); } } else if (command.equalsIgnoreCase("wait")) { ((Logger) LoggerFactory.getLogger(FluoConfiguration.class)).setLevel(Level.ERROR); } fluoInstall = new FluoInstall(fluoHomeDir); MiniAppRunner runner = new MiniAppRunner(); switch (command.toLowerCase()) { case "classpath": runner.classpath(fluoHomeDir, remainArgs); break; case "scan": runner.scan(chooseConfig(appName), remainArgs); break; case "cleanup": verifyNoArgs(remainArgs); runner.cleanup(fluoInstall.resolveFluoConfiguration(appName, false)); break; case "wait": verifyNoArgs(remainArgs); runner.waitUntilFinished(chooseConfig(appName)); break; default: System.err.println("Unknown command: " + command); break; } }
Source:
protected void showOutlinePageRec(OutlinePageRec pageRec) { if (activeRec == pageRec) { return; } if (activeRec != null && pageRec != null && activeRec.contentOutlinePage == pageRec.contentOutlinePage) { activeRec = pageRec; return; } activeRec = pageRec; Control pageControl = activeRec.contentOutlinePage.getControl(); if (pageControl != null && !pageControl.isDisposed()) { PageSite pageSite = (PageSite) activeRec.getPageSite(); sashEditorPageBook.showPage(pageControl); getSite().setActivePageSite(pageSite); } }

Target:
protected void showOutlinePageRec(OutlinePageRec pageRec) { if (activeRec == pageRec) { return; } if (activeRec != null && pageRec != null && activeRec.contentOutlinePage == pageRec.contentOutlinePage) { activeRec = pageRec; return; } activeRec = pageRec; if (activeRec != null) { Control pageControl = activeRec.contentOutlinePage.getControl(); if (pageControl != null && !pageControl.isDisposed()) { PageSite pageSite = (PageSite) activeRec.getPageSite(); sashEditorPageBook.showPage(pageControl); getSite().setActivePageSite(pageSite); } } }
Source:
private boolean pullImage(DockerTemplate dockerTemplate) throws IOException { final String imageName = dockerTemplate.getDockerTemplateBase().getImage(); List<Image> images = getClient().listImagesCmd().exec(); NameParser.ReposTag repostag = NameParser.parseRepositoryTag(imageName); final String fullImageName = repostag.repos + ":" + (repostag.tag.isEmpty() ? "latest" : repostag.tag); boolean imageExists = Iterables.any(images, new Predicate<Image>() { @Override public boolean apply(Image image) { return Arrays.asList(image.getRepoTags()).contains(fullImageName); } }); boolean pull = imageExists ? dockerTemplate.getPullStrategy().pullIfExists(imageName) : dockerTemplate.getPullStrategy().pullIfNotExists(imageName); if (pull) { LOGGER.info("Pulling image '{}' since one was not found. This may take awhile...", imageName); try (InputStream imageStream = getClient().pullImageCmd(imageName).exec()) { int streamValue = 0; while (streamValue != -1) { streamValue = imageStream.read(); } } LOGGER.info("Finished pulling image '{}'", imageName); } return true; }

Target:
private void pullImage(DockerTemplate dockerTemplate) throws IOException { final String imageName = dockerTemplate.getDockerTemplateBase().getImage(); List<Image> images = getClient().listImagesCmd().exec(); NameParser.ReposTag repostag = NameParser.parseRepositoryTag(imageName); final String fullImageName = repostag.repos + ":" + (repostag.tag.isEmpty() ? "latest" : repostag.tag); boolean imageExists = Iterables.any(images, new Predicate<Image>() { @Override public boolean apply(Image image) { return Arrays.asList(image.getRepoTags()).contains(fullImageName); } }); boolean pull = imageExists ? dockerTemplate.getPullStrategy().pullIfExists(imageName) : dockerTemplate.getPullStrategy().pullIfNotExists(imageName); if (pull) { LOGGER.info("Pulling image '{}' since one was not found. This may take awhile...", imageName); try (InputStream imageStream = getClient().pullImageCmd(imageName).exec()) { int streamValue = 0; while (streamValue != -1) { streamValue = imageStream.read(); } } LOGGER.info("Finished pulling image '{}'", imageName); } }
Source:
private TypeDefinition parseType( String typeName ) throws IOException, ParserException { TypeDefinition currentType = null; NativeType nativeType = readNativeType(); if ( nativeType == null ) { currentType = new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, token.content() ); getToken(); } else { getToken(); if ( nativeType.equals(NativeType.NativeTypeEnum.STRING) && token.is(Scanner.TokenType.LPAREN) ) { getToken(); currentType = new TypeInlineDefinition(getContext(), typeName, nativeType, token.content(), Constants.RANGE_ONE_TO_ONE); getToken(); eat(Scanner.TokenType.RPAREN, "expected right parenthesis"); } else { currentType = new TypeInlineDefinition( getContext(), typeName, nativeType, Constants.RANGE_ONE_TO_ONE); } if ( token.is( Scanner.TokenType.LCURLY ) ) { parseSubTypes((TypeInlineDefinition) currentType); } } if ( token.is( Scanner.TokenType.PARALLEL ) ) { getToken(); final TypeDefinition secondType = parseType( typeName ); final TypeChoiceDefinition choiceDefinition = new TypeChoiceDefinition( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, currentType, secondType ); return choiceDefinition; } return currentType; }

Target:
private TypeDefinition parseType( String typeName ) throws IOException, ParserException { TypeDefinition currentType; NativeType nativeType = readNativeType(); if ( nativeType == null ) { currentType = new TypeDefinitionLink( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, token.content() ); getToken(); } else { getToken(); if ( nativeType.equals(NativeType.NativeTypeEnum.STRING) && token.is(Scanner.TokenType.LPAREN) ) { getToken(); currentType = new TypeInlineDefinition(getContext(), typeName, (StringType) nativeType, token.content(), Constants.RANGE_ONE_TO_ONE); getToken(); eat(Scanner.TokenType.RPAREN, "expected right parenthesis"); } else { currentType = new TypeInlineDefinition( getContext(), typeName, nativeType, Constants.RANGE_ONE_TO_ONE); } if ( token.is( Scanner.TokenType.LCURLY ) ) { parseSubTypes( (TypeInlineDefinition) currentType ); } } if ( token.is( Scanner.TokenType.PARALLEL ) ) { getToken(); final TypeDefinition secondType = parseType( typeName ); final TypeChoiceDefinition choiceDefinition = new TypeChoiceDefinition( getContext(), typeName, Constants.RANGE_ONE_TO_ONE, currentType, secondType ); return choiceDefinition; } return currentType; }
Source:
protected String[] customCommandLineValidation() { if (PROGRAM.isEmpty()) { return new String[]{"No programs specified with PROGRAM"}; } programsToRun = new LinkedHashSet<>(PROGRAM); checkRInstallation(true); return super.customCommandLineValidation(); }

Target:
protected String[] customCommandLineValidation() { final List<String> errorMsgs = new ArrayList<String>(); if (PROGRAM.isEmpty()) { errorMsgs.add("No programs specified with PROGRAM"); } programsToRun = new LinkedHashSet<>(PROGRAM); if (!checkRInstallation(true)) { errorMsgs.add("R is not installed on this machine. It is required for creating the chart."); } return errorMsgs.isEmpty() ? null : errorMsgs.toArray(new String[errorMsgs.size()]); }
Source:
public void defineMappings(Cache cache, SearchMapping searchMapping) { searchMapping.entity(ProtobufValueWrapper.class) .indexed() .indexName(cache.getName() + "--" + ProtobufValueWrapperAnalyzerDiscriminator.class.getName()) .analyzerDiscriminator(ProtobufValueWrapperAnalyzerDiscriminator.class) .classBridgeInstance(new ProtobufValueWrapperFieldBridge(cache)) .norms(Norms.NO) .analyze(Analyze.NO) .store(Store.NO); }

Target:
public void defineMappings(Cache cache, SearchMapping searchMapping) { searchMapping.entity(ProtobufValueWrapper.class) .indexed() .indexName(cache.getName() + INDEX_NAME_SUFFIX) .analyzerDiscriminator(ProtobufValueWrapperAnalyzerDiscriminator.class) .classBridgeInstance(new ProtobufValueWrapperFieldBridge(cache)) .norms(Norms.NO) .analyze(Analyze.NO) .store(Store.NO); }
Source:
public boolean checkAndMaintain(final long hostId) { boolean hostInMaintenance = false; final HostVO host = _hostDao.findById(hostId); try { if (host.getType() != Host.Type.Storage) { final List<VMInstanceVO> vos = _vmDao.listByHostId(hostId); final List<VMInstanceVO> vosMigrating = _vmDao.listVmsMigratingFromHost(hostId); final List<VMInstanceVO> failedMigratedVms = _vmDao.listRunningVmsByHostAndLastHostSameId(hostId); if (vos.isEmpty() && vosMigrating.isEmpty() && failedMigratedVms.isEmpty()) { resourceStateTransitTo(host, ResourceState.Event.InternalEnterMaintenance, _nodeId); hostInMaintenance = true; ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), CallContext.current().getCallingAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_MAINTENANCE_PREPARE, "completed maintenance for host " + hostId, 0); } } } catch (final NoTransitionException e) { s_logger.debug("Cannot transmit host " + host.getId() + "to Maintenance state", e); } return hostInMaintenance; }

Target:
public boolean checkAndMaintain(final long hostId) { boolean hostInMaintenance = false; final HostVO host = _hostDao.findById(hostId); try { if (host.getType() != Host.Type.Storage) { final List<VMInstanceVO> vos = _vmDao.listByHostId(hostId); final List<VMInstanceVO> vosMigrating = _vmDao.listVmsMigratingFromHost(hostId); final List<VMInstanceVO> failedVmMigrations = _vmDao.listNonMigratingVmsByHostEqualsLastHost(hostId); hostInMaintenance = isHostInMaintenance(host, vos, vosMigrating, failedVmMigrations); } } catch (final NoTransitionException e) { s_logger.debug("Cannot transmit host " + host.getId() + "to Maintenance state", e); } return hostInMaintenance; }
Source:
public void messageReceived(UPBMessage message) { if (message.getType() == Type.MESSAGE_REPORT) { String sourceName = getItemName(message.getSource(), false); String destinationName = getItemName(message.getDestination(), message.getControlWord().isLink()); UPBBindingConfig sourceConfig = getConfig(sourceName); UPBBindingConfig destinationConfig = getConfig(destinationName); String itemName = isValidId(message.getDestination()) ? destinationName : sourceName; UPBBindingConfig config = isValidId(message.getDestination()) ? destinationConfig : sourceConfig; if (itemName != null && config != null) { State newState = null; byte level = 100; switch (message.getCommand()) { case GOTO: case DEVICE_STATE: case ACTIVATE: if (message.getArguments() != null && message.getArguments().length > 0) { level = message.getArguments()[0]; } else { level = (byte) (message.getCommand() == UPBMessage.Command.ACTIVATE ? 100 : 0); } if (level == -1 || level >= 100 || (level > 0 && !config.isDimmable())) { newState = OnOffType.ON; } else if (level == 0) { newState = OnOffType.OFF; } else { newState = new PercentType(level); } break; case DEACTIVATE: newState = OnOffType.OFF; break; default: break; } if (newState != null) { logger.debug("Posting update: {},{}", itemName, newState); eventPublisher.postUpdate(itemName, newState); } } else { logger.debug("Received message for unknown with id {}.", message.getControlWord().isLink() ? "Link" : "Device", message.getDestination() & 0xff); } } }

Target:
public void messageReceived(UPBMessage message) { if (message.getType() != Type.MESSAGE_REPORT) { return; } String sourceName = getItemName(message.getSource(), false); String destinationName = getItemName(message.getDestination(), message.getControlWord().isLink()); UPBBindingConfig sourceConfig = getConfig(sourceName); UPBBindingConfig destinationConfig = getConfig(destinationName); String itemName = isValidId(message.getDestination()) ? destinationName : sourceName; UPBBindingConfig config = isValidId(message.getDestination()) ? destinationConfig : sourceConfig; if (itemName == null || config == null) { logger.debug("Received message for unknown with id {}.", message.getControlWord().isLink() ? "Link" : "Device", message.getDestination() & 0xff); return; } State newState = null; byte level = 100; switch (message.getCommand()) { case GOTO: case DEVICE_STATE: case ACTIVATE: if (message.getArguments() != null && message.getArguments().length > 0) { level = message.getArguments()[0]; } else { level = (byte) (message.getCommand() == UPBMessage.Command.ACTIVATE ? 100 : 0); } if (level == -1 || level >= 100 || (level > 0 && !config.isDimmable())) { newState = OnOffType.ON; } else if (level == 0) { newState = OnOffType.OFF; } else { newState = new PercentType(level); } break; case DEACTIVATE: newState = OnOffType.OFF; break; default: break; } if (newState != null) { logger.debug("Posting update: {},{}", itemName, newState); eventPublisher.postUpdate(itemName, newState); } }
Source:
public String[] getSupportedAbis() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.SUPPORTED_ABIS.length > 0) { return Build.SUPPORTED_ABIS; } else { return new String[] { Build.CPU_ABI, Build.CPU_ABI2 }; } }

Target:
public static String[] getSupportedAbis() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.SUPPORTED_ABIS.length > 0) { return Build.SUPPORTED_ABIS; } else { return new String[] { Build.CPU_ABI, Build.CPU_ABI2 }; } }
Source:
public void runMultipleActionFailed(VdcActionType action, List<VdcReturnValueBase> returnValues, List<VdcFault> faults) { String actionStr = EnumTranslator.createAndTranslate(action); List<Message> errors = new ArrayList<Message>(); int actionNum = 0; for (VdcReturnValueBase v : returnValues) { ++actionNum; if (isRaiseErrorModalPanel(action, v.getFault())) { for (String canDo : v.getCanDoActionMessages()) { String description = (v.getDescription() != null && !"".equals(v.getDescription().trim())) || returnValues.size() == 1 ? v.getDescription() : "Action " + actionNum; Message msg = new Message(description, canDo); errors.add(msg); } } } for (VdcFault fault : faults) { if (isRaiseErrorModalPanel(action, fault)) { Message msg = new Message(actionStr, fault.getMessage()); errors.add(msg); } } errorPopupManager.show(ErrorMessageFormatter.formatMessages(errors)); }

Target:
public void runMultipleActionFailed(VdcActionType action, List<VdcReturnValueBase> returnValues, List<VdcFault> faults) { String actionStr = EnumTranslator.createAndTranslate(action); List<Message> errors = new ArrayList<Message>(); int actionNum = 0; for (VdcReturnValueBase v : returnValues) { ++actionNum; if (isRaiseErrorModalPanel(action, v.getFault())) { for (String canDo : v.getCanDoActionMessages()) { String description = (v.getDescription() != null && !"".equals(v.getDescription().trim())) || returnValues.size() == 1 ? v.getDescription() : ConstantsManager.getInstance().getConstants().action() + " " + actionNum; Message msg = new Message(description, canDo); errors.add(msg); } } } for (VdcFault fault : faults) { if (isRaiseErrorModalPanel(action, fault)) { Message msg = new Message(actionStr, fault.getMessage()); errors.add(msg); } } errorPopupManager.show(ErrorMessageFormatter.formatMessages(errors)); }
Source:
private static synchronized Session session() { final Properties properties = new Properties(); final ConfigurationProperties conf = EmailDispatchConfiguration.getConfiguration(); properties.put("mail.smtp.host", conf.mailSmtpHost()); properties.put("mail.smtp.name", conf.mailSmtpName()); properties.put("mail.smtp.port", conf.mailSmtpPort()); properties.put("mailSender.max.recipients", conf.mailSenderMaxRecipients()); SESSION = Session.getDefaultInstance(properties, null); return SESSION; }

Target:
private static synchronized Session session() { final Properties properties = new Properties(); ConfigurationProperties conf = EmailDispatchConfiguration.getConfiguration(); properties.put("mail.smtp.host", conf.mailSmtpHost()); properties.put("mail.smtp.name", conf.mailSmtpName()); properties.put("mail.smtp.port", conf.mailSmtpPort()); properties.put("mailSender.max.recipients", conf.mailSenderMaxRecipients()); SESSION = Session.getDefaultInstance(properties, null); return SESSION; }
Source:
public static void fetchUsers(String siteID, final int localTableBlogId, final PeopleUtils.Callback callback) { com.wordpress.rest.RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (jsonObject != null) { try { JSONArray jsonArray = jsonObject.getJSONArray("users"); List<Person> people = peopleListFromJSON(jsonArray, localTableBlogId); PeopleTable.savePeople(people); if (callback != null) { callback.onSuccess(); } } catch (JSONException e) { AppLog.e(T.API, "JSON exception occurred while parsing the response for sites/%s/users: " + e); } } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(T.API, volleyError); if (callback != null) { callback.onError(volleyError); } } }; String path = String.format("sites/%s/users", siteID); WordPress.getRestClientUtilsV1_1().get(path, listener, errorListener); }

Target:
public static void fetchUsers(String siteID, final int localTableBlogId, final PeopleUtils.Callback callback) { com.wordpress.rest.RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { if (jsonObject != null && callback != null) { try { JSONArray jsonArray = jsonObject.getJSONArray("users"); List<Person> people = peopleListFromJSON(jsonArray, localTableBlogId); callback.onSuccess(people); } catch (JSONException e) { AppLog.e(T.API, "JSON exception occurred while parsing the response for sites/%s/users: " + e); callback.onJSONException(e); } } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppLog.e(T.API, volleyError); if (callback != null) { callback.onError(volleyError); } } }; String path = String.format("sites/%s/users", siteID); WordPress.getRestClientUtilsV1_1().get(path, listener, errorListener); }
Source:
public boolean filterLogs(ActivityLogEntry logEntry){ if(!logEntry.toShow()){ return false; } if(q == null){ if (this.queryMessage == null){ this.queryMessage = "Error parsing the query. QueryParameters not created."; } return true; } if(q.toDate){ if(logEntry.getTime() > q.toDateValue){ return false; } } if(q.fromDate){ if(logEntry.getTime() < q.fromDateValue){ return false; } } if(q.request){ if(!arrayContains(q.requestValues, logEntry.getServletName())){ return false; } } if(q.response){ if(!arrayContains(q.responseValues, logEntry.getAction())){ return false; } } if(q.person){ if(!logEntry.getName().toLowerCase().contains(q.personValue) && !logEntry.getId().toLowerCase().contains(q.personValue) && !logEntry.getEmail().toLowerCase().contains(q.personValue)){ return false; } } if(q.role){ if(!arrayContains(q.roleValues, logEntry.getRole())){ return false; } } if(q.timeTaken){ if(logEntry.getTimeTaken() < q.timeTakenValue){ return false; } } if(shouldExcludeLogEntry(logEntry)){ return false; } return true; }

Target:
public boolean filterLogs(ActivityLogEntry logEntry){ if(!logEntry.toShow()){ return false; } if(q == null){ if (this.queryMessage == null){ this.queryMessage = "Error parsing the query. QueryParameters not created."; } return true; } if(q.isToDateInQuery){ if(logEntry.getTime() > q.toDateValue){ return false; } } if(q.isFromDateInQuery){ if(logEntry.getTime() < q.fromDateValue){ return false; } } if(q.isRequestInQuery){ if(!arrayContains(q.requestValues, logEntry.getServletName())){ return false; } } if(q.isResponseInQuery){ if(!arrayContains(q.responseValues, logEntry.getAction())){ return false; } } if(q.isPersonInQuery){ if(!logEntry.getName().toLowerCase().contains(q.personValue) && !logEntry.getId().toLowerCase().contains(q.personValue) && !logEntry.getEmail().toLowerCase().contains(q.personValue)){ return false; } } if(q.isRoleInQuery){ if(!arrayContains(q.roleValues, logEntry.getRole())){ return false; } } if(q.isCutoffInQuery){ if(logEntry.getTimeTaken() < q.cutoffValue){ return false; } } if(shouldExcludeLogEntry(logEntry)){ return false; } return true; }
Source:
public static <T> Constructor<T> findConstructorFor(Class<T> type) { @SuppressWarnings("unchecked") final Constructor<T>[] constructors = (Constructor<T>[]) type.getDeclaredConstructors(); List<Constructor<T>> annotatedConstructors = Stream.of(constructors) .filter(c -> c.isAnnotationPresent(JdbiConstructor.class)) .collect(Collectors.toList()); if (annotatedConstructors.size() > 1) { throw new IllegalArgumentException(type + " must have at most one constructor annotated @JdbiConstructor"); } else if (annotatedConstructors.size() == 1) { return annotatedConstructors.get(0); } annotatedConstructors = Stream.of(constructors) .filter(c -> c.isAnnotationPresent(ConstructorProperties.class)) .collect(Collectors.toList()); if (annotatedConstructors.size() > 1) { throw new IllegalArgumentException(type + " must have at most one constructor annotated @ConstructorProperties"); } else if (annotatedConstructors.size() == 1) { return annotatedConstructors.get(0); } if (constructors.length != 1) { throw new IllegalArgumentException(type + " must have exactly one constructor, or specify it with @JdbiConstructor"); } return constructors[0]; }

Target:
public static <T> Constructor<T> findConstructorFor(Class<T> type) { @SuppressWarnings("unchecked") final Constructor<T>[] constructors = (Constructor<T>[]) type.getDeclaredConstructors(); List<Constructor<T>> annotatedConstructors = Stream.of(constructors) .filter(c -> c.isAnnotationPresent(JdbiConstructor.class)) .collect(Collectors.toList()); if (annotatedConstructors.size() > 1) { throw new IllegalArgumentException(type + " must have at most one constructor annotated @JdbiConstructor"); } else if (annotatedConstructors.size() == 1) { return annotatedConstructors.get(0); } annotatedConstructors = Stream.of(constructors) .filter(c -> c.isAnnotationPresent(ConstructorProperties.class)) .collect(Collectors.toList()); if (annotatedConstructors.size() > 1) { throw new IllegalArgumentException(type + " must have at most one constructor annotated @ConstructorProperties"); } else if (annotatedConstructors.size() == 1) { return annotatedConstructors.get(0); } if (constructors.length != 1) { throw new IllegalArgumentException(type + " must have exactly one constructor, or specify it with @JdbiConstructor or @ConstructorProperties"); } return constructors[0]; }