auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public DeferredResult<MergeCollection> searchMerge( @ApiParam(value="The source branch path to match") @RequestParam(value="source", required = false) final String source, @ApiParam(value="The target branch path to match") @RequestParam(value="target", required = false) final String target, @ApiParam(value="The current status of the request") @RequestParam(value="status", required = false) final Merge.Status status) { return DeferredResults.wrap(RepositoryRequests.merging() .prepareSearch() .filterBySource(source) .filterByTarget(target) <START> .filterByStatus(status.name()) <END> .build(repositoryId) .execute(bus)); }</code><technical_language>NPE status is query parameter</technical_language>

Target:
public DeferredResult<MergeCollection> searchMerge( @ApiParam(value="The source branch path to match") @RequestParam(value="source", required = false) final String source, @ApiParam(value="The target branch path to match") @RequestParam(value="target", required = false) final String target, @ApiParam(value="The current status of the request") @RequestParam(value="status", required = false) final Merge.Status status) { return DeferredResults.wrap(RepositoryRequests.merging() .prepareSearch() .filterBySource(source) .filterByTarget(target) .filterByStatus(status != null ? status.name() : null) .build(repositoryId) .execute(bus)); }
Source:
<code>private void processSurveys(final DatastoreService ds) { final Query q = new Query("SurveyGroup"); final PreparedQuery pq = ds.prepare(q); <START> for (Entity form : pq.asIterable(FetchOptions.Builder.withChunkSize(500))) { <END> Long id = form.getKey().getId(); String type = (String) form.getProperty("projectType"); String name = (String) form.getProperty("name"); if ("PROJECT".contentEquals(type)) { surveys.add(id); nameOfSurvey.put(id, name); } } }</code><technical_language>suggestion for (Entity survey : pq.asIterable(FetchOptions.Builder.withChunkSize(500))) {</technical_language>

Target:
private void processSurveys(final DatastoreService ds) { final Query q = new Query("SurveyGroup"); final PreparedQuery pq = ds.prepare(q); for (Entity survey : pq.asIterable(FetchOptions.Builder.withChunkSize(500))) { Long id = survey.getKey().getId(); String type = (String) survey.getProperty("projectType"); String name = (String) survey.getProperty("name"); if ("PROJECT".contentEquals(type)) { surveys.add(id); nameOfSurvey.put(id, name); } } }
Source:
<code>public MachineStateDescriptor createMachineFromRecipe(final RecipeMachineCreationMetadata machineFromRecipeMetadata) throws ServerException, ForbiddenException, NotFoundException { requiredNotNull(machineFromRecipeMetadata, "Machine description"); requiredNotNull(machineFromRecipeMetadata.getType(), "Machine type"); requiredNotNull(machineFromRecipeMetadata.getWorkspaceId(), "Workspace id"); <START> requiredNotNull(machineFromRecipeMetadata.getMachineRecipe(), "Recipe descriptor"); <END> requiredNotNull(machineFromRecipeMetadata.getMachineRecipe().getScript(), "Recipe script"); requiredNotNull(machineFromRecipeMetadata.getMachineRecipe().getType(), "Recipe type"); checkCurrentUserPermissions(machineFromRecipeMetadata.getWorkspaceId()); final MachineImpl machine = machineManager.create(machineFromRecipeMetadata); return toDescriptor(machine); }</code><technical_language>remove descriptor message descriptor anymore</technical_language>

Target:
public MachineStateDescriptor createMachineFromRecipe(final RecipeMachineCreationMetadata machineFromRecipeMetadata) throws ServerException, ForbiddenException, NotFoundException { requiredNotNull(machineFromRecipeMetadata, "Machine description"); requiredNotNull(machineFromRecipeMetadata.getType(), "Machine type"); requiredNotNull(machineFromRecipeMetadata.getWorkspaceId(), "Workspace id"); requiredNotNull(machineFromRecipeMetadata.getRecipe(), "Recipe"); requiredNotNull(machineFromRecipeMetadata.getRecipe().getScript(), "Recipe script"); requiredNotNull(machineFromRecipeMetadata.getRecipe().getType(), "Recipe type"); checkCurrentUserPermissions(machineFromRecipeMetadata.getWorkspaceId()); final MachineImpl machine = machineManager.create(machineFromRecipeMetadata); return toDescriptor(machine); }
Source:
<code>public void testLogEventWithMasking() { System.out.println("Note: the console will show the 'password' content when running this test."); Marker marker = SecureLogging.CONFIDENTIAL; String password = "classified!"; this.loggerLogback.info(marker, "confidential message with password = '{}'", password); verify(this.mockAppender).doAppend(this.captorLoggingEvent.capture()); final LoggingEvent loggingEvent = this.captorLoggingEvent.getValue(); assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); String layoutMessage = this.encoder.getLayout().doLayout(loggingEvent); <START> System.out.println("test(): layoutMessage = " + layoutMessage); <END> assertFalse("formatted log message must not contain any classified information.", layoutMessage.contains(password)); assertTrue("formatted log message must contain the name of its marker.", layoutMessage.contains(marker.getName())); }</code><technical_language>System.out locally for debugging commit it</technical_language>

