auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EnumConstantDeclaration addEnumConstant(String name) { EnumConstantDeclaration enumConstant = new EnumConstantDeclaration(name); getEntries().add(enumConstant); enumConstant.setParentNode(this); return enumConstant; }

Target:
public EnumConstantDeclaration addEnumConstant(String name) { assertNonEmpty(name); EnumConstantDeclaration enumConstant = new EnumConstantDeclaration(name); getEntries().add(enumConstant); enumConstant.setParentNode(this); return enumConstant; }
Source:
public void testSelectMeasurementsWithJson() { Delete.table(Measurement.class); addMeasurement(EXISTING_REPORT_ID, true); addMeasurement(EXISTING_REPORT_ID_2, true); addMeasurement(NONEXISTING_REPORT_ID, true); addMeasurement(NONEXISTING_REPORT_ID, true); List<Measurement> measurements = Measurement.selectMeasurementsWithJson(a); if (measurements.size() == 2 && containsMeasurement(measurements, EXISTING_REPORT_ID) && containsMeasurement(measurements, EXISTING_REPORT_ID_2)) Assert.assertTrue(true); Assert.fail(); }

Target:
public void testSelectMeasurementsWithJson() throws IOException { Delete.table(Measurement.class); addMeasurement(EXISTING_REPORT_ID, false); addMeasurement(EXISTING_REPORT_ID_2, true); addMeasurement(NONEXISTING_REPORT_ID, true); List<Measurement> measurements = Measurement.selectMeasurementsWithJson(a); Assert.assertTrue(measurements.size() == 2 && containsMeasurement(measurements, NONEXISTING_REPORT_ID) && containsMeasurement(measurements, EXISTING_REPORT_ID_2)); }
Source:
public void testSetUpActions_Exception(){ Context context = getInstrumentation().getTargetContext(); View layout = mock(View.class); View view1 = new View(context); view1.setId(13); actionList = Lists.of(action1); setupActionGetViewId(); setupTriggerType(); when(layout.findViewById(1)).thenReturn(view1); ComponentActionManager actionManager = new ComponentActionManager(actionList); try{ actionManager.setupActions(layout); } catch(IllegalArgumentException e){ } }

Target:
public void testSetUpActions_Exception() { Context context = getInstrumentation().getTargetContext(); View layout = mock(View.class); View view1 = new View(context); view1.setId(13); actionList = Lists.of(view1Action1); when(layout.findViewById(1)).thenReturn(view1); ComponentActionManager actionManager = new ComponentActionManager(actionList); try { actionManager.setupActions(layout); } catch (IllegalArgumentException e) { } }
Source:
public Map<ArchitectureType, Integer> getDefaultOSes() { HashMap<ArchitectureType, Integer> defaultOSes = new HashMap<ArchitectureType, Integer>(); defaultOSes.put(ArchitectureType.x86_64, DEFAULT_X86_OS); defaultOSes.put(ArchitectureType.ppc64, DEFAULT_PPC_OS); return defaultOSes; }

Target:
public Map<ArchitectureType, Integer> getDefaultOSes() { return defaultOsMap; }
Source:
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException { if (index >= readOptions.size()) { throw new IndexOutOfBoundsException("index " + index + " out of the messageset size " + readOptions.size()); } BlobReadOptions options = readOptions.get(index); long startOffset = options.getOffset() + relativeOffset; long sizeToRead = Math.min(maxSize, options.getMessageInfo().getSize() - relativeOffset); logger.trace("Blob Message Read Set position count {}", startOffset, sizeToRead); long written = 0; if (options.getPreFetchedDataRelativeOffset() != -1) { ByteBuffer buf = options.getPreFetchedData(); buf.flip(); long bufStartOffset = relativeOffset - options.getPreFetchedDataRelativeOffset(); buf.limit((int)(bufStartOffset + sizeToRead)); buf.position((int)(bufStartOffset)); while (buf.hasRemaining()) { written += channel.write(buf); } } else { written = options.getChannel().transferTo(startOffset, sizeToRead, channel); } logger.trace("Written bytes to the write channel from the file channel : {}", written, options.getFile()); return written; }

Target:
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException { if (index >= readOptions.size()) { throw new IndexOutOfBoundsException("index " + index + " out of the messageset size " + readOptions.size()); } BlobReadOptions options = readOptions.get(index); long sizeToRead = Math.min(maxSize, options.getMessageInfo().getSize() - relativeOffset); long written = 0; if (options.getPrefetchedDataRelativeOffset() == -1) { long startOffset = options.getOffset() + relativeOffset; logger.trace("Blob Message Read Set position count {}", startOffset, sizeToRead); written = options.getChannel().transferTo(startOffset, sizeToRead, channel); } else { ByteBuffer buf = options.getPrefetchedData(); long bufStartOffset = relativeOffset - options.getPrefetchedDataRelativeOffset(); buf.limit((int) (bufStartOffset + sizeToRead)); buf.position((int) (bufStartOffset)); written = channel.write(buf); } logger.trace("Written bytes to the write channel from the file channel : {}", written, options.getFile()); return written; }
Source:
private static IOSDriver<?> createAppiumIOSInstance(URL url, DesiredCapabilities capability) { try { List<EventListener> listeners = DriverFactoryHelper.getSeLionEventListeners(); if (listeners.size() > 0) { return new SeLionAppiumIOSDriver( new EventFiringCommandExecutor(new HttpCommandExecutor(url), listeners), capability, url); } else { return new SeLionAppiumIOSDriver(url, capability); } } catch (Exception e) { throw new WebDriverException(e); } }

