auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Service getService() { Service service = new Service(); service.setId("1"); service.setName("Dockstore"); service.setType(getServiceType()); <START> service.setDescription("The GA4GH Tool Registry API is a standard for listing and describing available tools (both stand-alone, Docker-based tools as well as workflows in CWL, WDL, Nextflow, or Galaxy) in a given registry,"); <END> service.setOrganization(getOrganization()); service.setContactUrl("<LINK_2>"); service.setDocumentationUrl("<LINK_0>/en/develop"); service.setCreatedAt(new Date()); service.setUpdatedAt(new Date()); service.setEnvironment("prod"); service.setVersion("2.0.1"); return service; }</code><technical_language>this mention Dockstore? I other way; other fields mention it. Depends if this describes API implementation</technical_language>

Target:
public static Service getService() { Service service = new Service(); service.setId("1"); service.setName("Dockstore"); service.setType(getServiceType()); service.setDescription("Dockstore is an implementation of the GA4GH Tool Registry API which is a standard for listing and describing available tools (both stand-alone, Docker-based tools as well as workflows in CWL, WDL, Nextflow, or Galaxy)"); service.setOrganization(getOrganization()); service.setContactUrl("<LINK_2>"); service.setDocumentationUrl("<LINK_0>"); final int createYear = 2020; Date createDate = Date.from(LocalDate.of(createYear, Month.JULY, 2).atStartOfDay(ZoneId.systemDefault()).toInstant()); service.setCreatedAt(createDate); service.setUpdatedAt(UPDATE_DATE); String implVersion = ToolsApiServiceImpl.class.getPackage().getImplementationVersion(); String environment = implVersion == null ? "dev" : "prod"; implVersion = implVersion == null ? DEV_SEM_VER : implVersion; service.setEnvironment(environment); service.setVersion(implVersion); return service; }
Source:
<code>public IStatus validate(IProject project, String path) { File file = new File(path); if (!file.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); } if (!file.isFile()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); } int confidence = 0; try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { int lineCount = 0; int matches = 0; String line = rafile.getNextLine(); while ((line != null) && line.startsWith("#")) { line = rafile.getNextLine(); } while ((line != null) && (lineCount++ < MAX_LINES)) { try { ITmfEvent event = parseLine(0, line); if (event != null) { matches++; } } catch (RuntimeException e) { confidence = Integer.MIN_VALUE; <START> } catch (Exception e) { <END> } confidence = MAX_CONFIDENCE * matches / lineCount; line = rafile.getNextLine(); } } catch (IOException e) { Activator.logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); }</code><technical_language>messing Exception</technical_language>

Target:
public IStatus validate(IProject project, String path) { File file = new File(path); if (!file.exists()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "File not found: " + path); } if (!file.isFile()) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Not a file. It's a directory: " + path); } int confidence = 0; try (BufferedRandomAccessFile rafile = new BufferedRandomAccessFile(path, "r")) { int lineCount = 0; int matches = 0; String line = rafile.getNextLine(); while ((line != null) && line.startsWith("#")) { line = rafile.getNextLine(); } while ((line != null) && (lineCount++ < MAX_LINES)) { try { ITmfEvent event = parseLine(0, line); if (event != null) { matches++; } } catch (RuntimeException e) { confidence = Integer.MIN_VALUE; } confidence = MAX_CONFIDENCE * matches / lineCount; line = rafile.getNextLine(); } } catch (IOException e) { Activator.logError("Error validating file: " + path, e); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IOException validating file: " + path, e); } return new TraceValidationStatus(confidence, Activator.PLUGIN_ID); }
Source:
<code>public static void requestContactPermission(final Activity activity) { <START> requestPermissions(activity, new HashSet<>(Arrays.asList(new Type[]{ Type.CONTACTS }))); <END> }</code><technical_language>requestPermissions(activity, Collections.singelton(Type.CONTACTS));</technical_language>

Target:
public static void requestContactPermission(final Activity activity) { requestPermissions(activity, Collections.singleton(Type.CONTACTS)); }
Source:
<code>public String build(final Path directory, final String name, final ProgressHandler handler, final BuildParameter... params) throws DockerException, InterruptedException, IOException { checkNotNull(handler, "handler"); WebTarget resource = resource().path("build"); for (final BuildParameter param : params) { resource = resource.queryParam(param.queryParam, String.valueOf(param.value)); } if (name != null) { resource = resource.queryParam("t", name); } try (CompressedDirectory compressedDirectory = CompressedDirectory.create(directory); <START> InputStream fileStream = Files.newInputStream(compressedDirectory.file()); <END> ProgressStream build = request(POST, ProgressStream.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.entity(fileStream, "application/tar"))) { String imageId = null; while (build.hasNextMessage(POST, resource.getUri())) { final ProgressMessage message = build.nextMessage(POST, resource.getUri()); final String id = message.buildImageId(); if (id != null) { imageId = id; } handler.progress(message); } return imageId; } }</code><technical_language>final InputStream fileStream</technical_language>

Target:
public String build(final Path directory, final String name, final ProgressHandler handler, final BuildParameter... params) throws DockerException, InterruptedException, IOException { checkNotNull(handler, "handler"); WebTarget resource = resource().path("build"); for (final BuildParameter param : params) { resource = resource.queryParam(param.queryParam, String.valueOf(param.value)); } if (name != null) { resource = resource.queryParam("t", name); } try (final CompressedDirectory compressedDirectory = CompressedDirectory.create(directory); final InputStream fileStream = Files.newInputStream(compressedDirectory.file()); final ProgressStream build = request(POST, ProgressStream.class, resource, resource.request(APPLICATION_JSON_TYPE), Entity.entity(fileStream, "application/tar"))) { String imageId = null; while (build.hasNextMessage(POST, resource.getUri())) { final ProgressMessage message = build.nextMessage(POST, resource.getUri()); final String id = message.buildImageId(); if (id != null) { imageId = id; } handler.progress(message); } return imageId; } }
Source:
<code>public boolean tryLock(HoldType type) { <START> while (true) { <END> LockTransition transition = invoke(LockMessaging.tryLock(type)); if (transition.isAcquired()) { currentState = LockMessaging.lock(type); return true; } else { return false; } } }</code><technical_language>loops</technical_language>

