auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onPlaybackComplete() { try{ if(player!=null){ double current_time = player.getCurrentPosition()/AppConstants.MILLISECONDS_PER_SECOND ; environment.getAnalyticsRegistry().trackVideoStop(videoEntry.videoId, current_time, videoEntry.eid, videoEntry.lmsUrl); } }catch(Exception e){ logger.error(e); } if (callback != null) { callback.saveCurrentPlaybackPosition(0); callback.onPlaybackComplete(); } hideCCPopUp(); hideSettingsPopUp(); try{ if(player!=null){ if(player.getController()!=null){ player.getController().showSpecial( (getTouchExploreEnabled() ? 0L : 5000L) ); } } } catch(Exception e) { logger.error(e); } if (environment.getConfig().isAppReviewsEnabled() && NetworkUtil.isConnected(getContext())) { <START> PrefManager.UserPrefManager userPrefs = new PrefManager.UserPrefManager(MainApplication.application); <END> final float appRating = userPrefs.getAppRating(); if (appRating <= 0.0f) { showRatingDialog(); } else if (appRating <= 3.0f) { try { Version oldVersion = new Version(userPrefs.getVersionWhenLastRated()); Version curVersion = new Version(BuildConfig.VERSION_NAME); if (oldVersion.isNMinorVersionsDiff(curVersion, 2)) { showRatingDialog(); } } catch (ParseException e) { logger.error(e, true); } } } }</code><technical_language>This final instead of initialising again, get user prefs calling environment.getUserPrefs() here</technical_language>

Target:
public void onPlaybackComplete() { try{ if(player!=null){ double current_time = player.getCurrentPosition()/AppConstants.MILLISECONDS_PER_SECOND ; environment.getAnalyticsRegistry().trackVideoStop(videoEntry.videoId, current_time, videoEntry.eid, videoEntry.lmsUrl); } }catch(Exception e){ logger.error(e); } if (callback != null) { callback.saveCurrentPlaybackPosition(0); callback.onPlaybackComplete(); } hideCCPopUp(); hideSettingsPopUp(); try{ if(player!=null){ if(player.getController()!=null){ player.getController().showSpecial( (getTouchExploreEnabled() ? 0L : 5000L) ); } } }catch(Exception e){ logger.error(e); } if (!environment.getConfig().getAppStoreUris().isEmpty() && environment.getConfig().isAppReviewsEnabled() && NetworkUtil.isConnected(getContext())) { final PrefManager.UserPrefManager userPrefs = new PrefManager.UserPrefManager(MainApplication.application); final float appRating = userPrefs.getAppRating(); if (appRating <= AppConstants.APP_NOT_RATED_THRESHOLD) { showRatingDialog(); } else if (appRating <= AppConstants.APP_NEGATIVE_RATING_THRESHOLD) { try { final Version oldVersion = new Version(userPrefs.getLastRatedVersion()); final Version curVersion = new Version(BuildConfig.VERSION_NAME); if (oldVersion.isNMinorVersionsDiff(curVersion, AppConstants.MINOR_VERSIONS_DIFF_REQUIRED_FOR_NEGATIVE_RATERS)) { showRatingDialog(); } } catch (ParseException e) { logger.error(e, true); } } } }
Source:
<code>public void onChildRemoved(Object parentElement, Object childElement) { ChildNodeRemovedEvent message = new ChildNodeRemovedEvent(); message.parentNodeId = getOrCreateNodeIdForElement(parentElement); message.nodeId = getOrCreateNodeIdForElement(childElement); mPeerManager.sendNotificationToPeers("DOM.childNodeRemoved", message); <START> unhookElement(childElement); <END> }</code><technical_language>I realized is a serious bug in do run logic in onLastPeerUnregistered. This leaking, no</technical_language>

Target:
public void onChildRemoved(Object parentElement, Object childElement) { ChildNodeRemovedEvent message = new ChildNodeRemovedEvent(); message.parentNodeId = mObjectIdMapper.getIdForObject(parentElement); message.nodeId = mObjectIdMapper.getIdForObject(childElement); mPeerManager.sendNotificationToPeers("DOM.childNodeRemoved", message); removeElementTree(childElement); }
Source:
<code>public PolicyResponse processPreUpdate(Metacard newMetacard, Map<String, Serializable> properties) throws StopProcessingException { if (!newMetacard.getTags().isEmpty() && !newMetacard.getTags().contains("resource")) { return new PolicyResponseImpl(); } List<Metacard> previousStateMetacards = ((OperationTransaction) properties.get(OPERATION_TRANSACTION_KEY)) .getPreviousStateMetacards(); Metacard previous; previous = previousStateMetacards .stream() <START> .filter((x) -> x.getId().equals(newMetacard.getId())) <END> .findFirst() .orElse(null); return pointOfContactChanged(newMetacard, previous) ? new PolicyResponseImpl(null, PERMISSION_MAP) : new PolicyResponseImpl(); }</code><technical_language>Remove parens x</technical_language>

