auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void resizeWindow(Object drone, InjectionPoint<?> injectionPoint) { if (!WebDriver.class.isAssignableFrom(drone.getClass())) { return; } DroneContext context = droneContext.get(); WebDriver driver = (WebDriver) drone; Validate.stateNotNull(context, "DroneContext must not be null"); WebDriverConfiguration configuration = context.getDroneConfiguration(injectionPoint, WebDriverConfiguration .class); Validate.stateNotNull(configuration, "WebDriver configuration mus null"); String dimensions = configuration.getDimensions(); if (dimensions != null) { Matcher m = DIMENSIONS_PATTERN.matcher(dimensions); if (m.matches()) { int width = Integer.valueOf(m.group(1)); int height = Integer.valueOf(m.group(2)); safelyResizeWindow(driver, width, height, injectionPoint); } } }

Target:
private void resizeWindow(Object drone, InjectionPoint<?> injectionPoint) { if (!WebDriver.class.isAssignableFrom(drone.getClass())) { return; } DroneContext context = droneContext.get(); WebDriver driver = (WebDriver) drone; Validate.stateNotNull(context, "DroneContext must not be null"); WebDriverConfiguration configuration = context.getDroneConfiguration(injectionPoint, WebDriverConfiguration .class); Validate.stateNotNull(configuration, "WebDriver configuration must not be null"); String dimensions = configuration.getDimensions(); if (dimensions != null) { Matcher m = DIMENSIONS_PATTERN.matcher(dimensions); if (m.matches()) { int width = Integer.valueOf(m.group(1)); int height = Integer.valueOf(m.group(2)); safelyResizeWindow(driver, width, height, injectionPoint); } } }
Source:
public void execute(ClusterEvent event) { Map<String, WorkflowConfig> workflowConfigMap = event.getAttribute(AttributeName.WORKFLOW_CONFIG_MAP.name()); Map<String, ZNRecord> resourceContextMap = event.getAttribute(AttributeName.RESOURCE_CONTEXT_MAP.name()); HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); if (manager == null) { LOG.warn( " HelixManager is null for event {}({}) in cluster {}. Skip TaskGarbageCollectionStage.", event.getEventId(), event.getEventType(), event.getClusterName()); return; } Set<WorkflowConfig> existingWorkflows = new HashSet<>(workflowConfigMap.values()); for (WorkflowConfig workflowConfig : existingWorkflows) { if (workflowConfig != null && (!workflowConfig.isTerminable() || workflowConfig .isJobQueue())) { String workflowId = workflowConfig.getWorkflowId(); if (resourceContextMap.containsKey(workflowId) && resourceContextMap.get(workflowId) != null) { try { TaskUtil.purgeExpiredJobs(workflowId, workflowConfig, new WorkflowContext(resourceContextMap.get(workflowId)), manager, _rebalanceScheduler); } catch (Exception e) { LOG.warn(String.format("Failed to purge job for workflow %s with reason %s", workflowId, e.toString())); } } else { LOG.warn(String.format("Workflow %s context does not exist!", workflowId)); } } } TaskUtil.workflowGarbageCollection(workflowConfigMap, resourceContextMap, manager); }

Target:
public void execute(ClusterEvent event) { HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); if (manager == null) { LOG.warn( "HelixManager is null for event {}({}) in cluster {}. Skip TaskGarbageCollectionStage async execution.", event.getEventId(), event.getEventType(), event.getClusterName()); return; } Map<String, Set<String>> expiredJobsMap = event.getAttribute(AttributeName.TO_BE_PURGED_JOBS_MAP.name()); Set<String> toBePurgedWorkflows = event.getAttribute(AttributeName.TO_BE_PURGED_WORKFLOWS.name()); for (Map.Entry<String, Set<String>> entry : expiredJobsMap.entrySet()) { try { TaskUtil.purgeExpiredJobs(entry.getKey(), entry.getValue(), manager, _rebalanceScheduler); } catch (Exception e) { LOG.warn("Failed to purge job for workflow {}!", entry.getKey(), e); } } TaskUtil.workflowGarbageCollection(toBePurgedWorkflows, manager); }
Source:
private Object extractValue(DataValue value) throws IllegalArgumentException { Variant variant = value.getValue(); if (variant == null) { throw new NoSuchElementException(message.errorNullResult()); } Object result = variant.getValue(); if (result == null) { throw new NoSuchElementException(message.errorNullResult()); } return result; }

Target:
private Object extractValue(DataValue value) throws IllegalArgumentException { Variant variant = value.getValue(); if (variant == null) { throw new NullPointerException(message.errorNullResult()); } Object result = variant.getValue(); if (result == null) { throw new NullPointerException(message.errorNullResult()); } return result; }
Source:
public void mark() throws PublisherException { marked.add(current); if (marked.size() > markCapacity) { Node n = marked.remove(0); n.decrement(); } }

Target:
public void mark() throws PublisherException { if (current.data.push != null) { if (marked.size() >= markCapacity) { Data data = marked.removeLast(); data.decrement(); } marked.addFirst(current.data); current = new ForwardingNode(Data.EMPTY, current); } }
Source:
public void test_CreateJobFromPreset() throws Exception { String jobName = String.format("projects/%s/locations/%s/jobs/", PROJECT_NUMBER, LOCATION); try { CreateJobFromPreset.createJobFromPreset( PROJECT_ID, LOCATION, INPUT_URI, OUTPUT_URI_FOR_PRESET, PRESET); } catch (GoogleJsonResponseException gjre) { } String output = bout.toString(); assertThat(output, containsString(jobName)); String[] arr = output.split("/"); JOB_ID = arr[arr.length - 1].replace("\n", ""); bout.reset(); Thread.sleep(60000); try { GetJobState.getJobState(PROJECT_ID, LOCATION, JOB_ID); } catch (GoogleJsonResponseException gjre) { } output = bout.toString(); assertThat(output, containsString("SUCCEEDED")); bout.reset(); }

