auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void authenticateUserShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); <START> return null; <END> } }).build(); final AuthenticationService authenticationService = adapter.create(AuthenticationService.class); authenticationService.authenticateUser(OTP, AUTHORIZATION, new AuthenticationRequest("foobar"), new RetrofitPromise<AuthenticationResponse>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/tokens", MOCK_URL)); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("X-Bitreserve-OTP", OTP))); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Authorization", AUTHORIZATION))); Assert.assertEquals(bodyRef.get().getMethod(), "POST"); }</code><technical_language>Add newline return</technical_language>

Target:
public void authenticateUserShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final String mockUrl = "<LINK_0>"; final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(mockUrl).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final AuthenticationService authenticationService = adapter.create(AuthenticationService.class); authenticationService.authenticateUser("foobar", "authorizationfoobar", new AuthenticationRequest("foobar"), new RetrofitPromise<AuthenticationResponse>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "POST"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/tokens", mockUrl)); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Authorization", "authorizationfoobar"))); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("X-Bitreserve-OTP", "foobar"))); }
Source:
<code>private void safelyAddProperty(Properties properties, String key, KualiDecimal value) { <START> properties.put(key, ObjectUtils.isNull(value) ? KFSConstants.EMPTY_STRING : value.floatValue()); <END> }</code><technical_language>KualiDecimal's converted a String instead of a float, avoid risk of losing data? If need convert a primitive, I suggest converting a "double" instead if can. for equivalent BigDecimal method below</technical_language>

Target:
private void safelyAddProperty(Properties properties, String key, KualiDecimal value) { properties.put(key, ObjectUtils.isNull(value) ? KFSConstants.EMPTY_STRING : value.toString()); }
Source:
<code>public void afterPropertiesSet() { Assert.notNull(codeListTable, "codeListTable is not initialized!"); Assert.isTrue(codeListTable.containsRow(fallbackTo), "No codelist found for locale '" + fallbackTo <START> + "', it must be defined."); <END> }</code><technical_language>[x] This message contained "for **fallback** locale"</technical_language>

Target:
public void afterPropertiesSet() { Assert.notNull(codeListTable, "codeListTable is not initialized!"); Assert.isTrue(codeListTable.containsRow(fallbackTo), "No codelist found for fallback locale '" + fallbackTo + "', it must be defined."); }
Source:
<code>public static double quantileAtValueBigint(@SqlType("qdigest(bigint)") Slice input, @SqlType(StandardTypes.BIGINT) long value) { QuantileDigest digest = new QuantileDigest(input); <START> if (digest.getCount() == 0) return 1.0; <END> double bucketCount = digest.getHistogram(ImmutableList.of(value)).get(0).getCount(); return bucketCount / digest.getCount(); }</code><technical_language>braces for if statement, is example of code style <LINK_0></technical_language>

Target:
public static Double quantileAtValueBigint(@SqlType("qdigest(bigint)") Slice input, @SqlType(StandardTypes.BIGINT) long value) { QuantileDigest digest = new QuantileDigest(input); if (digest.getCount() == 0 || value > digest.getMax() || value < digest.getMin()) { return null; } double bucketCount = digest.getHistogram(ImmutableList.of(value)).get(0).getCount(); return bucketCount / digest.getCount(); }
Source:
<code>public void mergeWith(UnweightedDoubleReservoirSample other) { <START> if (other.count < other.maxSamples) { <END> Arrays.stream(other.elements).forEach(o -> add(o)); return; } if (count < maxSamples) { final UnweightedDoubleReservoirSample target = ((UnweightedDoubleReservoirSample) other.clone()); Arrays.stream(elements).forEach(o -> target.add(o)); count = target.count; maxSamples = target.maxSamples; elements = target.elements; return; } shuffleArray(elements); shuffleArray(other.elements); int nextIndex = 0; int otherNextIndex = 0; double[] merged = new double[maxSamples]; for (int i = 0; i < maxSamples; ++i) { if (ThreadLocalRandom.current().nextLong(0, count + other.count) < count) { merged[i] = elements[nextIndex++]; } else { merged[i] = other.elements[otherNextIndex++]; } } count += other.count; elements = merged; }</code><technical_language>is this needed</technical_language>

Target:
public void mergeWith(UnweightedDoubleReservoirSample other) { checkArgument(samples.length == other.samples.length, "Max samples must be equal"); if (other.count < other.samples.length) { Arrays.stream(other.samples).forEach(o -> add(o)); return; } if (count < samples.length) { final UnweightedDoubleReservoirSample target = ((UnweightedDoubleReservoirSample) other.clone()); Arrays.stream(samples).forEach(o -> target.add(o)); count = target.count; samples = target.samples; return; } shuffleArray(samples); shuffleArray(other.samples); int nextIndex = 0; int otherNextIndex = 0; double[] merged = new double[samples.length]; for (int i = 0; i < samples.length; ++i) { if (ThreadLocalRandom.current().nextLong(0, count + other.count) < count) { merged[i] = samples[nextIndex++]; } else { merged[i] = other.samples[otherNextIndex++]; } } count += other.count; samples = merged; }
Source:
<code>Iterable<ProgramState> startingStates(String signature, ProgramState currentState, boolean isStaticMethod) { int parameterIdx = 0; ProgramState state = currentState; if(!isStaticMethod) { SymbolicValue thisSV = constraintManager.createSymbolicValue((Instruction) null); <START> Type classType = semanticModel == null ? Symbols.unknownType : semanticModel.getClassType(signature.substring(0, signature.indexOf('#'))); <END> state = currentState.addConstraint(thisSV, ObjectConstraint.NOT_NULL).addConstraint(thisSV, new TypedConstraint(classType)).put(0, thisSV); parameterIdx = 1; } org.objectweb.asm.Type[] argumentTypes = org.objectweb.asm.Type.getArgumentTypes(signature.substring(signature.indexOf('('))); for (org.objectweb.asm.Type argumentType: argumentTypes) { SymbolicValue sv = constraintManager.createSymbolicValue((Instruction) null); methodBehavior.addParameter(sv); state = state.put(parameterIdx, sv); state = setDoubleOrLong(state, sv, argumentType.getSize() == 2); parameterIdx += argumentType.getSize(); } return Collections.singletonList(state); }</code><technical_language>semanticModel null in production , tests adapted instead</technical_language>

