auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AnalysisResult runCheckers(ImmutableList<AnalysisResult> knownResultsSoFar, AnalysisDatabase database, MutableTypeInformation mutableTypeInformation, AnalysisInProgress analysisInProgress) { Map<IsImmutable, Integer> results = newHashMap(); Collection<MutableReasonDetail> reasons = newArrayList(); Collection<AnalysisError> errors = newArrayList(); <START> boolean isClassSelfReferenced=false; <END> Iterable<AsmMutabilityChecker> checkers = factory.createInstances( database, verifierFactory, mutableTypeInformation, analysisInProgress); CheckerRunner checkerRunner = checkerRunnerFactory.createRunner(); for (AsmMutabilityChecker checker : checkers) { if(checker instanceof CollectionWithMutableElementTypeToFieldChecker) { checker.setIsClassSelfReferenced(isClassSelfReferenced); } CheckerResult checkerResult = checkerRunner.run(checker, toAnalyse, knownResultsSoFar); if(checker instanceof MutableTypeToFieldChecker) { isClassSelfReferenced = checker.isClassSelfReferenced(); } results.put(checkerResult.isImmutable, getNewCount(results, checkerResult.isImmutable)); reasons.addAll(checkerResult.reasons); errors.addAll(checkerResult.errors); } IsImmutable isImmutable = new ResultCalculator().calculateImmutableStatus(results); return AnalysisResult.analysisResult(toAnalyse, isImmutable, reasons, errors); }</code><technical_language>elsewhere: try follow existing code style respect whitespace: spaces =, space comma, space if, etc</technical_language>

Target:
public AnalysisResult runCheckers(ImmutableList<AnalysisResult> knownResultsSoFar, AnalysisDatabase database, MutableTypeInformation mutableTypeInformation, AnalysisInProgress analysisInProgress) { Map<IsImmutable, Integer> results = newHashMap(); Collection<MutableReasonDetail> reasons = newArrayList(); Collection<AnalysisError> errors = newArrayList(); Iterable<AsmMutabilityChecker> checkers = factory.createInstances( database, verifierFactory, mutableTypeInformation, analysisInProgress); CheckerRunner checkerRunner = checkerRunnerFactory.createRunner(); for (AsmMutabilityChecker checker : checkers) { CheckerResult checkerResult = checkerRunner.run(checker, toAnalyse, knownResultsSoFar); results.put(checkerResult.isImmutable, getNewCount(results, checkerResult.isImmutable)); reasons.addAll(checkerResult.reasons); errors.addAll(checkerResult.errors); } IsImmutable isImmutable = new ResultCalculator().calculateImmutableStatus(results); return AnalysisResult.analysisResult(toAnalyse, isImmutable, reasons, errors); }
Source:
<code>private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.get().getKeyType().equals(RSA) || key.get().getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key.get(), cryptographyServiceClient); } else if (key.get().getKeyType().equals(EC) || key.get().getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key.get(), cryptographyServiceClient); } else if (key.get().getKeyType().equals(OCT)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key.get(), cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( <START> "The Json Web Key Type: %s is not supported.", key.get().getKeyType().toString()))); <END> } }</code><technical_language>This more readable a switch statement</technical_language>

Target:
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(OCT)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); } }
Source:
<code>public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { <START> ; <END> } return val; }</code><technical_language>is checkstyle forbidding this, if write for( .. ; .. ; .. );</technical_language>

Target:
public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { } return val; }
Source:
<code>public int hashCode() { <START> return Objects.hash(getUsername(), getPolicy(), getContext(), getTitle(), ttl, getPushTitle(), pushBody); <END> }</code><technical_language>ttl getTTLM()</technical_language>

Target:
public int hashCode() { return Objects.hash(getUsername(), getPolicy(), getContext(), getTitle(), getTTL(), getPushTitle(), getPushBody()); }
Source:
<code>public void onMatch(RelOptRuleCall call) { SingleRel single = call.rel(0); RelNode emptyValues = call.builder().push(single).empty().build(); <START> RelNode result = emptyValues.copy(single.getTraitSet(), Collections.emptyList()); <END> call.transformTo(result); }</code><technical_language>If change PruneEmptyRule's autoPruneOld false, able another error</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { SingleRel singleRel = call.rel(0); RelNode emptyValues = call.builder().push(singleRel).empty().build(); RelTraitSet traits = singleRel.getTraitSet(); if (emptyValues.getConvention() != null) { traits = traits.replace(emptyValues.getConvention()); } emptyValues = emptyValues.copy(traits, Collections.emptyList()); call.transformTo(emptyValues); }
Source:
<code>public String getString(String key) throws JSONException { Object object = this.get(key); <START> return object.toString(); <END> }</code><technical_language>a note for other reviewers, get(key) throw exception if key is null, null check is needed here. if want this more succinct java return this.get(key).toString(); personally a fan of local variables once</technical_language>

Target:
public String getString(String key) throws JSONException { return this.get(key).toString(); }
Source:
<code>private static boolean isPositionWithin(final ContentPosition position, final Box box) { <START> return position.getOffset() >= box.getStartOffset() && position.getOffset() <= box.getEndOffset(); <END> }</code><technical_language>Please ContentPosition.isBeforeOrEquals isAfterOrEquals</technical_language>

