auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void initialiseAttributes(HttpServletRequest req) { request = req; requestUrl = HttpRequestHelper.getRequestedUrl(request); <START> currentUrl = request.getHeader("referer"); <END> logic = new Logic(); gateKeeper = new GateKeeper(); setTaskQueuer(new TaskQueuer()); setEmailSender(new EmailSender()); requestParameters = request.getParameterMap(); session = request.getSession(); sessionToken = CryptoHelper.computeSessionToken(session.getId()); parseAndInitializeRegkeyFromRequest(); isError = getRequestParamAsBoolean(Const.ParamsNames.ERROR); }</code><technical_language>currentUrl referer (or rather, referrer) a variable name</technical_language>

Target:
protected void initialiseAttributes(HttpServletRequest req) { request = req; requestUrl = HttpRequestHelper.getRequestedUrl(request); logic = new Logic(); gateKeeper = new GateKeeper(); setTaskQueuer(new TaskQueuer()); setEmailSender(new EmailSender()); requestParameters = request.getParameterMap(); session = request.getSession(); sessionToken = CryptoHelper.computeSessionToken(session.getId()); parseAndInitializeRegkeyFromRequest(); isError = getRequestParamAsBoolean(Const.ParamsNames.ERROR); }
Source:
<code>public static float getSize(String cssSize) { if (cssSize == null || cssSize.length() < 1) { throw new IllegalArgumentException("The parameter can't be null"); } <START> Stream<Unit> units = getUnits().filter(unit -> cssSize.endsWith(unit.toString())); String size; String unit = ""; try { unit = units.findFirst().get().toString(); } catch (NoSuchElementException e) { throw new IllegalArgumentException( "The parameter string '"+cssSize+"' does not contain valid unit"); } size = cssSize.substring(0,cssSize.length()-unit.length()); <END> if (size.isEmpty()) { size = "0"; } return Float.valueOf(size); }</code><technical_language>suggestion Unit unit = getUnits() .filter(value -> cssSize.endsWith(value.toString())).findFirst() .orElseThrow(() -> new IllegalArgumentException(String.format( "The parameter string '%s' valid unit", cssSize))); String size = cssSize .substring(0, cssSize.length() - unit.toString().length());</technical_language>

Target:
public static float getSize(String cssSize) { if (cssSize == null || cssSize.length() < 1) { throw new IllegalArgumentException("The parameter can't be null"); } Unit unit = getUnits() .filter(value -> cssSize.endsWith(value.toString())).findFirst() .orElseThrow(() -> new IllegalArgumentException(String.format( "The parameter string '%s' does not contain valid unit", cssSize))); String size = cssSize .substring(0, cssSize.length() - unit.toString().length()); if (size.isEmpty()) { size = "0"; } return Float.valueOf(size); }
Source:
<code>public void onReceive(Context context, Intent data) { DataHandler dh = KissApplication.getDataHandler(context); <START> ShortcutProvider sp = dh.getShortcutProvider(); <END> String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Log.d("onReceive", "Uninstall shortcut " + name); ShortcutPojo pojo = (ShortcutPojo) sp.findByName(name); if (pojo == null) { Log.d("onReceive", "Shortcut " + name + " not found"); return; } dh.getShortcutProvider().removeShortcut(pojo); dh.removeShortcut(context, pojo.name); }</code><technical_language>if for "shorcut handler null", forget check for null ;)</technical_language>

Target:
public void onReceive(Context context, Intent data) { DataHandler dh = KissApplication.getDataHandler(context); ShortcutProvider sp = dh.getShortcutProvider(); if (sp == null) return; String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Log.d("onReceive", "Uninstall shortcut " + name); ShortcutPojo pojo = (ShortcutPojo) sp.findByName(name); if (pojo == null) { Log.d("onReceive", "Shortcut " + name + " not found"); return; } dh.getShortcutProvider().removeShortcut(pojo); }
Source:
<code>private static String urlEncode(String string) { if(string == null) { return ""; } try { <START> return URLEncoder.encode(string, "UTF-8"); <END> } catch(UnsupportedEncodingException notGonnaHappen) { } return string; }</code><technical_language>constant for UTF-8</technical_language>

Target:
private static String urlEncode(String string) { if(string == null) { return ""; } try { return URLEncoder.encode(string, ENCODING); } catch(UnsupportedEncodingException notGonnaHappen) { } return string; }
Source:
<code>public void aggregate() { Object obj = selector.getObject(); <START> if (obj == null) { <END> return; } if (selector.getObject() instanceof Number) { synchronized (this) { histogram.add(((Number) selector.getObject()).doubleValue()); } } else if (selector.getObject() instanceof MergingDigest) { synchronized (this) { histogram.add((MergingDigest) selector.getObject()); } } else { TDigestSketchUtils.throwExceptionForWrongType(selector); } }</code><technical_language>nit: re-use obj instead of calling selector.getObject for if branch</technical_language>

Target:
public void aggregate() { Object obj = selector.getObject(); if (obj == null) { return; } if (obj instanceof Number) { synchronized (this) { histogram.add(((Number) obj).doubleValue()); } } else if (obj instanceof MergingDigest) { synchronized (this) { histogram.add((MergingDigest) obj); } } else { throw new IAE( "Expected a number or an instance of MergingDigest, but received [%s] of type [%s]", obj, obj.getClass() ); } }
Source:
<code>public void initialize(int capacity) { <START> neighbors = idTypeOps.createArrayList(capacity); <END> }</code><technical_language>call clear + setCapacity instead, reuse objects data is serialized? (I guess case this problem popped up)</technical_language>

