auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isSerializable(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider, PropertyWriter writer) { DynamicFilterData filterData = ResteasyProviderFactory.getContextData(DynamicFilterData.class); if (filterData != null) { List<String> path = new ArrayList<String>(10); path.clear(); path.add(0, writer.getName()); JsonStreamContext context = jsonGenerator.getOutputContext(); while ((context = context.getParent()) != null) { String cname = context.getCurrentName(); if (cname != null) { path.add(0, cname); } } return !filterData.isAttributeExcluded(path); } return true; }

Target:
public boolean isSerializable(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider, PropertyWriter writer) { DynamicFilterData filterData = ResteasyProviderFactory.getContextData(DynamicFilterData.class); if (filterData != null) { List<String> path = new ArrayList<String>(10); path.add(0, writer.getName()); JsonStreamContext context = jsonGenerator.getOutputContext(); while ((context = context.getParent()) != null) { String cname = context.getCurrentName(); if (cname != null) { path.add(0, cname); } } return !filterData.isAttributeExcluded(path); } return true; }
Source:
protected void executeCommand() { List<Disk> disks = getDiskDao().getAllForVm(getVmTemplateId()); for (Disk disk : disks) { StorageJobCommandParameters parameters = new StorageJobCommandParameters(((DiskImage) disk).getImageId()); parameters.setParentCommand(getParameters().getParentCommand()); parameters.setParentParameters(getParameters().getParentParameters()); CommandCoordinatorUtil.executeAsyncCommand( VdcActionType.SysprepImage, parameters, cloneContext().withoutCompensationContext().withoutExecutionContext()); } setSucceeded(true); }

Target:
protected void executeCommand() { if (getDiskImages().isEmpty()) { setSucceeded(true); return; } SysprepVDSCommandParameters parameters = new SysprepVDSCommandParameters(); getDiskImages().forEach(diskImage -> parameters.addVolume( diskImage.getStorageIds().get(0), diskImage.getId(), diskImage.getImageId())); lockTemplateInDb(); VDSReturnValue vdsReturnValue = VdsCommandsHelper.runVdsCommandWithFailover( VDSCommandType.Sysprep, parameters, getDiskImages().get(0).getStoragePoolId(), this); if (!vdsReturnValue.getSucceeded()) { setCommandStatus(CommandStatus.FAILED); unlockTemplateInDb(); } setSucceeded(vdsReturnValue.getSucceeded()); }
Source:
private static IEditorInput getActiveEditorInput(ExecutionEvent event) { Object o = HandlerUtil.getVariable(event, ISources.ACTIVE_EDITOR_INPUT_NAME); if (o instanceof IEditorInput) { return (IEditorInput) o; } return null; }

Target:
private static IEditorInput getActiveEditorInput(ExecutionEvent event) { Object o = HandlerUtil.getVariable(event, ISources.ACTIVE_EDITOR_INPUT_NAME); if (o instanceof IEditorInput) return (IEditorInput) o; return null; }
Source:
private TriggerPolicy<Tuple> getTriggerPolicy(Count slidingIntervalCount, Long slidingIntervalDurationMs, WindowManager<Tuple> manager, EvictionPolicy<Tuple> evictionPolicy, Map<String, Object> topoConf) { if (slidingIntervalCount != null) { if (isTupleTs()) { return new WatermarkCountTriggerPolicy<>(slidingIntervalCount.value, manager, evictionPolicy, manager); } else { return new CountTriggerPolicy<>(slidingIntervalCount.value, manager, evictionPolicy); } } else { if (isTupleTs()) { return new WatermarkTimeTriggerPolicy<>(slidingIntervalDurationMs, manager, evictionPolicy, manager); } else { Config.setTickTupleFrequency(topoConf, slidingIntervalDurationMs); return new TimeTriggerPolicy<>(slidingIntervalDurationMs, manager, evictionPolicy); } } }

Target:
private TriggerPolicy<Tuple> getTriggerPolicy(Count slidingIntervalCount, Long slidingIntervalDurationMs, WindowManager<Tuple> manager, EvictionPolicy<Tuple> evictionPolicy, Map<String, Object> topoConf) { if (slidingIntervalCount != null) { if (isTupleTs()) { return new WatermarkCountTriggerPolicy<>(slidingIntervalCount.value, manager, evictionPolicy, manager); } else { return new CountTriggerPolicy<>(slidingIntervalCount.value, manager, evictionPolicy); } } else { if (isTupleTs()) { return new WatermarkTimeTriggerPolicy<>(slidingIntervalDurationMs, manager, evictionPolicy, manager); } else { Config.setTickTupleFrequencyMs(topoConf, slidingIntervalDurationMs); return new TimeTriggerPolicy<>(slidingIntervalDurationMs, manager, evictionPolicy); } } }
Source:
public Response getTaskStatus(@PathParam("taskid") String taskid) { final Task task = taskStorageQueryAdapter.getTask(taskid).orNull(); final TaskStatus taskStatus = taskStorageQueryAdapter.getStatus(taskid).orNull(); final Pair<DateTime, String> createdDateAndDataSource = taskStorageQueryAdapter.getCreatedDateAndDataSource( taskid ); final TaskStatusResponse response; if (taskMaster.getTaskRunner().isPresent() && task != null && taskStatus != null && createdDateAndDataSource != null) { final TaskRunner taskRunner = taskMaster.getTaskRunner().get(); final TaskRunnerWorkItem workItem = taskRunner .getKnownTasks() .stream() .filter(item -> item.getTaskId().equals(taskid)) .findAny() .orElse(null); if (workItem != null) { response = new TaskStatusResponse( taskid, new TaskStatusPlus( taskid, task.getType(), createdDateAndDataSource.lhs, workItem.getQueueInsertionTime(), taskStatus.getStatusCode(), taskStatus.getDuration(), workItem.getLocation(), createdDateAndDataSource.rhs, null ) ); } else { response = new TaskStatusResponse( taskid, new TaskStatusPlus( taskid, task.getType(), createdDateAndDataSource.lhs, DateTimes.EPOCH, taskStatus.getStatusCode(), taskStatus.getDuration(), TaskLocation.unknown(), createdDateAndDataSource.rhs, null ) ); } } else { response = new TaskStatusResponse(taskid, null); } final Response.Status status = response.getStatus() == null ? Response.Status.NOT_FOUND : Response.Status.OK; return Response.status(status).entity(response).build(); }