Target:
public boolean tryLock(HoldType type) { LockTransition transition = invoke(LockMessaging.tryLock(type)); if (transition.isAcquired()) { currentState = LockMessaging.lock(type); return true; } else { return false; } }
Source:
<code>public void setUp(){ <START> final String directoryPath = TARGET_DIR + "cucumber-html-reports/embeddings"; <END> final File dir = new File(directoryPath); if (!dir.exists()) { final boolean created = dir.mkdirs(); if (!created) { Assert.fail("Could not create folder " + directoryPath); } } configuration = new Configuration(new File(TARGET_DIR),"TestProject"); }</code><technical_language>reuse <LINK_0></technical_language>

Target:
public void setUp() { final String directoryPath = RANDOM_DIR + ReportBuilder.BASE_DIRECTORY + "/embeddings"; final File dir = new File(directoryPath); if (!dir.exists()) { final boolean created = dir.mkdirs(); if (!created) { Assert.fail("Could not create folder " + directoryPath); } } configuration = new Configuration(new File(RANDOM_DIR), "TestProject"); }
Source:
<code>private static void AddEventNotificationEntry(EventNotificationEntity entity, AuditLogType auditLogType) { HashSet<AuditLogType> entry; if (!_eventNotificationTypeMap.containsKey(entity)) { _eventNotificationTypeMap.put(entity, new HashSet<AuditLogType>()); } entry = _eventNotificationTypeMap.get(entity); <START> entry.add(auditLogType); <END> }</code><technical_language>In order contains get methods, I prefer code: HashSet<AuditLogType> entry = _eventNotificationTypeMap.get(entity); if (entry == null) { entry = new HashSet<AuditLogType>(); _eventNotificationTypeMap.put(entity, entry); } entry.add(auditLogType);</technical_language>

Target:
private static void AddEventNotificationEntry(EventNotificationEntity entity, AuditLogType auditLogType) { HashSet<AuditLogType> entry = _eventNotificationTypeMap.get(entity); if (entry == null) { entry = new HashSet<AuditLogType>(); _eventNotificationTypeMap.put(entity, entry); } entry.add(auditLogType); }
Source:
<code>protected Cookie(byte[] cookieBytes) { if (cookieBytes == null || cookieBytes.length == 0) { <START> throw new IllegalArgumentException("Invalid value for cookieBytes passes to Cookie constructor"); END> } ByteBuffer byteBuffer = ByteBuffer.wrap(cookieBytes); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); byteBuffer.position(byteBuffer.position() + COOKIE_HEAD_SKIP); int urlOffset = byteBuffer.getInt(); int nameOffset = byteBuffer.getInt(); int pathOffset = byteBuffer.getInt(); int valueOffset = byteBuffer.getInt(); byteBuffer.getLong(); expirationDate = byteBuffer.getDouble(); creationDate = byteBuffer.getDouble(); url = decodeString(cookieBytes, urlOffset); name = decodeString(cookieBytes, nameOffset); path = decodeString(cookieBytes, pathOffset); value = decodeString(cookieBytes, valueOffset); }</code><technical_language>"passed" instead of "passes"</technical_language>

Target:
protected Cookie(byte[] cookieBytes) { if (cookieBytes == null || cookieBytes.length == 0) { throw new IllegalArgumentException("Invalid value for cookieBytes passed to Cookie constructor"); } ByteBuffer byteBuffer = ByteBuffer.wrap(cookieBytes); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); byteBuffer.position(byteBuffer.position() + COOKIE_HEAD_SKIP); int urlOffset = byteBuffer.getInt(); int nameOffset = byteBuffer.getInt(); int pathOffset = byteBuffer.getInt(); int valueOffset = byteBuffer.getInt(); byteBuffer.getLong(); expirationDate = byteBuffer.getDouble(); creationDate = byteBuffer.getDouble(); url = decodeString(cookieBytes, urlOffset); name = decodeString(cookieBytes, nameOffset); path = decodeString(cookieBytes, pathOffset); value = decodeString(cookieBytes, valueOffset); }
Source:
<code><START> public static <V> MapStream<V, V> of(Collection<V> collection) { return of(collection.stream(), key -> key); } <END></code><technical_language>add other option of MapStream.of(Stream<V> stream) delegate that</technical_language>

Target:
public static <V> MapStream<V, V> of(Collection<V> collection) { return of(collection.stream()); }
Source:
<code>RequestBuilder createRequest() { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, restApiBaseUrl); requestBuilder.setHeader("Prefer", "persistent-auth, csrf-protection"); requestBuilder.setHeader("Session-TTL", getSessionTimeout()); <START> if (restApiSessionId != null) { <END> requestBuilder.setHeader(SESSION_ID_HEADER, restApiSessionId); } return requestBuilder; }</code><technical_language>Minor thing, prefer getSessionId() instead of accessing "restApiSessionId" field here, for example: String sessionId = getSessionId(); if (sessionId != null) { requestBuilder.setHeader(SESSION_ID_HEADER, sessionId); }</technical_language>

Target:
RequestBuilder createRequest() { RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, restApiBaseUrl); requestBuilder.setHeader("Prefer", "persistent-auth, csrf-protection"); requestBuilder.setHeader("Session-TTL", getSessionTimeout()); String sessionId = getSessionId(); if (sessionId != null) { requestBuilder.setHeader(SESSION_ID_HEADER, sessionId); } return requestBuilder; }
Source:
<code>public void stop() { connectLock.lock(); try { <START> super.stop(); <END> createdStores.clear(); } finally { connectLock.unlock(); } }</code><technical_language>super.stop() in a finally block</technical_language>