Target:
public void initialize(int capacity) { neighbors.clear(); neighbors.setCapacity(capacity); }
Source:
<code>public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; for (StructuredRecord structuredRecord : structuredRecords) { Schema schema = structuredRecord.getSchema(); Object data = structuredRecord.get(config.bodyField); if (data == null) { LOG.debug("Found null data. Skipping record."); continue; } Schema.Field dataSchemaField = schema.getField(config.bodyField); PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(config.name); putRecordRequest.setPartitionKey(config.partition); switch (dataSchemaField.getSchema().getType()) { case BYTES: numRecordsWritten += writeBytes(putRecordRequest, data); break; case STRING: numRecordsWritten += writeString(putRecordRequest, data); break; default: <START> LOG.debug("Type is not supported for writing to stream", data.getClass().getName()); <END> break; } } return numRecordsWritten; }</code><technical_language>Kinesis supports bytes strings? Kinesis sync, need a projection plugin convert other types? add conversion for primitive types string here</technical_language>

Target:
public int write(Iterable<StructuredRecord> structuredRecords, DataWriter dataWriter) throws Exception { int numRecordsWritten = 0; for (StructuredRecord structuredRecord : structuredRecords) { Schema schema = structuredRecord.getSchema(); Object data = structuredRecord.get(config.bodyField); if (data == null) { LOG.debug("Found null data. Skipping record."); continue; } Schema.Field dataSchemaField = schema.getField(config.bodyField); PutRecordRequest putRecordRequest = new PutRecordRequest(); putRecordRequest.setStreamName(config.name); putRecordRequest.setPartitionKey(config.partition); switch (dataSchemaField.getSchema().getType()) { case BYTES: numRecordsWritten += writeBytes(putRecordRequest, data); break; case STRING: numRecordsWritten += writeString(putRecordRequest, data); break; case LONG: case DOUBLE: case FLOAT: case BOOLEAN: case INT: numRecordsWritten += writeString(putRecordRequest, String.valueOf(data)); break; default: throw new UnsupportedTypeException(String.format("Type %s is not supported for writing to stream", data.getClass().getName())); } } return numRecordsWritten; }
Source:
<code>private static String prompt() { StringBuilder input = new StringBuilder(); System.out.print(START_PROMPT); try { String lineSeparator = ""; while (true) { String line = reader.readLine(); if (line == null) { return null; } if (line.isEmpty()) { return input.toString(); } input.append(lineSeparator).append(line); StarlarkFile starlarkFile = StarlarkFile.parse(ParserInput.fromString(input.toString(), "<stdin>")); if (starlarkFile.ok()) { return input.toString(); } lineSeparator = "\n"; System.out.print(CONTINUATION_PROMPT); } } catch (IOException e) { System.err.format("Error reading line: %s\n", e); return null; <START> } <END> }</code><technical_language>Please this TODO: parser is able accurately stop reading. (See history of go.starlark.net REPL, is similar. some strange failure modes of approach implemented in this PR, is strictly improvement.)</technical_language>

Target:
private static String prompt() { StringBuilder input = new StringBuilder(); System.out.print(START_PROMPT); try { String lineSeparator = ""; while (true) { String line = reader.readLine(); if (line == null) { return null; } if (line.isEmpty()) { return input.toString(); } input.append(lineSeparator).append(line); StarlarkFile starlarkFile = StarlarkFile.parse(ParserInput.fromString(input.toString(), "<stdin>")); if (starlarkFile.ok()) { if (starlarkFile.getStatements().isEmpty()) { return input.toString(); } Statement lastStatement = starlarkFile.getStatements().get(starlarkFile.getStatements().size() - 1); switch (lastStatement.kind()) { case IF: case DEF: case FOR: break; default: return input.toString(); } } lineSeparator = "\n"; System.out.print(CONTINUATION_PROMPT); } } catch (IOException e) { System.err.format("Error reading line: %s\n", e); return null; } }
Source:
<code>public synchronized void init(QuipConfig config){ if(initialized){ <START> throw new RuntimeException("QuipStore is already initialized"); <END> } sourceFiles.put(QuipRequestTypes.COMPLIMENT, config.getComplimentsFile()); sourceFiles.put(QuipRequestTypes.WINSULT, config.getWinsultsFile()); sourceFiles.put(QuipRequestTypes.INSULT, config.getInsultsFile()); sourceFiles.put(QuipRequestTypes.BACKHANDED_COMPLIMENT, config.getBackhandedComplimentsFile()); refreshRate = config.getRefreshRate(); initialized = true; try{ updateQuips(QuipRequestTypes.COMPLIMENT); updateQuips(QuipRequestTypes.WINSULT); updateQuips(QuipRequestTypes.INSULT); updateQuips(QuipRequestTypes.BACKHANDED_COMPLIMENT); LOG.info("QuipStore initialized"); } catch(IOException e){ LOG.error("There was a problem loading quips",e); } }</code><technical_language>this a derpwizard exception</technical_language>

Target:
public synchronized void init(QuipConfig config){ if(initialized){ throw new RuntimeException("QuipStore is already initialized"); } if(config==null){return;} sourceFiles.put(QuipType.COMPLIMENT, config.getComplimentsFile()); sourceFiles.put(QuipType.WINSULT, config.getWinsultsFile()); sourceFiles.put(QuipType.INSULT, config.getInsultsFile()); sourceFiles.put(QuipType.BACKHANDED_COMPLIMENT, config.getBackhandedComplimentsFile()); refreshRate = config.getRefreshRate(); initialized = true; try{ updateQuips(QuipType.COMPLIMENT); updateQuips(QuipType.WINSULT); updateQuips(QuipType.INSULT); updateQuips(QuipType.BACKHANDED_COMPLIMENT); LOG.info("QuipStore initialized"); } catch(IOException e){ LOG.error("There was a problem loading quips",e); } }
Source:
<code><START> public InternationalFixedDate plus(final long amountToAdd, final TemporalUnit unit) { <END> if (amountToAdd == 0) { return this; } if (unit instanceof ChronoUnit) { ChronoUnit f = (ChronoUnit) unit; switch (f) { case DAYS: return plusDays(amountToAdd); case MONTHS: return plusMonths(amountToAdd); case YEARS: return plusYears(amountToAdd); default: break; } } return (InternationalFixedDate) super.plus(amountToAdd, unit); }</code><technical_language>Need special care weeks, leap-day year-day part of week. Discordian</technical_language>