Target:
Iterable<ProgramState> startingStates(String signature, ProgramState currentState, boolean isStaticMethod) { int parameterIdx = 0; ProgramState state = currentState; if(!isStaticMethod) { SymbolicValue thisSV = constraintManager.createSymbolicValue((Instruction) null); Type classType = semanticModel.getClassType(signature.substring(0, signature.indexOf('#'))); state = currentState.addConstraint(thisSV, ObjectConstraint.NOT_NULL).addConstraint(thisSV, new TypedConstraint(classType)).put(0, thisSV); parameterIdx = 1; } org.objectweb.asm.Type[] argumentTypes = org.objectweb.asm.Type.getArgumentTypes(signature.substring(signature.indexOf('('))); for (org.objectweb.asm.Type argumentType: argumentTypes) { SymbolicValue sv = constraintManager.createSymbolicValue((Instruction) null); methodBehavior.addParameter(sv); state = state.put(parameterIdx, sv); state = setDoubleOrLong(state, sv, argumentType.getSize() == 2); parameterIdx += argumentType.getSize(); } return Collections.singletonList(state); }
Source:
<code>private int getSleepTimeMs() { <START> int sleepMs = base_sleep_ms * Math.max(1, Math.min(1, random.nextInt(1 << retries.get()))); <END> if ( sleepMs > max_sleep_ms ) sleepMs = max_sleep_ms; if ( sleepMs < base_sleep_ms ) sleepMs = base_sleep_ms; return sleepMs; }</code><technical_language>do min() max()</technical_language>

Target:
private int getSleepTimeMs() { int backoff = 1 << Math.max(1, retries.get()); int sleepMs = base_sleep_ms * Math.max(1, random.nextInt(backoff)); if ( sleepMs > max_sleep_ms ) sleepMs = max_sleep_ms; if ( sleepMs < base_sleep_ms ) sleepMs = base_sleep_ms; return sleepMs; }
Source:
<code>public void sms_send(String id, String destination, String content) { try { smsSender.send(id, destination, content); } catch(Exception ex) { <START> logException(ex); <END> } }</code><technical_language>want exception JS caller</technical_language>

