auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SyncUser retrieveUser(final String provider, final String providerId) throws ObjectServerError { if (Util.isEmptyString(provider)) { throw new IllegalArgumentException("Not-null 'provider' required."); } if (Util.isEmptyString(providerId)) { throw new IllegalArgumentException("None empty 'providerId' required."); } if (!isAdmin()) { throw new IllegalStateException("User need to be admin in order to lookup ID."); } AuthenticationServer authServer = SyncManager.getAuthServer(); LookupUserIdResponse response = authServer.retrieveUser(getSyncUser().getUserToken(), provider, providerId, getAuthenticationUrl()); if (!response.isValid()) { throw response.getError(); } else { SyncUser syncUser = SyncManager.getUserStore().get(response.getUserId()); if (syncUser != null) { return syncUser; } else { Token refreshToken = new Token(null, response.getUserId(), null, 0, null, response.isAdmin()); ObjectServerUser objectServerUser = new ObjectServerUser(refreshToken, getAuthenticationUrl()); objectServerUser.localLogout(); return new SyncUser(objectServerUser); } } }

Target:
public SyncUser retrieveUser(final String provider, final String providerId) throws ObjectServerError { if (Util.isEmptyString(provider)) { throw new IllegalArgumentException("Not-null 'provider' required."); } if (Util.isEmptyString(providerId)) { throw new IllegalArgumentException("None empty 'providerId' required."); } if (!isAdmin()) { throw new IllegalArgumentException("SyncUser needs to be admin in order to lookup other users ID."); } AuthenticationServer authServer = SyncManager.getAuthServer(); LookupUserIdResponse response = authServer.retrieveUser(getSyncUser().getUserToken(), provider, providerId, getAuthenticationUrl()); if (!response.isValid()) { if (response.getError().getErrorCode() == ErrorCode.NOT_FOUND) { return null; } else { throw response.getError(); } } else { SyncUser syncUser = SyncManager.getUserStore().get(response.getUserId()); if (syncUser != null) { return syncUser; } else { Token refreshToken = new Token(null, response.getUserId(), null, 0, null, response.isAdmin()); ObjectServerUser objectServerUser = new ObjectServerUser(refreshToken, getAuthenticationUrl()); objectServerUser.localLogout(); return new SyncUser(objectServerUser); } } }
Source:
public void updateStats(Binary min_value, Binary max_value) { if (min.compareTo(min_value) > 0) { min = Binary.fromByteArray(min_value.getBytes()); } if (max.compareTo(max_value) < 0) { max = Binary.fromByteArray(max_value.getBytes()); } }

Target:
public void updateStats(Binary min_value, Binary max_value) { if (min.compareTo(min_value) > 0) { min = min_value.copy(); } if (max.compareTo(max_value) < 0) { max = max_value.copy(); } }
Source:
public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; if (socketsByUri.containsKey(uri)) { numberOpenedSocketForUri = socketsByUri.get(uri).size(); } return numberOpenedSocketForUri; }

Target:
public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; synchronized (this) { if (socketsByUri.containsKey(uri)) { numberOpenedSocketForUri = socketsByUri.get(uri).size(); } } return numberOpenedSocketForUri; }
Source:
private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); requestStaticInjection(AssetProvider.class); bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); }

Target:
private void bindFrontendInfrastructure() { bind(Frontend.class).in(Singleton.class); requestStaticInjection(Frontend.InstanceHolder.class); bind(VdcOperationManager.class).in(Singleton.class); bind(OperationProcessor.class).in(Singleton.class); bind(CommunicationProvider.class).to(GWTRPCCommunicationProvider.class).in(Singleton.class); }
Source:
public boolean isMap(final Object o) { if (o instanceof Map) { return true; } else { return o instanceof Group; } }

Target:
public boolean isMap(final Object o) { return o instanceof Map || o instanceof Group; }
Source:
public StateDescription getStateDescription(String itemName, Locale locale) { Set<ChannelUID> boundChannels = itemChannelLinkRegistry.getBoundChannels(itemName); if (!boundChannels.isEmpty()) { ChannelUID channelUID = boundChannels.iterator().next(); Channel channel = thingRegistry.getChannel(channelUID); if (channel != null) { ChannelType channelType = thingTypeRegistry.getChannelType(channel, locale); if (channelType != null) { StateDescription state = channelType.getState(); if ((channelType.getItemType() != null) && ((state == null) || (state.getPattern() == null))) { String pattern = null; if (channelType.getItemType().equalsIgnoreCase("String")) { pattern = "%s"; } else if (channelType.getItemType().equalsIgnoreCase("Number")) { pattern = "%.0f"; } if (pattern != null) { logger.debug("Provide a default pattern for item {}", pattern, itemName); if (state == null) { state = new StateDescription(null, null, null, pattern, false, null); } else { state = new StateDescription(state.getMinimum(), state.getMaximum(), state.getStep(), pattern, state.isReadOnly(), state.getOptions()); } } } return state; } else { return null; } } } return null; }

