auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void put(MessageWriteSet messageSetToWrite) throws StoreException { synchronized (lock) { checkStarted(); try { for (MessageInfo info : messageSetToWrite.getMessageSetInfo()) { if (index.exist(info.getStoreKey())) { throw new StoreException("key already exist in store. cannot be overwritten", StoreErrorCodes.Already_Exist); } } long writeStartOffset = log.getLogEndOffset(); messageSetToWrite.writeTo(log); List<MessageInfo> messageInfo = messageSetToWrite.getMessageSetInfo(); ArrayList<BlobIndexEntry> indexEntries = new ArrayList<BlobIndexEntry>(messageInfo.size()); for (MessageInfo info : messageInfo) { BlobIndexValue value = new BlobIndexValue(info.getSize(), writeStartOffset, (byte)0, info.getTimeToLiveInMs()); BlobIndexEntry entry = new BlobIndexEntry(info.getStoreKey(), value); indexEntries.add(entry) ; writeStartOffset += info.getSize(); } index.addToIndex(indexEntries, log.getLogEndOffset()); metrics.writes.inc(1); } catch (IOException e) { throw new StoreException("io error while trying to fetch blobs : " + e, StoreErrorCodes.IOError); } } }

Target:
public void put(MessageWriteSet messageSetToWrite) throws StoreException { synchronized (lock) { checkStarted(); try { for (MessageInfo info : messageSetToWrite.getMessageSetInfo()) { if (index.exists(info.getStoreKey())) { throw new StoreException("key already exist in store. cannot be overwritten", StoreErrorCodes.Already_Exist); } } long writeStartOffset = log.getLogEndOffset(); messageSetToWrite.writeTo(log); List<MessageInfo> messageInfo = messageSetToWrite.getMessageSetInfo(); ArrayList<BlobIndexEntry> indexEntries = new ArrayList<BlobIndexEntry>(messageInfo.size()); for (MessageInfo info : messageInfo) { BlobIndexValue value = new BlobIndexValue(info.getSize(), writeStartOffset, (byte)0, info.getTimeToLiveInMs()); BlobIndexEntry entry = new BlobIndexEntry(info.getStoreKey(), value); indexEntries.add(entry) ; writeStartOffset += info.getSize(); } index.addToIndex(indexEntries, log.getLogEndOffset()); metrics.writes.inc(1); } catch (IOException e) { throw new StoreException("io error while trying to fetch blobs : " + e, StoreErrorCodes.IOError); } } }
Source:
private static void loadDistributionsFromJson(String jsonString) { DISTRIBUTIONS = Lists.newArrayList(); Type fullRevisionType = new TypeToken<FullRevision>(){}.getType(); GsonBuilder gsonBuilder = new GsonBuilder() .registerTypeAdapter(fullRevisionType, new JsonDeserializer<FullRevision>() { @Override public FullRevision deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return FullRevision.parseRevision(json.getAsString()); } }); Gson gson = gsonBuilder.create(); Type listType = new TypeToken<ArrayList<Distribution>>() {}.getType(); try { DISTRIBUTIONS = gson.fromJson(jsonString, listType); } catch (JsonParseException e) { LOG.error(e); } }

Target:
private static List<Distribution> loadDistributionsFromJson(String jsonString) { Type fullRevisionType = new TypeToken<FullRevision>(){}.getType(); GsonBuilder gsonBuilder = new GsonBuilder() .registerTypeAdapter(fullRevisionType, new JsonDeserializer<FullRevision>() { @Override public FullRevision deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return FullRevision.parseRevision(json.getAsString()); } }); Gson gson = gsonBuilder.create(); Type listType = new TypeToken<ArrayList<Distribution>>() {}.getType(); try { return gson.fromJson(jsonString, listType); } catch (JsonParseException e) { LOG.error(e); } return null; }
Source:
public void testLotsOfCollisions() throws Exception { Random rand = new Random(45734985); int[] nums = new int[1000]; int[] expectedCounts = new int[5]; for (int i = 0; i < nums.length; i++) { nums[i] = rand.nextInt(expectedCounts.length); expectedCounts[nums[i]]++; } try (LoaderExecutor loader = client.newLoaderExecutor()) { for (int num : nums) { loader.execute(new NumLoader(num)); } } miniFluo.waitForObservers(); try (TypedSnapshot snapshot = typeLayer.wrap(client.newSnapshot())) { for (int i = 0; i < expectedCounts.length; i++) { Assert.assertEquals(expectedCounts[i], snapshot.get().row(i).fam("stat").qual("total").toInteger(-1)); } Assert.assertEquals(1000, snapshot.get().row("all").fam("stat").qual("total").toInteger(-1)); } long oldestTS = ZookeeperUtil.getOldestTimestamp(config.getZookeepers()); while (true) { UtilWaitThread.sleep(300); long tmp = ZookeeperUtil.getOldestTimestamp(config.getZookeepers()); if (oldestTS == tmp) { break; } oldestTS = tmp; } conn.tableOperations().compact(getCurTableName(), null, null, true, true); Scanner scanner = conn.createScanner(getCurTableName(), Authorizations.EMPTY); HashSet<String> rowCols = new HashSet<>(); for (Entry<Key,Value> entry : scanner) { Key k = entry.getKey(); String rowCol = k.getRow() + ":" + k.getColumnFamily() + ":" + k.getColumnQualifier() + ":" + String.format("%x", k.getTimestamp() & ColumnConstants.PREFIX_MASK); Assert.assertFalse("Duplicate row col " + rowCol, rowCols.contains(rowCol)); rowCols.add(rowCol); } }

