auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static void syncConfig() { maxGeneratedCubesPerTick = configuration.getInt("maxGeneratedCubesPerTick", Configuration.CATEGORY_GENERAL, 49*16, 1, Integer.MAX_VALUE, "The number of cubic chunks to generate per tick."); maxTimeSpentGeneratingCubesPerTick = configuration.getInt("maxTimeSpentGeneratingCubesPerTick", Configuration.CATEGORY_GENERAL, 50, 1, Integer.MAX_VALUE, "The maximum amount of time in milliseconds per tick to spend generating chunks."); verticalCubeLoadDistance = configuration.getInt("verticalCubeLoadDistance", Configuration.CATEGORY_GENERAL, 8, 2, 32, "Similar to Minecraft's view distance, only for vertical chunks."); worldHeightLowerBound = configuration.getInt("worldHeightLowerBound", Configuration.CATEGORY_GENERAL, -4096, -8388608, 0, "The lower boundary on the world. Blocks will not generate or load below this point."); worldHeightUpperBound = configuration.getInt("worldHeightUpperBound", Configuration.CATEGORY_GENERAL, 4096, 256, 8388608, "The upper boundary on the world. Blocks will not generate or load above this point."); if (configuration.hasChanged()) configuration.save(); }

Target:
static void syncConfig() { maxGeneratedCubesPerTick = configuration.getInt("maxGeneratedCubesPerTick", Configuration.CATEGORY_GENERAL, 49*16, 1, Integer.MAX_VALUE, "The number of cubic chunks to generate per tick."); lightingTickBudget = configuration.getInt("lightingTickBudget", Configuration.CATEGORY_GENERAL, 10, 1, Integer.MAX_VALUE, "The maximum amount of time in milliseconds per tick to spend performing lighting calculations."); verticalCubeLoadDistance = configuration.getInt("verticalCubeLoadDistance", Configuration.CATEGORY_GENERAL, 8, 2, 32, "Similar to Minecraft's view distance, only for vertical chunks."); worldHeightLowerBound = configuration.getInt("worldHeightLowerBound", Configuration.CATEGORY_GENERAL, -4096, AddressTools.MIN_BLOCK_Y, 0, "The lower boundary on the world. Blocks will not generate or load below this point."); worldHeightUpperBound = configuration.getInt("worldHeightUpperBound", Configuration.CATEGORY_GENERAL, 4096, 256, AddressTools.MAX_BLOCK_Y, "The upper boundary on the world. Blocks will not generate or load above this point."); if (configuration.hasChanged()) configuration.save(); }
Source:
protected Optional<Property> computeRemovedProperty(String name) { String schema = getSchema().getName(); String originalXpath = collectPath(new Path("/")).append(name).toString().substring(1); String xpath = originalXpath; if (xpath.indexOf('[') != -1) { xpath = NON_CANON_INDEX.matcher(xpath).replaceAll("*"); } SchemaManager schemaManager = Framework.getService(SchemaManager.class); if (schemaManager.isPropertyRemoved(schema, xpath)) { String fallback = schemaManager.getRemovedPropertyFallback(schema, xpath); Property property; if (fallback == null) { property = new RemovedProperty(this, name); } else { Matcher matcher = NON_CANON_INDEX.matcher(originalXpath); while (matcher.find()) { fallback = fallback.replaceFirst("\\*", matcher.group(0)); } Property fallbackProperty; int i = fallback.lastIndexOf("[-1]"); if (i != -1) { fallbackProperty = get(fallback.substring(i + 5)); } else { fallbackProperty = resolvePath('/' + fallback); } property = new RemovedProperty(this, name, fallbackProperty); } return Optional.of(property); } return Optional.empty(); }

Target:
protected Property computeRemovedProperty(String name) { String schema = getSchema().getName(); String originalXpath = collectPath(new Path("/")).append(name).toString().substring(1); String xpath; if (originalXpath.indexOf('[') != -1) { xpath = NON_CANON_INDEX.matcher(originalXpath).replaceAll("*"); } else { xpath = originalXpath; } SchemaManager schemaManager = Framework.getService(SchemaManager.class); PropertyDeprecationHandler removedProperties = schemaManager.getRemovedProperties(); if (!removedProperties.isMarked(schema, xpath)) { return null; } String fallback = removedProperties.getFallback(schema, xpath); if (fallback == null) { return new RemovedProperty(this, name); } Matcher matcher = NON_CANON_INDEX.matcher(originalXpath); while (matcher.find()) { fallback = fallback.replaceFirst("\\*", matcher.group(0)); } Property fallbackProperty; int i = fallback.lastIndexOf("[-1]"); if (i != -1) { fallbackProperty = get(fallback.substring(i + 5)); } else { fallbackProperty = resolvePath('/' + fallback); } return new RemovedProperty(this, name, fallbackProperty); }
Source:
private HtmlForm addAxis(String axis) throws Exception { HtmlPage page = wc.getPage(p, "configure"); HtmlForm form = page.getFormByName("config"); j.getButtonByCaption(form, "Add axis").click(); page.getAnchorByText(axis).click(); Thread.sleep(300); return form; }

Target:
private HtmlForm addAxis(String axis) throws Exception { HtmlPage page = wc.getPage(p, "configure"); HtmlForm form = page.getFormByName("config"); j.getButtonByCaption(form, "Add axis").click(); page.getAnchorByText(axis).click(); waitForInput(form); return form; }
Source:
public ConsumerDTO setFacts(Map<String, String> facts) { this.facts = facts; return this; }

Target:
public ConsumerDTO setFacts(Map<String, String> facts) { if (facts != null) { if (this.facts == null) { this.facts = new HashMap<String, String>(); } else { this.facts.clear(); } this.facts.putAll(facts); } else { this.facts = null; } return this; }
Source:
public void findAll() throws Exception { List<AuthEntry> expexted = Lists.newArrayList(new AuthEntry(CREDENTIAL_TYPE, SIM_1, USIM_2)); List<AuthEntry> items = catalog.findAll(); assertThat(items, deepEquals(expexted)); }

Target:
public void findAll() throws Exception { List<AuthEntry> want = Lists.newArrayList(new AuthEntry(CREDENTIAL_TYPE, SIM_1, USIM_2)); List<AuthEntry> items = catalog.findAll(); assertThat(items, deepEquals(want)); }
Source:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { hash = in.readInt(); int len = in.readInt(); data = new byte[len]; in.readFully((byte[]) data); }