Target:
public StateDescription getStateDescription(String itemName, Locale locale) { Set<ChannelUID> boundChannels = itemChannelLinkRegistry.getBoundChannels(itemName); if (!boundChannels.isEmpty()) { ChannelUID channelUID = boundChannels.iterator().next(); Channel channel = thingRegistry.getChannel(channelUID); if (channel != null) { ChannelType channelType = thingTypeRegistry.getChannelType(channel, locale); if (channelType != null) { StateDescription stateDescription = channelType.getState(); if ((channelType.getItemType() != null) && ((stateDescription == null) || (stateDescription.getPattern() == null))) { String pattern = null; if (channelType.getItemType().equalsIgnoreCase(CoreItemFactory.STRING)) { pattern = "%s"; } else if (channelType.getItemType().equalsIgnoreCase(CoreItemFactory.NUMBER)) { pattern = "%.0f"; } if (pattern != null) { logger.trace("Provide a default pattern for item {}", pattern, itemName); if (stateDescription == null) { stateDescription = new StateDescription(null, null, null, pattern, false, null); } else { stateDescription = new StateDescription(stateDescription.getMinimum(), stateDescription.getMaximum(), stateDescription.getStep(), pattern, stateDescription.isReadOnly(), stateDescription.getOptions()); } } } return stateDescription; } else { return null; } } } return null; }
Source:
public Node transform(QueryVisitor queryVisitor) { NodeVisitorImpl nodeVisitor = new NodeVisitorImpl(queryVisitor, new QueryVisitorStub()); Map<Class<?>, Object> rootVars = new LinkedHashMap<>(); rootVars.put(QueryTraversalContext.class, new QueryTraversalContext(rootParentType, rootParentType, null, null)); Node root = roots.stream().findFirst() .orElseThrow(() -> new IllegalArgumentException("Single root node is required for transformation.")); TraverserVisitor<Node> nodeTraverserVisitor = new TraverserVisitor<Node>() { @Override public TraversalControl enter(TraverserContext<Node> context) { context.setVar(LeaveOrEnter.class, LeaveOrEnter.ENTER); return context.thisNode().accept(context, nodeVisitor); } @Override public TraversalControl leave(TraverserContext<Node> context) { context.setVar(LeaveOrEnter.class, LeaveOrEnter.LEAVE); return context.thisNode().accept(context, nodeVisitor); } }; return new TreeTransformer<>(AST_NODE_ADAPTER).transform(root, nodeTraverserVisitor, rootVars); }

Target:
public Node transform(QueryVisitor queryVisitor) { NodeVisitorImpl nodeVisitor = new NodeVisitorImpl(queryVisitor, new QueryVisitorStub()); Map<Class<?>, Object> rootVars = new LinkedHashMap<>(); rootVars.put(QueryTraversalContext.class, new QueryTraversalContext(rootParentType, rootParentType, null, null)); assertTrue(roots.size() == 1, "Single root node is required for transformation."); Node root = roots.stream().findFirst().get(); TraverserVisitor<Node> nodeTraverserVisitor = new TraverserVisitor<Node>() { @Override public TraversalControl enter(TraverserContext<Node> context) { context.setVar(LeaveOrEnter.class, LeaveOrEnter.ENTER); return context.thisNode().accept(context, nodeVisitor); } @Override public TraversalControl leave(TraverserContext<Node> context) { return TraversalControl.CONTINUE; } }; return new TreeTransformer<>(AST_NODE_ADAPTER).transform(root, nodeTraverserVisitor, rootVars); }
Source:
private KafkaLogAppender(String topic, String name, Properties producerProperties, Properties consumerProperties) { this.topic = topic; this.name = name; this.producerProps = producerProperties; this.consumerProps = consumerProperties; this.producer = new KafkaProducer<>(this.producerProps); this.size = producer.partitionsFor(topic).size(); log.debug(String.format("Created appender: %s on topic: %s with %d partitions", name, topic, size)); }

Target:
private KafkaLogAppender(String topic, String name, Properties producerProperties, Properties consumerProperties) { this.topic = topic; this.name = name; this.producerProps = producerProperties; this.consumerProps = consumerProperties; this.producer = new KafkaProducer<>(this.producerProps); this.size = producer.partitionsFor(topic).size(); if (log.isDebugEnabled()) { log.debug(String.format("Created appender: %s on topic: %s with %d partitions", name, topic, size)); } }
Source:
private static void expectConsumerAssignmentPaused(final Consumer<byte[], byte[]> consumer) { final Set<TopicPartition> assignment = singleton(new TopicPartition("assignment", 0)); expect(consumer.assignment()).andReturn(assignment); consumer.pause(assignment); expectLastCall(); }

Target:
private static void expectConsumerAssignmentPaused(final Consumer<byte[], byte[]> consumer) { final Set<TopicPartition> assignment = singleton(new TopicPartition("assignment", 0)); expect(consumer.assignment()).andReturn(assignment); consumer.pause(assignment); }
Source:
public void testGetWriteFlagsNone() { assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(0)); }

Target:
public void testGetWriteFlagsNone() { assertEquals(EnumSet.noneOf(WriteFlag.class), WriteFlag.getWriteFlags(NONE)); }
Source:
public boolean visit(TypeDeclaration elem) { Utils.checkTemplate(collector, elem); if (ElementTypeTeller.isExternal(elem)) { return false; } if (ElementTypeTeller.isSignal(elem)) { Utils.checkModifiers(collector, elem); checkChildren(elem, Messages.ModelVisitor_signal_label, SignalVisitor.ALLOWED_SIGNAL_DECLARATIONS); acceptChildren(elem, new SignalVisitor(collector)); } else if (ElementTypeTeller.isAssociation(elem)) { Utils.checkModifiers(collector, elem); if (ElementTypeTeller.isComposition(elem)) { acceptChildren(elem, new CompositionVisitor(elem, collector)); } else { acceptChildren(elem, new AssociationVisitor(elem, collector)); } checkChildren(elem, Messages.ModelVisitor_association_label, AssociationVisitor.ALLOWED_ASSOCIATION_DECLARATIONS); } else if (ElementTypeTeller.isModelClass(elem)) { checkChildren(elem, Messages.ModelVisitor_class_label, ModelClassVisitor.ALLOWED_MODEL_CLASS_DECLARATIONS); acceptChildren(elem, new ModelClassVisitor(collector)); } else if (ElementTypeTeller.isDataType(elem.resolveBinding())) { checkChildren(elem, "data type", DataTypeVisitor.ALLOWED_DATA_TYPE_DECLARATIONS); acceptChildren(elem, new DataTypeVisitor(collector)); } else if (ElementTypeTeller.isInterface(elem)) { } else if (ElementTypeTeller.isConnector(elem)) { } else { collector.report(new InvalidTypeInModel(collector.getSourceInfo(), elem)); } return false; }