Target:
public void sms_send(String id, String destination, String content) throws Exception { try { smsSender.send(id, destination, content); } catch(Exception ex) { logException(ex); throw ex; } }
Source:
<code>public List<AttributeDTO> getAttributesByGidAndAttributeIds( final String gid, final List<String> attributeIds, final Integer pageSize, final Integer pageNumber) { final List<AttributeDTO> attributes = Lists.newArrayList(); try { String sql = "SELECT " + " u.fcode AS attributeCode," + " u.fldno AS attributeDbId," + " u.fname AS attributeName," + " a.adate AS determinedDate," + " a.aval AS value " + " FROM" + " atributs a" + " INNER JOIN" + " udflds u ON a.atype = u.fldno " + " WHERE" + " a.gid = :gid AND u.ftable = 'ATRIBUTS'"; if (attributeIds != null && !attributeIds.isEmpty()) { sql = sql + " AND u.fldno IN ( :attributs )"; } final SQLQuery query = this.getSession().createSQLQuery(sql); query.addScalar("attributeCode").addScalar("attributeDbId").addScalar("attributeName").addScalar("determinedDate") .addScalar("value"); query.setParameter("gid", gid); if (attributeIds != null && !attributeIds.isEmpty()) { query.setParameterList("attributs", attributeIds); } if (pageNumber != null && pageSize != null) { query.setFirstResult(pageSize * (pageNumber - 1)); query.setMaxResults(pageSize); } final List<Object> results = query.list(); <START> for (final Object o : results) { <END> final Object[] result = (Object[]) o; if (result != null) { final AttributeDTO attributeDTO = new AttributeDTO(); attributeDTO.setAttributeCode((String) result[0]); attributeDTO.setAttributeDbId((Integer) result[1]); attributeDTO.setAttributeName((String) result[2]); attributeDTO.setDeterminedDate((Integer) result[3]); attributeDTO.setValue((String) result[4]); attributes.add(attributeDTO); } } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error with getAttributesByGid(gidList=" + gid + "): " + e.getMessage(), e); } return attributes; }</code><technical_language>ALIAS_TO_BEAN</technical_language>

Target:
public List<AttributeDTO> getAttributesByGidAndAttributeIds( final String gid, final List<String> attributeIds, final Integer pageSize, final Integer pageNumber) { List<AttributeDTO> attributes; try { String sql = this.buildQueryForAttributes(attributeIds); final SQLQuery query = this.getSession().createSQLQuery(sql); query.addScalar("attributeCode").addScalar("attributeDbId").addScalar("attributeName").addScalar("determinedDate") .addScalar("value"); query.setParameter("gid", gid); if (attributeIds != null && !attributeIds.isEmpty()) { query.setParameterList("attributs", attributeIds); } if (pageNumber != null && pageSize != null) { query.setFirstResult(pageSize * (pageNumber - 1)); query.setMaxResults(pageSize); } query.setResultTransformer(Transformers.aliasToBean(AttributeDTO.class)); attributes = query.list(); } catch (final HibernateException e) { throw new MiddlewareQueryException("Error with getAttributesByGid(gidList=" + gid + "): " + e.getMessage(), e); } return attributes; }
Source:
<code>public static ClockSkewMonitor create(Set<String> remoteServers, Optional<SSLSocketFactory> optionalSecurity) { Map<String, ClockService> monitors = Maps.toMap(remoteServers, (remoteServer) -> AtlasDbHttpClients.createProxy(optionalSecurity, remoteServer, ClockService.class)); Map<String, RequestTime> previousRequests = Maps.newHashMap(); for (String server : remoteServers) { previousRequests.put(server, RequestTime.EMPTY); } return new ClockSkewMonitor(monitors, previousRequests, new ClockSkewEvents(AtlasDbMetrics.getMetricRegistry()), <START> Executors.newSingleThreadScheduledExecutor(), <END> new ClockServiceImpl()); }</code><technical_language>this a NamedThreadFactory sets daemon=true</technical_language>

Target:
public static ClockSkewMonitor create(Set<String> remoteServers, Optional<SSLSocketFactory> optionalSecurity) { Map<String, ClockService> monitors = Maps.toMap(remoteServers, (remoteServer) -> AtlasDbHttpClients.createProxy(optionalSecurity, remoteServer, ClockService.class)); Map<String, RequestTime> previousRequests = Maps.newHashMap(); for (String server : remoteServers) { previousRequests.put(server, RequestTime.EMPTY); } return new ClockSkewMonitor(monitors, previousRequests, new ClockSkewEvents(AtlasDbMetrics.getMetricRegistry()), Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("clock-skew-monitor", true)), new ClockServiceImpl()); }
Source:
<code>private void setFileTrackingInfo(BatchSourceContext context, Configuration conf) throws IOException { String tableName = this.config.tableName; <START> if (StringUtils.isNotEmpty(tableName)) { <END> try { processedFileTrackingTable = context.getDataset(tableName); if (processedFileTrackingTable != null) { List<String> processedFiles = new ArrayList<String>(); File tempFile = new File(tableName); if (tempFile.exists()) { tempFile.delete(); } tempFile.createNewFile(); CloseableIterator<KeyValue<byte[], byte[]>> iterator = processedFileTrackingTable.scan(null, null); while (iterator.hasNext()) { KeyValue<byte[], byte[]> keyValue = iterator.next(); processedFiles.add(new String(keyValue.getKey(), Charsets.UTF_8)); } conf.set(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_DATA_TEMP_FILE, tableName); if (config.reprocessingReq.equalsIgnoreCase("NO")) { conf.set(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_FILES, GSON.toJson(processedFiles, ARRAYLIST_PREPROCESSED_FILES)); } } } catch (DatasetInstantiationException datasetInstantiationException) { throw Throwables.propagate(datasetInstantiationException); } } }</code><technical_language>this check redundant? done in validateConfig()</technical_language>

Target:
private void setFileTrackingInfo(BatchSourceContext context, Configuration conf) { processedFileTrackingTable = context.getDataset(config.tableName); if (processedFileTrackingTable != null && !config.isReprocessingRequired()) { List<String> processedFiles = new ArrayList<String>(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -Integer.valueOf(config.tableExpiryPeriod)); Date expiryDate = cal.getTime(); try (CloseableIterator<KeyValue<byte[], byte[]>> iterator = processedFileTrackingTable.scan(null, null)) { while (iterator.hasNext()) { KeyValue<byte[], byte[]> keyValue = iterator.next(); Long time = Bytes.toLong(keyValue.getValue()); Date processedDate = new Date(time); if (processedDate.before(expiryDate)) { processedFileTrackingTable.delete(keyValue.getKey()); } else { processedFiles.add(Bytes.toString(keyValue.getKey())); } } } conf.set(XMLInputFormat.XML_INPUTFORMAT_PROCESSED_FILES, GSON.toJson(processedFiles, ARRAYLIST_PREPROCESSED_FILES)); } }
Source:
<code>private int getFakePort(String sniServerName) { fakePorts.addIfAbsent(sniServerName); <START> return fakePorts.indexOf(sniServerName); <END> }</code><technical_language>fake port's actual number difference, instead of storing host names in a list, AtomicInteger, preferably starting beginning of ephemeral port range (49152)? a bit uncomfortable is zero a special meaning a port, numbers reserved ports. stated number is for session caching, if this change in future JDK versions</technical_language>

Target:
private int getFakePort(String sniServerName) { fakePorts.addIfAbsent(sniServerName); return FAKE_PORT_OFFSET + fakePorts.indexOf(sniServerName); }
Source:
<code>public Optional<List<String>> getAllViews(String databaseName) { try { return retry() .stopOn(UnknownDBException.class) .stopOnIllegalExceptions() .run("getAllViews", stats.getGetAllViews().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { String filter = HIVE_FILTER_FIELD_PARAMS + PRESTO_VIEW_FLAG + " = \"true\""; return Optional.of(client.getTableNamesByFilter(databaseName, filter)); } })); } catch (UnknownDBException e) { return Optional.empty(); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); <START> } <END> }</code><technical_language>grantTablePrivileges, revokeTablePrivileges, createRole, dropRole, setPartitionColumnStatistics, deletePartitionColumnStatistics, updatePartitionStatistics, deleteTableColumnStatistics</technical_language>