Target:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { hash = in.readInt(); int len = in.readInt(); byte[] d = new byte[len]; IO.readFully(in, d, 0, len); data = d; }
Source:
public void clockProvider() { ValidatorFactory validatorFactory = Validation.byDefaultProvider() .configure() .clockProvider( new FixedClockProvider( ZonedDateTime.now() ) ) .buildValidatorFactory(); Validator validator = validatorFactory.getValidator(); }

Target:
public void clockProvider() { ValidatorFactory validatorFactory = Validation.byDefaultProvider() .configure() .clockProvider( new FixedClockProvider( ZonedDateTime.of( 2016, 6, 15, 0, 0, 0, 0, ZoneId.of( "Europe/Paris" ) ) ) ) .buildValidatorFactory(); Validator validator = validatorFactory.getValidator(); }
Source:
public void truncate() throws ConnectException { try { String oldLogFile = logFile + ".1"; storage.delete(oldLogFile); storage.commit(logFile, oldLogFile); close(); } catch (IOException e) { throw new ConnectException(e); } finally { close(); } }

Target:
public void truncate() throws ConnectException { try { String oldLogFile = logFile + ".1"; storage.delete(oldLogFile); storage.commit(logFile, oldLogFile); } finally { close(); } }
Source:
public static Builder of(final File jbossHome) { return new Builder(jbossHome); }

Target:
public static Builder of(final File jbossHome) { if (jbossHome == null) { throw EmbeddedLogger.ROOT_LOGGER.nullVar("jbossHome"); } return new Builder(jbossHome); }
Source:
private void logLoadingFromStorageFailed(Resource resource, IStorage storage, Exception e) { EMFCompareIDEPlugin .getDefault() .getLog() .log(new Status( IStatus.ERROR, EMFCompareIDEPlugin.PLUGIN_ID, EMFCompareIDEMessages .getString( "StorageResourceWrapper.failToLoad", resource.getURI().toString(), storage.getName()), e)); }

Target:
private void logLoadingFromStorageFailed(Resource resource, IStorage storage, Exception e) { Status errorStatus = new Status(IStatus.ERROR, EMFCompareIDEPlugin.PLUGIN_ID, EMFCompareIDEMessages .getString("StorageResourceWrapper.failToLoad", resource.getURI().toString(), storage .getName()), e); EMFCompareIDEPlugin.getDefault().getLog().log(errorStatus); }
Source:
private static Statement rhsAssignZeroValue(VariableDeclarationExpr vdExpr) { VariableDeclarationExpr exprCopy = (VariableDeclarationExpr) vdExpr.clone(); List<VariableDeclarator> vars = exprCopy.getVars(); if (vars.size() > 1) { return null; } VariableDeclarator vd = vars.get(0); Type type = exprCopy.getType(); if (type instanceof PrimitiveType) { switch (((PrimitiveType) type).getType()) { case Boolean: vd.setInit(new BooleanLiteralExpr(false)); break; case Byte: vd.setInit(new IntegerLiteralExpr("0")); break; case Char: vd.setInit(new CharLiteralExpr("")); break; case Short: vd.setInit(new IntegerLiteralExpr("0")); break; case Int: vd.setInit(new IntegerLiteralExpr("0")); break; case Long: vd.setInit(new LongLiteralExpr("0")); break; case Float: vd.setInit(new DoubleLiteralExpr("0")); break; case Double: vd.setInit(new DoubleLiteralExpr("0")); break; } } else { vd.setInit(new NullLiteralExpr()); } ExpressionStmt newStmt = new ExpressionStmt(exprCopy); exprCopy.setParentNode(newStmt); return newStmt; }

Target:
private static Statement rhsAssignZeroValue(VariableDeclarationExpr vdExpr) { Type type = vdExpr.getType(); if (type instanceof PrimitiveType) { switch (((PrimitiveType) type).getType()) { case Boolean: return rhsAssignWithValue(vdExpr, "false"); case Char: return rhsAssignWithValue(vdExpr, ""); default: return rhsAssignWithValue(vdExpr, "0"); } } return rhsAssignWithValue(vdExpr, null); }
Source:
public VnicProfileModel(IModel sourceModel, Version dcCompatibilityVersion, boolean customPropertiesVisible, Guid dcId, Guid defaultQosId) { this.sourceModel = sourceModel; this.customPropertiesVisible = customPropertiesVisible; this.defaultQosId = defaultQosId; setName(new EntityModel<String>()); setNetwork(new ListModel<Network>()); setNetworkQoS(new ListModel<NetworkQoS>()); setNetworkFilter(new ListModel<NetworkFilter>()); setPortMirroring(new EntityModel<Boolean>()); setPassthrough(new EntityModel<Boolean>()); setMigratable(new EntityModel<Boolean>()); setCustomPropertySheet(new KeyValueModel()); EntityModel<Boolean> publicUse = new EntityModel<>(); publicUse.setEntity(true); setPublicUse(publicUse); setDescription(new EntityModel<String>()); getNetwork().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { Network network = getNetwork().getSelectedItem(); boolean portMirroringAllowed = network == null || !network.isExternal(); if (!portMirroringAllowed) { getPortMirroring().setEntity(false); getPortMirroring().setChangeProhibitionReason(ConstantsManager.getInstance() .getConstants() .portMirroringNotSupportedExternalNetworks()); } getPortMirroring().setIsChangeable(portMirroringAllowed); } }); initPassthroughChangeListener(); initCustomPropertySheet(dcCompatibilityVersion); initNetworkQoSList(dcId); initNetworkFilterList(dcCompatibilityVersion); initCommands(); }