Target:
public void testLogEventWithMasking() { Marker marker = SecureLogging.CONFIDENTIAL; String password = "classified!"; LOG.info(marker, "confidential message with password = '{}'", password); final LoggingEvent loggingEvent = getLastLogEvent(); assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO); String layoutMessage = this.encoder.getLayout().doLayout(loggingEvent); assertThat(layoutMessage.contains(password)).as("formatted log message contains classified information.").isFalse(); assertThat(layoutMessage.contains(marker.getName())).as("log message contains name of marker.").isTrue(); }
Source:
<code>public void validate() { try { new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException(String.format("URL '%s' is malformed: %s", url, e.getMessage()), e); } if (intervalInSeconds <= 0) { throw new IllegalArgumentException(String.format( "Invalid intervalInSeconds %d. Interval must be greater than 0.", intervalInSeconds)); } if (connectTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid connectTimeout %d. Timeout must be a positive number.", connectTimeout)); } if (readTimeout < 0) { throw new IllegalArgumentException(String.format( <START> "Invalid readTimeout %d. Interval must be a positive number.", readTimeout)); <END> } try { if (!Strings.isNullOrEmpty(charsetString)) { Charset.forName(charsetString); } } catch (UnsupportedCharsetException e) { throw new IllegalArgumentException(String.format("Invalid charset string %s.", charsetString)); } try { convertHeadersToMap(requestHeadersString); } catch (Exception e) { throw new IllegalArgumentException(String.format("Could not parse requestHeadersString string due to: '%s'.", e.getMessage())); } }</code><technical_language>Interval -> Timeout</technical_language>

Target:
public void validate() { try { new URL(url); } catch (MalformedURLException e) { throw new IllegalArgumentException(String.format("URL '%s' is malformed: %s", url, e.getMessage()), e); } if (intervalInSeconds <= 0) { throw new IllegalArgumentException(String.format( "Invalid intervalInSeconds %d. Interval must be greater than 0.", intervalInSeconds)); } if (connectTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid connectTimeout %d. Timeout must be 0 or a positive number.", connectTimeout)); } if (readTimeout < 0) { throw new IllegalArgumentException(String.format( "Invalid readTimeout %d. Timeout must be 0 or a positive number.", readTimeout)); } try { if (!Strings.isNullOrEmpty(charsetString)) { Charset.forName(charsetString); } } catch (UnsupportedCharsetException e) { throw new IllegalArgumentException(String.format("Invalid charset string %s.", charsetString)); } convertHeadersToMap(requestHeadersString); }
Source:
<code>public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, NotGroupMemberException, PrivilegeException, GroupNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException, WrongAttributeValueException, AlreadyMemberException, WrongReferenceAttributeValueException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) <START> && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { <END> throw new PrivilegeException(sess, "removeMember"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Removing of member is not allowed. Group is externally managed."); } getGroupsManagerBl().removeMember(sess, group, member); }</code><technical_language>changes part of this logic. Please remove this pull request. is some automatic IDE</technical_language>

Target:
public void removeMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, NotGroupMemberException, PrivilegeException, GroupNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "removeMember"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Removing of member is not allowed. Group is externally managed."); } getGroupsManagerBl().removeMember(sess, group, member); }
Source:
<code>public Variable(final String identifier, final String content, final String description, final IPath path) { fName = identifier; fContent = content; fDescription = (description != null) ? description : ""; <START> fPath = (path != null) ? (path.makeAbsolute()) : new Path(NAME_ROOT_NODE); <END> }</code><technical_language>Path.ROOT</technical_language>

Target:
public Variable(final String identifier, final String content, final String description, final IPath path) { fName = identifier; fContent = content; fDescription = (description != null) ? description : ""; fPath = (path != null) ? (path.makeAbsolute()) : Path.ROOT; }
Source:
<code>private boolean initTrustedService() { List <String> hosts = new ArrayList<String> (); if (getVds().getStatus() != VDSStatus.NonOperational <START> || getVds().getNonOperationalReason() != NonOperationalReason.UNTRUSTED) { <END> return true; } hosts.add(getVds().getHostName()); List<AttestationValue> value = new ArrayList<AttestationValue> (); try { value = AttestationService.getInstance().attestHosts(hosts); } catch (Exception e) { log.errorFormat("Encounter an exception while attesting host's trustworthiness for Host {0}, Error is {1}", hosts, e); } if (value.size() > 0 && value.get(0).getTrustLevel() == AttestationResultEnum.TRUSTED) { return true; } else { setNonOperational(NonOperationalReason.UNTRUSTED, null); return false; } }</code><technical_language>i is wrong here, host moves this command is called, status shouldnt operational, reason, this returns true</technical_language>

Target:
private boolean initTrustedService() { List <String> hosts = new ArrayList<String> (); if (AttestThread.isTrustedVds(getVds().getId())) { return true; } hosts.add(getVds().getHostName()); List<AttestationValue> value = new ArrayList<AttestationValue> (); try { value = AttestationService.getInstance().attestHosts(hosts); } catch (Exception e) { log.errorFormat("Encounter an exception while attesting host's trustworthiness for Host {0}, Error is {1}", hosts, e); } if (value.size() > 0 && value.get(0).getTrustLevel() == AttestationResultEnum.TRUSTED) { return true; } else { setNonOperational(NonOperationalReason.UNTRUSTED, null); return false; } }
Source:
<code>private static boolean isSingleLineSwitchMember(DetailAST ast) { boolean result = false; final DetailAST slist = ast.getNextSibling(); if (slist == null) { result = true; } else { final DetailAST caseBreak = slist.findFirstToken(TokenTypes.LITERAL_BREAK); <START> if (caseBreak != null) { <END> final DetailAST block = slist.getFirstChild(); final boolean atOneLine = isOnSameLine(ast, block); result = atOneLine && isOnSameLine(block, caseBreak); } } return result; }</code><technical_language>I doubts this code. means "a single-line case/default end a break, needs a pair of braces". For example, this code raises violations of allowSingleLineStatement option: switch (0) { case 1: return; // false violation default: throw new RuntimeException(""); // false violation } fixed adding a trailing break. check child's line? private static boolean isSingleLineSwitchMember(DetailAST ast) { final DetailAST slist = ast.getNextSibling(); return slist == null || slist.getFirstChild() == null || isOnSameLine(ast, slist.getLastChild()); }</technical_language>

Target:
private static boolean isSingleLineSwitchMember(DetailAST ast) { return Optional.of(ast) .map(DetailAST::getNextSibling) .map(DetailAST::getLastChild) .map(lastToken -> isOnSameLine(ast, lastToken)) .orElse(true); }
Source:
<code>private static Object getFieldValue(Class<?> clazz, String fieldName) { try { return clazz.getField(fieldName).get(null); } catch (NoSuchFieldException | IllegalAccessException e) { <START> throw new IllegalStateException("Java 8 or later but field " + clazz.getName() <END> + "#" + fieldName + " is missing"); } }</code><technical_language>Add original exception cause</technical_language>

Target:
private static Object getFieldValue(Class<?> clazz, String fieldName) { try { return clazz.getField(fieldName).get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Java 8 or later but field " + clazz.getName() + "#" + fieldName + " is missing", e); } }
Source:
<code>public void filter(ContainerRequestContext requestContext) throws IOException { Principal principal = httpRequest.getUserPrincipal(); String scheme = requestContext.getUriInfo().getRequestUri().getScheme(); LOG.debug("Method: {}, AuthType: {}, RemoteUser: {}, UserPrincipal: {}, Scheme: {}", httpRequest.getMethod(), httpRequest.getAuthType(), httpRequest.getRemoteUser(), principal, scheme); if (principal == null || !httpRequest.getAuthType().equalsIgnoreCase(KERBEROS_AUTH)) { throw new WebserviceAuthorizationException("Not authorized"); } SecurityContext securityContext = new StreamlineSecurityContext(principal, scheme, KERBEROS_AUTH); <START> LOG.debug("SecuirtyContext {}", securityContext); <END> requestContext.setSecurityContext(securityContext); }</code><technical_language>NIT: Typo in SecurityContext</technical_language>

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { Principal principal = httpRequest.getUserPrincipal(); String scheme = requestContext.getUriInfo().getRequestUri().getScheme(); LOG.debug("Method: {}, AuthType: {}, RemoteUser: {}, UserPrincipal: {}, Scheme: {}", httpRequest.getMethod(), httpRequest.getAuthType(), httpRequest.getRemoteUser(), principal, scheme); if (principal == null || !httpRequest.getAuthType().equalsIgnoreCase(KERBEROS_AUTH)) { throw new WebserviceAuthorizationException("Not authorized"); } SecurityContext securityContext = new StreamlineSecurityContext(principal, scheme, KERBEROS_AUTH); LOG.debug("SecurityContext {}", securityContext); requestContext.setSecurityContext(securityContext); }
Source:
<code>private HashMap<String,String> parseVendorNumber(String vendorNumber) throws BadRequestException { HashMap<String, String> map = new HashMap<>(); if (StringUtils.isEmpty(vendorNumber) || !vendorNumber.contains(CUPurapConstants.DASH)) { throw new BadRequestException(); } String generatedVendorHeaderId = vendorNumber.substring(0, vendorNumber.indexOf(CUPurapConstants.DASH)); <START> String vendorDetailNumber = vendorNumber.substring(vendorNumber.indexOf(CUPurapConstants.DASH) + 1); <END> map.put(PurapPropertyConstants.VENDOR_HEADER_GENERATED_ID, generatedVendorHeaderId); map.put(PurapPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, vendorDetailNumber); return map; }</code><technical_language>StringUtils some helper methods simplify substrings, "substringBefore" "substringAfter". Also, want check is dash more one</technical_language>

Target:
private HashMap<String,String> parseVendorNumber(String vendorNumber) throws BadRequestException { HashMap<String, String> map = new HashMap<>(); if (StringUtils.isEmpty(vendorNumber) || !vendorNumber.contains(KFSConstants.DASH) || StringUtils.countMatches(vendorNumber, KFSConstants.DASH) > 1) { throw new BadRequestException(); } String generatedVendorHeaderId = StringUtils.substringBeforeLast(vendorNumber, KFSConstants.DASH); String vendorDetailNumber = StringUtils.substringAfterLast(vendorNumber, KFSConstants.DASH); map.put(PurapPropertyConstants.VENDOR_HEADER_GENERATED_ID, generatedVendorHeaderId); map.put(PurapPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, vendorDetailNumber); return map; }
Source:
<code>Buckets<IN, BucketID> createBuckets(int subtaskIndex) throws IOException { return new Buckets<>( basePath, bucketAssigner, bucketFactory, new BulkPartWriter.Factory<>(writerFactory), rollingPolicy, <START> null, <END> subtaskIndex, outputFileConfig); }</code><technical_language>Add litsener setter this bulk part writer builder</technical_language>

Target:
Buckets<IN, BucketID> createBuckets(int subtaskIndex) throws IOException { return new Buckets<>( basePath, bucketAssigner, bucketFactory, new BulkPartWriter.Factory<>(writerFactory), rollingPolicy, bucketLifeCycleListener, subtaskIndex, outputFileConfig); }
Source:
<code>protected void validateAssertion(final SamlAssertionWrapper samlAssertion) throws WSSecurityException { try { validateSubject(samlAssertion.getSaml2()); } catch (final WSSecurityException e) { <START> LOG.error("Unable to validate Assertion ", e); <END> throw e; } }</code><technical_language>@mhpnguyen a rule of thumb, want log a stack trace plan handle it. else in call stack, either: - log error ("Unable validate Assertion" is implicitly understood stack trace coming function "validateAssertion") - Log error message, stack ("Unable to.... {}", e.getLocalizedMessage()) In rare instances stack trace logged invaluable troubleshooting efforts, consider throwing in trace level (to prevent logs noisy debug level)</technical_language>

Target:
protected void validateAssertion(final SamlAssertionWrapper samlAssertion) throws WSSecurityException { validateSubject(samlAssertion.getSaml2()); }
Source:
<code>public Data createSortedData(@NonNull List<Talk> talks) { TreeMap<Room, TreeSet<RangePosition>> map = new TreeMap<>(ROOM_COMPARATOR); Date minTime = null; Date maxTime = null; for (int i = 0, end = talks.size(); i < end; i++) { Talk talk = talks.get(i); Room room = talk.getRoom(); TimeSlot timeSlot = talk.getTimeSlot(); Date startTime = timeSlot.getStart(); Date endTime = timeSlot.getEnd(); if (minTime == null || minTime.compareTo(startTime) > 0) { minTime = startTime; } if (maxTime == null || maxTime.compareTo(endTime) < 0) { maxTime = endTime; } TreeSet<RangePosition> row = map.get(room); <START> RangePosition tp = new RangePosition(startTime, endTime, i); <END> if (row == null) { row = new TreeSet<>(); map.put(room, row); } row.add(tp); } return new Data(talks, map, minTime, maxTime); }</code><technical_language>tp anything... name more meaningful</technical_language>

Target:
public Data createSortedData(@NonNull List<Talk> talks) { TreeMap<Room, TreeSet<RangePosition<Date>>> map = new TreeMap<>(ROOM_COMPARATOR); Date minTime = null; Date maxTime = null; for (int i = 0, end = talks.size(); i < end; i++) { Talk talk = talks.get(i); Room room = talk.getRoom(); TimeSlot timeSlot = talk.getTimeSlot(); Date startTime = timeSlot.getStart(); Date endTime = timeSlot.getEnd(); if (minTime == null || minTime.compareTo(startTime) > 0) { minTime = startTime; } if (maxTime == null || maxTime.compareTo(endTime) < 0) { maxTime = endTime; } TreeSet<RangePosition<Date>> row = map.get(room); if (row == null) { row = new TreeSet<>(); map.put(room, row); } row.add(createRangePosition(startTime, endTime, i)); } return new Data(talks, map, minTime, maxTime); }
Source:
<code>public void refreshSelfHealInfo() { <START> log.debug("Refreshing Gluster Self Heal Data"); <END> for (Cluster cluster : getClusterDao().getAll()) { if (supportsGlusterSelfHealMonitoring(cluster)) { try { refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); } } } }</code><technical_language>for sake of completeness - please add log.debug message process is completed</technical_language>

Target:
public void refreshSelfHealInfo() { log.debug("Refreshing Gluster Self Heal Data"); for (Cluster cluster : getClusterDao().getAll()) { if (supportsGlusterSelfHealMonitoring(cluster)) { try { refreshSelfHealData(cluster); } catch (Exception e) { log.error("Error while refreshing Gluster self heal data of cluster '{}': {}", cluster.getName(), e.getMessage()); log.debug("Exception", e); } } } log.debug("Refreshing Gluster Self Heal data is completed"); }
Source:
<code>private static void init(Supplier<Optional<MeterRegistry>> meterRegistrySupplier) { if (meterRegistry.isPresent()) { <START> log.warn("Registry has already been initialized."); return; <END> } meterRegistry = meterRegistrySupplier.get(); }</code><technical_language>if suppliers passed? I a good idea silently print a warning message</technical_language>

Target:
private static void init(Supplier<Optional<MeterRegistry>> meterRegistrySupplier) { if (meterRegistry.isPresent()) { throw new IllegalStateException("Registry has already been initialized."); } meterRegistry = meterRegistrySupplier.get(); }
Source:
<code>private void initJni() throws IOException { File jniDir = new File(mDir, "jni"); if (!jniDir.exists()) { return; } if (mNdkProject) { mNativeSources = jniDir; File makefile = new File(jniDir, "Android.mk"); if (makefile.exists()) { Pattern pattern = Pattern.compile("\\s*LOCAL_MODULE\\s*:=\\s*(\\S+)\\s*"); for (String line : Files.readLines(makefile, Charsets.UTF_8)) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { mNativeModuleName = matcher.group(1); if (mNativeLibs != null) { String libName = "lib" + mNativeModuleName + ".so"; ListIterator<File> iterator = mNativeLibs.listIterator(); while (iterator.hasNext()) { File lib = iterator.next(); if (libName.equals(lib.getName())) { iterator.remove(); } } if (mNativeLibs.isEmpty()) { mNativeLibs = null; } } break; } } } } else { <START> mImporter.reportWarning(this, <END> getClassPathFile(), "Project contains a jni directory, but does not have an Eclipse C/C++ " + "nature: malformed NDK project?"); } }</code><technical_language>hmm integration. do work</technical_language>

Target:
private void initJni() throws IOException { File jniDir = new File(mDir, "jni"); if (!jniDir.exists()) { return; } if (mNdkProject) { mNativeSources = jniDir; File makefile = new File(jniDir, "Android.mk"); if (makefile.exists()) { Pattern pattern = Pattern.compile("\\s*LOCAL_MODULE\\s*:=\\s*(\\S+)\\s*"); for (String line : Files.readLines(makefile, Charsets.UTF_8)) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { mNativeModuleName = matcher.group(1); if (mNativeLibs != null) { String libName = "lib" + mNativeModuleName + ".so"; ListIterator<File> iterator = mNativeLibs.listIterator(); while (iterator.hasNext()) { File lib = iterator.next(); if (libName.equals(lib.getName())) { iterator.remove(); } } if (mNativeLibs.isEmpty()) { mNativeLibs = null; } } break; } } } } }
Source:
<code>private static Request parse(final InputStream input) throws IOException { boolean eof = true; final Collection<String> head = new LinkedList<>(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Opt<Integer> data = new Opt.Empty<>(); data = RqLive.data(input, data, false); while (data.get() > 0) { eof = false; if (data.get() == '\r') { RqLive.checkLineFeed(input, baos, head.size() + 1); if (baos.size() == 0) { break; } data = new Opt.Single<>(input.read()); final Opt<String> header = RqLive.newHeader(data, baos); if (header.has()) { head.add(header.get()); } data = RqLive.data(input, data, false); continue; } baos.write(RqLive.legalCharacter(data, baos, head.size() + 1)); data = RqLive.data(input, new Opt.Empty<>(), true); } if (eof) { throw new IOException("empty request"); } <START> return new RqOf( <END> () -> head, () -> input ); }</code><technical_language>@fanifieiev above</technical_language>

Target:
private static Request parse(final InputStream input) throws IOException { boolean eof = true; final Collection<String> head = new LinkedList<>(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Opt<Integer> data = new Opt.Empty<>(); data = RqLive.data(input, data, false); while (data.get() > 0) { eof = false; if (data.get() == '\r') { RqLive.checkLineFeed(input, baos, head.size() + 1); if (baos.size() == 0) { break; } data = new Opt.Single<>(input.read()); final Opt<String> header = RqLive.newHeader(data, baos); if (header.has()) { head.add(header.get()); } data = RqLive.data(input, data, false); continue; } baos.write(RqLive.legalCharacter(data, baos, head.size() + 1)); data = RqLive.data(input, new Opt.Empty<>(), true); } if (eof) { throw new IOException("empty request"); } return new RequestOf(head, input); }
Source:
<code>public String translate(final DbColumn c) { switch (c.getDbColumnType()) { case BOOLEAN: return "BOOLEAN"; case DOUBLE: return "DOUBLE PRECISION"; case INT: <START> if (c.isAutoInc()) { <END> return "INT4"; } else { return "INT4"; } case LONG: if (c.isAutoInc()) { return "INT8"; } else { return "INT8"; } case STRING: return format("VARCHAR(%s)", c.isSizeSet() ? c.getSize().toString() : properties.getProperty(VARCHAR_SIZE)); case CLOB: return "TEXT"; case BLOB: return "BYTEA"; case JSON: return "JSONB"; default: throw new DatabaseEngineRuntimeException(format( "Mapping not found for '%s'. Please report this error.", c.getDbColumnType() )); } }</code><technical_language>Condition unnecessary INT4 is returned way</technical_language>

Target:
public String translate(final DbColumn c) { switch (c.getDbColumnType()) { case BOOLEAN: return "BOOLEAN"; case DOUBLE: return "DOUBLE PRECISION"; case INT: return "INT4"; case LONG: return "INT8"; case STRING: return format("VARCHAR(%s)", c.isSizeSet() ? c.getSize().toString() : properties.getProperty(VARCHAR_SIZE)); case CLOB: return "TEXT"; case BLOB: return "BYTEA"; case JSON: return "JSONB"; default: throw new DatabaseEngineRuntimeException(format( "Mapping not found for '%s'. Please report this error.", c.getDbColumnType() )); } }
Source:
<code>public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) { List<InterpreterCompletion> candidates = Collections.emptyList(); try { try { candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor)); } catch (SessionNotFoundException e) { <START> LOGGER.warn("Livy session is expired, new session will be created.", sessionInfo.id); <END> synchronized (this) { if (isSessionExpired()) { initLivySession(); } } candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor)); } } catch (LivyException le) { logger.error("Failed to call code completions. Will return empty list of candidates", le); } return candidates; }</code><technical_language>concern need recreate session code completion is called. session creation a long time while code completion response instantly</technical_language>

Target:
public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) { List<InterpreterCompletion> candidates = Collections.emptyList(); try { candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor)); } catch (SessionNotFoundException e) { LOGGER.warn("Livy session is expired. Will return empty list of candidates.", sessionInfo.id); } catch (LivyException le) { logger.error("Failed to call code completions. Will return empty list of candidates", le); } return candidates; }
Source:
<code>public Response getGroup(int groupId, String format, String requestedFilename, String acceptHeader) { boolean isCsvRequested = StringUtils.contains(acceptHeader, "text/comma-separated-values") || StringUtils.equalsIgnoreCase( "csv", format); if(isCsvRequested && requestedFilename != null && !new FilenameHelper().isValidFileName(requestedFilename)) { return Response.status(Response.Status.BAD_REQUEST).entity("parameter filename should follow this regex pattern: " + FilenameHelper.REGEX_ALLOWED_CHAR).build(); } else if(isCsvRequested) { final String csvContent = classificationService.exportRules(groupId); final String filename = new FilenameHelper().createFilenameForGroupExport(groupId, requestedFilename); return Response.ok() .header("Content-Disposition", "attachment; filename=\""+filename+"\"") .header("Content-Type", "text/comma-separated-values") .entity(csvContent) .build(); } else { <START> return getGroupAsJson(groupId); <END> } }</code><technical_language>create a getGroupAsCsv method a getGroupAsJson is fine</technical_language>