Target:
public Optional<List<String>> getAllViews(String databaseName) { try { return retry() .stopOn(UnknownDBException.class) .stopOnIllegalExceptions() .run("getAllViews", stats.getGetAllViews().wrap(() -> wrapMetastoreCallable((HiveMetastoreClient client, ThriftHiveMetastoreStats stat) -> stat.getGetAllViews().wrapCall(() -> { String filter = HIVE_FILTER_FIELD_PARAMS + PRESTO_VIEW_FLAG + " = \"true\""; return Optional.of(client.getTableNamesByFilter(databaseName, filter)); })))); } catch (UnknownDBException e) { return Optional.empty(); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }
Source:
<code>public void visit(LwM2mResource resource) { LOG.trace("Encoding resource into SenML JSON", resource); if (!requestPath.isResource()) { throw new CodecException("Invalid request path %s for resource encoding", requestPath); } <START> lwM2mResourceToSenMLRecord(EMPTY_RESOURCE_PATH, timestamp, resource); <END> }</code><technical_language>pass "resource path" empty string. I LwM2mNodeJsonEncoder do I this is good... this clearer call this recordName ? this sense recordName is null for singleResource baseName</technical_language>

Target:
public void visit(LwM2mResource resource) { LOG.trace("Encoding resource into SenML JSON", resource); if (!requestPath.isResource()) { throw new CodecException("Invalid request path %s for resource encoding", requestPath); } lwM2mResourceToSenMLRecord(null, resource); }
Source:
<code><START> public int partition(final Event event) { <END> crcGenerator.reset(); crcGenerator.update(event.getHost().getBytes()); return (int) crcGenerator.getValue(); }</code><technical_language>this is called multiple threads (I checked now), a single instance of CRC32, thread race other update/getValue(), possibly causing inconsistent values. This have: java final CRC32 crcGenerator = new CRC32(); In method</technical_language>

Target:
public int partition(final Event event) { final CRC32 crcGenerator = new CRC32(); crcGenerator.update(event.getHost().getBytes()); return (int) crcGenerator.getValue(); }
Source:
<code><START> public char getIgnoreWhitespace() { <END> return ignoreWhitespace; }</code><technical_language>try prefer proper enum for getter/setter methods, translation of char<->enum hidden of getter/setter methods. store smaller char in database, application code exposed database's insane char based storage</technical_language>

Target:
public Whitespace getIgnoreWhitespace() { return Whitespace.forCode(ignoreWhitespace); }
Source:
<code>public List<String> fetch() { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(filename).getFile()); if (isDirty(file.lastModified())) { System.out.println(filename + " is dirty! Re-fetching file content..."); List<String> data = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { data.add(line); } } catch (IOException e) { e.printStackTrace(); } return data; } <START> return null; <END> }</code><technical_language>I if DataFetcher returning null change in data. other options for this</technical_language>

Target:
public List<String> fetch() { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource(filename).getFile()); if (isDirty(file.lastModified())) { System.out.println(filename + " is dirty! Re-fetching file content..."); List<String> data = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { data.add(line); } } catch (IOException e) { e.printStackTrace(); } return data; } return new ArrayList<String>(); }
Source:
<code>protected void customizeTemplate(ConfigBag setup, ComputeService computeService, Template template) { for (JcloudsLocationCustomizer customizer : getCustomizers(setup)) { customizer.customize(this, computeService, template); customizer.customize(this, computeService, template.getOptions()); } if (template.getOptions() instanceof SoftLayerTemplateOptions) { SoftLayerTemplateOptions slT = ((SoftLayerTemplateOptions)template.getOptions()); if (Strings.isBlank(slT.getDomainName()) || "jclouds.org".equals(slT.getDomainName())) { slT.domainName("local.brooklyncentral.org"); } Map<String, String> md = slT.getUserMetadata(); if (md!=null && !md.isEmpty()) { Set<String> tags = MutableSet.copyOf(slT.getTags()); for (Map.Entry<String,String> entry: md.entrySet()) { tags.add(AbstractCloudMachineNamer.sanitize(entry.getKey())+":"+AbstractCloudMachineNamer.sanitize(entry.getValue())); } slT.tags(tags); if (!md.containsKey("notes")) { String notes = "User Metadata\n=============\n\n * " + Joiner.on("\n * ").withKeyValueSeparator(": ").join(md); if (notes.length() > NOTES_MAX_LENGTH) { <START> String truncatedMsg = "...\n<truncated>"; <END> notes = notes.substring(0, NOTES_MAX_LENGTH - truncatedMsg.length()) + truncatedMsg; } md.put("notes", notes); } } } }</code><technical_language>useful long entire message / truncated? hurts give more info a more characters</technical_language>

Target:
protected void customizeTemplate(ConfigBag setup, ComputeService computeService, Template template) { for (JcloudsLocationCustomizer customizer : getCustomizers(setup)) { customizer.customize(this, computeService, template); customizer.customize(this, computeService, template.getOptions()); } if (template.getOptions() instanceof SoftLayerTemplateOptions) { SoftLayerTemplateOptions slT = ((SoftLayerTemplateOptions)template.getOptions()); if (Strings.isBlank(slT.getDomainName()) || "jclouds.org".equals(slT.getDomainName())) { slT.domainName("local.brooklyncentral.org"); } Map<String, String> md = slT.getUserMetadata(); if (md!=null && !md.isEmpty()) { Set<String> tags = MutableSet.copyOf(slT.getTags()); for (Map.Entry<String,String> entry: md.entrySet()) { tags.add(AbstractCloudMachineNamer.sanitize(entry.getKey())+":"+AbstractCloudMachineNamer.sanitize(entry.getValue())); } slT.tags(tags); if (!md.containsKey("notes")) { String notes = "User Metadata\n=============\n\n * " + Joiner.on("\n * ").withKeyValueSeparator(": ").join(md); if (notes.length() > NOTES_MAX_LENGTH) { String truncatedMsg = "...\n<truncated - notes total length is " + notes.length() + " characters>"; notes = notes.substring(0, NOTES_MAX_LENGTH - truncatedMsg.length()) + truncatedMsg; } md.put("notes", notes); } } } }
Source:
<code><START> static public Set<String> parseProtocolRequestHeader(String value) { <END> if (StringUtils.isEmpty(value)) { return null; } Set<String> subprotocols = new LinkedHashSet<>(); if (!StringUtils.isEmpty(value)) { String[] values = value.split(","); for (String v : values) { subprotocols.add(v.trim()); } } return subprotocols; }</code><technical_language>observation... more cool return Collections.emptySet()?... if option reduce null usage do so... imho helps in long run... - I wrong..</technical_language>