Target:
public void test_CreateJobFromPreset() throws Exception { String jobName = String.format("projects/%s/locations/%s/jobs/", PROJECT_NUMBER, LOCATION); CreateJobFromPreset.createJobFromPreset( PROJECT_ID, LOCATION, INPUT_URI, OUTPUT_URI_FOR_PRESET, PRESET); String output = bout.toString(); assertThat(output, containsString(jobName)); String[] arr = output.split("/"); JOB_ID = arr[arr.length - 1].replace("\n", ""); bout.reset(); Thread.sleep(60000); GetJobState.getJobState(PROJECT_ID, LOCATION, JOB_ID); output = bout.toString(); assertThat(output, containsString("SUCCEEDED")); bout.reset(); }
Source:
public void doAfterTest() throws Exception { super.doAfterTest(); if (fServicesTracker != null) fServicesTracker.dispose(); }

Target:
public void doAfterTest() throws Exception { super.doAfterTest(); if (fServicesTracker != null) { fServicesTracker.dispose(); } }
Source:
public static ListWidgetEntry<ContainerDTO> create(ContainerDTO container) { Optional<URI> shortcutMiniature = Optional.empty(); final List<BufferedImage> miniatures = new ArrayList<>(); final int maxSegments = 4; int currentSegment = 0; for (ShortcutDTO shortcutDTO : container.getInstalledShortcuts()) { if (currentSegment >= maxSegments) { break; } try { miniatures.add(ImageIO.read(shortcutDTO.getMiniature().toURL())); currentSegment++; } catch (IOException e) { LOGGER.warn(String.format("Could not read miniature for shortcut \"%s\"", shortcutDTO.getName()), e); } } if (!miniatures.isEmpty()) { final int width = miniatures.get(0).getWidth(); final int height = miniatures.get(0).getHeight(); BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final int numberOfSegments = miniatures.size(); final int segmentWidth = width / numberOfSegments; final int offset = (width - segmentWidth) / 2; final List<BufferedImage> segments = new ArrayList<>(); miniatures.forEach( miniature -> segments.add(miniature.getSubimage(offset, 0, offset + segmentWidth, height))); Graphics2D graphics = result.createGraphics(); for (int i = 0; i < segments.size(); i++) { graphics.drawImage(segments.get(i), 0 + i * segmentWidth, 0, null); } try { final Path temp = Files.createTempFile(container.getName(), ".png").toAbsolutePath(); final File tempFile = temp.toFile(); tempFile.deleteOnExit(); ImageIO.write(result, "png", tempFile); shortcutMiniature = Optional.of(temp.toUri()); } catch (IOException e) { LOGGER.warn( String.format("Could not create container miniature for container \"%s\"", container.getName()), e); } } return new ListWidgetEntry<>(container, shortcutMiniature, StaticMiniature.CONTAINER_MINIATURE, container.getName(), Optional.empty(), Optional.empty()); }

Target:
public static ListWidgetEntry<ContainerDTO> create(ContainerDTO container) { final List<BufferedImage> miniatures = new ArrayList<>(); final int maxSegments = 4; int currentSegment = 0; for (ShortcutDTO shortcutDTO : container.getInstalledShortcuts()) { if (currentSegment >= maxSegments) { break; } try { miniatures.add(ImageIO.read(shortcutDTO.getMiniature().toURL())); currentSegment++; } catch (IOException e) { LOGGER.warn(String.format("Could not read miniature for shortcut \"%s\"", shortcutDTO.getName()), e); } } final BufferedImage segmentedMiniature = createSegmentedMiniature(miniatures); final Optional<URI> shortcutMiniature = saveBufferedImage(segmentedMiniature, container.getName()); return new ListWidgetEntry<>(container, shortcutMiniature, StaticMiniature.CONTAINER_MINIATURE, container.getName(), Optional.empty(), Optional.empty()); }
Source:
public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (! cqTailer.moveToIndex(offset)) { log.warn("Unable to move to the last committed offset, " + this); } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }

Target:
public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (!cqTailer.moveToIndex(offset) && cqTailer.index() != offset) { throw new IllegalStateException( "Unable to move to the last committed offset, " + this + " offset: " + offset); } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }
Source:
public static AzureADToken getTokenFromMsi(final String authEndpoint, final String tenantGuid, final String clientId, String authority, boolean bypassCache) throws IOException { QueryParams qp = new QueryParams(); qp.add("api-version", "2018-02-01"); qp.add("resource", RESOURCE_NAME); if (tenantGuid != null && tenantGuid.length() > 0) { authority = authority + tenantGuid; qp.add("authority", authority); } if (clientId != null && clientId.length() > 0) { qp.add("client_id", clientId); } if (bypassCache) { qp.add("bypass_cache", "true"); } Hashtable<String, String> headers = new Hashtable<>(); headers.put("Metadata", "true"); LOG.debug("AADToken: starting to fetch token using MSI"); return getTokenCall(authEndpoint, qp.serialize(), headers, "GET"); }

Target:
public static AzureADToken getTokenFromMsi(final String authEndpoint, final String tenantGuid, final String clientId, String authority, boolean bypassCache) throws IOException { QueryParams qp = new QueryParams(); qp.add("api-version", "2018-02-01"); qp.add("resource", RESOURCE_NAME); if (tenantGuid != null && tenantGuid.length() > 0) { authority = authority + tenantGuid; LOG.debug("MSI authority : {}", authority); qp.add("authority", authority); } if (clientId != null && clientId.length() > 0) { qp.add("client_id", clientId); } if (bypassCache) { qp.add("bypass_cache", "true"); } Hashtable<String, String> headers = new Hashtable<>(); headers.put("Metadata", "true"); LOG.debug("AADToken: starting to fetch token using MSI"); return getTokenCall(authEndpoint, qp.serialize(), headers, "GET"); }
Source:
public void setPhoto(Bitmap image) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream .toByteArray(); photo = android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT); }

