auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void startTestFor(Activity activity) { ViewGroup view = (ViewGroup) activity.findViewById(android.R.id.content); ImageView qrCodeImageView = new ImageView(activity); view.addView(qrCodeImageView); int randomIndex = RANDOM.nextInt(listOfUrls.length); String url = listOfUrls[randomIndex]; int color = listOfColors[randomIndex]; try { BitMatrix qrCode = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, 1000, 1000); int width = qrCode.getWidth(); int height = qrCode.getHeight(); Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bmp.setPixel(x, y, qrCode.get(x, y) ? color : Color.WHITE); } } qrCodeImageView.setImageBitmap(bmp); } catch (WriterException e) { e.printStackTrace(); } }

Target:
public void startTestFor(Activity activity) { ViewGroup view = getParent(activity); ImageView qrCodeImageView = new ImageView(activity); view.addView(qrCodeImageView); int randomIndex = RANDOM.nextInt(listOfUrls.length); String url = listOfUrls[randomIndex]; int color = listOfColors[randomIndex]; int qrCodeSizeInPixels = 1000; try { BitMatrix qrCode = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, qrCodeSizeInPixels, qrCodeSizeInPixels); int width = qrCode.getWidth(); int height = qrCode.getHeight(); Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bmp.setPixel(x, y, qrCode.get(x, y) ? color : Color.WHITE); } } qrCodeImageView.setImageBitmap(bmp); } catch (WriterException e) { assertThat(e).isNull(); } }
Source:
public void onDestroyView() { super.onDestroyView(); ((PageActivity)getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); app.getBus().unregister(this); }

Target:
public void onDestroyView() { super.onDestroyView(); app.getBus().unregister(this); }
Source:
public ViewerTestCase(String name) { super(name); disableTestsBug347491 = Util.isCocoa(); final String GTK_VERSION_PROPERTY = "org.eclipse.swt.internal.gtk.version"; String value = System.getProperty(GTK_VERSION_PROPERTY); if (value != null) { if (value.startsWith("3")) { disableTestsBug493357 = true; } } }

Target:
public ViewerTestCase(String name) { super(name); disableTestsBug347491 = Util.isCocoa(); }
Source:
public static void removeStatementPatternIds(TransactionBase tx, Set<String> ids) { Optional<Bytes> val = Optional.fromNullable(tx.get(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS)); Set<String> storedIds = new HashSet<>(); if (val.isPresent()) { storedIds = Sets.newHashSet(val.get().toString().split(VAR_DELIM)); } storedIds.removeAll(ids); String idString = Joiner.on(VAR_DELIM).join(ids); tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS, Bytes.of(idString)); tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS_HASH, Bytes.of(Hashing.sha256().hashString(idString).toString())); }

Target:
public static void removeStatementPatternIds(TransactionBase tx, Set<String> ids) { checkNotNull(tx); checkNotNull(ids); Optional<Bytes> val = Optional.fromNullable(tx.get(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS)); Set<String> storedIds = new HashSet<>(); if (val.isPresent()) { storedIds = Sets.newHashSet(val.get().toString().split(VAR_DELIM)); } storedIds.removeAll(ids); String idString = Joiner.on(VAR_DELIM).join(ids); tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS, Bytes.of(idString)); tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS_HASH, Bytes.of(Hashing.sha256().hashString(idString).toString())); }
Source:
public String getFile(@PathVariable("id") final String id, final HttpServletRequest request) { String encodedId; try { encodedId = URLEncoder.encode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { log.warn("Failed to encode id: {}", id, e); encodedId = id; } final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; }

Target:
public String getFile( @PathVariable("id") final String id, final HttpServletRequest request ) throws UnsupportedEncodingException { final String encodedId = URLEncoder.encode(id, "UTF-8"); final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; }
Source:
void remove(K key) { heads.writeLock().lock(); try { heads.computeIfPresent(key, (k, v) -> null); } finally { heads.writeLock().unlock(); } }

Target:
void remove(K key) { heads.removeNoReturn(key); }
Source:
public synchronized void markFailure() { final Status currentStatus = this.updateAndGetStatus(); switch (currentStatus) { case CLOSED: this.processFailureWhenClosed(); break; case HALF_OPEN: this.openCircuit(); break; case OPEN: LOGGER.debug("New failure. No action needed, circuit already open."); break; default: break; } }

Target:
public void markFailure() { final boolean isCurrentlyClosed = this.isClosed(); if (isCurrentlyClosed) { this.processFailureWhenClosed(); } else { LOGGER.debug("New failure. No action needed, circuit already open."); } }
Source:
public void testQueryTaskByVariablesWithAllOwners() { Map<String, Object> variables = emptyMap(); Map<String, Object> attributes = emptyMap(); List<String> potOwners = Arrays.asList("katy", "nobody"); List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(attributes, variables, emptyMap(), potOwners, new QueryContext(0, 2)); Assert.assertEquals(0, data.size()); }

Target:
public void testQueryTaskByVariablesWithAllOwners() { List<String> potOwners = Arrays.asList("katy", "nobody"); List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(emptyList(), emptyList(), emptyList(), potOwners, queryContext); Assert.assertEquals(0, data.size()); }
Source:
private boolean isRecord(Schema schema) { if (schema == null) { return false; } Schema.Type type = schema.getType(); if (type == Schema.Type.RECORD) { return true; } if (schema.isNullable()) { Schema nonNullable = schema.getNonNullable(); return nonNullable.getType() == Schema.Type.RECORD; } return false; }

Target:
private boolean isRecord(Schema schema) { if (schema == null) { return false; } Schema.Type type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); return type == Schema.Type.RECORD; }
Source:
private CompletionStage<Void> addTransfers(IntSet segments) { log.debugf("Adding inbound state transfer for segments %s", segments); Set<Address> excludedSources = new HashSet<>(); Map<Address, IntSet> sources = new HashMap<>(); CompletionStage<Void> stage = CompletableFutures.completedNull(); if (isTransactional && !isTotalOrder) { stage = stage.thenCompose(ignored -> requestTransactions(segments, sources, excludedSources)); } if (isFetchEnabled) { stage = stage.thenRun(() -> requestSegments(segments, sources, excludedSources)); } return stage; }