Target:
public PolicyResponse processPreUpdate(Metacard newMetacard, Map<String, Serializable> properties) throws StopProcessingException { if (!newMetacard.getTags().isEmpty() && !newMetacard.getTags().contains("resource")) { return new PolicyResponseImpl(); } List<Metacard> previousStateMetacards = ((OperationTransaction) properties.get(OPERATION_TRANSACTION_KEY)) .getPreviousStateMetacards(); Metacard previous; previous = previousStateMetacards .stream() .filter(x -> x.getId().equals(newMetacard.getId())) .findFirst() .orElse(null); return pointOfContactChanged(newMetacard, previous) ? new PolicyResponseImpl(null, PERMISSION_MAP) : new PolicyResponseImpl(); }
Source:
<code>protected Builder( final Content source ) { <START> this.id = source.getId(); <END> this.valid = source.isValid(); this.parentPath = source.getParentPath(); this.name = source.getName(); this.type = source.getType(); this.data = source.getData() != null ? source.getData().copy() : null; this.attachments = source.getAttachments(); this.extraDatas = source.getAllExtraData() != null ? source.getAllExtraData().copy() : null; this.displayName = source.getDisplayName(); this.owner = source.getOwner(); this.createdTime = source.getCreatedTime(); this.modifiedTime = source.getModifiedTime(); this.creator = source.getCreator(); this.modifier = source.getModifier(); this.hasChildren = source.hasChildren(); this.page = source.getPage() != null ? source.getPage().copy() : null; this.thumbnail = source.getThumbnail(); this.childOrder = source.getChildOrder(); this.permissions = source.getPermissions(); this.inheritPermissions = source.inheritsPermissions(); this.language = source.getLanguage(); this.contentState = source.getContentState(); this.publishInfo = source.getPublishInfo(); this.processedReferences = ContentIds.create().addAll( source.getProcessedReferences() ); this.workflowInfo = source.getWorkflowInfo(); }</code><technical_language>getters class of suspicions. wrong direct field access</technical_language>

Target:
protected Builder( final Content source ) { this.id = source.id; this.valid = source.valid; this.parentPath = source.parentPath; this.name = source.name; this.type = source.type; this.data = source.data != null ? source.data.copy() : null; this.attachments = source.attachments; this.extraDatas = source.extraDatas != null ? source.extraDatas.copy() : null; this.displayName = source.displayName; this.owner = source.owner; this.createdTime = source.createdTime; this.modifiedTime = source.modifiedTime; this.creator = source.creator; this.modifier = source.modifier; this.hasChildren = source.hasChildren; this.page = source.page != null ? source.page.copy() : null; this.thumbnail = source.thumbnail; this.childOrder = source.childOrder; this.permissions = source.permissions; this.inheritPermissions = source.inheritPermissions; this.language = source.language; this.contentState = source.contentState; this.publishInfo = source.publishInfo; this.processedReferences = ContentIds.create().addAll( source.processedReferences ); this.workflowInfo = source.workflowInfo; }
Source:
<code>private String getReadValueErrMsg(final String details) { <START> return String.format( <END> "Could not read value from %s.", XmlNodeType.getString(this.presentEvent.getEventType()) ) + details; }</code><technical_language>could't this simple string concatenation this faster</technical_language>

