auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void open() throws InterpreterException { try { if (ipythonClient != null) { return; } pythonExecutable = getProperty("zeppelin.python", "python"); LOGGER.info("Python Exec: " + pythonExecutable); String checkPrerequisiteResult = checkIPythonPrerequisite(pythonExecutable); if (!StringUtils.isEmpty(checkPrerequisiteResult)) { throw new InterpreterException("IPython prerequisite is not meet: " + checkPrerequisiteResult); } ipythonLaunchTimeout = Long.parseLong( getProperty("zeppelin.ipython.launch.timeout", "30000")); this.zeppelinContext = new PythonZeppelinContext( getInterpreterGroup().getInterpreterHookRegistry(), Integer.parseInt(getProperty("zeppelin.python.maxResult", "1000"))); int ipythonPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); int jvmGatewayPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); LOGGER.info("Launching IPython Kernel at port: " + ipythonPort); LOGGER.info("Launching JVM Gateway at port: " + jvmGatewayPort); int framesize = Integer.parseInt(getProperty("zeppelin.ipython.grpc.framesize", 4 * 1024 * 1024 + "")); ipythonClient = new IPythonClient(ManagedChannelBuilder.forAddress("127.0.0.1", ipythonPort) <START> .usePlaintext(true).maxInboundMessageSize(framesize)); <END> launchIPythonKernel(ipythonPort); setupJVMGateway(jvmGatewayPort); } catch (Exception e) { throw new RuntimeException("Fail to open IPythonInterpreter", e); } }</code><technical_language>this .usePlaintext(true) change behavior</technical_language>

Target:
public void open() throws InterpreterException { try { if (ipythonClient != null) { return; } pythonExecutable = getProperty("zeppelin.python", "python"); LOGGER.info("Python Exec: " + pythonExecutable); String checkPrerequisiteResult = checkIPythonPrerequisite(pythonExecutable); if (!StringUtils.isEmpty(checkPrerequisiteResult)) { throw new InterpreterException("IPython prerequisite is not meet: " + checkPrerequisiteResult); } ipythonLaunchTimeout = Long.parseLong( getProperty("zeppelin.ipython.launch.timeout", "30000")); this.zeppelinContext = new PythonZeppelinContext( getInterpreterGroup().getInterpreterHookRegistry(), Integer.parseInt(getProperty("zeppelin.python.maxResult", "1000"))); int ipythonPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); int jvmGatewayPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); LOGGER.info("Launching IPython Kernel at port: " + ipythonPort); LOGGER.info("Launching JVM Gateway at port: " + jvmGatewayPort); int framesize = Integer.parseInt(getProperty("zeppelin.ipython.grpc.framesize", 32 * 1024 * 1024 + "")); ipythonClient = new IPythonClient(ManagedChannelBuilder.forAddress("127.0.0.1", ipythonPort) .usePlaintext(true).maxInboundMessageSize(framesize)); launchIPythonKernel(ipythonPort); setupJVMGateway(jvmGatewayPort); } catch (Exception e) { throw new RuntimeException("Fail to open IPythonInterpreter", e); } }
Source:
<code>public static GeometryProperty<Geometry> calculateBuffer(Object geometryHolder, double bufferWidth, @Nullable TransformationLog log) { InstanceTraverser traverser = new DepthFirstInstanceTraverser(true); GeometryFinder geoFind = new GeometryFinder(null); traverser.traverse(geometryHolder, geoFind); List<GeometryProperty<?>> geometries = geoFind.getGeometries(); GeometryProperty<?> old_geometry = null; if (!geometries.isEmpty()) { old_geometry = geometries.get(0); if (geometries.size() > 1) { if (log != null) { log.warn(log .createMessage( "Multiple geometries found, but network expansion is only done on the first.", null)); } } } GeometryProperty<Geometry> result = null; if (old_geometry != null) { Geometry new_geometry = null; new_geometry = BufferOp.bufferOp(old_geometry.getGeometry(), bufferWidth); <START> <END> result = new DefaultGeometryProperty<Geometry>(old_geometry.getCRSDefinition(), new_geometry); } return result; }</code><technical_language>Is this default in new API</technical_language>

Target:
public static GeometryProperty<Geometry> calculateBuffer(Object geometryHolder, double bufferWidth, @Nullable TransformationLog log) { InstanceTraverser traverser = new DepthFirstInstanceTraverser(true); GeometryFinder geoFind = new GeometryFinder(null); traverser.traverse(geometryHolder, geoFind); List<GeometryProperty<?>> geometries = geoFind.getGeometries(); GeometryProperty<?> old_geometry = null; if (!geometries.isEmpty()) { old_geometry = geometries.get(0); if (geometries.size() > 1) { if (log != null) { log.warn(log .createMessage( "Multiple geometries found, but network expansion is only done on the first.", null)); } } } GeometryProperty<Geometry> result = null; if (old_geometry != null) { Geometry new_geometry = null; BufferParameters bufferParameters = new BufferParameters(); bufferParameters.setEndCapStyle(CAP_STYLE); new_geometry = BufferOp.bufferOp(old_geometry.getGeometry(), bufferWidth, bufferParameters); result = new DefaultGeometryProperty<Geometry>(old_geometry.getCRSDefinition(), new_geometry); } return result; }
Source:
<code><START> public ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { <END> this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); }</code><technical_language>This constructor package visibility instead of public</technical_language>