Target:
public boolean visit(TypeDeclaration elem) { if (ElementTypeTeller.isExternal(elem)) { return false; } Utils.checkTypeParameter(collector, elem); if (ElementTypeTeller.isSignal(elem)) { Utils.checkModifiers(collector, elem); checkChildren(elem, Messages.ModelVisitor_signal_label, SignalVisitor.ALLOWED_SIGNAL_DECLARATIONS); acceptChildren(elem, new SignalVisitor(collector)); } else if (ElementTypeTeller.isAssociation(elem)) { Utils.checkModifiers(collector, elem); if (ElementTypeTeller.isComposition(elem)) { acceptChildren(elem, new CompositionVisitor(elem, collector)); } else { acceptChildren(elem, new AssociationVisitor(elem, collector)); } checkChildren(elem, Messages.ModelVisitor_association_label, AssociationVisitor.ALLOWED_ASSOCIATION_DECLARATIONS); } else if (ElementTypeTeller.isModelClass(elem)) { checkChildren(elem, Messages.ModelVisitor_class_label, ModelClassVisitor.ALLOWED_MODEL_CLASS_DECLARATIONS); acceptChildren(elem, new ModelClassVisitor(collector)); } else if (ElementTypeTeller.isDataType(elem.resolveBinding())) { checkChildren(elem, "data type", DataTypeVisitor.ALLOWED_DATA_TYPE_DECLARATIONS); acceptChildren(elem, new DataTypeVisitor(collector)); } else if (ElementTypeTeller.isInterface(elem)) { } else if (ElementTypeTeller.isConnector(elem)) { } else { collector.report(new InvalidTypeInModel(collector.getSourceInfo(), elem)); } return false; }
Source:
private ASTArgumentList getArgumentList(ASTArguments args) { if (args != null) { super.visit(args, null); return args.getFirstChildOfType(ASTArgumentList.class); } return null; }

Target:
private ASTArgumentList getArgumentList(ASTArguments args) { if (args != null) { return args.getFirstChildOfType(ASTArgumentList.class); } return null; }
Source:
private static void buildPointsBlock(Geometry geometry, BlockBuilder blockBuilder) { GeometryType type = GeometryType.getForEsriGeometryType(geometry.getGeometryType()); if (type == GeometryType.POINT) { GEOMETRY.writeSlice(blockBuilder, serialize(geometry)); } else if (type == GeometryType.GEOMETRY_COLLECTION) { GeometryCollection collection = (GeometryCollection) geometry; for (int i = 0; i < collection.getNumGeometries(); i++) { Geometry entry = collection.getGeometryN(i); buildPointsBlock(entry, blockBuilder); } } else { GeometryFactory gFactory = geometry.getFactory(); Coordinate[] vertices = geometry.getCoordinates(); for (Coordinate coordinate : vertices) { GEOMETRY.writeSlice(blockBuilder, serialize(gFactory.createPoint(coordinate))); } } }

Target:
private static void buildPointsBlock(Geometry geometry, BlockBuilder blockBuilder) { GeometryType type = GeometryType.getForJtsGeometryType(geometry.getGeometryType()); if (type == GeometryType.POINT) { GEOMETRY.writeSlice(blockBuilder, serialize(geometry)); } else if (type == GeometryType.GEOMETRY_COLLECTION) { GeometryCollection collection = (GeometryCollection) geometry; for (int i = 0; i < collection.getNumGeometries(); i++) { Geometry entry = collection.getGeometryN(i); buildPointsBlock(entry, blockBuilder); } } else { GeometryFactory geometryFactory = geometry.getFactory(); Coordinate[] vertices = geometry.getCoordinates(); for (Coordinate coordinate : vertices) { GEOMETRY.writeSlice(blockBuilder, serialize(geometryFactory.createPoint(coordinate))); } } }
Source:
public List<String> getUntrackedFolders() { return (indexDiffFilter == null) ? (List<String>) Collections.EMPTY_LIST : indexDiffFilter.getUntrackedFolders(); }

Target:
public List<String> getUntrackedFolders() { return ((indexDiffFilter == null) ? Collections.<String>emptyList() : indexDiffFilter.getUntrackedFolders()); }
Source:
String getNewZipDestination(){ return getNewZipDestination(getProperties().getProperty(UNZIP_BASE_PROPERTY_NAME)); }

Target:
File getNewZipDestination(){ return getNewZipDestination(getProperties().getProperty(UNZIP_BASE_PROPERTY_NAME)); }
Source:
public int hashCode() { return Objects.hash(VIEW) + query.hashCode(); }

Target:
public int hashCode() { return Objects.hash(TYPE, query); }
Source:
private void log(String accessLog, AccessLogData accessLogData) { Set<AccessLogData> logSet = logQueue.get(accessLog); if (logSet == null) { logQueue.putIfAbsent(accessLog, new ConcurrentHashSet<AccessLogData>()); logSet = logQueue.get(accessLog); } if (logSet.size() < LOG_MAX_BUFFER) { logSet.add(accessLogData); } }