Target:
public InternationalFixedDate plus(final long amountToAdd, final TemporalUnit unit) { if (unit instanceof ChronoUnit) { ChronoUnit f = (ChronoUnit) unit; switch (f) { case WEEKS: return plusWeeks(amountToAdd); case MONTHS: return plusMonths(amountToAdd); default: break; } } return (InternationalFixedDate) super.plus(amountToAdd, unit); }
Source:
<code>public ProjectList call() { final ProjectList result = new ProjectList(); result.setProjects(getProjects()); result.setCanCreateProject(user.getCapabilities().canCreateProject()); <START> return result; <END> }</code><technical_language>[optional] remove blank lines this method</technical_language>

Target:
public List<Project> call() { List<Project> result = new ArrayList<Project>(); for (Project.NameKey p : projectCache.all()) { try { ProjectControl c = projectControlFactory.controlFor(p); if (c.isVisible() || c.isOwner()) { result.add(c.getProject()); } } catch (NoSuchProjectException e) { continue; } } Collections.sort(result, new Comparator<Project>() { public int compare(final Project a, final Project b) { return a.getName().compareTo(b.getName()); } }); return result; }
Source:
<code><START> public ListViewColumnDescriptor getDescriptor() { <END> return (ListViewColumnDescriptor) Jenkins.getInstance().getDescriptorOrDie(getClass()); }</code><technical_language>Technically breaks binary compatibility. important in this case. sense DescriptorImpl a return type</technical_language>

Target:
public DescriptorImpl getDescriptor() { return (DescriptorImpl) Jenkins.getInstance().getDescriptorOrDie(getClass()); }
Source:
<code>private void createSickNotes(Person person) { <START> LocalDate now = ZonedDateTime.now(UTC).toLocalDate(); <END> SickNoteType sickNoteTypeStandard = null; SickNoteType sickNoteTypeChild = null; List<SickNoteType> sickNoteTypes = sickNoteTypeService.getSickNoteTypes(); for (SickNoteType sickNoteType : sickNoteTypes) { if (sickNoteType.isOfCategory(SickNoteCategory.SICK_NOTE)) { sickNoteTypeStandard = sickNoteType; } if (sickNoteType.isOfCategory(SickNoteCategory.SICK_NOTE_CHILD)) { sickNoteTypeChild = sickNoteType; } } sickNoteDataProvider.createSickNote(person, office, DayLength.NOON, now.minusDays(10), now.minusDays(10), sickNoteTypeStandard, false); sickNoteDataProvider.createSickNote(person, office, DayLength.FULL, now.minusDays(2), now.minusDays(2), sickNoteTypeStandard, false); sickNoteDataProvider.createSickNote(person, office, DayLength.FULL, now.minusDays(30), now.minusDays(25), sickNoteTypeStandard, true); sickNoteDataProvider.createSickNote(person, office, DayLength.FULL, now.minusDays(40), now.minusDays(38), sickNoteTypeChild, false); }</code><technical_language>LocalDate.now(UTC);</technical_language>

Target:
private void createSickNotes(Person person) { LocalDate now = LocalDate.now(UTC); SickNoteType sickNoteTypeStandard = null; SickNoteType sickNoteTypeChild = null; List<SickNoteType> sickNoteTypes = sickNoteTypeService.getSickNoteTypes(); for (SickNoteType sickNoteType : sickNoteTypes) { if (sickNoteType.isOfCategory(SickNoteCategory.SICK_NOTE)) { sickNoteTypeStandard = sickNoteType; } if (sickNoteType.isOfCategory(SickNoteCategory.SICK_NOTE_CHILD)) { sickNoteTypeChild = sickNoteType; } } sickNoteDataProvider.createSickNote(person, office, DayLength.NOON, now.minusDays(10), now.minusDays(10), sickNoteTypeStandard, false); sickNoteDataProvider.createSickNote(person, office, DayLength.FULL, now.minusDays(2), now.minusDays(2), sickNoteTypeStandard, false); sickNoteDataProvider.createSickNote(person, office, DayLength.FULL, now.minusDays(30), now.minusDays(25), sickNoteTypeStandard, true); sickNoteDataProvider.createSickNote(person, office, DayLength.FULL, now.minusDays(40), now.minusDays(38), sickNoteTypeChild, false); }
Source:
<code>private void waitForUpdates(long timeout, long numUpdates) throws InterruptedException { long startTime = System.currentTimeMillis(); long pre = 0L; synchronized (updateLock) { pre = updates.get(); } do { Thread.sleep(5); <START> log.info("Waiting for updateLock"); <END> synchronized (updateLock) { Assert.assertTrue("Failed waiting for update", System.currentTimeMillis() - startTime < timeout); } } while (updates.get() < pre + numUpdates); }</code><technical_language>this generate a lot of log messages if printed 5ms. increase sleep time a ms move this trace / debug level</technical_language>

Target:
private void waitForUpdates(long timeout, long numUpdates) throws InterruptedException { long startTime = System.currentTimeMillis(); long pre = 0L; synchronized (updateLock) { pre = updates.get(); } long post = 0L; do { Thread.sleep(5); log.debug("Waiting for updateLock"); synchronized (updateLock) { Assert.assertTrue("Failed waiting for update", System.currentTimeMillis() - startTime < timeout); post = updates.get(); } } while (post < pre + numUpdates); }
Source:
<code>public <V> Pair<K, V> update(final K id, final V deltaValue) { final int blockId = blockResolver.resolveBlock(id); final Optional<String> remoteEvalId = router.resolveEval(blockId); if (remoteEvalId.isPresent()) { final SingleKeyOperation<K, V> operation = remoteOpHandler.sendOpToRemoteStore(DataOpType.UPDATE, id, Optional.of(deltaValue), remoteEvalId.get()); return new Pair<>(id, operation.getOutputData().get()); } else { final Block<V> block = blocks.get(blockId); final V output = block.update(id, deltaValue); <START> return output == null ? null : new Pair<>(id, output); <END> } }</code><technical_language>possibilities of a null return here? I guess a case depends clients define ParameterUpdater, is happen? out of curiosity, this more of entire EM question</technical_language>