Target:
protected ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); }
Source:
<code>public void run(final Map<String, List<DataInfo>> dataInfos, final Map<String, Map<String, Double>> computeMetrics, final String controllerId, final Map<String, Double> controllerMetrics) { LOG.log(Level.INFO, "Beginning migration"); <START> final Plan plan = optimizer.optimize( <END> getNodeParameters(dataInfos, computeMetrics), getAvailableEvaluators(computeMetrics.size())); if (planExecutionResult.isDone()) { try { LOG.log(Level.INFO, "Previous result: " + planExecutionResult.get()); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { throw new RuntimeException(e); } planExecutionResult = planExecutor.execute(plan); try { LOG.log(Level.INFO, "Blocking until the migration is done."); final PlanResult result = planExecutionResult.get(); LOG.log(Level.INFO, "Current result: " + result); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { throw new RuntimeException(e); } } }</code><technical_language>question. run() is called in iteration, right? If curious reasonable generate a plan possibly changed due migration in progress</technical_language>

Target:
public synchronized void run(final Map<String, List<DataInfo>> dataInfos, final Map<String, Map<String, Double>> computeMetrics, final String controllerId, final Map<String, Double> controllerMetrics) { if (isPlanExecuting()) { LOG.log(Level.INFO, "Skipping Optimization, as the previous plan is still executing."); return; } LOG.log(Level.INFO, "Optimization start."); logPreviousResult(); final Plan plan = optimizer.optimize( getEvaluatorParameters(dataInfos, computeMetrics, controllerId, controllerMetrics), getAvailableEvaluators(computeMetrics.size())); planExecutionResult = planExecutor.execute(plan); blockUntilPlanIsExecuted(); LOG.log(Level.INFO, "Optimization complete."); }
Source:
<code>public boolean isKeyStorePassword(char[] password) throws IOException{ if (password==null) return false; assertActivatedKeyStore(); KeyStore testStore=null; try { testStore = KeyStore.getInstance(KEYSTORETYPE); } catch (KeyStoreException e1) { throw new RuntimeException(e1); } <START> InputStream fis = getResource().in(); <END> try { testStore.load(fis, password); } catch (IOException e2) { return false; } catch (Exception e) { throw new RuntimeException(e); } fis.close(); return true; }</code><technical_language>@NielsCharlier please refactor try-with-resources. Shorter. error prone. In this case, Error leave InputStream unclosed</technical_language>

Target:
public boolean isKeyStorePassword(char[] password) throws IOException{ if (password==null) return false; assertActivatedKeyStore(); KeyStore testStore=null; try { testStore = KeyStore.getInstance(KEYSTORETYPE); } catch (KeyStoreException e1) { throw new RuntimeException(e1); } try (InputStream fis = getResource().in()) { testStore.load(fis, password); } catch (IOException e2) { return false; } catch (Exception e) { throw new RuntimeException(e); } return true; }
Source:
<code>public Tuple exec(Tuple input) throws IOException { if (sites==null) { initSites(); } String hostname = (String)input.get(5); DefaultDataBag timeline = (DefaultDataBag)input.get(7); Iterator<Tuple> myit = timeline.iterator(); Tuple item; String prevState = "UNKNOWN"; for (int i=0;i<timeline.size();i++) { item = myit.next(); item.append(prevState); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date parsedDate = null; try { parsedDate = dateFormat.parse((String) item.get(0)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(parsedDate); <START> int the_hours = cal.get(Calendar.HOUR); <END> int am = cal.get(Calendar.AM_PM); if (am>0) the_hours = the_hours + 12; int date_int = (cal.get(Calendar.YEAR) * 10000 ) + ((cal.get(Calendar.MONTH) + 1)*100) + (cal.get(Calendar.DAY_OF_MONTH)); int time_int = (the_hours * 10000) + ((cal.get(Calendar.MINUTE)*100)) + (cal.get(Calendar.SECOND)); item.append(date_int); item.append(time_int); prevState = (String) item.get(1); } input.append((String)sites.get(hostname)); return input; }</code><technical_language>HOUR here? Hour returns 12-hour clock representation, while HOUR_OF_DAY returns 24-hour clock. If HOUR_OF_DAY, need next lines. I missing</technical_language>

Target:
public Tuple exec(Tuple input) throws IOException { if (sites==null) { initSites(); } String hostname = (String)input.get(5); DefaultDataBag timeline = (DefaultDataBag)input.get(7); Iterator<Tuple> myit = timeline.iterator(); Tuple item; String prevState = "UNKNOWN"; for (int i=0;i<timeline.size();i++) { item = myit.next(); item.append(prevState); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date parsedDate = null; try { parsedDate = dateFormat.parse((String) item.get(0)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(parsedDate); int date_int = (cal.get(Calendar.YEAR) * 10000 ) + ((cal.get(Calendar.MONTH) + 1)*100) + (cal.get(Calendar.DAY_OF_MONTH)); int time_int = (cal.get(Calendar.HOUR_OF_DAY) * 10000) + ((cal.get(Calendar.MINUTE)*100)) + (cal.get(Calendar.SECOND)); item.append(date_int); item.append(time_int); prevState = (String) item.get(1); } input.append((String)sites.get(hostname)); return input; }
Source:
<code>public void setDataConsistentOnStandby(boolean isConsistent) { ReplicationStatusKey key = ReplicationStatusKey.newBuilder().setClusterId(localClusterId).build(); ReplicationStatusVal val = ReplicationStatusVal.newBuilder() <START> .setStatus(LogReplicationMetadata.SyncStatus.STOPPED) <END> .setDataConsistent(isConsistent) .build(); TxBuilder txBuilder = corfuStore.tx(NAMESPACE); txBuilder.update(REPLICATION_STATUS_TABLE, key, val, null); txBuilder.commit(); log.trace("setDataConsistentOnStandby: localClusterId: {}, isConsistent: {}", localClusterId, isConsistent); }</code><technical_language>this is valid for a Standby, more intuitive if status is ongoing? do aim reflect status of replication active's point of view? In case add a status reflects that? misleading, thinking data is consistent replication is stopped, in reality active is transferring data</technical_language>

Target:
public void setDataConsistentOnStandby(boolean isConsistent) { ReplicationStatusKey key = ReplicationStatusKey.newBuilder().setClusterId(localClusterId).build(); ReplicationStatusVal val = ReplicationStatusVal.newBuilder() .setDataConsistent(isConsistent) .build(); TxBuilder txBuilder = corfuStore.tx(NAMESPACE); txBuilder.update(REPLICATION_STATUS_TABLE, key, val, null); txBuilder.commit(); log.trace("setDataConsistentOnStandby: localClusterId: {}, isConsistent: {}", localClusterId, isConsistent); }
Source:
<code>Supplier<CassandraKeyValueServiceRuntimeConfig> preprocessKvsRuntimeConfig( Supplier<Optional<KeyValueServiceRuntimeConfig>> runtimeConfig) { return () -> { Optional<KeyValueServiceRuntimeConfig> configOptional = runtimeConfig.get(); <START> return configOptional.map(config -> { <END> Preconditions.checkArgument(config instanceof CassandraKeyValueServiceRuntimeConfig, "CassandraAtlasDbFactory expects an instance of type %s, found %s", CassandraKeyValueServiceRuntimeConfig.class, config.getClass()); return (CassandraKeyValueServiceRuntimeConfig) config; }).orElse(CassandraKeyValueServiceRuntimeConfig.getDefault()); }; }</code><technical_language>this if I change runtime config invalid (or invalid of a type), system fall default config? log a clear message previous version instead? safer potentially changing everything</technical_language>

Target:
Supplier<CassandraKeyValueServiceRuntimeConfig> preprocessKvsRuntimeConfig( Supplier<Optional<KeyValueServiceRuntimeConfig>> runtimeConfig) { return () -> { Optional<KeyValueServiceRuntimeConfig> configOptional = runtimeConfig.get(); return configOptional.map(config -> { if (!(config instanceof CassandraKeyValueServiceRuntimeConfig)) { log.error("Invalid KeyValueServiceRuntimeConfig. Expected a KeyValueServiceRuntimeConfig of type" + " CassandraKeyValueServiceRuntimeConfig, found %s." + " Using latest valid CassandraKeyValueServiceRuntimeConfig.", config.getClass()); return latestValidRuntimeConfig; } latestValidRuntimeConfig = (CassandraKeyValueServiceRuntimeConfig) config; return latestValidRuntimeConfig; }).orElse(CassandraKeyValueServiceRuntimeConfig.getDefault()); }; }
Source:
<code>public static void prepareMongoDatasources() { if (System.getProperty("mongo.backend") == null) { <START> System.setProperty("mongo.backend", "mongo"); <END> } if (System.getProperty("mongo.database") == null) { System.setProperty("mongo.database", "testdb"); } if (System.getProperty("mongo.host") == null) { System.setProperty("mongo.host", "localhost"); } if (System.getProperty("mongo.port") == null) { System.setProperty("mongo.port", String.valueOf(mongoServer.getPort())); } }</code><technical_language>Making this configurable sense. For mongo, string "mongo"</technical_language>

Target:
public static void prepareMongoDatasources() { if (System.getProperty("mongo.datasource") == null) { System.setProperty("mongo.datasource", "mongo"); } if (System.getProperty("mongo.database") == null) { System.setProperty("mongo.database", "testdb"); } if (System.getProperty("mongo.host") == null) { System.setProperty("mongo.host", "localhost"); } if (System.getProperty("mongo.port") == null) { System.setProperty("mongo.port", String.valueOf(mongoServer.getPort())); } }
Source:
<code>public TaskRepository getObject(){ TaskRepository taskRepository = null; <START> logger.debug("Creating SimpleTaskRepository that will use a JdbcTaskExecutionDao"); <END> taskRepository = new SimpleTaskRepository(createJdbcTaskExecutionDao()); return taskRepository; }</code><technical_language>refactoring-safe SimpleTaskRepository.class.getName(), for JdbcTaskExecutionDao</technical_language>

Target:
public TaskRepository getObject(){ TaskRepository taskRepository = null; logger.debug(String.format("Creating SimpleTaskRepository that will use a %s", JdbcTaskExecutionDao.class.getName())); taskRepository = new SimpleTaskRepository(createJdbcTaskExecutionDao()); return taskRepository; }
Source:
<code>public CreateAllSnapshotsFromVmParameters() { needsLocking = true; <START> snapshotType = SnapshotType.REGULAR; <END> saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); }</code><technical_language>prefer handled (the snapshot type) in a separate change</technical_language>

Target:
public CreateAllSnapshotsFromVmParameters() { needsLocking = true; saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); }
Source:
<code>public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobProperties properties = getProperties(); BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); BlobRequestConditions requestConditions = options.getRequestConditions() == null ? new BlobRequestConditions() : options.getRequestConditions(); <START> requestConditions.setIfMatch(properties.getETag()); <END> return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, requestConditions, properties); }</code><technical_language>I check existing etag conditions. If pass in etag want target, a new possibly some updates, reading version requested</technical_language>

Target:
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobProperties properties = getProperties(); BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); BlobRequestConditions requestConditions = options.getRequestConditions() == null ? new BlobRequestConditions() : options.getRequestConditions(); if (requestConditions.getIfMatch() == null) { requestConditions.setIfMatch(properties.getETag()); } return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, requestConditions, properties); }
Source:
<code>public static DbEngineDialect loadDbEngineDialect() { final String ENGINE_DB_ENGINE_PROPERTIES = "engine-db-engine.properties"; final String DIALECT = "DbEngineDialect"; final Properties props; try { props = ResourceUtils.loadProperties(DbFacadeLocator.class, ENGINE_DB_ENGINE_PROPERTIES); } catch (IOException exception) { throw new IllegalStateException( "Can't load properties from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\".", exception ); } String dialect = props.getProperty(DIALECT); if (dialect == null) { throw new IllegalStateException( "Can't load property \"" + DIALECT + "\" from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\"." ); } try { return (DbEngineDialect) <START> Class.forName(dialect).getDeclaredConstructor(Boolean.TYPE).newInstance(false); <END> } catch (Exception exception) { throw new IllegalStateException( "Can't create instance of dialect class \"" + dialect + "\".", exception ); } }</code><technical_language>this specific cunstructor prevents other inplementation of DbEngineDialect (in fact is a single imlementor), this class that. If class instanciate "new" this dynamic way. Alternatively, Qualifier (like @Named) annotations in order instance of class interested in</technical_language>