Target:
public void testLotsOfCollisions() throws Exception { Random rand = new Random(45734985); int[] nums = new int[1000]; int[] expectedCounts = new int[5]; for (int i = 0; i < nums.length; i++) { nums[i] = rand.nextInt(expectedCounts.length); expectedCounts[nums[i]]++; } try (LoaderExecutor loader = client.newLoaderExecutor()) { for (int num : nums) { loader.execute(new NumLoader(num)); } } miniFluo.waitForObservers(); try (TypedSnapshot snapshot = typeLayer.wrap(client.newSnapshot())) { for (int i = 0; i < expectedCounts.length; i++) { Assert.assertEquals(expectedCounts[i], snapshot.get().row(i).fam("stat").qual("total").toInteger(-1)); Assert.assertEquals(expectedCounts[i], snapshot.get().row(i).fam("stat").qual("processed").toInteger(-1)); } Assert.assertEquals(1000, snapshot.get().row("all").fam("stat").qual("total").toInteger(-1)); } long oldestTS = ZookeeperUtil.getOldestTimestamp(config.getZookeepers()); while (true) { UtilWaitThread.sleep(300); long tmp = ZookeeperUtil.getOldestTimestamp(config.getZookeepers()); if (oldestTS == tmp) { break; } oldestTS = tmp; } conn.tableOperations().compact(getCurTableName(), null, null, true, true); Scanner scanner = conn.createScanner(getCurTableName(), Authorizations.EMPTY); HashSet<String> rowCols = new HashSet<>(); for (Entry<Key,Value> entry : scanner) { Key k = entry.getKey(); String rowCol = k.getRow() + ":" + k.getColumnFamily() + ":" + k.getColumnQualifier() + ":" + String.format("%x", k.getTimestamp() & ColumnConstants.PREFIX_MASK); Assert.assertFalse("Duplicate row col " + rowCol, rowCols.contains(rowCol)); rowCols.add(rowCol); } }
Source:
public void sendEmail( final String jobId ) throws GenieException { try { log.debug("Got a job finished event. Sending email."); final JobRequest jobRequest = this.jobSearchService.getJobRequest(jobId); final Job job = this.jobSearchService.getJob(jobId); if (org.apache.commons.lang3.StringUtils.isNotBlank(jobRequest.getEmail())) { final String message = new StringBuilder() .append("Job with id [") .append(jobId).append("] finished with status ") .append(job.getStatus()) .toString(); this.mailServiceImpl.sendEmail( jobRequest.getEmail(), message, message ); } } catch (Exception e) { log.debug("Could not send email for job: {}", jobId, e); } }

Target:
public void sendEmail( final String jobId ) throws GenieException { try { log.debug("Got a job finished event. Sending email."); final JobRequest jobRequest = this.jobSearchService.getJobRequest(jobId); final Job job = this.jobSearchService.getJob(jobId); if (StringUtils.isNotBlank(jobRequest.getEmail())) { final String message = new StringBuilder() .append("Job with id [") .append(jobId).append("] finished with status ") .append(job.getStatus()) .toString(); this.mailServiceImpl.sendEmail( jobRequest.getEmail(), message, message ); } } catch (Exception e) { log.debug("Could not send email for job: {}", jobId, e); } }
Source:
public static void main(final String[] args) throws Exception { final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); final CommandLine commandLine = MISTExampleUtils.getDefaultCommandLine(jcb) .registerShortNameOfClass(NettySourceAddress.class) .processCommandLine(args); if (commandLine == null) { return; } Thread sinkServer = new Thread(MISTExampleUtils.getSinkServer()); sinkServer.start(); final APIQueryControlResult result = submitQuery(jcb.build()); System.out.println("Query submission result: " + result.getQueryId()); }

Target:
public static void main(final String[] args) throws Exception { final JavaConfigurationBuilder jcb = Tang.Factory.getTang().newConfigurationBuilder(); final CommandLine commandLine = MISTExampleUtils.getDefaultCommandLine(jcb) .processCommandLine(args); if (commandLine == null) { return; } Thread sinkServer = new Thread(MISTExampleUtils.getSinkServer()); sinkServer.start(); final APIQueryControlResult result = submitQuery(jcb.build()); System.out.println("Query submission result: " + result.getQueryId()); }
Source:
@Override public void testSiteBuildWithForkedMojo() throws Exception { }

Target:
public void testSiteBuildWithForkedMojo() throws Exception { }
Source:
@Test public void testRequestMalformed() throws Throwable { enqueueFromFile("announce_malformed.json"); AnnouncementClient.Callback cb = mock(AnnouncementClient.Callback.class); request(cb); server().takeRequest(); verify(cb, never()).success(eq(new ArrayList<Card>())); verify(cb).error(any(Throwable.class)); }

Target:
@Test public void testRequestMalformed() throws Throwable { server().enqueue("Jimmy crack corn, and I don't care."); Callback cb = mock(Callback.class); request(cb); server().takeRequest(); verify(cb, never()).success(anyListOf(Card.class)); verify(cb).error(any(Throwable.class)); }
Source:
public void markDuplicatesWithRemovingDuplicatesIntegrationTest(final String input) { final File outputDir = IOUtil.createTempDir(TEST_BASE_NAME + ".", ".tmp"); outputDir.deleteOnExit(); final List<String> args = new ArrayList<>(); args.add("INPUT=" + new File(TEST_DATA_DIR,input).getAbsolutePath()); final File output = new File(outputDir, TEST_BASE_NAME + ".sam"); args.add("OUTPUT=" + output.getAbsolutePath()); final File metrics = new File(outputDir, TEST_BASE_NAME + ".integration_metrics"); args.add("METRICS_FILE=" + metrics.getAbsolutePath()); args.add("REMOVE_DUPLICATES=true"); Assert.assertEquals(runPicardCommandLine(args), 0); examineDuplicationMetrics(input, output, metrics, true); }

Target:
public void markDuplicatesWithRemovingDuplicatesIntegrationTest(final String input) { removingDuplicatesIntegrationTest(input); }
Source:
public void onEnter() { TracingService.activateSpan(getContext().getCurrentSpan(), false); try { getContext().unregisterAuthorizationUpdates(); } catch (final RuntimeException ex) { TracingService.logErrorInSpan(getContext().getCurrentSpan(), "Unexpected fail during removing callback for registration updates " + ex.getMessage()); getLog().error("Unexpected fail during removing callback for registration updates", ex); } try { if (null != exception) { getOut().onException(exception); } } finally { try { getContext().unregisterSession(); } finally { switchState(StreamingContext.DEAD_STATE); } try { getContext().getZkClient().close(); } catch (final IOException e) { TracingService.logErrorInSpan(getContext().getCurrentSpan(), "Unexpected fail to release zk connection " + e.getMessage()); getLog().error("Unexpected fail to release zk connection", e); } getContext().getCurrentSpan().finish(); } }