Target:
public <V> Pair<K, V> update(final K id, final V deltaValue) { final int blockId = blockResolver.resolveBlock(id); final Optional<String> remoteEvalId = router.resolveEval(blockId); if (remoteEvalId.isPresent()) { final SingleKeyOperation<K, V> operation = remoteOpHandler.sendOpToRemoteStore(DataOpType.UPDATE, id, Optional.of(deltaValue), remoteEvalId.get()); return new Pair<>(id, operation.getOutputData().get()); } else { final Block<V> block = blocks.get(blockId); final V output = block.update(id, deltaValue); return new Pair<>(id, output); } }
Source:
<code>private static void addResponseHeaderWithOverride( HttpServletRequest request, HttpServletResponse response, String headerName, String overrideHeaderName, String value) { if (logger.isDebugEnabled()) { logger.debug("entry > addResponseHeaderWithOverride(). " + "headerName: {}, overideHeaderName: {}, value: {}", headerName, overrideHeaderName, value); } String override = request.getParameter(overrideHeaderName); override = (override != null) ? override : value; if (override != null) { response.addHeader(headerName, override); } <START> if (logger.isDebugEnabled()) { <END> logger.debug("exit < addResponseHeaderWithOverride()"); } }</code><technical_language>check isDebugEnabled this optimize out</technical_language>

Target:
private static void addResponseHeaderWithOverride( HttpServletRequest request, HttpServletResponse response, String headerName, String overrideHeaderName, String value) { logger.debug("entry > addResponseHeaderWithOverride(). " + "headerName: {}, overideHeaderName: {}, value: {}", headerName, overrideHeaderName, value); String override = request.getParameter(overrideHeaderName); override = (override != null) ? override : value; if (override != null) { response.addHeader(headerName, override); } logger.debug("exit < addResponseHeaderWithOverride()"); }
Source:
<code>public final Response act(final Request req) throws IOException { boolean hasorigin = false; Response response; String domain = ""; for (final String head : req.head()) { if (head.startsWith(ORIGIN_PREFIX)) { hasorigin = true; domain = head.split(ORIGIN_PREFIX)[1].trim(); break; } } if (hasorigin && ( <START> this.alloweddomains.size() == 0 <END> || this.alloweddomains.contains(domain))) { response = this.origin.act(req); final Set<String> headers = new HashSet<String>(); headers.add("Access-Control-Allow-Credentials: true"); headers.add("Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE, HEAD"); headers.add( String.format("Access-Control-Allow-Origin: %s", domain) ); response = new RsWithHeaders(response, headers); } else if (hasorigin) { final Set<String> headers = new HashSet<String>(); headers.add("Access-Control-Allow-Credentials: false"); response = new RsWithStatus(HttpURLConnection.HTTP_FORBIDDEN); response = new RsWithHeaders(response, headers); } else { response = this.origin.act(req); } return response; }</code><technical_language>@antonini isEmpty() method instead of size comparison</technical_language>

Target:
public Response act(final Request req) throws IOException { String domain; final Response response; try { domain = new RqHeaders.Smart( new RqHeaders.Base(req) ).single("origin"); } catch (final IOException exp) { domain = ""; } if (this.allowed.contains(domain)) { response = new RsWithHeaders( this.origin.act(req), "Access-Control-Allow-Credentials: true", "Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE, HEAD", String.format( "Access-Control-Allow-Origin: %s", domain ) ); } else { response = new RsWithHeaders( new RsWithStatus( HttpURLConnection.HTTP_FORBIDDEN ), "Access-Control-Allow-Credentials: false" ); } return response; }
Source:
<code>public Node visitColumnDefinition(SqlBaseParser.ColumnDefinitionContext context) { Optional<String> comment = Optional.empty(); List<Property> properties = ImmutableList.of(); boolean nullable = true; Optional<Literal> defaultValue = Optional.empty(); if (context.COMMENT() != null) { comment = Optional.of(((StringLiteral) visit(context.string())).getValue()); } <START> else if (context.properties() != null) { <END> properties = visit(context.properties().property(), Property.class); } else if (context.defaultValue != null) { defaultValue = Optional.of((Literal) visit(context.defaultValue)); } else if (context.NOT() != null) { nullable = false; } return new ColumnDefinition( getLocation(context), (Identifier) visit(context.identifier()), getType(context.type()), properties, comment, nullable, defaultValue); }</code><technical_language>else</technical_language>

Target:
public Node visitColumnDefinition(SqlBaseParser.ColumnDefinitionContext context) { Identifier columnIdentifier = (Identifier) visit(context.identifier()); Optional<String> comment = Optional.empty(); if (context.COMMENT() != null) { comment = Optional.of(((StringLiteral) visit(context.string())).getValue()); } List<Property> properties = ImmutableList.of(); if (context.properties() != null) { properties = visit(context.properties().property(), Property.class); } Optional<Literal> defaultValue = Optional.empty(); if (context.defaultValue != null) { Node defaultValueNode = visit(context.defaultValue); if (!(defaultValueNode instanceof Literal)) { throw parseError(format("Default value (%s) for column %s is not a literal expression", context.defaultValue.getText(), columnIdentifier.getValue()), context); } defaultValue = Optional.of((Literal) defaultValueNode); } boolean nullable = true; if (context.NOT() != null) { nullable = false; } return new ColumnDefinition( getLocation(context), columnIdentifier, getType(context.type()), properties, comment, nullable, defaultValue); }
Source:
<code>public void onApplicationEvent(WebServerInitializedEvent event) { String contextName = event.getApplicationContext().getServerNamespace(); <START> if (StringUtils.isEmpty(contextName)) { <END> int localPort = event.getWebServer().getPort(); if (this.port.get() == 0) { log.info("Updating port to " + localPort); this.port.compareAndSet(0, localPort); start(); } } }</code><technical_language>Is a guarantee this true</technical_language>