Target:
public void setPhoto(Bitmap image) { byte[] byteArray = bitmapToByteArray(image); base64EncodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT); }
Source:
private Map<String, String> getParameters(IMethodInstance im) { Map<String, String> params = m_xmlTest.getAllParameters(); Class<?> c = im.getMethod().getTestClass().getRealClass(); XmlClass xmlClass = m_xmlTest.getXmlClass(c); if (xmlClass != null) { params.putAll(xmlClass.getAllParameters()); } return params; }

Target:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); return im.getMethod().findMethodParameters(xmlTest); }
Source:
public void flush() throws IOException { if (outputStream != null) outputStream.flush(); }

Target:
public void flush() throws IOException { if (outputStream != null) { outputStream.flush(); } }
Source:
private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d > 0) { point += roundSeconds - d; if (point == Cell.MAX_DELETION_TIME) point = Cell.MAX_DELETION_TIME; else if (point < 0) return Cell.MAX_DELETION_TIME; return point; } else return point; }

Target:
private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d == 0) return point; point += roundSeconds - d; if (point > Cell.MAX_DELETION_TIME) return Cell.MAX_DELETION_TIME; else if (point < 0) return Cell.MAX_DELETION_TIME; return point; }
Source:
default Multimap<CallStackDepth, ICalledFunction> queryCallStacks(Collection<CallStackDepth> collection, Collection<Long> times) { CallStackSeries callStackSeries = getCallStackSeries(); if (callStackSeries == null) { return ArrayListMultimap.create(); } return callStackSeries.queryCallStacks(collection, times); }

Target:
default Multimap<CallStackDepth, ISegment> queryCallStacks(Collection<CallStackDepth> collection, Collection<Long> times) { CallStackSeries callStackSeries = getCallStackSeries(); if (callStackSeries == null) { return Objects.requireNonNull(ArrayListMultimap.create()); } return callStackSeries.queryCallStacks(collection, times); }
Source:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username); }

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username) .append("origintype", originType); }
Source:
private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) .map(colMet -> { return newColumnMeta(colMet.getCaption(), true); }).collect(Collectors.toList()); }

Target:
private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) .map(colMet -> newColumnMeta(colMet.getCaption(), true, false) ).collect(Collectors.toList()); }
Source:
public Map<String, Ref> getRefs(String prefix) throws IOException { Map<String, Ref> out; synchronized (cacheLock) { scanPackedRefs(); if (prefix.equals(ALL)) { scanLooseRefs(R_REFS, refsDir); scanRef(HEAD); } else if (prefix.startsWith(R_REFS)) { String name = prefix.substring(R_REFS.length()); scanLooseRefs(prefix, new File(refsDir, name)); } out = new HashMap<String, Ref>(Math.max(cache.size() * 2, 16)); for (RefHolder holder : cache.values()) { Ref ref = holder.currRef; if (ref.getName().startsWith(prefix)) { ref = resolve(ref, 0, prefix); if (ref != null && ref.getObjectId() != null) out.put(ref.getName().substring(prefix.length()), ref); } } } fireRefsChanged(); return out; }

Target:
public Map<String, Ref> getRefs(String prefix) throws IOException { final RefList<Ref> packed = getPackedRefs(); final RefList<LooseRef> oldLoose = looseRefs.get(); LooseScanner scan = new LooseScanner(oldLoose); scan.scan(prefix); RefList<LooseRef> loose; if (scan.newLoose != null) { loose = scan.newLoose.toRefList(); if (looseRefs.compareAndSet(oldLoose, loose)) modCnt.incrementAndGet(); } else loose = oldLoose; fireRefsChanged(); RefList.Builder<Ref> symbolic = scan.symbolic; for (int idx = 0; idx < symbolic.size();) { Ref ref = symbolic.get(idx); ref = resolve(ref, 0, prefix, loose, packed); if (ref != null && ref.getObjectId() != null) { symbolic.set(idx, ref); idx++; } else { loose = loose.remove(idx); symbolic.remove(idx); } } return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList()); }
Source:
protected void updateBlobTtl(final String blobIdStr, final String serviceId, long expiresAtMs, FutureResult<Void> futureResult, Callback<Void> callback) { Callback<GetBlobResultInternal> internalCallback = (GetBlobResultInternal result, Exception exception) -> { List<String> blobIdStrs = new ArrayList<>(); blobIdStrs.add(blobIdStr); if (exception != null) { completeOperation(futureResult, callback, null, exception, false); } else if (result.getBlobResult != null) { exception = new RouterException("Unexpected result returned by GET operation before TTL update", RouterErrorCode.UnexpectedInternalError); completeOperation(futureResult, callback, null, exception, false); } else if (result.storeKeys != null) { result.storeKeys.forEach(key -> blobIdStrs.add(key.getID())); } try { currentOperationsCount.addAndGet(blobIdStrs.size()); ttlUpdateManager.submitTtlUpdateOperation(blobIdStrs, serviceId, expiresAtMs, futureResult, callback); routerCallback.onPollReady(); } catch (RouterException e) { currentOperationsCount.addAndGet(1 - blobIdStrs.size()); completeUpdateBlobTtlOperation(e, futureResult, callback); } }; GetBlobOptionsInternal options = new GetBlobOptionsInternal(new GetBlobOptions(GetBlobOptions.OperationType.All, GetOption.None, null), true, routerMetrics.ageAtTtlUpdate); try { getBlob(blobIdStr, options, internalCallback); } catch (RouterException e) { completeUpdateBlobTtlOperation(e, futureResult, callback); } }