Target:
private String getReadValueErrMsg(final String details) { final int eventType = this.presentEvent.getEventType(); return "Could not read value from " + XmlNodeType.getString(eventType) + "." + details; }
Source:
<code>public void callAsync(long delay, TimeUnit timeUnit, Runnable r) { <START> long deadline = timeUnit.toMillis(delay) + currentTimeMillis(); <END> executor.submit(delayedExcution(r, deadline)); }</code><technical_language>I code check deadline is small, especially code decrease this amount [here](<LINK_0> option imho is perform deadline calculation in delayedExecution</technical_language>

Target:
public void callAsync(long delay, TimeUnit timeUnit, Runnable r) { long deadline = timeUnit.toMillis(delay) + currentTimeMillis(); executor.submit(delayedExecution(r, deadline)); }
Source:
<code>private boolean validateInjectable(Element injectable) { Element injectableType = injectable.getEnclosingElement(); if (injectable.getModifiers().contains(Modifier.PRIVATE)) { error("Can't inject a private field or constructor: " + injectableType + "." + injectable, injectable); return false; } <START> if (injectable.getKind() == ElementKind.METHOD) { <END> error("Method injection is not supported: " + injectableType + "." + injectable, injectable); return false; } ElementKind elementKind = injectableType.getEnclosingElement().getKind(); boolean isClassOrInterface = elementKind.isClass() || elementKind.isInterface(); boolean isStatic = injectableType.getModifiers().contains(Modifier.STATIC); if (isClassOrInterface && !isStatic) { error("Can't inject a non-static inner class: " + injectableType, injectableType); return false; } return true; }</code><technical_language>swap checks? sense if a private method is @Inject-annotated</technical_language>

Target:
private boolean validateInjectable(Element injectable) { Element injectableType = injectable.getEnclosingElement(); if (injectable.getKind() == ElementKind.METHOD) { error("Method injection is not supported: " + injectableType + "." + injectable, injectable); return false; } if (injectable.getModifiers().contains(Modifier.PRIVATE)) { error("Can't inject a private field or constructor: " + injectableType + "." + injectable, injectable); return false; } ElementKind elementKind = injectableType.getEnclosingElement().getKind(); boolean isClassOrInterface = elementKind.isClass() || elementKind.isInterface(); boolean isStatic = injectableType.getModifiers().contains(Modifier.STATIC); if (isClassOrInterface && !isStatic) { error("Can't inject a non-static inner class: " + injectableType, injectableType); return false; } return true; }
Source:
<code>public void testPowerOffDroplet() { int event = api.getDropletApi().powerOff(droplet.getId()); <START> assertTrue(event > 0, "The event id should not be null"); <END> waitForEvent(event); }</code><technical_language>"...be > 0"? in places below</technical_language>

Target:
public void testPowerOffDroplet() { int event = api.getDropletApi().powerOff(droplet.getId()); assertTrue(event > 0, "The event id should be > 0"); waitForEvent(event); }
Source:
<code>public Response intercept(Chain chain) throws IOException { RequestBody body = chain.request().body(); <START> if (body != null) { <END> Preconditions.checkArgument(body.contentLength() < MAX_PAYLOAD_SIZE, String.format("Request too large. Maximum allowed size is %s bytes, but the request has %s.", MAX_PAYLOAD_SIZE, body.contentLength())); } return chain.proceed(chain.request()); }</code><technical_language>SafeLogging</technical_language>

Target:
public Response intercept(Chain chain) throws IOException { RequestBody body = chain.request().body(); if (body != null && body.contentLength() >= MAX_PAYLOAD_SIZE) { throw new SafeIllegalArgumentException( "Request too large. Maximum allowed payload size is bytes, but the request has {}.", SafeArg.of("maximumSize", MAX_PAYLOAD_SIZE), SafeArg.of("actualSize", body.contentLength())); } return chain.proceed(chain.request()); }
Source:
<code>void openInventory(Inventory inventory, Cause cause) throws IllegalArgumentException; void closeInventory(Cause cause) throws IllegalArgumentException; int getViewDistance(); ChatVisibility getChatVisibility(); boolean isChatColorsEnabled(); <START> MessageChannelEvent.Chat chat(Text message); <END> Set<SkinPart> getDisplayedSkinParts(); @Override PlayerConnection getConnection(); void sendResourcePack(ResourcePack pack); TabList getTabList(); void kick(); void kick(Text reason); Scoreboard getScoreboard(); void setScoreboard(Scoreboard scoreboard); default JoinData getJoinData() { return get(JoinData.class).get(); }</code><technical_language>This accept String in opinion. Clients send a String only, this method simulate a client sending a String server</technical_language>

Target:
Optional<Container> openInventory(Inventory inventory, Cause cause) throws IllegalArgumentException; boolean closeInventory(Cause cause) throws IllegalArgumentException; int getViewDistance(); ChatVisibility getChatVisibility(); boolean isChatColorsEnabled(); MessageChannelEvent.Chat simulateChat(Text message, Cause cause); Set<SkinPart> getDisplayedSkinParts(); @Override PlayerConnection getConnection(); void sendResourcePack(ResourcePack pack); TabList getTabList(); void kick(); void kick(Text reason); Scoreboard getScoreboard(); void setScoreboard(Scoreboard scoreboard); default JoinData getJoinData() { return get(JoinData.class).get(); }
Source:
<code>protected void executeCommand() { <START> VdsValidator validator; <END> setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } validator = new VdsValidator(getVds()); if (validator.shouldVdsBeFenced()) { boolean result = executeSshSoftFencingCommand(getVds().getHostName(), getVds().getVdsGroupCompatibilityVersion().toString()); if (result) { ResourceManager.getInstance().GetVdsManager(getVds().getId()).finishSshSoftFencingExecution(getVds()); } getReturnValue().setSucceeded(result); } else { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it's status is ok.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); } }</code><technical_language>need declare variable it.</technical_language>

Target:
protected void executeCommand() { setVds(null); if (getVds() == null) { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it doesn't exist anymore.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); return; } VdsValidator validator = new VdsValidator(getVds()); if (validator.shouldVdsBeFenced()) { boolean result = executeSshSoftFencingCommand(getVds().getHostName(), getVds().getVdsGroupCompatibilityVersion().toString()); if (result) { ResourceManager.getInstance().GetVdsManager(getVds().getId()).finishSshSoftFencingExecution(getVds()); } getReturnValue().setSucceeded(result); } else { setCommandShouldBeLogged(false); log.infoFormat("SSH Soft Fencing will not be executed on host {0}({1}) since it's status is ok.", getVdsName(), getVdsId()); getReturnValue().setSucceeded(false); } }
Source:
<code>public PositionalFilter(StructFilter parent) { super(false); <START> this.parent = parent; <END> }</code><technical_language>requireNonNull</technical_language>

Target:
public PositionalFilter(StructFilter parent) { super(false); this.parent = requireNonNull(parent, "parent is null"); }
Source:
<code>public void checkValueReferenedBeforeDefined(Scope scope) { EList<Declaration> declarations = scope.getDeclarations(); Set<QualifiedName> defined = Sets.newHashSet(); for (Declaration declaration : declarations) { if (!(declaration instanceof VariableDefinition)) { <START> continue; <END> } VariableDefinition definition = (VariableDefinition) declaration; if (!definition.isConst()) return; Expression initialValue = definition.getInitialValue(); List<Expression> toCheck = Lists.newArrayList(initialValue); TreeIterator<EObject> eAllContents = initialValue.eAllContents(); while (eAllContents.hasNext()) { EObject next = eAllContents.next(); if (next instanceof Expression) toCheck.add((Expression) next); } for (Expression expression : toCheck) { EObject referencedObject = null; if (expression instanceof FeatureCall) referencedObject = ((FeatureCall) expression).getFeature(); else if (expression instanceof ElementReferenceExpression) referencedObject = ((ElementReferenceExpression) expression).getReference(); if (referencedObject instanceof VariableDefinition) { if (!defined.contains(nameProvider.getFullyQualifiedName(referencedObject))) error(REFERENCE_CONSTANT_BEFORE_DEFINED, definition, TypesPackage.Literals.PROPERTY__INITIAL_VALUE); } } defined.add(nameProvider.getFullyQualifiedName(definition)); } }</code><technical_language>rarely continue break in SCT, version more readable, especially inverted logic. version basically "if A do B", "if A do unimportant, (implicit) else do important"</technical_language>

Target:
public void checkValueReferenedBeforeDefined(Scope scope) { EList<Declaration> declarations = scope.getDeclarations(); Set<QualifiedName> defined = Sets.newHashSet(); for (Declaration declaration : declarations) { if (declaration instanceof VariableDefinition) { VariableDefinition definition = (VariableDefinition) declaration; if (!definition.isConst()) return; Expression initialValue = definition.getInitialValue(); List<Expression> toCheck = Lists.newArrayList(initialValue); TreeIterator<EObject> eAllContents = initialValue.eAllContents(); while (eAllContents.hasNext()) { EObject next = eAllContents.next(); if (next instanceof Expression) toCheck.add((Expression) next); } for (Expression expression : toCheck) { EObject referencedObject = null; if (expression instanceof FeatureCall) referencedObject = ((FeatureCall) expression).getFeature(); else if (expression instanceof ElementReferenceExpression) referencedObject = ((ElementReferenceExpression) expression).getReference(); if (referencedObject instanceof VariableDefinition) { if (!defined.contains(nameProvider.getFullyQualifiedName(referencedObject))) error(REFERENCE_CONSTANT_BEFORE_DEFINED, definition, TypesPackage.Literals.PROPERTY__INITIAL_VALUE); } } defined.add(nameProvider.getFullyQualifiedName(definition)); } } }
Source:
<code>public void afterChunk(ChunkContext context) { <START> Object lines = context.getStepContext().getStepExecutionContext() <END> .get(ExecutionContextParametersNames.NUMBER_OF_LINES); long estimatedTotalNumberOfLines = lines != null? (long) lines : 0; long read = context.getStepContext().getStepExecution().getReadCount(); long write = context.getStepContext().getStepExecution().getWriteCount(); long skip = context.getStepContext().getStepExecution().getReadSkipCount() + context.getStepContext().getStepExecution().getProcessSkipCount() + context.getStepContext().getStepExecution().getWriteSkipCount(); String chunkStatisticsMessage = "Items read = " + read + ", items written = " + write + ", items skipped = " + skip; String stepName = context.getStepContext().getStepName() + ": "; if (estimatedTotalNumberOfLines != 0) { int percent = (int) ((read * 100) / estimatedTotalNumberOfLines); logger.info(stepName + percent + "% complete: " + chunkStatisticsMessage); } else { logger.info(stepName + chunkStatisticsMessage); } }</code><technical_language>Assigning Long supports null, remove need for casting</technical_language>

Target:
public void afterChunk(ChunkContext context) { long estimatedTotalNumberOfLines = (long) context.getStepContext().getStepExecutionContext() .getOrDefault(ExecutionContextParametersNames.NUMBER_OF_LINES, 0L); long read = context.getStepContext().getStepExecution().getReadCount(); long write = context.getStepContext().getStepExecution().getWriteCount(); long skip = context.getStepContext().getStepExecution().getReadSkipCount() + context.getStepContext().getStepExecution().getProcessSkipCount() + context.getStepContext().getStepExecution().getWriteSkipCount(); String chunkStatisticsMessage = "Items read = " + read + ", items written = " + write + ", items skipped = " + skip; String stepName = context.getStepContext().getStepName() + ": "; if (estimatedTotalNumberOfLines != 0) { int percent = (int) ((read * 100) / estimatedTotalNumberOfLines); logger.info(stepName + percent + "% complete: " + chunkStatisticsMessage); } else { logger.info(stepName + chunkStatisticsMessage); } }
Source:
<code>private void testCodec(final int offset, final int bitsPerValue, final int[] values) throws IOException { try (final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BitOutputStream bos = new DefaultBitOutputStream(os)) { final CRAMCodec<Integer> writeCodec = new BetaIntegerCodec(null, bos, offset, bitsPerValue); for (final int value : values) { writeCodec.write(value); } final int[] actual = new int[values.length]; <START> try (final InputStream is = new ByteArrayInputStream(os.toByteArray()); <END> final DefaultBitInputStream dbis = new DefaultBitInputStream(is)) { final CRAMCodec<Integer> readCodec = new BetaIntegerCodec(dbis, null, offset, bitsPerValue); for (int i = 0; i < values.length; i++) { actual[i] = readCodec.read(); } } Assert.assertEquals(actual, values); } }</code><technical_language>Minor point, reading in a separate outer try-with-resources, nested in side writer</technical_language>

Target:
private void testCodec(final int offset, final int bitsPerValue, final int[] values) throws IOException { byte[] written; try (final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BitOutputStream bos = new DefaultBitOutputStream(os)) { final CRAMCodec<Integer> writeCodec = new BetaIntegerCodec(null, bos, offset, bitsPerValue); for (final int value : values) { writeCodec.write(value); } bos.flush(); written = os.toByteArray(); } final int[] actual = new int[values.length]; try (final InputStream is = new ByteArrayInputStream(written); final DefaultBitInputStream dbis = new DefaultBitInputStream(is)) { final CRAMCodec<Integer> readCodec = new BetaIntegerCodec(dbis, null, offset, bitsPerValue); for (int i = 0; i < values.length; i++) { actual[i] = readCodec.read(); } } Assert.assertEquals(actual, values); }
Source:
<code>private ApiResponseSet<String> alertToSet(Alert alert) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(alert.getAlertId())); map.put("pluginId", String.valueOf(alert.getPluginId())); map.put("alert", alert.getName()); map.put("name", alert.getName()); map.put("description", alert.getDescription()); map.put("risk", Alert.MSG_RISK[alert.getRisk()]); map.put("confidence", Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put("url", alert.getUri()); map.put("method", alert.getMethod()); map.put("other", alert.getOtherInfo()); map.put("param", alert.getParam()); map.put("attack", alert.getAttack()); map.put("evidence", alert.getEvidence()); map.put("reference", alert.getReference()); map.put("cweid", String.valueOf(alert.getCweId())); map.put("wascid", String.valueOf(alert.getWascId())); map.put("sourceid", String.valueOf(alert.getSource().getId())); map.put("solution", alert.getSolution()); if (alert.getHistoryRef() != null) { map.put("messageId", String.valueOf(alert.getHistoryRef().getHistoryId())); } else { <START> map.put("messageId", ""); <END> } return new ApiResponseSet<String>("alert", map); }</code><technical_language>ternary operator in setters (it avoid duplication of name)</technical_language>

Target:
private ApiResponseSet<String> alertToSet(Alert alert) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(alert.getAlertId())); map.put("pluginId", String.valueOf(alert.getPluginId())); map.put("alert", alert.getName()); map.put("name", alert.getName()); map.put("description", alert.getDescription()); map.put("risk", Alert.MSG_RISK[alert.getRisk()]); map.put("confidence", Alert.MSG_CONFIDENCE[alert.getConfidence()]); map.put("url", alert.getUri()); map.put("method", alert.getMethod()); map.put("other", alert.getOtherInfo()); map.put("param", alert.getParam()); map.put("attack", alert.getAttack()); map.put("evidence", alert.getEvidence()); map.put("reference", alert.getReference()); map.put("cweid", String.valueOf(alert.getCweId())); map.put("wascid", String.valueOf(alert.getWascId())); map.put("sourceid", String.valueOf(alert.getSource().getId())); map.put("solution", alert.getSolution()); map.put("messageId", (alert.getHistoryRef() != null) ? String.valueOf(alert.getHistoryRef().getHistoryId()) : ""); return new ApiResponseSet<String>("alert", map); }
Source:
<code>private void handleStartIntent(Intent intent) { if (pendingShare != null) { awaitShare(); return; } final String action = intent.getAction(); if ((action == null) || !(action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_VIEW))) return; Uri videoUri; if (action.equals(Intent.ACTION_SEND)) { videoUri = getYouTubeUri(intent.getStringExtra(Intent.EXTRA_TEXT)); } else { videoUri = intent.getData(); } if (videoUri == null) return; String videoUrl = toPluginUrl(videoUri); if (videoUrl == null) { videoUrl = videoUri.toString(); } String host_name = intent.getStringExtra("host.name"); if (host_name != null) { HostManager hostManager = HostManager.getInstance(this); for (HostInfo host : hostManager.getHosts()) { <START> if (host.getName().equals(host_name)) { <END> hostManager.switchHost(host); break; } } } String title = getString(R.string.app_name); String text = getString(R.string.item_added_to_playlist); pendingShare = getShareExecutor().submit(new OpenSharedUrl(hostManager.getConnection(), videoUrl, title, text)); awaitShare(); intent.setAction(null); }</code><technical_language>Please host.id instead of name</technical_language>