Target:
private void log(String accessLog, AccessLogData accessLogData) { Set<AccessLogData> logSet = logQueue.computeIfAbsent(accessLog, k -> new ConcurrentHashSet<>()); if (logSet.size() < LOG_MAX_BUFFER) { logSet.add(accessLogData); } else { logger.warn("AccessLog buffer is full skipping buffer "); } }
Source:
public void testLocalhostSingle() throws Exception { SingleMachineProvisioningLocation<SshMachineLocation> l = (SingleMachineProvisioningLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve("single:(localhost)"); l.setManagementContext(managementContext); SshMachineLocation m1 = l.obtain(); log.info("GOT "+m1); l.release(m1); }

Target:
public void testLocalhostSingle() throws Exception { SingleMachineProvisioningLocation<SshMachineLocation> l = (SingleMachineProvisioningLocation<SshMachineLocation>) managementContext.getLocationRegistry().resolve("single:(target='localhost')"); l.setManagementContext(managementContext); SshMachineLocation m1 = l.obtain(); assertNotNull(m1); log.info("GOT "+m1); l.release(m1); }
Source:
private static void enablePartialGetFields(GsonBuilder gb, Multimap<String, String> config) { final Set<String> want = Sets.newHashSet(); for (String p : config.get("fields")) { Iterables.addAll(want, OptionUtil.splitOptionValue(p)); } if (!want.isEmpty()) { gb.addSerializationExclusionStrategy(new ExclusionStrategy() { private final Map<String, String> names = Maps.newHashMap(); @Override public boolean shouldSkipField(FieldAttributes field) { String name = names.get(field.getName()); if (name == null) { try { name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName( field.getDeclaringClass().getDeclaredField(field.getName())); names.put(field.getName(), name); } catch (SecurityException e) { return true; } catch (NoSuchFieldException e) { return true; } } return !want.contains(name); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); } }

Target:
private static void enablePartialGetFields(GsonBuilder gb, Multimap<String, String> config) { final Set<String> want = Sets.newHashSet(); for (String p : config.get("fields")) { Iterables.addAll(want, OptionUtil.splitOptionValue(p)); } if (!want.isEmpty()) { gb.addSerializationExclusionStrategy(new ExclusionStrategy() { private final Map<String, String> names = Maps.newHashMap(); @Override public boolean shouldSkipField(FieldAttributes field) { String name = names.get(field.getName()); if (name == null) { try { name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName( field.getDeclaringClass().getDeclaredField(field.getName())); names.put(field.getName(), name); } catch (SecurityException e) { return true; } catch (NoSuchFieldException e) { return true; } } return !want.contains(name.toLowerCase()); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); } }
Source:
public int schedule() { schedulingMainLoopTimingLogger = new SchedulingMainLoopTimingLogger(logger); Policy currentPolicy = schedulingService.getPolicy(); activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER; Map<JobId, JobDescriptor> jobMap = schedulingService.lockJobsToSchedule(); Map<JobId, JobDescriptor> toUnlock = jobMap; logSelectedJobs(jobMap); if (jobMap.isEmpty()) { return 0; } int tasksStarted = startTasks(currentPolicy, jobMap, toUnlock); schedulingMainLoopTimingLogger.printTimingsINFOLevel(); return tasksStarted; }

Target:
public int schedule() { schedulingMainLoopTimingLogger = new SchedulingMainLoopTimingLogger(Logger.getLogger(SchedulingMethodImpl.class)); Policy currentPolicy = schedulingService.getPolicy(); activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER; Map<JobId, JobDescriptor> jobMap = schedulingService.lockJobsToSchedule(); Map<JobId, JobDescriptor> toUnlock = jobMap; logSelectedJobs(jobMap); if (jobMap.isEmpty()) { return 0; } int tasksStarted = startTasks(currentPolicy, jobMap, toUnlock); schedulingMainLoopTimingLogger.printTimingsINFOLevel(); return tasksStarted; }
Source:
public void init(GameEngine gameEngine) { context = gameEngine.createChildContext(); CoreRegistry.setContext(context); EntitySystemSetupUtil.addEntityManagementRelatedClasses(context); entityManager = context.get(EngineEntityManager.class); eventSystem = context.get(EventSystem.class); context.put(Console.class, new ConsoleImpl(context)); NUIManager nuiManager = new NUIManagerInternal(context.get(CanvasRenderer.class), context); context.put(NUIManager.class, nuiManager); componentSystemManager = new ComponentSystemManager(context); context.put(ComponentSystemManager.class, componentSystemManager); componentSystemManager.register(new ConsoleSystem(), "engine:ConsoleSystem"); componentSystemManager.register(new CoreCommands(), "engine:CoreCommands"); componentSystemManager.register(context.get(InputSystem.class), "engine:InputSystem"); EntityRef localPlayerEntity = entityManager.create(new ClientComponent()); LocalPlayer localPlayer = new LocalPlayer(); context.put(LocalPlayer.class, localPlayer); localPlayer.setClientEntity(localPlayerEntity); componentSystemManager.initialise(); GameManifest gameManifest = null; List<GameInfo> savedGames = GameProvider.getSavedGames(); if (savedGames.size() > 0) { gameManifest = savedGames.get(0).getManifest(); } else { gameManifest = createGameManifest(); } gameEngine.changeState(new StateLoading(gameManifest, NetworkMode.LISTEN_SERVER)); ServerConnectListManager.getInstance().loadLists(); }

Target:
public void init(GameEngine gameEngine) { context = gameEngine.createChildContext(); CoreRegistry.setContext(context); EntitySystemSetupUtil.addEntityManagementRelatedClasses(context); entityManager = context.get(EngineEntityManager.class); eventSystem = context.get(EventSystem.class); context.put(Console.class, new ConsoleImpl(context)); NUIManager nuiManager = new NUIManagerInternal(context.get(CanvasRenderer.class), context); context.put(NUIManager.class, nuiManager); componentSystemManager = new ComponentSystemManager(context); context.put(ComponentSystemManager.class, componentSystemManager); componentSystemManager.register(new ConsoleSystem(), "engine:ConsoleSystem"); componentSystemManager.register(new CoreCommands(), "engine:CoreCommands"); componentSystemManager.register(context.get(InputSystem.class), "engine:InputSystem"); EntityRef localPlayerEntity = entityManager.create(new ClientComponent()); LocalPlayer localPlayer = new LocalPlayer(); context.put(LocalPlayer.class, localPlayer); localPlayer.setClientEntity(localPlayerEntity); componentSystemManager.initialise(); GameManifest gameManifest = null; List<GameInfo> savedGames = GameProvider.getSavedGames(); if (savedGames.size() > 0) { gameManifest = savedGames.get(0).getManifest(); } else { gameManifest = createGameManifest(); } gameEngine.changeState(new StateLoading(gameManifest, NetworkMode.LISTEN_SERVER)); }
Source:
public static void toJSON(OutputWriter outputWriter, ArtifactStore store) { outputWriter .add("id", store.getId()) .add("plugin_id", store.getPluginId()) .addChildList("properties", listWriter -> store.forEach(property -> listWriter.addChild(propertyWriter -> ConfigurationPropertyRepresenter.toJSON(propertyWriter, property)))); if (store.hasErrors()) { Map<String, String> fieldMapping = Collections.singletonMap("pluginId", "plugin_id"); outputWriter.addChild("errors", errorWriter -> new ErrorGetter(fieldMapping).toJSON(errorWriter, store)); } }

Target:
public static void toJSON(OutputWriter outputWriter, ArtifactStore store) { outputWriter .addLinks(linksWriter -> linksWriter .addLink("self", Routes.ArtifactStoreConfig.id(store.getId())) .addAbsoluteLink("doc", Routes.ArtifactStoreConfig.DOC) .addLink("find", Routes.ArtifactStoreConfig.find())) .add("id", store.getId()) .add("plugin_id", store.getPluginId()) .addChildList("properties", listWriter -> store.forEach(property -> listWriter.addChild(propertyWriter -> ConfigurationPropertyRepresenter.toJSON(propertyWriter, property)))); if (store.hasErrors()) { Map<String, String> fieldMapping = Collections.singletonMap("pluginId", "plugin_id"); outputWriter.addChild("errors", errorWriter -> new ErrorGetter(fieldMapping).toJSON(errorWriter, store)); } }
Source:
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = Collections.singletonList(Arrays.copyOf(data, data.length)); return body; }

Target:
public static AmqpMessageBody fromData(byte[] data) { Objects.requireNonNull(data, "'data' cannot be null."); AmqpMessageBody body = new AmqpMessageBody(); body.bodyType = AmqpMessageBodyType.DATA; body.data = data; return body; }
Source:
public void Login_006_authModalInGlobalNav_staff() { WikiBasePageObject base = new WikiBasePageObject(driver); base.openWikiPage(wikiURL); NavigationBar signInLink = new NavigationBar(driver); signInLink.clickOnSignIn(); AuthModal authModal = signInLink.getAuthModal(); Assert.assertTrue(authModal.isOpened()); authModal.login(credentials.userNameStaff, credentials.passwordStaff); base.verifyUserLoggedIn(credentials.userNameStaff); }

Target:
public void Login_006_authModalInGlobalNav_staff() { WikiBasePageObject base = new WikiBasePageObject(driver); NavigationBar signInLink = new NavigationBar(driver); base.openWikiPage(wikiURL); signInLink.clickOnSignIn(); AuthModal authModal = signInLink.getAuthModal(); Assert.assertTrue(authModal.isOpened()); authModal.login(credentials.userNameStaff, credentials.passwordStaff); base.verifyUserLoggedIn(credentials.userNameStaff); }
Source:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String serverId) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { return new StandardUsernameListBoxModel().includeCurrentValue(serverId); } return new StandardUsernameListBoxModel().includeAs( ACL.SYSTEM, context, StandardUsernameCredentials.class, Collections.<DomainRequirement> singletonList(new MavenServerIdRequirement(serverId)) ) .includeCurrentValue(serverId); }

Target:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String serverId) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context == null || !_context.hasPermission(Computer.CONFIGURE)) { return new StandardUsernameListBoxModel().includeCurrentValue(serverId); } List<DomainRequirement> domainRequirements = Collections.emptyList(); if (StringUtils.isNotBlank(serverId)) { Collections.<DomainRequirement> singletonList(new MavenServerIdRequirement(serverId)); } return new StandardUsernameListBoxModel().includeAs( context instanceof Queue.Task ? Tasks.getDefaultAuthenticationOf((Queue.Task)context) : ACL.SYSTEM, context, StandardUsernameCredentials.class, domainRequirements ) .includeCurrentValue(serverId); }
Source:
public void testSetTheme() { ThemePropertyListener listener = new ThemePropertyListener(); fManager.addPropertyChangeListener(listener); ITheme currentTheme = fManager.getCurrentTheme(); fManager.setCurrentTheme(BOGUSID); assertEquals(currentTheme, fManager.getCurrentTheme()); fManager.setCurrentTheme(THEME1); assertNotSame(currentTheme, fManager.getCurrentTheme()); ITheme newCurrentTheme = fManager.getCurrentTheme(); ITheme theme1 = getTheme1(); assertEquals(theme1, newCurrentTheme); List events = listener.getEvents(); assertTrue(events.size() > 0); PropertyChangeEvent event = ((PropertyChangeEvent) events.get(0)); assertEquals(IThemeManager.CHANGE_CURRENT_THEME, event.getProperty()); assertEquals(currentTheme, event.getOldValue()); assertEquals(newCurrentTheme, event.getNewValue()); fManager.removePropertyChangeListener(listener); }