Target:
private static IOSDriver<? extends WebElement> createAppiumIOSInstance(URL url, DesiredCapabilities capability) { try { List<EventListener> listeners = DriverFactoryHelper.getSeLionEventListeners(); if (listeners.size() > 0) { return new SeLionAppiumIOSDriver( new EventFiringCommandExecutor(new HttpCommandExecutor(url), listeners), capability, url); } else { return new SeLionAppiumIOSDriver(url, capability); } } catch (Exception e) { throw new WebDriverException(e); } }
Source:
public void testStreamProcessor() { final String testSystem = "test-system"; final String inputTopic = "numbers"; final String outputTopic = "output"; final int messageCount = 20; final Config configs = new MapConfig(createConfigs("1", testSystem, inputTopic, outputTopic, messageCount)); createTopics(inputTopic, outputTopic); final StreamProcessor processor = new StreamProcessor( "1", new MapConfig(configs), new HashMap<>(), IdentityStreamTask::new, new StreamProcessorLifeCycleAware() { @Override public void onStart() { } @Override public void onShutdown() { } @Override public void onFailure(Throwable t) { } }); produceMessages(inputTopic, messageCount); run(processor, endLatch); verifyNumMessages(outputTopic, messageCount); }

Target:
public void testStreamProcessor() { final String testSystem = "test-system"; final String inputTopic = "numbers"; final String outputTopic = "output"; final int messageCount = 20; final Config configs = new MapConfig(createConfigs("1", testSystem, inputTopic, outputTopic, messageCount)); createTopics(inputTopic, outputTopic); final StreamProcessor processor = new StreamProcessor( "1", new MapConfig(configs), new HashMap<>(), IdentityStreamTask::new, new StreamProcessorLifecycleListener() { @Override public void onStart() { } @Override public void onShutdown() { } @Override public void onFailure(Throwable t) { } }); produceMessages(inputTopic, messageCount); run(processor, endLatch); verifyNumMessages(outputTopic, messageCount); }
Source:
public String getString(String dataType, BigInteger address, MemoryByte[] data) { StringBuilder strBuffer = new StringBuilder(); int endianess = getEndianness(data); String paddedStr = DebugUIPlugin.getDefault().getPreferenceStore().getString(IDebugUIConstants.PREF_PADDED_STR); if (endianess == RenderingsUtil.LITTLE_ENDIAN) { MemoryByte[] swapped = new MemoryByte[data.length]; for (int i = 0; i < data.length; i++){ swapped[data.length-i-1] = data[i]; } data = swapped; } for (MemoryByte d : data) { if (d.isReadable()) { strBuffer.append(new String(RenderingsUtil.convertByteToCharArray(d.getValue()))); } else { strBuffer.append(paddedStr); } } return strBuffer.toString().toUpperCase(); }

Target:
public String getString(String dataType, BigInteger address, MemoryByte[] data) { StringBuilder strBuffer = new StringBuilder(); int endianess = getEndianness(data); String paddedStr = DebugUIPlugin.getDefault().getPreferenceStore().getString(IDebugUIConstants.PREF_PADDED_STR); if (endianess == RenderingsUtil.LITTLE_ENDIAN) { MemoryByte[] swapped = new MemoryByte[data.length]; for (int i = 0; i < data.length; i++){ swapped[data.length-i-1] = data[i]; } data = swapped; } for (MemoryByte memByte : data) { if (memByte.isReadable()) { strBuffer.append(new String(RenderingsUtil.convertByteToCharArray(memByte.getValue()))); } else { strBuffer.append(paddedStr); } } return strBuffer.toString().toUpperCase(); }
Source:
public BoltConnectionQueueMonitorAggregate( BoltConnectionQueueMonitor... monitors ) { this.monitors = new ArrayList<>( Arrays.asList( monitors ) ); }

Target:
public BoltConnectionQueueMonitorAggregate( BoltConnectionQueueMonitor... monitors ) { this.monitors = Arrays.asList( monitors ); }
Source:
public void testSamePortConfiguredForClientAndElection() throws IOException, ConfigException { QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig(); try { Properties zkProp = getDefaultZKProperties(); zkProp.setProperty("server.1", "localhost:2888:2888"); quorumPeerConfig.parseProperties(zkProp); fail("ConfigException is expected"); } catch (ConfigException ce) { String expectedMessage = "Client and election port must be different! Please update the configuration file on server.1"; assertEquals(expectedMessage, ce.getMessage()); } }

Target:
public void testSamePortConfiguredForClientAndElection() throws IOException, ConfigException { QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig(); Properties zkProp = getDefaultZKProperties(); zkProp.setProperty("server.1", "localhost:2888:2888"); quorumPeerConfig.parseProperties(zkProp); }
Source:
public static ClusterContext validateContext(JsonCluster definition, ClusterContext context, ClusterContext commonContext) throws KaramelException { if (context == null) { context = new ClusterContext(); } context.mergeContext(commonContext); for (JsonGroup group : definition.getGroups()) { Provider provider = UserClusterDataExtractor.getGroupProvider(definition, group.getName()); if (provider instanceof Ec2 && context.getEc2Context() == null) { throw new KaramelException("No valid Ec2 credentials registered :-|"); } if (provider instanceof Ec2 && context.getEc2Context() == null) { throw new KaramelException("No valid Ec2 credentials registered :-|"); } else if (provider instanceof Gce && context.getGceContext() == null) { throw new KaramelException("No valid Gce credentials registered :-|"); } else if (provider instanceof Occi && context.getOcciContext() == null){ throw new KaramelException("No valid Occi credentials registered :-|"); } } if (context.getSshKeyPair() == null) { throw new KaramelException("No ssh keypair chosen :-|"); } return context; }