Target:
static public Set<String> parseProtocolRequestHeader(String value) { Set<String> subprotocols = new LinkedHashSet<>(); if (!StringUtils.isEmpty(value)) { String[] values = value.split(","); for (String v : values) { subprotocols.add(v.trim()); } } return subprotocols; }
Source:
<code>private synchronized void logMostLikelyMissedJobs(List<JobDescriptor> jobs) { <START> Date now = new Date(); <END> jobs.stream() .map(jobDescriptor -> ((JobDescriptorImpl) jobDescriptor).getInternal()) .filter(job -> job.getJobDeadline().isPresent()) .filter(job -> job.getJobInfo().getStartTime() < 0) .filter(job -> { Date deadline = getEffectiveDeadline(job); Date expeFinish = getEffectiveExpectedExecutionTime(job, now); return deadline.compareTo(expeFinish) < 0; }) .forEach(job -> { if (!alreadyNotified.contains(job.getId())) { final Date expectedFinishingTime = getEffectiveExpectedExecutionTime(job, now); final Date effectiveDeadline = getEffectiveDeadline(job); LOGGER.warn(String.format("Job[id=%s] will most likely miss its deadline (expected finish: %s, after deadline: %s)", job.getId().value(), expectedFinishingTime, effectiveDeadline)); JobMostLikelyMissedEmailNotification notificationSender; if (job.getJobExpectedExecutionTime().isPresent()) { notificationSender = new JobMostLikelyMissedEmailNotification(job, expectedFinishingTime, effectiveDeadline, job.getJobExpectedExecutionTime() .get()); } else { notificationSender = new JobMostLikelyMissedEmailNotification(job, expectedFinishingTime, effectiveDeadline); } notificationSender.checkAndSend(); alreadyNotified.add(job.getId()); } }); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Remove this useless assignment local variable "now". [![rule](<LINK_3>](<LINK_4> ![MINOR](<LINK_1> 'Severity: MINOR') Remove this unused "now" local variable. [![rule](<LINK_3>](<LINK_2></technical_language>

Target:
private synchronized void logMostLikelyMissedJobs(List<JobDescriptor> jobs) { Date now = new Date(); jobs.stream() .map(jobDescriptor -> ((JobDescriptorImpl) jobDescriptor).getInternal()) .filter(job -> job.getJobDeadline().isPresent()) .filter(job -> !job.getJobInfo().isStarted()) .filter(job -> { Date deadline = getDeadlineAsAbsoluteDate(job); Date finishingTime = getFinishingTimeIfJobStartedNow(job, now); return deadline.compareTo(finishingTime) < 0; }) .forEach(job -> { if (!alreadyNotified.contains(job.getId())) { alreadyNotified.add(job.getId()); final Date deadline = getDeadlineAsAbsoluteDate(job); final Date finishingTime = getFinishingTimeIfJobStartedNow(job, now); LOGGER.warn(String.format("Job[id=%s] will most likely miss its deadline (expected finish: %s is after deadline: %s)", job.getId().value(), finishingTime, deadline)); JobMostLikelyMissedEmailNotification notificationSender; if (job.getJobExpectedExecutionTime().isPresent()) { notificationSender = new JobMostLikelyMissedEmailNotification(job, finishingTime, deadline, job.getJobExpectedExecutionTime() .get()); } else { notificationSender = new JobMostLikelyMissedEmailNotification(job, finishingTime, deadline); } notificationSender.tryToSend(); } }); }
Source:
<code>public void init() { <START> dependencyPagedJarTable = IOC.getBeanManager().lookupBean(DependencyListWidget.class).getInstance(); <END> dependencyPagedJarTable.addOnSelect(parameter -> { presenter.onPathSelection(parameter); lockRequired.fire(new LockRequiredEvent()); }); setTitle("Artifacts"); setBody(dependencyPagedJarTable); setSize(ModalSize.LARGE); addShownHandler(shownEvent -> dependencyPagedJarTable.search()); }</code><technical_language>advantage of opportunity ManagedInstance<DependencyListWidget> here? :)</technical_language>

Target:
public void init() { dependencyPagedJarTable = dependencyPagedJarTables.get(); dependencyPagedJarTable.addOnSelect(parameter -> { presenter.onPathSelection(parameter); lockRequired.fire(new LockRequiredEvent()); }); setTitle("Artifacts"); setBody(dependencyPagedJarTable); setSize(ModalSize.LARGE); addShownHandler(shownEvent -> dependencyPagedJarTable.search()); }
Source:
<code>public void testInstantiateAuthorizationHandler() { GoogleCloudStorageOptions options = GoogleCloudStorageOptions.builder() .setAppName("test-name") .setProjectId("test-project") .setAuthorizationHandler(TestConfAuthorizationHandler.class) .setAuthorizationHandlerProperties( <START> new HashMap<String, String>() { { put( TestConfAuthorizationHandler.PROPERTY_KEY, TestConfAuthorizationHandler.EXPECTED_VALUE); } }) <END> .build(); StorageRequestAuthorizer authorizer = initializeAuthorizationHandler(options); assertThat(authorizer).isNotNull(); }</code><technical_language>ImmutableMap instead: java ImmutableMap.of( TestConfAuthorizationHandler.PROPERTY_KEY, TestConfAuthorizationHandler.EXPECTED_VALUE)</technical_language>

Target:
public void testInstantiateAuthorizationHandler() throws ReflectiveOperationException { GoogleCloudStorageOptions options = GoogleCloudStorageOptions.builder() .setAppName("test-name") .setProjectId("test-project") .setAuthorizationHandlerClass(TestConfAuthorizationHandler.class) .setAuthorizationHandlerProperties( ImmutableMap.of( TestConfAuthorizationHandler.PROPERTY_KEY, TestConfAuthorizationHandler.EXPECTED_VALUE)) .build(); StorageRequestAuthorizer authorizer = initializeStorageRequestAuthorizer(options); assertThat(authorizer).isNotNull(); }
Source:
<code>public void testBadCallback() throws Exception { ServerErrorCode[] serverErrorCodes = new ServerErrorCode[9]; Arrays.fill(serverErrorCodes, ServerErrorCode.No_Error); presetServerErrorCode(serverErrorCodes); final CountDownLatch callbackCalled = new CountDownLatch(1); router.deleteBlob(blobIdString, new Callback<Void>() { @Override public void onCompletion(Void result, Exception exception) { callbackCalled.countDown(); throw new RuntimeException("Throwing an exception in the user callback"); } }).get(); Assert.assertTrue("Callback not called.", callbackCalled.await(2, TimeUnit.SECONDS)); Assert.assertEquals("All operations should be finished.", 0, router.getOperationsCount()); Assert.assertTrue("Router should not be closed", router.isOpen()); <START> <END> future = router.deleteBlob(blobIdString, new ClientCallback()); future.get(); }</code><technical_language>easy interleave a bad operation good operations ensuring good affected</technical_language>

Target:
public void testBadCallback() throws Exception { ServerErrorCode[] serverErrorCodes = new ServerErrorCode[9]; Arrays.fill(serverErrorCodes, ServerErrorCode.No_Error); presetServerErrorCode(serverErrorCodes); final CountDownLatch callbackCalled = new CountDownLatch(1); List<Future> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { if (i == 1) { futures.add(router.deleteBlob(blobIdString, new Callback<Void>() { @Override public void onCompletion(Void result, Exception exception) { callbackCalled.countDown(); throw new RuntimeException("Throwing an exception in the user callback"); } })); } else { futures.add(router.deleteBlob(blobIdString)); } } for (Future future : futures) { future.get(); } Assert.assertTrue("Callback not called.", callbackCalled.await(2, TimeUnit.SECONDS)); Assert.assertEquals("All operations should be finished.", 0, router.getOperationsCount()); Assert.assertTrue("Router should not be closed", router.isOpen()); router.deleteBlob(blobIdString, new ClientCallback()).get(); Assert.assertTrue("Callback not called.", operationCompleteLatch.await(2, TimeUnit.SECONDS)); }
Source:
<code>private boolean hasCnxSASLAuthenticated(ServerCnxn cnxn) { for (Id id : cnxn.getAuthInfo()) { <START> if (id.getScheme().equals("sasl")) { <END> return true; } } return false; }</code><technical_language>Do a constant for 'sasl'</technical_language>

Target:
private boolean hasCnxSASLAuthenticated(ServerCnxn cnxn) { for (Id id : cnxn.getAuthInfo()) { if (id.getScheme().equals(SASL_AUTH_SCHEME)) { return true; } } return false; }
Source:
<code>protected CliGitAPIImpl(String gitExe, File workspace, TaskListener listener, EnvVars environment) { super(workspace); this.listener = listener; this.gitExe = gitExe; this.environment = environment; <START> this.encoding = isZos() && System.getProperty("ibm.system.encoding")!=null ? <END> Charset.forName(System.getProperty("ibm.system.encoding")).toString() : Charset.defaultCharset().toString(); launcher = new LocalLauncher(IGitAPI.verbose ? listener : TaskListener.NULL); }</code><technical_language>I is needed in rest of file. rest of file acts this.encoding is String representation of a Charset name, this assignment this.encoding assigned true zOS false other platforms (at I tell). I assume methods encoding continue pass unit tests called methods default system encoding detect unrecognized encoding character set. Please retain prior meaning of this.encoding, is in other places in file</technical_language>

Target:
protected CliGitAPIImpl(String gitExe, File workspace, TaskListener listener, EnvVars environment) { super(workspace); this.listener = listener; this.gitExe = gitExe; this.environment = environment; if( isZos() && System.getProperty("ibm.system.encoding") != null ) { this.encoding = Charset.forName(System.getProperty("ibm.system.encoding")).toString(); } else { this.encoding = Charset.defaultCharset().toString(); } launcher = new LocalLauncher(IGitAPI.verbose ? listener : TaskListener.NULL); }
Source:
<code>public Iterable<Object> loadObjects(EntityProjection entityProjection, RequestScope scope) { Query query = buildQuery(entityProjection, scope); queryResult = queryEngine.executeQuery(query); <START> queryResult.run(); <END> try { QueryResult result = queryResult.get(); if (entityProjection.getPagination() != null && entityProjection.getPagination().returnPageTotals()) { entityProjection.getPagination().setPageTotals(result.getPageTotals()); } return result.getData(); } catch (TransactionException e) { throw new TransactionException(null); } catch (InterruptedException e) { throw new IllegalStateException(e); } catch (ExecutionException e) { throw new IllegalStateException(e); } }</code><technical_language>need call run() here. Calling queryResult.get() invoke queryResult.run()</technical_language>

Target:
public Iterable<Object> loadObjects(EntityProjection entityProjection, RequestScope scope) { Query query = buildQuery(entityProjection, scope); QueryResult result = null; String cacheKey = null; if (cache != null && !query.isBypassingCache()) { String tableVersion = queryEngine.getTableVersion(query.getTable(), queryEngineTransaction); if (tableVersion != null) { cacheKey = tableVersion + ';' + QueryKeyExtractor.extractKey(query); result = cache.get(cacheKey); } } if (result == null) { result = queryEngine.executeQuery(query, queryEngineTransaction); if (cacheKey != null) { cache.put(cacheKey, result); } } if (entityProjection.getPagination() != null && entityProjection.getPagination().returnPageTotals()) { entityProjection.getPagination().setPageTotals(result.getPageTotals()); } return result.getData(); }
Source:
<code>private void parseInternalVars(final BaseFBType type) throws TypeImportException, XMLStreamException { processChildren(LibraryElementTags.INTERNAL_VARS_ELEMENT, name -> { if <START> (name.equals(LibraryElementTags.VAR_DECLARATION_ELEMENT)) <END> { VarDeclaration v = parseVarDeclaration(); type.getInternalVars().add(v); return true; } return false; }); }</code><technical_language>call equals constant</technical_language>

Target:
private void parseInternalVars(final BaseFBType type) throws TypeImportException, XMLStreamException { processChildren(LibraryElementTags.INTERNAL_VARS_ELEMENT, name -> { if (LibraryElementTags.VAR_DECLARATION_ELEMENT.equals(name)) { VarDeclaration v = parseVarDeclaration(); type.getInternalVars().add(v); return true; } return false; }); }
Source:
<code>protected void configure() { bind(TypeMappings.class, JavaTypeMappings.class); bind(QueryTypeFactory.class, QueryTypeFactoryImpl.class); bind(EntitySerializer.class); bind(EmbeddableSerializer.class); bind(ProjectionSerializer.class); bind(SupertypeSerializer.class); <START> bind(String.class); <END> bind(PREFIX, "Q"); bind(SUFFIX, ""); bind(PACKAGE_SUFFIX, ""); bind(KEYWORDS, Collections.<String>emptySet()); bind(IMPORTS, Collections.<String>emptySet()); bind(QUERYDSL_VARIABLE_NAME_FUNCTION_CLASS, DefaultVariableNameFunction.class.getCanonicalName()); }</code><technical_language>named injection instead, keywords, String is a service interface</technical_language>

Target:
protected void configure() { bind(TypeMappings.class, JavaTypeMappings.class); bind(QueryTypeFactory.class, QueryTypeFactoryImpl.class); bind(EntitySerializer.class); bind(EmbeddableSerializer.class); bind(ProjectionSerializer.class); bind(SupertypeSerializer.class); bind(PREFIX, "Q"); bind(SUFFIX, ""); bind(PACKAGE_SUFFIX, ""); bind(KEYWORDS, Collections.<String>emptySet()); bind(IMPORTS, Collections.<String>emptySet()); bind(VARIABLE_NAME_FUNCTION_CLASS, new DefaultVariableNameFunction()); bind(CASE_TRANSFORMER_CLASS, UncapitalizedCaseTransformer.class.getCanonicalName()); }
Source:
<code>public Queue getDlcQueue() throws AndesAdminServiceBrokerManagerAdminException, java.rmi.RemoteException { Queue[] queueList = stub.getAllQueues(); Queue dlcQueue = null; if (queueList != null) { for (Queue queue : queueList) { String nameOfQueue = queue.getQueueName(); <START> if (nameOfQueue != null && nameOfQueue.contains("DeadLetterChannel")) { <END> dlcQueue = queue; break; } } } return dlcQueue; }</code><technical_language>a constant for "DeadLetterChannel". Check andes a constant for this access here</technical_language>

Target:
public Queue getDlcQueue() throws AndesAdminServiceBrokerManagerAdminException, java.rmi.RemoteException { Queue[] queueList = stub.getAllQueues(); Queue dlcQueue = null; if (null != queueList) { for (Queue queue : queueList) { String nameOfQueue = queue.getQueueName(); if (StringUtils.isNotBlank(nameOfQueue) && nameOfQueue.contains( AndesConstants.DEAD_LETTER_QUEUE_SUFFIX)) { dlcQueue = queue; break; } } } return dlcQueue; }
Source:
<code>public IAnswerData getAnswer() { <START> return !binding.widgetAnswerText.getText().equals(getContext().getString(R.string.no_date_selected)) <END> ? new DateData(selectedDate.toDate()) : null; }</code><technical_language>need negation if turn order: return binding.widgetAnswerText.getText().equals(getContext().getString(R.string.no_date_selected)) ? null : new DateData(selectedDate.toDate());</technical_language>

Target:
public IAnswerData getAnswer() { return binding.dateAnswerText.getText().equals(getContext().getString(R.string.no_date_selected)) ? null : new DateData(selectedDate.toDate()); }
Source:
<code><START> public void run() { <END> for (int i = 0; i < keyCount; i++) { String key = keys[random.nextInt(keys.length)]; try { map.put(key, createValue(key)); } catch (IOException e) { } } }</code><technical_language>This test run long testContext indicates; other tests. control long is stressing system I is need</technical_language>

Target:
public void run() { long iteration = 0; while (!testContext.isStopped()) { String key = keys[random.nextInt(keys.length)]; map.put(key, createValue(key,random)); iteration++; if (iteration % logFrequency == 0) { LOGGER.info(Thread.currentThread().getName() + " At iteration: " + iteration); } } }
Source:
<code>public static void scheduleNotification(Context context) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); <START> if (Integer.parseInt(sp.getString("minimumCardsDueForNotification", "1000001")) <= 1000000) <END> return; final Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, sp.getInt("dayOffset", 0)); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); final PendingIntent notificationIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NotificationReceiver.class), 0); alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, notificationIntent ); }</code><technical_language>time separated this settings instead of "magic number" 1000000 represent "pending messages available"? originally this in attempt minimize number of settings, kind of counter-productive here</technical_language>