Target:
public VnicProfileModel(IModel sourceModel, Version dcCompatibilityVersion, boolean customPropertiesVisible, Guid dcId, Guid defaultQosId) { this.sourceModel = sourceModel; this.customPropertiesVisible = customPropertiesVisible; this.defaultQosId = defaultQosId; setName(new EntityModel<String>()); setNetwork(new ListModel<Network>()); setNetworkQoS(new ListModel<NetworkQoS>()); setNetworkFilter(new ListModel<NetworkFilter>()); setPortMirroring(new EntityModel<Boolean>()); setPassthrough(new EntityModel<Boolean>(false)); setMigratable(new EntityModel<Boolean>(false)); setCustomPropertySheet(new KeyValueModel()); EntityModel<Boolean> publicUse = new EntityModel<>(); publicUse.setEntity(true); setPublicUse(publicUse); setDescription(new EntityModel<String>()); getNetwork().getSelectedItemChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { Network network = getNetwork().getSelectedItem(); boolean portMirroringAllowed = network == null || !network.isExternal(); if (!portMirroringAllowed) { getPortMirroring().setEntity(false); getPortMirroring().setChangeProhibitionReason(ConstantsManager.getInstance() .getConstants() .portMirroringNotSupportedExternalNetworks()); } getPortMirroring().setIsChangeable(portMirroringAllowed); } }); initPassthroughChangeListener(); initCustomPropertySheet(dcCompatibilityVersion); initNetworkQoSList(dcId); initNetworkFilterList(dcCompatibilityVersion); initCommands(); }
Source:
public ILaunchConfiguration[] getApplicableLaunchConfigurations(String[] types, IResource resource) { ArrayList<ILaunchConfiguration> list = new ArrayList<>(); try { if(resource != null) { String[] ctypes = types; if(ctypes == null) { ctypes = getApplicableConfigurationTypes(resource); } HashSet<String> typeset = new HashSet<>(ctypes.length); Collections.addAll(typeset, ctypes); IResource[] resrcs = null; for (ILaunchConfiguration configuration : filterConfigs(getLaunchManager().getLaunchConfigurations())) { if(typeset.contains(configuration.getType().getIdentifier()) && acceptConfiguration(configuration)) { resrcs = configuration.getMappedResources(); if (resrcs != null) { for (IResource resrc : resrcs) { if (resource.equals(resrc) || resource.getFullPath().isPrefixOf(resrc.getFullPath())) { list.add(configuration); break; } } } else { list.add(configuration); } } } } } catch (CoreException e) { list.clear(); DebugPlugin.log(e); } return list.toArray(new ILaunchConfiguration[list.size()]); }

Target:
public ILaunchConfiguration[] getApplicableLaunchConfigurations(String[] types, IResource resource) { ArrayList<ILaunchConfiguration> list = new ArrayList<>(); try { if(resource != null) { String[] ctypes = types; if(ctypes == null) { ctypes = getApplicableConfigurationTypes(resource); } HashSet<String> typeset = new HashSet<>(ctypes.length); Collections.addAll(typeset, ctypes); for (ILaunchConfiguration configuration : filterConfigs(getLaunchManager().getLaunchConfigurations())) { if(typeset.contains(configuration.getType().getIdentifier()) && acceptConfiguration(configuration)) { IResource[] resrcs = configuration.getMappedResources(); if (resrcs != null) { for (IResource res : resrcs) { if (resource.equals(res) || resource.getFullPath().isPrefixOf(res.getFullPath())) { list.add(configuration); break; } } } else { list.add(configuration); } } } } } catch (CoreException e) { list.clear(); DebugPlugin.log(e); } return list.toArray(new ILaunchConfiguration[list.size()]); }
Source:
public void _onRequestSuggestions(final Request req, final Callback cb) { RpcStatus.hide(new Runnable() { @Override public void run() { AccountApi.suggest(req.getQuery(), req.getLimit(), new GerritCallback<JsArray<AccountInfo>>() { @Override public void onSuccess(JsArray<AccountInfo> in) { List<AccountSuggestion> r = new ArrayList<>(in.length()); for (AccountInfo p : Natives.asList(in)) { r.add(new AccountSuggestion(p)); } cb.onSuggestionsReady(req, new Response(r)); } }); } }); }

Target:
public void _onRequestSuggestions(final Request req, final Callback cb) { AccountApi.suggest(req.getQuery(), req.getLimit(), new GerritCallback<JsArray<AccountInfo>>() { @Override public void onSuccess(JsArray<AccountInfo> in) { List<AccountSuggestion> r = new ArrayList<>(in.length()); for (AccountInfo p : Natives.asList(in)) { r.add(new AccountSuggestion(p)); } cb.onSuggestionsReady(req, new Response(r)); } }); }
Source:
public void draw(int startX, int startY) { if (!slot.getHasStack()) { super.draw(startX, startY); } GlStateManager.pushMatrix(); GlStateManager.disableLighting(); GlStateManager.disableDepth(); GlStateManager.enableBlend(); String directionString = getDirectionString(); if (!directionString.isEmpty()){ FontRenderer fontRenderer = manager.minecraft.fontRenderer; fontRenderer.drawStringWithShadow(getDirectionString(), xPos + startX + 5, yPos + startY + 4, ColourProperties.INSTANCE.get("gui.screen")); } GlStateManager.color(1.0F, 1.0F, 1.0F, 0.5F); TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); textureManager.bindTexture(manager.gui.textureFile); manager.gui.drawTexturedModalRect(xPos + startX, yPos + startY, 206, 0, 16, 16); GlStateManager.disableBlend(); GlStateManager.enableDepth(); GlStateManager.enableLighting(); GlStateManager.popMatrix(); }

Target:
public void draw(int startX, int startY) { if (!slot.getHasStack()) { super.draw(startX, startY); } GlStateManager.disableLighting(); GlStateManager.disableDepth(); GlStateManager.enableBlend(); String directionString = getDirectionString(); if (!directionString.isEmpty()){ FontRenderer fontRenderer = manager.minecraft.fontRenderer; fontRenderer.drawStringWithShadow(getDirectionString(), xPos + startX + 5, yPos + startY + 4, ColourProperties.INSTANCE.get("gui.screen")); } GlStateManager.color(1.0F, 1.0F, 1.0F, 0.5F); TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); textureManager.bindTexture(manager.gui.textureFile); manager.gui.drawTexturedModalRect(xPos + startX, yPos + startY, 206, 0, 16, 16); GlStateManager.disableBlend(); GlStateManager.enableDepth(); GlStateManager.enableLighting(); }
Source:
public void createImportFileAudit(RchImportFacilitator rchImportFacilitator) throws RchFileManipulationException { Long state = rchImportFacilitator.getStateId(); LocalDate importDate = rchImportFacilitator.getImportDate(); RchUserType rchUserType = rchImportFacilitator.getUserType(); List<RchImportFacilitator> rchImportFacilitator1 = rchImportFacilitatorDataService.getByStateIdAndImportDateAndUserType(state, importDate, rchUserType); LOGGER.info("list size {}", rchImportFacilitator1.size()); if (rchImportFacilitator.getFileName() == null) { throw new RchFileManipulationException("Invalid file name"); } else if (rchImportFacilitator1.size() != 0) { LOGGER.debug("A record already present for the same state: and today's date: {}.", state, importDate); } else { rchImportFacilitatorDataService.create(rchImportFacilitator); } }