Target:
public Response getTaskStatus(@PathParam("taskid") String taskid) { final TaskInfo<Task, TaskStatus> taskInfo = taskStorageQueryAdapter.getTaskInfo(taskid); TaskStatusResponse response = null; if (taskInfo != null) { if (taskMaster.getTaskRunner().isPresent()) { final TaskRunner taskRunner = taskMaster.getTaskRunner().get(); final TaskRunnerWorkItem workItem = taskRunner .getKnownTasks() .stream() .filter(item -> item.getTaskId().equals(taskid)) .findAny() .orElse(null); if (workItem != null) { response = new TaskStatusResponse( workItem.getTaskId(), new TaskStatusPlus( taskInfo.getId(), taskInfo.getTask() == null ? null : taskInfo.getTask().getType(), taskInfo.getCreatedTime(), DateTimes.EPOCH, taskInfo.getStatus().getStatusCode(), taskRunner.getRunnerTaskState(workItem.getTaskId()), taskInfo.getStatus().getDuration(), workItem.getLocation(), taskInfo.getDataSource(), taskInfo.getStatus().getErrorMsg() ) ); } } if (response == null) { response = new TaskStatusResponse( taskid, new TaskStatusPlus( taskInfo.getId(), taskInfo.getTask() == null ? null : taskInfo.getTask().getType(), taskInfo.getCreatedTime(), DateTimes.EPOCH, taskInfo.getStatus().getStatusCode(), RunnerTaskState.WAITING, taskInfo.getStatus().getDuration(), TaskLocation.unknown(), taskInfo.getDataSource(), taskInfo.getStatus().getErrorMsg() ) ); } } else { response = new TaskStatusResponse(taskid, null); } final Response.Status status = response.getStatus() == null ? Response.Status.NOT_FOUND : Response.Status.OK; return Response.status(status).entity(response).build(); }
Source:
public static void main(final String[] args) throws Exception { final int fragmentLimitCount = 10; final String channel = new String("udp://localhost:40123"); final int streamId = 10; System.out.println("Subscribing to " + channel + " on stream Id " + streamId); final AtomicBoolean running = new AtomicBoolean(true); final DataHandler dataHandler = new DataHandler() { public void onData(final DirectBuffer buffer, final int offset, final int length, final Header header) { final byte[] data = new byte[length]; buffer.getBytes(offset, data); System.out.println( String.format( "Received message (%s) to stream %d from session %x term id %x term offset %d (%d@%d)", new String(data), streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset)); running.set(false); } }; SigInt.register(() -> running.set(false)); final Aeron.Context ctx = new Aeron.Context(); Subscription subscription = null; Aeron aeron = null; try { aeron = Aeron.connect(ctx); subscription = aeron.addSubscription(channel, streamId, dataHandler); final IdleStrategy idleStrategy = new BackoffIdleStrategy( 100, 10, TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100)); try { while (running.get()) { final int fragmentsRead = subscription.poll(fragmentLimitCount); idleStrategy.idle(fragmentsRead); } } catch (final Exception ex) { ex.printStackTrace(); } System.out.println("Shutting down..."); } finally { subscription.close(); aeron.close(); } }

Target:
public static void main(final String[] args) throws Exception { final int fragmentLimitCount = 10; final String channel = "udp://localhost:40123"; final int streamId = 10; System.out.println("Subscribing to " + channel + " on stream Id " + streamId); final AtomicBoolean running = new AtomicBoolean(true); SigInt.register(() -> running.set(false)); final DataHandler dataHandler = new DataHandler() { public void onData(final DirectBuffer buffer, final int offset, final int length, final Header header) { final byte[] data = new byte[length]; buffer.getBytes(offset, data); System.out.println( String.format( "Received message (%s) to stream %d from session %x term id %x term offset %d (%d@%d)", new String(data), streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset)); running.set(false); } }; final Aeron.Context ctx = new Aeron.Context(); try (final Aeron aeron = Aeron.connect(ctx); final Subscription subscription = aeron.addSubscription(channel, streamId, dataHandler);) { final IdleStrategy idleStrategy = new BackoffIdleStrategy( 100, 10, TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100)); try { while (running.get()) { final int fragmentsRead = subscription.poll(fragmentLimitCount); idleStrategy.idle(fragmentsRead); } } catch (final Exception ex) { ex.printStackTrace(); } System.out.println("Shutting down..."); } finally { ctx.close(); } }
Source:
private ActionEventRequest buildCreateEncounterAction(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_DATE, DisplayNames.ENCOUNTER_DATE, DATE, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_TYPE, DisplayNames.ENCOUNTER_TYPE, true, order++)); actionParameters.add(prepareParameter(Keys.LOCATION_NAME, DisplayNames.LOCATION_NAME, false, order++)); actionParameters.add(prepareParameter(Keys.PATIENT_UUID, DisplayNames.PATIENT_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.PROVIDER_UUID, DisplayNames.PROVIDER_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION, DisplayNames.OBSERVATION, MAP, false, order)); return new ActionEventRequestBuilder() .setDisplayName(String.format("Create Encounter [%s]", configName)) .setServiceInterface("org.motechproject.openmrs19.tasks.OpenMRSActionProxyService") .setServiceMethod("createEncounter") .setActionParameters(actionParameters) .createActionEventRequest(); }

Target:
private ActionEventRequest buildCreateEncounterAction(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_DATE, DisplayNames.ENCOUNTER_DATE, DATE, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_TYPE, DisplayNames.ENCOUNTER_TYPE, true, order++)); actionParameters.add(prepareParameter(Keys.LOCATION_NAME, DisplayNames.LOCATION_NAME, false, order++)); actionParameters.add(prepareParameter(Keys.PATIENT_UUID, DisplayNames.PATIENT_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.PROVIDER_UUID, DisplayNames.PROVIDER_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION, DisplayNames.OBSERVATION, MAP, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_ENCOUNTER, configName)) .setServiceInterface("org.motechproject.openmrs19.tasks.OpenMRSActionProxyService") .setServiceMethod("createEncounter") .setActionParameters(actionParameters) .createActionEventRequest(); }
Source:
public void testBuilderSetsPskCipherSuitesWhenPskStoreIsSet() { DtlsConnectorConfig config = builder.setPskStore(new StaticPskStore("ID", "KEY".getBytes())).build(); assertTrue(config.getSupportedCipherSuites().length > 0); for (CipherSuite suite : config.getSupportedCipherSuites()) { assertThat(suite.getKeyExchange(), Matchers.either(Matchers.is(KeyExchangeAlgorithm.PSK)).or(Matchers.is(KeyExchangeAlgorithm.ECDHE_PSK))); } }

