auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testShowTablesLike() { <START> MaterializedResult result = computeActual("SHOW TABLES LIKE 'orde%'"); <END> assertEquals(result.getOnlyColumnAsSet(), ImmutableSet.of(ORDERS.getTableName())); }</code><technical_language>why</technical_language>

Target:
public void testShowTablesLike() { assertThat(computeActual("SHOW TABLES LIKE 'or%'").getOnlyColumnAsSet()) .contains("orders") .allMatch(tableName -> ((String) tableName).startsWith("or")); }
Source:
<code>public boolean validateOptions(Map<String,String> options) { String o = options.get(NUM_SCANS_STRING_NAME); <START> if (o != null && !NumberUtils.isCreatable(o)) <END> throw new IllegalArgumentException( "bad integer " + NUM_SCANS_STRING_NAME + ":" + options.get(NUM_SCANS_STRING_NAME)); return true; }</code><technical_language>I isParsable more sense need call Integer.parseInt later. This a perfect check, explicitly check parse-able Integer class (it parse-able Long, Double, etc.), closer want check for isCreatable hex, etc. notations for this option</technical_language>

Target:
public boolean validateOptions(Map<String,String> options) { String o = options.get(NUM_SCANS_STRING_NAME); if (o != null && !NumberUtils.isParsable(o)) throw new IllegalArgumentException( "bad integer " + NUM_SCANS_STRING_NAME + ":" + options.get(NUM_SCANS_STRING_NAME)); return true; }
Source:
<code>protected void initializeDatabase() throws SQLException { String driver = "org.h2.Driver"; try { Class.forName(driver); } catch (ClassNotFoundException e) { <START> e.printStackTrace(); <END> } connection = DriverManager.getConnection("jdbc:h2:mem:openmrs;DB_CLOSE_DELAY=-1", USER_NAME, PASSWORD); connection.setAutoCommit(false); }</code><technical_language><LINK_0></technical_language>

Target:
protected void initializeDatabase() throws SQLException, ClassNotFoundException { String driver = "org.h2.Driver"; Class.forName(driver); connection = DriverManager.getConnection("jdbc:h2:mem:openmrs;DB_CLOSE_DELAY=-1", USER_NAME, PASSWORD); connection.setAutoCommit(false); }
Source:
<code>protected Object readResolve() { <START> if (dirName != null && delegate == null) { <END> delegate = new AbstractOnDiskBinding.UnbinderImpl(dirName); } return this; }</code><technical_language>dirName null, delegate null</technical_language>

Target:
protected Object readResolve() { return new AbstractOnDiskBinding.UnbinderImpl(dirName); }
Source:
<code>public void serverShutDown() throws Exception { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { <START> try { <END> CarbonCommandToolsUtil.serverShutdown(1, context); } catch (Exception e) { log.error("Error while server shutdown ..", e); } } }); }</code><technical_language>1. Change Exception exact exception get 2. throw exception log catch</technical_language>

Target:
public void serverShutDown() throws CarbonToolsIntegrationTestException { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { CarbonCommandToolsUtil.serverShutdown(1, context); } catch (Exception e) { log.error("Error while server shutdown ..", e); } } }); }
Source:
<code>private DBObject translateUnaryLogicalExpression(FieldTreeNode context, UnaryLogicalExpression expr) { List<DBObject> l=new ArrayList<>(1); l.add(translate(context,expr.getQuery())); <START> return new BasicDBObject("$nor", l); <END> }</code><technical_language>Hard coding "$nor" instead of UNARY_LOGICAL_OPERATOR_MAP confusing attempting debug change later</technical_language>

Target:
private DBObject translateUnaryLogicalExpression(FieldTreeNode context, UnaryLogicalExpression expr) { List<DBObject> l=new ArrayList<>(1); l.add(translate(context,expr.getQuery())); return new BasicDBObject(UNARY_LOGICAL_OPERATOR_MAP.get(expr.getOp()), l); }
Source:
<code>public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); if (mutableEditionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.NONE) { <START> throw BadRequestException.create("Can't uninstall the edition in the current state: " + mutableEditionManagementState.getPendingInstallationStatus()); <END> } editionInstaller.uninstall(); mutableEditionManagementState.uninstall(); response.noContent(); }</code><technical_language>with: "Uninstall of current edition is allowed install of edition is in progress" ignore case current state is "UNINSTALL_IN_PROGRESS"</technical_language>

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); if (mutableEditionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.NONE && mutableEditionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.UNINSTALL_IN_PROGRESS) { throw BadRequestException.create("Uninstall of the current edition is not allowed when install of an edition is in progress"); } editionInstaller.uninstall(); mutableEditionManagementState.uninstall(); response.noContent(); }
Source:
<code>public int getMinAxis() { <START> return (int) Math.round(Math.min(x, y)); <END> }</code><technical_language>This methods return index of max/min axis: x = 0, y = 1, z = 2, remove interfaces</technical_language>