Target:
public void stop() { connectLock.lock(); try { createdStores.clear(); } finally { connectLock.unlock(); super.stop(); } }
Source:
<code>private void validateDatasetFieldValues(List<DatasetField> fields) throws JsonParseException { String errors = ""; for (DatasetField dsf : fields) { if (dsf.getDatasetFieldType().isAllowMultiples() && dsf.getControlledVocabularyValues().isEmpty() && dsf.getDatasetFieldCompoundValues().isEmpty() && dsf.getDatasetFieldValues().isEmpty()) { <START> errors += "Empty multiple value for field " + dsf.getDatasetFieldType().getDisplayName() + " "; <END> } else if (!dsf.getDatasetFieldType().isAllowMultiples() && dsf.getSingleValue().getValue().isEmpty()) { errors += "Empty value for field " + dsf.getDatasetFieldType().getDisplayName() + " "; } } if (!errors.isEmpty()) { throw new JsonParseException(errors + " If you would like to delete values please add the parameter replace=true."); } }</code><technical_language>StringBuilder avoid bad perf in case of errors</technical_language>

Target:
private String validateDatasetFieldValues(List<DatasetField> fields) { StringBuilder error = new StringBuilder(); for (DatasetField dsf : fields) { if (dsf.getDatasetFieldType().isAllowMultiples() && dsf.getControlledVocabularyValues().isEmpty() && dsf.getDatasetFieldCompoundValues().isEmpty() && dsf.getDatasetFieldValues().isEmpty()) { error.append("Empty multiple value for field: ").append(dsf.getDatasetFieldType().getDisplayName()).append(" "); } else if (!dsf.getDatasetFieldType().isAllowMultiples() && dsf.getSingleValue().getValue().isEmpty()) { error.append("Empty value for field: ").append(dsf.getDatasetFieldType().getDisplayName()).append(" "); } } if (!error.toString().isEmpty()) { return (error.toString()); } return ""; }
Source:
<code>public Flux<PartitionEvent> receiveFromPartition(String partitionId, EventPosition startingPosition, ReceiveOptions receiveOptions) { if (Objects.isNull(partitionId)) { <START> return Flux.error(logger.logExceptionAsError(new NullPointerException("'partitionId' cannot be null."))); <END> } else if (partitionId.isEmpty()) { return Flux.error(logger.logExceptionAsError( new IllegalArgumentException("'partitionId' cannot be an empty string."))); } if (Objects.isNull(startingPosition)) { return Flux.error((logger.logExceptionAsError( new NullPointerException("'startingPosition' cannot be null.")))); } final String linkName = StringUtil.getRandomString(partitionId); return createConsumer(linkName, partitionId, startingPosition, receiveOptions); }</code><technical_language>azure-core a convenience method fluxError for this</technical_language>

Target:
public Flux<PartitionEvent> receiveFromPartition(String partitionId, EventPosition startingPosition, ReceiveOptions receiveOptions) { if (Objects.isNull(partitionId)) { return fluxError(logger, new NullPointerException("'partitionId' cannot be null.")); } else if (partitionId.isEmpty()) { return fluxError(logger, new IllegalArgumentException("'partitionId' cannot be an empty string.")); } if (Objects.isNull(startingPosition)) { return fluxError(logger, new NullPointerException("'startingPosition' cannot be null.")); } final String linkName = StringUtil.getRandomString(partitionId); return createConsumer(linkName, partitionId, startingPosition, receiveOptions); }
Source:
<code>public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } logger.info("Number of intra DC replica threads: " + replicationConfig.replicationNumOfIntraDCReplicaThreads); logger.info("Number of intra DC nodes to replicate from: " + replicasToReplicateIntraDC.size()); assignReplicasToThreads(replicasToReplicateIntraDC, replicationConfig.replicationNumOfIntraDCReplicaThreads, <START> replicationIntraDCThreads, "Intra DC", dataNodeId.getDatacenterName()); <END> logger.trace("Assigning thread pools for Inter DC replication"); assignReplicasToThreadPools(replicasToReplicateInterDC, replicationConfig.replicationNumOfInterDCReplicaThreads); for (ReplicaThread thread : replicationIntraDCThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting intra DC replica thread " + thread.getName()); replicaThread.start(); } for (String datacenter : replicaThreadPools.keySet()) { for (ReplicaThread thread : replicaThreadPools.get(datacenter)) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting inter DC replica thread " + thread.getName()); replicaThread.start(); } } this.scheduler.schedule("replica token persistor", persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }</code><technical_language>dataNodeId.getDatacenterName() redundant information</technical_language>

Target:
public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } this.scheduler.schedule("replica token persistor", persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }
Source:
<code>public List<ProjectDTO> getProjectDTOListAsWorkspaceCollaborator(String sUserName) throws QuadrigaStorageException { List<ProjectDTO> projectDTOList = null; try { Query query = sessionFactory .getCurrentSession() .createQuery( "Select projWork.projectDTO from ProjectWorkspaceDTO projWork where projWork.workspaceDTO in (Select wcDTO.workspaceDTO from WorkspaceCollaboratorDTO wcDTO where wcDTO.collaboratorDTOPK.collaboratoruser = :collaboratoruser)"); query.setParameter("collaboratoruser", sUserName); projectDTOList = query.list(); for(ProjectDTO projectDTO :projectDTOList){ System.out.println("Project ID: "+projectDTO.getId()+" , Project Name: "+projectDTO.getProjectname()+" , "+projectDTO.getProjectWorkspaceDTOList().size()); <START> } <END> } catch (Exception e) { logger.info("getProjectListAsWorkspaceCollaborator method :" + e.getMessage()); throw new QuadrigaStorageException(e); } return projectDTOList; }</code><technical_language>remove!!!! please sysout (unless remove right check wanted check)</technical_language>