Target:
private CompletionStage<Void> addTransfers(IntSet segments) { log.debugf("Adding inbound state transfer for segments %s", segments); Set<Address> excludedSources = new HashSet<>(); Map<Address, IntSet> sources = new HashMap<>(); CompletionStage<Void> stage = CompletableFutures.completedNull(); if (isTransactional && !isTotalOrder) { stage = requestTransactions(segments, sources, excludedSources); } if (isFetchEnabled) { stage = stage.thenRun(() -> requestSegments(segments, sources, excludedSources)); } return stage; }
Source:
public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IPropertySheetPage.class) { if (propertySheetPage == null) { if (adaptableObject instanceof CompareEditor) { IEditorInput editorInput = ((CompareEditor)adaptableObject).getEditorInput(); if (editorInput instanceof CompareEditorInput) { propertySheetPage = new ExtendedPropertySheetPage(null); CompareConfiguration configuration = ((CompareEditorInput)editorInput) .getCompareConfiguration(); } } } return propertySheetPage; } return null; }

Target:
public Object getAdapter(Object adaptableObject, Class adapterType) { if (adapterType == IPropertySheetPage.class) { if (propertySheetPage == null) { if (adaptableObject instanceof CompareEditor) { IEditorInput editorInput = ((CompareEditor)adaptableObject).getEditorInput(); if (editorInput instanceof CompareEditorInput) { propertySheetPage = new ExtendedPropertySheetPage(null); } } } return propertySheetPage; } return null; }
Source:
private void checkForCSRF(ASTMethod node, Object data) { if (node.isConstructor()) { if (Helper.foundAnyDML(node)) { addViolation(data, node); } } String name = node.getImage(); if (INIT.equalsIgnoreCase(name) || STATIC_INITIALIZER.equals(name)) { if (Helper.foundAnyDML(node)) { addViolation(data, node); } } }

Target:
private void checkForCSRF(ASTMethod node, Object data) { if (node.isConstructor() && Helper.foundAnyDML(node)) { addViolation(data, node); } String name = node.getImage(); if (isInitializerMethod(name) && Helper.foundAnyDML(node)) { addViolation(data, node); } }
Source:
public int hashCode() { return Objects.hash(getUsername(), getPolicy(), getContext(), getTitle(), ttl); }

Target:
public int hashCode() { return Objects.hash(getUsername(), getPolicy(), getContext(), getTitle(), getTTL()); }
Source:
Path(String definition) throws IOException { this.definition = definition; for (String filePath : definition.split(Pattern.quote(File.pathSeparator))) { try { addElement(getClassPathElement(new File(filePath))); } catch (IOException e) { throw new IOException("\"" + filePath + "\" can not be used as a classpath" + " element. (" + e.getMessage() + ")", e); } } }

Target:
Path(String definition) throws IOException { this.definition = definition; for (String filePath : definition.split(Pattern.quote(File.pathSeparator))) { try { addElement(getClassPathElement(new File(filePath))); } catch (IOException e) { throw new IOException("Wrong classpath: " + e.getMessage(), e); } } }
Source:
public DnsConfigurationModel() { getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { init(); } }); getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if ("IsChangable".equals(args.propertyName)) { boolean value = getIsChangable(); setDnsConfiguration.setIsChangeable(value); nameServerModelListModel.setIsChangeable(value); } } }); }

Target:
public DnsConfigurationModel() { listenToSetDnsConfigurationCheckboxChanges(); getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if ("IsChangable".equals(args.propertyName)) { boolean value = getIsChangable(); shouldSetDnsConfiguration.setIsChangeable(value); nameServerModelListModel.setIsChangeable(value); } } }); }
Source:
private List<ActivityLogEntry> searchLogsByQuery(LogQuery query, AdminActivityLogPageData data) { List<ActivityLogEntry> appLogs = new LinkedList<ActivityLogEntry>(); Iterable<RequestLogs> records = LogServiceFactory.getLogService().fetch(query); for (RequestLogs record : records) { record.getOffset(); List<AppLogLine> appLogLines = record.getAppLogLines(); for (AppLogLine appLog : appLogLines) { totalLogsSearched++; String logMsg = appLog.getLogMessage(); if (logMsg.contains("TEAMMATESLOG") && !logMsg.contains("adminActivityLogPage")) { ActivityLogEntry activityLogEntry = new ActivityLogEntry(appLog); activityLogEntry = data.filterLogs(activityLogEntry); if (activityLogEntry.toShow() && ((!activityLogEntry.isTestingData()) || data.getIfShowTestData())) { if (isFirstRow ) { activityLogEntry.setFirstRow(); isFirstRow = false; } appLogs.add(activityLogEntry); } } } } return appLogs; }