Target:
public int getMinAxis() { if (x < y) { return 0; } return 1; }
Source:
<code><START> private CallbackPlugin getPlugin() { <END> if (plugin == null) { try { plugin = (CallbackPlugin) getClassLoader().loadClass(pluginClass).getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return plugin; }</code><technical_language>This method is thread-safe is potentially called multiple threads. this lead weird behaviour. this method thread-safe</technical_language>

Target:
private synchronized CallbackPlugin getPlugin() { if (plugin == null) { try { plugin = (CallbackPlugin) getClassLoader().loadClass(pluginClass).getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return plugin; }
Source:
<code>public void testAutoCrashReportEnabling() { Context context = InstrumentationRegistry.getTargetContext(); SettingsActivity.setAutoCrashReportingEnabled(context, false); verify(CrashReporter.reporter, Mockito.times(0)).initialize(context); SettingsActivity.setAutoCrashReportingEnabled(context, true); <START> verify(CrashReporter.reporter, Mockito.times(1)).initialize(context); <END> }</code><technical_language>verify(~CrashReporter.~reporter, ~Mockito.~times(1)).initialize(context);</technical_language>

Target:
public void testAutoCrashReportEnabling() { Context context = InstrumentationRegistry.getTargetContext(); SettingsActivity.setAutoCrashReportingEnabled(context, false); verify(reporter, times(0)).initialize(context); SettingsActivity.setAutoCrashReportingEnabled(context, true); verify(reporter, times(1)).initialize(context); }
Source:
<code>static boolean isObjectInBucketIgnoringPermission(AmazonS3 s3Client, String bucketName, String objectKey) { try { return s3Client.doesObjectExist(bucketName, objectKey); } catch (AmazonS3Exception e) { <START> if (e.getStatusCode() == 403) { <END> return true; } throw e; } }</code><technical_language>is 404 valid anymore</technical_language>

Target:
static boolean isObjectInBucketIgnoringPermission(AmazonS3 s3Client, String bucketName, String objectKey) { try { return s3Client.doesObjectExist(bucketName, objectKey); } catch (AmazonS3Exception e) { if (e.getStatusCode() == 404) { return true; } throw e; } }
Source:
<code>public void applyPartitions(List<Map<String, String>> remainingPartitions) { if (allPartitions.isEmpty()) { <START> if (!remainingPartitions.isEmpty()) { <END> this.allPartitions = remainingPartitions; this.data = mapPartitionToRow(physicalSchema, data.get(Collections.EMPTY_MAP), remainingPartitions); } } else { this.allPartitions = remainingPartitions; } }</code><technical_language>if remainingPartitions is empty</technical_language>

Target:
public void applyPartitions(List<Map<String, String>> remainingPartitions) { if (allPartitions.isEmpty()) { if (!remainingPartitions.isEmpty()) { this.allPartitions = remainingPartitions; this.data = mapPartitionToRow(physicalSchema, data.get(Collections.EMPTY_MAP), remainingPartitions); } else { this.data.put(Collections.emptyMap(), Collections.emptyList()); } } else { this.allPartitions = remainingPartitions; if (remainingPartitions.isEmpty()) { this.data.put(Collections.emptyMap(), Collections.emptyList()); } } }
Source:
<code>public void onScoreCalculationLimitInputChange( ChangeEvent event ) { try { Long value = scoreCalculationCountLimitInput.getValue().isEmpty() ? null : Long.parseLong( scoreCalculationCountLimitInput.getValue() ); presenter.onScoreCalculationLimitChange( value ); } catch ( NumberFormatException e ) { <START> <END> } }</code><technical_language>Likewise.</technical_language>

Target:
public void onScoreCalculationLimitInputChange( ChangeEvent event ) { boolean isNumeric = scoreCalculationCountLimitInput.getValue().matches( "\\d+" ); if (isNumeric) { presenter.onScoreCalculationLimitChange( Long.parseLong( scoreCalculationCountLimitInput.getValue() ) ); } else { presenter.onScoreCalculationLimitChange( 0l ); scoreCalculationCountLimitInput.setValue( "0" ); } }
Source:
<code>public boolean equals(Object o) { <START> if (this == o) <END> { return true; } if (o == null || getClass() != o.getClass()) { return false; } Method method = (Method) o; return methodId == method.methodId; }</code><technical_language>whitespace/style</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Method method = (Method) o; return methodId == method.methodId; }
Source:
<code>public IndexGeneratorJobTest( String partitionType, String interval, Object[][][] shardInfoForEachSegment, List<String> data ) throws IOException { this.partitionType = partitionType; this.shardInfoForEachSegment = shardInfoForEachSegment; this.interval = new Interval(interval); mapper = new DefaultObjectMapper(); mapper.registerSubtypes(new NamedType(HashBasedNumberedShardSpec.class, "hashed")); mapper.registerSubtypes(new NamedType(SingleDimensionShardSpec.class, "single")); InjectableValues inject = new InjectableValues.Std().addValue(ObjectMapper.class, mapper); mapper.setInjectableValues(inject); <START> dataFile = File.createTempFile("test_website_data", "tmp"); <END> dataFile.deleteOnExit(); tmpDir = Files.createTempDir(); tmpDir.deleteOnExit(); FileUtils.writeLines(dataFile, data); config = new HadoopDruidIndexerConfig( new HadoopIngestionSpec( new DataSchema( "website", new StringInputRowParser( new CSVParseSpec( new TimestampSpec("timestamp", "yyyyMMddHH", null), new DimensionsSpec(ImmutableList.of("host"), null, null), null, ImmutableList.of("timestamp", "host", "visited_num") ) ), new AggregatorFactory[]{new LongSumAggregatorFactory("visited_num", "visited_num")}, new UniformGranularitySpec( Granularity.DAY, QueryGranularity.NONE, ImmutableList.of(this.interval) ) ), new HadoopIOConfig( ImmutableMap.<String, Object>of( "paths", dataFile.getCanonicalPath(), "type", "static" ), null, tmpDir.getCanonicalPath() ), new HadoopTuningConfig( tmpDir.getCanonicalPath(), null, null, null, null, null, false, false, false, false, null, false, false, false, null, null ) ) ); config.setShardSpecs(loadShardSpecs(partitionType, shardInfoForEachSegment)); config = HadoopDruidIndexerConfig.fromSpec(config.getSchema()); }</code><technical_language>a @Rule for TemporaryFolder in this class? simplifies cleanup a bit</technical_language>

Target:
public IndexGeneratorJobTest( String partitionType, String interval, Object[][][] shardInfoForEachSegment, List<String> data ) throws IOException { this.partitionType = partitionType; this.shardInfoForEachSegment = shardInfoForEachSegment; this.interval = new Interval(interval); this.data = data; }
Source:
<code><START> private boolean definesPatternProperty(String field) { <END> for (Entry<Pattern, Schema> entry : patternProperties.entrySet()) { if (entry.getKey().matcher(field).matches()) { return true; } } return false; }</code><technical_language>rewrite this method java8 stream API. a necessary change, good for practicing (if familiar streams), due simplicity of task. for definesSchemaDependencyProperty()</technical_language>

Target:
private boolean definesPatternProperty(String field) { return patternProperties.keySet().stream().filter(pattern -> pattern.matcher(field).matches()) .findAny().isPresent(); }
Source:
<code><START> public void charset(Charset charset) { <END> outputSettings.charset(charset); ensureMetaCharset(); }</code><technical_language>I turn updateMetaCharset this method is hit. If user want updated, hit this method. Output settings</technical_language>

Target:
public void charset(Charset charset) { updateMetaCharsetElement(true); outputSettings.charset(charset); ensureMetaCharsetElement(); }
Source:
<code>private PagesSerde createPagesSerdeInternal(Optional<SpillCipher> spillCipher) { Optional<Compressor> compressor; Optional<Decompressor> decompressor; if (compressionEnabled) { compressor = Optional.of(new Lz4Compressor()); decompressor = Optional.of(new Lz4Decompressor()); } else { compressor = Optional.empty(); decompressor = Optional.empty(); } <START> return new PagesSerde(blockEncodingSerde, compressor, decompressor, spillCipher); <END> }</code><technical_language>original code style in this method is better: private PagesSerde createPagesSerdeInternal(Optional<SpillCipher> spillCipher) { if (compressionEnabled) { return new PagesSerde(blockEncodingSerde, Optional.of(new Lz4Compressor()), Optional.of(new Lz4Decompressor()), spillCipher); } return new PagesSerde(blockEncodingSerde, Optional.empty(), Optional.empty(), spillCipher); }</technical_language>

Target:
private PagesSerde createPagesSerdeInternal(Optional<SpillCipher> spillCipher) { if (compressionEnabled) { return new PagesSerde(blockEncodingSerde, Optional.of(new Lz4Compressor()), Optional.of(new Lz4Decompressor()), spillCipher); } return new PagesSerde(blockEncodingSerde, Optional.empty(), Optional.empty(), spillCipher); }
Source:
<code>protected void onReveal() { Event entityChangedEvent = getModel().getDiskViewType().getEntityChangedEvent(); if (!entityChangedEvent.getListeners().contains(getView().getDiskTypeChangedEventListener())) { entityChangedEvent.addListener(getView().getDiskTypeChangedEventListener()); } Event systemTreeSelectedItemChangedEvent = CommonModel.getInstance().getSystemTree().getSelectedItemChangedEvent(); <START> <END> systemTreeSelectedItemChangedEvent.addListener(systemTreeChangedEventListener); super.onReveal(); getView().handleQuotaColumnVisibility(); }</code><technical_language>Unnecessary newline, I inline (i.e. CommonModel.getInstance().getSystemTree().getSelectedItemChangedEvent().addListener(systemTreeChangedEventListener))</technical_language>

Target:
protected void onReveal() { Event entityChangedEvent = getModel().getDiskViewType().getEntityChangedEvent(); if (!entityChangedEvent.getListeners().contains(getView().getDiskTypeChangedEventListener())) { entityChangedEvent.addListener(getView().getDiskTypeChangedEventListener()); } Event systemTreeSelectedItemChangedEvent = CommonModel.getInstance().getSystemTree().getSelectedItemChangedEvent(); systemTreeSelectedItemChangedEvent.addListener(systemTreeListener); super.onReveal(); getView().handleQuotaColumnVisibility(); }
Source:
<code>public Text replace(Pattern oldValue, Text newValue, boolean lossy) { <START> Text t = this.children.isEmpty() ? this : this.toBuilder().removeAll().append(this.children.stream() <END> .map(x -> x.replace(oldValue, newValue, lossy)).collect(Collectors.toList())).build(); String plain = t.toPlainSingle(); Matcher matcher = oldValue.matcher(plain); if (!matcher.find()) { if (lossy) { plain = t.toPlain(); matcher = oldValue.matcher(plain); if (matcher.find()) { t = t.toBuilder().removeAll().build(); } else { return t; } } else { return t; } } if (matcher.hitEnd()) { if (this.format.equals(TextFormat.NONE)) { return newValue; } return this.reformat(Text.builder()).append(newValue).build(); } Builder builder = Text.builder(); List<String> strs = Arrays.asList(oldValue.split(plain, -1)); for (String str : Iterables.limit(strs, strs.size() - 1)) { builder.append(Text.of(str)); builder.append(newValue); } builder.append(Text.of(strs.get(strs.size() - 1))); return this.reformat(builder).build(); }</code><technical_language>Please give this a longer name - single character variables reserved for for</technical_language>

Target:
public Text replace(Pattern oldValue, Text newValue, boolean lossy) { Text text = this.children.isEmpty() ? this : this.toBuilder().removeAll().append(this.children.stream() .map(child -> child.replace(oldValue, newValue, lossy)).collect(Collectors.toList())).build(); String plain = text.toPlainSingle(); Matcher matcher = oldValue.matcher(plain); if (!matcher.find()) { if (lossy) { plain = text.toPlain(); matcher = oldValue.matcher(plain); if (matcher.find()) { text = text.toBuilder().removeAll().build(); } else { return text; } } else { return text; } } if (matcher.hitEnd()) { return this.reformat(Text.builder()).append(newValue).append(text.children).build(); } Builder builder = Text.builder(); List<String> strs = Arrays.asList(oldValue.split(plain, -1)); for (String str : Iterables.limit(strs, strs.size() - 1)) { builder.append(Text.of(str)); builder.append(newValue); } builder.append(Text.of(strs.get(strs.size() - 1))).append(text.children); return this.reformat(builder).build(); }
Source:
<code><START> public UserDetails getCached(String idOrFullName) throws UsernameNotFoundException { <END> Boolean exists = existanceCache.getIfPresent(idOrFullName); if (exists != null && !exists) { throw new UsernameNotFoundException(String.format("\"%s\" does not exist", idOrFullName)); } else { return detailsCache.getIfPresent(idOrFullName); } }</code><technical_language>this is for testing - restricted in scope</technical_language>

Target:
public UserDetails getCached(String idOrFullName) throws UsernameNotFoundException { Boolean exists = existanceCache.getIfPresent(idOrFullName); if (exists != null && !exists) { throw new UserMayOrMayNotExistException(String.format("\"%s\" does not exist", idOrFullName)); } else { return detailsCache.getIfPresent(idOrFullName); } }
Source:
<code>public void testResolvingNullKeyValueQueryReturnsNullComparator() { HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); <START> Comparator<Map.Entry<?, ?>> comparator = (Comparator<Map.Entry<?, ?>>) hazelcastSortAccessor.resolve((KeyValueQuery<?>) null); <END> assertNull(comparator); }</code><technical_language>suggestion Comparator<Map.Entry<?, ?>> comparator = hazelcastSortAccessor.resolve(null);</technical_language>

Target:
public void testResolvingNullKeyValueQueryReturnsNullComparator() { HazelcastSortAccessor hazelcastSortAccessor = new HazelcastSortAccessor(); Comparator<Map.Entry<?, ?>> comparator = hazelcastSortAccessor.resolve(null); assertNull(comparator); }
Source:
<code>private static @NonNull Set<Integer> getActiveThreads(TmfTimeRange winRange, @NonNull ITmfTrace trace) { KernelAnalysisModule kernelModule = TmfTraceUtils.getAnalysisModuleOfClass(trace, KernelAnalysisModule.class, KernelAnalysisModule.ID); long beginTS = winRange.getStartTime().getValue(); long endTS = winRange.getEndTime().getValue(); if (kernelModule == null) { return new <START> HashSet<>(); <END> } Set<Integer> set = KernelThreadInformationProvider.getActiveThreadsForRange(kernelModule, beginTS, endTS); return set; }</code><technical_language>collections.emptySet()</technical_language>

Target:
private static @NonNull Set<Integer> getActiveThreads(TmfTimeRange winRange, @NonNull ITmfTrace trace) { KernelAnalysisModule kernelModule = TmfTraceUtils.getAnalysisModuleOfClass(trace, KernelAnalysisModule.class, KernelAnalysisModule.ID); long beginTS = winRange.getStartTime().getValue(); long endTS = winRange.getEndTime().getValue(); if (kernelModule == null) { return Collections.emptySet(); } return KernelThreadInformationProvider.getActiveThreadsForRange(kernelModule, beginTS, endTS); }
Source:
<code>public void tag(final String... tags) throws IOException { <START> final List<String> args = new ArrayList<String>(); <END> args.add("add"); args.add(this.jid); for (final String tag : tags) { args.add(tag); } this.client.call( LuaCommand.TAG.toString(), args); }</code><technical_language>java final List<String> args = new ArrayList<>();</technical_language>

Target:
public void tag(final String... tags) throws IOException { final List<String> args = new ArrayList<>(); args.add("add"); args.add(this.jid); Collections.addAll(args, tags); this.client.call( LuaCommand.TAG.toString(), args); }
Source:
<code>public void getFields( RowMetaInterface row, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException { ValueMetaInterface v = new ValueMeta( this.getValueXMLfield(), ValueMetaInterface.TYPE_STRING ); v.setOrigin( name ); TransMeta transMeta = (TransMeta) space; try { <START> String[] targetFieldNames = null; <END> RowMetaInterface targetRowMeta = transMeta.getStepFields( transMeta.findStep( getTargetXMLstep() ), null, null ); if ( targetRowMeta != null ) { targetFieldNames = targetRowMeta.getFieldNames(); } for ( String fieldName : transMeta.getStepFields( transMeta.findStep( getSourceXMLstep() ), null, null ).getFieldNames() ) { if ( targetFieldNames == null || !Arrays.asList( targetFieldNames ).contains( fieldName ) ) { row.removeValueMeta( fieldName ); } } } catch ( KettleValueException e ) { } row.addValueMeta( v ); }</code><technical_language>create this a List<String> in code creating a new list for iteration list of step fields</technical_language>

Target:
public void getFields( RowMetaInterface row, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException { ValueMetaInterface v = new ValueMeta( this.getValueXMLfield(), ValueMetaInterface.TYPE_STRING ); v.setOrigin( name ); TransMeta transMeta = (TransMeta) space; try { List<String> targetFieldNames = null; RowMetaInterface targetRowMeta = transMeta.getStepFields( transMeta.findStep( getTargetXMLstep() ), null, null ); if ( targetRowMeta != null ) { targetFieldNames = Arrays.asList( targetRowMeta.getFieldNames() ); } for ( String fieldName : transMeta.getStepFields( transMeta.findStep( getSourceXMLstep() ), null, null ).getFieldNames() ) { if ( targetFieldNames == null || !targetFieldNames.contains( fieldName ) ) { row.removeValueMeta( fieldName ); } } } catch ( KettleValueException e ) { } row.addValueMeta( v ); }
Source:
<code>public void ReadSerial() { <START> byte[] buf = new byte[256]; <END> boolean success = true; String data = ""; if (mPhysicaloid.read(buf) > 0) { try { data = new String(buf, "UTF-8"); } catch (UnsupportedEncodingException mEr) { success = false; Log.e(LOG_TAG, mEr.getMessage()); } } else { success = false; } AfterReadSerial(success, data); }</code><technical_language>Is data in buffer guaranteed < 256 bytes? if in middle of reading a multibyte UTF-8 character? possibly lose data. Is read() call blocking</technical_language>

Target:
public String ReadSerial() { String data = ""; if (mPhysicaloid == null) { form.dispatchErrorOccurredEvent(Serial.this, "ReadSerial", ErrorMessages.ERROR_SERIAL_NOT_INITIALIZED); } else { byte[] buf = new byte[this.bytes]; if (mPhysicaloid.read(buf) > 0) { try { data = new String(buf, "UTF-8"); } catch (UnsupportedEncodingException mEr) { Log.e(LOG_TAG, mEr.getMessage()); } } } return data; }
Source:
<code>public boolean getLegal() { if (getUseTimout()) { String keyForCheck = getkeyForCheck(); <START> if (!CacheManager.getTimeoutBaseCache().containsKey(keyForCheck)) { <END> CacheManager.getTimeoutBaseCache().put(keyForCheck, keyForCheck, getEndTime(), TimeUnit.MILLISECONDS); return true; } return false; } return true; }</code><technical_language>Is thread safe [fyi, much]? impl is atomic, split it</technical_language>

Target:
public boolean getLegal() { if (getUseTimout()) { String keyForCheck = getkeyForCheck(); synchronized (keyForCheck) { if (!CacheManager.getTimeoutBaseCache().containsKey(keyForCheck)) { CacheManager.getTimeoutBaseCache().put(keyForCheck, keyForCheck, getEndTime(), TimeUnit.MILLISECONDS); return true; } } return false; } return true; }
Source:
<code>protected ActionResult execute() { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); String nextUrl = getRequestParamValue(Const.ParamsNames.NEXT_URL); if (nextUrl == null) { nextUrl = Const.ActionURIs.INSTRUCTOR_FEEDBACK_SESSIONS_PAGE; } FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(courseId, account.googleId), feedbackSession, false, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); if (!feedbackSession.isOpened()) { statusToUser.add(new StatusMessage( Const.StatusMessages.FEEDBACK_SESSION_REMINDERSSESSIONNOTOPEN, StatusMessageColor.DANGER)); <START> return createRedirectResult(nextUrl); <END> } taskQueuer.scheduleFeedbackSessionReminders(courseId, feedbackSessionName); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SESSION_REMINDERSSENT, StatusMessageColor.SUCCESS)); statusToAdmin = "Email sent out to all students who have not completed " + "Feedback Session <span class=\"bold\">(" + feedbackSessionName + ")</span> " + "of Course <span class=\"bold\">[" + courseId + "]</span>"; return createRedirectResult(nextUrl); }</code><technical_language>Add statusToAdmin</technical_language>

