auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected static Map<String,Effector<?>> findEffectors(Class<? extends Entity> clazz, Entity optionalEntity) { try { Map<String,Effector<?>> result = Maps.newLinkedHashMap(); Map<String,Field> sources = Maps.newLinkedHashMap(); for (Field f : clazz.getFields()) { if (Effector.class.isAssignableFrom(f.getType())) { if (!Modifier.isStatic(f.getModifiers())) { <START> LOG.warn("Discouraged use of non-static effector "+f+" defined in " + (optionalEntity!=null ? optionalEntity : clazz)); <END> if (optionalEntity==null) continue; } Effector<?> eff = (Effector<?>) f.get(optionalEntity); Effector<?> overwritten = result.put(eff.getName(), eff); Field source = sources.put(eff.getName(), f); if (overwritten!=null && overwritten != eff) LOG.warn("multiple definitions for effector on {}; preferring from to from {}", new Object[] { eff.getName(), optionalEntity!=null ? optionalEntity : clazz, eff, f, overwritten, source}); } } return result; } catch (IllegalAccessException e) { throw Throwables.propagate(e); } }</code><technical_language>Do want continue support this kind of discouraged non-static effector? Do view "discouraged" warning deprecated, remove support in versions time? leaving support in necessary for compatibility</technical_language>

Target:
protected static Map<String,Effector<?>> findEffectors(Class<? extends Entity> clazz, Entity optionalEntity) { try { Map<String,Effector<?>> result = Maps.newLinkedHashMap(); Map<String,Field> sources = Maps.newLinkedHashMap(); for (Field f : clazz.getFields()) { if (Effector.class.isAssignableFrom(f.getType())) { if (!Modifier.isStatic(f.getModifiers())) { LOG.warn("Discouraged/deprecated use of non-static effector "+f+" defined in " + (optionalEntity!=null ? optionalEntity : clazz)); if (optionalEntity==null) continue; } Effector<?> eff = (Effector<?>) f.get(optionalEntity); Effector<?> overwritten = result.put(eff.getName(), eff); Field source = sources.put(eff.getName(), f); if (overwritten!=null && overwritten != eff) LOG.warn("multiple definitions for effector on {}; preferring from to from {}", new Object[] { eff.getName(), optionalEntity!=null ? optionalEntity : clazz, eff, f, overwritten, source}); } } return result; } catch (IllegalAccessException e) { throw Throwables.propagate(e); } }
Source:
<code>public Map<String,List<Map<String,String>>> getTserverRecovery() { <START> <END> Map<String,List<Map<String,String>>> jsonObj = new HashMap<String,List<Map<String,String>>>(); List<Map<String,String>> recoveryList = new ArrayList<>(); Map<String,String> recoveryObj = new HashMap<String,String>(); MasterMonitorInfo mmi = Monitor.getMmi(); if (null == mmi) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } for (TabletServerStatus server : mmi.tServerInfo) { if (server.logSorts != null) { for (RecoveryStatus recovery : server.logSorts) { recoveryObj.put("server", AddressUtil.parseAddress(server.name, false).getHostText()); recoveryObj.put("log", recovery.name); recoveryObj.put("time", Long.toString(recovery.runtime)); recoveryObj.put("copySort", Double.toString(recovery.progress)); recoveryList.add(recoveryObj); } } } jsonObj.put("recoveryList", recoveryList); return jsonObj; }</code><technical_language>I assume this return a Map of Maps for front end? List Map</technical_language>

Target:
public TabletServersRecovery getTserverRecovery() { TabletServersRecovery recoveryList = new TabletServersRecovery(); MasterMonitorInfo mmi = Monitor.getMmi(); if (null == mmi) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } for (TabletServerStatus server : mmi.tServerInfo) { if (server.logSorts != null) { for (RecoveryStatus recovery : server.logSorts) { String serv = AddressUtil.parseAddress(server.name, false).getHostText(); String log = recovery.name; int time = recovery.runtime; double copySort = recovery.progress; recoveryList.addRecovery(new TabletServerRecoveryInformation(serv, log, time, copySort)); } } } return recoveryList; }
Source:
<code>public List<byte[]> handle(final ResultSet rs) throws SQLException { if (!rs.next()) { return Collections.emptyList(); } <START> final ArrayList<byte[]> data = new ArrayList<>(); <END> do { final byte[] bytes = rs.getBytes(1); data.add(bytes); } while (rs.next()); return data; }</code><technical_language>List<byte[]></technical_language>

Target:
public List<byte[]> handle(final ResultSet rs) throws SQLException { if (!rs.next()) { return Collections.emptyList(); } final List<byte[]> data = new ArrayList<>(); do { final byte[] bytes = rs.getBytes(1); data.add(bytes); } while (rs.next()); return data; }
Source:
<code>public String BuildJSON() { if (swagger != null) { updateHostAndBasePath(); } else { synchronized (this) { <START> log.info("Initiating Swagger specification creation"); <END> toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } } return createJSON(); }</code><technical_language>Wrapping else body in a new method cleaner</technical_language>

Target:
private void BuildJSON() { synchronized (this) { log.info("Initiating Swagger specification creation"); toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } }
Source:
<code>public void send(final Message<?> message) throws Exception { if (message.getHeaders().containsKey("topic")) { final ProducerConfiguration<K, V> producerConfiguration = getTopicConfiguration(message .getHeaders().get("topic", String.class)); if (producerConfiguration != null) { producerConfiguration.send(message); } } else if (producerConfigurations.size() == 1) { producerConfigurations.get( producerConfigurations.keySet().iterator().next()).send( <START> message); <END> } }</code><technical_language>is need else IllegalStateException, topic header is more 1 producerConfigurations</technical_language>