Target:
private static boolean isPositionWithin(final ContentPosition position, final Box box) { return position.isAfterOrEquals(new ContentPosition(box.getNode(), box.getStartOffset())) && position.isBeforeOrEquals(new ContentPosition(box.getNode(), box.getEndOffset())); }
Source:
<code>private static Object evaluate(TokenKind op, Object value, Location loc) throws EvalException, InterruptedException { switch (op) { case NOT: return !EvalUtils.toBoolean(value); case MINUS: if (!(value instanceof Integer)) { throw new EvalException( loc, String.format( "unsupported operand type for -: '%s'", EvalUtils.getDataTypeName(value))); } try { return Math.negateExact((Integer) value); } catch (ArithmeticException e) { throw new EvalException(loc, e.getMessage()); } <START> case TILDE: <END> if (!(value instanceof Integer)) { throw new EvalException( loc, String.format( "unsupported operand type for ~: '%s'", EvalUtils.getDataTypeName(value))); } return ~((Integer) value); default: throw new AssertionError("Unsupported unary operator: " + op); } }</code><technical_language>write exception code if structure as: switch op { case NOT: ... case MINUS: if (x instanceof Integer) { return ... } break; case TILDE: if (x instanceof Integer) { return ... } break; } throw unsupported unary operation <op><type></technical_language>

Target:
private static Object evaluate(TokenKind op, Object value, Location loc) throws EvalException, InterruptedException { switch (op) { case NOT: return !EvalUtils.toBoolean(value); case MINUS: if (value instanceof Integer) { try { return Math.negateExact((Integer) value); } catch (ArithmeticException e) { throw new EvalException(loc, e.getMessage()); } } break; case PLUS: if (value instanceof Integer) { return value; } break; case TILDE: if (value instanceof Integer) { return ~((Integer) value); } break; default: } throw new EvalException( loc, String.format( "unsupported unary operation: %s%s", op, EvalUtils.getDataTypeName(value))); }
Source:
<code>public String toString() { <START> switch (this) { <END> case APPS: return "Apps"; case ENGINES: return "Engines"; default: throw new IllegalArgumentException(); } }</code><technical_language>alternative add display name of installation types a parameter enum, simply need return this parameter</technical_language>

Target:
public String toString() { return this.displayName; }
Source:
<code>public CPUStat getCPUStat() { <START> return new CPUStat(); <END> }</code><technical_language>Is this coded purpose? I mean, a stateless call? sight, this getCPUStat return object property, instead, return a object instance</technical_language>

Target:
public CPUStat getCPUStat() { return _cpuStat; }
Source:
<code>private Void dropTablesWithPrefix(String prefix) { String namespacedPrefix = NAMESPACE.getName() + "." + prefix + "__"; <START> Set<TableReference> tablesToDrop = Sets.newHashSet(); <END> for (TableReference tableRef : kvs.getAllTableNames()) { if (tableRef.getQualifiedName().startsWith(namespacedPrefix)) { tablesToDrop.add(tableRef); } } kvs.dropTables(tablesToDrop); return null; }</code><technical_language>= kvs.getAllTableNames().stream() .filter(tableRef -> tableRef.getQualifiedName().startsWith(namespacedPrefix)) .collect(Collectors.toSet()); for style points</technical_language>

Target:
private Void dropTablesWithPrefix(String prefix) { String namespacedPrefix = NAMESPACE.getName() + "." + prefix + "__"; Set<TableReference> tablesToDrop = kvs.getAllTableNames().stream() .filter(tableRef -> tableRef.getQualifiedName().startsWith(namespacedPrefix)) .collect(Collectors.toSet()); kvs.dropTables(tablesToDrop); return null; }
Source:
<code>public static CardinalitySize getEstimatedCardinality( String dimension, Class<?> cls, EntityDictionary entityDictionary ) { if (entityDictionary.isRelation(cls, dimension)) { Cardinality annotation = entityDictionary.getAttributeOrRelationAnnotation( cls, Cardinality.class, dimension ); if (annotation != null) { return annotation.size(); } } <START> Cardinality annotation = entityDictionary <END> .getAttributeOrRelationAnnotation(cls, Cardinality.class, dimension); return annotation == null ? getDefaultCardinality() : annotation.size(); }</code><technical_language>This is identical call 83. I this is intended</technical_language>