Target:
private List<ActivityLogEntry> searchLogsByQuery(LogQuery query, AdminActivityLogPageData data) { List<ActivityLogEntry> appLogs = new LinkedList<ActivityLogEntry>(); Iterable<RequestLogs> records = LogServiceFactory.getLogService().fetch(query); for (RequestLogs record : records) { List<AppLogLine> appLogLines = record.getAppLogLines(); for (AppLogLine appLog : appLogLines) { totalLogsSearched++; String logMsg = appLog.getLogMessage(); if (logMsg.contains("TEAMMATESLOG") && !logMsg.contains("adminActivityLogPage")) { ActivityLogEntry activityLogEntry = new ActivityLogEntry(appLog); activityLogEntry = data.filterLogs(activityLogEntry); if (activityLogEntry.toShow() && ((!activityLogEntry.isTestingData()) || data.getIfShowTestData())) { if (isFirstRow ) { activityLogEntry.setFirstRow(); isFirstRow = false; } appLogs.add(activityLogEntry); } } } } return appLogs; }
Source:
private List<Security> getSecurities() { IStructuredSelection selection = (IStructuredSelection) viewer.getStructuredSelection(); if (selection.isEmpty()) return null; List<Security> selectedSecurities = new ArrayList<>(); Iterator<Security> selectionIterator = selection.iterator(); while(selectionIterator.hasNext()) { Object object = selectionIterator.next(); Security selectedSecurity; if(object instanceof Security) { selectedSecurity = (Security) object; selectedSecurities.add(selectedSecurity); }else if(object instanceof Adaptable) { selectedSecurity = ((Adaptable) object).adapt(Security.class); selectedSecurities.add(selectedSecurity); }else{ } } return selectedSecurities; }

Target:
private List<Security> getSecurities() { IStructuredSelection selection = (IStructuredSelection) viewer.getStructuredSelection(); if (selection.isEmpty()) return null; List<Security> selectedSecurities = new ArrayList<>(); Iterator<Security> selectionIterator = selection.iterator(); while (selectionIterator.hasNext()) { Object object = selectionIterator.next(); Security selectedSecurity; if (object instanceof Security) { selectedSecurity = (Security) object; selectedSecurities.add(selectedSecurity); } else if (object instanceof Adaptable) { selectedSecurity = ((Adaptable) object).adapt(Security.class); if (selectedSecurity != null) { selectedSecurities.add(selectedSecurity); } } else { } } return selectedSecurities; }
Source:
public static Result update(String hash) { DynamicForm dynamicForm = Application.dynamicForm.bindFromRequest(request()); Record record = createRecordFromParams(dynamicForm.data()); List<ValError> validationErrors = new Validator(Register.instance.registerInfo().keys).validate(record); if (validationErrors.isEmpty()) { try { Register.instance.store().update(hash, record); return redirect("/hash/" + record.getHash()); } catch (DatabaseException e) { dynamicForm.reject(e.getMessage()); return ok(views.html.updateEntry.render( Register.instance.registerInfo().keys, dynamicForm, hash)); } } validationErrors.stream().forEach(error -> dynamicForm.reject(error.key, "error.required")); return ok(views.html.updateEntry.render( Register.instance.registerInfo().keys, dynamicForm, hash)); }

Target:
public static Result update(String hash) { DynamicForm dynamicForm = Application.dynamicForm.bindFromRequest(request()); Record record = createRecordFromParams(dynamicForm.data()); List<ValidationError> validationErrors = new Validator(Register.instance.registerInfo().keys).validate(record); if (validationErrors.isEmpty()) { try { Register.instance.store().update(hash, record); return redirect(controllers.api.routes.Rest.findByHash(record.getHash())); } catch (DatabaseException e) { dynamicForm.reject(e.getMessage()); return ok(views.html.updateEntry.render( Register.instance.registerInfo().keys, dynamicForm, hash)); } } validationErrors.stream().forEach(error -> dynamicForm.reject(error.key, "error.required")); return ok(views.html.updateEntry.render( Register.instance.registerInfo().keys, dynamicForm, hash)); }
Source:
private void initFilters() { IDialogSettings settings = getSettings(); fTreeViewer.addFilter(fJavaFilter); boolean hideWorkspace = settings.getBoolean(HIDE_WRKSPC); boolean hideEnabledExternal = settings.getBoolean(HIDE_EXENABLED); boolean hideDisabledExternal = !settings.getBoolean(SHOW_EXDISABLED); if (hideWorkspace) fTreeViewer.addFilter(fHideWorkspaceFilter); if (hideEnabledExternal) fTreeViewer.addFilter(fHideExtEnabledFilter); if (hideDisabledExternal) fTreeViewer.addFilter(fHideExtDisabledFilter); fHideWorkspaceFilterAction.setChecked(!hideWorkspace); fHideExtEnabledFilterAction.setChecked(!hideEnabledExternal); fHideExtDisabledFilterAction.setChecked(!hideDisabledExternal); if (PDECore.getDefault().getModelManager().isInitialized()) { PDEState state = PDECore.getDefault().getModelManager().getState(); fSourcePluginFilter = new SourcePluginFilter(state); } else { Job.createSystem("", monitor -> { PDEState state = TargetPlatformHelper.getPDEState(); Tree tree = fTreeViewer.getTree(); if (!tree.isDisposed()) { tree.getDisplay().asyncExec(() -> { fSourcePluginFilter = new SourcePluginFilter(state); fTreeViewer.addFilter(fSourcePluginFilter); }); } }).schedule(); } }