Target:
public List<ProjectDTO> getProjectDTOListAsWorkspaceCollaborator(String sUserName) throws QuadrigaStorageException { List<ProjectDTO> projectDTOList = null; try { Query query = sessionFactory .getCurrentSession() .createQuery( "Select projWork.projectDTO from ProjectWorkspaceDTO projWork where projWork.workspaceDTO in (Select wcDTO.workspaceDTO from WorkspaceCollaboratorDTO wcDTO where wcDTO.collaboratorDTOPK.collaboratoruser = :collaboratoruser)"); query.setParameter("collaboratoruser", sUserName); projectDTOList = query.list(); } catch (Exception e) { throw new QuadrigaStorageException(e); } return projectDTOList; }
Source:
<code>private void free(FileEntry fe) throws IOException { if (fe != null) { <START> fe.waitUnlocked(); <END> channel.write(ByteBuffer.wrap(ZERO_INT), fe.offset + KEYLEN_POS); if (!freeList.add(fe)) { throw new IllegalStateException(String.format("Trying to free an entry that was not allocated: %s", fe)); } if (trace) log.tracef("Deleted entry at %d:%d, there are now %d free entries", fe.offset, fe.size, freeList.size()); } }</code><technical_language>explain a bit this worked: free() overwrites key length disk, FileEntry in memory remains untouched. operation need wait for readers finish clear(), truncated file, for readers finish reading values a clear. changes, truncateFile() mergeFreeEntries() skip locked entries, I expect working waitUnlocked() call here</technical_language>

Target:
private void free(FileEntry fe) throws IOException { if (fe != null) { channel.write(ByteBuffer.wrap(ZERO_INT), fe.offset + KEYLEN_POS); if (!freeList.add(fe)) { throw new IllegalStateException(String.format("Trying to free an entry that was not allocated: %s", fe)); } if (trace) log.tracef("Deleted entry at %d:%d, there are now %d free entries", fe.offset, fe.size, freeList.size()); } }
Source:
<code>static void submitComments( AbstractBuild<?, ?> build, PrintStream logger, String jenkinsRootUrl, List<JiraIssue> issues, JiraSession session, boolean useWikiStyleComments, boolean recordScmChanges, String groupVisibility, String roleVisibility) throws RemoteException { List<JiraIssue> copy = new ArrayList<JiraIssue>(issues); StringBuilder issuesWithExceptions = new StringBuilder(); for (JiraIssue issue : copy) { logger.println(Messages.Updater_Updating(issue.id)); try { session.addComment( issue.id, createComment(build, useWikiStyleComments, jenkinsRootUrl, recordScmChanges, issue), groupVisibility, roleVisibility); <START> } catch (RemotePermissionException e) { <END> logger.println("Looks like " + issue.id + " is no valid JIRA issue or you don't have permission to update the issue.\n" + "Issue will not be updated.\n" + e); } catch (RemoteException e) { if( 0 < issuesWithExceptions.length()) { issuesWithExceptions.append(", "); } issuesWithExceptions.append(issue.id); logger.println(e.getLocalizedMessage()); logger.println(Messages.Updater_FailedToCommentOnIssue(issue.id)); continue; } issues.remove(issue); } if( 0 < issuesWithExceptions.length() ) { throw new RemoteException(Messages.Updater_ErrorCommentingIssues(issuesWithExceptions.toString())); } }</code><technical_language>issues well</technical_language>

Target:
static void submitComments( AbstractBuild<?, ?> build, PrintStream logger, String jenkinsRootUrl, List<JiraIssue> issues, JiraSession session, boolean useWikiStyleComments, boolean recordScmChanges, String groupVisibility, String roleVisibility) throws RemoteException { List<JiraIssue> copy = new ArrayList<JiraIssue>(issues); StringBuilder issuesWithExceptions = new StringBuilder(); for (JiraIssue issue : copy) { logger.println(Messages.Updater_Updating(issue.id)); try { session.addComment( issue.id, createComment(build, useWikiStyleComments, jenkinsRootUrl, recordScmChanges, issue), groupVisibility, roleVisibility); } catch (RemotePermissionException e) { logger.println("Looks like " + issue.id + " is no valid JIRA issue or you don't have permission to update the issue.\n" + "Issue will not be updated.\n" + e); } catch (RemoteException e) { if( issuesWithExceptions.length() > 0) { issuesWithExceptions.append(", "); } issuesWithExceptions.append(issue.id); logger.println(e.getLocalizedMessage()); logger.println(Messages.Updater_FailedToCommentOnIssue(issue.id)); continue; } issues.remove(issue); } if( issuesWithExceptions.length() > 0) { throw new RemoteException(Messages.Updater_ErrorCommentingIssues(issuesWithExceptions.toString())); } }
Source:
<code>public void update(Subscription newSubscription) { <START> this.subscription = subscription; <END> }</code><technical_language>[FindBugs] WARNING: SA: assignment of field KafkaSingleThreadedMessageReceiver.subscription in pl.allegro.tech.hermes.consumers.consumer.receiver.kafka.KafkaSingleThreadedMessageReceiver.update(Subscription)</technical_language>

Target:
public void update(Subscription newSubscription) { this.subscription = newSubscription; }
Source:
<code>Path getOrDefaultConfigurationDirectory(String configPath) { <START> return configPath != null ? Paths.get(configPath) : ((RawPath)Setting.NODE_CONFIG_DIR.getDefaultValue()).toPath(); <END> }</code><technical_language>do need cast: add a type that: Setting.NODE_CONFIG_DIR.<RawPath>getDefaultValue().toPath()</technical_language>