Target:
public void testBuilderSetsPskCipherSuitesWhenPskStoreIsSet() { DtlsConnectorConfig config = builder.setPskStore(new StaticPskStore("ID", "KEY".getBytes())).build(); assertTrue(config.getSupportedCipherSuites().length > 0); for (CipherSuite suite : config.getSupportedCipherSuites()) { assertThat(suite.getKeyExchange(), either(is(KeyExchangeAlgorithm.PSK)).or(is(KeyExchangeAlgorithm.ECDHE_PSK))); } }
Source:
private CharSequence getLabelText(@NonNull String lang) { if (invokeSource == SUGGESTED_EDITS_TRANSLATE_DESC || invokeSource == FEED_CARD_SUGGESTED_EDITS_TRANSLATE_DESC) { return String.format(getContext().getString(R.string.description_edit_text_hint_per_language), WikipediaApp.getInstance().language().getAppLanguageCanonicalName(lang)); } else if (invokeSource == SUGGESTED_EDITS_TRANSLATE_CAPTION) { return String.format(getContext().getString(R.string.description_edit_caption_hint_per_language), WikipediaApp.getInstance().language().getAppLanguageCanonicalName(lang)); } else { return getContext().getString(R.string.description_edit_article); } }

Target:
private CharSequence getLabelText(@NonNull String lang) { if (invokeSource == SUGGESTED_EDITS_TRANSLATE_DESC || invokeSource == FEED_CARD_SUGGESTED_EDITS_TRANSLATE_DESC) { return getContext().getString(R.string.description_edit_text_hint_per_language, WikipediaApp.getInstance().language().getAppLanguageCanonicalName(lang)); } else if (invokeSource == SUGGESTED_EDITS_TRANSLATE_CAPTION) { return getContext().getString(R.string.description_edit_caption_hint_per_language, WikipediaApp.getInstance().language().getAppLanguageCanonicalName(lang)); } else { return getContext().getString(R.string.description_edit_article); } }
Source:
public ValidationResult isVmPluggedDiskUsingScsiReservation() { StringBuilder vmUsingScsiReservation = new StringBuilder(); for (VM vm : vms) { List<VmDevice> devices = getDbFacade().getVmDeviceDao().getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.DISK); for (VmDevice device : devices) { if (device.getIsPlugged() && device.isUsingScsiReservation()) { vmUsingScsiReservation.append(vm.getName()).append(" "); } } } if (vmUsingScsiReservation.length() == 0) { return ValidationResult.VALID; } return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VM_USES_SCSI_RESERVATION, String.format("$VmName %s", vmUsingScsiReservation.toString().substring(0, vmUsingScsiReservation.toString().length()-1))); }

Target:
public ValidationResult isVmPluggedDiskUsingScsiReservation() { for (VM vm : vms) { List<VmDevice> devices = getDbFacade().getVmDeviceDao().getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.DISK); for (VmDevice device : devices) { if (device.getIsPlugged() && device.isUsingScsiReservation()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VM_USES_SCSI_RESERVATION, String.format("$VmName %s", vm.getName())); } } } return ValidationResult.VALID; }
Source:
protected void addToEntryList(ITmfTrace trace, ITmfStateSystem ss, List<TimeGraphEntry> list) { addToEntryList(trace, list); synchronized (fSSEntryListMap) { List<TimeGraphEntry> entryList = fSSEntryListMap.get(ss); if (entryList == null) { fSSEntryListMap.put(ss, new CopyOnWriteArrayList<>(list)); } else { entryList.addAll(list); } fTraceSSMap.put(trace, ss); } }

Target:
protected void addToEntryList(ITmfTrace trace, ITmfStateSystem ss, List<TimeGraphEntry> list) { super.addToEntryList(trace, list); synchronized (fSSEntryListMap) { List<TimeGraphEntry> entryList = fSSEntryListMap.get(ss); if (entryList == null) { fSSEntryListMap.put(ss, new CopyOnWriteArrayList<>(list)); } else { entryList.addAll(list); } fTraceSSMap.put(trace, ss); } }
Source:
public static byte[] ipV6XOR(String ip, byte[] transactionId) { InetAddress address; try { address = InetAddress.getByName(ip); } catch (UnknownHostException e) { e.printStackTrace(); return null; } if (!(address instanceof Inet6Address)) { System.out.println("Address must be IPv6."); return null; } byte[] ipAddr = address.getAddress(); byte[] x = new byte[16]; x[0] = (byte) ((byte)0x21 ^ ipAddr[0]); x[1] = (byte) ((byte)0x12 ^ ipAddr[1]); x[2] = (byte) ((byte)0xA4 ^ ipAddr[2]); x[3] = (byte) ((byte)0x42 ^ ipAddr[3]); for (int i = 4; i < 16; i++) { x[i] = (byte) (transactionId[i-4] ^ ipAddr[i]); } return x; }

Target:
public static byte[] ipV6XOR(String ip, byte[] transactionId) { InetAddress address; try { address = InetAddress.getByName(ip); } catch (UnknownHostException e) { throw new RuntimeException("Unable to parse IPv6 address", e); } if (!(address instanceof Inet6Address)) { throw new RuntimeException("Address must be IPv6."); } byte[] ipAddr = address.getAddress(); byte[] x = new byte[16]; x[0] = (byte) ((byte)0x21 ^ ipAddr[0]); x[1] = (byte) ((byte)0x12 ^ ipAddr[1]); x[2] = (byte) ((byte)0xA4 ^ ipAddr[2]); x[3] = (byte) ((byte)0x42 ^ ipAddr[3]); for (int i = 4; i < 16; i++) { x[i] = (byte) (transactionId[i-4] ^ ipAddr[i]); } return x; }
Source:
public EEFButtonLifecycleManager(EEFButtonDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(description, variableManager, interpreter, editingDomain); this.description = description; }

Target:
public EEFButtonLifecycleManager(EEFButtonDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(variableManager, interpreter, editingDomain); this.description = description; }
Source:
public static String normalizeLineEndings(String s) { return s.replaceAll(CRLF, LF).replace(CR_CHAR, LF_CHAR); }