Target:
public static CardinalitySize getEstimatedCardinality( String dimension, Class<?> cls, EntityDictionary entityDictionary ) { if (entityDictionary.isRelation(cls, dimension)) { Cardinality annotation = entityDictionary.getAnnotation( entityDictionary.getType(cls, dimension), Cardinality.class ); if (annotation != null) { return annotation.size(); } } Cardinality annotation = entityDictionary .getAttributeOrRelationAnnotation(cls, Cardinality.class, dimension); return annotation == null ? getDefaultCardinality() : annotation.size(); }
Source:
<code>public int read(ByteBuffer buff) throws IOException { int read = 0; if (this.appPeerBuffer.position() == 0) { this.channel.read(this.packatPeerBuffer); if (this.packatPeerBuffer.position() == 0) { return read; } this.packatPeerBuffer.flip(); boolean retry = true; while (retry) { SSLEngineResult result = this.engine.unwrap(this.packatPeerBuffer, this.appPeerBuffer); switch (result.getStatus()) { case BUFFER_OVERFLOW: putBuffer(buff); <START> read += result.bytesProduced(); retry = false; break; <END> case BUFFER_UNDERFLOW: read += result.bytesProduced(); retry = false; break; default: if (HandshakeStatus.NEED_TASK.equals(result.getHandshakeStatus()) || !this.appPeerBuffer.hasRemaining()) { retry = false; } read += result.bytesProduced(); } } this.packatPeerBuffer.compact(); } putBuffer(buff); return read; }</code><technical_language>a matter of preferences (and style) - move lines 63-65 code work same. this well</technical_language>

Target:
public int read(ByteBuffer buff) throws IOException { int read = 0; if (this.appPeerBuffer.position() == 0) { this.channel.read(this.packatPeerBuffer); if (this.packatPeerBuffer.position() == 0) { return read; } this.packatPeerBuffer.flip(); boolean retry = true; while (retry) { SSLEngineResult result = this.engine.unwrap(this.packatPeerBuffer, this.appPeerBuffer); switch (result.getStatus()) { case BUFFER_OVERFLOW: putBuffer(buff); case BUFFER_UNDERFLOW: read += result.bytesProduced(); retry = false; break; default: if (HandshakeStatus.NEED_TASK.equals(result.getHandshakeStatus()) || !this.appPeerBuffer.hasRemaining()) { retry = false; } read += result.bytesProduced(); } } this.packatPeerBuffer.compact(); } putBuffer(buff); return read; }
Source:
<code>public void testRegisterClusterListenerDuplicates() { reset(); TestClusterListener clusterListener = new TestClusterListener(); _state.registerClusterListener(clusterListener); _state.registerClusterListener(clusterListener); _state.listenToCluster(CLUSTER1_CLUSTER_NAME, new NullStateListenerCallback()); _clusterRegistry.put(CLUSTER1_CLUSTER_NAME, new ClusterProperties(CLUSTER1_CLUSTER_NAME)); <START> assertEquals(clusterListener.getCount(CLUSTER1_CLUSTER_NAME), 1, "expected 1 call"); <END> }</code><technical_language>nice if messages a bit more descriptive reasons expect a number of count. for example, "Expected 1 call duplicates allowed." test easier understand</technical_language>

Target:
public void testRegisterClusterListenerDuplicates() { reset(); MockClusterListener clusterListener = new MockClusterListener(); _state.registerClusterListener(clusterListener); _state.registerClusterListener(clusterListener); _state.listenToCluster(CLUSTER1_CLUSTER_NAME, new NullStateListenerCallback()); _clusterRegistry.put(CLUSTER1_CLUSTER_NAME, new ClusterProperties(CLUSTER1_CLUSTER_NAME)); assertEquals(clusterListener.getClusterAddedCount(CLUSTER1_CLUSTER_NAME), 1, "expected 1 call since duplicates are not allowed"); }
Source:
<code>private ExportValue emptyValue() { <START> return new JustValue("", ValueType.EMPTY, (empty) -> "--"); <END> }</code><technical_language>Define empty string a constant</technical_language>

Target:
private ExportValue emptyValue() { return new JustValue("--", ValueType.EMPTY); }
Source:
<code>protected Thread createDispatchThread() { return new Thread(new Runnable() { public void run() { while (!shutDown || drainingBeforeShutdown) { try { final ApnsConnection<T> connection = connectionPool.getNextConnection(); T notification = retryQueue.poll(); if (notification == null && !drainingBeforeShutdown) { notification = queue.poll(); } if (notification != null) { connection.sendNotification(notification); } else { <START> if (drainingBeforeShutdown) { <END> for (final ApnsConnection<T> connectionToClose : connectionPool.getAll()) { connectionToClose.shutdownGracefully(); } } Thread.sleep(POLL_TIMEOUT); } } catch (InterruptedException e) { continue; } } } }); }</code><technical_language>drain send of notifications</technical_language>

Target:
protected Thread createDispatchThread() { return new Thread(new Runnable() { public void run() { while (!shutDown || drainingBeforeShutdown) { try { final ApnsConnection<T> connection = connectionPool.getNextConnection(); T notification = retryQueue.poll(); if (notification == null && !drainingBeforeShutdown) { notification = queue.take(); } if (notification != null) { connection.sendNotification(notification); } else { for (final ApnsConnection<T> connectionToClose : connectionPool.getAll()) { connectionToClose.shutdownGracefully(); } } } catch (InterruptedException e) { continue; } } } }); }
Source:
<code>public String toString() { return "BuildImageParams{" + "repository='" + repository + '\'' + ", tag='" + tag + '\'' + ", authConfigs=" + authConfigs + ", doForcePull=" + doForcePull + ", memoryLimit=" + memoryLimit + ", memorySwapLimit=" + memorySwapLimit + ", files=" + files + ", dockerfile='" + dockerfile + '\'' + ", remote='" + remote + '\'' + ", quiet=" + quiet + ", noCache=" + noCache + ", removeIntermediateContainer=" + removeIntermediateContainer + ", forceRemoveIntermediateContainers=" + forceRemoveIntermediateContainers + <START> ", cpusetCpus=" + cpusetCpus + <END> ", cpuPeriod=" + cpuPeriod + ", cpuQuota=" + cpuQuota + ", buildArgs=" + buildArgs + '}'; }</code><technical_language>symbol</technical_language>