Target:
Path getOrDefaultConfigurationDirectory(String configPath) { return configPath != null ? Paths.get(configPath) : Setting.NODE_CONFIG_DIR.<RawPath>getDefaultValue().toPath(); }
Source:
<code>public List<AuditEvent> getEvents(int start, int number, String action, String userId, String ip, String entityId, String fromTime, String toTime) { if (this.auth.hasAccess(this.users.getCurrentUser(), Right.ADMIN, this.resolver.resolve(Constants.XWIKI_SPACE_REFERENCE))) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Calendar from = Calendar.getInstance(); try { from.setTime(sdf.parse(fromTime)); } catch (Exception e) { from.setTimeInMillis(0); } Calendar to = Calendar.getInstance(); try { <START> if (to.after(from)) { <END> to.setTime(sdf.parse(toTime)); } else { to.setTimeInMillis(System.currentTimeMillis()); } } catch (Exception e) { to.setTimeInMillis(System.currentTimeMillis()); } DocumentReference entity = entityId != null ? this.resolverd.resolve(entityId) : null; User user = userId != null ? this.users.getUser(userId) : null; String actionId = StringUtils.isNotBlank(action) ? action : null; String ipValue = StringUtils.isNotBlank(ip) ? ip : null; AuditEvent eventTemplate = new AuditEvent(user, ipValue, actionId, null, entity, null); return this.store.getEvents(eventTemplate, from, to, start, number); } return Collections.emptyList(); }</code><technical_language>I understand this check. If "now" is "from", set upper limit requested time? set upper limit requested time</technical_language>

Target:
public List<AuditEvent> getEvents(int start, int number, String action, String userId, String ip, String entityId, String fromTime, String toTime) { if (this.auth.hasAccess(this.users.getCurrentUser(), Right.ADMIN, this.resolver.resolve(Constants.XWIKI_SPACE_REFERENCE))) { Calendar from = null; try { Date d = DATE_FORMAT.parse(fromTime); from = Calendar.getInstance(); from.setTime(d); } catch (Exception e) { } Calendar to = null; try { Date d = DATE_FORMAT.parse(toTime); to = Calendar.getInstance(); to.setTime(d); } catch (Exception e) { } DocumentReference entity = entityId != null ? this.resolverd.resolve(entityId) : null; User user = userId != null ? this.users.getUser(userId) : null; String actionId = StringUtils.isNotBlank(action) ? action : null; String ipValue = StringUtils.isNotBlank(ip) ? ip : null; AuditEvent eventTemplate = new AuditEvent(user, ipValue, actionId, null, entity, null); return this.store.getEvents(eventTemplate, from, to, start, number); } return Collections.emptyList(); }
Source:
<code>private void fetchCenterDetails() { <START> presenter.loadCenterDetails("dd MMMM yyyy", "en", <END> tvMeetingDate.getText().toString(), officeId, staffId); }</code><technical_language>pass string this put this in Constants.java it</technical_language>

Target:
private void fetchCenterDetails() { presenter.loadCenterDetails(Constants.DATE_FORMAT_LONG, Constants.LOCALE_EN, tvMeetingDate.getText().toString(), officeId, staffId); }
Source:
<code>public void makeSureConcurrentDownloadisNotSerialized() throws Exception { String baseUrl = AbstractNexusIntegrationTest.nexusBaseUrl + REPOSITORY_RELATIVE_URL + REPO_TEST_HARNESS_REPO + "/"; String path = getRelitiveArtifactPath( gav ); final URL url = new URL( baseUrl + path ); final long op = ping( url ); final Long[] time = new Long[1]; final Throwable[] errors = new Throwable[1]; Thread t = new Thread( new Runnable() { public void run() { try { long t = System.currentTimeMillis(); read( url, 100 ); time[0] = System.currentTimeMillis() - t; } catch ( Exception e ) { errors[0] = e; time[0] = -1L; } } } ); t.setUncaughtExceptionHandler( new UncaughtExceptionHandler() { public void uncaughtException( Thread t, Throwable e ) { errors[0] = e; } } ); t.setDaemon( true ); t.start(); for ( int i = 0; i < 10; i++ ) { Thread.yield(); Thread.sleep( 1 ); } final long ping = ping( url ); <START> assertTrue( ping < ( op * 2 ), "Ping took " + ping + " original pind " + op ); <END> if ( time[0] != null ) { assertTrue( ping < time[0], "Ping took " + ping + " dl time: " + time[0] ); } assertThat( t.getState(), not( equalTo( State.TERMINATED ) ) ); if ( errors[0] != null ) { ByteArrayOutputStream str = new ByteArrayOutputStream(); PrintStream s = new PrintStream( str ); for ( Throwable e : errors ) { e.printStackTrace( s ); s.append( "\n" ); s.append( "\n" ); } Assert.fail( "Found some errors downloading:\n" + str.toString() ); } t.stop(); }</code><technical_language>avoid junit testng Assert.\* fail(), hamcrest assertThat instead</technical_language>

Target:
public void makeSureConcurrentDownloadisNotSerialized() throws Exception { String baseUrl = AbstractNexusIntegrationTest.nexusBaseUrl + REPOSITORY_RELATIVE_URL + REPO_TEST_HARNESS_REPO + "/"; String path = getRelitiveArtifactPath( gav ); final URL url = new URL( baseUrl + path ); final long op = clockUrlDownload( url ); final Long[] time = new Long[1]; final Throwable[] errors = new Throwable[1]; Thread t = new Thread( new Runnable() { public void run() { try { time[0] = clockUrlDownload( url, 10 ); } catch ( Exception e ) { errors[0] = e; time[0] = -1L; } } } ); t.setUncaughtExceptionHandler( new UncaughtExceptionHandler() { public void uncaughtException( Thread t, Throwable e ) { errors[0] = e; } } ); t.setDaemon( true ); t.start(); for ( int i = 0; i < 10; i++ ) { Thread.yield(); Thread.sleep( 1 ); } final long ping = clockUrlDownload( url ); assertThat( "Ping took " + ping + " original pind " + op, ping, lessThan( op * 2 ) ); if ( time[0] != null ) { assertThat( "Ping took " + ping + " dl time: " + time[0], ping, lessThan( time[0] ) ); } assertThat( t.getState(), not( equalTo( State.TERMINATED ) ) ); if ( errors[0] != null ) { ByteArrayOutputStream str = new ByteArrayOutputStream(); PrintStream s = new PrintStream( str ); for ( Throwable e : errors ) { e.printStackTrace( s ); s.append( "\n" ); s.append( "\n" ); } assertThat( "Found some errors downloading:\n" + str.toString(), false ); } stop( t ); }
Source:
<code>public void testNestedGetTags() throws Exception { class DebugGetTagsHandler implements OneSignal.GetTagsHandler { boolean executed = false; @Override public void tagsAvailable(JSONObject tags) { OneSignal.getTags(new OneSignal.GetTagsHandler() { @Override public void tagsAvailable(JSONObject tags) { <START> <END> } }); executed = true; } } OneSignalInit(); threadAndTaskWait(); DebugGetTagsHandler first = new DebugGetTagsHandler(); OneSignal.getTags(first); threadAndTaskWait(); }</code><technical_language>Hmm this test fail. outer tagsAvailable callbacks fire</technical_language>