Target:
public static DbEngineDialect loadDbEngineDialect() { final String ENGINE_DB_ENGINE_PROPERTIES = "engine-db-engine.properties"; final String DIALECT = "DbEngineDialect"; final Properties props; try { props = ResourceUtils.loadProperties(DbFacadeLocator.class, ENGINE_DB_ENGINE_PROPERTIES); } catch (IOException exception) { throw new IllegalStateException( "Can't load properties from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\".", exception ); } String dialect = props.getProperty(DIALECT); if (dialect == null) { throw new IllegalStateException( "Can't load property \"" + DIALECT + "\" from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\"." ); } try { return (DbEngineDialect) Class.forName(dialect).newInstance(); } catch (Exception exception) { throw new IllegalStateException( "Can't create instance of dialect class \"" + dialect + "\".", exception ); } }
Source:
<code>public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName) throws RealmUnavailableException { Assert.checkNotNullParam("credentialType", credentialType); SupportLevel supportLevel = stateRef.get().getCredentialAcquireSupport(credentialType, algorithmName); <START> if (supportLevel == null) { <END> throw log.unableToDetermineSupportLevel(); } return supportLevel; }</code><technical_language>This dropped</technical_language>

Target:
public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName) throws RealmUnavailableException { Assert.checkNotNullParam("credentialType", credentialType); return stateRef.get().getCredentialAcquireSupport(credentialType, algorithmName); }
Source:
<code>protected String convertToCSV(PersistentResource resource) { if (resource == null) { return null; } StringBuilder str = new StringBuilder(); List<Object[]> json2Csv; try { String jsonStr = resourceToJsonStr(resource); JFlat flat = new JFlat(jsonStr); json2Csv = flat.json2Sheet().headerSeparator("_").getJsonAsSheet(); int index = 0; for (Object[] obj : json2Csv) { if (index++ == 0 && downloadRecordCount != 0) { continue; } String objString = Arrays.toString(obj); if (objString != null) { <START> objString = objString.substring(1, objString.length() - 1); <END> } str.append(objString); if (index == 1) { str.append(System.getProperty("line.separator")); } incrementRecordCount(); } } catch (Exception e) { log.debug("Exception while converting to CSV: {}", e.getMessage()); throw new IllegalStateException(e); } return str.toString(); }</code><technical_language>do remove character</technical_language>