Target:
public static void scheduleNotification(Context context) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); if (Integer.parseInt(sp.getString("minimumCardsDueForNotification", "1000001")) <= 1000000) { return; } final Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, sp.getInt("dayOffset", 0)); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); final PendingIntent notificationIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, NotificationReceiver.class), 0); alarmManager.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, notificationIntent ); }
Source:
<code><START> public DataValue copy() { <END> return new NullValue(); }</code><technical_language>public NullValue copy() i.p.v. DataValue</technical_language>

Target:
public NullValue copy() { return new NullValue(); }
Source:
<code><START> public MediaType getMediaType() { <END> if (TextUtils.isEmpty(mime_type)) { return MediaType.UNKNOWN; } else { if (mime_type.startsWith("audio")) { return MediaType.AUDIO; } else if (mime_type.startsWith("video")) { return MediaType.VIDEO; } else if (mime_type.equals("application/ogg")) { return MediaType.AUDIO; } } return MediaType.UNKNOWN; }</code><technical_language>this is asking for a helper function turns mime type in a MediaType. in MediaType enum</technical_language>

Target:
public MediaType getMediaType() { return MediaType.fromMimeType(mime_type); }
Source:
<code>public void testNoPrioritizedTypes() throws Exception { settings.put("citation.prioritized_types", ""); when(bitstreamFormat1.getMIMEType()).thenReturn("text/richtext"); when(bitstreamFormat2.getMIMEType()).thenReturn("application/msword"); when(bitstreamFormat3.getMIMEType()).thenReturn("application/postscript"); when(bitstream1.getSize()).thenReturn(new Long(100)); when(bitstream2.getSize()).thenReturn(new Long(200)); when(bitstream3.getSize()).thenReturn(new Long(300)); List<Bitstream> toSort = bundle.getBitstreams(); Collections.sort(toSort, new GoogleBitstreamComparator(context, settings)); <START> assertEquals("PS should be first", "bitstream3", toSort.get(0).getName()); <END> assertEquals("RTF second", "bitstream2", toSort.get(1).getName()); assertEquals("Word third", "bitstream1", toSort.get(2).getName()); }</code><technical_language>assert labels confusing size is making determination</technical_language>