Target:
public void createImportFileAudit(RchImportFacilitator rchImportFacilitator) throws RchFileManipulationException { Long state = rchImportFacilitator.getStateId(); LocalDate importDate = rchImportFacilitator.getImportDate(); RchUserType rchUserType = rchImportFacilitator.getUserType(); List<RchImportFacilitator> rchImportFacilitator1 = rchImportFacilitatorDataService.getByStateIdAndImportDateAndUserType(state, importDate, rchUserType); LOGGER.info("list size {}", rchImportFacilitator1.size()); if (rchImportFacilitator.getFileName() == null) { throw new RchFileManipulationException("Invalid file name"); } else if (rchImportFacilitator1.size() != 0) { LOGGER.error("A record already present for the same state: , today's date: and userType: {}.", state, importDate, rchUserType.toString()); } else { rchImportFacilitatorDataService.create(rchImportFacilitator); } }
Source:
public RetryHandler(Forklift forklift, File dir) { this.dir = dir; this.forklift = forklift; this.mapper = new ObjectMapper().registerModule(new JavaTimeModule()) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); this.executor = Executors.newScheduledThreadPool(1); cleanup = new Consumer<RetryMessage>() { @Override public void accept(RetryMessage msg) { log.info("Cleaning up persistent file {}", msg.getPersistedPath()); final File f = new File(msg.getPersistedPath()); if (f.exists()) f.delete(); } }; new FileScanner(dir).scan().stream() .filter(result -> result.getFilename().startsWith("retry") && result.getFilename().endsWith(".msg")) .forEach(result -> { try { final RetryMessage retryMessage = mapper.readValue(new File(dir, result.getFilename()), RetryMessage.class); executor.schedule(new RetryRunnable(retryMessage, forklift.getConnector(), cleanup), Long.parseLong(Integer.toString(Integer.parseInt(retryMessage.getProperties().get("forklift-retry-timeout")))), TimeUnit.SECONDS); } catch (Exception e) { log.error("Unable to read file {}", result.getFilename()); } }); }

Target:
public RetryHandler(Forklift forklift, File dir) { this.dir = dir; this.forklift = forklift; this.mapper = new ObjectMapper().registerModule(new JavaTimeModule()) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); this.executor = Executors.newScheduledThreadPool(1); cleanup = (msg) -> { log.info("Cleaning up persistent file {}", msg.getPersistedPath()); final File f = new File(msg.getPersistedPath()); if (f.exists()) f.delete(); }; new FileScanner(dir).scan().stream() .filter(result -> result.getFilename().startsWith("retry") && result.getFilename().endsWith(".msg")) .forEach(result -> { try { final RetryMessage retryMessage = mapper.readValue(new File(dir, result.getFilename()), RetryMessage.class); executor.schedule(new RetryRunnable(retryMessage, forklift.getConnector(), cleanup), Long.parseLong(Integer.toString(Integer.parseInt(retryMessage.getProperties().get("forklift-retry-timeout")))), TimeUnit.SECONDS); } catch (Exception e) { log.error("Unable to read file {}", result.getFilename()); } }); }
Source:
public Optional<PassengerData> build(DataView container) throws InvalidDataException { return Optional.absent(); }

Target:
public Optional<PassengerData> build(DataView container) throws InvalidDataException { PassengerData passengerData = create(); passengerData.set(Keys.BASE_VEHICLE, getData(container, Keys.BASE_VEHICLE)); passengerData.set(Keys.VEHICLE, getData(container, Keys.VEHICLE)); return Optional.of(passengerData); }
Source:
public void roundRobinAllocationTest() throws InjectionException { final int numExecutors = 4; final int numOperatorChains = 10; final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(NumExecutors.class, 4+""); final Injector injector = Tang.Factory.getTang().newInjector(jcb.build()); final ExecutorListProvider executorListProvider = injector.getInstance(ExecutorListProvider.class); final DAG<OperatorChain> operatorChainDAG = new AdjacentListDAG<>(); final OperatorChainAllocator operatorChainAllocator = injector.getInstance(DefaultOperatorChainAllocatorImpl.class); OperatorChain src = injector.getInstance(OperatorChain.class); operatorChainDAG.addVertex(src); for (int i = 1; i < numOperatorChains; i++) { final Injector newInjector = Tang.Factory.getTang().newInjector(); final OperatorChain dest = newInjector.getInstance(OperatorChain.class); operatorChainDAG.addVertex(dest); operatorChainDAG.addEdge(src, dest); src = dest; } operatorChainAllocator.allocate(operatorChainDAG); final Iterator<OperatorChain> operatorChainIterator = GraphUtils.topologicalSort(operatorChainDAG); final List<MistExecutor> executors = executorListProvider.getExecutors(); int index = 0; while (operatorChainIterator.hasNext()) { final OperatorChain operatorChain = operatorChainIterator.next(); Assert.assertEquals("Assigned executor should be " + executors.get(index).getIdentifier(), executors.get(index), operatorChain.getExecutor()); index = (index + 1) % numExecutors; } }

Target:
public void roundRobinAllocationTest() throws InjectionException { final int numExecutors = 4; final int numOperatorChains = 10; final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); jcb.bindNamedParameter(NumExecutors.class, Integer.toString(4)); final Injector injector = Tang.Factory.getTang().newInjector(jcb.build()); final ExecutorListProvider executorListProvider = injector.getInstance(ExecutorListProvider.class); final DAG<OperatorChain> operatorChainDAG = new AdjacentListDAG<>(); final OperatorChainAllocator operatorChainAllocator = injector.getInstance(DefaultOperatorChainAllocatorImpl.class); OperatorChain src = injector.getInstance(OperatorChain.class); operatorChainDAG.addVertex(src); for (int i = 1; i < numOperatorChains; i++) { final Injector newInjector = Tang.Factory.getTang().newInjector(); final OperatorChain dest = newInjector.getInstance(OperatorChain.class); operatorChainDAG.addVertex(dest); operatorChainDAG.addEdge(src, dest); src = dest; } operatorChainAllocator.allocate(operatorChainDAG); final Iterator<OperatorChain> operatorChainIterator = GraphUtils.topologicalSort(operatorChainDAG); final List<MistExecutor> executors = executorListProvider.getExecutors(); int index = 0; while (operatorChainIterator.hasNext()) { final OperatorChain operatorChain = operatorChainIterator.next(); Assert.assertEquals("Assigned executor should be " + executors.get(index).getIdentifier(), executors.get(index), operatorChain.getExecutor()); index = (index + 1) % numExecutors; } }
Source:
public String executeCommand(String command) throws IOException { command = command.endsWith("\r\n") ? command : command + "\r\n"; byte b[] = command.getBytes(Sage.BYTE_CHARSET); return executeCommand(b, 0, b.length); }