Target:
public static ClusterContext validateContext(JsonCluster definition, ClusterContext context, ClusterContext commonContext) throws KaramelException { if (context == null) { context = new ClusterContext(); } context.mergeContext(commonContext); for (JsonGroup group : definition.getGroups()) { Provider provider = UserClusterDataExtractor.getGroupProvider(definition, group.getName()); if (provider instanceof Ec2 && context.getEc2Context() == null) { throw new KaramelException("No valid Ec2 credentials registered :-|"); } else if (provider instanceof Gce && context.getGceContext() == null) { throw new KaramelException("No valid Gce credentials registered :-|"); } else if (provider instanceof Nova && context.getNovaContext() == null) { throw new KaramelException("No valid Nova credentials registered :-|"); } else if (provider instanceof Occi && context.getOcciContext() == null) { throw new KaramelException("No valid Occi credentials registered :-|"); } } if (context.getSshKeyPair() == null) { throw new KaramelException("No ssh keypair chosen :-|"); } return context; }
Source:
public void create(Event e){ B86_ZK_4016FileDealer.writeMsg(this.getClass() + e.getName()); }

Target:
public void create(Event e){ Clients.log(this.getClass() + e.getName()); }
Source:
private int onSpinMisses(int spins) { if (UPDATE_STATISTICS) spinMisses.increment(); if (spins == YIELD_SPINS) { spins = 0; Thread.yield(); } else { spins++; JDKSpecific.onSpinWait(); } return spins; }

Target:
private int onSpinMisses(int spins) { if (UPDATE_STATISTICS) spinMisses.increment(); if (spins == YIELD_SPINS) { Thread.yield(); return 0; } JDKSpecific.onSpinWait(); return spins + 1; }
Source:
public void internalTrigger(final org.kie.api.runtime.process.NodeInstance from, String type) { super.internalTrigger(from, type); if (getNodeInstanceContainer().getNodeInstance(getId()) == null) { return; } CompositeNode.NodeAndType nodeAndType = getCompositeNode().internalGetLinkedIncomingNode(type); if (nodeAndType != null) { List<Connection> connections = nodeAndType.getNode().getIncomingConnections(nodeAndType.getType()); for (Iterator<Connection> iterator = connections.iterator(); iterator.hasNext(); ) { Connection connection = iterator.next(); long fromNodeId = from != null ? from.getNodeId() : -1; if (from != null && from.getNode() instanceof AsyncEventNode) { fromNodeId = ((AsyncEventNode) from.getNode()).getPreviousNode(type).getId(); } if ((connection.getFrom() instanceof CompositeNode.CompositeNodeStart) && (from == null || ((CompositeNode.CompositeNodeStart) connection.getFrom()).getInNode().getId() == fromNodeId)) { NodeInstance nodeInstance = getNodeInstance(connection.getFrom()); ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).trigger(null, nodeAndType.getType()); return; } } } else { boolean found = false; for (Node node: getCompositeNode().getNodes()) { if (node instanceof StartNode) { StartNode startNode = (StartNode) node; if (startNode.getTriggers() == null || startNode.getTriggers().isEmpty()) { NodeInstance nodeInstance = getNodeInstance(startNode); ((org.jbpm.workflow.instance.NodeInstance) nodeInstance) .trigger(null, null); found = true; } } } if (found) { return; } } if (isLinkedIncomingNodeRequired()) { throw new IllegalArgumentException( "Could not find start for composite node: " + type); } }

Target:
public void internalTrigger(final org.kie.api.runtime.process.NodeInstance from, String type) { super.internalTrigger(from, type); if (getNodeInstanceContainer().getNodeInstance(getId()) == null) { return; } CompositeNode.NodeAndType nodeAndType = getCompositeNode().internalGetLinkedIncomingNode(type); if (nodeAndType != null) { List<Connection> connections = nodeAndType.getNode().getIncomingConnections(nodeAndType.getType()); for (Iterator<Connection> iterator = connections.iterator(); iterator.hasNext(); ) { Connection connection = iterator.next(); if ((connection.getFrom() instanceof CompositeNode.CompositeNodeStart) && (from == null || ((CompositeNode.CompositeNodeStart) connection.getFrom()).getInNode().getId() == from.getNodeId())) { NodeInstance nodeInstance = getNodeInstance(connection.getFrom()); ((org.jbpm.workflow.instance.NodeInstance) nodeInstance).trigger(null, nodeAndType.getType()); return; } } } else { boolean found = false; for (Node node: getCompositeNode().getNodes()) { if (node instanceof StartNode) { StartNode startNode = (StartNode) node; if (startNode.getTriggers() == null || startNode.getTriggers().isEmpty()) { NodeInstance nodeInstance = getNodeInstance(startNode); ((org.jbpm.workflow.instance.NodeInstance) nodeInstance) .trigger(null, null); found = true; } } } if (found) { return; } } if (isLinkedIncomingNodeRequired()) { throw new IllegalArgumentException( "Could not find start for composite node: " + type); } }
Source:
private void processServerError(ServerErrorCode errorCode) { switch (errorCode) { case Blob_Authorization_Failure: logger.trace("Requested blob authorization failed"); setOperationException( new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobAuthorizationFailure)); break; case Blob_Deleted: logger.trace("Requested blob was deleted"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDeleted)); break; case Blob_Expired: logger.trace("Requested blob has expired"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobExpired)); break; case Blob_Not_Found: logger.trace("Requested blob was not found on this server"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDoesNotExist)); break; case Disk_Unavailable: logger.trace("Requested blob is not accessible"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.AmbryUnavailable)); default: setOperationException( new RouterException("Server returned: " + errorCode, RouterErrorCode.UnexpectedInternalError)); break; } }