Target:
protected ActionResult execute() { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); String nextUrl = getRequestParamValue(Const.ParamsNames.NEXT_URL); if (nextUrl == null) { nextUrl = Const.ActionURIs.INSTRUCTOR_FEEDBACK_SESSIONS_PAGE; } FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(courseId, account.googleId), feedbackSession, false, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); if (!feedbackSession.isOpened()) { statusToUser.add(new StatusMessage( Const.StatusMessages.FEEDBACK_SESSION_REMINDERSSESSIONNOTOPEN, StatusMessageColor.DANGER)); statusToAdmin = "Reminder email could not be sent out as the feedback session is not open for submissions."; return createRedirectResult(nextUrl); } taskQueuer.scheduleFeedbackSessionReminders(courseId, feedbackSessionName); statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SESSION_REMINDERSSENT, StatusMessageColor.SUCCESS)); statusToAdmin = "Email sent out to all students who have not completed " + "Feedback Session <span class=\"bold\">(" + feedbackSessionName + ")</span> " + "of Course <span class=\"bold\">[" + courseId + "]</span>"; return createRedirectResult(nextUrl); }
Source:
<code><START> protected MessageBus getMessageBus() { <END> testMessageBus = new RabbitTestMessageBus(rabbitAvailableRule.getResource(), getCodec()); return testMessageBus; }</code><technical_language>this initialize testMessageBus instance if null? (could synchronized method-level in a synchronized block)</technical_language>