Target:
protected String convertToCSV(PersistentResource resource) { if (resource == null) { return null; } StringBuilder str = new StringBuilder(); List<Object[]> json2Csv; try { String jsonStr = resourceToJsonStr(resource); JFlat flat = new JFlat(jsonStr); json2Csv = flat.json2Sheet().headerSeparator("_").getJsonAsSheet(); int index = 0; for (Object[] obj : json2Csv) { if (index++ == 0 && downloadRecordCount != 1) { continue; } String objString = Arrays.toString(obj); if (objString != null) { objString = objString.substring(1, objString.length() - 1); } str.append(objString); if (index == 1) { str.append(System.getProperty("line.separator")); } } } catch (Exception e) { log.debug("Exception while converting to CSV: {}", e.getMessage()); throw new IllegalStateException(e); } return str.toString(); }
Source:
<code>private IsotopePattern calculateAbundanceAndMass(IsotopePattern current, List<IsotopeContainer> additional) { if (additional == null || additional.size() == 0) return current; List<IsotopeContainer> containers = new ArrayList<>(); if (current == null) { current = new IsotopePattern(); for (IsotopeContainer container : additional) current.addIsotope(container); } else { for (IsotopeContainer container : current.getIsotopes()) { for (IsotopeContainer other : additional) { double abundance = container.getIntensity() * other.getIntensity() * 0.01; double mass = container.getMass() + other.getMass(); IsotopeContainer existing = findExisting(containers, mass, resolution); if (existing != null) { <START> existing.setMass((existing.getMass() + mass) / 2); END> existing.setIntensity(existing.getIntensity() + abundance); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) addDistinctFormula(existing, union(mf, other.getFormula())); } continue; } if (abundance > minAbundance) { IsotopeContainer newcontainer = new IsotopeContainer(mass, abundance); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) newcontainer.addFormula(union(mf, other.getFormula())); } containers.add(newcontainer); } } } current = new IsotopePattern(); for (IsotopeContainer container : containers) { current.addIsotope(container); } } return current; }</code><technical_language>I more sense calculate a weighed average (weighted isotope intensity). In other words, if I 2 isotopes in container isotope 1 100% intensity isotope 2 1% intensity, sense report mass closer isotope 1 mass</technical_language>