Target:
private void processServerError(ServerErrorCode errorCode) { switch (errorCode) { case Blob_Authorization_Failure: logger.trace("Requested blob authorization failed"); setOperationException( new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobAuthorizationFailure)); break; case Blob_Deleted: logger.trace("Requested blob was deleted"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDeleted)); break; case Blob_Expired: logger.trace("Requested blob has expired"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobExpired)); break; case Blob_Not_Found: logger.trace("Requested blob was not found on this server"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.BlobDoesNotExist)); break; case Disk_Unavailable: logger.trace("Disk on which the requested blob resides is not accessible"); setOperationException(new RouterException("Server returned: " + errorCode, RouterErrorCode.AmbryUnavailable)); default: setOperationException( new RouterException("Server returned: " + errorCode, RouterErrorCode.UnexpectedInternalError)); break; } }
Source:
public void testEqualsCondition() { doTest(GoStringIndexIsByteQuickFix.NAME); }

Target:
public void testEqualsCondition() { doTest(); }
Source:
private boolean verifyLocalAvailableSpace(Set<Entity> entities) { val spaceRequired = downloadService.getSpaceRequired(entities); val spaceAvailable = getLocalAvailableSpace(); log.debug("space required: ({}) space available: ({})", FileUtils.byteCountToDisplaySize(spaceRequired), spaceRequired, FileUtils.byteCountToDisplaySize(spaceAvailable), spaceAvailable); if (spaceRequired > spaceAvailable) { terminal.printf("Insufficient space to download requested files: %s. Need %s", FileUtils.byteCountToDisplaySize(spaceRequired), FileUtils.byteCountToDisplaySize(spaceAvailable)); terminal.println(""); terminal.println(""); return false; } return true; }

Target:
private boolean verifyLocalAvailableSpace(Set<Entity> entities) { val spaceRequired = downloadService.getSpaceRequired(entities); val spaceAvailable = getLocalAvailableSpace(); log.debug("space required: ({}) space available: ({})", FileUtils.byteCountToDisplaySize(spaceRequired), spaceRequired, FileUtils.byteCountToDisplaySize(spaceAvailable), spaceAvailable); if (spaceRequired > spaceAvailable) { terminal.printf("Insufficient space to download requested files: Require %s. %s Available", FileUtils.byteCountToDisplaySize(spaceRequired), FileUtils.byteCountToDisplaySize(spaceAvailable)); terminal.println(""); terminal.println(""); return false; } return true; }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String finalLanguageList = StringUtil.listToJsonArrayString(app.language().getAppLanguageCodes()); List<Boolean> finalFeedCardsEnabled = Prefs.getFeedCardsEnabled(); List<Integer> finalFeedCardsOrder = Prefs.getFeedCardsOrder(); if (requestCode == ACTIVITY_REQUEST_ADD_A_LANGUAGE && (!finalLanguageList.equals(initialLanguageList))) { setResult(ACTIVITY_RESULT_LANGUAGE_CHANGED); } else if (requestCode == ACTIVITY_REQUEST_FEED_CONFIGURE && (!initialFeedCardsEnabled.equals(finalFeedCardsEnabled) || !initialFeedCardsOrder.equals(finalFeedCardsOrder))) { setResult(ACTIVITY_RESULT_FEED_CONFIGURATION_CHANGED); } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String finalLanguageList = StringUtil.listToJsonArrayString(app.language().getAppLanguageCodes()); if (requestCode == ACTIVITY_REQUEST_ADD_A_LANGUAGE && (!finalLanguageList.equals(initialLanguageList))) { setResult(ACTIVITY_RESULT_LANGUAGE_CHANGED); } else if (requestCode == ACTIVITY_REQUEST_FEED_CONFIGURE && (!Prefs.getFeedCardsEnabled().equals(initialFeedCardsEnabled) || !Prefs.getFeedCardsOrder().equals(initialFeedCardsOrder))) { setResult(ACTIVITY_RESULT_FEED_CONFIGURATION_CHANGED); } }
Source:
public void setExecutorActive(final boolean isActive, final String host, final int port) throws ExecutorManagerException { final Executor executor = this.executorLoader.fetchExecutor(host, port); Preconditions.checkState(executor != null, "Unable to obtain self entry in DB"); if (executor.isActive() != isActive) { executor.setActive(isActive); this.executorLoader.updateExecutor(executor); } else { logger.info( "Set active action ignored. Executor is already " + (isActive ? "active" : "inactive")); } this.active = isActive; if (!this.active) { waitUntilFlowPreparationFinish(); } }

Target:
public void setExecutorActive(final boolean isActive, final String host, final int port) throws ExecutorManagerException, InterruptedException { final Executor executor = this.executorLoader.fetchExecutor(host, port); Preconditions.checkState(executor != null, "Unable to obtain self entry in DB"); if (executor.isActive() != isActive) { executor.setActive(isActive); this.executorLoader.updateExecutor(executor); } else { logger.info( "Set active action ignored. Executor is already " + (isActive ? "active" : "inactive")); } this.active = isActive; if (!this.active) { waitUntilFlowPreparationFinish(); } }
Source:
public Boolean call() throws Exception { long sleepBackoff = 200L; while (poolState == POOL_NORMAL && totalConnections.get() < config.getMaximumPoolSize()) { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry != null) { totalConnections.incrementAndGet(); connectionBag.add(poolEntry); return Boolean.TRUE; } quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 5, (long) (sleepBackoff * 1.3)); } return Boolean.FALSE; }

