auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void output(@AggregationState EntropyState state, BlockBuilder out) { if (state.getNull()) { out.appendNull(); return; } if (state.getSumC() == 0) { DOUBLE.writeDouble(out, 0); return; } double entropy = Math.max( (-state.getSumCLogC() / state.getSumC() + Math.log(state.getSumC())) / Math.log(2), 0); entropy = Math.max(entropy, 0); DOUBLE.writeDouble(out, entropy); }

Target:
public static void output(@AggregationState EntropyState state, BlockBuilder out) { Double entropy = 0.0; if (state.getSumC() > 0.0) { entropy = Math.max( (Math.log(state.getSumC()) - state.getSumCLogC() / state.getSumC()) / Math.log(2.0), 0.0); } DOUBLE.writeDouble(out, entropy); }
Source:
public void validateComponentType() { assertThat(this.defaultR2dbcMessageSource.getComponentType()).isEqualTo("r2dbc:inbound-channel" + "-adapter"); }

Target:
public void validateComponentType() { assertThat(this.defaultR2dbcMessageSource.getComponentType()) .isEqualTo("r2dbc:inbound-channel-adapter"); }
Source:
public void onComplete() { ObservableSource<? extends R> p = other; if (p == null) { downstream.onComplete(); } else { other = null; p.subscribe(this); } }

Target:
public void onComplete() { ObservableSource<? extends R> o = other; if (o == null) { downstream.onComplete(); } else { other = null; o.subscribe(this); } }
Source:
public Builder clusterName(String clusterName) { assertThat(clusterName, Objects::nonNull, () -> new AxonConfigurationException("The clusterName may not be null")); this.clusterName = clusterName; return this; }

Target:
public Builder clusterName(String clusterName) { assertClusterName(clusterName, "The clusterName may not be null or empty"); this.clusterName = clusterName; return this; }
Source:
private Answer executeRequest(UpdateDhcpOptionVspCommand cmd) { try { isNuageVspManagerLoaded(); _nuageVspGuruClient.applyDhcpOptions(cmd.getDhcpOptions(), cmd.getNetwork()); return new Answer(cmd, true, "Update DhcpOptions on VM's in network: " + cmd.getNetwork().getName() + " on Nuage VSD " + _hostName); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e); return new Answer(cmd, e); } }