Target:
private IsotopePattern calculateAbundanceAndMass(IsotopePattern current, List<IsotopeContainer> additional) { if (additional == null || additional.size() == 0) return current; List<IsotopeContainer> containers = new ArrayList<>(); if (current == null) { current = new IsotopePattern(); for (IsotopeContainer container : additional) current.addIsotope(container); } else { for (IsotopeContainer container : current.getIsotopes()) { for (IsotopeContainer other : additional) { double abundance = container.getIntensity() * other.getIntensity() * 0.01; double mass = container.getMass() + other.getMass(); IsotopeContainer existing = findExisting(containers, mass, resolution); if (existing != null) { double newIntensity = existing.getIntensity() + abundance; existing.setMass((existing.getMass()*existing.getIntensity() + mass*abundance) / newIntensity); existing.setIntensity(newIntensity); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) addDistinctFormula(existing, union(mf, other.getFormula())); } continue; } if (abundance > minAbundance) { IsotopeContainer newcontainer = new IsotopeContainer(mass, abundance); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) newcontainer.addFormula(union(mf, other.getFormula())); } containers.add(newcontainer); } } } current = new IsotopePattern(); for (IsotopeContainer container : containers) { current.addIsotope(container); } } return current; }
Source:
<code>public CompletableFuture<Versioned<LedgerMetadata>> createLedgerMetadata(long ledgerId, LedgerMetadata metadata) { CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>(); String ledgerPath = getLedgerPath(ledgerId); StringCallback scb = new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { if (rc == Code.OK.intValue()) { promise.complete(new Versioned<>(metadata, new LongVersion(0))); } else if (rc == Code.NODEEXISTS.intValue()) { LOG.warn("Failed to create ledger metadata for which already exist", ledgerId); promise.completeExceptionally(new BKException.BKLedgerExistException()); } else { LOG.error("Could not create node for ledger {}", ledgerId, KeeperException.create(Code.get(rc), path)); promise.completeExceptionally(new BKException.ZKException()); } } }; final byte[] data; try { data = serDe.serialize(metadata); } catch (IOException ioe) { <START> promise.completeExceptionally(new BKException.ZKException(ioe)); <END> return promise; } List<ACL> zkAcls = ZkUtils.getACLs(conf); ZkUtils.asyncCreateFullPathOptimistic(zk, ledgerPath, data, zkAcls, CreateMode.PERSISTENT, scb, null); return promise; }</code><technical_language>I suggest defining a new error code for this type of exception. BKException.ZKException is a bit confusing</technical_language>

Target:
public CompletableFuture<Versioned<LedgerMetadata>> createLedgerMetadata(long ledgerId, LedgerMetadata metadata) { CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>(); String ledgerPath = getLedgerPath(ledgerId); StringCallback scb = new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { if (rc == Code.OK.intValue()) { promise.complete(new Versioned<>(metadata, new LongVersion(0))); } else if (rc == Code.NODEEXISTS.intValue()) { LOG.warn("Failed to create ledger metadata for which already exist", ledgerId); promise.completeExceptionally(new BKException.BKLedgerExistException()); } else { LOG.error("Could not create node for ledger {}", ledgerId, KeeperException.create(Code.get(rc), path)); promise.completeExceptionally(new BKException.ZKException()); } } }; final byte[] data; try { data = serDe.serialize(metadata); } catch (IOException ioe) { promise.completeExceptionally(new BKException.BKMetadataSerializationException(ioe)); return promise; } List<ACL> zkAcls = ZkUtils.getACLs(conf); ZkUtils.asyncCreateFullPathOptimistic(zk, ledgerPath, data, zkAcls, CreateMode.PERSISTENT, scb, null); return promise; }
Source:
<code>private static long getSliceArrayRetainedSizeInBytes(Slice[] values) { long sizeInBytes = sizeOf(values); Map<Object, Boolean> uniqueRetained = new IdentityHashMap<>(); for (Slice value : values) { if (value == null) { continue; } if (value.getBase() != null && uniqueRetained.put(value.getBase(), true) == null) { sizeInBytes += value.getRetainedSize(); } <START> else { <END> sizeInBytes += SLICE_INSTANCE_SIZE; } } return sizeInBytes; }</code><technical_language>For empty slice (Slices.EMPTY_SLICE, a single instance JVM) value.getBase() is NULL overtrack in else branch</technical_language>

Target:
private static long getSliceArrayRetainedSizeInBytes(Slice[] values) { long sizeInBytes = sizeOf(values); Map<Object, Boolean> uniqueRetained = new IdentityHashMap<>(); for (Slice value : values) { if (value == null) { continue; } if (value.getBase() != null && uniqueRetained.put(value.getBase(), true) == null) { sizeInBytes += value.getRetainedSize(); } else if (value != EMPTY_SLICE) { sizeInBytes += SLICE_INSTANCE_SIZE; } } return sizeInBytes; }
Source:
<code>public DelegatingSystemTablesProvider(SystemTablesProvider... delegates) { <START> this(Arrays.asList(delegates)); <END> }</code><technical_language>ImmutableList.copyOf</technical_language>