Target:
private void handleStartIntent(Intent intent) { if (pendingShare != null) { awaitShare(); return; } final String action = intent.getAction(); if ((action == null) || !(action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_VIEW))) return; Uri videoUri; if (action.equals(Intent.ACTION_SEND)) { videoUri = getYouTubeUri(intent.getStringExtra(Intent.EXTRA_TEXT)); } else { videoUri = intent.getData(); } if (videoUri == null) return; String videoUrl = toPluginUrl(videoUri); if (videoUrl == null) { videoUrl = videoUri.toString(); } int hostId = intent.getIntExtra("hostId", 0); if (hostId > 0) { HostManager hostManager = HostManager.getInstance(this); for (HostInfo host : hostManager.getHosts()) { if (host.getId() == hostId) { hostManager.switchHost(host); break; } } } String title = getString(R.string.app_name); String text = getString(R.string.item_added_to_playlist); pendingShare = getShareExecutor().submit(new OpenSharedUrl(hostManager.getConnection(), videoUrl, title, text)); awaitShare(); intent.setAction(null); }
Source:
<code>private List<String> queryMetadata(String query) { ImmutableList.Builder<String> cache = ImmutableList.builder(); try (StatementClient client = queryRunner.startInternalQuery(query)) { while (client.isRunning()) { if (Thread.currentThread().isInterrupted()) { <START> client.close(); <END> break; } QueryData results = client.currentData(); if (results.getData() != null) { for (List<Object> row : results.getData()) { cache.add((String) row.get(0)); } } client.advance(); } } return cache.build(); }</code><technical_language>This needed in try-with-resources. This while loop</technical_language>