Target:
private void initFilters() { IDialogSettings settings = getSettings(); fTreeViewer.addFilter(fJavaFilter); boolean hideWorkspace = settings.getBoolean(HIDE_WRKSPC); boolean hideEnabledExternal = settings.getBoolean(HIDE_EXENABLED); boolean hideDisabledExternal = !settings.getBoolean(SHOW_EXDISABLED); if (hideWorkspace) fTreeViewer.addFilter(fHideWorkspaceFilter); if (hideEnabledExternal) fTreeViewer.addFilter(fHideExtEnabledFilter); if (hideDisabledExternal) fTreeViewer.addFilter(fHideExtDisabledFilter); fHideWorkspaceFilterAction.setChecked(!hideWorkspace); fHideExtEnabledFilterAction.setChecked(!hideEnabledExternal); fHideExtDisabledFilterAction.setChecked(!hideDisabledExternal); if (PDECore.getDefault().getModelManager().isInitialized()) { PDEState state = PDECore.getDefault().getModelManager().getState(); fSourcePluginFilter = new SourcePluginFilter(state); fTreeViewer.addFilter(fSourcePluginFilter); } else { Job.createSystem("", monitor -> { PDEState state = TargetPlatformHelper.getPDEState(); Tree tree = fTreeViewer.getTree(); if (!tree.isDisposed()) { tree.getDisplay().asyncExec(() -> { fSourcePluginFilter = new SourcePluginFilter(state); fTreeViewer.addFilter(fSourcePluginFilter); }); } }).schedule(); } }
Source:
public void testDeleteWhen404() throws InterruptedException { server.enqueue(jsonResponse("/virtualmachinescalesetlist.json").setResponseCode(404)); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); vmssAPI.delete(vmssname); assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/" + vmssname + "?api-version=2017-03-30"); }

Target:
public void testDeleteWhen404() throws InterruptedException { server.enqueue(jsonResponse("/virtualmachinescalesetlist.json").setResponseCode(404)); final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup); assertNull(vmssAPI.delete(vmssname)); assertSent(server, "DELETE", "/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/" + "Microsoft.Compute" + "/VirtualMachineScaleSets/" + vmssname + "?api-version=2017-03-30"); }
Source:
private void validateFilePath(ApplicationContext currentContext) { if (!isFilePathValid(pathname) || !isXMLFile(pathname)) { throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("'%s' is not a valid file.", pathname)); } if (isFileExisting(pathname) && isFileEmpty(pathname)) { throw new CLIException(REASON_FILE_EMPTY, String.format("'%s' is empty.", pathname)); } if (!isFileExisting(pathname)) { throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("'%s' does not exist.", pathname)); } }

Target:
private void validateFilePath(ApplicationContext currentContext) throws JobCreationRestException { if (!isFilePathValid(pathname)) { throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("'%s' is not a valid file.", pathname)); } if (!isValidFileMimeType(pathname)) { throw new JobCreationRestException("Unknown job descriptor type: " + pathname); } if (isFileExisting(pathname) && isFileEmpty(pathname)) { throw new CLIException(REASON_FILE_EMPTY, String.format("'%s' is empty.", pathname)); } if (!isFileExisting(pathname)) { throw new CLIException(REASON_INVALID_ARGUMENTS, String.format("'%s' does not exist.", pathname)); } }
Source:
public CacheEntry<K, V> get() throws TimeoutException { if (taskRef.get() == null && taskRef.getAndUpdate((t) -> t == null ? new SupplierCacheLoaderTask() : t) == null) { AdvancedCacheLoader.CacheLoaderTask<K, V> task = taskRef.get(); executor.execute(() -> { try { manager.processOnAllStores(new WithinThreadExecutor(), filter, task, true, true); } finally { close(); } }); } CacheEntry<K, V> entry; boolean interrupted = false; while ((entry = queue.poll()) == null) { closeLock.lock(); try { if (closed) { if (queue.peek() != null) { continue; } break; } long targetTime = System.nanoTime() + unit.toNanos(timeout); try { if (!closeCondition.await(targetTime - System.nanoTime(), TimeUnit.NANOSECONDS)) { throw new TimeoutException("Couldn't retrieve entry an entry from store in allotted timeout: " + timeout + " unit: " + unit); } } catch (InterruptedException e) { interrupted = true; } } finally { closeLock.unlock(); } } if (interrupted) { Thread.currentThread().interrupt(); } return entry; }