Target:
public void testSetTheme() { ThemePropertyListener listener = new ThemePropertyListener(); fManager.addPropertyChangeListener(listener); ITheme currentTheme = fManager.getCurrentTheme(); fManager.setCurrentTheme(BOGUSID); assertEquals(currentTheme, fManager.getCurrentTheme()); fManager.setCurrentTheme(THEME1); assertNotSame(currentTheme, fManager.getCurrentTheme()); ITheme newCurrentTheme = fManager.getCurrentTheme(); ITheme theme1 = getTheme1(); assertEquals(theme1, newCurrentTheme); List events = listener.getEvents(); assertEquals(1, events.size()); PropertyChangeEvent event = ((PropertyChangeEvent) events.get(0)); assertEquals(IThemeManager.CHANGE_CURRENT_THEME, event.getProperty()); assertEquals(currentTheme, event.getOldValue()); assertEquals(newCurrentTheme, event.getNewValue()); fManager.removePropertyChangeListener(listener); }
Source:
private void glusterHostRemove() { boolean forceAction = false; if (getVdsDAO().getAll().size() > 1) { if (isGlusterEnabled() && !hasVolumeOnServer()) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostRemove, new GlusterHostRemoveVDSParameters((ClusterUtils.getInstance().getUpServer(getVdsGroupId())).getId(), getVdsName(), forceAction)); setSucceeded(returnValue.getSucceeded()); if (!returnValue.getSucceeded()) { errorType = AuditLogType.GLUSTER_HOST_REMOVE_FAILED; } } } }