Target:
public void send(final Message<?> message) throws Exception { if (message.getHeaders().containsKey("topic")) { final ProducerConfiguration<K, V> producerConfiguration = getTopicConfiguration(message .getHeaders().get("topic", String.class)); if (producerConfiguration != null) { producerConfiguration.send(message); } } else if (producerConfigurations.size() == 1) { producerConfigurations.get(producerConfigurations.keySet().iterator().next()).send(message); } else { throw new IllegalStateException("Could not send messages as there are multiple producer configurations" + "with no topic information found from the message header."); } }
Source:
<code>public long enqueue(ByteBufferMessageSet messages, long fetchOffset) throws InterruptedException { long size = messages.getValidSize(); if (size > 0) { <START> final long oldOffset = fetchedOffset.get(); <END> chunkQueue.put(new FetchedDataChunk(messages, this, fetchOffset)); long newOffset = fetchedOffset.addAndGet(size); logger.debug(format("updated fetchset (origin+size=newOffset) => %d + %d = %d", oldOffset, size, newOffset)); } return size; }</code><technical_language>final</technical_language>

Target:
public long enqueue(ByteBufferMessageSet messages, long fetchOffset) throws InterruptedException { long size = messages.getValidSize(); if (size > 0) { long oldOffset = fetchedOffset.get(); chunkQueue.put(new FetchedDataChunk(messages, this, fetchOffset)); long newOffset = fetchedOffset.addAndGet(size); logger.debug("updated fetchset (origin+size=newOffset) => " + oldOffset + " + " + size + " = " + newOffset); } return size; }
Source:
<code>protected void doSetUp() throws Exception { super.doSetUp(); BackPressureGeneratorProcessingStrategy strategy = new BackPressureGeneratorProcessingStrategy(); flow = createAndRegisterFlow(muleContext, APPLE_FLOW, componentLocator, (ctx, n) -> strategy); async = createAsyncDelegateMessageProcessor(target, flow); <START> async.setSchedulerService(new FixingBackPressureSchedulerService(strategy)); <END> async.start(); }</code><technical_language>if override createAsyncDelegateMessageProcessor move this line 39 there, move this doSetUp superclass</technical_language>

Target:
protected void doSetUp() throws Exception { super.doSetUp(); BackPressureGeneratorProcessingStrategy strategy = new BackPressureGeneratorProcessingStrategy(); flow = createAndRegisterFlow(muleContext, APPLE_FLOW, componentLocator, (ctx, n) -> strategy); async = createAsyncDelegateMessageProcessor(target, flow); service = new FixingBackPressureSchedulerService(strategy); async.setSchedulerService(service); async.initialise(); async.start(); }
Source:
<code>public FormValidation doCheckEncoding(@QueryParameter String encoding) { if (!StringUtils.isBlank(encoding)) { try { Charset.forName(encoding.trim()); <START> } catch(Exception e) { <END> return FormValidation.error(e, "Unsupported Encoding"); } if(!ParameterizedTriggerUtils.isSupportNonAsciiPropertiesFile()) { return FormValidation.warning("Non-ascii properties files are supported only since Java 1.6."); } } return FormValidation.ok(); }</code><technical_language>Catching a generic Exception is poor practice</technical_language>

Target:
public FormValidation doCheckEncoding(@QueryParameter String encoding) { if (!StringUtils.isBlank(encoding)) { try { Charset.forName(encoding.trim()); } catch(UnsupportedCharsetException e) { return FormValidation.error("Unsupported Encoding"); } catch(IllegalCharsetNameException e) { return FormValidation.error("Bad Encoding Name"); } if(!ParameterizedTriggerUtils.isSupportNonAsciiPropertiesFile()) { return FormValidation.warning("Non-ascii properties files are supported only since Java 1.6."); } } return FormValidation.ok(); }
Source:
<code>public static void setNotificationOpenedHandler(NotificationOpenedHandler callback) { notificationOpenedHandler = callback; <START> if (appContext != null) <END> setAppContext(appContext); }</code><technical_language>This a hack setting if exists. process list of unfired notifications if is init is done</technical_language>

Target:
public static void setNotificationOpenedHandler(NotificationOpenedHandler callback) { notificationOpenedHandler = callback; if (initDone && notificationOpenedHandler != null) fireCallbackForOpenedNotifications(); }
Source:
<code>private Resource locateResource() throws IOException , NullPointerException { Resource[] resources = this.context.getResources(this.ldif); <START> if (null == resources || 0 == resources.length) { <END> throw new IllegalArgumentException("requested resource is not found"); } return Arrays.stream(resources).filter(resource -> !StringUtils.isEmpty(resource.getFilename()) && resource.isFile() && resource.exists() && resource.isReadable() ) .findFirst() .orElseThrow(()->new IllegalArgumentException("Unable to load LDIF :"+this.ldif)); }</code><technical_language>do need throw exception in this case, instead simply for LDIF. reason is default set ldif = "classpath*:*.ldif". If a user create LDIF in this case is okay, configure it</technical_language>