Target:
public Boolean call() throws Exception { long sleepBackoff = 200L; while (poolState == POOL_NORMAL && totalConnections.get() < config.getMaximumPoolSize()) { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry != null) { totalConnections.incrementAndGet(); connectionBag.add(poolEntry); return Boolean.TRUE; } quietlySleep(sleepBackoff); sleepBackoff = Math.min( TimeUnit.SECONDS.toMillis(10), Math.min(connectionTimeout, (long) (sleepBackoff * 1.3))); } return Boolean.FALSE; }
Source:
public void run() { while (true) { try { registrationManager.updateRegistration(configuration.getConnectorId(), configuration.getContent()); LOGGER.info("successfully recreated connector from persistence", configuration.getConnectorId()); break; } catch (ConnectorValidationFailedException e) { LOGGER.error("connector that has been loaded from persistence was found to be invalid", configuration.getConnectorId(), e); break; } catch (OsgiServiceNotAvailableException e) { LOGGER.warn("connector that has been loaded from persistence could not be created because the" + "factory-service was missing", configuration.getConnectorId()); continue; } catch (Exception e) { LOGGER.error("connector that has been loaded from persistence could not be created because of an unexpected Error", e); break; } } semaphore.release(); }

Target:
public void run() { while (true) { try { registrationManager.updateRegistration(configuration.getConnectorId(), configuration.getContent()); LOGGER.info("successfully recreated connector from persistence", configuration.getConnectorId()); break; } catch (ConnectorValidationFailedException e) { LOGGER.error("connector that has been loaded from persistence was found to be invalid", configuration.getConnectorId(), e); break; } catch (OsgiServiceNotAvailableException e) { LOGGER.warn("connector that has been loaded from persistence could not be created because the" + "factory-service was missing", configuration.getConnectorId()); continue; } catch (Exception e) { LOGGER.error("connector that has been loaded from persistence could not be created because of" + "an unexpected Error", e); break; } } semaphore.release(); }
Source:
public void testNormalBinlogReplicationDiagnostic() throws Exception { MaxwellDiagnosticContext.Config config = new MaxwellDiagnosticContext.Config(); config.timeout = 5000; MaxwellContext maxwellContext = buildContext(); DiagnosticHealthCheck healthCheck = getDiagnosticHealthCheck(config, maxwellContext); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(outputStream); when(response.getWriter()).thenReturn(writer); final CountDownLatch latch = new CountDownLatch(1); Maxwell maxwell = new MaxwellWithContext(maxwellContext) { @Override protected void onReplicatorStart() { latch.countDown(); } }; new Thread(maxwell).start(); latch.await(); healthCheck.doGet(request, response); writer.flush(); String result = new String(outputStream.toByteArray()); assertTrue(result.contains("\"name\":\"binlog-connector\",\"success\":true")); maxwell.terminate(); writer.close(); }

Target:
public void testNormalBinlogReplicationDiagnostic() throws Exception { MaxwellDiagnosticContext.Config config = new MaxwellDiagnosticContext.Config(); config.timeout = 5000; MaxwellContext maxwellContext = buildContext(); DiagnosticHealthCheck healthCheck = getDiagnosticHealthCheck(config, maxwellContext); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(writer); final CountDownLatch latch = new CountDownLatch(1); Maxwell maxwell = new MaxwellWithContext(maxwellContext) { @Override protected void onReplicatorStart() { latch.countDown(); } }; new Thread(maxwell).start(); latch.await(); healthCheck.doGet(request, response); writer.flush(); JsonNode binlogNode = getBinlogNode(); assertThat(binlogNode.get("name").asText(), is("binlog-connector")); assertThat(binlogNode.get("success").asBoolean(), is(true)); assertTrue(binlogNode.get("mandatory").asBoolean()); assertTrue(binlogNode.get("message").asText().contains("Binlog replication lag")); maxwell.terminate(); }
Source:
private static Expression toSymbolExpression(Symbol symbol) { if (symbol instanceof SymbolWithSubfieldPath) { SubfieldPath path = ((SymbolWithSubfieldPath) symbol).getPath(); Expression base = new SymbolReference(symbol.getName()); for (int i = 1; i < path.getPath().size(); i++) { SubfieldPath.PathElement element = path.getPath().get(i); if (element instanceof NestedField) { base = new DereferenceExpression(base, new Identifier(((NestedField) element).getName())); } else if (element instanceof LongSubscript) { base = new SubscriptExpression(base, new LongLiteral(String.valueOf(((LongSubscript) element).getIndex()))); } else if (element instanceof StringSubscript) { base = new SubscriptExpression(base, new StringLiteral(((StringSubscript) element).getIndex())); } else { throw new IllegalArgumentException("Unsupported path element: " + element.getClass().getSimpleName()); } } return base; } return symbol.toSymbolReference(); }

Target:
private static Expression toSymbolExpression(Symbol symbol) { if (symbol instanceof SymbolWithSubfieldPath) { SubfieldPath path = ((SymbolWithSubfieldPath) symbol).getSubfieldPath(); Expression base = new SymbolReference(symbol.getName()); for (int i = 1; i < path.getPath().size(); i++) { SubfieldPath.PathElement element = path.getPath().get(i); if (element instanceof NestedField) { base = new DereferenceExpression(base, new Identifier(((NestedField) element).getName())); } else if (element instanceof LongSubscript) { base = new SubscriptExpression(base, new LongLiteral(String.valueOf(((LongSubscript) element).getIndex()))); } else if (element instanceof StringSubscript) { base = new SubscriptExpression(base, new StringLiteral(((StringSubscript) element).getIndex())); } else { throw new IllegalArgumentException("Unsupported path element: " + element.getClass().getSimpleName()); } } return base; } return symbol.toSymbolReference(); }
Source:
void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { RederivableNode node = getFirstRederivable(); while (node != null) { node.rederiveOne(); node = getFirstRederivable(); } if (!activeMailboxes.isEmpty()) { Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } } }

Target:
void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { while (!activeMailboxes.isEmpty()) { Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } RederivableNode node = getFirstRederivable(); if (node != null) { node.rederiveOne(); } } }
Source:
public long populate(final ByteSource source, final Map<K, V> map) throws IOException { return source.asCharSource(Charsets.UTF_8).readLines( new LineProcessor<Long>() { private long count = 0L; @Override public boolean processLine(String line) throws IOException { final Map<K, V> kvMap = parser.parse(line); if (kvMap != null) { map.putAll(kvMap); count += map.size(); } return true; } @Override public Long getResult() { return count; } } ); }