Target:
protected MessageBus getMessageBus() { if (testMessageBus == null) { testMessageBus = new RabbitTestMessageBus(rabbitAvailableRule.getResource(), getCodec()); } return testMessageBus; }
Source:
<code>public boolean isConnectionAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager)mConnectionContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); <START> return isConnected; <END> }</code><technical_language>collapse 2 lines</technical_language>

Target:
public boolean isConnectionAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager)mConnectionContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); }
Source:
<code>public boolean isHoliday(LocalDate date) { ArgChecker.notNull(date, "date"); try { int index = (date.getYear() - startYear) * 12 + date.getMonthValue() - 1; <START> return (lookup[index] & (1 << (date.getDayOfMonth() - 1))) > 0; <END> } catch (ArrayIndexOutOfBoundsException ex) { if (startYear == 0) { return weekendDays.contains(date.getDayOfWeek()); } throw new IllegalArgumentException("Date is not within the range of known holidays: " + date + ", " + range); } }</code><technical_language>of (tediously) statically creating bit masks for day front i.e. int[] masks = new int[31]; for (int i = 0; i < 31; i++) { masks[i] = (1 << i); } in line here, do: return (lookup[index] & masks[date.getDayOfMonth() - 1)]) > 0; (As re: indexxing of day in month)</technical_language>