Target:
public String toString() { return "BuildImageParams{" + "repository='" + repository + '\'' + ", tag='" + tag + '\'' + ", authConfigs='" + authConfigs + '\'' + ", doForcePull='" + doForcePull + '\'' + ", memoryLimit='" + memoryLimit + '\'' + ", memorySwapLimit='" + memorySwapLimit + '\'' + ", files=" + files + '\'' + ", dockerfile='" + dockerfile + '\'' + ", remote='" + remote + '\'' + ", quiet='" + quiet + '\'' + ", noCache='" + noCache + '\'' + ", removeIntermediateContainer='" + removeIntermediateContainer + '\'' + ", forceRemoveIntermediateContainers='" + forceRemoveIntermediateContainers + '\'' + ", cpusetCpus='" + cpusetCpus + '\'' + ", cpuPeriod='" + cpuPeriod + '\'' + ", cpuQuota='" + cpuQuota + '\'' + ", buildArgs='" + buildArgs + '\'' + '}'; }
Source:
<code><START> public void testSerializable() throws JsonProcessingException { <END> RestoreRedundancyResultsImpl restoreRedundancyResults = new RestoreRedundancyResultsImpl(); restoreRedundancyResults.setStatusMessage("Test"); restoreRedundancyResults.setSuccess(true); restoreRedundancyResults.setTotalPrimaryTransfersCompleted(150); restoreRedundancyResults.setTotalPrimaryTransferTime(250); RegionRedundancyStatusImpl regionRedundancyStatus = new RegionRedundancyStatusImpl(); regionRedundancyStatus.setActualRedundancy(1); regionRedundancyStatus.setConfiguredRedundancy(1); regionRedundancyStatus.setRegionName("/foo"); regionRedundancyStatus.setStatus(SATISFIED); restoreRedundancyResults.addRegionResult(regionRedundancyStatus); String jsonString = geodeMapper.writeValueAsString(restoreRedundancyResults); RestoreRedundancyResultsImpl value = geodeMapper.readValue(jsonString, RestoreRedundancyResultsImpl.class); assertThat(value.getStatusMessage()).isEqualTo("Test"); assertThat(value.getSuccess()).isTrue(); }</code><technical_language>This test sets multiple fields verify of them. confirm data in object is correctly serialized deserialized, message status fields</technical_language>

Target:
public void testSerializable() throws JsonProcessingException { RestoreRedundancyResultsImpl restoreRedundancyResults = new RestoreRedundancyResultsImpl(); restoreRedundancyResults.setStatusMessage(TEST_STRING); restoreRedundancyResults.setSuccess(true); restoreRedundancyResults.setTotalPrimaryTransfersCompleted(150); restoreRedundancyResults.setTotalPrimaryTransferTime(250); RegionRedundancyStatusImpl regionRedundancyStatus = new RegionRedundancyStatusImpl(); regionRedundancyStatus.setActualRedundancy(1); regionRedundancyStatus.setConfiguredRedundancy(1); regionRedundancyStatus.setRegionName("/foo"); regionRedundancyStatus.setStatus(SATISFIED); restoreRedundancyResults.addRegionResult(regionRedundancyStatus); String jsonString = geodeMapper.writeValueAsString(restoreRedundancyResults); RestoreRedundancyResultsImpl value = geodeMapper.readValue(jsonString, RestoreRedundancyResultsImpl.class); assertThat(value).usingRecursiveComparison().isEqualTo(restoreRedundancyResults); }
Source:
<code>public void toggleAvailableOffline(OCFile file, boolean isAvailableOffline) { if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT == file.getAvailableOfflineStatus()) { Snackbar snackbar = Snackbar.make( mFileActivity.findViewById(android.R.id.content), R.string.available_offline_inherited_msg, Snackbar.LENGTH_LONG ); snackbar.show(); } else { OCFile.AvailableOfflineStatus targetAvailableOfflineStatus = isAvailableOffline ? OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE : OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE; file.setAvailableOfflineStatus(targetAvailableOfflineStatus); boolean success = mFileActivity.getStorageManager().saveLocalAvailableOfflineStatus(file); if (success) { FileObserverService.observeFile( mFileActivity, file, mFileActivity.getAccount(), isAvailableOffline ); if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE == file.getAvailableOfflineStatus()) { syncFile(file); } else { cancelTransference(file); } } else { <START> Snackbar snackbar = Snackbar.make( <END> mFileActivity.findViewById(android.R.id.content), R.string.common_error_unknown, Snackbar.LENGTH_LONG ); snackbar.show(); } } }</code><technical_language>Same, avoid duplicating code a method show snackbar</technical_language>