Target:
public void onApplicationEvent(WebServerInitializedEvent event) { String contextName = event.getApplicationContext().getServerNamespace(); if (contextName == null || !contextName.equals("management")) { int localPort = event.getWebServer().getPort(); if (this.port.get() == 0) { log.info("Updating port to " + localPort); this.port.compareAndSet(0, localPort); start(); } } }
Source:
<code>public String toString() { return new StringJoiner(", ", TestOutputTopic.class.getSimpleName() + "[", "]") .add("topic='" + topic + "'") <START> .add("keyDeserializer=" + keyDeserializer) <END> .add("valueDeserializer=" + valueDeserializer) .add("size=" + getQueueSize()) .toString(); }</code><technical_language>keyDeserializer.getClass().getSimpleName() (same for value)</technical_language>

Target:
public String toString() { return new StringJoiner(", ", TestOutputTopic.class.getSimpleName() + "[", "]") .add("topic='" + topic + "'") .add("keyDeserializer=" + keyDeserializer.getClass().getSimpleName()) .add("valueDeserializer=" + valueDeserializer.getClass().getSimpleName()) .add("size=" + getQueueSize()) .toString(); }
Source:
<code>private static Cache<?, ?> checkValidConfiguration(final Cache<?, ?> cache, String indexName) { if (cache == null) { return null; } Configuration configuration = cache.getCacheConfiguration(); if (configuration.expiration().maxIdle() != -1) { throw log.luceneStorageHavingIdleTimeSet( indexName, cache.getName() ); } if (configuration.expiration().lifespan() != -1) { throw log.luceneStorageHavingLifespanSet( indexName, cache.getName() ); } if (configuration.storeAsBinary().enabled()) { throw log.luceneStorageAsBinaryEnabled(indexName, cache.getName()); } <START> if (configuration.clustering().cacheMode().isClustered() && !StateConsumerImpl.isFetchStateEnabled(configuration)) { <END> throw log.luceneStorageNoStateTransferEnabled(indexName, cache.getName()); } return cache; }</code><technical_language>passivation is enabled, fetchInMemoryState fetchPersistentState enabled. passivation is disabled cache store is shared, I enabling kind of state transfer is required</technical_language>

Target:
private static Cache<?, ?> checkValidConfiguration(final Cache<?, ?> cache, String indexName) { if (cache == null) { return null; } Configuration configuration = cache.getCacheConfiguration(); if (configuration.expiration().maxIdle() != -1) { throw log.luceneStorageHavingIdleTimeSet( indexName, cache.getName() ); } if (configuration.expiration().lifespan() != -1) { throw log.luceneStorageHavingLifespanSet( indexName, cache.getName() ); } if (configuration.storeAsBinary().enabled()) { throw log.luceneStorageAsBinaryEnabled(indexName, cache.getName()); } if (!Configurations.noDataLossOnJoiner(configuration)) { throw log.luceneStorageNoStateTransferEnabled(indexName, cache.getName()); } return cache; }
Source:
<code>private String getTargetBranchName(final Composite parent, Repository localRepo) { Set<String> branches = null; try { branches = getShortLocalBranchNames(new Git(localRepo)); } catch (GitAPIException e1) { Status status = new Status(IStatus.ERROR, EGerritCorePlugin.PLUGIN_ID, "No branches found"); ErrorDialog.openError(parent.getShell(), "Error", "Operation could not be performed", status); return ""; } String shortName = fChangeInfo.get_number() + "/" + filesTab.getSelectedPatchSetNumber(); Iterator<String> iterator = branches.iterator(); String branchName = null; while (iterator.hasNext()) { String setElement = iterator.next(); if (setElement.contains(shortName)) { <START> branchName = setElement; <END> } } return branchName; }</code><technical_language>putting a break find branch</technical_language>

Target:
private String getTargetBranchName(final Composite parent, Repository localRepo) { Set<String> branches = null; try { branches = getShortLocalBranchNames(new Git(localRepo)); } catch (GitAPIException e1) { Status status = new Status(IStatus.ERROR, EGerritCorePlugin.PLUGIN_ID, "No branches found"); ErrorDialog.openError(parent.getShell(), "Error", "Operation could not be performed", status); return ""; } String shortName = fChangeInfo.get_number() + "/" + filesTab.getSelectedPatchSetNumber(); Iterator<String> iterator = branches.iterator(); String branchName = null; while (iterator.hasNext()) { String setElement = iterator.next(); if (setElement.contains(shortName)) { branchName = setElement; break; } } return branchName; }
Source:
<code>public void matchesWithAnyTypes() throws IOException { MatcherAssert.assertThat( new FkContentType( "text/xml", FkContentTypeTest.createTakeWithEmptyResponse() <START> ).route( <END> new RqWithHeader( new RqFake(), FkContentTypeTest.CONTENT_TYPE, "*/* " ) ).has(), Matchers.is(true) ); }</code><technical_language>@dalifreire wrong indentation here, this line 4 spaces</technical_language>