Target:
public boolean isHoliday(LocalDate date) { ArgChecker.notNull(date, "date"); try { int index = (date.getYear() - startYear) * 12 + date.getMonthValue() - 1; return (lookup[index] & (1 << (date.getDayOfMonth() - 1))) == 0; } catch (ArrayIndexOutOfBoundsException ex) { if (startYear == 0) { return weekendDays.contains(date.getDayOfWeek()); } throw new IllegalArgumentException(rangeError(date)); } }
Source:
<code><START> private Object readResolve() { <END> return INSTANCE; }</code><technical_language>a final class, a breaking change if overrides</technical_language>

Target:
protected Object readResolve() { return INSTANCE; }
Source:
<code>public void shouldTraverseListWithGivenFunction2(){ List<String> strings = list("some1", "some2", "some3"); F<String, Option<String>> f = s -> { if(s.startsWith("some")) return some(s); else return Option.none(); }; Option<List<String>> optStr = strings.traverseOption(f); Assert.assertEquals("optStr should be some", optStr.isSome(), true); Assert.assertArrayEquals(optStr.some().toArray().array(), new String[]{"some1", "some2", "some3"}); <START> } <END></code><technical_language>easier compare lists Assert.assertArrayEquals(optStr.some(), List.list("some1", "some2", "some3")); I try this code</technical_language>