Target:
public void toggleAvailableOffline(OCFile file, boolean isAvailableOffline) { if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT == file.getAvailableOfflineStatus()) { mFileActivity.showSnackMessage( mFileActivity.getString(R.string.available_offline_inherited_msg) ); } else { OCFile.AvailableOfflineStatus targetAvailableOfflineStatus = isAvailableOffline ? OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE : OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE; file.setAvailableOfflineStatus(targetAvailableOfflineStatus); boolean success = mFileActivity.getStorageManager().saveLocalAvailableOfflineStatus(file); if (success) { FileObserverService.observeFile( mFileActivity, file, mFileActivity.getAccount(), isAvailableOffline ); if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE == file.getAvailableOfflineStatus()) { syncFile(file); } else { cancelTransference(file); } } else { mFileActivity.showSnackMessage( mFileActivity.getString(R.string.common_error_unknown) ); } } }
Source:
<code>private MQTTSessionState getSessionState(String clientId) { <START> return MQTTSession.getSessionState(clientId, session.getServer().getIdentity()); <END> }</code><technical_language>1 Ive raised this already, simply shouldnt static map holding state</technical_language>

Target:
private MQTTSessionState getSessionState(String clientId) { return session.getProtocolManager().getSessionState(clientId); }
Source:
<code>public void createSynapseDebugEnvironment(ServerContextInformation contextInfo) { try { String carbonHome = System.getProperty(ServerConstants.CARBON_HOME); <START> File synapseProperties = new File(CarbonUtils.getCarbonConfigDirPath() + File.separator + "synapse" + <END> ".properties"); Properties properties = new Properties(); InputStream inputStream = new FileInputStream(synapseProperties); properties.load(inputStream); inputStream.close(); int event_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_EVENT_PORT)); int command_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_COMMAND_PORT)); SynapseDebugInterface debugInterface = SynapseDebugInterface.getInstance(); debugInterface.init(command_port, event_port); contextInfo.setServerDebugModeEnabled(true); contextInfo.setSynapseDebugInterface(debugInterface); SynapseDebugManager debugManager = SynapseDebugManager.getInstance(); contextInfo.setSynapseDebugManager(debugManager); log.info("Synapse debug Environment created successfully"); } catch (IOException ex) { log.error("Error while creating Synapse debug environment ", ex); } catch (InterruptedException ex) { log.error("Error while creating Synapse debug environment ", ex); } }</code><technical_language>Paths.get("").toFile</technical_language>

Target:
public void createSynapseDebugEnvironment(ServerContextInformation contextInfo) { try { File synapseProperties = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "synapse.properties").toFile(); Properties properties = new Properties(); InputStream inputStream = new FileInputStream(synapseProperties); properties.load(inputStream); inputStream.close(); int event_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_EVENT_PORT)); int command_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_COMMAND_PORT)); SynapseDebugInterface debugInterface = SynapseDebugInterface.getInstance(); debugInterface.init(command_port, event_port); contextInfo.setServerDebugModeEnabled(true); contextInfo.setSynapseDebugInterface(debugInterface); SynapseDebugManager debugManager = SynapseDebugManager.getInstance(); contextInfo.setSynapseDebugManager(debugManager); log.info("Synapse debug Environment created successfully"); } catch (IOException ex) { log.error("Error while creating Synapse debug environment ", ex); } catch (InterruptedException ex) { log.error("Error while creating Synapse debug environment ", ex); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> mAnalyticsListener.trackLoginMagicLinkOpened(); <END> Intent intent = new Intent(this, WPMainActivity.class); intent.setAction(getIntent().getAction()); intent.setData(getIntent().getData()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); }</code><technical_language>I need inject mAnalyticsListener instance it, null</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) getApplication()).component().inject(this); mLoginAnalyticsListener.trackLoginMagicLinkOpened(); Intent intent = new Intent(this, WPMainActivity.class); intent.setAction(getIntent().getAction()); intent.setData(getIntent().getData()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); }
Source:
<code>public void registerAttributes(ManagementResourceRegistration registry) { super.registerAttributes(registry); registerPatchingAttributes(registry); final StandardResourceDescriptionResolver resolver = new StandardResourceDescriptionResolver("patching.patch-stream", RESOURCE_NAME, PatchResourceDefinition.class.getClassLoader()); registry.registerSubModel(new SimpleResourceDefinition(PathElement.pathElement("patch-stream"), resolver) { @Override public void registerAttributes(final ManagementResourceRegistration resource) { super.registerAttributes(resource); registerPatchingAttributes(resource); <START> resource.setRuntimeOnly(true); <END> } @Override public void registerOperations(ManagementResourceRegistration registry) { PatchResourceDefinition.this.registerPatchingOperations(registry, false); } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return sensitivity; } }); registry.setRuntimeOnly(true); }</code><technical_language>WFCORE-17 is resolved now</technical_language>