Target:
public void testNestedGetTags() throws Exception { class DebugGetTagsHandler implements OneSignal.GetTagsHandler { boolean executed = false; @Override public void tagsAvailable(JSONObject tags) { OneSignal.getTags(new OneSignal.GetTagsHandler() { @Override public void tagsAvailable(JSONObject tags) { } }); executed = true; } } OneSignalInit(); threadAndTaskWait(); OneSignal.sendTag("test", "value"); threadAndTaskWait(); DebugGetTagsHandler first = new DebugGetTagsHandler(); DebugGetTagsHandler second = new DebugGetTagsHandler(); OneSignal.getTags(first); OneSignal.getTags(second); threadAndTaskWait(); assertTrue(first.executed); assertTrue(second.executed); }
Source:
<code><START> public void calculatePipelineRoutes(Task task, final Route route, List<Route> allRoutes) { <END> if (task.getDownstreamTasks() != null && task.getDownstreamTasks().size() > 0) { for (String downstreamTaskName: task.getDownstreamTasks()) { Route currentRoute = createRouteAndCopyTasks(route, task); calculatePipelineRoutes(getTaskFromName(downstreamTaskName), currentRoute, allRoutes); } } else { Route currentRoute = createRouteAndCopyTasks(route, task); allRoutes.add(currentRoute); } }</code><technical_language>this method public</technical_language>

Target:
void calculatePipelineRoutes(Task task, final Route route, List<Route> allRoutes) { if (task.getDownstreamTasks() != null && task.getDownstreamTasks().size() > 0) { for (String downstreamTaskName: task.getDownstreamTasks()) { Route currentRoute = createRouteAndCopyTasks(route, task); calculatePipelineRoutes(getTaskFromName(downstreamTaskName), currentRoute, allRoutes); } } else { Route currentRoute = createRouteAndCopyTasks(route, task); allRoutes.add(currentRoute); } }
Source:
<code>public void setOutOfServiceProxy( final String repoId, final boolean outOfService ) throws Exception { RepositoryStatusResource status = new RepositoryStatusResource(); status.setId( repoId ); status.setRepoType( "proxy" ); if ( outOfService ) { status.setLocalStatus( LocalStatus.OUT_OF_SERVICE.name() ); } else { status.setLocalStatus( LocalStatus.IN_SERVICE.name() ); } <START> Response response = RepositoryStatusMessageUtil.changeStatus( status ); <END> assertThat( "Could not set proxy out of service status (Status: " + response.getStatus() + ": " + repoId + "\n" + response.getEntity().getText(), response, isSuccessful() ); TaskScheduleUtil.waitForAllTasksToStop(); getTest().getEventInspectorsUtil().waitForCalmPeriod(); }</code><technical_language>set free</technical_language>

Target:
public void setOutOfServiceProxy( final String repoId, final boolean outOfService ) throws Exception { RepositoryStatusResource status = new RepositoryStatusResource(); status.setId( repoId ); status.setRepoType( "proxy" ); if ( outOfService ) { status.setLocalStatus( LocalStatus.OUT_OF_SERVICE.name() ); } else { status.setLocalStatus( LocalStatus.IN_SERVICE.name() ); } Response response = RepositoryStatusMessageUtil.changeStatus( status ); try { assertThat( "Could not set proxy out of service status (Status: " + response.getStatus() + ": " + repoId + "\n" + response.getEntity().getText(), response, isSuccessful() ); } finally { RequestFacade.releaseResponse( response ); } TaskScheduleUtil.waitForAllTasksToStop(); getTest().getEventInspectorsUtil().waitForCalmPeriod(); }
Source:
<code>Flux<BlobChangefeedEventWrapper> getEvents() { return client.getBlobAsyncClient(path) <START> .download().reduce(new ByteArrayOutputStream(), (os, buffer) -> { <END> try { os.write(FluxUtil.byteBufferToArray(buffer)); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } return os; }) .map(ByteArrayOutputStream::toString) .map(json -> { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = null; try { jsonNode = objectMapper.readTree(json); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } List<Flux<BlobChangefeedEventWrapper>> shards = new ArrayList<>(); for (JsonNode shard : jsonNode.withArray("chunkFilePaths")) { String shardPath = shard.asText().substring(BlobChangefeedAsyncClient.CHANGEFEED_CONTAINER_NAME.length() + 1); shards.add(new Shard(client, shardPath, cfCursor.toShardCursor(shardPath), userCursor).getEvents()); } return shards; }) .flatMapMany(this::roundRobinAmongShards); }</code><technical_language>worth throwing this download->reduce->map stuff in a shared method</technical_language>