Target:
private void glusterHostRemove() { boolean forceAction = false; if (isGlusterEnabled() && getVdsDAO().getAll().size() > 1 && !hasVolumeOnServer()) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostRemove, new GlusterHostRemoveVDSParameters((ClusterUtils.getInstance().getUpServer(getVdsGroupId())).getId(), getVdsName(), forceAction)); setSucceeded(returnValue.getSucceeded()); if (!returnValue.getSucceeded()) { errorType = AuditLogType.GLUSTER_HOST_REMOVE_FAILED; } } }
Source:
Optional<Path> downloadAndExtractAllureTo(String home, String version) { return downloadAllure(version).map(zipFilePath -> { try { LOGGER.info("Extracting file " + zipFilePath + " to " + home + "..."); final String extractedDirName = "allure-" + version; final Path allureHome = Paths.get(home); final Path extractDir = zipFilePath.getParent(); new ZipFile(zipFilePath.toFile()).extractAll(extractDir.toString()); if (Files.exists(allureHome)) { LOGGER.info("Directory " + allureHome + " already exists, removing it.."); deleteQuietly(allureHome.toFile()); } moveDirectory(extractDir.resolve(extractedDirName).toFile(), allureHome.toFile()); addExecutablePermissions(allureHome); return allureHome; } catch (ZipException | IOException e) { LOGGER.error("Failed to download and extract Allure of version to dir {}", version, home, e); return null; } finally { deleteQuietly(zipFilePath.toFile()); } }); }

Target:
Optional<Path> downloadAndExtractAllureTo(String home, String version) { return downloadAllure(version).map(zipFilePath -> { try { LOGGER.info("Extracting file to {}...", zipFilePath, home); final String extractedDirName = "allure-" + version; final Path allureHome = Paths.get(home); final Path extractDir = zipFilePath.getParent(); new ZipFile(zipFilePath.toFile()).extractAll(extractDir.toString()); if (Files.exists(allureHome)) { LOGGER.info("Directory already exists, skipping it..", allureHome); return null; } moveDirectory(extractDir.resolve(extractedDirName).toFile(), allureHome.toFile()); addExecutablePermissions(allureHome); return allureHome; } catch (ZipException | IOException e) { LOGGER.error("Failed to download and extract Allure of version to dir {}", version, home, e); return null; } finally { deleteQuietly(zipFilePath.toFile()); } }); }
Source:
boolean isCallPermitted() { return false; }

Target:
boolean isCallPermitted() { circuitBreakerMetrics.onCallNotPermitted(); return false; }
Source:
public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { final SynchronizationModel syncModel; if (context == initialContext || !(resource instanceof IFile)) { syncModel = synchronizationModel; } else { SynchronizationModel temp = null; try { temp = ((EMFModelProvider)getModelProvider()).getOrComputeLogicalModel((IFile)resource, context, monitor); } catch (InterruptedException e) { Thread.currentThread().interrupt(); temp = synchronizationModel; } syncModel = temp; } latestModel = syncModel; if (syncModel.getDiagnostic().getSeverity() >= Diagnostic.ERROR) { EMFCompareIDEUIPlugin.getDefault().getLog().log( BasicDiagnostic.toIStatus(syncModel.getDiagnostic())); List<?> datas = syncModel.getDiagnostic().getData(); boolean isInError = true; for (Object data : datas) { if (data instanceof SynchronizationModel) { isInError = false; SynchronizationModel synch = (SynchronizationModel)data; if (synch.getLeftTraversal().getDiagnostic().getSeverity() >= Diagnostic.ERROR || synch.getRightTraversal().getDiagnostic().getSeverity() >= Diagnostic.ERROR || synch.getOriginTraversal().getDiagnostic().getSeverity() >= Diagnostic.ERROR) { isInError = true; break; } } } if (isInError) { return createSingletonTraversal(resource); } } return convertToTraversal(syncModel); }