Target:
public PopulateResult populate(final ByteSource source, final Map<K, V> map) throws IOException { return source.asCharSource(Charsets.UTF_8).readLines( new LineProcessor<PopulateResult>() { private int lines = 0; private int entries = 0; @Override public boolean processLine(String line) throws IOException { if (lines == Integer.MAX_VALUE) { throw new ISE("Cannot read more than %,d lines", Integer.MAX_VALUE); } final Map<K, V> kvMap = parser.parse(line); map.putAll(kvMap); lines++; entries += kvMap.size(); return true; } @Override public PopulateResult getResult() { return new PopulateResult(lines, entries); } } ); }
Source:
protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception { final SettableFuture f = futures.get(msg.getCommandId()); switch (msg.getCommand()) { case MUTATE: if (!msg.getMutate().getProcessed()) { f.setException(new IOException("Not Processed")); } f.set(null); break; case SCAN: final long scannerId = msg.getScan().getScannerId(); ClientScanner clientScanner; if (CLIENT_SCANNER_MANAGER.hasScanner(scannerId)) { clientScanner = CLIENT_SCANNER_MANAGER.get(scannerId); } else { clientScanner = CLIENT_SCANNER_MANAGER.createAndGet(ctx.channel(), scannerId, msg.getCommandId()); f.set(scannerId); } clientScanner.add(msg.getScan()); if (!msg.getScan().getMoreResults()) { clientScanner.close(); } break; default: f.set(msg); break; } }

Target:
protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception { switch (msg.getCommand()) { case MUTATE: final SettableFuture<Response> f = futures.get(msg.getCommandId()); if (!msg.getMutate().getProcessed()) { f.setException(new IOException("Not Processed")); } f.set(null); break; case SCAN: final long scannerId = msg.getScan().getScannerId(); ClientScanner clientScanner; if (CLIENT_SCANNER_MANAGER.hasScanner(scannerId)) { clientScanner = CLIENT_SCANNER_MANAGER.get(scannerId); } else { clientScanner = CLIENT_SCANNER_MANAGER.createAndGet(ctx.channel(), scannerId, msg.getCommandId()); scannerFutures.get(msg.getCommandId()).set(scannerId); } clientScanner.add(msg.getScan()); if (!msg.getScan().getMoreResults()) { clientScanner.close(); } break; default: futures.get(msg.getCommandId()).set(msg); break; } }
Source:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } HibernateConstraintValidatorInitializationContextImpl hibernateConstraintValidatorInitializationContextImpl = (HibernateConstraintValidatorInitializationContextImpl) o; if ( scriptEvaluatorFactory != null ? scriptEvaluatorFactory != hibernateConstraintValidatorInitializationContextImpl.scriptEvaluatorFactory : hibernateConstraintValidatorInitializationContextImpl.scriptEvaluatorFactory != null ) { return false; } if ( clockProvider != null ? clockProvider != hibernateConstraintValidatorInitializationContextImpl.clockProvider : hibernateConstraintValidatorInitializationContextImpl.clockProvider != null ) { return false; } if ( temporalValidationTolerance != null ? !temporalValidationTolerance.equals( hibernateConstraintValidatorInitializationContextImpl.temporalValidationTolerance ) : hibernateConstraintValidatorInitializationContextImpl.temporalValidationTolerance != null ) { return false; } if ( constraintValidatorPayload != null ? constraintValidatorPayload != hibernateConstraintValidatorInitializationContextImpl.constraintValidatorPayload : hibernateConstraintValidatorInitializationContextImpl.constraintValidatorPayload != null ) { return false; } return true; }

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } HibernateConstraintValidatorInitializationContextImpl hibernateConstraintValidatorInitializationContextImpl = (HibernateConstraintValidatorInitializationContextImpl) o; if ( scriptEvaluatorFactory != hibernateConstraintValidatorInitializationContextImpl.scriptEvaluatorFactory ) { return false; } if ( clockProvider != hibernateConstraintValidatorInitializationContextImpl.clockProvider ) { return false; } if ( !temporalValidationTolerance.equals( hibernateConstraintValidatorInitializationContextImpl.temporalValidationTolerance ) ) { return false; } if ( constraintValidatorPayload != hibernateConstraintValidatorInitializationContextImpl.constraintValidatorPayload ) { return false; } return true; }
Source:
public static Resource locateModuleResource(SimpleModuleDefinition definition, ClassLoader moduleClassLoader, String extension) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(moduleClassLoader); Resource result = null; String ext = extension.startsWith(".") ? extension : "." + extension; try { Resource[] resources = resolver.getResources("/config/*" + ext); if (resources.length > 1) { throw new IllegalStateException("Multiple top level module resources found :" + StringUtils .arrayToCommaDelimitedString(resources)); } else if (resources.length == 1) { result = resources[0]; } } catch (IOException e) { throw new RuntimeException(e); } return result; }