Target:
private Resource locateResource() throws IOException, NullPointerException { Resource[] resources = this.context.getResources(this.ldif); if (0 == resources.length) { throw new IllegalArgumentException("requested resource is not found"); } for (Resource resource : resources) { if (!isEmpty(resource.getFilename()) && resource.isFile() && resource.exists() && resource.isReadable()) { return resource; } } throw new IllegalArgumentException("Unable to load LDIF :" + this.ldif); }
Source:
<code>public void poll(long timeout) { final long start = time.milliseconds(); long now = start; long remaining; do { if (coordinatorUnknown()) { log.debug("Broker coordinator is marked unknown. Attempting discovery with a timeout of {}ms", coordinatorDiscoveryTimeoutMs); if (ensureCoordinatorReady(time.timer(coordinatorDiscoveryTimeoutMs))) { log.debug("Broker coordinator is ready"); } else { <START> log.debug("Can not connect to broker coordinator"); <END> if (assignmentSnapshot != null && !assignmentSnapshot.failed()) { log.info("Broker coordinator was unreachable for {}ms. Revoking previous assignment to " + "avoid running tasks while not being a member the group", coordinatorDiscoveryTimeoutMs, assignmentSnapshot); listener.onRevoked(assignmentSnapshot.leader(), assignmentSnapshot.connectors(), assignmentSnapshot.tasks()); assignmentSnapshot.connectors().clear(); assignmentSnapshot.tasks().clear(); assignmentSnapshot.revokedConnectors().clear(); assignmentSnapshot.revokedTasks().clear(); } } now = time.milliseconds(); } if (rejoinNeededOrPending()) { ensureActiveGroup(); now = time.milliseconds(); } pollHeartbeat(now); long elapsed = now - start; remaining = timeout - elapsed; long pollTimeout = Math.min(Math.max(0, remaining), timeToNextHeartbeat(now)); client.poll(time.timer(pollTimeout)); now = time.milliseconds(); elapsed = now - start; remaining = timeout - elapsed; } while (remaining > 0); }</code><technical_language>is significance of this check? If a worker failed task running task, snapshot reset? running task stopped</technical_language>

Target:
public void poll(long timeout) { final long start = time.milliseconds(); long now = start; long remaining; do { if (coordinatorUnknown()) { log.debug("Broker coordinator is marked unknown. Attempting discovery with a timeout of {}ms", coordinatorDiscoveryTimeoutMs); if (ensureCoordinatorReady(time.timer(coordinatorDiscoveryTimeoutMs))) { log.debug("Broker coordinator is ready"); } else { log.debug("Can not connect to broker coordinator"); final ExtendedAssignment localAssignmentSnapshot = assignmentSnapshot; if (localAssignmentSnapshot != null && !localAssignmentSnapshot.failed()) { log.info("Broker coordinator was unreachable for {}ms. Revoking previous assignment to " + "avoid running tasks while not being a member the group", coordinatorDiscoveryTimeoutMs, localAssignmentSnapshot); listener.onRevoked(localAssignmentSnapshot.leader(), localAssignmentSnapshot.connectors(), localAssignmentSnapshot.tasks()); assignmentSnapshot = null; } } now = time.milliseconds(); } if (rejoinNeededOrPending()) { ensureActiveGroup(); now = time.milliseconds(); } pollHeartbeat(now); long elapsed = now - start; remaining = timeout - elapsed; long pollTimeout = Math.min(Math.max(0, remaining), timeToNextHeartbeat(now)); client.poll(time.timer(pollTimeout)); now = time.milliseconds(); elapsed = now - start; remaining = timeout - elapsed; } while (remaining > 0); }
Source:
<code>public void verify() { Preconditions.checkNotNull(schema.getDataSchema().getDataSource(), "dataSource"); Preconditions.checkNotNull(schema.getDataSchema().getParser(), "inputRowParser"); Preconditions.checkNotNull(schema.getDataSchema().getParser().getParseSpec(), "parseSpec"); <START> Preconditions.checkNotNull(schema.getDataSchema().getNonNullTimestampSpec(), "timestampSpec"); <END> Preconditions.checkNotNull(schema.getDataSchema().getGranularitySpec(), "granularitySpec"); Preconditions.checkNotNull(pathSpec, "inputSpec"); Preconditions.checkNotNull(schema.getTuningConfig().getWorkingPath(), "workingPath"); Preconditions.checkNotNull(schema.getIOConfig().getSegmentOutputPath(), "segmentOutputPath"); Preconditions.checkNotNull(schema.getTuningConfig().getVersion(), "version"); }</code><technical_language>Checking this for null redundant</technical_language>

Target:
public void verify() { Preconditions.checkNotNull(schema.getDataSchema().getDataSource(), "dataSource"); Preconditions.checkNotNull(schema.getDataSchema().getParser(), "inputRowParser"); Preconditions.checkNotNull(schema.getDataSchema().getParser().getParseSpec(), "parseSpec"); Preconditions.checkNotNull(schema.getDataSchema().getGranularitySpec(), "granularitySpec"); Preconditions.checkNotNull(pathSpec, "inputSpec"); Preconditions.checkNotNull(schema.getTuningConfig().getWorkingPath(), "workingPath"); Preconditions.checkNotNull(schema.getIOConfig().getSegmentOutputPath(), "segmentOutputPath"); Preconditions.checkNotNull(schema.getTuningConfig().getVersion(), "version"); }
Source:
<code>private void emitConsumerRecord(ConsumerRecord<K, V> record) { Map<String, List<Object>> tupleByStream = consumerRecordTransformer.transform(record); if (tupleByStream.isEmpty() && topologyReliabilityMode == Config.TopologyReliabilityMode.ATLEAST_ONCE) { ack(new ConsumerRecordMessageId(new TopicPartition(record.topic(), record.partition()), record.offset())); } tupleByStream.forEach((s, objects) -> { <START> if (topologyReliabilityMode != Config.TopologyReliabilityMode.ATLEAST_ONCE) { <END> collector.emit(s, objects); if (topologyReliabilityMode == Config.TopologyReliabilityMode.EFFECTIVELY_ONCE) { state.put(new TopicPartition(record.topic(), record.partition()), record.offset()); } } else { ConsumerRecordMessageId consumerRecordMessageId = new ConsumerRecordMessageId(new TopicPartition(record.topic(), record.partition()), record.offset()); collector.emit(s, objects, consumerRecordMessageId); } }); }</code><technical_language>I feel "switch(mode)" more readable</technical_language>