Target:
public void onEnter() { try { getContext().unregisterAuthorizationUpdates(); } catch (final RuntimeException ex) { getLog().error("Unexpected fail during removing callback for registration updates", ex); } try { if (null != exception) { getOut().onException(exception); } } finally { try { getContext().unregisterSession(); } finally { switchState(StreamingContext.DEAD_STATE); } try { getContext().getZkClient().close(); } catch (final IOException e) { getLog().error("Unexpected fail to release zk connection", e); } getContext().getCurrentSpan().finish(); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IssueTracker)) { return false; } IssueTracker that = (IssueTracker) o; if (!Objects.equals(name, that.name)) { return false; } return Objects.equals(version, that.version); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof IssueTracker)) { return false; } IssueTracker that = (IssueTracker) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version); }
Source:
protected InvocationStatus beforeInvoke() throws Exception { CompletableFuture<Void> future; switch (topologyMode) { case WAIT_TOPOLOGY: future = handler.getStateTransferLock().topologyFuture(waitTopology()); if (!future.isDone()) { if (forceOrdering) { future.get(1, TimeUnit.DAYS); } else { future.thenRunAsync(this, remoteExecutor); return InvocationStatus.DEFERRED; } } break; case WAIT_TX_DATA: future = handler.getStateTransferLock().transactionDataFuture(waitTopology()); if (!future.isDone()) { if (forceOrdering) { future.get(1, TimeUnit.DAYS); } else { future.thenRunAsync(this, remoteExecutor); return InvocationStatus.DEFERRED; } } break; default: break; } if (handler.isCommandSentBeforeFirstTopology(commandTopologyId)) { return InvocationStatus.CACHE_NOT_FOUND; } return super.beforeInvoke(); }

Target:
protected CompletableFuture<Response> beforeInvoke() { CompletableFuture<Void> future = null; switch (topologyMode) { case WAIT_TOPOLOGY: future = handler.getStateTransferLock().topologyFuture(waitTopology()); break; case WAIT_TX_DATA: future = handler.getStateTransferLock().transactionDataFuture(waitTopology()); break; default: break; } if (handler.isCommandSentBeforeFirstTopology(commandTopologyId)) { return future == null ? CompletableFuture.completedFuture(CacheNotFoundResponse.INSTANCE) : future.thenApply(nil -> CacheNotFoundResponse.INSTANCE); } else if (future != null) { return future.thenApply(nil -> null); } else { return null; } }
Source:
public void handleRow(int index, Values row) { if (index == 1) { aliases = new LineBasedAliases(row, dictionary); process.log(ProcessLog.info().withMessage(aliases.toString())); } else { Watch w = Watch.start(); try { Context ctx = aliases.transform(row); handleRow(index, ctx); } catch (Exception e) { process.handle(e); } finally { process.addTiming(descriptor.getPluralLabel(), w.elapsedMillis()); } } }