Target:
public static Resource locateModuleResource(SimpleModuleDefinition definition, ClassLoader moduleClassLoader, String extension) { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(moduleClassLoader); Resource moduleLocation = resolver.getResource(definition.getLocation()); Assert.isTrue(moduleLocation.exists(), "module resource " + definition.getLocation() + " does not exist"); ClassLoader parentClassloader = moduleClassLoader == null? null : moduleClassLoader.getParent(); PathMatchingResourcePatternResolver moduleResolver = new PathMatchingResourcePatternResolver (createModuleClassLoader(moduleLocation, parentClassloader, false)); Resource result = null; String ext = extension.startsWith(".") ? extension : "." + extension; try { Resource[] resources = moduleResolver.getResources("classpath:/config/*" + ext); if (resources.length > 1) { throw new IllegalStateException("Multiple top level module resources found :" + StringUtils .arrayToCommaDelimitedString(resources)); } else if (resources.length == 1) { result = resources[0]; } } catch (IOException e) { return null; } return result; }
Source:
private List<EmailWrapper> generateFeedbackSessionClosedEmail( CourseAttributes course, FeedbackSessionAttributes session, List<InstructorAttributes> instructors, List<StudentAttributes> students) { List<EmailWrapper> emails = new ArrayList<EmailWrapper>(); String instructorFragmentArgumentInstructors = "<p>The email below has been sent to students of course: " + SanitizationHelper.sanitizeForHtml(course.getId()) + ", " + SanitizationHelper.sanitizeForHtml(course.getName()) + ".<br>" + Const.EOL + "<br>" + Const.EOL + "=== Email message as seen by the students ===</p>" + Const.EOL; String instructorFragmentArgumentStudents = ""; for (InstructorAttributes instructor : instructors) { emails.add(generateFeedbackSessionClosedEmail(course, session, instructor.name, instructor.email, instructorFragmentArgumentInstructors)); } for (StudentAttributes student : students) { emails.add(generateFeedbackSessionClosedEmail(course, session, student.name, student.email, instructorFragmentArgumentStudents)); } return emails; }

Target:
private List<EmailWrapper> generateFeedbackSessionClosedEmail( CourseAttributes course, FeedbackSessionAttributes session, List<InstructorAttributes> instructors, List<StudentAttributes> students) { List<EmailWrapper> emails = new ArrayList<EmailWrapper>(); String instructorPreamble = generateInstructorPreamble(course.getId(), course.getName()); String studentPreamble = ""; for (InstructorAttributes instructor : instructors) { emails.add(generateFeedbackSessionClosedEmail(course, session, instructor.name, instructor.email, instructorPreamble)); } for (StudentAttributes student : students) { emails.add(generateFeedbackSessionClosedEmail(course, session, student.name, student.email, studentPreamble)); } return emails; }
Source:
private void createPerspectiveBarExtras() { String persps = PrefUtil.getAPIPreferenceStore() .getString(IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); String[] parts = persps.split("[, ]"); Set<String> perspSet = new LinkedHashSet<>(); for (String part : parts) { part = part.trim(); if (!part.isEmpty()) perspSet.add(part); } WorkbenchPage page = (WorkbenchPage) window.getContext().get(IWorkbenchPage.class); for (String perspId : perspSet) { MPerspective persp = (MPerspective) modelService.find(perspId, window); if (persp != null) continue; IPerspectiveDescriptor desc = getDescriptorFor(perspId); if (desc == null) continue; persp = page.createPerspective(desc); persp.setLabel(desc.getLabel()); getPerspectiveStack().getChildren().add(persp); } }

Target:
private void createPerspectiveBarExtras() { String persps = PrefUtil.getAPIPreferenceStore() .getString(IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); String[] parts = persps.split("[, ]"); Set<String> perspSet = new LinkedHashSet<>(); for (String part : parts) { part = part.trim(); if (!part.isEmpty()) perspSet.add(part); } for (String perspId : perspSet) { MPerspective persp = (MPerspective) modelService.find(perspId, window); if (persp != null) continue; IPerspectiveDescriptor desc = getDescriptorFor(perspId); if (desc == null) continue; persp = createPerspective(desc); persp.setLabel(desc.getLabel()); getPerspectiveStack().getChildren().add(persp); } }
Source:
private Instant getEndOfTheDayOffsetNowInAdminTimeZone(int dayOffset) { return TimeHelper.getInstantDaysOffsetFromNow(dayOffset).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID) .toLocalDate().atTime(23, 59, 59).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID).toInstant(); }

Target:
private Instant getEndOfTheDayOffsetNowInAdminTimeZone(int dayOffset) { return TimeHelper.getInstantDaysOffsetFromNow(dayOffset).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID) .toLocalDate().atTime(LocalTime.MAX).atZone(Const.SystemParams.ADMIN_TIME_ZONE_ID).toInstant(); }
Source:
public Object handleValidationException(ValidationException e, HandlerMethod handlerMethod) { LOG.info(e.getErrorCode(), e); return handleTypedException(isHtmlRequest(handlerMethod), NotFoundController.URI, e.getLocalizedMessage(), BAD_REQUEST, e.getErrorCode()); }

Target:
public Object handleValidationException(ValidationException e, HandlerMethod handlerMethod) { LOG.info(e.getErrorCode(), e); return handleTypedException(isHtmlRequest(handlerMethod), BadRequestController.URI, e.getLocalizedMessage(), BAD_REQUEST, e.getErrorCode()); }
Source:
ModelBuilder addRepeatGroup(String name) { TreeElement child = new TreeElement(name, 0); child.setDataType(DataType.NULL.value); child.setRepeatable(true); child.setParent(current); current.addChild(child); current = child; return this; }

Target:
ModelBuilder addRepeatGroup(String name) { TreeElement child = new TreeElement(name, DEFAULT_MULTIPLICITY); child.setDataType(DataType.NULL.value); child.setRepeatable(true); child.setParent(current); current.addChild(child); current = child; return this; }
Source:
public AbstractExpression getFirstArgument() { if (m_left != null) { return m_left; } if (m_args != null && m_args.size() > 0) { return m_args.get(0); } return null; }