Target:
public void testNoPrioritizedTypes() throws Exception { settings.put("citation.prioritized_types", ""); when(bitstreamFormat1.getMIMEType()).thenReturn("text/richtext"); when(bitstreamFormat2.getMIMEType()).thenReturn("application/msword"); when(bitstreamFormat3.getMIMEType()).thenReturn("application/postscript"); when(bitstream1.getSize()).thenReturn(new Long(100)); when(bitstream2.getSize()).thenReturn(new Long(200)); when(bitstream3.getSize()).thenReturn(new Long(300)); List<Bitstream> toSort = bundle.getBitstreams(); Collections.sort(toSort, new GoogleBitstreamComparator(context, settings)); assertEquals("PS should be first because it is the largest one and there is no type prioritization", "bitstream3", toSort.get(0).getName()); assertEquals("RTF should come second because it is the second largest and there is no type prioritization", "bitstream2", toSort.get(1).getName()); assertEquals("Word has to be last (third) as it is the smallest one and there is no type prioritization", "bitstream1", toSort.get(2).getName()); }
Source:
<code>public Map<Integer, Integer> getGIDsBySampleIds(final Set<Integer> sampleIds) { <START> Map<Integer, Integer> map = new HashMap<>(); <END> List<Object[]> result = this.getSession() .createCriteria(Sample.class, "sample") .createAlias("sample.plant", "plant") .createAlias("plant.experiment", "experiment") .createAlias("experiment.experimentStocks", "experimentStocks") .createAlias("experimentStocks.stock", "stock") .add(Restrictions.in("sampleId", sampleIds)) .setProjection(Projections.projectionList() .add(Projections.property("sample.sampleId")) .add(Projections.property("stock.dbxrefId"))) .list(); for (Object[] row : result) { map.put((Integer) row[0], (Integer) row[1]); } return map; }</code><technical_language>Please add final</technical_language>