Target:
public Response getGroup(int groupId, String format, String requestedFilename, String acceptHeader) { boolean isCsvRequested = (acceptHeader != null && acceptHeader.contains("text/comma-separated-values")) || "csv".equalsIgnoreCase(format); if(isCsvRequested && requestedFilename != null && !new FilenameHelper().isValidFileName(requestedFilename)) { return Response.status(Response.Status.BAD_REQUEST).entity("parameter filename should follow this regex pattern: " + FilenameHelper.REGEX_ALLOWED_CHAR).build(); } else if(isCsvRequested) { return getGroupAsCsv(groupId, requestedFilename); } else { return getGroupAsJson(groupId); } }
Source:
<code><START> public List<IMetric> transform(List<IMetric> metrics) <END> { if (metrics.size() == 0) { return metrics; } Comparator<IMetric> compare = new Comparator<IMetric>() { public int compare(IMetric m1, IMetric m2) { return m1.getName().compareTo(m2.getName()); } }; Collections.sort(metrics,compare); SimpleMetric workingMetric = new SimpleMetric(metrics.get(0)); ArrayList<IMetric> summedMetrics = new ArrayList<IMetric>(); for (int i = 1; i < metrics.size(); i++) { IMetric curMetric = metrics.get(i); if (workingMetric.getName() != curMetric.getName()) { summedMetrics.add(workingMetric); workingMetric = new SimpleMetric(curMetric); } else { workingMetric.setValue(workingMetric.getValue() + curMetric.getValue()); } } return summedMetrics; }</code><technical_language>@Override</technical_language>