Target:
public String executeCommand(String command) throws IOException { command = command.endsWith("\r\n") ? command : (command + "\r\n"); byte b[] = command.getBytes(Sage.BYTE_CHARSET); return executeCommand(b, 0, b.length); }
Source:
public static <T extends UnspecificPlugin> Collection<T> getPlugins(Class<T> clazz) { final String kInternalClassesPrefix = "net.xeoh.plugins."; final short kInternalClassesCount = 4; ArrayList<T> result; PluginType type = UnspecificPlugin.typeOf(clazz); PluginManagerUtil pluginLoader = getPluginLoader(type); Collection<Plugin> plugins = pluginLoader.getPlugins(Plugin.class); result = new ArrayList<>(plugins.size() - kInternalClassesCount); for (Plugin implementation : plugins) { if (implementation.getClass().getName().startsWith(kInternalClassesPrefix)) { continue; } try { T plugin = (T) UnspecificPlugin.create(type, implementation); plugin.configure(getPluginConfiguration()); result.add(plugin); } catch (NoSuchMethodException | SecurityException e) { if (logger.isWarnEnabled()) { logger.warn( "Bad implementation of " + type.getName() + " plugin " + implementation.getClass().getName(), e); } } } return result; }

Target:
public static <T extends UnspecificPlugin> Collection<T> getPlugins(Class<T> clazz) { final String internalClassesPrefix = "net.xeoh.plugins."; final short internalClassesCount = 4; ArrayList<T> result; PluginType type = UnspecificPlugin.typeOf(clazz); PluginManagerUtil pluginLoader = getPluginLoader(type); Collection<Plugin> plugins = pluginLoader.getPlugins(Plugin.class); result = new ArrayList<>(plugins.size() - internalClassesCount); for (Plugin implementation : plugins) { if (implementation.getClass().getName().startsWith(internalClassesPrefix)) { continue; } try { T plugin = (T) UnspecificPlugin.create(type, implementation); plugin.configure(getPluginConfiguration()); result.add(plugin); } catch (NoSuchMethodException | SecurityException e) { if (logger.isWarnEnabled()) { logger.warn( "Bad implementation of " + type.getName() + " plugin " + implementation.getClass().getName(), e); } } } return result; }
Source:
public void onListItemClick(ListView l, View v, int position, long id) { if (!carrierConfig.getBoolean("config_fdn_direct_dial")) { editSelected(position); } else { SelectionPopUpMenu menu = new SelectionPopUpMenu(getApplicationContext(), v, position); menu.showPopUp(); } }

Target:
public void onListItemClick(ListView l, View v, int position, long id) { if (!mFdnDialDirectlySupported) { editSelected(position); } else { SelectionPopUpMenu menu = new SelectionPopUpMenu(this, v, position); menu.showPopUp(); } }
Source:
void checkWhitespaceAroundColon(SwitchCaseContext ctx) { Token left = null; Token right = null; Token colon = null; if (ctx.caseLabel() != null) { left = ctx.caseLabel().caseItemList().getStop(); ParseTree rightChild = ctx.getChild(1); right = rightChild instanceof StatementsContext ? ((StatementsContext) rightChild).getStart() : ((TerminalNodeImpl) rightChild).getSymbol(); colon = ((TerminalNodeImpl) ctx.caseLabel().getChild(2)).getSymbol(); } else if (ctx.defaultLabel() != null) { left = ((TerminalNodeImpl) ctx.defaultLabel().getChild(0)).getSymbol(); ParseTree rightChild = ctx.getChild(1); right = rightChild instanceof StatementsContext ? ((StatementsContext) rightChild).getStart() : ((TerminalNodeImpl) rightChild).getSymbol(); colon = ((TerminalNodeImpl) ctx.defaultLabel().getChild(1)).getSymbol(); } else { return; } verifyColonLeftAssociation(left, right, colon); }

Target:
void checkWhitespaceAroundColon(SwitchCaseContext ctx) { Token left = null; Token right = null; Token colon = null; if (ctx.caseLabel() != null) { left = ctx.caseLabel().caseItemList().getStop(); ParseTree rightChild = ctx.getChild(1); right = rightChild instanceof StatementsContext ? ((StatementsContext) rightChild).getStart() : ((TerminalNodeImpl) rightChild).getSymbol(); colon = ((TerminalNodeImpl) ctx.caseLabel().getChild(2)).getSymbol(); } else { left = ((TerminalNodeImpl) ctx.defaultLabel().getChild(0)).getSymbol(); ParseTree rightChild = ctx.getChild(1); right = rightChild instanceof StatementsContext ? ((StatementsContext) rightChild).getStart() : ((TerminalNodeImpl) rightChild).getSymbol(); colon = ((TerminalNodeImpl) ctx.defaultLabel().getChild(1)).getSymbol(); } verifyColonLeftAssociation(left, right, colon); }
Source:
public List<ISuite> runSuitesLocally() { if (m_suites.isEmpty()) { this.m_hasTests = false; error("No test suite found. Nothing to run"); usage(); return Collections.emptyList(); } SuiteRunnerMap suiteRunnerMap = new SuiteRunnerMap(); if (m_suites.get(0).getVerbose() >= 2) { Version.displayBanner(); } for (XmlSuite xmlSuite : m_suites) { createSuiteRunners(suiteRunnerMap, xmlSuite); } if (m_suiteThreadPoolSize == 1 && !m_randomizeSuites) { for (XmlSuite xmlSuite : m_suites) { runSuitesSequentially(xmlSuite, suiteRunnerMap, getVerbose(xmlSuite), getDefaultSuiteName()); } return Lists.newArrayList(suiteRunnerMap.values()); } DynamicGraph<ISuite> suiteGraph = new DynamicGraph<>(); for (XmlSuite xmlSuite : m_suites) { populateSuiteGraph(suiteGraph, suiteRunnerMap, xmlSuite); } IThreadWorkerFactory<ISuite> factory = new SuiteWorkerFactory(suiteRunnerMap, 0 , getDefaultSuiteName()); GraphThreadPoolExecutor<ISuite> pooledExecutor = new GraphThreadPoolExecutor<>("suites", suiteGraph, factory, m_suiteThreadPoolSize, m_suiteThreadPoolSize, Integer.MAX_VALUE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); Utils.log("TestNG", 2, "Starting executor for all suites"); pooledExecutor.run(); try { pooledExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); pooledExecutor.shutdownNow(); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); error("Error waiting for concurrent executors to finish " + handled.getMessage()); } return Lists.newArrayList(suiteRunnerMap.values()); }