Target:
public static String normalizeLineEndings(String s) { if (s == null) return null; if (s.length() == 0) return EMPTY_STRING; StringBuilder result = new StringBuilder(); int length = s.length(); int i = 0; while (i < length) { if (s.charAt(i) == CR_CHAR) { if (i + 1 < length) { if (s.charAt(i + 1) == LF_CHAR) { result.append(LF_CHAR); i += 1; } else { result.append(LF_CHAR); } } else { result.append(LF_CHAR); } } else result.append(s.charAt(i)); i++; } return result.toString(); }
Source:
public Observable<PutResults<T>> createObservable() { try { throwExceptionIfRxJavaIsNotAvailable("createObservable()"); return Observable .create(OnSubscribeExecuteAsBlocking.newInstance(this)) .subscribeOn(Schedulers.io()); } catch (Throwable throwable) { throw new StorIOException(throwable); } }

Target:
public Observable<PutResults<T>> createObservable() { throwExceptionIfRxJavaIsNotAvailable("createObservable()"); return Observable .create(OnSubscribeExecuteAsBlocking.newInstance(this)) .subscribeOn(Schedulers.io()); }
Source:
public boolean isSelectable(Run<?, ?> run, EnvVars env) { return run.getArtifacts().isEmpty() ? false : true; }

Target:
public boolean isSelectable(Run<?, ?> run, EnvVars env) { return run.getHasArtifacts(); }
Source:
public String getIoThreadsAndEmulatorPinningCpus(VM vm, MemoizingSupplier<List<VdsNumaNode>> hostNumaNodesSupplier, int vdsCpuThreads) { if (vm.getVmType() != VmType.HighPerformance) { return null; } final String cpuPinning = vm.getCpuPinning(); List<VmNumaNode> vmNumaNodes = vmNumaNodeDao.getAllVmNumaNodeByVmId(vm.getId()); Optional<VmNumaNode> pinnedVmNumaNode = vmNumaNodes.stream().filter(d -> !d.getVdsNumaNodeList().isEmpty()).findAny(); if (StringUtils.isEmpty(cpuPinning) || !pinnedVmNumaNode.isPresent() || vm.getNumOfIoThreads() == 0) { String msgReason1 = StringUtils.isEmpty(cpuPinning) ? "CPU Pinning topology is not set": ""; String msgReason2 = vm.getNumOfIoThreads() == 0 ? "IO Threads is not enabled": ""; String msgReason3 = !pinnedVmNumaNode.isPresent() ? "vm's virtual NUMA nodes are not pinned to host's NUMA nodes": ""; String finalMsgReason = msgReason1 + (!msgReason1.isEmpty() && !msgReason2.isEmpty() ? ", " : "") + msgReason2 + ((!msgReason1.isEmpty() || !msgReason2.isEmpty()) && !msgReason3.isEmpty() ? ", " : "") + msgReason3 + "."; log.warn("No IO thread(s) pinning and Emulator thread(s) pinning for High Performance VM due to wrong configuration: {}", vm.getName(), vm.getId(), finalMsgReason); return null; } return findCpusToPinIoAndEmulator(vm, hostNumaNodesSupplier, vdsCpuThreads); }

Target:
public String getIoThreadsAndEmulatorPinningCpus(VM vm, MemoizingSupplier<List<VdsNumaNode>> hostNumaNodesSupplier, int vdsCpuThreads) { if (vm.getVmType() != VmType.HighPerformance) { return null; } final String cpuPinning = vm.getCpuPinning(); List<VmNumaNode> vmNumaNodes = vmNumaNodeDao.getAllVmNumaNodeByVmId(vm.getId()); Optional<VmNumaNode> pinnedVmNumaNode = vmNumaNodes.stream().filter(d -> !d.getVdsNumaNodeList().isEmpty()).findAny(); if (StringUtils.isEmpty(cpuPinning) || !pinnedVmNumaNode.isPresent() || vm.getNumOfIoThreads() == 0) { String msgReason1 = StringUtils.isEmpty(cpuPinning) ? "CPU Pinning topology is not set": ""; String msgReason2 = vm.getNumOfIoThreads() == 0 ? "IO Threads is not enabled": ""; String msgReason3 = !pinnedVmNumaNode.isPresent() ? "vm's virtual NUMA nodes are not pinned to host's NUMA nodes": ""; String finalMsgReason = Arrays.asList(msgReason1, msgReason2, msgReason3).stream().filter(r -> !r.isEmpty()).collect(Collectors.joining(", ")) + "."; log.warn("No IO thread(s) pinning and Emulator thread(s) pinning for High Performance VM due to wrong configuration: {}", vm.getName(), vm.getId(), finalMsgReason); return null; } return findCpusToPinIoAndEmulator(vm, hostNumaNodesSupplier, vdsCpuThreads); }
Source:
protected void put(Data dataKey, Data dataValue) { MultiMapContainer container = getOrCreateContainer(); Collection c = (Collection) toObject(dataValue); Collection<MultiMapRecord> coll = container.getOrCreateMultiMapValue(dataKey).getCollection(false); Iterator it = c.iterator(); while (it.hasNext()) { Object o = it.next(); MultiMapRecord record = new MultiMapRecord(container.nextId(), isBinary() ? toData(o) : o); if (coll.add(record)) { response = true; } } }

Target:
protected void put(Data dataKey, Data dataValue) { MultiMapContainer container = getOrCreateContainer(); Collection<Data> c = ((DataCollection) toObject(dataValue)).getCollection(); Collection<MultiMapRecord> coll = container.getOrCreateMultiMapValue(dataKey).getCollection(false); Iterator<Data> it = c.iterator(); while (it.hasNext()) { Data o = it.next(); MultiMapRecord record = new MultiMapRecord(container.nextId(), isBinary() ? o : toObject(o)); if (coll.add(record)) { response = true; } } }
Source:
private RollingUpdateOp rollingUpdateUndeploy(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, final String host) { final List<ZooKeeperOperation> operations = Lists.newArrayList(); for (final Deployment deployment : getTasks(client, host).values()) { final boolean isOwnedByDeploymentGroup = Objects.equals( deployment.getDeploymentGroupName(), deploymentGroup.getName()); final boolean isSameJob = deployment.getJobId().equals(deploymentGroup.getJobId()); final RolloutOptions rolloutOptions = deploymentGroup.getRolloutOptions(); if (isOwnedByDeploymentGroup || ( isSameJob && rolloutOptions.getMigrate())) { if (isSameJob && isOwnedByDeploymentGroup && deployment.getGoal().equals(Goal.START)) { continue; } try { final String token = rolloutOptions.getToken() == null ? Job.EMPTY_TOKEN : rolloutOptions.getToken(); operations.addAll(getUndeployOperations( client, host, deployment.getJobId(), token)); } catch (TokenVerificationException e) { return opFactory.error(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR); } catch (HostNotFoundException e) { return opFactory.error(e, host, RollingUpdateError.HOST_NOT_FOUND); } catch (JobNotDeployedException e) { } } } return opFactory.nextTask(operations); }