Target:
public List<IMetric> transform(List<IMetric> metrics) { if (metrics.size() == 0) { return metrics; } Comparator<IMetric> compare = new Comparator<IMetric>() { public int compare(IMetric m1, IMetric m2) { return m1.getName().compareTo(m2.getName()); } }; Collections.sort(metrics,compare); ArrayList<IMetric> summedMetrics = new ArrayList<IMetric>(); SimpleMetric workingMetric = new SimpleMetric(metrics.get(0)); summedMetrics.add(workingMetric); for (int i = 1; i < metrics.size(); i++) { IMetric curMetric = metrics.get(i); if (workingMetric.getName() != curMetric.getName()) { workingMetric = new SimpleMetric(curMetric); summedMetrics.add(workingMetric); } else { workingMetric.setValue(workingMetric.getValue() + curMetric.getValue()); } } return summedMetrics; }
Source:
<code>void addTweets() { final List<Tweet> tweets = new ArrayList<Tweet>(); tweets.add(Tweet.newTweet("artem_zin", "Checkout StorIO — modern API for SQLiteDatabase & ContentResolver")); tweets.add(Tweet.newTweet("HackerNews", "It's revolution! Dolphins can write news on HackerNews with our new app!")); tweets.add(Tweet.newTweet("AndroidDevReddit", "Awesome library — StorIO")); tweets.add(Tweet.newTweet("Facebook", "Facebook community in Twitter is more popular than Facebook community in Facebook and Instagram!")); tweets.add(Tweet.newTweet("Google", "Android be together not the same: AOSP, AOSP + Google Apps, Samsung Android")); tweets.add(Tweet.newTweet("Reddit", "Now we can send funny gifs directly into your brain via Oculus Rift app!")); tweets.add(Tweet.newTweet("ElonMusk", "Tesla Model S OTA update with Android Auto 5.2, fixes for memory leaks")); tweets.add(Tweet.newTweet("AndroidWeekly", "Special issue #1: StorIO — forget about SQLiteDatabase, ContentResolver APIs, ORMs suck!")); tweets.add(Tweet.newTweet("Apple", "Yosemite update: fixes for Wifi issues, yosemite-wifi-patch#142")); storIOContentResolver .put() .objects(tweets) .prepare() <START> .asRxFlowable(MISSING) <END> .observeOn(mainThread()) .subscribe(new FlowableSubscriber<PutResults<Tweet>>() { @Override public void onSubscribe(Subscription subscription) { } @Override public void onError(Throwable e) { safeShowShortToast(getActivity(), R.string.tweets_add_error_toast); } @Override public void onNext(PutResults<Tweet> putResults) { } @Override public void onComplete() { } }); }</code><technical_language>Completable avoid empty callbacks</technical_language>