Target:
public List<ISuite> runSuitesLocally() { if (m_suites.isEmpty()) { error("No test suite found. Nothing to run"); usage(); return Collections.emptyList(); } SuiteRunnerMap suiteRunnerMap = new SuiteRunnerMap(); if (m_suites.get(0).getVerbose() >= 2) { Version.displayBanner(); } for (XmlSuite xmlSuite : m_suites) { createSuiteRunners(suiteRunnerMap, xmlSuite); } if (m_suiteThreadPoolSize == 1 && !m_randomizeSuites) { for (XmlSuite xmlSuite : m_suites) { runSuitesSequentially(xmlSuite, suiteRunnerMap, getVerbose(xmlSuite), getDefaultSuiteName()); } return Lists.newArrayList(suiteRunnerMap.values()); } DynamicGraph<ISuite> suiteGraph = new DynamicGraph<>(); for (XmlSuite xmlSuite : m_suites) { populateSuiteGraph(suiteGraph, suiteRunnerMap, xmlSuite); } IThreadWorkerFactory<ISuite> factory = new SuiteWorkerFactory(suiteRunnerMap, 0 , getDefaultSuiteName()); GraphThreadPoolExecutor<ISuite> pooledExecutor = new GraphThreadPoolExecutor<>("suites", suiteGraph, factory, m_suiteThreadPoolSize, m_suiteThreadPoolSize, Integer.MAX_VALUE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); Utils.log("TestNG", 2, "Starting executor for all suites"); pooledExecutor.run(); try { pooledExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); pooledExecutor.shutdownNow(); } catch (InterruptedException handled) { Thread.currentThread().interrupt(); error("Error waiting for concurrent executors to finish " + handled.getMessage()); } return Lists.newArrayList(suiteRunnerMap.values()); }
Source:
private String getSignature(Method method) { StringBuilder sb = new StringBuilder(); Class<?> returnType = method.getReturnType(); if (returnType != null) { sb.append(returnType.getName()).append('#'); } sb.append(method.getName()); Class<?>[] parameters = method.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { sb.append(i == 0 ? ":" : ",").append(parameters[i].getName()); } return sb.toString(); }

Target:
private String getSignature(Method method) { StringBuilder sb = new StringBuilder(); Class<?> returnType = method.getReturnType(); if (returnType != null) { sb.append(returnType.getName()).append('#'); } sb.append(method.getName()); Class<?>[] parameters = method.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { sb.append(i == 0 ? ':' : ',').append(parameters[i].getName()); } return sb.toString(); }
Source:
protected void setUp() throws Exception { System.out.println("TEST-SETUP: " + getName()); super.setUp(); workspace = ResourcesPlugin.getWorkspace(); setAutobuilding(true); Hashtable<String, String> options = JavaCore.getOptions(); options.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ".svn/"); JavaCore.setOptions(options); InstanceScope.INSTANCE.getNode(LaunchingPlugin.ID_PLUGIN).put( JavaRuntime.PREF_STRICTLY_COMPATIBLE_JRE_NOT_AVAILABLE, JavaCore.IGNORE); projectRefreshJob = MavenPluginActivator.getDefault().getProjectManagerRefreshJob(); projectRefreshJob.sleep(); downloadSourcesJob = ((BuildPathManager) MavenJdtPlugin.getDefault().getBuildpathManager()).getDownloadSourcesJob(); downloadSourcesJob.sleep(); mavenConfiguration = MavenPlugin.getMavenConfiguration(); oldUserSettingsFile = mavenConfiguration.getUserSettingsFile(); File settings = new File("settings.xml").getCanonicalFile(); if(settings.canRead()) { String userSettingsFile = settings.getAbsolutePath(); System.out.println("Setting user settings file: " + userSettingsFile); mavenConfiguration.setUserSettingsFile(userSettingsFile); } ArtifactRepository localRepository = MavenPlugin.getMaven().getLocalRepository(); if(localRepository != null) { repo = new File(localRepository.getBasedir()); } else { fail("Cannot determine local repository path"); } LifecycleMappingFactory.setUseDefaultLifecycleMappingMetadataSource(true); LifecycleMappingFactory.setDefaultLifecycleMappingMetadataSource(null); WorkspaceHelpers.cleanWorkspace(); FilexWagon.setRequestFailPattern(null); FilexWagon.setRequestFilterPattern(null, true); }

Target:
protected void setUp() throws Exception { System.out.println("TEST-SETUP: " + getName()); super.setUp(); workspace = ResourcesPlugin.getWorkspace(); setAutoBuilding(false); Hashtable<String, String> options = JavaCore.getOptions(); options.put(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ".svn/"); JavaCore.setOptions(options); projectRefreshJob = MavenPluginActivator.getDefault().getProjectManagerRefreshJob(); projectRefreshJob.sleep(); downloadSourcesJob = ((BuildPathManager) MavenJdtPlugin.getDefault().getBuildpathManager()).getDownloadSourcesJob(); downloadSourcesJob.sleep(); mavenConfiguration = MavenPlugin.getMavenConfiguration(); oldUserSettingsFile = mavenConfiguration.getUserSettingsFile(); File settings = new File("settings.xml").getCanonicalFile(); if(settings.canRead()) { String userSettingsFile = settings.getAbsolutePath(); System.out.println("Setting user settings file: " + userSettingsFile); mavenConfiguration.setUserSettingsFile(userSettingsFile); } ArtifactRepository localRepository = MavenPlugin.getMaven().getLocalRepository(); if(localRepository != null) { repo = new File(localRepository.getBasedir()); } else { fail("Cannot determine local repository path"); } LifecycleMappingFactory.setUseDefaultLifecycleMappingMetadataSource(true); LifecycleMappingFactory.setDefaultLifecycleMappingMetadataSource(null); WorkspaceHelpers.cleanWorkspace(); FilexWagon.setRequestFailPattern(null); FilexWagon.setRequestFilterPattern(null, true); }
Source:
public CopyRatioState.SegmentMeans estimateSegmentMeans() { final List<Double> means = new ArrayList<>(numSegments); for (int segment = 0; segment < numSegments; segment++) { means.add(new Mean().evaluate(Doubles.toArray(getCoveragesInSegment(segment)))); } return new CopyRatioState.SegmentMeans(means); }