Target:
public DelegatingSystemTablesProvider(SystemTablesProvider... delegates) { this(ImmutableList.copyOf(delegates)); }
Source:
<code>default ResourceIterator<Node> findNodes( Label label, String key1, Object value1, String key2, Object value2 ) { <START> throw new UnsupportedOperationException( "Composite findNodes is not supported by this GraphDatabaseService" ); <END> }</code><technical_language>I good rephrase this kind of messages "findNodes multiple property names values supported."</technical_language>

Target:
default ResourceIterator<Node> findNodes( Label label, String key1, Object value1, String key2, Object value2 ) { throw new UnsupportedOperationException( "findNodes by multiple property names and values is not supported." ); }
Source:
<code>private <T> void invokeSetter(T r, JSONObject j, String name, Method m) { final Object json = getJsonValueOrDefault(j, name, m.getParameters()[0]); if (json == null) return; Class<?>[] pt = m.getParameterTypes(); final Object value = bindJSON(m.getGenericParameterTypes()[0], pt[0], json); try { m.invoke(r, value); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.log(WARNING, "Cannot access property " + name + " of " + r.getClass(), e); } <START> } <END></code><technical_language>publish a library avoid call this directly? useful here</technical_language>

Target:
private <T> void invokeSetter(T r, JSONObject j, String name, Method m) { final Object json = getJsonValueOrDefault(j, name, m.getParameters()[0]); if (json == null) return; Class<?>[] pt = m.getParameterTypes(); final Object value = bindJSON(m.getGenericParameterTypes()[0], pt[0], json); try { final Set violations = validator.forExecutables().validateParameters(r, m, new Object[]{value}); if (!violations.isEmpty()) throw new ConstraintsValidationException(violations); m.invoke(r, value); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.log(WARNING, "Cannot access property " + name + " of " + r.getClass(), e); } }
Source:
<code>public void initialize(CNPJ constraintAnnotation) { <START> firstMod11CheckWithSeparator.initialize( createMod11ProxyAnnotation( 9, 14, 16, true ) ); <END> secondMod11CheckWithSeparator.initialize( createMod11ProxyAnnotation( 9, 16, 17, true ) ); firstMod11CheckWithoutSeparator.initialize( createMod11ProxyAnnotation( 9, 11, 12, true ) ); secondMod11CheckWithoutSeparator.initialize( createMod11ProxyAnnotation( 9, 12, 13, true ) ); }</code><technical_language>adding initialize() method Mod11CheckValidator takes actual argument types instead of annotation. That'd a bit more straight-forward creating annotation proxy for retrieving values it</technical_language>

Target:
public void initialize(CNPJ constraintAnnotation) { withSeparatorMod11Validator1.initialize( 0, 14, 16, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); withSeparatorMod11Validator2.initialize( 0, 16, 17, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); withoutSeparatorMod11Validator1.initialize( 0, 11, 12, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); withoutSeparatorMod11Validator2.initialize( 0, 12, 13, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); }
Source:
<code>protected Loader<CompletedTask> createLoader(int id, Bundle bundle) { if( id == LOADER_PERSONA ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getProfilePersonasUri(mProfileData.getId())); } else if( id == LOADER_STATS ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getPersonaOverviewUri(mSelectedPersona, mSelectedPlatformId)); } <START> return null; <END> }</code><technical_language>Bad, do return null. Return is loader other, is between. If get return null carry out checks do trust code</technical_language>

Target:
protected Loader<CompletedTask> createLoader(int id, Bundle bundle) { if( id == LOADER_PERSONA ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getProfilePersonasUri(mProfileData.getId())); } else { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getPersonaOverviewUri(mSelectedPersona, mSelectedPlatformId)); } }
Source:
<code>public static void main(String...args) { Cli<BrooklynCommand> parser = buildCli(); try { log.debug("Parsing command line arguments"); BrooklynCommand command = parser.parse(args); <START> log.debug("Executing command: "+command); <END> command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); System.err.println(); callHelpCommand(); System.exit(PARSE_ERROR); } catch (Exception e) { System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); System.exit(EXECUTION_ERROR); } }</code><technical_language>wrong this line</technical_language>

Target:
public static void main(String...args) { Cli<BrooklynCommand> parser = buildCli(); try { log.debug("Parsing command line arguments: {}",args); BrooklynCommand command = parser.parse(args); log.debug("Executing command: {}", command); command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); System.err.println(getUsageInfo(parser)); System.exit(PARSE_ERROR); } catch (Exception e) { log.error("Execution error: {}\n{}" + e.getMessage(),e.getStackTrace()); System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); System.exit(EXECUTION_ERROR); } }
Source:
<code>public static int ownedQuantity(ArrayList<Order> position, String symbol) { int ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { <START> ownedQuantity += stock.getSize(); <END> } } return ownedQuantity; }</code><technical_language>unsafe addition, integer overflow. long instead of integer</technical_language>