Target:
public CacheEntry<K, V> get() throws TimeoutException { if (taskRef.get() == null && taskRef.getAndUpdate((t) -> t == null ? new SupplierCacheLoaderTask() : t) == null) { AdvancedCacheLoader.CacheLoaderTask<K, V> task = taskRef.get(); executor.execute(() -> { try { manager.processOnAllStores(new WithinThreadExecutor(), filter, task, true, true); } finally { close(); } }); } CacheEntry<K, V> entry; boolean interrupted = false; while ((entry = queue.poll()) == null) { closeLock.lock(); try { if (closed) { if ((entry = queue.poll()) != null) { break; } break; } long targetTime = System.nanoTime() + unit.toNanos(timeout); try { if (!closeCondition.await(targetTime - System.nanoTime(), TimeUnit.NANOSECONDS)) { throw new TimeoutException("Couldn't retrieve entry an entry from store in allotted timeout: " + timeout + " unit: " + unit); } } catch (InterruptedException e) { interrupted = true; } } finally { closeLock.unlock(); } } if (interrupted) { Thread.currentThread().interrupt(); } return entry; }
Source:
private void validateSchema(final EventTypeBase eventType) throws InvalidEventTypeException { try { final String eventTypeSchema = eventType.getSchema().getSchema(); JsonUtils.checkEventTypeSchemaValid(eventTypeSchema); final JSONObject schemaAsJson = new JSONObject(eventTypeSchema); final Schema schema = SchemaLoader.load(schemaAsJson); if (schemaAsJson.has("type") && schemaAsJson.getString("type").equals("array") && eventType.getCategory() != EventCategory.UNDEFINED) { throw new InvalidEventTypeException("\"type\" of root element in schema cannot be \"array\""); } if (eventType.getCategory() == EventCategory.BUSINESS && schema.definesProperty("#/metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); } if (featureToggleService.isFeatureEnabled(CHECK_PARTITIONS_KEYS)) { validatePartitionKeys(schema, eventType); } validateOrderingKeys(schema, eventType); if (eventType.getCompatibilityMode() == CompatibilityMode.COMPATIBLE) { validateJsonSchemaConstraints(schemaAsJson); } } catch (final JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (final SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } }

Target:
private void validateSchema(final EventTypeBase eventType) throws InvalidEventTypeException { try { final String eventTypeSchema = eventType.getSchema().getSchema(); JsonUtils.checkEventTypeSchemaValid(eventTypeSchema); final JSONObject schemaAsJson = new JSONObject(eventTypeSchema); if (schemaAsJson.has("type") && !Objects.equals("object", schemaAsJson.getString("type"))) { throw new InvalidEventTypeException("\"type\" of root element in schema can only be \"object\""); } final Schema schema = SchemaLoader.load(schemaAsJson); if (eventType.getCategory() == EventCategory.BUSINESS && schema.definesProperty("#/metadata")) { throw new InvalidEventTypeException("\"metadata\" property is reserved"); } validateOrderingKeys(schema, eventType); if (eventType.getCompatibilityMode() == CompatibilityMode.COMPATIBLE) { validateJsonSchemaConstraints(schemaAsJson); } } catch (final JSONException e) { throw new InvalidEventTypeException("schema must be a valid json"); } catch (final SchemaException e) { throw new InvalidEventTypeException("schema must be a valid json-schema"); } }
Source:
public void successfulStartupShutdownTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); StorageManager storageManager = createAndStartStoreManager(replicas); for (ReplicaId replica : replicas) { Store store = storageManager.getStore(replica.getPartitionId()); assertTrue("Store should be started", ((BlobStore) store).isStarted()); assertTrue("Compaction should be scheduled", storageManager.scheduleNextForCompaction(replica.getPartitionId())); } MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, Collections.<MockDataNodeId>emptyList(), 0); assertNull("Should not have found a store for an invalid partition.", storageManager.getStore(invalidPartition)); assertEquals("Compaction thread count is incorrect", dataNode.getMountPaths().size(), TestUtils.numThreadsByThisName(CompactionManager.THREAD_NAME_PREFIX)); verifyCompactionThreadCount(storageManager, dataNode.getMountPaths().size()); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals("Compaction thread count is incorrect", 0, storageManager.getCompactionThreadCount()); }

Target:
public void successfulStartupShutdownTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); StorageManager storageManager = createAndStartStoreManager(replicas, metricRegistry); for (ReplicaId replica : replicas) { Store store = storageManager.getStore(replica.getPartitionId()); assertTrue("Store should be started", ((BlobStore) store).isStarted()); assertTrue("Compaction should be scheduled", storageManager.scheduleNextForCompaction(replica.getPartitionId())); } Map<String, Counter> counters = metricRegistry.getCounters(); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreStartFailures")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "DiskMountPathFailures")); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, Collections.<MockDataNodeId>emptyList(), 0); assertNull("Should not have found a store for an invalid partition.", storageManager.getStore(invalidPartition)); assertEquals("Compaction thread count is incorrect", dataNode.getMountPaths().size(), TestUtils.numThreadsByThisName(CompactionManager.THREAD_NAME_PREFIX)); verifyCompactionThreadCount(storageManager, dataNode.getMountPaths().size()); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals("Compaction thread count is incorrect", 0, storageManager.getCompactionThreadCount()); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreShutdownFailures")); }
Source:
private List<Comment> getComments() { LOG.info("Start: Jira NewCommentsConsumer: retrieving issue comments. Last comment id: {}", lastCommentId); List<Comment> newComments = new ArrayList<>(); List<Issue> issues = getIssues(); for (Issue issue : issues) { Issue fullIssue = client().getIssueClient().getIssue(issue.getKey()).claim(); for (Comment comment : fullIssue.getComments()) { if (comment.getId() > lastCommentId) { newComments.add(comment); } } } for (Comment c: newComments) { if (c.getId() > lastCommentId) { lastCommentId = c.getId(); } } LOG.info("End: Jira NewCommentsConsumer: retrieving issue comments. new comments since last run.", newComments.size()); return newComments; }

Target:
private List<Comment> getComments() { LOG.debug("Start: Jira NewCommentsConsumer: retrieving issue comments. Last comment id: {}", lastCommentId); List<Comment> newComments = new ArrayList<>(); List<Issue> issues = getIssues(); for (Issue issue : issues) { Issue fullIssue = client().getIssueClient().getIssue(issue.getKey()).claim(); for (Comment comment : fullIssue.getComments()) { if (comment.getId() > lastCommentId) { newComments.add(comment); } } } for (Comment c: newComments) { if (c.getId() > lastCommentId) { lastCommentId = c.getId(); } } LOG.debug("End: Jira NewCommentsConsumer: retrieving issue comments. new comments since last run.", newComments.size()); return newComments; }
Source:
private FormatterBuilder createFormatterBuilder(KafkaExternalLoaderCLIArguments properties) throws Exception { FormatterBuilder fb; Properties formatterProperties = m_args.formatterProperties; AbstractFormatterFactory factory; if (formatterProperties.size() > 0) { String formatterClass = m_args.formatterProperties.getProperty("formatter"); String format = m_args.formatterProperties.getProperty("format", "csv"); Class<?> classz = Class.forName(formatterClass); Class<?>[] ctorParmTypes = new Class[]{ String.class, Properties.class }; Constructor<?> ctor = classz.getDeclaredConstructor(ctorParmTypes); Object[] ctorParms = new Object[]{ format, m_args.formatterProperties }; factory = new AbstractFormatterFactory() { @Override public Formatter create(String formatName, Properties props) { try { return (Formatter) ctor.newInstance(ctorParms); } catch (Exception e) { e.printStackTrace(); return null; } } }; fb = new FormatterBuilder(format, formatterProperties); } else { factory = new VoltCSVFormatterFactory(); Properties props = new Properties(); factory.create("csv", props); fb = new FormatterBuilder("csv", props); } fb.setFormatterFactory(factory); return fb; }