Target:
public void matchesWithAnyTypes() throws IOException { MatcherAssert.assertThat( new FkContentType("text/xml", new RsEmpty()).route( new RqWithHeader( new RqFake(), FkContentTypeTest.CONTENT_TYPE, "*/* " ) ).has(), Matchers.is(true) ); }
Source:
<code>public void onlyTheLatestTransactionIsKeptAfterIncrementalBackup() throws Exception { db.withSetting( GraphDatabaseSettings.keep_logical_logs, "1 txs" ) .withSetting( GraphDatabaseSettings.logical_log_rotation_threshold, "1M" ); int port = 4446; startDb( "" + port ); createSomeData( db ); String backupName = "backupName" + recordFormat; File backupLocation = new File( backupDir, backupName ); String address = "localhost:" + port; assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( "--from", address, "--cc-report-dir=" + backupDir, "--backup-dir=" + backupDir, "--name=" + backupName ) ); long megabytes = 1024 * 1024; long numberOfBytesInTx = 100; <START> long defaultLogRotationPolicyM = 250; END> LongStream.range( 0, defaultLogRotationPolicyM ).forEach( number -> createSomeData( db, megabytes / numberOfBytesInTx ) ); assertEquals( "Server should have 3 tx log files", 3, transactionFiles( db.getStoreDirFile() ).size() ); assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( "--from", address, "--cc-report-dir=" + backupDir, "--backup-dir=" + backupDir, "--name=" + backupName ) ); Collection<File> txLogFiles = transactionFiles( backupLocation ); File expectedTxLogFile1 = new File( backupLocation, "neostore.transaction.db.1" ); File expectedTxLogFile2 = new File( backupLocation, "neostore.transaction.db.2" ); assertEquals( "Backup client retains latest incomplete tx log and previous complete log: " + txLogFiles.toString(), 2, txLogFiles.size() ); assertEquals( new HashSet<>( Arrays.asList( expectedTxLogFile1, expectedTxLogFile2 ) ), new HashSet<>( txLogFiles ) ); }</code><technical_language>this todo fixed</technical_language>

Target:
public void onlyTheLatestTransactionIsKeptAfterIncrementalBackup() throws Exception { int port = 4446; startDb( "" + port ); createSomeData( db ); String backupName = "backupName" + recordFormat; File backupLocation = new File( backupDir, backupName ); String address = "localhost:" + port; assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( "--from", address, "--cc-report-dir=" + backupDir, "--backup-dir=" + backupDir, "--name=" + backupName ) ); long aMegabyte = ByteUnit.mebiBytes( 1 ); long numberOfBytesInTx = 100; LongStream.range( 0, 205 ).forEach( number -> createSomeData( db, aMegabyte / numberOfBytesInTx ) ); assertEquals( "Server should have 3 tx log files", 3, transactionFiles( db.getStoreDirFile() ).size() ); assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( "--from", address, "--cc-report-dir=" + backupDir, "--backup-dir=" + backupDir, "--name=" + backupName ) ); Collection<File> txLogFiles = transactionFiles( backupLocation ); File expectedTxLogFile1 = new File( backupLocation, "neostore.transaction.db.1" ); File expectedTxLogFile2 = new File( backupLocation, "neostore.transaction.db.2" ); assertEquals( new HashSet<>( Arrays.asList( expectedTxLogFile1, expectedTxLogFile2 ) ), new HashSet<>( txLogFiles ) ); }
Source:
<code>boolean updateMoreAggInfo(HTable aggTable, AppAggregationKey appAggKey, JobDetails jobDetails) throws IOException { int attempts = 0; boolean status = false; <START> while ((status != true) && (attempts < AggregationConstants.RETRY_COUNT)) { <END> status = updateNumberRuns(appAggKey, aggTable, jobDetails); attempts++; } attempts = 0; status = false; while ((status != true) && (attempts < AggregationConstants.RETRY_COUNT)) { status = updateQueue(appAggKey, aggTable, jobDetails); attempts++; } attempts = 0; status = false; while ((status != Boolean.TRUE) && (attempts < AggregationConstants.RETRY_COUNT)) { status = updateCost(appAggKey, aggTable, jobDetails); attempts++; } byte[] rowKey = aggConv.toBytes(appAggKey); Put p = new Put(rowKey); p.add(Constants.INFO_FAM_BYTES, AggregationConstants.USER_BYTES, Bytes.toBytes(appAggKey.getUserName())); p.add(Constants.INFO_FAM_BYTES, AggregationConstants.APP_ID_COL_BYTES, Bytes.toBytes(appAggKey.getAppId())); aggTable.put(p); return true; }</code><technical_language>offline discussion limiting this 2 tries. awkward if (for reason) status turn true in 2 tries. silently ignoring failure. do think? Also, (status != true) -> !status</technical_language>

Target:
boolean updateMoreAggInfo(HTable aggTable, AppAggregationKey appAggKey, JobDetails jobDetails) throws IOException { int attempts = 0; boolean status = false; while ((!status) && (attempts < AggregationConstants.RETRY_COUNT)) { status = updateNumberRuns(appAggKey, aggTable, jobDetails); attempts++; } attempts = 0; status = false; while ((!status) && (attempts < AggregationConstants.RETRY_COUNT)) { status = updateQueue(appAggKey, aggTable, jobDetails); attempts++; } attempts = 0; status = false; while ((!status) && (attempts < AggregationConstants.RETRY_COUNT)) { status = updateCost(appAggKey, aggTable, jobDetails); attempts++; } byte[] rowKey = aggConv.toBytes(appAggKey); Put p = new Put(rowKey); p.add(Constants.INFO_FAM_BYTES, AggregationConstants.USER_BYTES, Bytes.toBytes(appAggKey.getUserName())); p.add(Constants.INFO_FAM_BYTES, AggregationConstants.APP_ID_COL_BYTES, Bytes.toBytes(appAggKey.getAppId())); aggTable.put(p); return true; }
Source:
<code>protected Runnable getCallback(final RefreshProfileDialog dialog) { return new Runnable() { public void run() { Map<Package, Collection<Profile>> profilesToReapply = dialog.getProfilesToReapply(); EditingDomain domain = EMFHelper.resolveEditingDomain(rootPackage); if(domain instanceof TransactionalEditingDomain) { Collection<Profile> allProfiles = new LinkedList<Profile>(); for(Collection<Profile> profiles : profilesToReapply.values()) { allProfiles.addAll(profiles); } if(ProfileValidationHelper.checkApplicableProfiles(Display.getCurrent().getActiveShell(), allProfiles)) { CompoundCommand command = new CompoundCommand(); for(Map.Entry<Package, Collection<Profile>> profiles : profilesToReapply.entrySet()) { command.append(new ApplyProfileCommand(profiles.getKey(), profiles.getValue(), (TransactionalEditingDomain)domain)); <START> command.append(new ApplyProfileVersionCommand(profiles.getKey(), profiles.getValue(), (TransactionalEditingDomain)domain)); <END> } domain.getCommandStack().execute(command); } } else { Activator.log.error(new IllegalArgumentException("Cannot reapply profiles on Package " + rootPackage.getQualifiedName() + ". The EditingDomain cannot be found")); } } }; }</code><technical_language>Ah, I see. I thought a refactoring/upgrade of ApplyProfileCommand, name thing. I agree useful separate concepts, if want able apply profiles this new annotation. if want enforce annotation, combine in command? fence this point ..</technical_language>