Target:
private RollingUpdateOp rollingUpdateUndeploy(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, final String host) { final List<ZooKeeperOperation> operations = Lists.newArrayList(); for (final Deployment deployment : getTasks(client, host).values()) { final boolean isOwnedByDeploymentGroup = Objects.equals( deployment.getDeploymentGroupName(), deploymentGroup.getName()); final boolean isSameJob = deployment.getJobId().equals(deploymentGroup.getJobId()); final RolloutOptions rolloutOptions = deploymentGroup.getRolloutOptions(); if (isOwnedByDeploymentGroup || ( isSameJob && rolloutOptions.getMigrate())) { if (isSameJob && isOwnedByDeploymentGroup && deployment.getGoal().equals(Goal.START)) { continue; } try { final String token = firstNonNull(deploymentGroup.getRolloutOptions().getToken(), Job.EMPTY_TOKEN); operations.addAll(getUndeployOperations( client, host, deployment.getJobId(), token)); } catch (TokenVerificationException e) { return opFactory.error(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR); } catch (HostNotFoundException e) { return opFactory.error(e, host, RollingUpdateError.HOST_NOT_FOUND); } catch (JobNotDeployedException e) { } } } return opFactory.nextTask(operations); }
Source:
public AccessControlPolicyExtension( AccessControlSecurityConfiguration config, SubjectIdentity subjectIdentity) { isOwner = predicate(subjectIdentity.getIdentityAttribute(), Core.METACARD_OWNER); isSystem = (s) -> { Set<String> subject = s.getOrDefault(config.getSystemUserAttribute(), Collections.emptySet()); return subject.contains(config.getSystemUserAttributeValue()); }; hasAccessAdministrators = predicate(subjectIdentity.getIdentityAttribute(), Security.ACCESS_ADMINISTRATORS); hasAccessGroups = predicate(Constants.ROLES_CLAIM_URI, SecurityAttributes.ACCESS_GROUPS); hasAccessGroupsReadOnly = predicate(subjectIdentity.getIdentityAttribute(), SecurityAttributes.ACCESS_GROUPS_READ); hasAccessIndividuals = predicate(subjectIdentity.getIdentityAttribute(), SecurityAttributes.ACCESS_INDIVIDUALS); hasAccessIndividualsReadOnly = predicate( subjectIdentity.getIdentityAttribute(), SecurityAttributes.ACCESS_INDIVIDUALS_READ); }

Target:
public AccessControlPolicyExtension( AccessControlSecurityConfiguration config, SubjectIdentity subjectIdentity) { isOwner = predicate(subjectIdentity.getIdentityAttribute(), Core.METACARD_OWNER); isSystem = (s) -> { Set<String> subject = s.getOrDefault(config.getSystemUserAttribute(), Collections.emptySet()); return subject.contains(config.getSystemUserAttributeValue()); }; hasAccessAdministrators = predicate(subjectIdentity.getIdentityAttribute(), Security.ACCESS_ADMINISTRATORS); hasAccessGroups = predicate(Constants.ROLES_CLAIM_URI, SecurityAttributes.ACCESS_GROUPS); hasAccessGroupsReadOnly = predicate(Constants.ROLES_CLAIM_URI, SecurityAttributes.ACCESS_GROUPS_READ); hasAccessIndividuals = predicate(subjectIdentity.getIdentityAttribute(), SecurityAttributes.ACCESS_INDIVIDUALS); hasAccessIndividualsReadOnly = predicate( subjectIdentity.getIdentityAttribute(), SecurityAttributes.ACCESS_INDIVIDUALS_READ); }
Source:
public void shouldCaptureSuccessfully() { setUpAndCheckThatEpdqIsUp(); CardAuthorisationGatewayRequest request = buildAuthorisationRequest(chargeEntity); GatewayResponse<BaseAuthoriseResponse> response = paymentProvider.authorise(request); assertThat(response.isSuccessful(), is(true)); String transactionId = response.getBaseResponse().get().getTransactionId(); assertThat(transactionId, is(not(nullValue()))); CaptureGatewayRequest captureRequest = buildCaptureRequest(chargeEntity, transactionId); CaptureResponse captureResponse = paymentProvider.capture(captureRequest); assertThat(captureResponse.isSuccessful(), is(true)); }

Target:
public void shouldCaptureSuccessfully() { setUpAndCheckThatEpdqIsUp(); CardAuthorisationGatewayRequest request = buildAuthorisationRequest(chargeEntity); GatewayResponse<BaseAuthoriseResponse> response = paymentProvider.authorise(request); assertThat(response.isSuccessful(), is(true)); String transactionId = response.getBaseResponse().get().getTransactionId(); assertThat(transactionId, is(not(nullValue()))); CaptureGatewayRequest captureRequest = buildCaptureRequest(chargeEntity, transactionId); CaptureResponse captureResponse = paymentProvider.capture(captureRequest); assertThat(captureResponse.isSuccessful(), is(true)); assertThat(captureResponse.state(), Is.is(CaptureResponse.ChargeState.PENDING)); }
Source:
public String getPeerUserAgent() { if (options == null) throw new RequestNotYetReadException(); for (String o : options) { if (o.startsWith(AGENT)) return o.substring(AGENT.length()); } return userAgent; }