Target:
public void registerAttributes(ManagementResourceRegistration registry) { super.registerAttributes(registry); registerPatchingAttributes(registry); final StandardResourceDescriptionResolver resolver = new StandardResourceDescriptionResolver("patching.patch-stream", RESOURCE_NAME, PatchResourceDefinition.class.getClassLoader()); registry.registerSubModel(new SimpleResourceDefinition(PathElement.pathElement("patch-stream"), resolver) { @Override public void registerAttributes(final ManagementResourceRegistration resource) { super.registerAttributes(resource); registerPatchingAttributes(resource); } @Override public void registerOperations(ManagementResourceRegistration registry) { PatchResourceDefinition.this.registerPatchingOperations(registry, false); } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return sensitivity; } }); }
Source:
<code>public RestHighLevelClient create() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(args.esUser, args.esPassword)); return new RestHighLevelClient( RestClient.builder(new HttpHost(args.esHostname, args.esPort, "http")) .setHttpClientConfigCallback(new HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { <START> return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); <END> } }) .setRequestConfigCallback(new RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder .setConnectTimeout(args.esConnectTimeout) .setSocketTimeout(args.esSocketTimeout); } }) ); }</code><technical_language>This done a lambda remove lots of boilerplate code</technical_language>

Target:
public RestHighLevelClient create() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(args.esUser, args.esPassword)); return new RestHighLevelClient( RestClient.builder(new HttpHost(args.esHostname, args.esPort, "http")) .setHttpClientConfigCallback( (HttpAsyncClientBuilder httpClientBuilder) -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) .setRequestConfigCallback( (RequestConfig.Builder requestConfigBuilder) -> requestConfigBuilder .setConnectTimeout(args.esConnectTimeout) .setSocketTimeout(args.esSocketTimeout)) ); }
Source:
<code>private XSSFSheet getSheet() { if(sheet==null) { workbook = new XSSFWorkbook(); <START> sheet = workbook.createSheet(); <END> } return sheet; }</code><technical_language>This remove ability modify existing chart</technical_language>

Target:
private XSSFSheet getSheet() { XSSFSheet sheet = null; try { sheet = getWorkbook().getSheetAt(0); } catch (InvalidFormatException ife) { } catch (IOException ioe) { } return sheet; }
Source:
<code>protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { <START> logger.error("Interrupted when trying to buffer data! Dropping data"); <END> return false; } }</code><technical_language>This a WARN instead of ERROR</technical_language>