Target:
void addTweets() { final List<Tweet> tweets = new ArrayList<Tweet>(); tweets.add(Tweet.newTweet("artem_zin", "Checkout StorIO — modern API for SQLiteDatabase & ContentResolver")); tweets.add(Tweet.newTweet("HackerNews", "It's revolution! Dolphins can write news on HackerNews with our new app!")); tweets.add(Tweet.newTweet("AndroidDevReddit", "Awesome library — StorIO")); tweets.add(Tweet.newTweet("Facebook", "Facebook community in Twitter is more popular than Facebook community in Facebook and Instagram!")); tweets.add(Tweet.newTweet("Google", "Android be together not the same: AOSP, AOSP + Google Apps, Samsung Android")); tweets.add(Tweet.newTweet("Reddit", "Now we can send funny gifs directly into your brain via Oculus Rift app!")); tweets.add(Tweet.newTweet("ElonMusk", "Tesla Model S OTA update with Android Auto 5.2, fixes for memory leaks")); tweets.add(Tweet.newTweet("AndroidWeekly", "Special issue #1: StorIO — forget about SQLiteDatabase, ContentResolver APIs, ORMs suck!")); tweets.add(Tweet.newTweet("Apple", "Yosemite update: fixes for Wifi issues, yosemite-wifi-patch#142")); storIOContentResolver .put() .objects(tweets) .prepare() .asRxCompletable() .observeOn(mainThread()) .subscribe( new Action() { @Override public void run() throws Exception { } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { safeShowShortToast(getActivity(), R.string.tweets_add_error_toast); } } ); }
Source:
<code>public Set<ObjectId> getAlreadyAccepted(Repository repo) { if (alreadyAccepted == null) { alreadyAccepted = Sets.newHashSet(); for <START> (final Ref <END> r : repo.getAllRefs().values()) { if (r.getName().startsWith(Constants.R_HEADS) || r.getName().startsWith(Constants.R_TAGS)) { alreadyAccepted.add(r.getObjectId()); } } } return alreadyAccepted; }</code><technical_language>final is necessary</technical_language>