Target:
public String getPeerUserAgent() { return UserAgent.getAgent(options, userAgent); }
Source:
public WebElement getFiltersSuggestionByName(String suggestionName) { return seleniumWebDriverHelper.waitVisibility( By.xpath(format(" }

Target:
public WebElement getFiltersSuggestionByName(String suggestionName) { String filtersSuggestion = format(" return seleniumWebDriverHelper.waitVisibility(By.xpath(filtersSuggestion)); }
Source:
public Object invoke(Object object, Method method, Object[] objects) throws Throwable { if ("toString".equals(method.getName())) { return "Proxy element for: " + locator.toString(); } WebElement element; try { element = locator.findElement(); } catch (NoSuchElementException e) { throw e; } if ("getWrappedElement".equals(method.getName())) { return element; } try { return method.invoke(element, objects); } catch (InvocationTargetException e) { throw e.getCause(); } }

Target:
public Object invoke(Object object, Method method, Object[] objects) throws Throwable { if ("toString".equals(method.getName())) { return format("Proxy element for: %s", locator.toString()); } WebElement element; try { element = locator.findElement(); } catch (NoSuchElementException e) { throw e; } if ("getWrappedElement".equals(method.getName())) { return element; } try { return method.invoke(element, objects); } catch (InvocationTargetException e) { throw e.getCause(); } }
Source:
public void set(long index, Slice value) { Slice currentValue = array.get(index); if (currentValue != null) { int baseReferenceCount = trackedSlices.decrementReference(currentValue.getBase()); int sliceReferenceCount = trackedSlices.decrementReference(currentValue); if (baseReferenceCount == 0) { sizeOfSlices -= currentValue.getRetainedSize(); } else if (sliceReferenceCount == 0) { sizeOfSlices -= SLICE_INSTANCE_SIZE; } } if (value != null) { int baseReferenceCount = trackedSlices.incrementReference(value.getBase()); int sliceReferenceCount = trackedSlices.incrementReference(value); if (baseReferenceCount == 1) { sizeOfSlices += value.getRetainedSize(); } else if (sliceReferenceCount == 1) { sizeOfSlices += SLICE_INSTANCE_SIZE; } } array.set(index, value); }

Target:
public void set(long index, Slice value) { updateRetainedSize(index, value); array.set(index, value); }
Source:
private static int readCPUMask() { try (Stream<String> lines = Files.lines(Paths.get("/proc/self/status"), StandardCharsets.US_ASCII)) { return lines.filter(line -> line.startsWith(CPUS_ALLOWED)) .findFirst().map(line -> { int count = 0; int start = CPUS_ALLOWED.length(); for (int i = start; i < line.length(); i++) { char ch = line.charAt(i); if (ch >= '0' && ch <= '9') { count += BITS[ch - '0']; } else if (ch >= 'a' && ch <= 'f') { count += BITS[ch - 'a' + 10]; } else if (ch >= 'A' && ch <= 'F') { count += BITS[ch - 'A' + 10]; } } return count; }).orElse(-1); } catch (IOException e) { return -1; } }

Target:
private static int readCPUMask() { try (Stream<String> lines = Files.lines(Paths.get(PROC_SELF_STATUS), StandardCharsets.US_ASCII)) { return lines.filter(line -> line.startsWith(CPUS_ALLOWED)) .findFirst().map(line -> { int count = 0; int start = CPUS_ALLOWED.length(); for (int i = start; i < line.length(); i++) { char ch = line.charAt(i); if (ch >= '0' && ch <= '9') { count += BITS[ch - '0']; } else if (ch >= 'a' && ch <= 'f') { count += BITS[ch - 'a' + 10]; } else if (ch >= 'A' && ch <= 'F') { count += BITS[ch - 'A' + 10]; } } return count; }).orElse(-1); } catch (IOException e) { return -1; } }
Source:
private String extractNextLink(HttpResponse canvasResponse) { String linkValueString = null; String linkValueNext = null; String searchPhrase = "rel=\"next\""; M_log.debug("SEARCH PHRASE: " + searchPhrase); HashMap<String, String> links = new HashMap<String, String>(); Header[] headers = canvasResponse.getAllHeaders(); for (Header header : headers) { M_log.debug("Key : " + header.getName() + " ,Value : " + header.getValue()); if(header.getName().equals("Link")){ linkValueString = header.getValue(); String[] headerPairs = linkValueString.split(","); for(String headerPair : headerPairs){ M_log.debug("String: " + headerPair); String[] splitPairs = headerPair.split(";"); splitPairs[0] = splitPairs[0].replace("<",""); splitPairs[0] = splitPairs[0].replace(">",""); links.put(splitPairs[1].trim(), splitPairs[0]); } break; } } if(links.containsKey(searchPhrase)){ M_log.debug("LINKS CONTAINS NEXT: " + links.get(searchPhrase)); linkValueNext = links.get(searchPhrase); linkValueNext = linkValueNext.substring(linkValueNext.indexOf("/api"), linkValueNext.length()); M_log.debug("NEW VALUE: " + linkValueNext); linkValueNext = "/canvasCourseManager/manager" + linkValueNext; M_log.debug("NEW VALUE: " + linkValueNext); if(linkValueNext.contains("as_user_id")){ linkValueNext = linkValueNext.replaceAll("as_user_id=sis_login_id.*?&", "user=self&"); M_log.debug("NEW VALUE: " + linkValueNext); } } M_log.debug("LINKS; " + links); M_log.debug("NEXT LINK VALUE: " + linkValueNext); return linkValueNext; }

Target:
private String extractNextLink(HttpResponse canvasResponse) { String linkValueString = null; String linkValueNext = null; String searchPhrase = "rel=\"next\""; M_log.debug("SEARCH PHRASE: " + searchPhrase); HashMap<String, String> links = new HashMap<String, String>(); Header[] headers = canvasResponse.getHeaders("Link"); for (Header header : headers) { M_log.debug("Key : " + header.getName() + " ,Value : " + header.getValue()); if(header.getName().equals("Link")){ linkValueString = header.getValue(); String[] headerPairs = linkValueString.split(","); for(String headerPair : headerPairs){ M_log.debug("String: " + headerPair); String[] splitPairs = headerPair.split(";"); splitPairs[0] = splitPairs[0].replace("<",""); splitPairs[0] = splitPairs[0].replace(">",""); links.put(splitPairs[1].trim(), splitPairs[0]); } break; } } if(links.containsKey(searchPhrase)){ M_log.debug("LINKS CONTAINS NEXT: " + links.get(searchPhrase)); linkValueNext = "/canvasCourseManager/manager" + links.get(searchPhrase).substring(links.get(searchPhrase).indexOf("/api"), links.get(searchPhrase).length()); if(linkValueNext.contains("as_user_id")){ linkValueNext = linkValueNext.replaceAll("as_user_id=sis_login_id.*?&", "user=self&"); } } M_log.debug("LINKS; " + links); M_log.debug("NEXT LINK VALUE: " + linkValueNext); return linkValueNext; }
Source:
public ServiceManagerEnvironment loadServiceManagerEnvironment(IServer server) { Map<String, String> adbEnv = loadDockerEnv(server); Properties props = loadOpenshiftConsoleDetails(server); Map<String, String> merged = merge(adbEnv, props); String dotMinishift = System.getProperty("user.home") + File.separator + ".minishift"; Properties dotCDK = CDKServerUtility.getDotCDK(dotMinishift); merged = merge(merged, dotCDK); if( merged == null ) { System.out.println("WHY!?!?!"); } try { return new ServiceManagerEnvironment(merged); } catch (URISyntaxException urise) { CDKCoreActivator.pluginLog() .logError("Environment variable DOCKER_HOST is not a valid uri: " + merged.get("DOCKER_HOST"), urise); return null; } }

Target:
public ServiceManagerEnvironment loadServiceManagerEnvironment(IServer server) { Map<String, String> adbEnv = loadDockerEnv(server); Properties props = loadOpenshiftConsoleDetails(server); Map<String, String> merged = merge(adbEnv, props); String dotMinishift = System.getProperty("user.home") + File.separator + ".minishift"; Properties dotCDK = CDKServerUtility.getDotCDK(dotMinishift); merged = merge(merged, dotCDK); try { return new ServiceManagerEnvironment(merged); } catch (URISyntaxException urise) { CDKCoreActivator.pluginLog() .logError("Environment variable DOCKER_HOST is not a valid uri: " + merged.get("DOCKER_HOST"), urise); return null; } }
Source:
public String getItemType() { return DisplayableItemNode.FILE_PARENT_NODE_KEY; }

Target:
public String getItemType() { return getClass().getName(); }
Source:
public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("myId", myId) .append("myUrl", myUrl) .append(myResource != null ? ("myResource=" + myResource.toString()) : ("myResource=(null)")) .append("myResourcePid", myResourcePid) .append("myName", myName) .append(myCodes != null ? ("myCodes - size=" + myCodes.size()) : ("myCodes=(null)")) .toString(); }

Target:
public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("myId", myId) .append("myUrl", myUrl) .append(myResource != null ? ("myResource=" + myResource.toString()) : ("myResource=(null)")) .append("myResourcePid", myResourcePid) .append("myName", myName) .append(myCodes != null ? ("myCodes - size=" + myCodes.size()) : ("myCodes=(null)")) .toString(); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof RouteInfo)) return false; RouteInfo target = (RouteInfo) obj; return Objects.equals(mDestination, target.getDestination()); }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof RouteInfo)) return false; RouteInfo target = (RouteInfo) obj; return Objects.equals(mDestination, target.getDestination()) && Objects.equals(mGateway, target.getGateway()) && Objects.equals(mInterface, target.getInterface()) && mType == target.getType() && mMtu == target.getMtu(); }
Source:
public void move(FileResource<?> target) { try { getFileOperations().move(file, target.getUnderlyingResourceObject()); this.file = target.getUnderlyingResourceObject(); } catch (IOException e) { throw new ResourceException("Error while moving Resource " + this, e); } }