Target:
public void shouldTraverseListWithGivenFunction2(){ List<String> strings = list("some1", "some2", "some3"); F<String, Option<String>> f = s -> { if(s.startsWith("some")) return some(s); else return Option.none(); }; Option<List<String>> optStr = strings.traverseOption(f); Assert.assertEquals("optStr should be some", optStr.isSome(), true); assertThat(optStr.some(), is(List.list("some1", "some2", "some3"))); }
Source:
<code>public static AssetTable<String> buildFromIngestible(AssetNodesByDoi assetNodeMap, ManifestXml manifest) { Map<Key, Value<String>> ingestibleEntryNames = new LinkedHashMap<>(); for (ManifestXml.Asset asset : manifest.parse()) { AssetType assetType = findAssetType(assetNodeMap, asset); <START> for (ManifestXml.Representation representation : asset.getRepresentations()) { <END> String entryName = representation.getEntry(); String fileType = assetType.getFileType(representation.getName()); Key key = new Key(AssetIdentity.create(asset.getUri()), fileType); Value<String> value = new Value<>(assetType, entryName); Value<String> previous = ingestibleEntryNames.put(key, value); if (previous != null) { String message = String.format("More than one file has uri=\"%s\" and repr=\"%s\"", asset.getUri(), representation.getName()); throw new RestClientException(message, HttpStatus.BAD_REQUEST); } } } return new AssetTable<>(ingestibleEntryNames); }</code><technical_language>I break out this for loop method</technical_language>

Target:
public static AssetTable<String> buildFromIngestible(AssetNodesByDoi assetNodeMap, ManifestXml manifest) { Map<Key, Value<String>> ingestibleEntryNames = new LinkedHashMap<>(); for (ManifestXml.Asset asset : manifest.parse()) { AssetType assetType = findAssetType(assetNodeMap, asset); for (ManifestXml.Representation representation : asset.getRepresentations()) { insertEntryForAssetRepr(ingestibleEntryNames, asset, assetType, representation); } } return new AssetTable<>(ingestibleEntryNames); }
Source:
<code>private boolean removeInternal(final K key) throws CacheWritingException { removeObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); final AtomicBoolean modified = new AtomicBoolean(); final BiFunction<K, V, V> remappingFunction = memoize(new BiFunction<K, V, V>() { @Override public V apply(final K key, final V previousValue) { modified.set(previousValue != null); try { if (cacheLoaderWriter != null) { cacheLoaderWriter.delete(key); } } catch (Exception e) { throw newCacheWritingException(e); } eventNotificationService.onEvent(CacheEvents.removal(key, previousValue, Ehcache.this)); return null; } }); try { store.compute(key, remappingFunction); if (modified.get()) { removeObserver.end(RemoveOutcome.SUCCESS); markAllCacheEventsFireable(); } else { removeObserver.end(RemoveOutcome.NOOP); <START> markAllCacheEventsFireable(); <END> } } catch (CacheAccessException e) { try { try { remappingFunction.apply(key, null); } catch (CacheWritingException f) { resilienceStrategy.removeFailure(key, e, f); } resilienceStrategy.removeFailure(key, e); } finally { removeObserver.end(RemoveOutcome.FAILURE); markAllCacheEventsFailed(); } } return modified.get(); }</code><technical_language>returns here, call moved of if</technical_language>

Target:
private boolean removeInternal(final K key) throws CacheWritingException { removeObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); final AtomicBoolean modified = new AtomicBoolean(); final BiFunction<K, V, V> remappingFunction = memoize(new BiFunction<K, V, V>() { @Override public V apply(final K key, final V previousValue) { modified.set(previousValue != null); try { if (cacheLoaderWriter != null) { cacheLoaderWriter.delete(key); } } catch (Exception e) { throw newCacheWritingException(e); } eventNotificationService.onEvent(CacheEvents.removal(key, previousValue, Ehcache.this)); return null; } }); try { store.compute(key, remappingFunction); if (modified.get()) { removeObserver.end(RemoveOutcome.SUCCESS); eventNotificationService.fireAllEvents(); } else { removeObserver.end(RemoveOutcome.NOOP); eventNotificationService.fireAllEvents(); } } catch (CacheAccessException e) { try { try { remappingFunction.apply(key, null); } catch (CacheWritingException f) { resilienceStrategy.removeFailure(key, e, f); } resilienceStrategy.removeFailure(key, e); } finally { removeObserver.end(RemoveOutcome.FAILURE); } } finally { eventNotificationService.processAndFireRemainingEvents(); } return modified.get(); }
Source:
<code>public void updatePayload( final Map<String, String> key, final Set<Series> series, final List<Payload> values ) { <START> this.childSession.updatePayload(key, series, values); <END> }</code><technical_language>Leave this others empty if intend support other metric types. This ignore data is of wrong type</technical_language>

Target:
public void updatePayload( final Map<String, String> key, final Set<Series> series, final List<Payload> values ) { }
Source:
<code>public void persistTimer(final TimerImpl timer, boolean newTimer) { if (timer == null) { return; } if (timer.isTimerPersistent()) { try { if (timerPersistence.getOptionalValue() == null) { EJB3_TIMER_LOGGER.timerPersistenceNotEnable(); return; } final ContextTransactionManager transactionManager = ContextTransactionManager.getInstance(); Transaction clientTX = transactionManager.getTransaction(); if (newTimer) { if( clientTX == null ){ transactionManager.begin(); } try { timerPersistence.getValue().addTimer(timer); if(clientTX == null) transactionManager.commit(); } catch (Exception e){ if(clientTX == null) { try { transactionManager.rollback(); } catch (Exception ee){ EjbLogger.EJB3_TIMER_LOGGER.timerUpdateFailedAndRollbackNotPossible(ee); } } throw e; } } else { <START> if( clientTX != null ) transactionManager.suspend(); <END> for (int count = 3; count > 0; count--) { try { transactionManager.begin(); timerPersistence.getValue().persistTimer(timer); transactionManager.commit(); break; } catch (RuntimeException e) { try { transactionManager.rollback(); } catch (Exception ee) { } if (count > 1) { EJB3_TIMER_LOGGER.debug("Failed to persist timer " + timer + " due to " + e.getCause()); } else { throw e; } } } if( clientTX != null ) transactionManager.resume(clientTX); } } catch (Throwable t) { this.setRollbackOnly(); throw new RuntimeException(t); } } }</code><technical_language>Timer updates transactional, if outer transaction fails timer updated</technical_language>