Target:
protected void updateBlobTtl(final String blobIdStr, final String serviceId, long expiresAtMs, FutureResult<Void> futureResult, Callback<Void> callback) { Callback<GetBlobResultInternal> internalCallback = (GetBlobResultInternal result, Exception exception) -> { List<String> blobIdStrs = new ArrayList<>(); blobIdStrs.add(blobIdStr); if (exception != null) { completeOperation(futureResult, callback, null, exception, false); } else if (result.getBlobResult != null) { exception = new RouterException("GET blob call returned the blob instead of just the store keys (before TTL update)", RouterErrorCode.UnexpectedInternalError); completeOperation(futureResult, callback, null, exception, false); } else if (result.storeKeys != null) { result.storeKeys.forEach(key -> blobIdStrs.add(key.getID())); } try { currentOperationsCount.addAndGet(blobIdStrs.size()); ttlUpdateManager.submitTtlUpdateOperation(blobIdStrs, serviceId, expiresAtMs, futureResult, callback); routerCallback.onPollReady(); } catch (RouterException e) { currentOperationsCount.addAndGet(1 - blobIdStrs.size()); completeUpdateBlobTtlOperation(e, futureResult, callback); } }; GetBlobOptionsInternal options = new GetBlobOptionsInternal(new GetBlobOptions(GetBlobOptions.OperationType.All, GetOption.None, null), true, routerMetrics.ageAtTtlUpdate); try { getBlob(blobIdStr, options, internalCallback); } catch (RouterException e) { completeUpdateBlobTtlOperation(e, futureResult, callback); } }
Source:
public String toString() { try { return "LargeServerMessage[messageID=" + messageID + ",durable=" + isDurable() + ",userID=" + getUserID() + ",priority=" + this.getPriority() + ", timestamp=" + toDate(getTimestamp()) + ",expiration=" + toDate(getExpiration()) + ", durable=" + durable + ", address=" + getAddress() + ",size=" + getPersistentSize(true) + ",properties=" + (properties != null ? properties.toString() : "") + "]@" + System.identityHashCode(this); } catch (Exception e) { e.printStackTrace(); return "LargeServerMessage[messageID=" + messageID + "]"; } }

Target:
public String toString() { try { return "LargeServerMessage[messageID=" + messageID + ",durable=" + isDurable() + ",userID=" + getUserID() + ",priority=" + this.getPriority() + ", timestamp=" + toDate(getTimestamp()) + ",expiration=" + toDate(getExpiration()) + ", durable=" + durable + ", address=" + getAddress() + ", properties=" + (properties != null ? properties.toString() : "") + "]@" + System.identityHashCode(this); } catch (Exception e) { e.printStackTrace(); return "LargeServerMessage[messageID=" + messageID + "]"; } }
Source:
public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) { Object request = requestContext.getLocalAttr(ORIGINAL_REQUEST); if (request instanceof RestRequest) { if (_darkClusterVerifier.isEnabled()) { _executorService.execute(() -> _darkClusterVerifier.onResponse((RestRequest) request, ResponseImpl.success(res))); } } nextFilter.onResponse(res, requestContext, wireAttrs); }

Target:
public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) { Object request = requestContext.getLocalAttr(ORIGINAL_REQUEST_KEY); if (request instanceof RestRequest) { _darkClusterVerifierManager.onResponse((RestRequest) request, res); } nextFilter.onResponse(res, requestContext, wireAttrs); }
Source:
public void testTryFill() throws Exception { try (final ServerSocket socket = new ServerSocket(0)) { final ForkJoinTask<?> forked = ForkJoinTask.adapt(() -> { try { socket.setSoTimeout(1000); socket.accept().getOutputStream().write(1); } catch (Exception e) { throw new RuntimeException(e); } }).fork(); try (SocketChannel channel = SocketChannel.open()) { channel.configureBlocking(false); channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), socket.getLocalPort())); TimeoutTask.attempt(t -> channel.finishConnect(), 100, 1); final ByteBuffer buffer = ByteBuffer.allocate(1); SingleInstanceManager.tryFill(channel, buffer, 100); assertFalse(buffer.hasRemaining()); } forked.join(); } }

Target:
public void testTryFill() throws Exception { try (final ServerSocket socket = new ServerSocket(0)) { final ForkJoinTask<?> forked = ForkJoinTask.adapt(() -> { try { socket.setSoTimeout(1000); socket.accept().getOutputStream().write(1); } catch (Exception e) { throw new RuntimeException(e); } }).fork(); try (SocketChannel channel = SocketChannel.open()) { channel.configureBlocking(false); channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), socket.getLocalPort())); TimeoutTask.attempt(t -> channel.finishConnect(), 1000, 1); final ByteBuffer buffer = ByteBuffer.allocate(1); SingleInstanceManager.tryFill(channel, buffer, 1000); assertFalse(buffer.hasRemaining()); } forked.join(); } }
Source:
private Function<String, Object> getMapperFunction(final VCFHeaderLineType genValType) { if (genValType == VCFHeaderLineType.Integer) { return Integer::parseInt; } if (genValType == VCFHeaderLineType.Float) { return Double::parseDouble; } return x -> x.charAt(0); }

Target:
private Function<String, Object> getMapperFunction(final VCFHeaderLineType genValType) { switch(genValType){ case String: return x -> x; case Integer: return Integer::parseInt; case Float: return Double::parseDouble; case Character: return x -> x.charAt(0); default: throw new IllegalArgumentException("Unknown type of genotype field's value(s)"); } }
Source:
public void testOrConstraint() { final String drl = "import org.drools.testcoverage.common.model.Employee;\n" + "import org.drools.testcoverage.common.model.Address;\n" + "global java.util.List list\n" + "\n" + "rule R when\n" + " $emp: Employee( $address: /address{ street == 'Elm' || city == 'Big City' } )\n" + " Employee( this != $emp, /address{ street == 'Elm' || city == 'Big City' } )\n" + "then\n" + " list.add( $address.getCity() );\n" + "end\n"; final KieBase kieBase = KieBaseUtil.getKieBaseFromDRLResources(true, KIE_SERVICES.getResources().newByteArrayResource(drl.getBytes())); this.kieSession = kieBase.newKieSession(); final List<String> list = new ArrayList<String>(); this.kieSession.setGlobal("list", list); final Address addressOfBruno = new Address("Elm", 10, "Small City"); final Employee bruno = new Employee("Bruno"); bruno.setAddress(addressOfBruno); final Address addressOfAlice = new Address("Elm", 10, "Big City"); final Employee alice = new Employee("Alice"); alice.setAddress(addressOfAlice); this.kieSession.insert(bruno); this.kieSession.insert(alice); this.kieSession.fireAllRules(); Assertions.assertThat(list).containsExactlyInAnyOrder("Big City", "Small City"); }