Target:
private List<String> queryMetadata(String query) { ImmutableList.Builder<String> cache = ImmutableList.builder(); try (StatementClient client = queryRunner.startInternalQuery(query)) { while (client.isRunning() && !Thread.currentThread().isInterrupted()) { QueryData results = client.currentData(); if (results.getData() != null) { for (List<Object> row : results.getData()) { cache.add((String) row.get(0)); } } client.advance(); } } return cache.build(); }
Source:
<code>private boolean performPermissionRequest(IField field) { if (field instanceof AudioRecordingField && !Permissions.canRecordAudio(this)) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECORD_AUDIO}, REQUEST_AUDIO_PERMISSION); return true; } if (field instanceof ImageField && !Permissions.canUseCamera(this)) { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); return true; <START> } <END> return false; }</code><technical_language>If a Permissions object, encapsulate requests in too</technical_language>

Target:
private boolean performPermissionRequest(IField field) { if (field instanceof AudioRecordingField && !Permissions.canRecordAudio(this)) { Timber.d("Requesting Audio Permissions"); ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECORD_AUDIO}, REQUEST_AUDIO_PERMISSION); return true; } if (field instanceof ImageField && !Permissions.canUseCamera(this)) { Timber.d("Requesting Camera Permissions"); ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); return true; } return false; }
Source:
<code>public VertxProxyConnection write(Buffer chunk) { <START> if (! headersWritten) { <END> HttpHeaders headers = proxyRequest.headers(); String encoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING); if (encoding != null && encoding.contains(HttpHeadersValues.TRANSFER_ENCODING_CHUNKED)) { httpClientRequest.setChunked(true); } this.writeHeaders(); } httpClientRequest.write(io.vertx.core.buffer.Buffer.buffer(chunk.getBytes())); return this; }</code><technical_language>I ensure deffering write of headers regression though. (hope tests catch any). lgtm</technical_language>