Target:
public void persistTimer(final TimerImpl timer, boolean newTimer) { if (timer == null) { return; } if (timer.isTimerPersistent()) { try { if (timerPersistence.getOptionalValue() == null) { EJB3_TIMER_LOGGER.timerPersistenceNotEnable(); return; } final ContextTransactionManager transactionManager = ContextTransactionManager.getInstance(); Transaction clientTX = transactionManager.getTransaction(); if (newTimer || timer.isCanceled()) { if( clientTX == null ){ transactionManager.begin(); } try { if( newTimer ) timerPersistence.getValue().addTimer(timer); else timerPersistence.getValue().persistTimer(timer); if(clientTX == null) transactionManager.commit(); } catch (Exception e){ if(clientTX == null) { try { transactionManager.rollback(); } catch (Exception ee){ EjbLogger.EJB3_TIMER_LOGGER.timerUpdateFailedAndRollbackNotPossible(ee); } } throw e; } } else { new TaskPostPersist(timer).persistTimer(); } } catch (Throwable t) { this.setRollbackOnly(); throw new RuntimeException(t); } } }
Source:
<code>private void send(){ if(!typeText.getText().equals("")){ <START> getMessege("lala",typeText.getText()); <END> typeText.setText(""); } }</code><technical_language>WTF is lala</technical_language>

Target:
private void send(){ if(!typeText.getText().equals("")){ getMessege("Username",typeText.getText()); typeText.setText(""); } }
Source:
<code>public static void main(String[] args) throws IOException, ClassNotFoundException { Client client = ClientBuilder.newClient(); WebTarget target = client.target(HZ_REST_URL); Response stringResponse = target.path("/maps/simple/key1").request().get(); String responseBody = stringResponse.readEntity(String.class); System.out.println("Value for key1 is " + responseBody); Response objectResponse = target.path("/maps/object/key1").request().get(); byte[] entity = objectResponse.readEntity(byte[].class); ByteArrayInputStream byteArrayInputStream = null; ObjectInputStream objectInputStream = null; try { byteArrayInputStream = new ByteArrayInputStream(entity); objectInputStream = new ObjectInputStream(byteArrayInputStream); Person person = (Person) objectInputStream.readObject(); System.out.println("Object for key1 is " + person.toString()); } finally { closeQuietly(objectInputStream); closeQuietly(byteArrayInputStream); } <START> HazelcastClient.shutdownAll(); <END> }</code><technical_language>@Donnerbart need this here? I Hazelcast client functionality</technical_language>

Target:
public static void main(String[] args) throws IOException, ClassNotFoundException { Client client = ClientBuilder.newClient(); WebTarget target = client.target(HZ_REST_URL); Response stringResponse = target.path("/maps/simple/key1").request().get(); String responseBody = stringResponse.readEntity(String.class); System.out.println("Value for key1 is " + responseBody); Response objectResponse = target.path("/maps/object/key1").request().get(); byte[] entity = objectResponse.readEntity(byte[].class); ByteArrayInputStream byteArrayInputStream = null; ObjectInputStream objectInputStream = null; try { byteArrayInputStream = new ByteArrayInputStream(entity); objectInputStream = new ObjectInputStream(byteArrayInputStream); Person person = (Person) objectInputStream.readObject(); System.out.println("Object for key1 is " + person.toString()); } finally { closeQuietly(objectInputStream); closeQuietly(byteArrayInputStream); } }
Source:
<code>public boolean onPreferenceChange(Preference preference, Object objValue) { boolean <START> isCombiningRestrictedAndUnknownOption = <END> getResources().getBoolean( R.bool.combine_options_to_block_restricted_and_unknown_callers); if (isCombiningRestrictedAndUnknownOption && preference.getKey().equals(BLOCK_UNKNOWN_NUMBERS_KEY)) { Log.i(this, "onPreferenceChange: changing %s and %s to %b", preference.getKey(), BLOCK_RESTRICTED_NUMBERS_KEY, (boolean) objValue); BlockedNumbersUtil.setEnhancedBlockSetting(getActivity(), BLOCK_RESTRICTED_NUMBERS_KEY, (boolean) objValue); } BlockedNumbersUtil.setEnhancedBlockSetting(getActivity(), preference.getKey(), (boolean) objValue); return true; }</code><technical_language>more sense put this initialization in onCreate change</technical_language>

Target:
public boolean onPreferenceChange(Preference preference, Object objValue) { if (mIsCombiningRestrictedAndUnknownOption && preference.getKey().equals(BLOCK_UNKNOWN_NUMBERS_KEY)) { Log.i(this, "onPreferenceChange: changing %s and %s to %b", preference.getKey(), BLOCK_RESTRICTED_NUMBERS_KEY, (boolean) objValue); BlockedNumbersUtil.setEnhancedBlockSetting(getActivity(), BLOCK_RESTRICTED_NUMBERS_KEY, (boolean) objValue); } BlockedNumbersUtil.setEnhancedBlockSetting(getActivity(), preference.getKey(), (boolean) objValue); return true; }
Source:
<code>private void mapNodes(GraphModel graphModel, Set<Long> nodeIds) { for (Node node : graphModel.getNodes()) { if (!nodeIds.contains(node.getId())) { Object entity = mappingContext.getNodeEntity(node.getId()); try { if (entity == null) { synchronized (this) { entity = entityFactory.newObject(node); setIdentity(entity, node.getId()); setProperties(node, entity); <START> entity = mappingContext.registerNodeEntity(entity, node.getId()); <END> } } nodeIds.add(node.getId()); } catch (BaseClassNotFoundException e) { logger.debug(e.getMessage()); } } } }</code><technical_language>reason setProperties is called node entity is in mapping context is reload entity graph, update properties. This fix longer case. missing a test for this, push shortly demo issue</technical_language>