Target:
public ResourceTraversal[] getTraversals(ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { final SynchronizationModel syncModel; if (context == initialContext || !(resource instanceof IFile)) { syncModel = synchronizationModel; } else { SynchronizationModel temp = null; try { temp = ((EMFModelProvider)getModelProvider()).getOrComputeLogicalModel((IFile)resource, context, monitor); } catch (InterruptedException e) { Thread.currentThread().interrupt(); temp = synchronizationModel; } syncModel = temp; } latestModel = syncModel; return convertToTraversal(syncModel); }
Source:
public void setup() { super.setup(); zones = api.getConfiguredZones(); for (String zone : zones){ ServerApi api = this.api.getServerApiForZone(zone); for (Resource server : api.list().concat()){ if (server.getName().equals(hostName)) api.delete(server.getId()); } } }

Target:
public void setup() { super.setup(); zones = api.getConfiguredZones(); for (String zone : zones){ ServerApi serverApi = api.getServerApiForZone(zone); for (Resource server : serverApi.list().concat()){ if (server.getName().equals(hostName)) serverApi.delete(server.getId()); } } }
Source:
private void printPlanNodesStats(int indent, PlanNode... nodes) { if (Arrays.stream(nodes).anyMatch(this::isPlanNodeStatsKnown)) { String formatedStats = Joiner.on("/").join(Arrays.stream(nodes) .map(this::formatPlanNodeStats) .collect(toImmutableList())); print(indent, "Cost: %s", formatedStats); } }

Target:
private void printPlanNodesStats(int indent, PlanNode... nodes) { if (Arrays.stream(nodes).anyMatch(this::isPlanNodeStatsKnown)) { String formattedStats = Joiner.on("/").join(Arrays.stream(nodes) .map(this::formatPlanNodeStats) .collect(toImmutableList())); print(indent, "Cost: %s", formattedStats); } }
Source:
public void handlesRequestInTime() throws IOException { final int length = 100000000; final File tempfile = this.temp.newFile("handlesRequestInTime.tmp"); final BufferedWriter bwr = new BufferedWriter(new FileWriter(tempfile)); bwr.write( Joiner.on(RqMultipartTest.CRLF).join( "--zzz", "Content-Disposition: form-data; name=\"test\"", "", "" ) ); for (int ind = 0; ind < length; ++ind) { bwr.write("X"); } bwr.write(RqMultipartTest.CRLF); bwr.write("--zzz--"); bwr.write(RqMultipartTest.CRLF); bwr.close(); final long start = System.currentTimeMillis(); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: example.com", "Content-Type: multipart/form-data; boundary=zzz", String.format( "Content-Length:%s", tempfile.length() ) ), new TempInputStream(new FileInputStream(tempfile), tempfile) ); final RqMultipart.Smart smartreq = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( smartreq.single("test").body().available(), Matchers.equalTo(length) ); MatcherAssert.assertThat( System.currentTimeMillis() - start, Matchers.lessThan(3000L) ); } finally { req.body().close(); smartreq.part("test").iterator().next().body().close(); } }

Target:
public void handlesRequestInTime() throws IOException { final int length = 100000000; final String part = "test"; final File file = this.temp.newFile("handlesRequestInTime.tmp"); final BufferedWriter bwr = new BufferedWriter(new FileWriter(file)); bwr.write( Joiner.on(RqMultipartTest.CRLF).join( "--zzz", String.format(RqMultipartTest.CONTENT, part), "", "" ) ); for (int ind = 0; ind < length; ++ind) { bwr.write("X"); } bwr.write(RqMultipartTest.CRLF); bwr.write("--zzz--"); bwr.write(RqMultipartTest.CRLF); bwr.close(); final long start = System.currentTimeMillis(); final Request req = new RqFake( Arrays.asList( "POST /post?u=3 HTTP/1.1", "Host: example.com", "Content-Type: multipart/form-data; boundary=zzz", String.format("Content-Length:%s", file.length()) ), new TempInputStream(new FileInputStream(file), file) ); final RqMultipart.Smart smart = new RqMultipart.Smart( new RqMultipart.Base(req) ); try { MatcherAssert.assertThat( smart.single(part).body().available(), Matchers.equalTo(length) ); MatcherAssert.assertThat( System.currentTimeMillis() - start, Matchers.lessThan(3000L) ); } finally { req.body().close(); smart.part(part).iterator().next().body().close(); } }
Source:
public long getDocumentNumericId() { return documentNumericId; }

Target:
protected long getDocumentNumericId() { return documentNumericId; }
Source:
public void recoverDeletedSecretCodeSnippets() { SecretClient secretClient = getSecretClient(); Poller<KeyVaultSecret, Void> poller = secretClient.beginRecoverDeletedSecret("deletedSecretName"); poller.getObserver() .map(pollResponse -> { System.out.println("Current status: " + pollResponse.getStatus()); if (pollResponse.getStatus() != PollResponse.OperationStatus.NOT_STARTED) { KeyVaultSecret recoveredSecret = pollResponse.getValue(); System.out.println("Recovered key name: " + recoveredSecret.getName()); System.out.println("Recovered key id: " + recoveredSecret.getId()); } return pollResponse.getStatus(); }) .blockLast(); System.out.println("Final status: " + poller.getStatus()); System.out.println("Final response: " + poller.getLastPollResponse()); END: com.azure.security.keyvault.secretclient.recoverDeletedSecret#string }

Target:
public void recoverDeletedSecretCodeSnippets() throws InterruptedException { SecretClient secretClient = getSecretClient(); Poller<KeyVaultSecret, Void> recoverSecretPoller = secretClient.beginRecoverDeletedSecret("deletedSecretName"); while (recoverSecretPoller.getStatus() != PollResponse.OperationStatus.IN_PROGRESS && !recoverSecretPoller.isComplete()) { System.out.println(recoverSecretPoller.getStatus().toString()); Thread.sleep(2000); } KeyVaultSecret recoveredSecret = recoverSecretPoller.getLastPollResponse().getValue(); System.out.println("Recovered Key Name: " + recoveredSecret.getName()); System.out.printf("Recovered Key's Id %s", recoveredSecret.getId()); while (!recoverSecretPoller.isComplete()) { System.out.println(recoverSecretPoller.getStatus().toString()); Thread.sleep(2000); } END: com.azure.security.keyvault.secretclient.recoverDeletedSecret#string }
Source:
private BigtableOptions resolveLegacyOptions(BigtableOptions options) throws IOException { if (options.getClusterId() != null && options.getZoneId() != null) { String instanceId = BigtableClusterUtilities.lookupInstanceId( options.getProjectId(), options.getClusterId(), options.getZoneId() ); if (options.getInstanceId() != null) { Preconditions.checkArgument( options.getInstanceId().equals(instanceId), "Supplied instanceId: '%s', zoneId: '%s' and clusterId: '%s'. They do not match." + "\nFound instanceId '%s' that corresponds to the zoneId/clusterId"); } return options.toBuilder().setInstanceId(instanceId).build(); } return options; }

Target:
private BigtableOptions resolveLegacyOptions(BigtableOptions options) throws IOException { if (options.getClusterId() != null && options.getZoneId() != null) { String instanceId = BigtableClusterUtilities.lookupInstanceId( options.getProjectId(), options.getClusterId(), options.getZoneId() ); if (options.getInstanceId() != null) { Preconditions.checkArgument( options.getInstanceId().equals(instanceId), "Supplied instanceId: '%s', zoneId: '%s' and clusterId: '%s'. They do not match." + "\nFound instanceId '%s' that corresponds to the zoneId/clusterId", options.getInstanceId(), options.getZoneId(), options.getClusterId(), instanceId); } return options.toBuilder().setInstanceId(instanceId).build(); } return options; }
Source:
public ServiceProviderImpl(ServiceDiscoveryImpl<T> discovery, String serviceName, ProviderStrategy<T> providerStrategy, ThreadFactory threadFactory, CloseableExecutorService executorService, List<InstanceFilter<T>> filters, DownInstancePolicy downInstancePolicy) { this.discovery = discovery; this.providerStrategy = providerStrategy; downInstanceManager = new DownInstanceManager<T>(downInstancePolicy); final ServiceCacheBuilder builder = discovery.serviceCacheBuilder().name(serviceName); if (executorService != null) { builder.executorService(executorService); } else { builder.threadFactory(threadFactory); } cache = builder.build(); ArrayList<InstanceFilter<T>> localFilters = Lists.newArrayList(filters); localFilters.add(downInstanceManager); localFilters.add(new InstanceFilter<T>() { @Override public boolean apply(ServiceInstance<T> instance) { return instance.isEnabled(); } }); instanceProvider = new FilteredInstanceProvider<T>(cache, localFilters); }

Target:
protected ServiceProviderImpl(ServiceDiscoveryImpl<T> discovery, String serviceName, ProviderStrategy<T> providerStrategy, ThreadFactory threadFactory, CloseableExecutorService executorService, List<InstanceFilter<T>> filters, DownInstancePolicy downInstancePolicy) { this.discovery = discovery; this.providerStrategy = providerStrategy; downInstanceManager = new DownInstanceManager<T>(downInstancePolicy); final ServiceCacheBuilder builder = discovery.serviceCacheBuilder().name(serviceName); if (executorService != null) { builder.executorService(executorService); } else { builder.threadFactory(threadFactory); } cache = builder.build(); ArrayList<InstanceFilter<T>> localFilters = Lists.newArrayList(filters); localFilters.add(downInstanceManager); localFilters.add(new InstanceFilter<T>() { @Override public boolean apply(ServiceInstance<T> instance) { return instance.isEnabled(); } }); instanceProvider = new FilteredInstanceProvider<T>(cache, localFilters); }
Source:
public void testIsDistinctFrom() { long[] arr1 = {112L, 0L}; long[] arr2 = {185L, 0L}; Block left = new Int128ArrayBlock(1, Optional.empty(), arr1); Block right = new Int128ArrayBlock(1, Optional.empty(), arr2); assertFalse(DecimalInequalityOperators.distinctBlockPositionLongLong(left, 0, left, 0)); assertTrue(DecimalInequalityOperators.distinctBlockPositionLongLong(left, 0, right, 0)); }

Target:
public void testIsDistinctFrom() { Block left = new Int128ArrayBlock(1, Optional.empty(), new long[]{112L, 0L}); Block right = new Int128ArrayBlock(1, Optional.empty(), new long[]{185L, 0L}); assertFalse(distinctBlockPositionLongLong(left, 0, left, 0)); assertTrue(distinctBlockPositionLongLong(left, 0, right, 0)); }
Source:
public void listPatientsNonDefaultBehaviour() throws WebApplicationException, QueryException { Query query = mock(DefaultQuery.class); doReturn(query).when(this.queries).createQuery(anyString(), anyString()); doReturn(query).when(query).bindValue(anyString(), anyString()); doReturn(new ArrayList<Object[]>()).when(query).execute(); Patients result = this.patientsResource.listPatients(0, 30, "eid", "desc"); verify(this.queries).createQuery("select doc.fullName, p.external_id, doc.creator, doc.creationDate, doc.version, doc.author, doc.date" + " from Document doc, doc.object(PhenoTips.PatientClass) p where doc.name <> :t order by " + "p.external_id" + " desc", "xwql"); }

Target:
public void listPatientsNonDefaultBehaviour() throws QueryException { Query query = mock(DefaultQuery.class); doReturn(query).when(this.queries).createQuery(anyString(), anyString()); doReturn(query).when(query).bindValue(anyString(), anyString()); doReturn(new ArrayList<Object[]>()).when(query).execute(); Patients result = this.patientsResource.listPatients(0, 30, "eid", "desc"); verify(this.queries).createQuery("select doc.fullName, p.external_id, doc.creator, doc.creationDate, doc.version, doc.author, doc.date" + " from Document doc, doc.object(PhenoTips.PatientClass) p where doc.name <> :t order by " + "p.external_id" + " desc", "xwql"); }
Source:
public void run() { if (shutdown) { return; } Exception exceptionToThrow = null; try { initialize(); log.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e) { log.error("Unable to initialize after attempts. Shutting down.", lifecycleConfig.maxInitializationAttempts(), e); shutdown(); exceptionToThrow = e; } while (!shouldShutdown()) { exceptionToThrow = null; runProcessLoop(); } finalShutdown(); log.info("Worker loop is complete. Exiting from worker."); if (exceptionToThrow != null) { coordinatorExceptionHandler.propogate(exceptionToThrow); } }

Target:
public void run() { if (shutdown) { return; } try { initialize(); log.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e) { log.error("Unable to initialize after attempts. Shutting down.", maxInitializationAttempts, e); workerStateChangeListener.onAllInitializationAttemptsFailed(e); shutdown(); } while (!shouldShutdown()) { runProcessLoop(); } finalShutdown(); log.info("Worker loop is complete. Exiting from worker."); }
Source:
static boolean isNullColumn(Iterable<String> dimValues) { if (dimValues == null) { return true; } for (String val : dimValues) { if (!Strings.isNullOrEmpty(val)) { return false; } } return true; }

Target:
static boolean isNullColumn(Iterable<String> dimValues) { if (dimValues == null) { return true; } for (String val : dimValues) { if (val != null) { return false; } } return true; }