Target:
public VertxProxyConnection write(Buffer chunk) { content = true; if (! headersWritten) { this.writeHeaders(); } httpClientRequest.write(io.vertx.core.buffer.Buffer.buffer(chunk.getBytes())); return this; }
Source:
<code>public void sendsMail() throws Exception { final Postman postman = Mockito.spy(Postman.CONSOLE); <START> final Profile profile = this.profile(); <END> final Agent agent = new Mails( profile, postman ); final Talk talk = MailsTest.talk(); agent.execute(talk); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Envelope envelope = captor.getValue(); MatcherAssert.assertThat( envelope.unwrap().getContent().toString(), Matchers.allOf( Matchers.containsString("See #456, release log:"), Matchers.containsString("Released by Rultor"), Matchers.containsString(Manifests.read("Rultor-Version")), Matchers.containsString( "see [build log](<LINK_0>" ) ) ); MatcherAssert.assertThat( envelope.unwrap().getSubject(), Matchers.equalTo("user/repo v2.0 released!") ); }</code><technical_language>avoid one-time variables, inline if usage</technical_language>

Target:
public void sendsMail() throws Exception { final Postman postman = Mockito.spy(Postman.CONSOLE); final Agent agent = new Mails( this.profile(), postman ); agent.execute(MailsTest.talk()); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Envelope envelope = captor.getValue(); MatcherAssert.assertThat( envelope.unwrap().getContent().toString(), Matchers.allOf( Matchers.containsString("See #456, release log:"), Matchers.containsString("Released by Rultor"), Matchers.containsString(Manifests.read("Rultor-Version")), Matchers.containsString( "see [build log](<LINK_0>" ) ) ); MatcherAssert.assertThat( envelope.unwrap().getSubject(), Matchers.equalTo("user/repo v2.0 released!") ); }
Source:
<code>public void testInvalidFieldName() { try { MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", <START> " \"name\": \"FooBar\",", <END> " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"_badName\", \"type\": \"[]int32\", \"versions\": \"0+\" }", " ]", "}")), MessageSpec.class); fail("Expected MessageDataGenerator constructor to fail"); } catch (Exception e) { assertTrue("Invalid error message: " + e.getMessage(), e.getMessage().contains("Invalid field name")); } }</code><technical_language>helpful is invalid name. Is underscore start</technical_language>

Target:
public void testInvalidFieldName() { assertStringContains("Invalid field name", assertThrows(Throwable.class, () -> { MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"_badName\", \"type\": \"[]int32\", \"versions\": \"0+\" }", " ]", "}")), MessageSpec.class); }).getMessage()); }
Source:
<code>private void initDatabase(MysqldConfig config) throws IOException { try { boolean isSeverVersion57 = config.getVersion().getMajorVersion().equals("5.7"); <START> System.out.println(getBaseDir()); <END> Process p = isSeverVersion57 ? getProcessForVersion57() : getProcess(); int retCode = p.waitFor(); if (retCode != 0) { resolveException(retCode, IOUtils.toString(p.getInputStream()) + IOUtils.toString(p.getErrorStream())); } } catch (InterruptedException e) { throw new RuntimeException(e); } }</code><technical_language>debug line, remove please</technical_language>

Target:
private void initDatabase(MysqldConfig config) throws IOException { try { boolean isSeverVersion57 = config.getVersion().getMajorVersion().equals("5.7"); Process p = isSeverVersion57 ? getProcessForVersion57() : getProcess(); int retCode = p.waitFor(); if (retCode != 0) { resolveException(retCode, IOUtils.toString(p.getInputStream()) + IOUtils.toString(p.getErrorStream())); } } catch (InterruptedException e) { throw new RuntimeException(e); } }
Source:
<code>public static String linkifyPattern(String text, Pattern pattern, String name, String url) { try { String buildLink = buildLink(name, url, true); return pattern.matcher(text).replaceAll(buildLink); } catch (URISyntaxException | MalformedURLException ex) { <START> LOGGER.log(Level.INFO, "The given url '{0}' is not valid", url); <END> return text; } }</code><technical_language>Warning</technical_language>

Target:
public static String linkifyPattern(String text, Pattern pattern, String name, String url) { try { String buildLink = buildLink(name, url, true); return pattern.matcher(text).replaceAll(buildLink); } catch (URISyntaxException | MalformedURLException ex) { LOGGER.log(Level.WARNING, "The given URL '{0}' is not valid", url); return text; } }
Source:
<code>public AuditLogType getAuditLogTypeValue() { addCustomValue("ProviderName", getProviderName()); if (isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED; } if (isInternalCommandTriggered() && !getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED_FAILED; } if (!isInternalCommandTriggered() && getSucceeded()) { <START> return AuditLogType.PROVIDER_SYNCHRONIZED; <END> } return AuditLogType.PROVIDER_SYNCHRONIZED_FAILED; }</code><technical_language>Dan asked, if is done please change AuditLogType.UNASSIGNED</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { addCustomValue("ProviderName", getProviderName()); if (isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED; } if (isInternalCommandTriggered() && !getSucceeded()) { return AuditLogType.PROVIDER_SYNCHRONIZED_PERFORMED_FAILED; } if (!isInternalCommandTriggered() && getSucceeded()) { return AuditLogType.UNASSIGNED; } return AuditLogType.PROVIDER_SYNCHRONIZED_FAILED; }
Source:
<code><START> public void createClassLoaderModelJsonFile(ClassLoaderModel classLoaderModel) { <END> File destinationFile = new File(projectTargetFolder.resolve(META_INF).resolve(MULE_ARTIFACT).toAbsolutePath().toString(), CLASSLOADER_MODEL_FILE_NAME); try { destinationFile.createNewFile(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Writer writer = new FileWriter(destinationFile.getAbsolutePath()); gson.toJson(classLoaderModel, writer); writer.close(); } catch (IOException e) { throw new RuntimeException("Could not create classloadermodel.json", e); } }</code><technical_language>please add a Java Doc here, remember this class is part of public API</technical_language>

Target:
public void createClassLoaderModelJsonFile(ClassLoaderModel classLoaderModel) { File destinationFile = projectTargetFolder.resolve(META_INF).resolve(MULE_ARTIFACT).resolve(CLASSLOADER_MODEL_FILE_NAME).toFile(); try { destinationFile.createNewFile(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Writer writer = new FileWriter(destinationFile.getAbsolutePath()); gson.toJson(classLoaderModel, writer); writer.close(); } catch (IOException e) { throw new RuntimeException("Could not create classloadermodel.json", e); } }
Source:
<code>public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; <START> this.serviceLevel = null; <END> }</code><technical_language>I change this line, initializing empty string, worry created a Consumer serviceLevel in java(null string), loaded serviceLevel database (empty string). Logically a difference, scary</technical_language>

Target:
public Consumer(String name, String userName, Owner owner, ConsumerType type) { this(); this.name = name; this.username = userName; this.owner = owner; this.type = type; this.facts = new HashMap<String, String>(); this.installedProducts = new HashSet<ConsumerInstalledProduct>(); this.guestIds = new ArrayList<GuestId>(); this.autoheal = true; this.serviceLevel = ""; }
Source:
<code>public void delete(Path path, boolean force) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) path; logger.debug("Removing " + repositoryPath + "..."); if (Files.isDirectory(repositoryPath)) { cleanupDirectory(repositoryPath.relativize(), force); } <START> deleteMetadata(repositoryPath); <END> super.delete(repositoryPath, force); }</code><technical_language>need called in super method</technical_language>