Target:
protected Runnable getCallback(final RefreshProfileDialog dialog) { return new Runnable() { public void run() { Map<Package, Collection<Profile>> profilesToReapply = dialog.getProfilesToReapply(); EditingDomain domain = EMFHelper.resolveEditingDomain(rootPackage); if(domain instanceof TransactionalEditingDomain) { Collection<Profile> allProfiles = new LinkedList<Profile>(); for(Collection<Profile> profiles : profilesToReapply.values()) { allProfiles.addAll(profiles); } if(ProfileValidationHelper.checkApplicableProfiles(Display.getCurrent().getActiveShell(), allProfiles)) { CompoundCommand command = new CompoundCommand(); for(Map.Entry<Package, Collection<Profile>> profiles : profilesToReapply.entrySet()) { command.append(new ApplyProfileCommand(profiles.getKey(), profiles.getValue(), (TransactionalEditingDomain)domain)); } domain.getCommandStack().execute(command); } } else { Activator.log.error(new IllegalArgumentException("Cannot reapply profiles on Package " + rootPackage.getQualifiedName() + ". The EditingDomain cannot be found")); } } }; }
Source:
<code>public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) throws ConfigurationException { logger.debug("activate is called."); this.bundleContext = bundleContext; context.setProviders(providers); String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } context.getConfig().parse(configuration); <START> logger.info(context.getConfig().toString()); <END> communicator.start(); setProperlyConfigured(true); }</code><technical_language>decrease DEBUG</technical_language>

Target:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) throws ConfigurationException { logger.debug("activate is called."); context.setProviders(providers); String refreshIntervalString = (String) configuration.get("poll.interval"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } context.getConfig().parse(configuration); logger.debug(context.getConfig().toString()); communicator.start(); setProperlyConfigured(true); }
Source:
<code>public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } <START> mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); <END> storeRenderer(mRenderer); }</code><technical_language>I mRenderer converted a local variable (instead of member variable) here? GeoJsonLayer extends Layer, is a reference GeoJsonRenderer superclass Renderer Layers.storeRenderer()</technical_language>

Target:
public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } GeoJsonRenderer mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); storeRenderer(mRenderer); }
Source:
<code>Class<?> getTypeParameterDescriptorForRelationship(String relationshipType, Direction relationshipDirection) { final boolean STRICT_MODE = true; final boolean INFERRED_MODE = false; try { FieldInfo fieldInfo = relationshipField(relationshipType, relationshipDirection, STRICT_MODE); if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) { return DescriptorMappings.getType(fieldInfo.getTypeDescriptor()); } <START> if (!relationshipDirection.equals(Direction.INCOMING)) { END> fieldInfo = relationshipField(relationshipType, relationshipDirection, INFERRED_MODE); if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) { return DescriptorMappings.getType(fieldInfo.getTypeDescriptor()); } } } catch (RuntimeException e) { LOGGER.debug("Could not get class type for relationshipType and relationshipDirection ", className, relationshipType, relationshipDirection); } return null; }</code><technical_language>suggestion if (relationshipDirection != Direction.INCOMING) { //we expect annotation for INCOMING</technical_language>

Target:
Class<?> getTypeParameterDescriptorForRelationship(String relationshipType, Direction relationshipDirection) { final boolean STRICT_MODE = true; final boolean INFERRED_MODE = false; try { FieldInfo fieldInfo = relationshipField(relationshipType, relationshipDirection, STRICT_MODE); if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) { return DescriptorMappings.getType(fieldInfo.getTypeDescriptor()); } if (relationshipDirection != Direction.INCOMING) { fieldInfo = relationshipField(relationshipType, relationshipDirection, INFERRED_MODE); if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) { return DescriptorMappings.getType(fieldInfo.getTypeDescriptor()); } } } catch (RuntimeException e) { LOGGER.debug("Could not get class type for relationshipType and relationshipDirection ", className, relationshipType, relationshipDirection); } return null; }
Source:
<code>Bitmap decodeContentStream(Uri path, PicassoBitmapOptions options) throws IOException { ContentResolver contentResolver = context.getContentResolver(); if (options != null && options.inJustDecodeBounds) { InputStream is = null; try { is = contentResolver.openInputStream(path); BitmapFactory.decodeStream(is, null, options); } finally { Utils.closeQuietly(is); } <START> calculateInSampleSize(options); <END> } InputStream is = null; try { is = contentResolver.openInputStream(path); return BitmapFactory.decodeStream(contentResolver.openInputStream(path), null, options); } finally { Utils.closeQuietly(is); } }</code><technical_language>push this BitmapHunter? subclasses</technical_language>