Target:
private void emitConsumerRecord(ConsumerRecord<K, V> record) { Map<String, List<Object>> tupleByStream = consumerRecordTransformer.transform(record); if (tupleByStream.isEmpty() && topologyReliabilityMode == Config.TopologyReliabilityMode.ATLEAST_ONCE) { ack(new ConsumerRecordMessageId(new TopicPartition(record.topic(), record.partition()), record.offset())); return; } tupleByStream.forEach((s, objects) -> { switch (topologyReliabilityMode) { case ATMOST_ONCE: collector.emit(s, objects); break; case ATLEAST_ONCE: ConsumerRecordMessageId consumerRecordMessageId = new ConsumerRecordMessageId(new TopicPartition(record.topic(), record.partition()), record.offset()); collector.emit(s, objects, consumerRecordMessageId); break; case EFFECTIVELY_ONCE: collector.emit(s, objects); state.put(new TopicPartition(record.topic(), record.partition()), record.offset()); break; default: LOG.warn("unsupported reliability mode {}", topologyReliabilityMode); } }); }
Source:
<code>public void testOutstandingSplitSize() { DataSize maxOutstandingSplitsSize = new DataSize(1, MEGABYTE); HiveSplitSource hiveSplitSource = HiveSplitSource.allAtOnce( SESSION, "database", "table", TupleDomain.all(), 10, 10000, maxOutstandingSplitsSize, new TestingHiveSplitLoader(), Executors.newFixedThreadPool(5), new CounterStat()); <START> InternalHiveSplit testSplit = new InternalHiveSplit( <END> "partition-name", "path", 0, 100, 100, new Properties(), ImmutableList.of(new HivePartitionKey("pk_col", "pk_value")), ImmutableList.of(new InternalHiveBlock(0, 100, ImmutableList.of(HostAddress.fromString("localhost")))), OptionalInt.empty(), true, false, ImmutableMap.of(), Optional.empty(), false); int testSplitSizeInBytes = new TestSplit(0).getEstimatedSizeInBytes(); int maxSplitCount = toIntExact(maxOutstandingSplitsSize.toBytes()) / testSplitSizeInBytes; for (int i = 0; i < maxSplitCount; i++) { hiveSplitSource.addToQueue(new TestSplit(i)); assertEquals(hiveSplitSource.getBufferedInternalSplitCount(), i + 1); } assertEquals(getSplits(hiveSplitSource, maxSplitCount).size(), maxSplitCount); for (int i = 0; i < maxSplitCount; i++) { hiveSplitSource.addToQueue(new TestSplit(i)); assertEquals(hiveSplitSource.getBufferedInternalSplitCount(), i + 1); } try { hiveSplitSource.addToQueue(new TestSplit(0)); fail("expect failure"); } catch (PrestoException e) { assertContains(e.getMessage(), "Split buffering for database.table exceeded memory limit"); } }</code><technical_language>unused</technical_language>

Target:
public void testOutstandingSplitSize() { DataSize maxOutstandingSplitsSize = new DataSize(1, MEGABYTE); HiveSplitSource hiveSplitSource = HiveSplitSource.allAtOnce( SESSION, "database", "table", TupleDomain.all(), 10, 10000, maxOutstandingSplitsSize, new TestingHiveSplitLoader(), Executors.newFixedThreadPool(5), new CounterStat()); int testSplitSizeInBytes = new TestSplit(0).getEstimatedSizeInBytes(); int maxSplitCount = toIntExact(maxOutstandingSplitsSize.toBytes()) / testSplitSizeInBytes; for (int i = 0; i < maxSplitCount; i++) { hiveSplitSource.addToQueue(new TestSplit(i)); assertEquals(hiveSplitSource.getBufferedInternalSplitCount(), i + 1); } assertEquals(getSplits(hiveSplitSource, maxSplitCount).size(), maxSplitCount); for (int i = 0; i < maxSplitCount; i++) { hiveSplitSource.addToQueue(new TestSplit(i)); assertEquals(hiveSplitSource.getBufferedInternalSplitCount(), i + 1); } try { hiveSplitSource.addToQueue(new TestSplit(0)); fail("expect failure"); } catch (PrestoException e) { assertContains(e.getMessage(), "Split buffering for database.table exceeded memory limit"); } }
Source:
<code><START> public void testOne() throws Exception { <END> final File fileToProcess = new File(getPath( "SuppressionXpathRegressionAnnotationUseStyleOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AnnotationUseStyleCheck.class); moduleConfig.addAttribute("closingParens", "ALWAYS"); moduleConfig.addAttribute("elementStyle", "ignore"); moduleConfig.addAttribute("trailingArrayComma", "ignore"); final String[] expectedViolation = { "3:1: " + getCheckMessage(AnnotationUseStyleCheck.class, AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_PARENS_MISSING), }; final List<String> expectedXpathQueries = Arrays.asList( "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnnotationUseStyleOne']]", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnnotationUseStyleOne']]" + "/MODIFIERS", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnnotationUseStyleOne']]" + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnnotationUseStyleOne']]" + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]/AT" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }</code><technical_language>I see, tests 1. Default config 2. compact style 3. expanded style 4. closingParens = 5. trailingComma =</technical_language>

Target:
public void testOne() throws Exception { final File fileToProcess = new File(getPath( "SuppressionXpathRegressionAnnotationUseStyleOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AnnotationUseStyleCheck.class); final String[] expectedViolation = { "4:1: " + getCheckMessage(AnnotationUseStyleCheck.class, AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_INCORRECT_STYLE, "COMPACT_NO_ARRAY"), }; final List<String> expectedXpathQueries = Arrays.asList( "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnnotationUseStyleOne']]" + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]", "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnnotationUseStyleOne']]" + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]/AT" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_remove_all_history: new MaterialDialog.Builder(this) .title(R.string.title_clear_history_dialog) .content(R.string.text_clear_history_dialog) .onPositive((dialog, which) -> { Utils.getAppDaoSession(getParent()).getHistoryProductDao().deleteAll();; <START> productItems.clear(); <END> recyclerHistoryScanView.getAdapter().notifyDataSetChanged(); }) .positiveText(R.string.txtYes) .negativeText(R.string.txtNo) .show(); return true; case R.id.action_export_all_history: if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { new MaterialDialog.Builder(this) .title(R.string.action_about) .content(R.string.permision_write_external_storage) .neutralText(R.string.txtOk) .show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Utils.MY_PERMISSIONS_REQUEST_STORAGE); } } else { exportCSV(); } return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>extract in a class field Utils.getAppDaoSession(getParent()).getHistoryProductDao() historyProductDao</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_remove_all_history: new MaterialDialog.Builder(this) .title(R.string.title_clear_history_dialog) .content(R.string.text_clear_history_dialog) .onPositive((dialog, which) -> { mHistoryProductDao.deleteAll();; productItems.clear(); recyclerHistoryScanView.getAdapter().notifyDataSetChanged(); }) .positiveText(R.string.txtYes) .negativeText(R.string.txtNo) .show(); return true; case R.id.action_export_all_history: if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { new MaterialDialog.Builder(this) .title(R.string.action_about) .content(R.string.permision_write_external_storage) .neutralText(R.string.txtOk) .show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Utils.MY_PERMISSIONS_REQUEST_STORAGE); } } else { exportCSV(); } return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public void edit(final GlusterVolumeSnapshotModel object) { driver.edit(object); forceWarningLabel.setVisible(object.getForceCreate().getEntity()); <START> object.getForceCreate().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { <END> @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { forceWarningLabel.setVisible(object.getForceCreate().getEntity()); } }); }</code><technical_language>View.edit(model) add new listeners model object. This responsibility of presenter - for example, in GlusterVolumeSnapshotCreatePopupPresenterWidget: @Override public void init(final GlusterVolumeSnapshotModel model) { super.init(model); model.getForceCreate().getEntityChangedEvent().addListener(...); } View.edit() is responsible for populating UI model data potentially called multiple times. Model listener registration belong here, in AbstractModelBoundPopupPresenterWidget.init(model) method override</technical_language>