Target:
public CopyRatioState.SegmentMeans estimateSegmentMeans() { final List<Double> means = IntStream.range(0, numSegments).boxed() .map(s -> new Mean().evaluate(Doubles.toArray(getIndexedCoveragesInSegment(s).stream().map(IndexedCoverage::getCoverage).collect(Collectors.toList())))) .collect(Collectors.toList()); return new CopyRatioState.SegmentMeans(means); }
Source:
public IComplexNumber dotu(IComplexNDArray x, IComplexNDArray y) { return null; }

Target:
public IComplexNumber dotu(IComplexNDArray x, IComplexNDArray y) { throw new UnsupportedOperationException(); }
Source:
public List<InputSplit> getSplits(JobContext context) throws IOException { final Configuration configuration = context.getConfiguration(); BigQueryStorageClient client = getClient(configuration); BigQueryHelper bigQueryHelper; try { bigQueryHelper = getBigQueryHelper(configuration); } catch (GeneralSecurityException gse) { LOG.error("Failed to create BigQuery client", gse); throw new IOException("Failed to create BigQuery client", gse); } double skewLimit = configuration.getDouble(BigQueryConfiguration.SKEW_LIMIT_KEY, BigQueryConfiguration.SKEW_LIMIT_DEFAULT); Preconditions.checkArgument( skewLimit >= 1.0, BigQueryConfiguration.SKEW_LIMIT_KEY + " is less than 1, than not all records would be read. Exiting"); Table table = getTable(configuration, bigQueryHelper); ReadSession session = startSession(configuration, table, client); long numRows = table.getNumRows().longValue(); long limit = Math.round(skewLimit * numRows / session.getStreamsCount()); return session.getStreamsList().stream() .map( stream -> new DirectBigQueryInputSplit( stream.getName(), session.getAvroSchema().getSchema(), limit)) .collect(Collectors.toList()); }

Target:
public List<InputSplit> getSplits(JobContext context) throws IOException { final Configuration configuration = context.getConfiguration(); BigQueryStorageClient client = getClient(configuration); BigQueryHelper bigQueryHelper; try { bigQueryHelper = getBigQueryHelper(configuration); } catch (GeneralSecurityException gse) { throw new IOException("Failed to create BigQuery client", gse); } double skewLimit = configuration.getDouble( BigQueryConfiguration.SKEW_LIMIT_KEY, BigQueryConfiguration.SKEW_LIMIT_DEFAULT); Preconditions.checkArgument( skewLimit >= 1.0, "%s is less than 1; not all records would be read. Exiting", BigQueryConfiguration.SKEW_LIMIT_KEY); Table table = getTable(configuration, bigQueryHelper); ReadSession session = startSession(configuration, table, client); long numRows = table.getNumRows().longValue(); long limit = Math.round(skewLimit * numRows / session.getStreamsCount()); return session.getStreamsList().stream() .map( stream -> new DirectBigQueryInputSplit( stream.getName(), session.getAvroSchema().getSchema(), limit)) .collect(Collectors.toList()); }
Source:
private void saveEditingTargetsWithPrompt( String title, ArrayList<EditingTarget> editingTargets, final Command onCompleted, final Command onCancelled) { if (editingTargets.size() == 0) { onCompleted.execute(); } else if (editingTargets.size() == 1) { editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled); } else { ArrayList<UnsavedChangesTarget> unsavedTargets = new ArrayList<UnsavedChangesTarget>(); unsavedTargets.addAll(editingTargets); showUnsavedChangesDialog( title, unsavedTargets, new OperationWithInput<UnsavedChangesDialog.Result>() { @Override public void execute(UnsavedChangesDialog.Result result) { saveChanges(result.getSaveTargets(), onCompleted); } }, onCancelled); } }

Target:
private void saveEditingTargetsWithPrompt( String title, ArrayList<EditingTarget> editingTargets, final Command onCompleted, final Command onCancelled) { if (editingTargets.size() == 0) { onCompleted.execute(); } else if (editingTargets.size() == 1) { editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled); } else { ArrayList<UnsavedChangesTarget> unsavedTargets = new ArrayList<>(editingTargets); showUnsavedChangesDialog( title, unsavedTargets, new OperationWithInput<UnsavedChangesDialog.Result>() { @Override public void execute(UnsavedChangesDialog.Result result) { saveChanges(result.getSaveTargets(), onCompleted); } }, onCancelled); } }
Source:
public int compare(JudgmentCorrection correctionOne, JudgmentCorrection correctionTwo) { if (correctionOne.getCorrectedObjectClass() == correctionTwo.getCorrectedObjectClass()) { return compareChangeOperation(correctionOne.getChangeOperation(), correctionTwo.getChangeOperation()); } else if (correctionOne.getCorrectedObjectClass() == CommonCourtJudgment.class || correctionOne.getCorrectedObjectClass() == SupremeCourtJudgment.class) { return -1; } else if (correctionOne.getCorrectedObjectClass() == SupremeCourtChamber.class) { if (correctionTwo.getCorrectedObjectClass() == CommonCourtJudgment.class || correctionTwo.getCorrectedObjectClass() == SupremeCourtJudgment.class) { return 1; } else { return -1; } } else if (correctionOne.getCorrectedObjectClass() == SupremeCourtJudgmentForm.class) { if (correctionTwo.getCorrectedObjectClass() == Judge.class) { return -1; } else { return 1; } } else { return 1; } }