Target:
private Bitmap decodeContentStream(Uri path, PicassoBitmapOptions options) throws IOException { ContentResolver contentResolver = context.getContentResolver(); if (options != null && options.inJustDecodeBounds) { InputStream is = null; try { is = contentResolver.openInputStream(path); BitmapFactory.decodeStream(is, null, options); } finally { Utils.closeQuietly(is); } calculateInSampleSize(options); } InputStream is = null; try { is = contentResolver.openInputStream(path); return BitmapFactory.decodeStream(contentResolver.openInputStream(path), null, options); } finally { Utils.closeQuietly(is); } }
Source:
<code>public void valueMapShouldReturnAProperDeserializedJsonMap() { String json = "{ \"fruit\" : \"pear\" , \"color\" : \"green\" }"; Map<String, Object> expected = new LinkedHashMap<String, Object>(); expected.put("fruit", "pear"); expected.put("color", "green"); ValueMap valueMap = new ValueMap().withJSON(KEY, json); <START> Map<String,Object> actual = (Map<String,Object>)valueMap.get(KEY); <END> assertThat(actual, is(expected)); }</code><technical_language>add suppress warnings @SuppressWarnings("unchecked") (and for cast List below)</technical_language>

Target:
public void valueMapShouldReturnAProperDeserializedJsonMap() { String json = "{ \"fruit\" : \"pear\" , \"color\" : \"green\" }"; ValueMap valueMap = new ValueMap().withJSON(KEY, json); Map<String,Object> actual = (Map<String,Object>)valueMap.get(KEY); assertThat(actual.size(), is(2)); assertThat((String)actual.get("fruit"), is("pear")); assertThat((String)actual.get("color"), is("green")); }
Source:
<code>public CallStatus run() { if(stream) { context = metrics.startStreamingEntityRequest("find", entity, version); <START> } <END> LOGGER.debug("run: entity={}, version={}", entity, version); Error.reset(); Error.push("rest"); Error.push(getClass().getSimpleName()); Error.push(entity); try { FindRequest ireq; try { ireq = getJsonTranslator().parse(FindRequest.class, JsonUtils.json(request)); } catch (Exception e) { LOGGER.error("find:parse failure: {}", e); return new CallStatus(Error.get(RestCrudConstants.ERR_REST_FIND, "Error during the parse of the request")); } LOGGER.debug("Find request:{}", ireq); try { validateReq(ireq, entity, version); } catch (Exception e) { LOGGER.error("find:validate failure: {}", e); return new CallStatus(Error.get(RestCrudConstants.ERR_REST_FIND, "Request is not valid")); } addCallerId(ireq); if(stream) { streamResponse=getMediator(metrics).findAndStream(ireq); return new CallStatus(new Response()); } else { return new CallStatus(getMediator(metrics).find(ireq)); } } catch (Error e) { LOGGER.error("find:generic_error failure: {}", e); return new CallStatus(e); } catch (Exception e) { LOGGER.error("find:generic_exception failure: {}", e); return new CallStatus(Error.get(RestCrudConstants.ERR_REST_FIND, e.toString())); } }</code><technical_language>need pollute HTTP layer this here, track in Mediator. listen for streaming results depleted</technical_language>

Target:
public CallStatus run() { if (stream) { metricCtx = metrics.startStreamingEntityRequest("find", entity, version); } else { metricCtx = metrics.startEntityRequest("find", entity, version); } LOGGER.debug("run: entity={}, version={}", entity, version); Error.reset(); Error.push("rest"); Error.push(getClass().getSimpleName()); Error.push(entity); Response r = null; try { FindRequest ireq; try { ireq = getJsonTranslator().parse(FindRequest.class, JsonUtils.json(request)); } catch (Exception e) { Error error = Error.get(RestCrudConstants.ERR_REST_FIND, "Error during the parse of the request"); metricCtx.markRequestException(error); LOGGER.error("find:parse failure: {}", e); return new CallStatus(error); } LOGGER.debug("Find request:{}", ireq); try { validateReq(ireq, entity, version); } catch (Exception e) { Error error = Error.get(RestCrudConstants.ERR_REST_FIND, "Request is not valid"); metricCtx.markRequestException(error); LOGGER.error("find:validate failure: {}", e); return new CallStatus(error); } addCallerId(ireq); if(stream) { streamResponse = getMediator().findAndStream(ireq); return new CallStatus(new Response()); } else { r = getMediator().find(ireq); return new CallStatus(r); } } catch (Error e) { metricCtx.markRequestException(e); LOGGER.error("find:generic_error failure: {}", e); return new CallStatus(e); } catch (Exception e) { Error error = Error.get(RestCrudConstants.ERR_REST_FIND, e.toString()); metricCtx.markRequestException(error); LOGGER.error("find:generic_exception failure: {}", e); return new CallStatus(error); } finally { if (streamResponse == null) { if (r != null) { metricCtx.markAllErrorsAndEndRequestMonitoring(r.getErrors()); } else { metricCtx.endRequestMonitoring(); } } } }
Source:
<code>protected void executeCommand() { <START> VmPoolMap map = getVmPoolDAO().getVmPoolMapByVmGuid(getVmId()); <END> List<DbUser> users = getDbUserDAO().getAllForVm(getVmId()); if (map != null && users != null && !users.isEmpty()) { VmPool pool = getVmPoolDAO().get(map.getvm_pool_id()); if (pool != null && pool.getVmPoolType() == VmPoolType.Automatic) { for (DbUser dbUser : users) { Backend.getInstance().runInternalAction(VdcActionType.DetachUserFromVmFromPool, new VmPoolSimpleUserParameters(map.getvm_pool_id(), dbUser.getId(), getVmId()), ExecutionHandler.createDefaultContexForTasks(getExecutionContext(), getLock())); } } } else { removeVmStatelessImages(); } QuotaManager.getInstance().rollbackQuotaByVmId(getVmId()); removeStatelessVmUnmanagedDevices(); applyNextRunConfiguration(); }</code><technical_language>i dont need map, get vmPoolId vm object</technical_language>

Target:
protected void executeCommand() { boolean statelessSnapshotRemoved = detachUsers(); if (!statelessSnapshotRemoved) { removeVmStatelessImages(); } QuotaManager.getInstance().rollbackQuotaByVmId(getVmId()); removeStatelessVmUnmanagedDevices(); applyNextRunConfiguration(); }