Target:
public AbstractExpression getFirstArgument() { if (m_left != null) { assert(m_args == null); return m_left; } if (m_args != null && m_args.size() > 0) { assert(m_left == null && m_right == null); return m_args.get(0); } return null; }
Source:
public void deletePrefix(WinePrefixContainerDTO winePrefix, Consumer<Exception> errorCallback) { try { fileUtilities.remove(new File(winePrefix.getPath())); } catch (IOException e) { LOGGER.error("Cannot delete Wine prefix (" + winePrefix.getPath() + ")! Exception: " + e.toString()); errorCallback.accept(e); } List<ShortcutCategoryDTO> categories = libraryManager.fetchShortcuts(); for (ShortcutCategoryDTO shortcutCategoryDTO : categories) { for (ShortcutDTO shortcutDTO : shortcutCategoryDTO.getShortcuts()) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Functions\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String container = (String) shortcutReader.callMember("container"); if (container.equals(winePrefix.getName())) { shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback); } } }

Target:
public void deletePrefix(WinePrefixContainerDTO winePrefix, Consumer<Exception> errorCallback) { try { fileUtilities.remove(new File(winePrefix.getPath())); } catch (IOException e) { LOGGER.error("Cannot delete Wine prefix (" + winePrefix.getPath() + ")! Exception: " + e.toString()); errorCallback.accept(e); } List<ShortcutCategoryDTO> categories = libraryManager.fetchShortcuts(); categories.stream().flatMap(shortcutCategoryDTO -> shortcutCategoryDTO.getShortcuts().stream()) .forEach(shortcutDTO -> { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter .createInteractiveSession(); interactiveScriptSession.eval("include([\"Functions\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String container = (String) shortcutReader.callMember("container"); if (container.equals(winePrefix.getName())) { shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback); }); }
Source:
private boolean containsForbiddenFragment(String firstSentence) { final String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN .matcher(firstSentence).replaceAll(" ").trim(); final StringBuilder finalText = new StringBuilder(100); boolean previousWhitespace = true; for (char letter : javadocText.toCharArray()) { final char print; if (Character.isWhitespace(letter)) { if (previousWhitespace) { continue; } previousWhitespace = true; print = ' '; } else { previousWhitespace = false; print = letter; } finalText.append(print); } return forbiddenSummaryFragments.matcher(finalText).find(); }

Target:
private boolean containsForbiddenFragment(String firstSentence) { final String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN .matcher(firstSentence).replaceAll(" ").trim(); return forbiddenSummaryFragments.matcher(trimExcessWhitespaces(javadocText)).find(); }
Source:
public Response clearFlairTemplates(String type, String subreddit) { if (!type.equalsIgnoreCase("USER_FLAIR") && !type.equalsIgnoreCase("LINK_FLAIR")) { System.err.println("Type must be either USER_FLAIR or LINK_FLAIR."); Response response = new Response() { @Override public int getStatusCode() { return 400; } @Override public Object getResponseObject() { return null; } @Override public String getResponseText() { return "Bad request, type must be either USER_FLAIR or LINK_FLAIR. (Generated by FlairActions.clearFlairTemplates(String, String);)"; } }; return response; } String params = "" + "api_type=" + "json" + "&uh=" + user.getModhash() + "&flair_type=" + type; return restClient.post(params, String.format(ApiEndpointUtils.CLEAR_SUBREDDIT_FLAIR_TEMPLATES, subreddit), user.getCookie()); }

Target:
public Response clearFlairTemplates(String type, String subreddit) { if (!type.equalsIgnoreCase("USER_FLAIR") && !type.equalsIgnoreCase("LINK_FLAIR")) { System.err.println("Type must be either USER_FLAIR or LINK_FLAIR."); Response response = new Response() { @Override public int getStatusCode() { return 400; } @Override public Object getResponseObject() { return null; } @Override public String getResponseText() { return "Bad request, type must be either USER_FLAIR or LINK_FLAIR. (Generated by FlairActions.clearFlairTemplates(String, String);)"; } }; return response; } String params = "" + "api_type=json" + "&uh=" + user.getModhash() + "&flair_type=" + type; return restClient.post(params, String.format(ApiEndpointUtils.CLEAR_SUBREDDIT_FLAIR_TEMPLATES, subreddit), user.getCookie()); }
Source:
protected String getValue(Environment env, Map params) throws TemplateModelException, IOException { String path = getStringValue(params.get("path")); String targetJournal = getStringValue(params.remove("journalKey")); String handlerName = getStringValue(params.remove("handlerName")); SitePageContext sitePageContext = new SitePageContext(siteResolver, handlerMappingConfig, env); if (handlerName != null) { return targetJournal == null ? sitePageContext.buildLink(handlerName, params) : sitePageContext.buildLink(siteSet, targetJournal, handlerName, params); } else if (path != null) { return targetJournal == null ? sitePageContext.buildLink(path) : sitePageContext.buildLink(siteSet, targetJournal, path); } else { throw new RuntimeException("Either a path or handlerName parameter is required"); } }

Target:
protected String getValue(Environment env, Map params) throws TemplateModelException, IOException { String path = getStringValue(params.get("path")); String targetJournal = getStringValue(params.get("journalKey")); String handlerName = getStringValue(params.get("handlerName")); SitePageContext sitePageContext = new SitePageContext(siteResolver, env); Site site = sitePageContext.getSite(); Link.Factory linkFactory = (targetJournal == null) ? Link.toLocalSite(site) : Link.toForeignSite(site, targetJournal, siteSet); final Link link; if (handlerName != null) { Map<String, ?> variables = getValueAsMap(params.get("pathVariables")); ListMultimap<String, ?> queryParameters = getValueAsMultimap(params.get("queryParameters")); List<?> wildcardValues = getValueAsList(params.get("wildcardValues")); link = linkFactory.toPattern(requestHandlerPatternDictionary, handlerName, variables, queryParameters, wildcardValues); } else if (path != null) { link = linkFactory.toPath(path); } else { throw new RuntimeException("Either a path or handlerName parameter is required"); } return link.get(sitePageContext.getRequest()); }