Target:
public static int ownedQuantity(ArrayList<Order> position, String symbol) { long ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { ownedQuantity += stock.getSize(); } } return ownedQuantity; }
Source:
<code>public static String formatDuration(long nanoseconds) { String[] parts = DurationFormatUtils.formatDuration(nanoseconds / NANOSECONDS_PER_SEC, "H:m:s:S").split(":"); StringBuilder builder = new StringBuilder(); if(Integer.valueOf(parts[0]) > 0){ builder.append(parts[0]).append(" hrs."); } if(Integer.valueOf(parts[1]) > 0){ builder.append(" ").append(parts[1]).append(" min."); } if(Integer.valueOf(parts[2]) > 0){ builder.append(" ").append(parts[2]).append(" sec."); } if(builder.length() == 0) { <START> builder.append("Less than 0 sec."); <END> } return builder.toString().trim(); }</code><technical_language>"just now."</technical_language>

Target:
public static String formatDuration(long nanoseconds) { String[] parts = DurationFormatUtils.formatDuration(nanoseconds / NANOSECONDS_PER_SEC, "H:m:s:S").split(":"); StringBuilder builder = new StringBuilder(); if(Integer.valueOf(parts[0]) > 0){ builder.append(parts[0]).append(" hrs."); } if(Integer.valueOf(parts[1]) > 0){ builder.append(" ").append(parts[1]).append(" min."); } if(Integer.valueOf(parts[2]) > 0){ builder.append(" ").append(parts[2]).append(" sec."); } if(builder.length() == 0) { builder.append("Now"); } return builder.toString().trim(); }
Source:
<code>public void testInitializeStats() throws IOException { describe("Testing the counter values after Abfs is initialised"); <START> AbfsInstrumentation instrumentation = <END> new AbfsInstrumentation(getFileSystem().getUri()); for (int i = 0; i < LARGE_OPS; i++) { instrumentation.incrementStat(AbfsStatistic.CALL_GET_DELEGATION_TOKEN, 1); instrumentation.incrementStat(AbfsStatistic.ERROR_IGNORED, 1); } Map<String, Long> metricMap = instrumentation.toMap(); assertEquals("Mismatch in " + getDelegationTokenOp, LARGE_OPS, (long) metricMap.get(getDelegationTokenOp)); assertEquals("Mismatch in " + errorIgnored, LARGE_OPS, (long) metricMap.get(errorIgnored)); }</code><technical_language>match initial values a separate methods earlier</technical_language>

Target:
public void testInitializeStats() throws IOException { describe("Testing the counter values after Abfs is initialised"); AbfsCounters instrumentation = new AbfsInstrumentation(getFileSystem().getUri()); for (int i = 0; i < LARGE_OPS; i++) { instrumentation.incrementCounter(AbfsStatistic.CALL_GET_DELEGATION_TOKEN, 1); instrumentation.incrementCounter(AbfsStatistic.ERROR_IGNORED, 1); } Map<String, Long> metricMap = instrumentation.toMap(); assertAbfsStatistics(AbfsStatistic.CALL_GET_DELEGATION_TOKEN, LARGE_OPS, metricMap); assertAbfsStatistics(AbfsStatistic.ERROR_IGNORED, LARGE_OPS, metricMap); }
Source:
<code>private <T extends Message> void fetchUnsyncedMessages(final Account account, final Folder<T> remoteFolder, List<T> unsyncedMessages, final List<Message> smallMessages, final List<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages, fp, new MessageRetrievalListener<T>() { @Override public void messageFinished(T message, int number, int ofTotal) { try { if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { <START> if (K9.isDebug()) { <END> if (message.isSet(Flag.DELETED)) { Timber.v("Newly downloaded message %s:%s:%s was marked deleted on server, " + "skipping", account, folder, message.getUid()); } else { Timber.d("Newly downloaded message %s is older than %s, skipping", message.getUid(), earliestDate); } } progress.incrementAndGet(); for (MessagingListener l : controller.getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } if (account.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } } catch (Exception e) { Timber.e(e, "Error while storing downloaded message."); } } @Override public void messageStarted(String uid, int number, int ofTotal) { } @Override public void messagesFinished(int total) { } }); }</code><technical_language>extract processOldOrDeletedMessage() reduce nesting here</technical_language>

Target:
private <T extends Message> void fetchUnsyncedMessages(final Account account, final Folder<T> remoteFolder, List<T> unsyncedMessages, final List<Message> smallMessages, final List<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages, fp, new MessageRetrievalListener<T>() { @Override public void messageFinished(T message, int number, int ofTotal) { try { if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { processDeletedOrOldMessage(message, account, remoteFolder.getName(), earliestDate, progress, todo); return; } if (account.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } } catch (Exception e) { Timber.e(e, "Error while storing downloaded message."); } } @Override public void messageStarted(String uid, int number, int ofTotal) { } @Override public void messagesFinished(int total) { } }); }
Source:
<code>public List<Diagnosis> getPrimaryDiagnoses(Encounter encounter) { <START> List<Diagnosis> diagnoses = null; <END> if (encounter != null && !encounter.getVoided()) { diagnoses = new ArrayList<Diagnosis>(); for (Diagnosis diagnosis : encounter.getDiagnoses()) { if (diagnosis.getOrder == DIAGNOSIS_ORDER_PRIMARY) { diagnoses.add(diagnosis); } } } return diagnoses; }</code><technical_language>want this return null, return empty list worst case scenario</technical_language>