Target:
private FormatterBuilder createFormatterBuilder(KafkaExternalLoaderCLIArguments properties) throws Exception { FormatterBuilder builder; Properties formatterProperties = m_args.formatterProperties; AbstractFormatterFactory factory; if (formatterProperties.size() > 0) { String formatterClass = m_args.formatterProperties.getProperty("formatter"); String format = m_args.formatterProperties.getProperty("format", "csv"); Class<?> classz = Class.forName(formatterClass); Class<?>[] ctorParmTypes = new Class[]{ String.class, Properties.class }; Constructor<?> ctor = classz.getDeclaredConstructor(ctorParmTypes); Object[] ctorParms = new Object[]{ format, m_args.formatterProperties }; factory = new AbstractFormatterFactory() { @Override public Formatter create(String formatName, Properties props) { try { return (Formatter) ctor.newInstance(ctorParms); } catch (Exception e) { e.printStackTrace(); return null; } } }; builder = new FormatterBuilder(format, formatterProperties); } else { factory = new VoltCSVFormatterFactory(); Properties props = new Properties(); factory.create("csv", props); builder = new FormatterBuilder("csv", props); } builder.setFormatterFactory(factory); return builder; }
Source:
public WeightedSnapshot(Collection<WeightedSample> values) { if (values.size()==1 && Double.compare(values.iterator().next().weight,0D)==0) { this.values = new long[0]; this.normWeights = new double[0]; this.quantiles = new double[0]; return; } final WeightedSample[] copy = values.toArray( new WeightedSample[]{} ); Arrays.sort(copy, new Comparator<WeightedSample>() { @Override public int compare(WeightedSample o1, WeightedSample o2) { if (o1.value > o2.value) return 1; if (o1.value < o2.value) return -1; return 0; } } ); this.values = new long[copy.length]; this.normWeights = new double[copy.length]; this.quantiles = new double[copy.length]; double sumWeight = 0; for (WeightedSample sample : copy) { sumWeight += sample.weight; } for (int i = 0; i < copy.length; i++) { this.values[i] = copy[i].value; this.normWeights[i] = copy[i].weight / sumWeight; } for (int i = 1; i < copy.length; i++) { this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1]; } }

Target:
public WeightedSnapshot(Collection<WeightedSample> values) { final WeightedSample[] copy = values.toArray( new WeightedSample[]{} ); Arrays.sort(copy, new Comparator<WeightedSample>() { @Override public int compare(WeightedSample o1, WeightedSample o2) { if (o1.value > o2.value) return 1; if (o1.value < o2.value) return -1; return 0; } } ); this.values = new long[copy.length]; this.normWeights = new double[copy.length]; this.quantiles = new double[copy.length]; double sumWeight = 0; for (WeightedSample sample : copy) { sumWeight += sample.weight; } for (int i = 0; i < copy.length; i++) { this.values[i] = copy[i].value; this.normWeights[i] = copy[i].weight / sumWeight; } for (int i = 1; i < copy.length; i++) { this.quantiles[i] = this.quantiles[i - 1] + this.normWeights[i - 1]; } }
Source:
public static Workspace getWorkspace() throws Exception { if (getInstance() == null) { throw new IllegalStateException("Central is not initialised"); } Workspace ws; synchronized (workspaceQueue) { ws = workspace; if (ws != null) { return ws; } try { Workspace.setDriver(Constants.BNDDRIVER_ECLIPSE); Workspace.addGestalt(Constants.GESTALT_INTERACTIVE, new Attrs()); ws = Workspace.getWorkspaceWithoutException(getWorkspaceDirectory()); if (ws == null) { Processor p = new Processor(); File defaultBase = IO.getFile("~/.bnd/default-ws"); ws = Workspace.createStandaloneWorkspace(p, defaultBase.toURI()); ws.setBase(defaultBase); ws.setProperty("-default-ws", "true"); ws.warning("No bnd workspace found in %s; created default in ~/.bnd/default-ws", getWorkspaceDirectory()); } ws.addBasicPlugin(new WorkspaceListener(ws)); ws.addBasicPlugin(getInstance().repoListenerTracker); ws.addBasicPlugin(getWorkspaceR5Repository()); ws.addBasicPlugin(new JobProgress()); ws.getBuildOrder(); addCnfChangeListener(ws); workspaceRepositoryChangeDetector = new WorkspaceRepositoryChangeDetector(ws); workspace = ws; } catch (final Exception e) { if (ws != null) { ws.close(); } workspaceQueue.fail(e); throw e; } } workspaceQueue.resolve(ws); return ws; }