Target:
public void testOrConstraint() { final String drl = "import org.drools.testcoverage.common.model.Employee;\n" + "import org.drools.testcoverage.common.model.Address;\n" + "global java.util.List list\n" + "\n" + "rule R when\n" + " $emp: Employee( $address: /address{ street == 'Elm' || city == 'Big City' } )\n" + " Employee( this != $emp, /address{ street == 'Elm' || city == 'Big City' } )\n" + "then\n" + " list.add( $address.getCity() );\n" + "end\n"; final KieBase kieBase = KieBaseUtil.getKieBaseFromDRLResources(true, KIE_SERVICES.getResources().newByteArrayResource(drl.getBytes())); this.initKieSession(kieBase); this.kieSession.fireAllRules(); Assertions.assertThat(this.results).containsExactlyInAnyOrder("Big City", "Small City"); }
Source:
public List<ValidationError> validate(){ Pattern hasLetters = Pattern.compile("[a-zA-Z]"); List<ValidationError> errors = new ArrayList<>(); if (hasLetters.matcher(phoneNumber).find()) errors.add(new ValidationError("phoneNumber", "The Phone Number must NOT contain letters")); return errors.isEmpty() ? null : errors; }

Target:
public List<ValidationError> validate(){ Pattern hasLetters = Pattern.compile("[\\D]"); List<ValidationError> errors = new ArrayList<>(); if (hasLetters.matcher(phoneNumber).find()) errors.add(new ValidationError("phoneNumber", "The Phone Number must ONLY contain numbers")); return errors.isEmpty() ? null : errors; }
Source:
public CompletableFuture<@Nullable Void> setValue(Command command) { String mqttCommandValue = getValue().update(command); final MqttBrokerConnection connection = this.connection; if (!config.commandTopic.isEmpty() && connection != null) { if (config.formatBeforePublish.length() > 0) { try (Formatter formatter = new Formatter()) { Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue); mqttCommandValue = format.toString(); } } return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained) .thenRun(() -> { }); } else { CompletableFuture<@Nullable Void> f = new CompletableFuture<>(); f.completeExceptionally(new IllegalStateException("No connection or no command topic!")); return f; } }

Target:
public CompletableFuture<@Nullable Void> setValue(Command command) { String mqttCommandValue = getValue().update(command); final MqttBrokerConnection connection = this.connection; if (!readOnly && connection != null) { if (config.formatBeforePublish.length() > 0) { try (Formatter formatter = new Formatter()) { Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue); mqttCommandValue = format.toString(); } catch (IllegalFormatException e) { logger.debug("Format pattern incorrect for {}", channelUID, e); } } return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained) .thenRun(() -> { }); } else { CompletableFuture<@Nullable Void> f = new CompletableFuture<>(); f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!")); return f; } }
Source:
public void testIsHeartbeatTopic() throws InterruptedException, TimeoutException { MirrorClient client = new FakeMirrorClient(); assertTrue(client.isHeartbeatTopic("heartbeats")); assertTrue(client.isHeartbeatTopic("source1.heartbeats")); assertTrue(client.isHeartbeatTopic("source2.source1.heartbeats")); assertFalse(client.isHeartbeatTopic("heartbeats!")); assertFalse(client.isHeartbeatTopic("!heartbeats")); assertFalse(client.isHeartbeatTopic("source1heartbeats")); assertFalse(client.isHeartbeatTopic("source1-heartbeats")); client.close(); }

Target:
public void testIsHeartbeatTopic() throws InterruptedException, TimeoutException { MirrorClient client = new FakeMirrorClient(); assertTrue(client.isHeartbeatTopic("heartbeats")); assertTrue(client.isHeartbeatTopic("source1.heartbeats")); assertTrue(client.isHeartbeatTopic("source2.source1.heartbeats")); assertFalse(client.isHeartbeatTopic("heartbeats!")); assertFalse(client.isHeartbeatTopic("!heartbeats")); assertFalse(client.isHeartbeatTopic("source1heartbeats")); assertFalse(client.isHeartbeatTopic("source1-heartbeats")); }
Source:
public void testAddTransfer_Owner(){ addTicketTransfer(user.getUsername(), "password").then().statusCode(HttpStatus.SC_OK); ticket = ticketRepository.findByKey(ticket.getKey()).orElse(null); if(ticket == null) Assert.fail("Could not refresh ticket"); Assert.assertTrue(ticket.isLockedForTransfer()); }

Target:
public void testAddTransfer_Owner(){ String token = addTicketTransfer(user.getUsername(), "password") .then() .statusCode(HttpStatus.SC_OK) .extract().path("object.token"); TicketTransferToken ttt = tttRepository.findByToken(token).orElseThrow(() -> new TokenNotFoundException(token)); Assert.assertTrue(ttt.isValid()); Assert.assertTrue(ttt.getTicket().getOwner().equals(user)); Assert.assertTrue(ttt.getUser().equals(ticketReceiver)); }
Source:
public void onNext(T element) { try { received.add(element); } catch (IllegalStateException ex) { if (ex.getMessage().contains("Queue full")) { throw new IllegalStateException("Received more than bufferSize (" + received.QUEUE_SIZE + ") onNext signals. " + "The Publisher probably emited more signals than expected!", ex); } else throw ex; } }

Target:
public void onNext(T element) { try { received.add(element); } catch (IllegalStateException ex) { throw new SubscriberBufferOverflowException( String.format("Received more than bufferSize (%d) onNext signals. " + "The Publisher probably emited more signals than expected!", received.QUEUE_SIZE), ex); } }
Source:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { try { if (currentFormat != null) calc(); } catch (GeopointException e) { context.showToast(e.getMessage()); spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); }

Target:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (currentFormat != null && !calc()) { spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); }
Source:
public MesosSlaveInfo copyWithDockerImage(String label, String dockerImage) { LOGGER.fine(String.format("Customize mesos slave %s using docker image %s", this.getLabelString(), dockerImage)); try { return new MesosSlaveInfo( label, mode, slaveCpus, slaveMem, minExecutors, maxExecutors, executorCpus, executorMem, remoteFSRoot, idleTerminationMinutes, slaveAttributes, jvmArgs, jnlpArgs, defaultSlave, containerInfo.copyWithDockerImage(dockerImage), additionalURIs, nodeProperties ); } catch (Descriptor.FormException e) { return null; } catch (IOException e) { return null; } }