Target:
public void move(FileResource<?> target) { try { this.file = getFileOperations().move(file, target.getUnderlyingResourceObject()); } catch (IOException e) { throw new ResourceException("Error while moving Resource " + this, e); } }
Source:
private static Function1<CharSeq, CharSeq> removeTrailingZeroes() { return seq -> seq .reverse() .dropWhile(c -> Character.valueOf('0').equals(c)) .reverse(); }

Target:
private static Function1<CharSeq, CharSeq> removeTrailingZeroes() { return seq -> seq .reverse() .dropWhile(c -> c == '0') .reverse(); }
Source:
public void run() { while (running) { long now = System.currentTimeMillis(); checkLowReplication(now); boolean periodic = (now - this.lastRollTime) > this.rollPeriod; if (periodic) { LOG.debug("WAL roll period ms elapsed", this.rollPeriod); } else { synchronized (this) { if (walNeedsRoll.values().stream().anyMatch(Boolean::booleanValue)) { LOG.debug("WAL roll requested"); } else { try { wait(this.threadWakeFrequency); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } continue; } } } try { this.lastRollTime = System.currentTimeMillis(); for (Iterator<Entry<WAL, Boolean>> iter = walNeedsRoll.entrySet().iterator(); iter .hasNext();) { Entry<WAL, Boolean> entry = iter.next(); if (!periodic && !entry.getValue()) { continue; } WAL wal = entry.getKey(); entry.setValue(Boolean.FALSE); Map<byte[], List<byte[]>> regionsToFlush = null; try { regionsToFlush = wal.rollWriter(true); } catch (WALClosedException e) { LOG.warn("WAL has been closed. Skipping rolling of writer and just remove it", e); iter.remove(); } if (regionsToFlush != null) { for (Map.Entry<byte[], List<byte[]>> r : regionsToFlush.entrySet()) { scheduleFlush(Bytes.toString(r.getKey()), r.getValue()); } } afterRoll(wal); } } catch (FailedLogCloseException | ConnectException e) { abort("Failed log close in log roller", e); } catch (IOException ex) { abort("IOE in log roller", ex instanceof RemoteException ? ((RemoteException) ex).unwrapRemoteException() : ex); } catch (Exception ex) { LOG.error("Log rolling failed", ex); abort("Log rolling failed", ex); } } LOG.info("LogRoller exiting."); }

Target:
public void run() { while (running) { long now = System.currentTimeMillis(); checkLowReplication(now); synchronized (this) { if (wals.values().stream().noneMatch(rc -> rc.needsRoll(now))) { try { wait(this.threadWakeFrequency); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } continue; } } try { for (Iterator<Entry<WAL, RollController>> iter = wals.entrySet().iterator(); iter.hasNext();) { Entry<WAL, RollController> entry = iter.next(); WAL wal = entry.getKey(); RollController controller = entry.getValue(); if (controller.isRollRequested()) { LOG.debug("WAL roll requested", wal); } else if (controller.needsPeriodicRoll(now)){ LOG.debug("WAL roll period ms elapsed", wal, this.rollPeriod); } else { continue; } try { Map<byte[], List<byte[]>> regionsToFlush = controller.rollWal(now); if (regionsToFlush != null) { for (Map.Entry<byte[], List<byte[]>> r : regionsToFlush.entrySet()) { scheduleFlush(Bytes.toString(r.getKey()), r.getValue()); } } } catch (WALClosedException e) { LOG.warn("WAL has been closed. Skipping rolling of writer and just remove it", e); iter.remove(); } afterRoll(wal); } } catch (FailedLogCloseException | ConnectException e) { abort("Failed log close in log roller", e); } catch (IOException ex) { abort("IOE in log roller", ex instanceof RemoteException ? ((RemoteException) ex).unwrapRemoteException() : ex); } catch (Exception ex) { LOG.error("Log rolling failed", ex); abort("Log rolling failed", ex); } } LOG.info("LogRoller exiting."); }
Source:
private Account getAccount(Account[] accounts, String username) { if (accounts != null) { for (Account account : accounts) { if (account.name.equals(username)) { return account; } } } return null; }