Target:
public static Workspace getWorkspace() throws Exception { if (getInstance() == null) { throw new IllegalStateException("Central is not initialised"); } Workspace ws; Exception exception = null; synchronized (workspaceQueue) { ws = workspace; if (ws != null) { return ws; } try { Workspace.setDriver(Constants.BNDDRIVER_ECLIPSE); Workspace.addGestalt(Constants.GESTALT_INTERACTIVE, new Attrs()); ws = Workspace.getWorkspaceWithoutException(getWorkspaceDirectory()); if (ws == null) { Processor p = new Processor(); File defaultBase = IO.getFile("~/.bnd/default-ws"); ws = Workspace.createStandaloneWorkspace(p, defaultBase.toURI()); ws.setBase(defaultBase); ws.setProperty("-default-ws", "true"); ws.warning("No bnd workspace found in %s; created default in ~/.bnd/default-ws", getWorkspaceDirectory()); } ws.addBasicPlugin(new WorkspaceListener(ws)); ws.addBasicPlugin(getInstance().repoListenerTracker); ws.addBasicPlugin(getWorkspaceR5Repository()); ws.addBasicPlugin(new JobProgress()); ws.getBuildOrder(); addCnfChangeListener(ws); workspaceRepositoryChangeDetector = new WorkspaceRepositoryChangeDetector(ws); workspace = ws; } catch (final Exception e) { if (ws != null) { ws.close(); } exception = e; } } if (exception != null) { workspaceQueue.fail(exception); throw exception; } workspaceQueue.resolve(ws); return ws; }
Source:
public void testCreateOrReplaceWithDeleteExisting() { server.expect().get().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200, service).times(2); server.expect().get().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, configMap).times(2); server.expect().delete().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200 , service).once(); server.expect().delete().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, configMap).once(); server.expect().post().withPath("/api/v1/namespaces/ns1/services").andReturn(200, service).once(); server.expect().post().withPath("/api/v1/namespaces/ns1/configmaps").andReturn(200, configMap).once(); KubernetesClient client = server.getClient(); KubernetesList list = new KubernetesListBuilder().withItems(service, configMap).build(); client.resourceList(list).inNamespace("ns1").deletingExisting().createOrReplace(); }

Target:
public void testCreateOrReplaceWithDeleteExisting() throws Exception { server.expect().get().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200, service).once(); server.expect().get().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, configMap).once(); server.expect().delete().withPath("/api/v1/namespaces/ns1/services/my-service").andReturn(200 , service).once(); server.expect().delete().withPath("/api/v1/namespaces/ns1/configmaps/my-configmap").andReturn(200, configMap).once(); server.expect().post().withPath("/api/v1/namespaces/ns1/services").andReturn(200, updatedService).once(); server.expect().post().withPath("/api/v1/namespaces/ns1/configmaps").andReturn(200, updatedConfigMap).once(); KubernetesClient client = server.getClient(); KubernetesList list = new KubernetesListBuilder().withItems(updatedService, updatedConfigMap).build(); client.resourceList(list).inNamespace("ns1").deletingExisting().createOrReplace(); assertEquals(6, server.getMockServer().getRequestCount()); RecordedRequest request = server.getLastRequest(); assertEquals("/api/v1/namespaces/ns1/configmaps", request.getPath()); assertEquals("POST", request.getMethod()); }
Source:
public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); try (DbSession dbSession = dbClient.openSession(false)) { Optional<ComponentDto> projectOptional = dbClient.componentDao().selectByKey(dbSession, projectKey); if (!projectOptional.isPresent()) { throw new IllegalArgumentException(String.format("Project key '%s' not found", projectKey)); } ComponentDto project = projectOptional.get(); userSession.checkComponentPermission(UserRole.USER, project); if (!project.isEnabled() || !Qualifiers.PROJECT.equals(project.qualifier())) { throw new IllegalArgumentException("Invalid project key"); } Collection<BranchDto> branches = dbClient.branchDao().selectByComponent(dbSession, project); WsBranches.ListWsResponse.Builder protobufResponse = WsBranches.ListWsResponse.newBuilder(); branches.stream() .filter(b -> b.getKeeType().equals(BranchKeyType.BRANCH)) .forEach(b -> addToProtobuf(protobufResponse, b)); WsUtils.writeProtobuf(protobufResponse.build(), request, response); } }

Target:
public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_PROJECT); try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = WsUtils.checkFoundWithOptional( dbClient.componentDao().selectByKey(dbSession, projectKey), "Project key '%s' not found", projectKey); userSession.checkComponentPermission(UserRole.USER, project); if (!project.isEnabled() || !Qualifiers.PROJECT.equals(project.qualifier())) { throw new IllegalArgumentException("Invalid project key"); } Collection<BranchDto> branches = dbClient.branchDao().selectByComponent(dbSession, project); WsBranches.ListWsResponse.Builder protobufResponse = WsBranches.ListWsResponse.newBuilder(); branches.stream() .filter(b -> b.getKeeType().equals(BranchKeyType.BRANCH)) .forEach(b -> addToProtobuf(protobufResponse, b)); WsUtils.writeProtobuf(protobufResponse.build(), request, response); } }
Source:
private void findMaps() { File folder = new File("c:/users/jim/workspace/bubblebobble/src/main/resources"); File[] listOfFiles = folder.listFiles(); assert listOfFiles != null; for (File listOfFile : listOfFiles) { if (listOfFile.isFile()) { if (listOfFile.getName().matches("map[0-9]*.txt")) { maps.add(listOfFile.getName()); } } } }

Target:
private void findMaps() { File folder = new File("src/main/resources"); File[] listOfFiles = folder.listFiles(); assert listOfFiles != null; for (File file : listOfFiles) { if (file.isFile()) { if (file.getName().matches("map[0-9]*.txt")) { maps.add(file.getName()); } } } }
Source:
private @Nullable List<ISegment> computeData(final TmfTimeRange timeRange, final Range durationRange) { final AbstractSegmentStoreAnalysisModule analysisModule = fAnalysisModule; if (analysisModule == null) { return null; } final ISegmentStore<ISegment> results = analysisModule.getSegmentStore(); if (results == null) { return null; } Iterator<ISegment> intersectingElements = results.getIntersectingElements(timeRange.getStartTime().getValue(), timeRange.getEndTime().getValue()).iterator(); if (durationRange.lower > Double.MIN_VALUE || durationRange.upper < Double.MAX_VALUE) { Predicate<? super ISegment> predicate = new Predicate<ISegment>() { @Override public boolean apply(@Nullable ISegment input) { return input != null && input.getLength() >= durationRange.lower && input.getLength() <= durationRange.upper; } }; intersectingElements = Iterators.<ISegment> filter(intersectingElements, predicate); } return Lists.newArrayList(intersectingElements); }