Target:
public MesosSlaveInfo copyWithDockerImage(String label, String dockerImage) { LOGGER.fine(String.format("Customize mesos slave %s using docker image %s", this.getLabelString(), dockerImage)); try { return new MesosSlaveInfo( label, mode, slaveCpus, slaveMem, minExecutors, maxExecutors, executorCpus, executorMem, remoteFSRoot, idleTerminationMinutes, slaveAttributes, jvmArgs, jnlpArgs, defaultSlave, containerInfo.copyWithDockerImage(dockerImage), additionalURIs, nodeProperties ); } catch (Descriptor.FormException e) { LOGGER.log(Level.WARNING, "Failed to create customized mesos container info", e); return null; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to create customized mesos slave info", e); return null; } }
Source:
public DataSegment push(final File inDir, final DataSegment segment, final boolean useUniquePath) throws IOException { final String storageDir = this.getStorageDir(segment, false); log.info( "Copying segment[%s] to HDFS at location[%s/%s]", segment.getId(), fullyQualifiedStorageDirectory.get(), storageDir ); final String uniquePrefix = useUniquePath ? DataSegmentPusher.generateUniquePath() + "_" : ""; final Path outIndexFile = new Path(StringUtils.format( "%s/%s/%d_%sindex.zip", fullyQualifiedStorageDirectory.get(), storageDir, segment.getShardSpec().getPartitionNum(), uniquePrefix )); FileSystem fs = outIndexFile.getFileSystem(hadoopConfig); fs.mkdirs(outIndexFile.getParent()); log.info("Compressing files from[%s] to [%s]", inDir, outIndexFile); final long size; try (FSDataOutputStream out = fs.create(outIndexFile)) { size = CompressionUtils.zip(inDir, out); } return segment.withLoadSpec(makeLoadSpec(outIndexFile.toUri())) .withSize(size) .withBinaryVersion(SegmentUtils.getVersionFromDir(inDir)); }

Target:
public DataSegment push(final File inDir, final DataSegment segment, final boolean useUniquePath) throws IOException { final String storageDir = this.getStorageDir(segment, false); log.info( "Copying segment[%s] to HDFS at location[%s/%s]", segment.getId(), fullyQualifiedStorageDirectory.get(), storageDir ); final String uniquePrefix = useUniquePath ? DataSegmentPusher.generateUniquePath() + "_" : ""; final Path outIndexFile = new Path(StringUtils.format( "%s/%s/%d_%sindex.zip", fullyQualifiedStorageDirectory.get(), storageDir, segment.getShardSpec().getPartitionNum(), uniquePrefix )); FileSystem fs = outIndexFile.getFileSystem(hadoopConfig); fs.mkdirs(outIndexFile.getParent()); log.info("Compressing files from[%s] to [%s]", inDir, outIndexFile); final long size; try (FSDataOutputStream out = fs.create(outIndexFile, false)) { size = CompressionUtils.zip(inDir, out); } return segment.withLoadSpec(makeLoadSpec(outIndexFile.toUri())) .withSize(size) .withBinaryVersion(SegmentUtils.getVersionFromDir(inDir)); }
Source:
private int readIntConfigWithDefaultValue(Map<String, String> configs, String key, int defaultValue) { int intConfigValue; String intConfigStrValue = configs.get(key); if (intConfigStrValue != null) { try { intConfigValue = Integer.parseInt(intConfigStrValue); } catch (Exception e) { intConfigValue = defaultValue; } } else { intConfigValue = defaultValue; } return intConfigValue; }

Target:
private int readIntConfigWithDefaultValue(Map<String, String> configs, String key, int defaultValue) { int intConfigValue; String intConfigStrValue = configs.get(key); if (intConfigStrValue != null) { try { intConfigValue = Integer.parseInt(intConfigStrValue); } catch (Exception e) { LOGGER.warn("Failed to read the int config with the key = {}. Using default value = {}", key, defaultValue); intConfigValue = defaultValue; } } else { intConfigValue = defaultValue; } return intConfigValue; }
Source:
private void initSession() throws RuntimeException, InterruptedException { int retryCounter = cassandraConnectionMaxRetries; while (retryCounter-- != 0) { try { createSession(); break; } catch (NoHostAvailableException e) { log.error(e.getMessage()); Thread.sleep(cassandraConnectionMaxDelay); } } throw new RuntimeException("Cassandra connection retry limit exceeded."); }

Target:
private void initSession() throws RuntimeException, InterruptedException { int retryCounter = cassandraConnectionMaxRetries; while (retryCounter-- != 0) { try { createSession(); return; } catch (NoHostAvailableException e) { log.error(e.getMessage()); Thread.sleep(cassandraConnectionMaxDelay); } } throw new RuntimeException("Cassandra connection retry limit exceeded."); }
Source:
public void shouldFailWithoutAdditionalInfosWhenMimeTypeIsNotSupportedByConverter() throws IOException { String converterName = cs.getConverterName("image/jpeg", "application/pdf"); BlobHolder blobHolder = getBlobFromPath("test-docs/" + "hello.xls", "application/vnd.ms-excel"); try { cs.convert(converterName, blobHolder, Collections.emptyMap()); } catch (ConversionException e) { assertNotNull(e.getInfos()); assertTrue(CollectionUtils.isEmpty(e.getInfos())); } }

Target:
public void shouldFailWithoutAdditionalInfosWhenMimeTypeIsNotSupportedByConverter() throws IOException { String converterName = cs.getConverterName("image/jpeg", "application/pdf"); BlobHolder blobHolder = getBlobFromPath("test-docs/hello.xls", "application/vnd.ms-excel"); try { cs.convert(converterName, blobHolder, Collections.emptyMap()); fail("Should have raised a ConversionException"); } catch (ConversionException e) { assertTrue(e.getInfos().isEmpty()); } }
Source:
public RegistryAuthLocator(AuthConfig defaultAuthConfig) { this.defaultAuthConfig = defaultAuthConfig; this.configFile = new File(System.getProperty("user.home") + "/.docker/config.json"); this.commandPathPrefix = ""; }

Target:
public RegistryAuthLocator(AuthConfig defaultAuthConfig) { this.defaultAuthConfig = defaultAuthConfig; final String dockerConfigLocation = System.getenv().getOrDefault("DOCKER_CONFIG", System.getProperty("user.home") + "/.docker"); this.configFile = new File(dockerConfigLocation + "/config.json"); this.commandPathPrefix = ""; }
Source:
public void initClass() { Log.setGlobalLogLevel(LogLevel.ERROR); }

Target:
public void initClass() { globalLogLevel = Log.getGlobalLogLevel(); Log.setGlobalLogLevel(LogLevel.ERROR); }
Source:
public void disableManager() { _logger.info("Disabling Metric Manager"); if (_isManagerEnabled) { _isManagerEnabled = false; for (IMetricEmitter emitter : _metricEmitters) { try { emitter.purgeAllData(); } catch (Exception ex) { _logger.error("Failed to purge data " + ex.toString()); } } } }

Target:
public void disableManager() { logger.info("Disabling Metric Manager"); if (isManagerEnabled) { isManagerEnabled = false; for (IMetricEmitter emitter : metricEmitters) { try { emitter.purgeAllData(); } catch (MetricException ex) { logger.error("Failed to purge data ", ex); } } } }
Source:
private boolean contentCheck(DirCacheEntry entry, ObjectReader reader) throws IOException { if (getEntryObjectId().equals(entry.getObjectId())) { entry.setLength((int) getEntryLength()); return false; } else { if (mode == FileMode.SYMLINK.getBits()) return !new File(FS.detect().normalize( readContentAsString(current()))).equals(new File((FS .detect().normalize(readContentAsString(entry))))); if (reader == null) return true; switch (getOptions().getAutoCRLF()) { case INPUT: case TRUE: InputStream dcIn = null; try { ObjectLoader loader = reader.open(entry.getObjectId()); if (loader == null) return true; dcIn = new EolCanonicalizingInputStream( loader.openStream(), true, true ); long dcInLen; try { dcInLen = computeLength(dcIn); } catch (EolCanonicalizingInputStream.IsBinaryException e) { return true; } finally { dcIn.close(); } dcIn = new EolCanonicalizingInputStream( loader.openStream(), true); byte[] autoCrLfHash = computeHash(dcIn, dcInLen); boolean changed = getEntryObjectId().compareTo( autoCrLfHash, 0) != 0; return changed; } catch (IOException e) { return true; } finally { if (dcIn != null) try { dcIn.close(); } catch (IOException e) { } } case FALSE: break; } return true; } }

Target:
private boolean contentCheck(DirCacheEntry entry, ObjectReader reader) throws IOException { if (getEntryObjectId().equals(entry.getObjectId())) { entry.setLength((int) getEntryLength()); return false; } else { if (mode == FileMode.SYMLINK.getBits()) return !new File(readContentAsNormalizedString(current())) .equals(new File((readContentAsNormalizedString(entry)))); if (reader == null) return true; switch (getOptions().getAutoCRLF()) { case INPUT: case TRUE: InputStream dcIn = null; try { ObjectLoader loader = reader.open(entry.getObjectId()); if (loader == null) return true; dcIn = new EolCanonicalizingInputStream( loader.openStream(), true, true ); long dcInLen; try { dcInLen = computeLength(dcIn); } catch (EolCanonicalizingInputStream.IsBinaryException e) { return true; } finally { dcIn.close(); } dcIn = new EolCanonicalizingInputStream( loader.openStream(), true); byte[] autoCrLfHash = computeHash(dcIn, dcInLen); boolean changed = getEntryObjectId().compareTo( autoCrLfHash, 0) != 0; return changed; } catch (IOException e) { return true; } finally { if (dcIn != null) try { dcIn.close(); } catch (IOException e) { } } case FALSE: break; } return true; } }
Source:
public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory, boolean startImmediately, String threadName) { SmartThread thread = new SmartThread(new Runnable() { public void run() { try { final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; while (true) { final Long s = fn.call(); if (s==null) break; if (s>0) Time.sleep(s); } } catch (Throwable t) { LOG.info("Async loop Exception Stacktrace is: ", getStackTrace(t)); if (Utils.exceptionCauseIsInstanceOf( InterruptedException.class, t)) { LOG.info("Async loop interrupted!"); return; } LOG.error("Async loop died!", t); throw new RuntimeException(t); } } }); if (eh != null) { thread.setUncaughtExceptionHandler(eh); } else { thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOG.error("Async loop died!", e); Utils.exitProcess(1, "Async loop died!"); } }); } thread.setDaemon(isDaemon); thread.setPriority(priority); if (threadName != null && !threadName.isEmpty()) { thread.setName(thread.getName() +"-"+ threadName); } if (startImmediately) { thread.start(); } return thread; }