Target:
public void handleRow(int index, Values row) { if (aliases == null) { aliases = new LineBasedAliases(row, dictionary); process.log(ProcessLog.info().withMessage(aliases.toString())); } else { Watch w = Watch.start(); try { Context ctx = aliases.transform(row); handleRow(index, ctx); } catch (Exception e) { process.handle(e); } finally { process.addTiming(descriptor.getPluralLabel(), w.elapsedMillis()); } } }
Source:
public List<KeySlice> get_range_slices(ColumnParent column_parent, SlicePredicate predicate, KeyRange range, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { List<KeySlice> result = checkLimitAndCall( () -> super.get_range_slices(column_parent, predicate, range, consistency_level)); int approximateBytesRead = result.stream() .mapToInt(keySlice -> SerializationUtils.serialize(keySlice).length) .sum(); try { recordBytesRead(approximateBytesRead); } catch (Exception e) { log.warn("Encountered an exception when recording read metrics for get_range_slices.", e); } return result; }

Target:
public List<KeySlice> get_range_slices(ColumnParent column_parent, SlicePredicate predicate, KeyRange range, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { qosClient.checkLimit(); List<KeySlice> result = super.get_range_slices(column_parent, predicate, range, consistency_level); recordBytesRead(getCollectionSize(result, ThriftObjectSizeUtils::getKeySliceSize)); return result; }
Source:
public OpenShiftProjectFactory( @Nullable @Named("che.infra.openshift.project") String projectName, @Nullable @Named("che.infra.kubernetes.service_account_name") String serviceAccountName, @Nullable @Named("che.infra.kubernetes.cluster_role_name") String clusterRoleName, @Nullable @Named("che.infra.kubernetes.namespace.default") String defaultNamespaceName, @Named("che.infra.kubernetes.namespace.allow_user_defined") boolean allowUserDefinedNamespaces, OpenShiftClientFactory clientFactory, OpenShiftClientConfigFactory clientConfigFactory) { super( projectName, serviceAccountName, clusterRoleName, defaultNamespaceName, allowUserDefinedNamespaces, clientFactory); if (allowUserDefinedNamespaces && !clientConfigFactory.isPersonalized()) { LOG.warn( "Users allowed to list projects but all reuse Che Server configured service account. " + "Consider configuring OpenShift OAuth to personalize credentials that will be used for cluster access."); } this.defaultNamespaceName = defaultNamespaceName; this.allowUserDefinedNamespaces = allowUserDefinedNamespaces; this.clientFactory = clientFactory; }

Target:
public OpenShiftProjectFactory( @Nullable @Named("che.infra.openshift.project") String projectName, @Nullable @Named("che.infra.kubernetes.service_account_name") String serviceAccountName, @Nullable @Named("che.infra.kubernetes.cluster_role_name") String clusterRoleName, @Nullable @Named("che.infra.kubernetes.namespace.default") String defaultNamespaceName, @Named("che.infra.kubernetes.namespace.allow_user_defined") boolean allowUserDefinedNamespaces, OpenShiftClientFactory clientFactory, OpenShiftClientConfigFactory clientConfigFactory) { super( projectName, serviceAccountName, clusterRoleName, defaultNamespaceName, allowUserDefinedNamespaces, clientFactory); if (allowUserDefinedNamespaces && !clientConfigFactory.isPersonalized()) { LOG.warn( "Users are allowed to list projects but Che server is configured with a service account. " + "All users will receive the same list of projects. Consider configuring OpenShift " + "OAuth to personalize credentials that will be used for cluster access."); } this.clientFactory = clientFactory; }
Source:
public MotionEventHandler() { if (Context.getConfig() != null) { tripsConfig = ReportUtils.initTripsConfig(); } }

Target:
public MotionEventHandler() { tripsConfig = ReportUtils.initTripsConfig(); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Integer.valueOf(maxBatchSize).hashCode(); result = prime * result + Long.valueOf(timeOut).hashCode(); return result; }

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + maxBatchSize; result = 31 * result + Long.valueOf(timeOut).hashCode(); return result; }
Source:
public void testRefreshLocalHosts() { Set<InetSocketAddress> localHosts = clientPool.getLocalHosts(); assertTrue(localHosts.size() == 1); myLocation = Optional.of(HostLocation.of("dc1", "rack2")); CassandraClientPoolImpl clientPoolDifferentLocation = CassandraClientPoolImpl.createImplForTest(metricsManager, CASSANDRA.getConfig(), CassandraClientPoolImpl.StartupChecks.RUN, blacklist, myLocation); localHosts = clientPoolDifferentLocation.getLocalHosts(); assertTrue(localHosts.size() == 0); }

Target:
public void testRefreshLocalHosts() { HostLocation localLocation = HostLocation.of("dc1", "rack1"); HostLocation remoteLocation = HostLocation.of("dc1", "rack4"); assertThat(getLocalHostsUsingLocation(localLocation)).isNotEmpty(); assertThat(getLocalHostsUsingLocation(remoteLocation)).isEmpty(); }
Source:
public BaseMatcher(final NetworkConfig config, final NotificationListener notificationListener, final ObservationStore observationStore) { if (config == null) { throw new NullPointerException("Config must not be null"); } else if (notificationListener == null) { throw new NullPointerException("NotificationListener must not be null"); } else if (observationStore == null) { throw new NullPointerException("ObservationStore must not be null"); } else { this.config = config; } this.notificationListener = notificationListener; this.observationStore = observationStore; }

Target:
public BaseMatcher(final NetworkConfig config, final NotificationListener notificationListener, final ObservationStore observationStore) { if (config == null) { throw new NullPointerException("Config must not be null"); } else if (notificationListener == null) { throw new NullPointerException("NotificationListener must not be null"); } else if (observationStore == null) { throw new NullPointerException("ObservationStore must not be null"); } else { this.config = config; this.notificationListener = notificationListener; this.observationStore = observationStore; } }
Source:
protected static void assertQueryFailsEventually(QueryRunner queryRunner, Session session, @Language("SQL") String sql, @Language("RegExp") String expectedMessageRegExp, Duration timeout) { long start = System.nanoTime(); while (!Thread.currentThread().isInterrupted()) { try { assertQueryFails(queryRunner, session, sql, expectedMessageRegExp); return; } catch (AssertionError e) { if (nanosSince(start).compareTo(timeout) > 0) { throw e; } } sleepUninterruptibly(50, TimeUnit.MILLISECONDS); } }

Target:
protected static void assertQueryFailsEventually(QueryRunner queryRunner, Session session, @Language("SQL") String sql, @Language("RegExp") String expectedMessageRegExp, Duration timeout) { long start = System.nanoTime(); while (!Thread.currentThread().isInterrupted()) { try { assertQueryFails(queryRunner, session, sql, expectedMessageRegExp); return; } catch (AssertionError e) { if (nanosSince(start).compareTo(timeout) > 0) { throw e; } } sleepUninterruptibly(50, MILLISECONDS); } }
Source:
BigtableTableName(String tableName) { this.name = tableName; }

Target:
BigtableTableName(String tableName) { this.tableName = tableName; }
Source:
@Override public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (EP_BATCH_HANDLER.equalsIgnoreCase(extensionPoint)) { if (BatchHandlerDescriptor.class.isAssignableFrom(contribution.getClass())) { BatchHandlerDescriptor contributionDescriptor = (BatchHandlerDescriptor) contribution; BatchHandler batchHandler = newInstance(contributionDescriptor.getKlass()); batchHandler.setName(contributionDescriptor.getName()); batchHandler.init(contributionDescriptor.getProperties()); handlers.put(contributionDescriptor.getName(), batchHandler); } } }

Target:
public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) { if (EP_BATCH_HANDLER.equals(extensionPoint)) { if (contribution instanceof BatchHandlerDescriptor) { BatchHandlerDescriptor contributionDescriptor = (BatchHandlerDescriptor) contribution; String name = contributionDescriptor.getName(); BatchHandler batchHandler = contributionDescriptor.newInstance(); batchHandler.initialize(name, contributionDescriptor.getProperties()); handlers.put(name, batchHandler); } else { throw new NuxeoException("Invalid class: " + contribution.getClass().getName()); } } else { throw new NuxeoException("Invalid extension point: " + extensionPoint); } }
Source:
public void handleActionButtons() { if (mModeListener != null) mModeListener.inflate(getContentActionMode()); }

Target:
public void handleActionButtons() { if (mModeListener != null) { mModeListener.inflate(getContentActionMode()); } }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { try { PushOperation pushOperation = new PushOperation( repository.getRepository(), DEFAULT_REMOTE_NAME, false, timeout); pushOperation.run(monitor); operationResult = pushOperation.getOperationResult(); if (!operationResult.isSuccessfulConnectionForAnyURI()) { String errorMessage = String.format( CoreText.pushToRemoteFailed, operationResult.getErrorStringForAllURis()); throw new CoreException(error(errorMessage)); } } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); throw new CoreException(error(targetException.getMessage(), targetException)); } String newLocalBranch = getCurrentBranchhName(); try { repository.setRemote(newLocalBranch, DEFAULT_REMOTE_NAME); repository.setMerge(newLocalBranch, repository.getRepository().getFullBranch()); } catch (IOException e) { throw new CoreException(error(CoreText.unableToStoreGitConfig, e)); } }