Target:
Set<ObjectId> getAlreadyAccepted(Repository repo) { if (alreadyAccepted == null) { alreadyAccepted = Sets.newHashSet(); for (Ref r : repo.getAllRefs().values()) { if (r.getName().startsWith(Constants.R_HEADS) || r.getName().startsWith(Constants.R_TAGS)) { if (r.getObjectId() != null) { alreadyAccepted.add(r.getObjectId()); } } } } return alreadyAccepted; }
Source:
<code>public void makeGraph() { try { File nodeFile = FileSelector.selectFile("Select node file", this, ".node.graph"); File edgeFile = new File(nodeFile.getAbsolutePath().replace(".node", ".edge")); GeneData geneData = GeneData.parseGenes("geneAnnotationsRef"); final long startTime = System.currentTimeMillis(); GraphDataRepository gd = new GraphDataRepository(); gd.addLoadingObserversList(loadingObservers); gd.parseGraph(nodeFile, edgeFile, geneData); graphView = new GraphView(gd, loadingObservers); zoomBarView = new ZoomBarView(getGraphController()); setZoomBarView(zoomBarView.getPanel()); setGraphView(graphView.getPanel()); graphView.getController().init(); KeyController keys = new KeyController(this); graphView.getPanel().addKeyListener(keys); <START> <END> this.setFocusable(true); long loadTime = System.currentTimeMillis() - startTime; System.out.println("Loadtime: " + loadTime); } catch (FileNotFoundException | FileSelectorException exception) { if (confirm("Error!", "Your file was not found. Want to try again?")) { makeGraph(); } } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>Y u do dis??</technical_language>

Target:
public void makeGraph() { try { File nodeFile = FileSelector.selectFile("Select node file", this, ".node.graph"); File edgeFile = new File(nodeFile.getAbsolutePath().replace(".node", ".edge")); GeneData geneData = GeneData.parseGenes("geneAnnotationsRef"); final long startTime = System.currentTimeMillis(); GraphDataRepository gd = new GraphDataRepository(); gd.addLoadingObserversList(loadingObservers); gd.parseGraph(nodeFile, edgeFile, geneData); graphView = new GraphView(gd, loadingObservers); zoomBarView = new ZoomBarView(getGraphController()); findgenesController = new FindgenesController(gd, getGraphController()); findgenesController.setFrame(this); setZoomBarView(zoomBarView.getPanel()); setGraphView(graphView.getPanel()); graphView.getPanel().requestFocus(); graphView.getController().init(); graphView.getPanel().addKeyListener(keys); this.setFocusable(true); long loadTime = System.currentTimeMillis() - startTime; System.out.println("Loadtime: " + loadTime); } catch (FileNotFoundException | FileSelectorException exception) { if (confirm("Error!", "Your file was not found. Want to try again?")) { makeGraph(); } } catch (IOException e) { e.printStackTrace(); } }
Source:
<code>public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { ++cumulations; if (!cumulation.isReadable()) { <START> return in; <END> } assertTrue(cumulation.readableBytes() < messageSize); ByteBuf result = alloc.buffer(messageSize); result.writeBytes(cumulation); while (result.isWritable() && in.isReadable()) { result.writeByte(in.readByte()); } cumulation.release(); if (!in.isReadable()) { in.release(); } return result; }</code><technical_language>I need call cumulation.release() in real implementation</technical_language>

Target:
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) { ++cumulations; if (!cumulation.isReadable()) { cumulation.release(); return in; } assertTrue(cumulation.readableBytes() < messageSize); ByteBuf result = alloc.buffer(messageSize); result.writeBytes(cumulation); while (result.isWritable() && in.isReadable()) { result.writeByte(in.readByte()); } cumulation.release(); if (!in.isReadable()) { in.release(); } return result; }
Source:
<code><START> private static List<RuleSet> findRuleSets() { <END> List<RuleSet> ruleSets = new ArrayList<>(); for (RuleSetProvider ruleSetProvider : ServiceLoader.load(RuleSetProvider.class)) { ruleSets.add(ruleSetProvider.get()); } return ruleSets; }</code><technical_language>static</technical_language>