Target:
public int compare(JudgmentCorrection correctionOne, JudgmentCorrection correctionTwo) { if (correctionOne.getCorrectedObjectClass() == correctionTwo.getCorrectedObjectClass()) { return compareChangeOperation(correctionOne.getChangeOperation(), correctionTwo.getChangeOperation()); } if (Judgment.class.isAssignableFrom(correctionOne.getCorrectedObjectClass())) { return -1; } if (correctionOne.getCorrectedObjectClass() == SupremeCourtChamber.class) { if (correctionTwo.getCorrectedObjectClass() == CommonCourtJudgment.class || correctionTwo.getCorrectedObjectClass() == SupremeCourtJudgment.class) { return 1; } else { return -1; } } if (correctionOne.getCorrectedObjectClass() == SupremeCourtJudgmentForm.class) { if (correctionTwo.getCorrectedObjectClass() == Judge.class) { return -1; } else { return 1; } } return 1; }
Source:
public void insertTaskContainerEvent(ITmfStateSystemBuilder ssb, TaskContainerEvent t) { checkNotNull(t); if (!hmTasks.containsKey(t.getTid())) { hmTasks.put(t.getTid(), t); if (rootContainerInfoAdded) { int rootContainerQuark = ContainerHelper.getRootContainerQuark(ssb); ContainerInfo rootContainerInfo = ContainerHelper.getContainerInfo(ssb, rootContainerQuark); if (rootContainerInfo == null) { throw new IllegalStateException("Error, root container seems added but container info is unavailable!"); } if (t.getNsInode() == rootContainerInfo.getContainerInode()) { setTaskCPUStatus(ssb, t); } else if (isParentContainerAdded(ssb, t)) { addTaskAndResolveOrphans(ssb, t); } else { unresolvedTasks.add(t); } } } }

Target:
public void insertTaskContainerEvent(ITmfStateSystemBuilder ssb, TaskContainerEvent t) { if (!fTasks.containsKey(t.getTid())) { fTasks.put(t.getTid(), t); int rootContainerQuark = ContainerHelper.getRootContainerQuark(ssb); ContainerInfo rootContainerInfo = ContainerHelper.getContainerInfo(ssb, rootContainerQuark); if (rootContainerInfo != null) { if (t.getNsInode() == rootContainerInfo.getContainerInode()) { setTaskCPUStatus(ssb, t); } else if (isParentContainerAdded(ssb, t)) { addTaskAndResolveOrphans(ssb, t); } else { unresolvedTasks.add(t); } } } }
Source:
public void send_shouldFillInLastIntentData() throws Exception { Intent[] intents = {new Intent("first"), new Intent("second")}; Context context = new Activity(); PendingIntent pendingIntent = PendingIntent.getActivities(context, 99, intents, 100); Activity otherContext = new Activity(); Intent fillIntent = new Intent(); fillIntent.putExtra("TEST", 23); pendingIntent.send(otherContext, 0, fillIntent); ShadowActivity shadowActivity = shadowOf(otherContext); Intent first = shadowActivity.getNextStartedActivity(); assertThat(first).isNotNull(); assertThat(first).isSameAs(intents[0]); assertThat(first.hasExtra("TEST")).isFalse(); Intent second = shadowActivity.getNextStartedActivity(); assertThat(second).isNotNull(); assertThat(second).isSameAs(intents[1]); assertThat(second.getIntExtra("TEST", -1)).isEqualTo(23); }

Target:
public void send_shouldFillInLastIntentData() throws Exception { Intent[] intents = {new Intent("first"), new Intent("second")}; Context context = Robolectric.setupActivity(Activity.class); PendingIntent pendingIntent = PendingIntent.getActivities(context, 99, intents, 100); Activity otherContext = Robolectric.setupActivity(Activity.class); Intent fillIntent = new Intent(); fillIntent.putExtra("TEST", 23); pendingIntent.send(otherContext, 0, fillIntent); ShadowActivity shadowActivity = shadowOf(otherContext); Intent first = shadowActivity.getNextStartedActivity(); assertThat(first).isNotNull(); assertThat(first).isSameAs(intents[0]); assertThat(first.hasExtra("TEST")).isFalse(); Intent second = shadowActivity.getNextStartedActivity(); assertThat(second).isNotNull(); assertThat(second).isSameAs(intents[1]); assertThat(second.getIntExtra("TEST", -1)).isEqualTo(23); }
Source:
public void tearDown() throws Exception { mJobScheduler.cancel(CONNECTIVITY_JOB_ID); if (mInitialRestrictBackground) { SystemUtil.runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_ON_CMD); } if (mHasWifi) { if (mWifiManager.isWifiEnabled() == mInitialWiFiState) { return; } NetworkInfo.State expectedState = mInitialWiFiState ? NetworkInfo.State.CONNECTED : NetworkInfo.State.DISCONNECTED; ConnectivityActionReceiver receiver = new ConnectivityActionReceiver(ConnectivityManager.TYPE_WIFI, expectedState); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mContext.registerReceiver(receiver, filter); assertTrue(mWifiManager.setWifiEnabled(mInitialWiFiState)); receiver.waitForStateChange(); assertTrue("Failure to restore previous WiFi state", mWifiManager.isWifiEnabled() == mInitialWiFiState); mContext.unregisterReceiver(receiver); } super.tearDown(); }

Target:
public void tearDown() throws Exception { mJobScheduler.cancel(CONNECTIVITY_JOB_ID); if (mInitialRestrictBackground) { SystemUtil.runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_ON_CMD); } if (mHasWifi) { if (mWifiManager.isWifiEnabled() != mInitialWiFiState) { NetworkInfo.State expectedState = mInitialWiFiState ? NetworkInfo.State.CONNECTED : NetworkInfo.State.DISCONNECTED; ConnectivityActionReceiver receiver = new ConnectivityActionReceiver(ConnectivityManager.TYPE_WIFI, expectedState); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); mContext.registerReceiver(receiver, filter); assertTrue(mWifiManager.setWifiEnabled(mInitialWiFiState)); receiver.waitForStateChange(); assertTrue("Failure to restore previous WiFi state", mWifiManager.isWifiEnabled() == mInitialWiFiState); mContext.unregisterReceiver(receiver); } } super.tearDown(); }
Source:
public String requestUserCode(@RequestParam(value = "user_code", required = false) String userCode, ModelMap model, HttpSession session) { if (userCode == null) { return "requestUserCode"; } else { return readUserCode(userCode, model, session); } }

Target:
public String requestUserCode(@RequestParam(value = "user_code", required = false) String userCode, ModelMap model, HttpSession session) { if (userCode == null) { return "requestUserCode"; } else { model.addAttribute("completeVerificationUriUsed", true); return readUserCode(userCode, model, session); } }