Target:
public void execute(IProgressMonitor monitor) throws CoreException { try { PushOperation pushOperation = new PushOperation( repository.getRepository(), DEFAULT_REMOTE_NAME, false, timeout); pushOperation.run(monitor); operationResult = pushOperation.getOperationResult(); if (!operationResult.isSuccessfulConnectionForAnyURI()) { String errorMessage = String.format( CoreText.pushToRemoteFailed, operationResult.getErrorStringForAllURis()); throw new CoreException(error(errorMessage)); } } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); throw new CoreException(error(targetException.getMessage(), targetException)); } String newLocalBranch = getCurrentBranchhName(); try { repository.setRemote(newLocalBranch, DEFAULT_REMOTE_NAME); repository.setUpstreamBranchName(newLocalBranch, repository.getRepository().getFullBranch()); } catch (IOException e) { throw new CoreException(error(CoreText.unableToStoreGitConfig, e)); } }
Source:
private void collectAndExportAttribute(MBeanServer mbeanServer, OutputWriter outputWriter, ObjectName objectName, String attribute) { try { Object attributeValue = null; try { attributeValue = mbeanServer.getAttribute(objectName, attribute); } catch (Exception ex) { logger.info("Failed to fetch attribute for '" + objectName + "'#" + attribute + ", exception: " + ex.getMessage()); return; } Object value; if (attributeValue instanceof CompositeData) { CompositeData compositeData = (CompositeData) attributeValue; if (key == null) { CompositeType compositeType = compositeData.getCompositeType(); for (String key : compositeType.keySet()) { value = compositeData.get(key); processAttributeValue(outputWriter, objectName, attribute, value, key); } return; } else { value = compositeData.get(key); } } else { if (key == null) { value = attributeValue; } else { logger.warning("Ignore NON compositeData for specified key for '" + objectName + "'#" + attribute + "#" + key + ": " + attributeValue); return; } } if (value != null && value.getClass().isArray()) { List valueAsList = new ArrayList(); for (int i = 0; i < Array.getLength(value); i++) { valueAsList.add(Array.get(value, i)); } value = valueAsList; } processAttributeValue(outputWriter, objectName, attribute, value, key); } catch (Exception e) { logger.log(Level.WARNING, "Exception collecting " + objectName + "#" + attribute + (key == null ? "" : "#" + key), e); } }

Target:
private void collectAndExportAttribute(MBeanServer mbeanServer, OutputWriter outputWriter, ObjectName objectName, String attribute) { try { Object attributeValue = null; try { attributeValue = mbeanServer.getAttribute(objectName, attribute); } catch (Exception ex) { logger.warning("Failed to fetch attribute for '" + objectName + "'#" + attribute + ", exception: " + ex.getMessage()); return; } Object value; if (attributeValue instanceof CompositeData) { CompositeData compositeData = (CompositeData) attributeValue; if (key == null) { CompositeType compositeType = compositeData.getCompositeType(); for (String key : compositeType.keySet()) { value = compositeData.get(key); processAttributeValue(outputWriter, objectName, attribute, value, key); } return; } else { value = compositeData.get(key); } } else { if (key == null) { value = attributeValue; } else { logger.warning("Ignore NON compositeData for specified key for '" + objectName + "'#" + attribute + "#" + key + ": " + attributeValue); return; } } if (value != null && value.getClass().isArray()) { List valueAsList = new ArrayList(); for (int i = 0; i < Array.getLength(value); i++) { valueAsList.add(Array.get(value, i)); } value = valueAsList; } processAttributeValue(outputWriter, objectName, attribute, value, key); } catch (Exception e) { logger.log(Level.WARNING, "Exception collecting " + objectName + "#" + attribute + (key == null ? "" : "#" + key), e); } }
Source:
public String toString() { return "MetadataImpl{" + "name='" + name + '\'' + '}'; }