Target:
private Answer executeRequest(UpdateDhcpOptionVspCommand cmd) { try { isNuageVspManagerLoaded(); _nuageVspGuruClient.applyDhcpOptions(cmd.getDhcpOptions(), cmd.getNetwork()); return new Answer(cmd, true, "Update DhcpOptions on VM's in network: " + cmd.getNetwork().getName() + " on Nuage VSD " + _hostName); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failure during " + cmd.toDetailString() + " on Nuage VSD " + _hostName, e); return new Answer(cmd, e); } }
Source:
public List<Map<String, Object>> getRefund(long refundId) { List<Map<String, Object>> ret = jdbi.withHandle(h -> h.createQuery("SELECT external_id, reference, amount, status, created_date, charge_id, refunded_by " + "FROM refunds " + "WHERE id = :refund_id") .bind("refund_id", refundId) .list()); return ret; }

Target:
public List<Map<String, Object>> getRefund(long refundId) { List<Map<String, Object>> ret = jdbi.withHandle(h -> h.createQuery("SELECT external_id, reference, amount, status, created_date, charge_id, user_external_id " + "FROM refunds " + "WHERE id = :refund_id") .bind("refund_id", refundId) .list()); return ret; }
Source:
static ReadStrand getStrand(final SAMRecord rec) { if (rec.getReadUnmappedFlag() || rec.getMateUnmappedFlag()) { return ReadStrand.UNKNOWN; } if (!rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag()) { if (rec.getFirstOfPairFlag() == (rec.getReferenceIndex() < rec.getMateReferenceIndex())) { return ReadStrand.TOP; } else { return ReadStrand.BOTTOM; } } final int read5PrimeStart = (rec.getReadNegativeStrandFlag()) ? rec.getUnclippedEnd() : rec.getUnclippedStart(); final int mate5PrimeStart = (rec.getMateNegativeStrandFlag()) ? SAMUtils.getMateUnclippedEnd(rec) : SAMUtils.getMateUnclippedStart(rec); if(rec.getFirstOfPairFlag() == (read5PrimeStart <= mate5PrimeStart)) { return ReadStrand.TOP; } else { return ReadStrand.BOTTOM; } }

Target:
static ReadStrand getStrand(final SAMRecord rec) { if (rec.getReadUnmappedFlag() || rec.getMateUnmappedFlag()) { return ReadStrand.UNKNOWN; } if (!rec.getReferenceIndex().equals(rec.getMateReferenceIndex())) { if (rec.getFirstOfPairFlag() == (rec.getReferenceIndex() < rec.getMateReferenceIndex())) { return ReadStrand.TOP; } else { return ReadStrand.BOTTOM; } } final int read5PrimeStart = (rec.getReadNegativeStrandFlag()) ? rec.getUnclippedEnd() : rec.getUnclippedStart(); final int mate5PrimeStart = (rec.getMateNegativeStrandFlag()) ? SAMUtils.getMateUnclippedEnd(rec) : SAMUtils.getMateUnclippedStart(rec); if (rec.getFirstOfPairFlag() == (read5PrimeStart <= mate5PrimeStart)) { return ReadStrand.TOP; } else { return ReadStrand.BOTTOM; } }
Source:
private void checkOrSetContentType(final Contentlet contentletIn, final User user) { if (contentletIn.isNew() && null == contentletIn.getContentType() && contentletIn.getMap().containsKey(Contentlet.BASE_TYPE_KEY)) { final BaseContentType baseContentType = BaseContentType.getBaseContentType( (String) contentletIn.getMap().get(Contentlet.BASE_TYPE_KEY)); if (null != baseContentType) { final Optional<BaseTypeToContentTypeStrategy> typeStrategy = this.baseTypeToContentTypeStrategyResolver.get(baseContentType); if (typeStrategy.isPresent()) { final Host host = Try.of(()->APILocator.getHostAPI().find( contentletIn.getHost(), user, false)).getOrNull(); if (null != host) { final Optional<ContentType> contentTypeOpt = typeStrategy.get().apply(baseContentType, CollectionsUtils.map("user", user, "host", host, "contentletMap", contentletIn.getMap())); if (contentTypeOpt.isPresent()) { contentletIn.setContentType(contentTypeOpt.get()); } } } } } }

Target:
private void checkOrSetContentType(final Contentlet contentletIn, final User user) { final Optional<BaseContentType> baseTypeOpt = contentletIn.getBaseType(); if (contentletIn.isNew() && null == contentletIn.getContentType() && baseTypeOpt.isPresent()) { final BaseContentType baseContentType = baseTypeOpt.get(); final Optional<BaseTypeToContentTypeStrategy> typeStrategy = this.baseTypeToContentTypeStrategyResolver.get(baseContentType); if (typeStrategy.isPresent()) { final Host host = Try.of(()->APILocator.getHostAPI().find( contentletIn.getHost(), user, false)).getOrNull(); if (null != host) { final Optional<ContentType> contentTypeOpt = typeStrategy.get().apply(baseContentType, CollectionsUtils.map("user", user, "host", host, "contentletMap", contentletIn.getMap())); if (contentTypeOpt.isPresent()) { contentletIn.setContentType(contentTypeOpt.get()); } } } } }
Source:
public void surviveWithOneTaskAsStandby() throws ExecutionException, InterruptedException, IOException { IntegrationTestUtils.produceKeyValuesSynchronouslyWithTimestamp( inputTopic, Collections.singletonList( new KeyValue<>(0, 0)), TestUtils.producerConfig( CLUSTER.bootstrapServers(), IntegerSerializer.class, IntegerSerializer.class, new Properties()), 10L); final String appId = "eos-test-app"; final String stateDirPath = TestUtils.tempDirectory(appId).getPath(); final CountDownLatch instanceLatch = new CountDownLatch(1); try ( final KafkaStreams streamInstanceOne = buildStreamWithDirtyStateDir(appId, stateDirPath + "/" + appId + "-1/", instanceLatch); final KafkaStreams streamInstanceTwo = buildStreamWithDirtyStateDir(appId, stateDirPath + "/" + appId + "-2/", instanceLatch); ) { streamInstanceOne.start(); streamInstanceTwo.start(); assertTrue(instanceLatch.await(15, TimeUnit.SECONDS)); waitForCondition(() -> streamInstanceOne.state().equals(KafkaStreams.State.RUNNING), "Stream instance one should be up and running by now"); waitForCondition(() -> streamInstanceTwo.state().equals(KafkaStreams.State.RUNNING), "Stream instance one should be up and running by now"); streamInstanceOne.close(Duration.ZERO); streamInstanceTwo.close(Duration.ZERO); } }

Target:
public void surviveWithOneTaskAsStandby() throws ExecutionException, InterruptedException, IOException { IntegrationTestUtils.produceKeyValuesSynchronouslyWithTimestamp( inputTopic, Collections.singletonList( new KeyValue<>(0, 0)), TestUtils.producerConfig( CLUSTER.bootstrapServers(), IntegerSerializer.class, IntegerSerializer.class, new Properties()), 10L); final String appId = "eos-test-app"; final String stateDirPath = TestUtils.tempDirectory(appId).getPath(); final CountDownLatch instanceLatch = new CountDownLatch(1); try ( final KafkaStreams streamInstanceOne = buildStreamWithDirtyStateDir(appId, stateDirPath + "/" + appId + "-1/", instanceLatch); final KafkaStreams streamInstanceTwo = buildStreamWithDirtyStateDir(appId, stateDirPath + "/" + appId + "-2/", instanceLatch); ) { streamInstanceOne.start(); streamInstanceTwo.start(); assertTrue(instanceLatch.await(15, TimeUnit.SECONDS)); waitForCondition(() -> streamInstanceOne.state().equals(KafkaStreams.State.RUNNING), "Stream instance one should be up and running by now"); waitForCondition(() -> streamInstanceTwo.state().equals(KafkaStreams.State.RUNNING), "Stream instance two should be up and running by now"); streamInstanceOne.close(Duration.ZERO); streamInstanceTwo.close(Duration.ZERO); } }
Source:
public String viewEntityDetailsById(@PathVariable(value = "entityTypeId") String entityTypeId, @PathVariable(value = "entityId") String entityId, Model model) throws Exception { EntityType entityType = dataService.getEntityType(entityTypeId); if (entityType == null) { throw new MolgenisDataAccessException( "EntityType with id [" + entityTypeId + "] does not exist. Did you use the correct URL?"); } else { Object id = getTypedValue(entityId, entityType.getIdAttribute()); model.addAttribute("entity", dataService.getRepository(entityTypeId).findOneById(id)); model.addAttribute("entityType", entityType); model.addAttribute("entityTypeId", entityTypeId); model.addAttribute("viewName", getStandaloneReportViewName(entityTypeId)); return "view-standalone-report"; } }

Target:
public String viewEntityDetailsById(@PathVariable(value = "entityTypeId") String entityTypeId, @PathVariable(value = "entityId") String entityId, Model model) throws Exception { EntityType entityType = dataService.getEntityType(entityTypeId); if (entityType == null) { throw new MolgenisDataAccessException( "EntityType with id [" + entityTypeId + "] does not exist. Did you use the correct URL?"); } Object id = getTypedValue(entityId, entityType.getIdAttribute()); model.addAttribute("entity", dataService.getRepository(entityTypeId).findOneById(id)); model.addAttribute("entityType", entityType); model.addAttribute("entityTypeId", entityTypeId); model.addAttribute("viewName", getStandaloneReportViewName(entityTypeId)); return "view-standalone-report"; }
Source:
private void setHColumnFamilyProperties(HColumnDescriptor[] columnDescriptors) { Map<ImmutableBytesWritable, ImmutableBytesWritable> propsMap = columnDescriptors[0].getValues(); for(Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry : propsMap.entrySet()){ ImmutableBytesWritable key = entry.getKey(); ImmutableBytesWritable defaultValue = entry.getValue(); Map<String, String> CFMap = new HashMap<String, String>(); Set<ImmutableBytesWritable> set = new HashSet<ImmutableBytesWritable>(); for(HColumnDescriptor columnDescriptor: columnDescriptors){ String columnFamilyName = Bytes.toString(columnDescriptor.getName()); ImmutableBytesWritable value = columnDescriptor.getValues().get(key); if (SYNCED_DATA_TABLE_AND_INDEX_COL_FAM_PROPERTIES.contains(Bytes.toString(key.get()))){ definedProps.put(Bytes.toString(key.get()), Bytes.toString(value.get())); continue; } CFMap.put(columnFamilyName, Bytes.toString(value.get())); set.add(value); } if (set.size() > 1){ for(Map.Entry<String, String> mapEntry: CFMap.entrySet()){ definedProps.put(String.format("%s.%s", mapEntry.getKey(), Bytes.toString(key.get())), mapEntry.getValue()); } } else { definedProps.put(Bytes.toString(key.get()), Bytes.toString(defaultValue.get())); } } }

Target:
private void setHColumnFamilyProperties(HColumnDescriptor[] columnDescriptors) { Map<ImmutableBytesWritable, ImmutableBytesWritable> propsMap = columnDescriptors[0].getValues(); for(Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry : propsMap.entrySet()) { ImmutableBytesWritable key = entry.getKey(); ImmutableBytesWritable globalValue = entry.getValue(); Map<String, String> cfToPropertyValueMap = new HashMap<String, String>(); Set<ImmutableBytesWritable> cfPropertyValueSet = new HashSet<ImmutableBytesWritable>(); for(HColumnDescriptor columnDescriptor: columnDescriptors) { String columnFamilyName = Bytes.toString(columnDescriptor.getName()); ImmutableBytesWritable value = columnDescriptor.getValues().get(key); if (SYNCED_DATA_TABLE_AND_INDEX_COL_FAM_PROPERTIES.contains(Bytes.toString(key.get()))) { definedProps.put(Bytes.toString(key.get()), Bytes.toString(value.get())); break; } cfToPropertyValueMap.put(columnFamilyName, Bytes.toString(value.get())); cfPropertyValueSet.add(value); } if (cfPropertyValueSet.size() > 1) { for(Map.Entry<String, String> mapEntry: cfToPropertyValueMap.entrySet()) { definedProps.put(String.format("%s.%s", mapEntry.getKey(), Bytes.toString(key.get())), mapEntry.getValue()); } } else { definedProps.put(Bytes.toString(key.get()), Bytes.toString(globalValue.get())); } } }
Source:
public void unrelatedNodesWithSamePropertyShouldNotInterfereWithUniquenessCheck() throws Exception { createConstraint( "Person", "id" ); long ourNode; { Statement statement = statementInNewTransaction( AnonymousContext.writeToken() ); ourNode = createLabeledNode( statement, "Person", "id", 1 ); createLabeledNode( statement, "Item", "id", 2 ); commit(); } Statement statement = statementInNewTransaction( AnonymousContext.writeToken() ); ReadOperations readOps = statement.readOperations(); int person = readOps.labelGetForName( "Person" ); int propId = readOps.propertyKeyGetForName( "id" ); final int labelId = person; final int[] propertyKeyIds = new int[]{propId}; NewIndexDescriptor idx = readOps .uniqueIndexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( labelId, propertyKeyIds ) ); createLabeledNode( statement, "Item", "id", 2 ); assertThat( readOps.nodeGetFromUniqueIndexSeek( idx, exact( propId, 1 ) ), equalTo( ourNode ) ); }

Target:
public void unrelatedNodesWithSamePropertyShouldNotInterfereWithUniquenessCheck() throws Exception { createConstraint( "Person", "id" ); long ourNode; { Statement statement = statementInNewTransaction( AnonymousContext.writeToken() ); ourNode = createLabeledNode( statement, "Person", "id", 1 ); createLabeledNode( statement, "Item", "id", 2 ); commit(); } Statement statement = statementInNewTransaction( AnonymousContext.writeToken() ); ReadOperations readOps = statement.readOperations(); int person = readOps.labelGetForName( "Person" ); int propId = readOps.propertyKeyGetForName( "id" ); NewIndexDescriptor idx = readOps .uniqueIndexGetForLabelAndPropertyKey( SchemaDescriptorFactory.forLabel( person, propId ) ); createLabeledNode( statement, "Item", "id", 2 ); assertThat( readOps.nodeGetFromUniqueIndexSeek( idx, exact( propId, 1 ) ), equalTo( ourNode ) ); }
Source:
AssignableNode(ClusterConfig clusterConfig, InstanceConfig instanceConfig, String instanceName) { _instanceName = instanceName; Map<String, Integer> instanceCapacity = fetchInstanceCapacity(clusterConfig, instanceConfig); _faultZone = computeFaultZone(clusterConfig, instanceConfig); _instanceTags = ImmutableSet.copyOf(instanceConfig.getTags()); _disabledPartitionsMap = ImmutableMap.copyOf(instanceConfig.getDisabledPartitionsMap()); _maxAllowedCapacity = ImmutableMap.copyOf(instanceCapacity); _remainingCapacity = new HashMap<>(_maxAllowedCapacity); _maxPartition = clusterConfig.getMaxPartitionsPerInstance(); }

Target:
AssignableNode(ClusterConfig clusterConfig, InstanceConfig instanceConfig, String instanceName) { _instanceName = instanceName; Map<String, Integer> instanceCapacity = fetchInstanceCapacity(clusterConfig, instanceConfig); _faultZone = computeFaultZone(clusterConfig, instanceConfig); _instanceTags = ImmutableSet.copyOf(instanceConfig.getTags()); _disabledPartitionsMap = ImmutableMap.copyOf(instanceConfig.getDisabledPartitionsMap()); _maxAllowedCapacity = ImmutableMap.copyOf(instanceCapacity); _remainingCapacity = new HashMap<>(instanceCapacity); _maxPartition = clusterConfig.getMaxPartitionsPerInstance(); _currentAssignedReplicaMap = new HashMap<>(); _highestCapacityUtilization = 0f; }
Source:
public ResponseEntity<String> viewTextfile(@RequestParam("txtid") String txtId, HttpServletResponse response, HttpServletRequest request) throws QuadrigaAccessException { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String respMessage = null; try { respMessage = tfManager.retrieveTextFileContent(txtId); String decodedRespMsg = StringEscapeUtils.unescapeXml(respMessage); return new ResponseEntity<String>(decodedRespMsg, HttpStatus.OK); } catch (FileStorageException e) { logger.error(e.getMessage()); respMessage = "Error while retrieving the file content"; return new ResponseEntity<String>(respMessage, HttpStatus.NOT_FOUND); } }

Target:
public ResponseEntity<String> viewTextfile(@RequestParam("txtid") String txtId, HttpServletResponse response, HttpServletRequest request) throws QuadrigaAccessException { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String respMessage = null; try { respMessage = tfManager.retrieveTextFileContent(txtId); return new ResponseEntity<String>(respMessage, HttpStatus.OK); } catch (FileStorageException e) { logger.error(e.getMessage()); respMessage = "Error while retrieving the file content"; return new ResponseEntity<String>(respMessage, HttpStatus.NOT_FOUND); } }
Source:
public ListenableFuture<TaskStatus> run(final Task task) { RemoteTaskRunnerWorkItem runningTask = runningTasks.get(task.getId()); if (runningTask != null) { ZkWorker zkWorker = findWorkerRunningTask(task.getId()); if (zkWorker == null) { log.error("Got task %s that is running but no worker is actually running it?", task.getId()); runningTasks.remove(task.getId()); } else { log.info("Task[%s] already running on %s.", task.getId(), zkWorker.getWorker().getHost()); TaskStatus status = zkWorker.getRunningTasks().get(task.getId()); if (status.isComplete()) { taskComplete(runningTask, zkWorker, task.getId(), status); } return runningTask.getResult(); } } RemoteTaskRunnerWorkItem pendingTask = pendingTasks.get(task.getId()); if (pendingTask != null) { log.info("Assigned a task[%s] that is already pending, not doing anything", task.getId()); return pendingTask.getResult(); } RemoteTaskRunnerWorkItem taskRunnerWorkItem = new RemoteTaskRunnerWorkItem( task, SettableFuture.<TaskStatus>create() ); addPendingTask(taskRunnerWorkItem); return taskRunnerWorkItem.getResult(); }

Target:
public ListenableFuture<TaskStatus> run(final Task task) { RemoteTaskRunnerWorkItem runningTask = runningTasks.get(task.getId()); if (runningTask != null) { ZkWorker zkWorker = findWorkerRunningTask(task.getId()); if (zkWorker == null) { log.makeAlert("Told to run task that is in the running queue but no worker is actually running it?!") .addData("taskId", task.getId()) .emit(); runningTasks.remove(task.getId()); } else { log.info("Task[%s] already running on %s.", task.getId(), zkWorker.getWorker().getHost()); TaskStatus status = zkWorker.getRunningTasks().get(task.getId()); if (status.isComplete()) { taskComplete(runningTask, zkWorker, task.getId(), status); } return runningTask.getResult(); } } RemoteTaskRunnerWorkItem pendingTask = pendingTasks.get(task.getId()); if (pendingTask != null) { log.info("Assigned a task[%s] that is already pending, not doing anything", task.getId()); return pendingTask.getResult(); } RemoteTaskRunnerWorkItem taskRunnerWorkItem = new RemoteTaskRunnerWorkItem( task, SettableFuture.<TaskStatus>create() ); addPendingTask(taskRunnerWorkItem); return taskRunnerWorkItem.getResult(); }
Source:
private static @NonNull InputStream readFilePath(@NonNull FilePath index) throws IOException, InterruptedException { InputStream stream = index.read(); assert stream != null; return stream; }

Target:
private static InputStream readFilePath(@NonNull FilePath index) throws IOException, InterruptedException { InputStream stream = index.read(); assert stream != null; return stream; }
Source:
public static StarlarkInt xor(StarlarkInt x, StarlarkInt y) { if (x instanceof Int32 && y instanceof Int32) { int xl = ((Int32) x).v; int yl = ((Int32) y).v; return StarlarkInt.of(xl ^ yl); } try { long xl = x.toLongFast(); long yl = y.toLongFast(); return StarlarkInt.of(xl ^ yl); } catch (Overflow unused) { } BigInteger xbig = x.toBigInteger(); BigInteger ybig = y.toBigInteger(); BigInteger zbig = xbig.xor(ybig); return StarlarkInt.of(zbig); }

Target:
public static StarlarkInt xor(StarlarkInt x, StarlarkInt y) { try { long xl = x.toLongFast(); long yl = y.toLongFast(); return StarlarkInt.of(xl ^ yl); } catch (Overflow unused) { } BigInteger xbig = x.toBigInteger(); BigInteger ybig = y.toBigInteger(); BigInteger zbig = xbig.xor(ybig); return StarlarkInt.of(zbig); }
Source:
private void processCommandLine(String[] args) { if (args == null || args.length == 0) return; String arg; for (int i = 0; i < args.length; i++) { if (i == args.length - 1 || args[i + 1].startsWith("-")) continue; arg = args[++i]; if (args[i - 1].equalsIgnoreCase(KEYRING)) keyringFile = arg; if (args[i - 1].equalsIgnoreCase(PASSWORD)) password = arg; } }

Target:
private void processCommandLine(String[] args) { if (args == null || args.length == 0) return; for (int i = 0; i < args.length; i++) { if (i == args.length - 1 || args[i + 1].startsWith("-")) continue; String arg = args[++i]; if (args[i - 1].equalsIgnoreCase(KEYRING)) keyringFile = arg; if (args[i - 1].equalsIgnoreCase(PASSWORD)) password = arg; } }
Source:
private FSQueue createNewQueues(FSQueueType queueType, FSParentQueue topParent, List<String> newQueueNames) { AllocationConfiguration queueConf = scheduler.getAllocationConfiguration(); Iterator<String> i = newQueueNames.iterator(); FSParentQueue parent = topParent; FSQueue queue = null; while (i.hasNext()) { FSParentQueue newParent = null; String queueName = i.next(); SchedulingPolicy policy = scheduler.getAllocationConfiguration(). getSchedulingPolicy(queueName); try { parent.getPolicy().isChildPolicyAllowed(policy); } catch (AllocationConfigurationException ex) { LOG.error("Can't create queue '" + queueName + "'.", ex); return null; } if (!i.hasNext() && (queueType != FSQueueType.PARENT)) { FSLeafQueue leafQueue = new FSLeafQueue(queueName, scheduler, parent); leafQueues.add(leafQueue); queue = leafQueue; } else { newParent = new FSParentQueue(queueName, scheduler, parent); queue = newParent; } try { policy.initialize(scheduler.getClusterResource()); queue.setPolicy(policy); } catch (AllocationConfigurationException ex) { LOG.error("Failed to set the scheduling policy!", ex); } parent.addChildQueue(queue); setChildResourceLimits(parent, queue, queueConf); queues.put(queue.getName(), queue); parent = newParent; } return queue; }

Target:
private FSQueue createNewQueues(FSQueueType queueType, FSParentQueue topParent, List<String> newQueueNames) { AllocationConfiguration queueConf = scheduler.getAllocationConfiguration(); Iterator<String> i = newQueueNames.iterator(); FSParentQueue parent = topParent; FSQueue queue = null; while (i.hasNext()) { FSParentQueue newParent = null; String queueName = i.next(); SchedulingPolicy childPolicy = scheduler.getAllocationConfiguration(). getSchedulingPolicy(queueName); if (!parent.getPolicy().isChildPolicyAllowed(childPolicy)) { LOG.error("Can't create queue '" + queueName + "'."); return null; } if (!i.hasNext() && (queueType != FSQueueType.PARENT)) { FSLeafQueue leafQueue = new FSLeafQueue(queueName, scheduler, parent); leafQueues.add(leafQueue); queue = leafQueue; } else { if (childPolicy instanceof FifoPolicy) { LOG.error("Can't create queue '" + queueName + "', since " + FifoPolicy.NAME + " is only for leaf queues."); return null; } newParent = new FSParentQueue(queueName, scheduler, parent); queue = newParent; } parent.addChildQueue(queue); setChildResourceLimits(parent, queue, queueConf); queues.put(queue.getName(), queue); parent = newParent; } return queue; }
Source:
public void testAccessCheck() { final WinNT.GENERIC_MAPPING mapping = new WinNT.GENERIC_MAPPING(); mapping.genericRead = new DWORD(FILE_GENERIC_READ); mapping.genericWrite = new DWORD(FILE_GENERIC_WRITE); mapping.genericExecute = new DWORD(FILE_GENERIC_EXECUTE); mapping.genericAll = new DWORD(FILE_ALL_ACCESS); final Memory securityDescriptorMemoryPointer = new Memory(1); final PRIVILEGE_SET privileges = new PRIVILEGE_SET(1); privileges.PrivilegeCount = new DWORD(0); final DWORDByReference privilegeLength = new DWORDByReference(new DWORD(privileges.size())); final DWORDByReference grantedAccess = new DWORDByReference(); final BOOLByReference result = new BOOLByReference(); final boolean status = Advapi32.INSTANCE.AccessCheck(securityDescriptorMemoryPointer, null, new DWORD(FILE_GENERIC_READ), mapping, privileges, privilegeLength, grantedAccess, result); assertFalse(status); assertFalse(result.getValue().booleanValue()); assertEquals("The handle is invalid.", Kernel32Util.formatMessage(W32Errors.HRESULT_FROM_WIN32(Kernel32.INSTANCE.GetLastError()))); }

Target:
public void testAccessCheck() { final GENERIC_MAPPING mapping = new GENERIC_MAPPING(); mapping.genericRead = new DWORD(FILE_GENERIC_READ); mapping.genericWrite = new DWORD(FILE_GENERIC_WRITE); mapping.genericExecute = new DWORD(FILE_GENERIC_EXECUTE); mapping.genericAll = new DWORD(FILE_ALL_ACCESS); final Memory securityDescriptorMemoryPointer = new Memory(1); final PRIVILEGE_SET privileges = new PRIVILEGE_SET(1); privileges.PrivilegeCount = new DWORD(0); final DWORDByReference privilegeLength = new DWORDByReference(new DWORD(privileges.size())); final DWORDByReference grantedAccess = new DWORDByReference(); final BOOLByReference result = new BOOLByReference(); final boolean status = Advapi32.INSTANCE.AccessCheck(securityDescriptorMemoryPointer, null, new DWORD(FILE_GENERIC_READ), mapping, privileges, privilegeLength, grantedAccess, result); assertFalse(status); assertFalse(result.getValue().booleanValue()); assertEquals(WinError.ERROR_INVALID_HANDLE, Kernel32.INSTANCE.GetLastError()); }
Source:
public void foreverBrickTest() throws InterpretationException { addLoopAtPosition(R.string.brick_forever, 2); checkIfBrickAtPositionShowsString(1, R.string.brick_repeat); checkIfBrickAtPositionShowsString(2, R.string.brick_forever); checkIfBrickAtPositionShowsString(3, R.string.brick_change_y_by); checkIfBrickAtPositionShowsString(4, R.string.brick_loop_end); checkIfBrickAtPositionShowsString(5, R.string.brick_loop_end); deleteBrickAtPosition(2); checkSetUpBrickArrangement(); }

Target:
public void foreverBrickTest() throws InterpretationException { addBrickAtPosition(ForeverBrick.class, 2, R.string.category_control); checkIfBrickAtPositionShowsString(1, R.string.brick_repeat); checkIfBrickAtPositionShowsString(2, R.string.brick_forever); checkIfBrickAtPositionShowsString(3, R.string.brick_change_y_by); checkIfBrickAtPositionShowsString(4, R.string.brick_loop_end); checkIfBrickAtPositionShowsString(5, R.string.brick_loop_end); deleteBrickAtPosition(2); checkSetUpBrickArrangement(); }
Source:
byte[] getByteBodyContents() { if (bytePayload != null) return bytePayload; String body = payload; if (body == null && !bodyParams.isEmpty()) { body = URLUtils.formURLEncodeMap(bodyParams); if (!this.headers.containsKey(CONTENT_TYPE)) this.addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded"); } try { return body.getBytes(getCharset()); } catch(UnsupportedEncodingException uee) { throw new OAuthException("Unsupported Charset: "+getCharset(), uee); } }

Target:
byte[] getByteBodyContents() { if (bytePayload != null) return bytePayload; String body = payload; if (body == null && !bodyParams.isEmpty()) { body = URLUtils.formURLEncodeMap(bodyParams); if (!this.headers.containsKey(CONTENT_TYPE)) this.addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded; charset=" + getCharset() + ";"); } try { return body.getBytes(getCharset()); } catch(UnsupportedEncodingException uee) { throw new OAuthException("Unsupported Charset: "+getCharset(), uee); } }
Source:
public void deleteEntity(DeleteOption deleteOption) { String selectedEntity = getSelectedEntityTitle(); LOG.info("deleteEntity {}, mode={} ...", selectedEntity, deleteOption); deleteDropdownMenu.click(); switch (deleteOption) { case DATA: deleteDataButton.click(); break; case DATA_AND_METADATA: deleteDataMetadataBtn.click(); break; default: break; } WebDriverWait wait = new WebDriverWait(driver, 60); wait.until(ExpectedConditions.elementToBeClickable(confirmButton)); confirmButton.click(); spinner().waitTillDone(20, TimeUnit.SECONDS); }

Target:
public void deleteEntity(DeleteOption deleteOption) { String selectedEntity = getSelectedEntityTitle(); LOG.info("deleteEntity {}, mode={} ...", selectedEntity, deleteOption); deleteDropdownMenu.click(); switch (deleteOption) { case DATA: deleteDataButton.click(); break; case DATA_AND_METADATA: deleteDataMetadataBtn.click(); break; default: break; } confirmButton.click(); spinner().waitTillDone(20, TimeUnit.SECONDS); }
Source:
final AsyncFunction<ResultSet, R> iterate() { return rs -> { Preconditions.checkArgument(rs != null, "ResultSet should not be null when iterating"); R currentResult = resultSetVisitor.visit(rs); boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null; if (wasLastPage) { return Futures.immediateFuture(currentResult); } else { ListenableFuture<ResultSet> future = rs.fetchMoreResults(); return Futures.transformAsync(future, iterate(), executor); } }; }

Target:
final AsyncFunction<ResultSet, R> iterate() { return resultSet -> { Preconditions.checkArgument(resultSet != null, "ResultSet should not be null when iterating"); rowStreamAccumulator.accumulateRowStream(Streams.stream(resultSet) .limit(resultSet.getAvailableWithoutFetching())); boolean wasLastPage = resultSet.getExecutionInfo().getPagingState() == null; if (wasLastPage) { return Futures.immediateFuture(rowStreamAccumulator.result()); } else { ListenableFuture<ResultSet> future = resultSet.fetchMoreResults(); return Futures.transformAsync(future, iterate(), executor); } }; }
Source:
public void shouldFindServerGivenListOfServersContainsServerWithNullType() throws CoreException { IServer os3Server = mockOS3Server("os3", "someService"); IServer[] servers = new IServer[] { mockServer("null", null), os3Server, mockServer("as7", mockServerType(IJBossToolingConstants.SERVER_AS_70)) }; IServer serverFound = OpenShiftServerUtils.findServerForService("someService", servers); assertThat(serverFound).isEqualTo(os3Server); }

Target:
public void shouldFindServerGivenListOfServersContainsServerWithNullType() throws CoreException { IServer os3Server = mockOS3Server("os3", "someService"); IServer[] servers = new IServer[] { mockServer("null", null), os3Server, mockServer("as7", mockServerType(IJBossToolingConstants.SERVER_AS_70)) }; IServer serverFound = OpenShiftServerUtils.findServerForService("someService", servers); assertThat(serverFound).isSameAs(os3Server); }
Source:
public byte[] persistToBytes() { byte[] result = new byte[] { 0, 0, 0, 0 }; result[0] |= (shard() & 0xFF) >> 2; if (dedicatedRow()) { result[0] |= 0x40; } if (conservative()) { result[0] |= 0x80; } result[1] |= dedicatedRowNumber(); result[1] |= (shard() << 6) & 0xFF; return result; }

Target:
public byte[] persistToBytes() { byte[] result = new byte[] { 0, 0, 0, 0 }; result[0] |= (shard() & BYTE_MASK) >> 2; if (dedicatedRow()) { result[0] |= USE_DEDICATED_ROWS_MASK; } if (conservative()) { result[0] |= SWEEP_STRATEGY_MASK; } result[1] |= dedicatedRowNumber() & DEDICATED_ROW_NUMBER_MASK; result[1] |= (shard() << 6) & BYTE_MASK; return result; }
Source:
private void waitForTaskReleaseOrForceIfOwnerIsDead(DatastreamTask task, long timeoutMs, String lockPath) { boolean deadOwner = false; if (_zkclient.exists(lockPath)) { String owner = _zkclient.readData(lockPath, true); if (owner != null && owner.equals(_instanceName)) { LOG.info("{} already owns the lock on {}", _instanceName, task); return; } long waitTimeout = timeoutMs; if (timeoutMs >= _debounceTimerMs) { if (_liveInstancesProvider != null && !getLiveInstances().contains(owner)) { LOG.info("dead owner found for the lock on the task {}", owner, task.getDatastreamTaskName()); deadOwner = true; } else { waitForTaskRelease(task, timeoutMs - _debounceTimerMs, lockPath); if (!_zkclient.exists(lockPath)) { return; } owner = _zkclient.readData(lockPath, true); if (owner != null && _liveInstancesProvider != null && !getLiveInstances().contains(owner)) { LOG.info("dead owner found for the lock on the task after waiting ms", owner, task.getDatastreamTaskName(), timeoutMs - _debounceTimerMs); deadOwner = true; } } waitTimeout = _debounceTimerMs; } waitForTaskRelease(task, waitTimeout, lockPath); if (deadOwner && _zkclient.exists(lockPath)) { String tempOwner = _zkclient.readData(lockPath, true); if (tempOwner != null && tempOwner.equals(owner)) { _zkclient.delete(lockPath); } } } }

Target:
private void waitForTaskReleaseOrForceIfOwnerIsDead(DatastreamTask task, long timeoutMs, String lockPath) { boolean deadOwner = false; if (_zkclient.exists(lockPath)) { String owner = _zkclient.readData(lockPath, true); long waitTimeout = timeoutMs; if (timeoutMs >= _debounceTimerMs) { if (owner != null && _liveInstancesProvider != null && !getLiveInstances().contains(owner)) { LOG.info("dead owner found for the lock on the task {}", owner, task.getDatastreamTaskName()); deadOwner = true; } else { waitForTaskRelease(task, timeoutMs - _debounceTimerMs, lockPath); if (!_zkclient.exists(lockPath)) { return; } owner = _zkclient.readData(lockPath, true); if (owner != null && _liveInstancesProvider != null && !getLiveInstances().contains(owner)) { LOG.info("dead owner found for the lock on the task after waiting ms", owner, task.getDatastreamTaskName(), timeoutMs - _debounceTimerMs); deadOwner = true; } } waitTimeout = _debounceTimerMs; } waitForTaskRelease(task, waitTimeout, lockPath); if (deadOwner && _zkclient.exists(lockPath)) { String tempOwner = _zkclient.readData(lockPath, true); if (tempOwner != null && tempOwner.equals(owner)) { _zkclient.delete(lockPath); } else { LOG.warn("Not deleting the lock for the task since the owner changed from dead owner to {}.", task.getDatastreamTaskName(), owner, tempOwner); } } } }
Source:
public void acquirePartitionLockLazily() throws IOException { if (partitionKeyLock != null) { return; } Object partitionKey = getPartitionKey(); channelManager.acquireChannelLock(partitionKey); Object prevKey = partitionKeyLockField.getAndSet(this, partitionKey); if (prevKey != null) { channelManager.releaseChannelLock(prevKey); releasePartitionKeyLock(); throw new AssertionError("unreachable"); } if (isDone()) { releasePartitionKeyLock(); } }

Target:
public void acquirePartitionLockLazily() throws IOException { if (partitionKeyLock != null) { return; } Object partitionKey = getPartitionKey(); connectionSemaphore.acquireChannelLock(partitionKey); Object prevKey = partitionKeyLockField.getAndSet(this, partitionKey); if (prevKey != null) { connectionSemaphore.releaseChannelLock(prevKey); releasePartitionKeyLock(); throw new IllegalStateException("Trying to acquire partition lock concurrently. Please report."); } if (isDone()) { releasePartitionKeyLock(); } }
Source:
public Status getStatusHTTP(@Context final HttpServletRequest req) { Access access = authorizationCheck(req, Action.READ); if (!access.isAllowed()) { log.warn("Authorization failure."); return null; } return status; }

Target:
public Status getStatusHTTP(@Context final HttpServletRequest req) { authorizationCheck(req, Action.READ); return status; }
Source:
public SecretCreateResponse createSecret(final SecretSpec secret) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.25"); final WebTarget resource = resource().path("secrets").path("create"); try { return request(POST, SecretCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(secret)); } catch (DockerRequestException dre) { switch (dre.status()) { case 409: throw new DockerException("Name conflicts with an existing object.", dre); case 503: throw new DockerException("Server not part of swarm.", dre); default: throw dre; } } }

Target:
public SecretCreateResponse createSecret(final SecretSpec secret) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.25"); final WebTarget resource = resource().path("secrets").path("create"); try { return request(POST, SecretCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.json(secret)); } catch (DockerRequestException dre) { switch (dre.status()) { case 406: throw new DockerException("Server not part of swarm.", dre); case 409: throw new ConflictException("Name conflicts with an existing object.", dre); default: throw dre; } } }
Source:
public void testBeforeNoTimezone() throws IOException { BundleFilterTimeRange filter1 = Configs.decodeObject(BundleFilterTimeRange.class, BEFORE_160923); BundleFilterTimeRange filter2 = Configs.decodeObject(BundleFilterTimeRange.class, BEFORE_150925); assertTrue("Expected true since filtered out later than 160923", filter1.filter(bundle)); assertFalse("Expected false since filtered out later than 150925", filter2.filter(bundle)); }

Target:
public void testBeforeNoTimezone() throws IOException { BundleFilterTimeRange filter1 = Configs.decodeObject(BundleFilterTimeRange.class, BEFORE_160923); BundleFilterTimeRange filter2 = Configs.decodeObject(BundleFilterTimeRange.class, BEFORE_150925); assertTrue("Expected true since 160922 is earlier than 160923", filter1.filter(bundle)); assertFalse("Expected false since 160922 is later than 150925", filter2.filter(bundle)); }
Source:
public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { String result; BaseProperty prop = (BaseProperty) object.safeget(name); if (prop != null) { result = prop.toText(); } else { result = ""; } buffer.append(context.getDoc().getRenderedInlineContent(result, context.getDoc().getSyntax().toIdString())); }

Target:
public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { BaseProperty property = (BaseProperty) object.safeget(name); if (property != null) { buffer.append(XMLUtils.escapeElementText(property.toText())); } }
Source:
private void loadUsers() { int i = 0; File[] path = usersFolderFile.listFiles(); if (path != null) { for (File file : path) { if (file.isDirectory() || file.length() == 0) { file.delete(); i++; continue; } if (!FunnyGuilds.USERNAME_PATTERN.matcher(StringUtils.removeEnd(file.getName(), ".yml")).matches()) { FunnyGuilds.getInstance().getPluginLogger().warning("Skipping loading of user file '" + file.getName() + "'. Name is invalid."); continue; } User user = FlatUser.deserialize(file); if (user == null) { file.delete(); i++; } else { user.wasChanged(); } } } if (i > 0) { FunnyGuilds.getInstance().getPluginLogger().warning("Repaired conflicts: " + i); } FunnyGuilds.getInstance().getPluginLogger().info("Loaded users: " + UserUtils.getUsers().size()); }

Target:
private void loadUsers() { int i = 0; File[] path = usersFolderFile.listFiles(); if (path != null) { for (File file : path) { if (file.isDirectory() || file.length() == 0) { file.delete(); i++; continue; } if (!UserUtils.validateUsername(StringUtils.removeEnd(file.getName(), ".yml"))) { FunnyGuilds.getInstance().getPluginLogger().warning("Skipping loading of user file '" + file.getName() + "'. Name is invalid."); continue; } User user = FlatUser.deserialize(file); if (user == null) { file.delete(); i++; } else { user.wasChanged(); } } } if (i > 0) { FunnyGuilds.getInstance().getPluginLogger().warning("Repaired conflicts: " + i); } FunnyGuilds.getInstance().getPluginLogger().info("Loaded users: " + UserUtils.getUsers().size()); }
Source:
Resource getConfigFile(String configFileLocation ) throws IOException { File file = new File(configFileLocation); Resource resource; if( file.isAbsolute() ){ if( file.canRead() ){ return Files.asResource(file); } else { throw new IOException("Cannot read file: "+file.getCanonicalPath()); } } return null; }

Target:
Resource getConfigFile(String configFileLocation) throws IOException { File file = new File(configFileLocation); if (file.isAbsolute()) { if (file.canRead()) { return Files.asResource(file); } else { throw new IOException("Cannot read file: " + file.getCanonicalPath()); } } return null; }
Source:
public LRUCache(int capacity) { this.capacity = capacity; count = 0; map = new HashMap<>(); head = new DoubleLinkedList(0, 0); tail = new DoubleLinkedList(0, 0); head.next = tail; tail.pre = head; head.pre = null; tail.next = null; }

Target:
public LRUCache(int capacity) { this.capacity = capacity; count = 0; head = new DoubleLinkedList(0, 0); tail = new DoubleLinkedList(0, 0); head.next = tail; tail.pre = head; head.pre = null; tail.next = null; }
Source:
private String expectedDiff() { return extractDiff(expected); }

Target:
public String expectedDiff() { return extractDiff(expected); }
Source:
public void run() { try { currentInterval = intervalQueue.take(); while (currentInterval.getStartTime() != -1) { getSHT().insertInterval(currentInterval); currentInterval = intervalQueue.take(); } if (currentInterval.getAttribute() != -1) { throw new IllegalStateException(); } getSHT().closeTree(currentInterval.getEndTime()); return; } catch (TimeRangeException e) { Activator.getDefault().logError("Error starting the state system", e); } }

Target:
public void run() { try { intervalQueue.takeIntoAtomicReference(currentInterval); HTInterval interval = currentInterval.get(); while (interval.getStartTime() != -1) { getSHT().insertInterval(interval); intervalQueue.takeIntoAtomicReference(currentInterval); interval = currentInterval.get(); } if (interval.getAttribute() != -1) { throw new IllegalStateException(); } getSHT().closeTree(interval.getEndTime()); return; } catch (TimeRangeException e) { Activator.getDefault().logError("Error starting the state system", e); } }
Source:
public void indexReturnsAllEventsWhenNoParameters(EventsInteractor mockedEventsInteractor) { Result result = eventsController.index(); assertEquals(Helpers.OK, Helpers.status(result)); assertEquals("application/json", Helpers.contentType(result)); String json = Helpers.contentAsString(result); JsonNode jsonNode = Json.parse(json); assertTrue(jsonNode.isArray()); JsonNode eventDto1 = jsonNode.get(0); JsonNode eventDto2 = jsonNode.get(1); JsonNode event1 = eventDto1.get("event"); JsonNode event2 = eventDto2.get("event"); assertEquals(tempEventsList.size(), jsonNode.size()); assertEquals(FIRST_EVENT_ID, event1.get("id").asLong()); assertEquals(EventsTestHelper.FIRST_RANDOM_SPORT, event1.get("sport").get("name").asText()); assertEquals(SECOND_EVENT_ID, event2.get("id").asLong()); assertEquals(EventsTestHelper.SECOND_RANDOM_SPORT, event2.get("sport").get("name").asText()); verify(mockedEventsInteractor).search(refEq(eventSearchCriteria)); }

Target:
public void indexReturnsAllEventsWhenNoParameters(EventsInteractor mockedEventsInteractor) { Result result = eventsController.index(); assertEquals(Helpers.OK, Helpers.status(result)); assertEquals("application/json", Helpers.contentType(result)); String json = Helpers.contentAsString(result); JsonNode jsonNode = Json.parse(json); assertTrue(jsonNode.isArray()); JsonNode eventDto1 = jsonNode.get(0); JsonNode eventDto2 = jsonNode.get(1); JsonNode event1 = eventDto1.get("event"); JsonNode event2 = eventDto2.get("event"); assertEquals(tempEventsList.size(), jsonNode.size()); assertEquals(NUMBER_OF_TICKETS, eventDto1.get("ticketCount").getIntValue()); assertEquals(FIRST_EVENT_ID, event1.get("id").getLongValue()); assertEquals(EventsTestHelper.FIRST_RANDOM_SPORT, event1.get("sport").get("name").asText()); assertEquals(NUMBER_OF_TICKETS, eventDto2.get("ticketCount").getIntValue()); assertEquals(SECOND_EVENT_ID, event2.get("id").getLongValue()); assertEquals(EventsTestHelper.SECOND_RANDOM_SPORT, event2.get("sport").get("name").asText()); verify(mockedEventsInteractor).search(refEq(eventSearchCriteria)); }
Source:
public boolean copyNonEditableFieldsToDestination(Object source, Object destination, boolean hotsetEnabled) { Class<?> cls = source.getClass(); while (!cls.equals(Object.class)) { for (Field srcFld : cls.getDeclaredFields()) { try { if (!Modifier.isFinal(srcFld.getModifiers()) && !IsFieldUpdatable(srcFld.getName()) && (!isHotsetField(srcFld.getName()) || (isHotsetField(srcFld.getName()) && !hotsetEnabled))) { srcFld.setAccessible(true); Field dstFld = cls.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(destination, srcFld.get(source)); } } catch (Exception exp) { log.errorFormat("Failed to copy non editable field {0}, error: {1}", srcFld.getName(), exp.getMessage()); return false; } } cls = cls.getSuperclass(); } return true; }

Target:
public boolean copyNonEditableFieldsToDestination(Object source, Object destination, boolean hotsetEnabled) { Class<?> cls = source.getClass(); while (!cls.equals(Object.class)) { for (Field srcFld : cls.getDeclaredFields()) { try { if (!Modifier.isFinal(srcFld.getModifiers()) && !IsFieldUpdatable(srcFld.getName()) && (!isHotsetField(srcFld.getName()) || !hotsetEnabled)) { srcFld.setAccessible(true); Field dstFld = cls.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(destination, srcFld.get(source)); } } catch (Exception exp) { log.errorFormat("Failed to copy non editable field {0}, error: {1}", srcFld.getName(), exp.getMessage()); return false; } } cls = cls.getSuperclass(); } return true; }
Source:
private byte[] handleInputReadSiMessage(byte[] message, byte[] messageNumber) { byte[] reply = null; replyRequired = true; boolean msgValid = true; int port = -1; if (!isMessageLengthValid(message, 11)) { msgValid = false; } else { port = message[7]; } if (!msgValid) { reply = new byte[3]; reply[0] = messageNumber[0]; reply[1] = messageNumber[1]; reply[2] = DIRECT_REPLY_ERROR; } else { portSensorMode[port] = message[9]; if (message[3] == 1) { reply = new byte[4]; } else if (message[3] == 4) { reply = new byte[7]; } else { throw new MindstormsException("read siValue with unusual length"); } reply[0] = messageNumber[0]; reply[1] = messageNumber[1]; reply[2] = DIRECT_REPLY; if (message[3] == 1) { byte value = (byte) portSensorValue[port]; reply[3] = value; } else if (message[3] == 4) { byte[] floatValueAsByte = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(portSensorValue[port]).array(); for (int i = 0; i < floatValueAsByte.length; i++) { reply[3 + i] = floatValueAsByte[i]; } } } return reply; }

Target:
private byte[] handleInputReadSiMessage(byte[] message, byte[] messageNumber) { byte[] reply = null; replyRequired = true; boolean msgValid = true; int port = -1; if (!isMessageLengthValid(message, 11)) { msgValid = false; } else { port = message[7]; } if (!msgValid) { reply = new byte[3]; reply[0] = messageNumber[0]; reply[1] = messageNumber[1]; reply[2] = DIRECT_REPLY_ERROR; } else { portSensorMode[port] = message[9]; if (message[3] == 1) { reply = new byte[4]; byte value = (byte) portSensorValue[port]; reply[3] = value; } else if (message[3] == 4) { reply = new byte[7]; byte[] floatValueAsByte = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(portSensorValue[port]).array(); for (int i = 0; i < floatValueAsByte.length; i++) { reply[3 + i] = floatValueAsByte[i]; } } else { throw new MindstormsException("read siValue with unusual length"); } reply[0] = messageNumber[0]; reply[1] = messageNumber[1]; reply[2] = DIRECT_REPLY; } return reply; }