Target:
public void delete(Path path, boolean force) throws IOException { RepositoryPath repositoryPath = (RepositoryPath) path; logger.debug("Removing " + repositoryPath + "..."); if (Files.isDirectory(repositoryPath)) { cleanupDirectory(repositoryPath.relativize(), force); } super.delete(repositoryPath, force); }
Source:
<code>public void commenceTrading(double price, String symbol) throws StockMarketException { <START> for (Order o : this.sellOrders.get(symbol)) <END> { if (o.getPrice() <= price || o.isMarketOrder) { o.getTrader().tradePerformed(o, price); } } for (Order o : this.buyOrders.get(symbol)) { if (o.getPrice() >= price || o.isMarketOrder) { o.getTrader().tradePerformed(o, price); } } }</code><technical_language>bad naming</technical_language>

Target:
public void commenceTrading(double price, String symbol) throws StockMarketException { for (Order order : this.sellOrders.get(symbol)) { if (order.getPrice() <= price || order.isMarketOrder) { order.getTrader().tradePerformed(order, price); } } for (Order order : this.buyOrders.get(symbol)) { if (order.getPrice() >= price || order.isMarketOrder) { order.getTrader().tradePerformed(order, price); } } }
Source:
<code>public void setUp() throws Exception { this.columbusTelescopeReporter = ColumbusTelescopeReporter.create( telescopeClient, environment, objectMapper ); this.bootstrapWorker = ContentBootstrapWorker.create( contentResolver, writer, metricsTimer, contentNotWrittenMeter, failureMeter, columbusTelescopeReporter ); this.content = new org.atlasapi.content.Item("panda.com", "panda", Publisher.PA); <START> this.content.setId(Id.valueOf(1l)); <END> this.successfulWriteResult = new WriteResult<>(content, true, DateTime.now(), null); this.failedWriteResult = new WriteResult<>(content, false, DateTime.now(), null); }</code><technical_language>Uppercase L for numbers. This fail Sonar</technical_language>

Target:
public void setUp() throws Exception { this.columbusTelescopeReporter = ColumbusTelescopeReporter.create( telescopeClient, environment, objectMapper ); this.bootstrapWorker = ContentBootstrapWorker.create( contentResolver, writer, metricsTimer, contentNotWrittenMeter, failureMeter, columbusTelescopeReporter ); this.content = new org.atlasapi.content.Item("panda.com", "panda", Publisher.PA); this.content.setId(Id.valueOf(1L)); this.successfulWriteResult = new WriteResult<>(content, true, DateTime.now(), null); }
Source:
<code>Class loadClass(String className, boolean resolve) throws ClassNotFoundException { <START> boolean isRS = Thread.currentThread().getName().contains("DRDAConnThread"); <END> JarLoader jl = null; boolean unlockLoader = false; try { unlockLoader = lockClassLoader(ShExQual.SH); synchronized (this) { if (needReload || !isRS) { reload(); } Class clazz = checkLoaded(className, resolve); if (clazz != null) return clazz; for (String RESTRICTED_PACKAGE : RESTRICTED_PACKAGES) { if (className.startsWith(RESTRICTED_PACKAGE)) throw new ClassNotFoundException(className); } String jvmClassName = className.replace('.', '/') + ".class"; if (!initDone) initLoaders(); for (JarLoader aJarList1 : jarList) { jl = aJarList1; Class c = jl.loadClassData(className, jvmClassName, resolve); if (c != null) { if (vs != null) vs.println(MessageService.getTextMessage(MessageId.CM_CLASS_LOAD, className, jl.getJarName())); return c; } } } return null; } catch (StandardException se) { throw new ClassNotFoundException(MessageService.getTextMessage(MessageId.CM_CLASS_LOAD_EXCEPTION, className, jl == null ? null : jl.getJarName(), se)); } finally { if (unlockLoader) { lf.unlock(compat, this, classLoaderLock, ShExQual.SH); } } }</code><technical_language>If running in a NLJ, union operation other contexts running in a thread, need a identify RS Olap/Spark</technical_language>