Target:
public void edit(final GlusterVolumeSnapshotModel object) { driver.edit(object); forceWarningLabel.setVisible(object.getForceCreate().getEntity()); }
Source:
<code><START> public String[] getAuthorizedGroups() { <END> return new String[]{"administrators"}; }</code><technical_language>this method final. is missing @Override annotation AFAICT</technical_language>

Target:
protected final String[] getAuthorizedGroups() { return new String[]{"administrators"}; }
Source:
<code>public static void setUpPerTestClass() throws Exception { System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager"); System.setProperty("java.util.logging.config.file", TestFileHandlerNonRotatable.class .getResource("logging-non-rotatable.properties") .getFile()); <START> } <END></code><technical_language>This is working system I **space** in path: java.io.FileNotFoundException: /.../tc9.0.x%20(trunk)/.../org/apache/juli/logging-non-rotatable.properties (No file directory) java.io.FileInputStream.open0(Native Method) java.io.FileInputStream.open(FileInputStream.java:195) java.io.FileInputStream.<init>(FileInputStream.java:138) java.io.FileInputStream.<init>(FileInputStream.java:93) org.apache.juli.ClassLoaderLogManager.readConfiguration(ClassLoaderLogManager.java:469) org.apache.juli.ClassLoaderLogManager.readConfiguration(ClassLoaderLogManager.java:309)</technical_language>

Target:
public static void setUpPerTestClass() throws Exception { System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager"); String configLoggingPath = TestFileHandlerNonRotatable.class .getResource("logging-non-rotatable.properties") .getFile(); System.setProperty("java.util.logging.config.file", URLDecoder.decode(configLoggingPath, java.nio.charset.StandardCharsets.UTF_8.toString())); }
Source:
<code>public CloseUnrelatedProjectsAction(IShellProvider provider){ super(provider, IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text); <START> TEXT_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text; <END> TOOLTIP_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_toolTip; TEXT_PLURAL_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text_plural; TOOLTIP_PLURAL_STRING = IDEWorkbenchMessages.CloseUnrelatedProjectsAction_toolTip_plural; initAction(); }</code><technical_language>Ideall in super constructor</technical_language>

Target:
public CloseUnrelatedProjectsAction(IShellProvider provider){ super(provider, IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text, IDEWorkbenchMessages.CloseUnrelatedProjectsAction_toolTip, IDEWorkbenchMessages.CloseUnrelatedProjectsAction_text_plural, IDEWorkbenchMessages.CloseUnrelatedProjectsAction_toolTip_plural); initAction(); }
Source:
<code>public MutationWriter(int numSendThreads) { serversMutations = new HashMap<String,TabletServerMutations<Mutation>>(); queued = new HashSet<String>(); sendThreadPool = new SimpleThreadPool(numSendThreads, this.getClass().getName()); locators = new HashMap<String,TabletLocator>(); binTimer.schedule(new TimerTask() { @Override public void run() { MutationSet m = queue.poll(); while (null != m) { try { addMutations(m); } catch (Exception e) { updateUnknownErrors("Error processing mutation set", e); } m = queue.poll(); } } <START> }, 0, 500); <END> }</code><technical_language>this 500ms check for queue bin? Whats rational for this</technical_language>

Target:
public MutationWriter(int numSendThreads) { serversMutations = new HashMap<String,TabletServerMutations<Mutation>>(); queued = new HashSet<String>(); sendThreadPool = new SimpleThreadPool(numSendThreads, this.getClass().getName()); locators = new HashMap<String,TabletLocator>(); binningThreadPool = new SimpleThreadPool(1, "BinMutations", new SynchronousQueue<Runnable>()); binningThreadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); }
Source:
<code>public void colorSettingsChanged(StateItem[] stateItems) { <START> updateColorMap(stateItems); <END> }</code><technical_language>method moved in (and setTimeGraphProvider call public method). save method</technical_language>

Target:
public void colorSettingsChanged(StateItem[] stateItems) { if (stateItems != null) { fEventColorMap = new Color[stateItems.length]; for (int i = 0; i < stateItems.length; i++) { fEventColorMap[i] = fResourceManager.createColor(stateItems[i].getStateColor()); } } else { fEventColorMap = new Color[] { }; } }
Source:
<code>String extractPatientInfo(List<SlotType1> documentSlots, String patientInfoName) { String slotValue = null; for (SlotType1 slot : documentSlots) { if (slot != null && slot.getName().equals(DocRepoConstants.XDS_SOURCE_PATIENT_INFO_SLOT) <START> && slot.getValueList().getValue() != null) { <END> Iterator<String> iter = slot.getValueList().getValue().iterator(); while (iter.hasNext()) { String nextSlotValue = iter.next(); if (nextSlotValue.startsWith(patientInfoName)) { slotValue = nextSlotValue.substring(patientInfoName.length() + 1); LOG.debug("{} extractionValue: {}", patientInfoName, slotValue); } } } } return slotValue; }</code><technical_language>if valuelist is empty? check for that</technical_language>

Target:
String extractPatientInfo(List<SlotType1> documentSlots, String patientInfoName) { String slotValue = null; for (SlotType1 slot : documentSlots) { if (slot != null && slot.getName().equals(DocRepoConstants.XDS_SOURCE_PATIENT_INFO_SLOT) && slot.getValueList() != null && slot.getValueList().getValue() != null) { Iterator<String> iter = slot.getValueList().getValue().iterator(); while (iter.hasNext()) { String nextSlotValue = iter.next(); if (nextSlotValue.startsWith(patientInfoName)) { slotValue = nextSlotValue.substring(patientInfoName.length() + 1); LOG.debug("{} extractionValue: {}", patientInfoName, slotValue); } } } } return slotValue; }
Source:
<code>public <T> T getResource(String resourcePath, Class<? extends T> resourceClass) { return <START> isJarResource(resourceClass) ? (T) jarFile.getJarEntry(resourcePath) : null; <END> }</code><technical_language>IMO ternary operator is useful expression fits in single line, is splited lines is readable. Personally simple if/else</technical_language>

Target:
public <T> Optional<T> getResource(String resourcePath, Class<? extends T> resourceClass) { if (isJarResource(resourceClass)) { return (Optional<T>) Optional.fromNullable(jarFile .getJarEntry(resourcePath)); } else { return Optional.absent(); } }
Source:
<code>private void push() { if (DELAY_SECONDS < 0) return; Future<?> ns = nextSave; if (ns != null && !(ns.isDone() || ns.isCancelled())) return; <START> nextSave = Timer.get().schedule(this, DELAY_SECONDS, TimeUnit.SECONDS); <END> }</code><technical_language>thread-unsafe due a race condition: a thread fetch field, empty, schedule a *second* task while is scheduling a Timer task writes field. synchronize darn thing. synchronization is for. Volatile reserved for booleans, ints, more safely -- 90% of time need AtomicX compare & set / increment operations compound tasks, a read a write</technical_language>

Target:
private void push() { if (DELAY_SECONDS < 0) return; synchronized (lock) { if (nextSave != null && !(nextSave.isDone() || nextSave.isCancelled())) return; nextSave = Timer.get().schedule(this, DELAY_SECONDS, TimeUnit.SECONDS); } }
Source:
<code>public void changeDiscoveryMode(){ <START> validationProvider = new InterceptorValidationProviderCDI11(); <END> prepareBeanXml("all", true); }</code><technical_language>This validation provider JSR-346 string in problem's message</technical_language>

Target:
public void changeDiscoveryMode(){ validationProvider = new InterceptorValidationProvider("JSR-365"); prepareBeanXml("all", true); }
Source:
<code>public String getValueAt(int column) { String value = getColumns().get(column); if <START> (value.equals(StringConstants.UNICODE_NULL)) { <END> return null; } return value; }</code><technical_language>Switch equals check (a.equals(b) --> b.equals(a)) is null-safe potentially faster</technical_language>

Target:
public String getValueAt(int column) { String value = getColumns().get(column); if (StringConstants.UNICODE_NULL.equals(value)) { return null; } return value; }
Source:
<code>public void addLogo(View view) { Intent i = new Intent(this, LogoActivity.class); i.putExtra("photoByteArray", byteArray); i.putExtra("companyTag", companyTag); <START> i.putExtra("filePath", fileUri.getPath()); <END> i.putExtra("accessToken", getIntent().getExtras().getString("accessToken")); startActivity(i); }</code><technical_language>start editing picture, do need pass original? reason need is if offer option reset changes, right passing byte stream track of date edited version</technical_language>

Target:
public void addLogo(View view) { Intent i = new Intent(this, LogoActivity.class); i.putExtra("photoByteArray", byteArray); i.putExtra("filePath", fileUri.getPath()); startActivity(i); }
Source:
<code>public List<String> getSelectNestedColPathsFromChildren( SelectOperator op, List<String> paths) { List<String> groups = new ArrayList<>(); SelectDesc conf = op.getConf(); if (paths != null && conf.isSelStarNoCompute()) { groups.addAll(paths); return groups; } List<ExprNodeDesc> selectDescs = conf.getColList(); List<String> outputColumnNames = conf.getOutputColumnNames(); for (int i = 0; i < outputColumnNames.size(); i++) { if (paths == null || paths.contains(outputColumnNames.get(i))) { ExprNodeDesc desc = selectDescs.get(i); List<String> gp = getNestedColPathByDesc(desc); <START> if (!gp.isEmpty()) { <END> groups.addAll(gp); } } } return groups; }</code><technical_language>need check empty</technical_language>

Target:
public List<String> getSelectNestedColPathsFromChildren( SelectOperator op, List<String> paths) { List<String> groups = new ArrayList<>(); SelectDesc conf = op.getConf(); if (paths != null && conf.isSelStarNoCompute()) { groups.addAll(paths); return groups; } List<ExprNodeDesc> selectDescs = conf.getColList(); List<String> outputColumnNames = conf.getOutputColumnNames(); for (int i = 0; i < outputColumnNames.size(); i++) { if (paths == null || paths.contains(outputColumnNames.get(i))) { ExprNodeDesc desc = selectDescs.get(i); List<String> gp = getNestedColPathByDesc(desc); groups.addAll(gp); } } return groups; }
Source:
<code>public byte[] apply(RuntimeEnvironment env) throws IOException { <START> if (hasTag("reindex")) { <END> env.applyConfig(this, true); } else { env.applyConfig(this, false); } return null; }</code><technical_language>Possibly shorter write java env.applyConfig(this, hasTag("reindex")); this is ok</technical_language>

Target:
public byte[] apply(RuntimeEnvironment env) throws IOException { env.applyConfig(this, hasTag("reindex")); return null; }
Source:
<code>public ResultSet<ChangeData> read() throws OrmException { ChangeDataSource source = source(); if (source == null) { throw new OrmException("No ChangeDataSource: " + this); } ArrayList<ChangeData> r = new ArrayList<ChangeData>(); ChangeData last = null; boolean skipped = false; for (ChangeData cd : prefetchData(source)) { if (match(cd)) { r.add(cd); } else { skipped = true; } last = cd; } if (skipped && last != null && source instanceof Paginated) { Paginated p = (Paginated) source; while (skipped && r.size() < p.limit()) { ChangeData lastBeforeRestart = last; skipped = false; last = null; <START> for (ChangeData cd : p.restart(lastBeforeRestart)) { <END> if (match(cd)) { r.add(cd); } else { skipped = true; } last = cd; } } } return new ListResultSet<ChangeData>(r); }</code><technical_language>This prefetch</technical_language>

Target:
public ResultSet<ChangeData> read() throws OrmException { ChangeDataSource source = source(); if (source == null) { throw new OrmException("No ChangeDataSource: " + this); } ArrayList<ChangeData> r = new ArrayList<ChangeData>(); ChangeData last = null; boolean skipped = false; for (ChangeData cd : prefetchData(source.read())) { if (match(cd)) { r.add(cd); } else { skipped = true; } last = cd; } if (skipped && last != null && source instanceof Paginated) { Paginated p = (Paginated) source; while (skipped && r.size() < p.limit()) { ChangeData lastBeforeRestart = last; skipped = false; last = null; for (ChangeData cd : prefetchData(p.restart(lastBeforeRestart))) { if (match(cd)) { r.add(cd); } else { skipped = true; } last = cd; } } } return new ListResultSet<ChangeData>(r); }
Source:
<code><START> public Resource<Task> getTaskById(@PathVariable String taskId) { <END> return resourceAssembler.toResource(dao.findById(taskId).get()); }</code><technical_language>@erdemedeiros stick tasks authenticated users see. is default findAllByWebQuerydsl() do. add check in getTaskById() method user making request is allowed task. sense</technical_language>

Target:
public Resource<Task> getTaskById(@PathVariable String taskId) { return resourceAssembler.toResource(entityFinder.findById(dao, taskId, "Unable to find task: " + taskId)); }
Source:
<code>public Server createHttpServerInstance(int port) throws IOException { Server server = getServerWithContext(port); HttpConfiguration http = new HttpConfiguration(); http.addCustomizer(new SecureRequestCustomizer()); http.setSecurePort(port); http.setSecureScheme("https"); ServerConnector connector = new ServerConnector(server); connector.addConnectionFactory(new HttpConnectionFactory(http)); <START> connector.setPort(80); <END> HttpConfiguration https = new HttpConfiguration(); https.addCustomizer(new SecureRequestCustomizer()); ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https)); sslConnector.setPort(port); server.setConnectors(new Connector[]{connector, sslConnector}); return server; }</code><technical_language>hardcoded value. move this a constant get some other way</technical_language>