Target:
private void mapNodes(GraphModel graphModel, Set<Long> nodeIds) { for (Node node : graphModel.getNodes()) { if (!nodeIds.contains(node.getId())) { Object entity = mappingContext.getNodeEntity(node.getId()); try { if (entity == null) { synchronized (this) { entity = entityFactory.newObject(node); setIdentity(entity, node.getId()); setProperties(node, entity); entity = mappingContext.registerNodeEntity(entity, node.getId()); } } else { setProperties(node, entity); } nodeIds.add(node.getId()); } catch (BaseClassNotFoundException e) { logger.debug(e.getMessage()); } } } }
Source:
<code>private <T extends Serializable> void registerStatistic(String name, StatisticType type, String tag, Function<EhcacheOffHeapBackingMap<K, OffHeapValueHolder<V>>, T> fn) { <START> StatisticsManager.createPassThroughStatistic(this, name, new HashSet<>(Arrays.asList(name, "tier")), type, () -> { <END> EhcacheOffHeapBackingMap<K, OffHeapValueHolder<V>> map = backingMap(); return map == null ? null : fn.apply(map); }); }</code><technical_language>Collections.singleton</technical_language>

Target:
private <T extends Serializable> void registerStatistic(String name, StatisticType type, String tag, Function<EhcacheOffHeapBackingMap<K, OffHeapValueHolder<V>>, T> fn) { StatisticsManager.createPassThroughStatistic(this, name, tags(tag, "tier"), type, () -> { EhcacheOffHeapBackingMap<K, OffHeapValueHolder<V>> map = backingMap(); return map == null ? null : fn.apply(map); }); }
Source:
<code>public synchronized String toString() { StringBuilder sb = new StringBuilder(); <START> sb.append("Stream " + getUniqueID() + ", Number of Packets: " + (fNbPacketsAtoB + fNbPacketsBtoA) + "\n"); END> String string = sb.toString(); if (string == null) { return EMPTY_STRING; } return string; }</code><technical_language>do getNbPackets()</technical_language>

Target:
public synchronized String toString() { StringBuilder sb = new StringBuilder(); sb.append("Stream " + getUniqueID() + ", Number of Packets: " + getNbPackets() + "\n"); @SuppressWarnings("null") @NonNull String string = sb.toString(); return string; }
Source:
<code>public void test_SerializationBug_26387905() throws Exception { Locale l = Locale.US; ObjectInputStream oinput = null; <START> try { oinput = new ObjectInputStream(getClass().getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream()); l = (Locale) oinput.readObject(); } finally { try { if (null != oinput) { oinput.close(); } } catch (Exception e) { } } <END> }</code><technical_language>please try resources. try (ObjectInputStream oinput = ...) { }</technical_language>

Target:
public void test_SerializationBug_26387905() throws Exception { try (ObjectInputStream oinput = new ObjectInputStream(getClass() .getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream())) { Locale l = (Locale) oinput.readObject(); } }
Source:
<code>private Map<String, String> addBuildArgsFromDockerConfig() { JsonObject dockerConfig = DockerFileUtil.readDockerConfig(); if (dockerConfig == null) { return Collections.emptyMap(); } Map<String, String> buildArgs = new HashMap<>(); if (dockerConfig.has("proxies")) { JsonObject proxies = dockerConfig.getAsJsonObject("proxies"); if (proxies.has("default")) { JsonObject defaultProxyObj = proxies.getAsJsonObject("default"); for(Map.Entry<String, String> entry : Collections.unmodifiableMap(new HashMap<String, String>() {{ <START> put("httpProxy", "http_proxy"); <END> put("httpsProxy", "https_proxy"); put("noProxy", "no_proxy"); put("ftpProxy", "ftp_proxy"); }}).entrySet()) { if (defaultProxyObj.has(entry.getKey())) { buildArgs.put(argPrefix + entry.getValue(), defaultProxyObj.get(entry.getKey()).getAsString()); } } } } log.debug("Build args set %s", buildArgs); return buildArgs; }</code><technical_language>a plain String[] array iterate i += 2 A Map is proper data structure (you need properties of a map here) e.g. java String[] proxyMapping = new String[] { "httpProxy", "http_proxy", ... }; for (int i = 0; i < proxyMapping.length; i+=2) { if (defaultProxyObk.has(proxyMapping[i]) { buildArgs.put(... proxyMapping[i], .... proxyMapping[i+1]); } }</technical_language>

Target:
private Map<String, String> addBuildArgsFromDockerConfig() { JsonObject dockerConfig = DockerFileUtil.readDockerConfig(); if (dockerConfig == null) { return Collections.emptyMap(); } Map<String, String> buildArgs = new HashMap<>(); if (dockerConfig.has("proxies")) { JsonObject proxies = dockerConfig.getAsJsonObject("proxies"); if (proxies.has("default")) { JsonObject defaultProxyObj = proxies.getAsJsonObject("default"); String[] proxyMapping = new String[] { "httpProxy", "http_proxy", "httpsProxy", "https_proxy", "noProxy", "no_proxy", "ftpProxy", "ftp_proxy" }; for(int index = 0; index < proxyMapping.length; index += 2) { if (defaultProxyObj.has(proxyMapping[index])) { buildArgs.put(argPrefix + proxyMapping[index+1], defaultProxyObj.get(proxyMapping[index]).getAsString()); } } } } log.debug("Build args set %s", buildArgs); return buildArgs; }