Target:
public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory, boolean startImmediately, String threadName) { SmartThread thread = new SmartThread(new Runnable() { public void run() { try { final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; while (true) { final Long s = fn.call(); if (s == null) { break; } if (s > 0) { Time.sleep(s); } } } catch (Throwable t) { if (Utils.exceptionCauseIsInstanceOf( InterruptedException.class, t)) { LOG.error("Async loop interrupted!", t); return; } LOG.error("Async loop died!", t); throw new RuntimeException(t); } } }); if (eh != null) { thread.setUncaughtExceptionHandler(eh); } else { thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOG.error("Async loop died!", e); Utils.exitProcess(1, "Async loop died!"); } }); } thread.setDaemon(isDaemon); thread.setPriority(priority); if (threadName != null && !threadName.isEmpty()) { thread.setName(thread.getName() + "-" + threadName); } if (startImmediately) { thread.start(); } return thread; }
Source:
synchronized long expireServer(final ServerName serverName, boolean force) { ZKWatcher zkw = master.getZooKeeper(); if (serverName.equals(master.getServerName())) { if (!(master.isAborted() || master.isStopped())) { master.stop("We lost our znode?"); } return Procedure.NO_PROC_ID; } if (this.deadservers.isDeadServer(serverName)) { LOG.warn("Expiration called on but already in DeadServer", serverName); return Procedure.NO_PROC_ID; } moveFromOnlineToDeadServers(serverName); String drainingZnode = ZNodePaths.joinZNode(zkw.getZNodePaths().drainingZNode, serverName.getServerName()); try { ZKUtil.deleteNodeFailSilent(zkw, drainingZnode); } catch (KeeperException e) { LOG.warn("Error deleting the znode for draining server " + drainingZnode); } if (isClusterShutdown()) { LOG.info("Cluster shutdown set; " + serverName + " expired; onlineServers=" + this.onlineServers.size()); if (this.onlineServers.isEmpty()) { master.stop("Cluster shutdown set; onlineServer=0"); } return Procedure.NO_PROC_ID; } LOG.info("Processing expiration of " + serverName + " on " + this.master.getServerName()); long pid = master.getAssignmentManager().submitServerCrash(serverName, true, force); if (!this.listeners.isEmpty()) { this.listeners.stream().forEach(l -> l.serverRemoved(serverName)); } if (flushedSeqIdFlusher != null) { flushedSeqIdFlusher.triggerNow(); } return pid; }