Target:
private List<RuleSet> findRuleSets() { List<RuleSet> ruleSets = new ArrayList<>(); for (RuleSetProvider ruleSetProvider : ServiceLoader.load(RuleSetProvider.class)) { ruleSets.add(ruleSetProvider.get()); } return ruleSets; }
Source:
<code>public Long getDirectDownloadExpiration() { <START> return config.get("direct_download_expiration", Long.class, 10L*60); <END> }</code><technical_language>explain default 10L*60</technical_language>

Target:
public Optional<Long> getDirectDownloadExpiration() { return Optional.of(config.get("direct_download_expiration", Long.class, 10L*60)); }
Source:
<code>public boolean isSecure() { <START> return isPSK() || isRPK() || isX509() || isOSCORE(); <END> }</code><technical_language>isSecure() return true if "coaps is false if "coap" is used. naming is good OSCORE addition (so need rename later.) in this case isOSCORE impact isSecure()</technical_language>

Target:
public boolean isSecure() { return isPSK() || isRPK() || isX509(); }
Source:
<code>public TDigest(double compression) { if (compression < 10) { compression = 10; } double sizeFudge = 10; if (compression < 30) { sizeFudge += 20; } this.publicCompression = compression; int size = (int) Math.ceil(this.publicCompression + sizeFudge); int bufferSize = 5 * size; <START> <END> double scale = Math.max(1, bufferSize / size - 1); this.compression = Math.sqrt(scale) * publicCompression; size = (int) Math.ceil(this.compression + sizeFudge); weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; activeCentroids = 0; }</code><technical_language>original code explained 5 * size is a good choice. I useful for context</technical_language>