Target:
Flux<BlobChangefeedEventWrapper> getEvents() { return DownloadUtils.downloadToString(client, path) .map(json -> { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = null; try { jsonNode = objectMapper.readTree(json); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } List<Flux<BlobChangefeedEventWrapper>> shards = new ArrayList<>(); for (JsonNode shard : jsonNode.withArray("chunkFilePaths")) { String shardPath = shard.asText().substring(BlobChangefeedAsyncClient.CHANGEFEED_CONTAINER_NAME.length() + 1); shards.add(new Shard(client, shardPath, cfCursor.toShardCursor(shardPath), userCursor).getEvents()); } return shards; }) .flatMapMany(this::roundRobinAmongShards); }
Source:
<code>public void experimentSelected(TmfExperimentSelectedSignal signal) { if (signal != null) { if (fExperiment == null || signal.getExperiment().toString().compareTo(fExperiment.toString()) != 0) { if (fStatsViewers != null) { fStatsViewers.dispose(); } fExperiment = signal.getExperiment(); fStatsViewers = createStatisticsViewers(); fParent.layout(); TmfStatisticsViewer statViewer; for (ITmfViewer viewer : fStatsViewers.getViewers()) { <START> statViewer = (TmfStatisticsViewer) viewer; <END> setInput(statViewer, fExperiment.getTraces()); } if (fRequestData) { TmfExperimentRangeUpdatedSignal updateSignal = new TmfExperimentRangeUpdatedSignal(null, fExperiment, fExperiment.getTimeRange()); TmfStatisticsViewer statsViewer; for (ITmfViewer viewer : fStatsViewers.getViewers()) { statsViewer = (TmfStatisticsViewer) viewer; statsViewer.experimentRangeUpdated(updateSignal); } fRequestData = false; } } } }</code><technical_language>This cast pretty... discussed, a generic type for TmfViewerFolder worth it, ensure type-safety. worse/in meantime, do instanceof check casting</technical_language>

Target:
public void experimentSelected(TmfExperimentSelectedSignal signal) { if (signal != null) { if (fExperiment == null || signal.getExperiment().toString().compareTo(fExperiment.toString()) != 0) { fStatsViewers.clear(); fExperiment = signal.getExperiment(); createStatisticsViewers(); fStatsViewers.layout(); TmfStatisticsViewer statViewer; for (ITmfViewer viewer : fStatsViewers.getViewers()) { statViewer = (TmfStatisticsViewer) viewer; setInput(statViewer, fExperiment.getTraces()); } if (fRequestData) { TmfExperimentRangeUpdatedSignal updateSignal = new TmfExperimentRangeUpdatedSignal(null, fExperiment, fExperiment.getTimeRange()); TmfStatisticsViewer statsViewer; for (ITmfViewer viewer : fStatsViewers.getViewers()) { statsViewer = (TmfStatisticsViewer) viewer; statsViewer.experimentRangeUpdated(updateSignal); } fRequestData = false; } } } }
Source:
<code>public String checkFileContent(File content){ if(checkWDL(content)){ <START> return "wdl"; <END> }else if(checkCWL(content)){ return "cwl"; } return null; }</code><technical_language>Enum</technical_language>