Target:
protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.warn("Interrupted when trying to buffer data! Dropping data"); return false; } }
Source:
<code>private PrivateKeyEntry getPrivateKeyEntry() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); KeyStore.PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StoreUtil.getInstance().getPrivateKeyAlias(); if (clientkeyAlias != null) { final String password = getKeyStoreSystemProperties().get(KEY_STORE_SECRET_KEY); if (password != null) { try { pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { LOG.error("Error initializing Private Key: {}", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("javax.net.ssl.keyStorePassword is not a defined system property."); } } else { <START> LOG.error(NhincConstants.CLIENT_KEY_ALIAS + " is not a defined system property."); <END> } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }</code><technical_language>This log statement parameterized</technical_language>

Target:
private PrivateKeyEntry getPrivateKeyEntry() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); KeyStore.PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StoreUtil.getInstance().getPrivateKeyAlias(); if (clientkeyAlias != null) { final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { LOG.error("Error initializing Private Key: {}", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } } else { LOG.error("{} is not a defined system property.", NhincConstants.CLIENT_KEY_ALIAS); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }
Source:
<code>public void testSetInteresting() { GerritEventType type = GerritEventType.CHANGE_MERGED; <START> type.setInteresting(false); <END> assertEquals(false, type.isInteresting()); type.setInteresting(true); assertEquals(true, type.isInteresting()); }</code><technical_language>moment static changes affects other tests. Some engines newer surefire runs suite in vm while others run in same, if wrong line 12 set false. wrap line 12 15 in a try {...} finally { type.setInteresting(true); } in case</technical_language>

Target:
public void testSetInteresting() { GerritEventType type = GerritEventType.CHANGE_MERGED; try { type.setInteresting(false); assertEquals(false, type.isInteresting()); type.setInteresting(true); assertEquals(true, type.isInteresting()); } finally { type.setInteresting(true); } }
Source:
<code>private Date parseEndTimeJson(JSONObject json) { String endTimeString; try { endTimeString = json.getString(END_TIME); } catch (JSONException e) { return null; } <START> SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); <END> try { Date date = format.parse(endTimeString); return date; } catch (ParseException e) { e.printStackTrace(); } return null; }</code><technical_language>put this a constant</technical_language>

Target:
private Date parseEndTimeJson(JSONObject json) { String endTimeString; try { endTimeString = json.getString(END_TIME); } catch (JSONException e) { return null; } SimpleDateFormat format = OneSignalSimpleDateFormat.iso8601Format(); try { Date date = format.parse(endTimeString); return date; } catch (ParseException e) { e.printStackTrace(); } return null; }
Source:
<code>public static final void enforceTetherChangePermission(Context context, String callingPkg) { if (context.getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) { context.enforceCallingOrSelfPermission( android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService"); } else { int uid = Binder.getCallingUid(); <START> if (callingPkg == null) { callingPkg = Settings.getPackageNameForUid(context, uid); } <END> Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg, true ); } }</code><technical_language>Is valid for callingPkg null? If not, this code throw NullPointerException IllegalArgumentException</technical_language>

Target:
public static final void enforceTetherChangePermission(Context context, String callingPkg) { if (null == context || null == callingPkg) { throw new IllegalArgumentException("arguments should not be null"); } if (context.getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) { context.enforceCallingOrSelfPermission( android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService"); } else { int uid = Binder.getCallingUid(); Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg, true ); } }
Source:
<code>public void onResume() { super.onResume(); addCachedDevices(); <START> if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) <END> removeAllDevices(); if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } }</code><technical_language>Style issue: please braces in a multiline conditional</technical_language>

Target:
public void onResume() { super.onResume(); addCachedDevices(); if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) { removeAllDevices(); } if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } }
Source:
<code>static void validate(Job job, ForecastJobAction.Request request) { if (job.getJobVersion() == null || job.getJobVersion().before(Version.fromString("6.1.0"))) { throw ExceptionsHelper.badRequestException( "Cannot run forecast because jobs created prior to version 6.1 are not supported"); } if (request.getDuration() != null) { TimeValue duration = request.getDuration(); TimeValue bucketSpan = job.getAnalysisConfig().getBucketSpan(); if (duration.compareTo(bucketSpan) < 0) { throw ExceptionsHelper.badRequestException( "[" + DURATION.getPreferredName() + "] must be greater or equal to the bucket span: [" + duration.getStringRep() + "/" + bucketSpan.getStringRep() + "]"); } } if (request.getMaxModelMemory() != null) { if (request.getMaxModelMemory() >= FORECAST_LOCAL_STORAGE_LIMIT.getBytes()) { throw ExceptionsHelper.badRequestException( <START> "[{}] must be less than 500MB", <END> ForecastJobAction.Request.MAX_MODEL_MEMORY.getPreferredName()); } } }</code><technical_language>nit: constant in if, sense here,</technical_language>

Target:
static void validate(Job job, ForecastJobAction.Request request) { if (job.getJobVersion() == null || job.getJobVersion().before(Version.fromString("6.1.0"))) { throw ExceptionsHelper.badRequestException( "Cannot run forecast because jobs created prior to version 6.1 are not supported"); } if (request.getDuration() != null) { TimeValue duration = request.getDuration(); TimeValue bucketSpan = job.getAnalysisConfig().getBucketSpan(); if (duration.compareTo(bucketSpan) < 0) { throw ExceptionsHelper.badRequestException( "[" + DURATION.getPreferredName() + "] must be greater or equal to the bucket span: [" + duration.getStringRep() + "/" + bucketSpan.getStringRep() + "]"); } } }
Source:
<code>public Optional<String> uriForClip(Publisher publisher, Entry entry) { if (!entry.getAlternateLinks().isEmpty()) { Link link = (Link) entry.getAlternateLinks().get(0); return Optional.of(link.getHref()); <START> } else { <END> Element mediaGroup = C4AtomApi.mediaGroup(entry); if (mediaGroup == null) { return null; } Element player = mediaGroup.getChild("player", C4AtomApi.NS_MEDIA_RSS); if (player == null) { return null; } return Optional.of(player.getAttributeValue("url")); } }</code><technical_language>Else is unnecessary</technical_language>

Target:
public Optional<String> uriForClip(Publisher publisher, Entry entry) { List alternateLinks = entry.getAlternateLinks(); if (!alternateLinks.isEmpty()) { java.util.Optional<Link> odLink = ((List<Link>) alternateLinks).stream() .filter(link -> "4oD".equals(link.getTitle())) .findFirst(); if (odLink.isPresent()) { return Optional.of(odLink.get().getHref()); } } Element mediaGroup = C4AtomApi.mediaGroup(entry); if (mediaGroup == null) { return null; } Element player = mediaGroup.getChild("player", C4AtomApi.NS_MEDIA_RSS); if (player == null) { return null; } return Optional.of(player.getAttributeValue("url")); }
Source:
<code>private void parse() throws IOException { stream.mark(0); try { <START> byte[] curIdentifier = new byte[3]; <END> for (int i = 0; i < curIdentifier.length; i++) { curIdentifier[i] = stream.readByte(); } setIdentifier(new String(curIdentifier)); setFileVersion(stream.readByte()); setNumberOfEntries(Integer.reverseBytes(stream.readInt())); for (InfiniumFileTOC toc : getTableOfContents()) { stream.reset(); readData(stream, toc); } if (numCalls == 0) { numCalls = aaCalls + abCalls + bbCalls; } } finally { stream.close(); } if ((normalizationManifest != null) && (normalizationManifest.getNormIds() != null)) { normalizeIntensities(); } }</code><technical_language>finals</technical_language>

Target:
private void parse() throws IOException { stream.mark(0); try { final byte[] curIdentifier = new byte[IDENTIFIER_LENGTH]; for (int i = 0; i < curIdentifier.length; i++) { curIdentifier[i] = stream.readByte(); } final String identifier = new String(curIdentifier); setIdentifier(identifier); if (!identifier.equals(GTC_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for GTC file"); } setFileVersion(stream.readByte()); setNumberOfEntries(Integer.reverseBytes(stream.readInt())); for (InfiniumFileTOC toc : getTableOfContents()) { stream.reset(); readData(stream, toc); } if (numCalls == 0) { numCalls = aaCalls + abCalls + bbCalls; } } finally { stream.close(); } if ((normalizationManifest != null) && (normalizationManifest.getNormIds() != null)) { normalizeIntensities(); } }
Source:
<code>private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException { <START> String value = rawAttributeText(reader, attributeDefinition.getXmlName(), attributeDefinition.getDefaultValue().asString()); <END> if (value != null) { attributeDefinition.parseAndSetParameter(value, operation, reader); } else { throw missingRequired(reader, attributeDefinition.getXmlName()); } }</code><technical_language>@ochaloup parser do this. needs preserve read xml, introduce default values management model user put in xml. subsystem a default AttributeDefinition configure runtime services, stored in management model reflect user provided configuration. appears this method is called parseCM method, I eliminating 'else' block throws missingRequired fine</technical_language>

Target:
private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException { String value = rawAttributeText(reader, attributeDefinition.getXmlName(), null); if (value != null) { attributeDefinition.parseAndSetParameter(value, operation, reader); } }
Source:
<code>protected void executeQueryCommand() { String volumeName = getParameters().getVolumeName(); if (!getParameters().isDetailRequired() && StringUtils.isEmpty(volumeName)) { volumeName = getVolumeName(getParameters().getClusterId()); } if (StringUtils.isEmpty(volumeName)) { log.error("No volumes found in the cluster."); getQueryReturnValue().setReturnValue(new GlusterVolumeAdvancedDetails()); return; } <START> try { <END> VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(getParameters().getClusterId()), getParameters().getClusterId(), volumeName, getParameters().getBrickName(), getParameters().isDetailRequired())); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); } catch (RuntimeException e) { log.error(e.getMessage()); getQueryReturnValue().setReturnValue(new GlusterVolumeAdvancedDetails()); } }</code><technical_language>try catch here, is done in QueriesCommandBase, error is set for caller</technical_language>

Target:
protected void executeQueryCommand() { String volumeName = getParameters().getVolumeName(); if (!getParameters().isDetailRequired() && StringUtils.isEmpty(volumeName)) { volumeName = getVolumeName(getParameters().getClusterId()); } if (StringUtils.isEmpty(volumeName)) { log.error("No volumes found in the cluster."); getQueryReturnValue().setReturnValue(new GlusterVolumeAdvancedDetails()); return; } VDSReturnValue returnValue = getBackendResourceManager().RunVdsCommand(VDSCommandType.GetGlusterVolumeAdvancedDetails, new GlusterVolumeAdvancedDetailsVDSParameters(getUpServerId(getParameters().getClusterId()), getParameters().getClusterId(), volumeName, getParameters().getBrickName(), getParameters().isDetailRequired())); getQueryReturnValue().setReturnValue(returnValue.getReturnValue()); }
Source:
<code>public View getView(int position, View view, ViewGroup container) { final Photo current = photos.get(position); final ViewHolder viewHolder; if (view == null) { view = inflater.inflate(R.layout.flickr_photo_list_item, container, false); final ImageView imageView = (ImageView) view.findViewById(R.id.photo_view); TextView titleView = (TextView) view.findViewById(R.id.title_view); viewHolder = new ViewHolder(imageView, titleView); view.setTag(viewHolder); <START> if (photoDimens == null) { <END> photoDimens = new int[]{imageView.getWidth(), imageView.getHeight()}; } } else { viewHolder = (ViewHolder) view.getTag(); } fullRequest .thumbnail(thumbRequest.load(current)) .load(current) .into(viewHolder.imageView); viewHolder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = FullscreenActivity.getIntent(getActivity(), current); startActivity(intent); } }); viewHolder.titleText.setText(current.getTitle()); return view; }</code><technical_language>I this is a bug. time create views, measured getWidth() getHeight() return 0. I get in grid fragment ImageViews fixed dp dimensions. In Giphy sample ImageViews match_parent width in photo list ImageViews layout_weight, incorrect dimensions. A Runnable posted view typically is called View is measured get valid sizes. retain behavior for Giphy PhotoList classes. In future, if it, sense extract another interface is responsible for providing sizes, provide implementation fixed dimensions, another [OnPreDrawListener](<LINK_1> in [ViewTarget](<LINK_0> does, provided a View set dimensions from</technical_language>

Target:
public View getView(int position, View view, ViewGroup container) { final Photo current = photos.get(position); final ViewHolder viewHolder; if (view == null) { view = inflater.inflate(R.layout.flickr_photo_list_item, container, false); final ImageView imageView = (ImageView) view.findViewById(R.id.photo_view); TextView titleView = (TextView) view.findViewById(R.id.title_view); viewHolder = new ViewHolder(imageView, titleView); view.setTag(viewHolder); preloadSizeProvider.setView(imageView); } else { viewHolder = (ViewHolder) view.getTag(); } fullRequest .thumbnail(thumbRequest.load(current)) .load(current) .into(viewHolder.imageView); viewHolder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = FullscreenActivity.getIntent(getActivity(), current); startActivity(intent); } }); viewHolder.titleText.setText(current.getTitle()); return view; }