Target:
private @Nullable List<ISegment> computeData(final TmfTimeRange timeRange, final Range durationRange) { final AbstractSegmentStoreAnalysisModule analysisModule = fAnalysisModule; if (analysisModule == null) { return null; } final ISegmentStore<ISegment> segStore = analysisModule.getSegmentStore(); if (segStore == null) { return null; } Iterator<ISegment> intersectingElements = segStore.getIntersectingElements(timeRange.getStartTime().getValue(), timeRange.getEndTime().getValue()).iterator(); if (durationRange.lower > Double.MIN_VALUE || durationRange.upper < Double.MAX_VALUE) { Predicate<? super ISegment> predicate = new Predicate<ISegment>() { @Override public boolean apply(@Nullable ISegment input) { return input != null && input.getLength() >= durationRange.lower && input.getLength() <= durationRange.upper; } }; intersectingElements = Iterators.filter(intersectingElements, predicate); } return Lists.newArrayList(intersectingElements); }
Source:
public GenericRow transform(GenericRow record) { for (Map.Entry<String, PinotDataType> entry : _dataTypes.entrySet()) { String column = entry.getKey(); Object value = record.getValue(column); if (value instanceof List) { value = ((List) value).toArray(); } PinotDataType source; if (value instanceof Object[]) { Object[] values = (Object[]) value; source = MULTI_VALUE_TYPE_MAP.get(values[0].getClass()); if (source == null) { source = PinotDataType.OBJECT_ARRAY; } else if (source == PinotDataType.HASHMAP) { source = PinotDataType.getPinotDataTypeFromHashMap((Map<Object, Object>) values[0]); } } else { source = SINGLE_VALUE_TYPE_MAP.get(value.getClass()); if (source == null) { source = PinotDataType.OBJECT; } } PinotDataType dest = entry.getValue(); if (source != dest) { value = dest.convert(value, source); } record.putValue(column, value); } return record; }

Target:
public GenericRow transform(GenericRow record) { for (Map.Entry<String, PinotDataType> entry : _dataTypes.entrySet()) { String column = entry.getKey(); Object value = record.getValue(column); if (value instanceof List) { value = ((List) value).toArray(); } PinotDataType source; if (value instanceof Object[]) { Object[] values = (Object[]) value; source = MULTI_VALUE_TYPE_MAP.get(values[0].getClass()); if (source == null) { if (values[0] instanceof Map) { source = PinotDataType.getSpecificMapDataTypeFromMap((Map<Object, Object>) values[0]); } else { source = PinotDataType.OBJECT_ARRAY; } } } else { source = SINGLE_VALUE_TYPE_MAP.get(value.getClass()); if (source == null) { source = PinotDataType.OBJECT; } } PinotDataType dest = entry.getValue(); if (source != dest) { value = dest.convert(value, source); } record.putValue(column, value); } return record; }
Source:
public void setBodyFieldsOnly(boolean bodyFieldsOnly) { this.bodyFieldsOnly = bodyFieldsOnly; searchPreferences.setBodyFieldsOnly(bodyFieldsOnly); Object searchPreferencesObject = createNativeSearchPreferences(searchPreferences); try { Header searchPreferencesHeader = new Header( new QName(getPlatformMessageNamespaceUri(), "searchPreferences"), searchPreferencesObject, new JAXBDataBinding(searchPreferencesObject.getClass())); setHeader(port, searchPreferencesHeader); } catch (JAXBException e) { throw new NetSuiteException(new NetSuiteErrorCode(NetSuiteErrorCode.INTERNAL_ERROR), "XML binding error", e); } }

Target:
public void setBodyFieldsOnly(boolean bodyFieldsOnly) { this.bodyFieldsOnly = bodyFieldsOnly; searchPreferences.setBodyFieldsOnly(bodyFieldsOnly); Object searchPreferencesObject = createNativeSearchPreferences(searchPreferences); try { Header searchPreferencesHeader = new Header( new QName(getPlatformMessageNamespaceUri(), "searchPreferences"), searchPreferencesObject, new JAXBDataBinding(searchPreferencesObject.getClass())); setHeader(port, searchPreferencesHeader); } catch (JAXBException e) { throw new NetSuiteException(new NetSuiteErrorCode(NetSuiteErrorCode.INTERNAL_ERROR), NetSuiteRuntimeI18n.MESSAGES.getMessage("error.binding"), e); } }
Source:
public static boolean registerFluidContainer(FluidContainerData data) { if (isFilledContainer(data.filledContainer)) { return false; } containerFluidMap.put(Arrays.asList(data.filledContainer.itemID, data.filledContainer.getItemDamage()), data); if (data.emptyContainer != null) { filledContainerMap.put(Arrays.asList(data.emptyContainer.itemID, data.emptyContainer.getItemDamage(), data.fluid.fluidID), data); emptyContainers.add(Arrays.asList(data.emptyContainer.itemID, data.emptyContainer.getItemDamage())); } MinecraftForge.EVENT_BUS.post(new FluidContainerRegisterEvent(data)); return true; }

Target:
public static boolean registerFluidContainer(FluidContainerData data) { if (isFilledContainer(data.filledContainer)) { return false; } containerFluidMap.put(getHashcode(data.filledContainer.itemID, data.filledContainer.getItemDamage()), data); if (data.emptyContainer != null) { filledContainerMap.put(Arrays.asList(data.emptyContainer.itemID, data.emptyContainer.getItemDamage(), data.fluid.fluidID), data); emptyContainers.add(getHashcode(data.emptyContainer.itemID, data.emptyContainer.getItemDamage())); } MinecraftForge.EVENT_BUS.post(new FluidContainerRegisterEvent(data)); return true; }