Target:
public List<Diagnosis> getPrimaryDiagnoses(Encounter encounter) { List<Diagnosis> diagnoses = new ArrayList<Diagnosis>(); if (encounter != null && !encounter.getVoided()) { for (Diagnosis diagnosis : encounter.getDiagnoses()) { if (diagnosis.getRank() == 1) { diagnoses.add(diagnosis); } } } return diagnoses; }
Source:
<code>private boolean hasCorrespondingNotificationPreference(DocumentReference user, CompositeEvent compositeEvent) { try { for (NotificationPreference notificationPreference: this.modelBridge.getNotificationsPreferences(user)) { <START> if (notificationPreference.getEventType().equals(compositeEvent.getType())) { <END> return notificationPreference.isNotificationEnabled(); } } } catch (NotificationException e) { this.logger.warn( String.format("Unable to retrieve the notifications preferences of [%s]: [%s]", user, e)); } return false; }</code><technical_language>need verify preference is email format, alert (a.ka. notifications in menu)</technical_language>

Target:
private boolean hasCorrespondingNotificationPreference(DocumentReference user, CompositeEvent compositeEvent) { try { for (NotificationPreference notificationPreference: this.modelBridge.getNotificationsPreferences(user)) { if (notificationPreference.getFormat().equals(NotificationFormat.EMAIL) && notificationPreference.getEventType().equals(compositeEvent.getType())) { return notificationPreference.isNotificationEnabled(); } } } catch (NotificationException e) { this.logger.warn( String.format("Unable to retrieve the notifications preferences of [%s]: [%s]", user, e)); } return false; }
Source:
<code>private void createColumns() { if (!fColumnsCreated) { SegmentStoreTableDataProvider provider = fDataProvider; if (provider != null) { TmfModelResponse<List<SegmentStoreTableColumnDataModel>> providerColumns = provider.fetchTree(new TimeQueryFilter(0, 0, 2), null); List<SegmentStoreTableColumnDataModel> model = providerColumns.getModel(); if (model != null && !model.isEmpty()) { int columnIndex = 0; for (SegmentStoreTableColumnDataModel columnData : model) { fColumnIdToLineIndex.put(columnData.getId(), columnIndex); createColumn(columnData.getId(), columnData.getName(), new SegmentStoreTableColumnLabelProvider() { @Override public String getTextForLine(SegmentStoreTableLine input) { Integer index = fColumnIdToLineIndex.get(columnData.getId()); if (index != null && index < input.getLine().size()) { String text = input.getLine().get(index); <START> if (index == 0 || index == 1) { return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(Long.parseLong(text))); } else if (index == 2) { return NonNullUtils.nullToEmptyString(FORMATTER.format(Long.parseLong(text))); } <END> return input.getLine().get(index); } return ""; } }, null); columnIndex++; } setColumnOrder(model.size()); } fColumnsCreated = true; } } }</code><technical_language>start /end / duration necessarily here</technical_language>

Target:
private void createColumns() { if (!fColumnsCreated) { SegmentStoreTableDataProvider provider = fDataProvider; if (provider != null) { TmfModelResponse<List<SegmentStoreTableColumnDataModel>> providerColumns = provider.fetchTree(new TimeQueryFilter(0, 0, 2), null); List<SegmentStoreTableColumnDataModel> model = providerColumns.getModel(); if (model != null && !model.isEmpty()) { int columnIndex = 0; for (SegmentStoreTableColumnDataModel columnData : model) { fColumnIdToLineIndex.put(columnData.getId(), columnIndex); createColumn(columnData.getId(), columnData.getName(), new SegmentStoreTableColumnLabelProvider() { @Override public String getTextForLine(SegmentStoreTableLine input) { Integer index = fColumnIdToLineIndex.get(columnData.getId()); if (index != null && index < input.getLine().size()) { switch (index) { case 0: return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getStartTime())); case 1: return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getEndTime())); case 2: return NonNullUtils.nullToEmptyString(FORMATTER.format(input.getEndTime() - input.getStartTime())); default: return input.getLine().get(index); } } return ""; } }, null); columnIndex++; } setColumnOrder(model.size()); } fColumnsCreated = true; } } }
Source:
<code>protected void executeVmCommand() { Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getParameters().setSnapshotType(determineSnapshotType()); getParameters().setInitialVmStatus(getVm().getStatus()); getSnapshotDao().updateId(createdSnapshotId, newActiveSnapshotId); setActionReturnValue(createdSnapshotId); MemoryImageBuilder memoryImageBuilder = createMemoryImageBuilder(); addSnapshotToDB(createdSnapshotId, memoryImageBuilder); createSnapshotsForDisks(); memoryImageBuilder.build(); <START> if (getTaskIdList().isEmpty()) { <END> getParameters().setTaskGroupSuccess(true); incrementVmGeneration(); } if (!prepareForMemorySnapshot) { freeLock(); } setSucceeded(true); }</code><technical_language>initializing taskGroupSuccess true while is true default. set task group success false update true</technical_language>

Target:
protected void executeVmCommand() { Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getParameters().setSnapshotType(determineSnapshotType()); getParameters().setInitialVmStatus(getVm().getStatus()); getSnapshotDao().updateId(createdSnapshotId, newActiveSnapshotId); setActionReturnValue(createdSnapshotId); MemoryImageBuilder memoryImageBuilder = createMemoryImageBuilder(); addSnapshotToDB(createdSnapshotId, memoryImageBuilder); createSnapshotsForDisks(); memoryImageBuilder.build(); getParameters().setTaskGroupSuccess(false); if (getTaskIdList().isEmpty()) { incrementVmGeneration(); } if (!prepareForMemorySnapshot) { freeLock(); } setSucceeded(true); }