Target:
public Server createHttpServerInstance(int port) throws IOException { Server server = new Server(port); HttpConfiguration http = new HttpConfiguration(); http.addCustomizer(new SecureRequestCustomizer()); http.setSecurePort(port); http.setSecureScheme("https"); ServerConnector connector = new ServerConnector(server); connector.addConnectionFactory(new HttpConnectionFactory(http)); connector.setPort(httpPort); HttpConfiguration https = new HttpConfiguration(); https.addCustomizer(new SecureRequestCustomizer()); ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https)); sslConnector.setPort(port); server.setConnectors(new Connector[]{connector, sslConnector}); return server; }
Source:
<code>public TcpReplicationHandler(WriteServerConfig config, SelfInfoResolver selfIdentityService, SourcedEurekaRegistry registry, WriteServerMetricFactory metricFactory) { this.config = config; this.selfIdentityService = selfIdentityService; this.registry = registry; this.metricFactory = metricFactory; this.channelSubject = BehaviorSubject.create(); <START> channelSubject <END> .scan(new Func2<ReceiverReplicationChannel, ReceiverReplicationChannel, ReceiverReplicationChannel>() { @Override public ReceiverReplicationChannel call(ReceiverReplicationChannel prev, ReceiverReplicationChannel curr) { setUpEviction(prev, curr).subscribe(new Subscriber<Long>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Long aLong) { logger.info("Evicted instances in one round of eviction due to a new receiverReplicationChannel creation", aLong); } }); return curr; } }) .subscribe(new NoOpSubscriber<ReceiverReplicationChannel>()); }</code><technical_language>TCP replication handler is shared replication connections. get new replication connections first, random failures on. this scan process resolves this</technical_language>