Target:
private TDigest(double compression) { checkArgument(compression <= MAX_COMPRESSION_FACTOR, "Compression factor cannot exceed %s", MAX_COMPRESSION_FACTOR); this.publicCompression = max(compression, 10); this.compression = 2 * publicCompression; int bufferSize = 5 * (int) ceil(this.publicCompression + sizeFudge); int size = (int) ceil(this.compression + sizeFudge); weight = new double[size]; mean = new double[size]; tempWeight = new double[bufferSize]; tempMean = new double[bufferSize]; order = new int[bufferSize]; activeCentroids = 0; }
Source:
<code>static Path createConfigurationFileInFs(FileSystem fs, String appHome, Map stormConf, YarnConfiguration yarnConf) throws IOException { Path confDst = new Path(fs.getHomeDirectory(), appHome + Path.SEPARATOR + STORM_CONF_PATH_STRING); Path dirDst = confDst.getParent(); <START> if (!fs.exists(dirDst)) <END> fs.mkdirs(dirDst); if (!fs.exists(confDst)) { FSDataOutputStream out = fs.create(confDst); Yaml yaml = new Yaml(); OutputStreamWriter writer = new OutputStreamWriter(out); rmNulls(stormConf); yaml.dump(stormConf, writer); writer.close(); out.close(); } Path yarn_site_xml = new Path(dirDst, "yarn-site.xml"); if (!fs.exists(yarn_site_xml)) { FSDataOutputStream out = fs.create(yarn_site_xml); OutputStreamWriter writer = new OutputStreamWriter(out); yarnConf.writeXml(writer); writer.close(); out.close(); } return dirDst; }</code><technical_language>I blow if dirDst exists. This means a conf written out for a cluster if over-write other cluster fail. If overwrite cluster get wrong config. appHome is supposed separate including applicationId in path. If is working need fix that</technical_language>

Target:
static Path createConfigurationFileInFs(FileSystem fs, String appHome, Map stormConf, YarnConfiguration yarnConf) throws IOException { Path confDst = new Path(fs.getHomeDirectory(), appHome + Path.SEPARATOR + STORM_CONF_PATH_STRING); Path dirDst = confDst.getParent(); fs.mkdirs(dirDst); FSDataOutputStream out = fs.create(confDst); Yaml yaml = new Yaml(); OutputStreamWriter writer = new OutputStreamWriter(out); rmNulls(stormConf); yaml.dump(stormConf, writer); writer.close(); out.close(); Path yarn_site_xml = new Path(dirDst, "yarn-site.xml"); out = fs.create(yarn_site_xml); writer = new OutputStreamWriter(out); yarnConf.writeXml(writer); writer.close(); out.close(); return dirDst; }
Source:
<code>public AcknowledgementType auditLog(LogEventRequestType request, AssertionType assertion) { LOG.debug("Entering AuditRepositoryProxyWebServiceSecured.auditLog(...)"); AcknowledgementType result = new AcknowledgementType(); if (request.getAuditMessage() == null) { LOG.error("Audit Request Message is null"); return result; } try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.AUDIT_REPO_SECURE_SERVICE_NAME); if (NullChecker.isNotNullish(url)) { ServicePortDescriptor<AuditRepositoryManagerSecuredPortType> portDescriptor = new AuditRepositorySecuredServicePortDescriptor(); CONNECTClient<AuditRepositoryManagerSecuredPortType> client = CONNECTCXFClientFactory.getInstance() .getCONNECTClientSecured(portDescriptor, url, assertion); result = (AcknowledgementType) client.invokePort(AuditRepositoryManagerSecuredPortType.class, invokeMethodName, createLogSecureEventRequestType(request)); } } catch (Exception e) { LOG.error("Failed to call the web service({}). An unexpected exception occurred. Exception: {}", NhincConstants.AUDIT_REPO_SECURE_SERVICE_NAME, e.getLocalizedMessage(), e); } LOG.debug("In AuditRepositoryProxyWebServiceSecured.auditLog(...) - completed called to ConnectionManager to " <START> + "retrieve endpoint."); <END> return result; }</code><technical_language>Optional: parameterized log if possible</technical_language>

Target:
public AcknowledgementType auditLog(LogEventRequestType request, AssertionType assertion) { LOG.debug("Entering AuditRepositoryProxyWebServiceSecured.auditLog(...)"); AcknowledgementType result = new AcknowledgementType(); if (request.getAuditMessage() == null) { LOG.error("Audit Request Message is null"); return result; } try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.AUDIT_REPO_SECURE_SERVICE_NAME); if (NullChecker.isNotNullish(url)) { ServicePortDescriptor<AuditRepositoryManagerSecuredPortType> portDescriptor = new AuditRepositorySecuredServicePortDescriptor(); CONNECTClient<AuditRepositoryManagerSecuredPortType> client = CONNECTCXFClientFactory.getInstance() .getCONNECTClientSecured(portDescriptor, url, assertion); result = (AcknowledgementType) client.invokePort(AuditRepositoryManagerSecuredPortType.class, invokeMethodName, createLogSecureEventRequestType(request)); } } catch (Exception e) { LOG.error("Failed to call the web service({}). An unexpected exception occurred. Exception: {}", NhincConstants.AUDIT_REPO_SECURE_SERVICE_NAME, e.getLocalizedMessage(), e); } LOG.debug( "In AuditRepositoryProxyWebServiceSecured.auditLog(...) - completed called to ConnectionManager to retrieve endpoint."); return result; }