Target:
Class loadClass(String className, boolean resolve) throws ClassNotFoundException { JarLoader jl = null; boolean unlockLoader = false; try { unlockLoader = lockClassLoader(ShExQual.SH); synchronized (this) { if (needReload || !isHBaseJVM) { reload(); } Class clazz = checkLoaded(className, resolve); if (clazz != null) return clazz; for (String RESTRICTED_PACKAGE : RESTRICTED_PACKAGES) { if (className.startsWith(RESTRICTED_PACKAGE)) throw new ClassNotFoundException(className); } String jvmClassName = className.replace('.', '/') + ".class"; if (!initDone) initLoaders(); for (JarLoader aJarList1 : jarList) { jl = aJarList1; Class c = jl.loadClassData(className, jvmClassName, resolve); if (c != null) { if (vs != null) vs.println(MessageService.getTextMessage(MessageId.CM_CLASS_LOAD, className, jl.getJarName())); return c; } } } return null; } catch (StandardException se) { throw new ClassNotFoundException(MessageService.getTextMessage(MessageId.CM_CLASS_LOAD_EXCEPTION, className, jl == null ? null : jl.getJarName(), se)); } finally { if (unlockLoader) { lf.unlock(compat, this, classLoaderLock, ShExQual.SH); } } }
Source:
<code>public File createBadEmailReport(List<PDPBadEmailRecord> badEmailRecords) { <START> LOG.info("createBadEmailReport, there are " + badEmailRecords.size() + " bad email records to report"); <END> initializeErrorReport(); printErrorReportDetails(badEmailRecords); reportWriterService.destroy(); return reportWriterService.getReportFile(); }</code><technical_language>records => addresses well</technical_language>

Target:
public File createBadEmailReport(List<PDPBadEmailRecord> badEmailRecords) { LOG.info("createBadEmailReport, there are " + badEmailRecords.size() + " bad email addresses to report"); initializeErrorReport(); printErrorReportDetails(badEmailRecords); reportWriterService.destroy(); return reportWriterService.getReportFile(); }
Source:
<code>public void onNewView(Set<Address> members) { try { boolean isDone = false; T result = null; synchronized (responseCollector) { if (missingResponses <= 0) { return; } for (int i = 0; i < targets.length; i++) { Address target = targets[i]; if (target != null && !members.contains(target)) { targets[i] = null; missingResponses--; <START> if (trace) log.tracef("Missing target %s for request %d", target, requestId); <END> result = responseCollector.addResponse(target, CacheNotFoundResponse.INSTANCE); if (result != null) { isDone = true; break; } } } if (!isDone && missingResponses <= 0) { result = responseCollector.finish(); isDone = true; } } if (isDone) { complete(result); } } catch (Throwable t) { completeExceptionally(t); } }</code><technical_language>"%s left view for request %d" more intelligible</technical_language>

Target:
public void onNewView(Set<Address> members) { try { boolean isDone = false; T result = null; synchronized (responseCollector) { if (missingResponses <= 0) { return; } for (int i = 0; i < targets.length; i++) { Address target = targets[i]; if (target != null && !members.contains(target)) { targets[i] = null; missingResponses--; if (trace) log.tracef("Target %s of request %d left the cluster view", target, requestId); result = responseCollector.addResponse(target, CacheNotFoundResponse.INSTANCE); if (result != null) { isDone = true; break; } } } if (!isDone && missingResponses <= 0) { result = responseCollector.finish(); isDone = true; } } if (isDone) { complete(result); } } catch (Throwable t) { completeExceptionally(t); } }
Source:
<code>public Map<String, Object> getSchedulerPropertiesFromSessionId(@HeaderParam("sessionid") final String sessionId) throws NotConnectedRestException, PermissionRestException { SchedulerProxyUserInterface scheduler = checkAccess(sessionId, "properties"); <START> Map<String, Object> schedulerProperties = null; <END> try { schedulerProperties = scheduler.getSchedulerProperties(); } catch (NotConnectedException e) { logger.warn("Attempt to retrieve scheduler properties but failed because connection exception", e); return null; } catch (PermissionException e) { logger.warn("Attempt to retrieve scheduler properties but failed because permission exception", e); return null; } return schedulerProperties; }</code><technical_language>Initialize this map. empty map</technical_language>

Target:
public Map<String, Object> getSchedulerPropertiesFromSessionId(@HeaderParam("sessionid") final String sessionId) throws NotConnectedRestException, PermissionRestException { SchedulerProxyUserInterface scheduler = checkAccess(sessionId, "properties"); Map<String, Object> schedulerProperties = new HashMap<String, Object>(); try { schedulerProperties = scheduler.getSchedulerProperties(); } catch (NotConnectedException e) { logger.warn("Attempt to retrieve scheduler properties but failed because connection exception", e); throw new PermissionRestException(e); } catch (PermissionException e) { logger.warn("Attempt to retrieve scheduler properties but failed because permission exception", e); throw new NotConnectedRestException(e); } return schedulerProperties; }
Source:
<code>public void spawnParticles(ParticleEffect particleEffect, Vector3d position, int radius) { checkNotNull(particleEffect, "The particle effect cannot be null!"); checkNotNull(position, "The position cannot be null"); checkArgument(radius > 0, "The radius has to be greater then zero!"); List<Packet> packets = SpongeParticleHelper.toPackets((SpongeParticleEffect) particleEffect, position); if (!packets.isEmpty()) { double dx = this.posX - position.getX(); double dy = this.posY - position.getY(); double dz = this.posZ - position.getZ(); if (dx * dx + dy * dy + dz * dz < radius * radius) { <START> packets.forEach(this.playerNetServerHandler::sendPacket); <END> } } }</code><technical_language>no</technical_language>

Target:
public void spawnParticles(ParticleEffect particleEffect, Vector3d position, int radius) { checkNotNull(particleEffect, "The particle effect cannot be null!"); checkNotNull(position, "The position cannot be null"); checkArgument(radius > 0, "The radius has to be greater then zero!"); List<Packet> packets = SpongeParticleHelper.toPackets((SpongeParticleEffect) particleEffect, position); if (!packets.isEmpty()) { double dx = this.posX - position.getX(); double dy = this.posY - position.getY(); double dz = this.posZ - position.getZ(); if (dx * dx + dy * dy + dz * dz < radius * radius) { for (Packet packet : packets) { this.playerNetServerHandler.sendPacket(packet); } } } }