Target:
public TcpReplicationHandler(WriteServerConfig config, SelfInfoResolver selfIdentityService, SourcedEurekaRegistry registry, WriteServerMetricFactory metricFactory) { this.config = config; this.selfIdentityService = selfIdentityService; this.registry = registry; this.metricFactory = metricFactory; }
Source:
<code>public void aggregate() { if (foundValue == null) { final Object object = valueSelector.getObject(); <START> if (object != null) { <END> foundValue = DimensionHandlerUtils.convertObjectToString(object); if (foundValue != null && foundValue.length() > maxStringBytes) { foundValue = foundValue.substring(0, maxStringBytes); } } } }</code><technical_language>I missed this earlier, this check necessary, DimensionHandlerUtils.convertObjectToString null check</technical_language>

Target:
public void aggregate() { if (foundValue == null) { final Object object = valueSelector.getObject(); foundValue = DimensionHandlerUtils.convertObjectToString(object); if (foundValue != null && foundValue.length() > maxStringBytes) { foundValue = foundValue.substring(0, maxStringBytes); } } }
Source:
<code>private boolean hardDelete() { if (indexes.size() > 0) { final Timer.Context context = metrics.hardDeleteTime.time(); try { FindInfo info = findDeletedEntriesSince(startToken, scanSizeInBytes, <START> SystemTime.getInstance().milliseconds() / 1000 - config.storeDeletedMessageRetentionDays * 24 * 60 * 60); <END> endToken = info.getFindToken(); if (!endToken.equals(startToken)) { persistCleanupToken(); if (!info.getMessageEntries().isEmpty()) { performHardDeletes(info.getMessageEntries()); } startToken = endToken; return true; } } catch (Exception e) { logger.error("Index : " + dataDir + " error while performing hard deletes ", e); } finally { context.stop(); } } return false; }</code><technical_language>this a constant calculated once. Also, in a name. Also, need mock instances of time. file a follow JIRA for this</technical_language>