Target:
synchronized long expireServer(final ServerName serverName, boolean force) { if (serverName.equals(master.getServerName())) { if (!(master.isAborted() || master.isStopped())) { master.stop("We lost our znode?"); } return Procedure.NO_PROC_ID; } if (this.deadservers.isDeadServer(serverName)) { LOG.warn("Expiration called on but already in DeadServer", serverName); return Procedure.NO_PROC_ID; } moveFromOnlineToDeadServers(serverName); if (master.getZooKeeper() != null) { String drainingZnode = ZNodePaths .joinZNode(master.getZooKeeper().getZNodePaths().drainingZNode, serverName.getServerName()); try { ZKUtil.deleteNodeFailSilent(master.getZooKeeper(), drainingZnode); } catch (KeeperException e) { LOG.warn("Error deleting the draining znode for stopping server " + serverName.getServerName(), e); } } if (isClusterShutdown()) { LOG.info("Cluster shutdown set; " + serverName + " expired; onlineServers=" + this.onlineServers.size()); if (this.onlineServers.isEmpty()) { master.stop("Cluster shutdown set; onlineServer=0"); } return Procedure.NO_PROC_ID; } LOG.info("Processing expiration of " + serverName + " on " + this.master.getServerName()); long pid = master.getAssignmentManager().submitServerCrash(serverName, true, force); if (!this.listeners.isEmpty()) { this.listeners.stream().forEach(l -> l.serverRemoved(serverName)); } if (flushedSeqIdFlusher != null) { flushedSeqIdFlusher.triggerNow(); } return pid; }
Source:
void scrollToBottom() { final HTMLElement container = (HTMLElement) getElement(); container.scrollTop = container.scrollHeight - container.clientHeight; }

Target:
private void scrollToBottom() { scrollHelper.scrollToBottom(getElement()); }
Source:
private boolean checkTetrahedral(int u, int[] mapping) { int v = mapping[u]; if (targetTypes[v] != null && targetTypes[v] != Type.Tetrahedral) return false; ITetrahedralChirality queryElement = (ITetrahedralChirality) queryElements[u]; ITetrahedralChirality targetElement = (ITetrahedralChirality) targetElements[v]; IAtom queryAtom = query.getAtom(u); IAtom targetAtom = target.getAtom(v); if (targetTypes[v] == null) return ((QueryAtom)queryAtom).getExpression().matches(targetAtom, 0); if (targetTypes[v] != Type.Tetrahedral) return false; int[] us = map(u, v, neighbors(queryElement, queryMap), mapping); int[] vs = neighbors(targetElement, targetMap); int focusIdx = targetMap.get(targetAtom); for (int i = 0; i < 4; i++) { int j = 0, k = 0; for (; j < 4; j++) { if (vs[i] == us[j]) break; if (us[j] == focusIdx) k = j; } if (j == 4) us[k] = vs[i]; } int parity = permutationParity(us) * permutationParity(vs) * parity(targetElement.getStereo()); if (parity < 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.LEFT); else if (parity > 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.RIGHT); else return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, 0); }

Target:
private boolean checkTetrahedral(int u, int[] mapping) { int v = mapping[u]; if (targetTypes[v] != null && targetTypes[v] != Type.Tetrahedral) return false; ITetrahedralChirality queryElement = (ITetrahedralChirality) queryElements[u]; ITetrahedralChirality targetElement = (ITetrahedralChirality) targetElements[v]; IAtom queryAtom = query.getAtom(u); IAtom targetAtom = target.getAtom(v); if (targetTypes[v] == null) return ((QueryAtom)queryAtom).getExpression().matches(targetAtom, 0); if (targetTypes[v] != Type.Tetrahedral) return false; int[] us = map(u, v, neighbors(queryElement, queryMap), mapping); int[] vs = neighbors(targetElement, targetMap); int focusIdx = targetMap.get(targetAtom); for (int i = 0; i < 4; i++) { int j = indexOf(us, vs[i]); if (j < 0) us[indexOf(us, focusIdx)] = vs[i]; } int parity = permutationParity(us) * permutationParity(vs) * parity(targetElement.getStereo()); if (parity < 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.LEFT); else if (parity > 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.RIGHT); else return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, 0); }