Target:
public String toString() { return "MetadataImpl{'name='" + name + '\'' + '}'; }
Source:
public void updateUser(@NonNull final String id, final JSONObject content, final KuzzleOptions options, final KuzzleResponseListener<KuzzleUser> listener) throws JSONException { if (id == null) { throw new IllegalArgumentException("KuzzleSecurity.updateUser: cannot update user without an ID"); } JSONObject data = new JSONObject().put("_id", id); data.put("body", content); if (listener != null) { this.kuzzle.query(buildQueryArgs("updateUser"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { listener.onSuccess(new KuzzleUser(KuzzleSecurity.this.kuzzle, response.getJSONObject("result").getString("_id"), response.getJSONObject("result"))); } catch(JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); } else { this.kuzzle.query(buildQueryArgs("updateUser"), data, options); } }

Target:
public void updateUser(@NonNull final String id, final JSONObject content, final KuzzleOptions options, final KuzzleResponseListener<KuzzleUser> listener) throws JSONException { if (id == null) { throw new IllegalArgumentException("KuzzleSecurity.updateUser: cannot update user without an ID"); } JSONObject data = new JSONObject().put("_id", id); data.put("body", content); if (listener != null) { this.kuzzle.query(buildQueryArgs("updateUser"), data, options, new OnQueryDoneListener() { @Override public void onSuccess(JSONObject response) { try { listener.onSuccess(new KuzzleUser(KuzzleSecurity.this.kuzzle, response.getJSONObject("result").getString("_id"), response.getJSONObject("result").getJSONObject("_source"))); } catch(JSONException e) { throw new RuntimeException(e); } } @Override public void onError(JSONObject error) { listener.onError(error); } }); } else { this.kuzzle.query(buildQueryArgs("updateUser"), data, options); } }
Source:
static Object getProviderFromEntry(String entry, Class<?>[] argumentTypes, Object[] arguments) throws FacesException, NoSuchMethodException { if (entry == null) { return null; } try { Class<?> clazz = Util.loadClass(entry, null); Constructor c = clazz.getDeclaredConstructor(argumentTypes); if (c == null) { throw new FacesException("Unable to find constructor accepting arguments: " + Arrays.toString(arguments)); } return c.newInstance(arguments); } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new FacesException(e); } }

Target:
static Object getProviderFromEntry(String entry, Class<?>[] argumentTypes, Object[] arguments) throws FacesException { if (entry == null) { return null; } try { Class<?> clazz = Util.loadClass(entry, null); Constructor c = clazz.getDeclaredConstructor(argumentTypes); if (c == null) { throw new FacesException("Unable to find constructor accepting arguments: " + Arrays.toString(arguments)); } return c.newInstance(arguments); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new FacesException(e); } }
Source:
public AcceptorCacheDigest latestSequencesPreparedOrAccepted( Optional<AcceptorCacheKey> maybeCacheKey, Set<Client> clients) { primeCache(clients); if (!maybeCacheKey.isPresent()) { return acceptorCache.getAllUpdates(); } else { AcceptorCacheKey cacheKey = maybeCacheKey.get(); return latestSequencesPreparedOrAcceptedCached(cacheKey) .orElseGet(() -> emptyDigest(cacheKey)); } }

Target:
public AcceptorCacheDigest latestSequencesPreparedOrAccepted( Optional<AcceptorCacheKey> maybeCacheKey, Set<Client> clients) { primeCache(clients); if (!maybeCacheKey.isPresent()) { return acceptorCache.getAllUpdates(); } AcceptorCacheKey cacheKey = maybeCacheKey.get(); return latestSequencesPreparedOrAcceptedCached(cacheKey) .orElseGet(() -> emptyDigest(cacheKey)); }
Source:
private int getForeignIdHashSource() { int result = 0; if (getArgs() != null && getArgs().get(FID_HASH_SRC_ARG) != null) { String hashSourceArg = getArgs().get(FID_HASH_SRC_ARG).toLowerCase(); for (String keyword : HASH_IP_KEYWORDS) { if (hashSourceArg.contains(keyword)) { result = 2; break; } } for (String keyword : HASH_LABEL_KEYWORDS) { if (hashSourceArg.contains(keyword)) { result++; break; } } } return result; }

Target:
private ForeignIdHashSource getForeignIdHashSource() { boolean hasIpKeywords = false; boolean hasLabelKeywords = false; if (getArgs() != null && getArgs().get(FID_HASH_SRC_ARG) != null) { String hashSourceArg = getArgs().get(FID_HASH_SRC_ARG).toLowerCase(); for (String keyword : HASH_IP_KEYWORDS) { if (hashSourceArg.contains(keyword)) { hasIpKeywords = true; break; } } for (String keyword : HASH_LABEL_KEYWORDS) { if (hashSourceArg.contains(keyword)) { hasLabelKeywords = true; break; } } } if (hasIpKeywords && !hasLabelKeywords) { return ForeignIdHashSource.IP_ADDRESS; } else if (hasIpKeywords && hasLabelKeywords) { return ForeignIdHashSource.NODE_LABEL_AND_IP_ADDRESS; } else { return ForeignIdHashSource.NODE_LABEL; } }
Source:
public void addWAL(final WAL wal) { if (null == wals.putIfAbsent(wal, new RollController(wal))) { wal.registerWALActionsListener(new WALActionsListener.Base() { @Override public void logRollRequested(WALActionsListener.RollRequestReason reason) { RollController controller = wals.get(wal); if (controller == null) { synchronized(wals) { controller = wals.get(wal); if (controller == null) { controller = new RollController(wal); wals.put(wal, controller); } } } controller.requestRoll(); synchronized(rollLog) { rollLog.set(true); rollLog.notifyAll(); } } }); } }

Target:
public void addWAL(final WAL wal) { if (null == wals.putIfAbsent(wal, new RollController(wal))) { wal.registerWALActionsListener(new WALActionsListener.Base() { @Override public void logRollRequested(WALActionsListener.RollRequestReason reason) { RollController controller = wals.get(wal); if (controller == null) { wals.putIfAbsent(wal, new RollController(wal)); controller = wals.get(wal); } controller.requestRoll(); synchronized(rollLog) { rollLog.set(true); rollLog.notifyAll(); } } }); } }
Source:
private BigDecimal mean() { BigDecimal sum = new BigDecimal(0.0); int i = 0; decimalVals = new BigDecimal[valueVsCount.size()]; for (Entry<ImmutableBytesPtr, Integer> entry : valueVsCount.entrySet()) { BigDecimal colValue = (BigDecimal)PDataType.DECIMAL.toObject(entry.getKey()); sum = sum.add(colValue.multiply(new BigDecimal(entry.getValue()))); decimalVals[i++] = colValue; } return BigDecimalUtil.divide(sum, new BigDecimal(totalCount)); }

Target:
private BigDecimal mean() { BigDecimal sum = BigDecimal.ZERO; for (Entry<ImmutableBytesPtr, Integer> entry : valueVsCount.entrySet()) { BigDecimal colValue = (BigDecimal)PDataType.DECIMAL.toObject(entry.getKey()); sum = sum.add(colValue.multiply(new BigDecimal(entry.getValue()))); } return sum.divide(new BigDecimal(totalCount), PDataType.DEFAULT_MATH_CONTEXT); }
Source:
public final void perform(GoogleRobotCredentials credentials, Run<?, ?> run, FilePath workspace, TaskListener listener) throws UploadException { if (!forResult(run.getResult())) { return; } try { BucketPath storagePrefix = new BucketPath(getBucket(), run, listener, moduleName()); if (storagePrefix.error()) { return; } UploadSpec uploads = getInclusions( run, checkNotNull(workspace), listener); if (uploads != null) { BuildGcsUploadReport links = BuildGcsUploadReport.of(run); links.addBucket(storagePrefix.bucket); initiateUploadsAtWorkspace(credentials, run, storagePrefix, uploads, listener); } } catch (InterruptedException e) { throw new UploadException(Messages.AbstractUpload_UploadException(), e); } catch (IOException e) { throw new UploadException(Messages.AbstractUpload_UploadException(), e); } }

Target:
public final void perform(GoogleRobotCredentials credentials, Run<?, ?> run, FilePath workspace, TaskListener listener) throws UploadException { if (!forResult(run.getResult())) { return; } try { String resolvedBucket = StorageUtil.replaceMacro(getBucket(), run, listener); BucketPath storagePrefix = new BucketPath(resolvedBucket); UploadSpec uploads = getInclusions( run, checkNotNull(workspace), listener); if (uploads != null) { BuildGcsUploadReport links = BuildGcsUploadReport.of(run); links.addBucket(storagePrefix.getBucket()); initiateUploadsAtWorkspace(credentials, run, storagePrefix, uploads, listener); } } catch (InterruptedException e) { throw new UploadException(Messages.AbstractUpload_UploadException(), e); } catch (IOException e) { throw new UploadException(Messages.AbstractUpload_UploadException(), e); } }
Source:
public static QuantityType<?> operator_divide(Number x, QuantityType<?> y) { QuantityType<?> xQuantity = new QuantityType<>("" + x.doubleValue()); return operator_divide(xQuantity, y); }

Target:
public static QuantityType<?> operator_divide(Number x, QuantityType<?> y) { QuantityType<Dimensionless> xQuantity = new QuantityType<>(x, SmartHomeUnits.ONE); return operator_divide(xQuantity, y); }
Source:
public Future<?> scheduleCancelLotsOutsideLoop(final ThreadState threadState) { for (int i = 1; i <= threadState.num; i++) { threadState.eventLoop.schedule(NO_OP, i, TimeUnit.HOURS).cancel(false); } return null; }

Target:
public Future<?> scheduleCancelLotsOutsideLoop(final ThreadState threadState) { final AbstractScheduledEventExecutor eventLoop = threadState.eventLoop; for (int i = 1; i <= threadState.num; i++) { eventLoop.schedule(NO_OP, i, TimeUnit.HOURS).cancel(false); } return null; }
Source:
public void reset() { hasParsedHeader = !firstRowIsHeader; }

Target:
public void reset() { hasParsedHeader = false; }
Source:
private Command addOrderLine(OrderId orderId) { final double price = 51.33; final Book book = Book.newBuilder() .setBookId(BookId.newBuilder().setISBN("978-0321125217").build()) .setAuthor("Eric Evans") .setTitle("Domain Driven Design.") .setPrice(price) .build(); final int quantity = 1; final double totalPrice = book.getPrice() * quantity; final OrderLine orderLine = OrderLine.newBuilder() .setProductId(Messages.toAny(book.getBookId())) .setQuantity(quantity) .setTotal(totalPrice) .build(); final AddOrderLine msg = AddOrderLine.newBuilder() .setOrderId(orderId) .setOrderLine(orderLine).build(); return commandFactory.create(msg); }

Target:
private Command addOrderLine(OrderId orderId) { final int bookPriceUsd = 52; final Book book = Book.newBuilder() .setBookId(BookId.newBuilder().setISBN("978-0321125217").build()) .setAuthor("Eric Evans") .setTitle("Domain Driven Design.") .setPrice(newMoney(bookPriceUsd, USD)) .build(); final int quantity = 1; final Money totalPrice = newMoney(bookPriceUsd * quantity, USD); final OrderLine orderLine = OrderLine.newBuilder() .setProductId(Messages.toAny(book.getBookId())) .setQuantity(quantity) .setPrice(totalPrice) .build(); final AddOrderLine msg = AddOrderLine.newBuilder() .setOrderId(orderId) .setOrderLine(orderLine).build(); return commandFactory.create(msg); }
Source:
public List<AnnotationMirror> getPostconditionAnnotation( VariableElement elt, AField f, List<AnnotationMirror> preconds) { return getPreOrPostconditionAnnotation(elt, f, AFTER, preconds); }

Target:
public List<AnnotationMirror> getPostconditionAnnotation( VariableElement elt, AField f, List<AnnotationMirror> preconds) { return getPreOrPostconditionAnnotation(elt, f, BeforeOrAfter.AFTER, preconds); }
Source:
public RowExpression visitSpecialForm(SpecialFormExpression specialForm, Form clauseJoiner) { if (!isConjunctionOrDisjunction(specialForm)) { return specialForm; } RowExpression left = specialForm.getArguments().get(0).accept(new ConvertNormalFormVisitor(), clauseJoiner); RowExpression right = specialForm.getArguments().get(1).accept(new ConvertNormalFormVisitor(), clauseJoiner); if (specialForm.getForm() == clauseJoiner) { return clauseJoiner == AND ? and(left, right) : or(left, right); } Form termJoiner = clauseJoiner == AND ? OR : AND; List<RowExpression> leftClauses = extractPredicates(clauseJoiner, left); List<RowExpression> rightClauses = extractPredicates(clauseJoiner, right); List<RowExpression> permutationClauses = new ArrayList<>(); leftClauses.forEach(leftClause -> rightClauses.forEach(rightClause -> permutationClauses.add(termJoiner == AND ? and(leftClause, rightClause) : or(leftClause, rightClause)))); return combinePredicates(clauseJoiner, unmodifiableList(permutationClauses)); }

Target:
public RowExpression visitSpecialForm(SpecialFormExpression specialForm, Form clauseJoiner) { if (!isConjunctionOrDisjunction(specialForm)) { return specialForm; } RowExpression left = specialForm.getArguments().get(0).accept(new ConvertNormalFormVisitor(), clauseJoiner); RowExpression right = specialForm.getArguments().get(1).accept(new ConvertNormalFormVisitor(), clauseJoiner); if (specialForm.getForm() == clauseJoiner) { return clauseJoiner == AND ? and(left, right) : or(left, right); } Form termJoiner = clauseJoiner == AND ? OR : AND; List<RowExpression> leftClauses = extractPredicates(clauseJoiner, left); List<RowExpression> rightClauses = extractPredicates(clauseJoiner, right); List<RowExpression> permutationClauses = new ArrayList<>(); for (RowExpression leftClause : leftClauses) { for (RowExpression rightClause : rightClauses) { permutationClauses.add(termJoiner == AND ? and(leftClause, rightClause) : or(leftClause, rightClause)); } } return combinePredicates(clauseJoiner, unmodifiableList(permutationClauses)); }
Source:
public DataContainer toContainer() { DataContainer data = super.toContainer(); data.set(Keys.ZOMBIE_TYPE, getType()); if(getProfession().isPresent()) { data.set(Keys.VILLAGER_ZOMBIE_PROFESSION.getQuery(), getProfession().get()); } return data; }

Target:
public DataContainer toContainer() { DataContainer data = super.toContainer(); data.set(Keys.ZOMBIE_TYPE.getQuery(), getType().getId()); if (getProfession().isPresent()) { data.set(Keys.VILLAGER_ZOMBIE_PROFESSION.getQuery(), getProfession().get().getId()); } return data; }
Source:
public Collection<RecipientGroup> getRecipientGroups() { return Collections.unmodifiableCollection(_groups); }

Target:
public ImmutableSet<RecipientGroup> getRecipientGroups() { return _groups; }
Source:
@Override public Response load(Uri uri, boolean localCacheOnly) throws IOException { com.squareup.okhttp.Request.Builder requestBuilder = new com.squareup.okhttp.Request.Builder().url(uri.toString()); if (localCacheOnly) { requestBuilder.addHeader("Cache-Control", "only-if-cached,max-age=" + Integer.MAX_VALUE); } com.squareup.okhttp.Response response = client.newCall(requestBuilder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { throw new ResponseException(responseCode + " " + response.message(), localCacheOnly, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }

Target:
@Override public Response load(Uri uri, boolean localCacheOnly) throws IOException { com.squareup.okhttp.Request.Builder requestBuilder = new com.squareup.okhttp.Request.Builder().url(uri.toString()); if (localCacheOnly) { requestBuilder.addHeader("Cache-Control", "only-if-cached,max-age=" + Integer.MAX_VALUE); } com.squareup.okhttp.Response response = client.newCall(requestBuilder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), localCacheOnly, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }
Source:
public void sendOperation(final String targetEvalId, final DataOperation operation) { final Codec codec = serializer.getCodec(operation.getDataType()); if (operation.isFromLocalClient()) { resultHandler.registerOperation(operation); } try (final TraceScope traceScope = Trace.startSpan("SEND_REMOTE_OP")) { final TraceInfo traceInfo = TraceInfo.fromSpan(traceScope.getSpan()); final ByteBuffer inputData = operation.getInputData().isPresent() ? ByteBuffer.wrap(codec.encode(operation.getInputData().get())) : null; final Optional<String> origEvalID = operation.getOrigEvalId(); msgSender.get().sendRemoteOpMsg(origEvalID.get(), targetEvalId, operation.getOperationType(), operation.getDataType(), operation.getDataKey(), inputData, operation.getOperationId(), traceInfo); } if (operation.isFromLocalClient()) { try { operation.waitOperation(TIMEOUT_MS); } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Interrupted while waiting for executing remote operation", e); } finally { if (resultHandler.deregisterOperation(operation.getOperationId()) != null) { LOG.log(Level.WARNING, "The operation {0} has no response in timeout.", operation.getOperationId()); } } } }

Target:
void sendOperation(final String targetEvalId, final DataOperation operation) { final Codec codec = serializer.getCodec(operation.getDataType()); if (operation.isFromLocalClient()) { resultHandler.registerOperation(operation); } try (final TraceScope traceScope = Trace.startSpan("SEND_REMOTE_OP")) { final TraceInfo traceInfo = TraceInfo.fromSpan(traceScope.getSpan()); final ByteBuffer inputData = operation.getDataValue().isPresent() ? ByteBuffer.wrap(codec.encode(operation.getDataValue().get())) : null; msgSender.get().sendRemoteOpMsg((String) operation.getOrigEvalId().get(), targetEvalId, operation.getOperationType(), operation.getDataType(), operation.getDataKey(), inputData, operation.getOperationId(), traceInfo); } if (operation.isFromLocalClient()) { try { operation.waitOperation(TIMEOUT_MS); } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Interrupted while waiting for executing remote operation", e); } finally { if (resultHandler.deregisterOperation(operation.getOperationId()) != null) { LOG.log(Level.WARNING, "The operation {0} has no response for {1} ms.", new Object[]{operation.getOperationId(), TIMEOUT_MS}); } } } }
Source:
public void testPostNewAppointmentAndGetAppointmentID() throws Exception { List<String> applicants = new ArrayList<>(); applicants.add("My test Appointment"); List<String> users = new ArrayList<>(); users.add("testUserId"); Appointment appointment = new Appointment(users, applicants, 555); String appointmentJson = jsonUtil.toJson(appointment); mockMvc.perform( post("/appointments") .contentType(MediaType.APPLICATION_JSON) .content(appointmentJson) ) .andExpect(content().contentType("application/json")) .andExpect(content().string("4")) .andExpect(status().isAccepted()); }

Target:
public void testPostNewAppointmentAndGetAppointmentID() throws Exception { List<String> applicants = new ArrayList<>(); applicants.add("My test Appointment"); List<String> users = new ArrayList<>(); users.add("testUserId"); Appointment appointment = new Appointment(users, applicants, 555); String appointmentJson = jsonUtil.toJson(appointment); String exptectedIdJson = jsonUtil.toJson(4); MvcResult ExpectingObject = mockMvc.perform( post("/appointments") .contentType(MediaType.APPLICATION_JSON) .content(appointmentJson) ) .andExpect(content().contentType("application/json")) .andExpect(status().isAccepted()) .andReturn(); String ExpectID = ExpectingObject.getResponse().getContentAsString(); assertEquals("Return Appointment ID in JSON in response to Post appointment request", exptectedIdJson, ExpectID); }