Target:
private boolean hardDelete() { if (indexes.size() > 0) { final Timer.Context context = metrics.hardDeleteTime.time(); try { FindInfo info = findDeletedEntriesSince(startToken, scanSizeInBytes, SystemTime.getInstance().seconds() - messageRetentionSeconds); endToken = info.getFindToken(); if (!endToken.equals(startToken)) { persistCleanupToken(); if (!info.getMessageEntries().isEmpty()) { performHardDeletes(info.getMessageEntries()); } startToken = endToken; return true; } } catch (Exception e) { logger.error("Index : " + dataDir + " error while performing hard deletes ", e); } finally { context.stop(); } } return false; }
Source:
<code>public void onRemoval() { monitoring.get().unregister(provider.getId()); List<Network> networks = networkDao.getAllForCluster(provider.getId()); networks.stream() .filter(n -> !managementNetworkUtil.getDefaultManagementNetworkName().equals(n.getName())) .forEach(n -> deleteNetwork(n, provider.getId())); ClusterParametersBase parameters = new ClusterParametersBase(provider.getId()); parameters.setForce(true); backend.runInternalAction(ActionType.RemoveCluster, parameters); Optional<StoragePool> <START> kubevirtDc = <END> findKubevirtDataCenter(); Guid storagePoolId = kubevirtDc.get().getId(); List<Cluster> clusters = clusterDao.getAllForStoragePool(storagePoolId); if (clusters.isEmpty()) { StoragePoolParametersBase sp = new StoragePoolParametersBase(storagePoolId); backend.runInternalAction(ActionType.RemoveStoragePool, sp); } }</code><technical_language>I imagine a scenario in DC replaced this DC is returned empty (perhaps if DC accidentally renamed). verify kubevirtDc.isPresent() proceeding deletion</technical_language>

Target:
public void onRemoval() { monitoring.get().unregister(provider.getId()); List<Network> networks = networkDao.getAllForCluster(provider.getId()); networks.stream() .filter(n -> !managementNetworkUtil.getDefaultManagementNetworkName().equals(n.getName())) .forEach(n -> deleteNetwork(n, provider.getId())); ClusterParametersBase parameters = new ClusterParametersBase(provider.getId()); parameters.setForce(true); backend.runInternalAction(ActionType.RemoveCluster, parameters); Optional<StoragePool> kubevirtDc = findKubevirtDataCenter(); if (kubevirtDc.isPresent()) { Guid storagePoolId = kubevirtDc.get().getId(); List<Cluster> clusters = clusterDao.getAllForStoragePool(storagePoolId); if (clusters.isEmpty()) { StoragePoolParametersBase sp = new StoragePoolParametersBase(storagePoolId); backend.runInternalAction(ActionType.RemoveStoragePool, sp); } } }
Source:
<code>public void play(boolean tut, String shipName, boolean isNewGame) { if (isNewGame) { beforeNewGame(); <START> solGame = new SolGame(this, shipName, tut, isNewGame, commonDrawer); <END> } else { beforeLoadGame(); solGame = new SolGame(this, shipName, tut, isNewGame, commonDrawer); } inputManager.setScreen(this, solGame.getScreens().mainScreen); musicManager.playGameMusic(options); }</code><technical_language>this line out of if/else statement</technical_language>

Target:
public void play(boolean tut, String shipName, boolean isNewGame) { if (isNewGame) { beforeNewGame(); } else { beforeLoadGame(); } solGame = new SolGame(this, shipName, tut, isNewGame, commonDrawer); inputManager.setScreen(this, solGame.getScreens().mainScreen); musicManager.playGameMusic(options); }