Target:
public Map<Integer, Integer> getGIDsBySampleIds(final Set<Integer> sampleIds) { final Map<Integer, Integer> map = new HashMap<>(); final List<Object[]> result = this.getSession() .createCriteria(Sample.class, "sample") .createAlias("sample.plant", "plant") .createAlias("plant.experiment", "experiment") .createAlias("experiment.experimentStocks", "experimentStocks") .createAlias("experimentStocks.stock", "stock") .add(Restrictions.in("sampleId", sampleIds)) .setProjection(Projections.projectionList() .add(Projections.property("sample.sampleId")) .add(Projections.property("stock.dbxrefId"))) .list(); for (final Object[] row : result) { map.put((Integer) row[0], (Integer) row[1]); } return map; }
Source:
<code>public static ListPluginRequest createListPluginRequest(JsonObject request, HivePrincipal principal) { ListPluginRequest listPluginRequest = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED) .create() .fromJson(request, ListPluginRequest.class); <START> listPluginRequest.setTake(Optional.ofNullable(listPluginRequest.getTake()).orElse(20)); <END> listPluginRequest.setSkip(Optional.ofNullable(listPluginRequest.getSkip()).orElse(DEFAULT_SKIP)); listPluginRequest.setPrincipal(principal); return listPluginRequest; }</code><technical_language>Avoid magic numbers</technical_language>

Target:
public static ListPluginRequest createListPluginRequest(JsonObject request, HivePrincipal principal) { ListPluginRequest listPluginRequest = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED) .create() .fromJson(request, ListPluginRequest.class); listPluginRequest.setTake(Optional.ofNullable(listPluginRequest.getTake()).orElse(DEFAULT_TAKE)); listPluginRequest.setSkip(Optional.ofNullable(listPluginRequest.getSkip()).orElse(DEFAULT_SKIP)); listPluginRequest.setPrincipal(principal); return listPluginRequest; }