Target:
private Account getAccount(Account[] accounts, String username) { if (accounts != null && username != null) { for (Account account : accounts) { if (account.name.equalsIgnoreCase(username)) { return account; } } } return null; }
Source:
QueryResultSubject assertQueryResult(QueryResponse queryResponse) { checkNotNull(queryResponse, "`QueryResponse` must never be `null`"); Iterable<Message> entityStates = extractEntityStates(queryResponse); QueryResultSubject subject = assertAbout(queryResult()).that(entityStates); subject.initChildSubjects(queryResponse); return subject; }

Target:
QueryResultSubject assertQueryResult(QueryResponse queryResponse) { checkNotNull(queryResponse, "`QueryResponse` must never be `null`."); Iterable<Message> entityStates = extractEntityStates(queryResponse); QueryResultSubject subject = assertAbout(queryResult()).that(entityStates); subject.initChildSubjects(queryResponse); return subject; }
Source:
public void loadBlocks() { exec1 = new ExecutorPipeline(8, 1000, true, (Function<Block, Block>) b -> { if (b.getNumber() >= blockchain.getBlockStore().getBestBlock().getNumber()) { for (Transaction tx : b.getTransactionsList()) { tx.getSender(); } } return b; }, throwable -> logger.error("Unhandled exception: ", throwable) ); exec2 = exec1.add(1, 1000, block -> { try { blockWork(block); } catch (Exception e) { e.printStackTrace(); } }); String fileSrc = config.blocksLoader(); try { final String blocksFormat = config.getConfig().hasPath("blocks.format") ? config.getConfig().getString("blocks.format") : null; System.out.println("Loading blocks: " + fileSrc + ", format: " + blocksFormat); if ("rlp".equalsIgnoreCase(blocksFormat)) { Path path = Paths.get(fileSrc); byte[] data = Files.readAllBytes(path); RLPList list = RLP.decode2ListNarrow(data); for (RLPElement item : list) { Block block = new Block(item.getRLPData()); exec1.push(block); } } else { FileInputStream inputStream = new FileInputStream(fileSrc); scanner = new Scanner(inputStream, "UTF-8"); while (scanner.hasNextLine()) { byte[] blockRLPBytes = Hex.decode(scanner.nextLine()); Block block = new Block(blockRLPBytes); exec1.push(block); } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } try { exec1.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } dbFlushManager.flushSync(); System.out.println(" * Done * "); System.exit(0); }

Target:
public void loadBlocks() { exec1 = new ExecutorPipeline(8, 1000, true, (Function<Block, Block>) b -> { if (b.getNumber() >= blockchain.getBlockStore().getBestBlock().getNumber()) { for (Transaction tx : b.getTransactionsList()) { tx.getSender(); } } return b; }, throwable -> logger.error("Unhandled exception: ", throwable) ); exec2 = exec1.add(1, 1000, block -> { try { blockWork(block); } catch (Exception e) { e.printStackTrace(); } }); String fileSrc = config.blocksLoader(); try { final String blocksFormat = config.getConfig().hasPath("blocks.format") ? config.getConfig().getString("blocks.format") : null; System.out.println("Loading blocks: " + fileSrc + ", format: " + blocksFormat); if ("rlp".equalsIgnoreCase(blocksFormat)) { Path path = Paths.get(fileSrc); byte[] data = Files.readAllBytes(path); RLPList list = RLP.decode2(data, 1); for (RLPElement item : list) { Block block = new Block(item.getRLPData()); exec1.push(block); } } else { FileInputStream inputStream = new FileInputStream(fileSrc); scanner = new Scanner(inputStream, "UTF-8"); while (scanner.hasNextLine()) { byte[] blockRLPBytes = Hex.decode(scanner.nextLine()); Block block = new Block(blockRLPBytes); exec1.push(block); } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } try { exec1.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } dbFlushManager.flushSync(); System.out.println(" * Done * "); System.exit(0); }
Source:
LoginResponse runInJob(ICluster cluster, IAccount account) { LoginJob job = new LoginJob(cluster, account); job.schedule(); IProgressMonitor monitor = new NullProgressMonitor(); try { if (job.join(10000, monitor)) { return job.getResponse(); } else { throw new InterruptedException(); } } catch (OperationCanceledException e) { return null; } catch (InterruptedException e) { if (job.isRunninginUI()) { try { job.join(); return job.getResponse(); } catch (InterruptedException e1) { return null; } } else { job.setShouldRun(false); monitor.setCanceled(true); job.cancel(); return null; } } }

Target:
LoginResponse runInJob(ICluster cluster, IAccount account) { LoginJob job = new LoginJob(cluster, account); job.schedule(); IProgressMonitor monitor = new NullProgressMonitor(); try { if (job.join(TIMEOUT_JOB_ON_UI_THREAD, monitor)) { return job.getResponse(); } else { throw new InterruptedException(); } } catch (OperationCanceledException e) { return null; } catch (InterruptedException e) { if (job.isRunninginUI()) { try { job.join(); return job.getResponse(); } catch (InterruptedException e1) { return null; } } else { job.setShouldRun(false); monitor.setCanceled(true); job.cancel(); return null; } } }
Source:
protected void initEffectiveCompatibilityVersion() { Version effectiveCompatibilityVersion = VmPropertiesUtils.getInstance().getSupportedClusterLevels().contains(getParameters().getVmStaticData().getCustomCompatibilityVersion()) ? CompatibilityVersionUtils.getEffective(getParameters().getVmStaticData(), this::getCluster) : CompatibilityVersionUtils.getEffective(this::getCluster); setEffectiveCompatibilityVersion(effectiveCompatibilityVersion); }

Target:
protected void initEffectiveCompatibilityVersion() { setEffectiveCompatibilityVersion( CompatibilityVersionUtils.getEffective(getParameters().getVmStaticData(), this::getCluster)); }