Target:
public Type checkFileContent(File content){ if(checkWDL(content)){ return Type.WDL; }else if(checkCWL(content)){ return Type.CWL; } return Type.NONE; }
Source:
<code>public static Object readValue( ValueMetaInterface meta, Row row, int i ) { <START> if (row.isNull( i ) ) { <END> return null; } switch ( meta.getType() ) { case ValueMetaInterface.TYPE_INTEGER: case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_BIGNUMBER: case ValueMetaInterface.TYPE_BOOLEAN: case ValueMetaInterface.TYPE_DATE: case ValueMetaInterface.TYPE_BINARY: ColumnDefinitions cdef = row.getColumnDefinitions(); switch( cdef.getType( i ).getName() ) { case BIGINT: case COUNTER: return row.getLong( i ); case SMALLINT: return new Long( row.getShort( i ) ); case TINYINT: return new Long( row.getByte( i ) ); case INT: return new Long( row.getInt( i ) ); case FLOAT: return new Double( row.getFloat( i ) ); case DOUBLE: return row.getDouble( i ); case DECIMAL: return row.getDecimal( i ); case VARINT: return new BigDecimal( row.getVarint( i ) ); case BOOLEAN: return row.getBool( i ); case DATE: return new Date( row.getDate( i ).getMillisSinceEpoch() ); case TIMESTAMP: return row.getTimestamp( i ); case TIME: return row.getTime( i ); case BLOB: return row.getBytes( i ).array(); default: return row.getObject( i ); } default: return row.getObject( i ); } }</code><technical_language>this fail checkstyle right off. if (row..... if ( row ..... Please run site target in Maven get checkstyle output navigate target/site folder open checkstyle.html violations in PR. This line fail</technical_language>

Target:
public static Object readValue( ValueMetaInterface meta, Row row, int i ) { if ( row.isNull( i ) ) { return null; } switch ( meta.getType() ) { case ValueMetaInterface.TYPE_INTEGER: case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_BIGNUMBER: case ValueMetaInterface.TYPE_BOOLEAN: case ValueMetaInterface.TYPE_DATE: case ValueMetaInterface.TYPE_BINARY: ColumnDefinitions cdef = row.getColumnDefinitions(); switch ( cdef.getType( i ).getName() ) { case BIGINT: case COUNTER: return row.getLong( i ); case SMALLINT: return (long) row.getShort( i ); case TINYINT: return (long) row.getByte( i ); case INT: return (long) row.getInt( i ); case FLOAT: return (double) row.getFloat( i ); case DOUBLE: return row.getDouble( i ); case DECIMAL: return row.getDecimal( i ); case VARINT: return new BigDecimal( row.getVarint( i ) ); case BOOLEAN: return row.getBool( i ); case DATE: return new Date( row.getDate( i ).getMillisSinceEpoch() ); case TIMESTAMP: return row.getTimestamp( i ); case TIME: return row.getTime( i ); case BLOB: return row.getBytes( i ).array(); default: return row.getObject( i ); } default: return row.getObject( i ); } }
Source:
<code>public EVCacheLatch add(EVCacheKey evcKey, final CachedData cd, Transcoder evcacheValueTranscoder, int timeToLive, Policy policy) throws Exception { if (cd == null) return null; final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); final EVCacheLatchImpl latch = new EVCacheLatchImpl(policy, clients.length - _pool.getWriteOnlyEVCacheClients().length, _appName); <START> <END> Boolean firstStatus = null; for (EVCacheClient client : clients) { CachedData cd1 = null; if (evcKey.getHashKey(client.isDuetClient(), client.getHashingAlgorithm()) != null) { final EVCacheValue val = new EVCacheValue(evcKey.getCanonicalKey(client.isDuetClient()), cd.getData(), cd.getFlags(), timeToLive, System.currentTimeMillis()); cd1 = evcacheValueTranscoder.encode(val); } else { cd1 = cd; } String key = evcKey.getDerivedKey(client.isDuetClient(), client.getHashingAlgorithm()); final Future<Boolean> f = client.add(key, timeToLive, cd1, latch); if (log.isDebugEnabled()) log.debug("ADD : Op Submitted : APP " + _appName + ", key " + key + "; future : " + f + "; client : " + client); boolean status = f.get().booleanValue(); if(!status) { if(firstStatus == null) { for(int i = 0; i < clients.length; i++) { latch.countDown(); } return latch; } else { return fixup(client, clients, evcKey, timeToLive, policy); } } if(firstStatus == null) firstStatus = Boolean.valueOf(status); } return latch; }</code><technical_language>good. is encode in some situations for add esp if mixed algo some copies hashed some hashed</technical_language>

Target:
public EVCacheLatch add(EVCacheKey evcKey, final CachedData cd, Transcoder evcacheValueTranscoder, int timeToLive, Policy policy) throws Exception { if (cd == null) return null; final EVCacheClient[] clients = _pool.getEVCacheClientForWrite(); final EVCacheLatchImpl latch = new EVCacheLatchImpl(policy, clients.length - _pool.getWriteOnlyEVCacheClients().length, _appName); Boolean firstStatus = null; for (EVCacheClient client : clients) { CachedData cd1 = null; if (evcKey.getHashKey(client.isDuetClient(), client.getHashingAlgorithm(), client.shouldEncodeHashKey(), client.getMaxHashingBytes()) != null) { final EVCacheValue val = new EVCacheValue(evcKey.getCanonicalKey(client.isDuetClient()), cd.getData(), cd.getFlags(), timeToLive, System.currentTimeMillis()); cd1 = evcacheValueTranscoder.encode(val); } else { cd1 = cd; } String key = evcKey.getDerivedKey(client.isDuetClient(), client.getHashingAlgorithm(), client.shouldEncodeHashKey(), client.getMaxHashingBytes()); final Future<Boolean> f = client.add(key, timeToLive, cd1, latch); if (log.isDebugEnabled()) log.debug("ADD : Op Submitted : APP " + _appName + ", key " + key + "; future : " + f + "; client : " + client); boolean status = f.get().booleanValue(); if(!status) { if(firstStatus == null) { for(int i = 0; i < clients.length; i++) { latch.countDown(); } return latch; } else { return fixup(client, clients, evcKey, timeToLive, policy); } } if(firstStatus == null) firstStatus = Boolean.valueOf(status); } return latch; }
Source:
<code>protected Promise<Void> makeMenuBar() { scenarioSimulationEditorPresenter.makeMenuBar(fileMenuBuilder); if (workbenchContext.getActiveWorkspaceProject().isPresent()) { final WorkspaceProject activeProject = workbenchContext.getActiveWorkspaceProject().orElseThrow(IllegalStateException::new); return projectController.canUpdateProject(activeProject).then(canUpdateProject -> { <START> if (Boolean.TRUE.equals(canUpdateProject)) { <END> addSave(fileMenuBuilder); addCopy(fileMenuBuilder); addRename(fileMenuBuilder); addDelete(fileMenuBuilder); } addDownloadMenuItem(fileMenuBuilder); addCommonActions(fileMenuBuilder); setSaveEnabled(canUpdateProject); return promises.resolve(); }); } return promises.resolve(); }</code><technical_language>Is this needed? canUpdateProject null</technical_language>

Target:
protected Promise<Void> makeMenuBar() { scenarioSimulationEditorPresenter.makeMenuBar(fileMenuBuilder); if (workbenchContext.getActiveWorkspaceProject().isPresent()) { final WorkspaceProject activeProject = workbenchContext.getActiveWorkspaceProject().orElseThrow(IllegalStateException::new); return projectController.canUpdateProject(activeProject).then(canUpdateProject -> { if (Boolean.TRUE.equals(canUpdateProject)) { addSave(fileMenuBuilder); addCopy(fileMenuBuilder); addRename(fileMenuBuilder); addDelete(fileMenuBuilder); } addDownloadMenuItem(fileMenuBuilder); addCommonActions(fileMenuBuilder); return promises.resolve(); }); } return promises.resolve(); }
Source:
<code>public synchronized void processStreamControl(OperationMode operation) { switch (operation) { case RELEASE: if (isBlocked() && isMastershipAccepted() && m_gapTracker.getFirstGap() != null) { long firstUnpolledSeqNo = m_gapTracker.getFirstGap().getSecond() + 1; if (exportLog.isDebugEnabled()) { <START> exportLog.debug("Unblock " + this + " move firstUnpolledSeqNo from " + <END> m_firstUnpolledSeqNo + " to " + firstUnpolledSeqNo); } m_firstUnpolledSeqNo = firstUnpolledSeqNo; setStatus(StreamStatus.ACTIVE); } break; default: throw new IllegalArgumentException(operation + " is not a valid export control operation."); } }</code><technical_language>If admin command is 'release' want 'release' instead of 'unblock'</technical_language>

Target:
public synchronized void processStreamControl(OperationMode operation) { switch (operation) { case RELEASE: if (m_status == StreamStatus.BLOCKED && m_mastershipAccepted.get() && m_gapTracker.getFirstGap() != null) { long firstUnpolledSeqNo = m_gapTracker.getFirstGap().getSecond() + 1; if (exportLog.isDebugEnabled()) { exportLog.debug("Release " + this + " move firstUnpolledSeqNo from " + m_firstUnpolledSeqNo + " to " + firstUnpolledSeqNo); } m_firstUnpolledSeqNo = firstUnpolledSeqNo; setStatus(StreamStatus.ACTIVE); } break; default: } }