auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private TextBody buildText(boolean isDraft, SimpleMessageFormat messageFormat) { TextBodyBuilder textBodyBuilder = new TextBodyBuilder( mMessageContentView.getText().toString(), <START> mIdentity.getSignatureUse() ? mSignatureView.getCharacters() : null <END> ); if (isDraft || mQuotedTextMode == QuotedTextMode.SHOW) { textBodyBuilder.setIncludeQuotedText(true); } else { textBodyBuilder.setIncludeQuotedText(false); } if (!isDraft) { textBodyBuilder.setAppendSignature(true); } else { textBodyBuilder.setAppendSignature(false); } textBodyBuilder.setDraft(isDraft); textBodyBuilder.setSignatureBeforeQuotedText(mAccount.isSignatureBeforeQuotedText()); if (mQuoteStyle == QuoteStyle.PREFIX && mAccount.isReplyAfterQuote()) { textBodyBuilder.setReplyAfterQuote(true); } else { textBodyBuilder.setReplyAfterQuote(false); } TextBody body; if (messageFormat == SimpleMessageFormat.HTML) { body = textBodyBuilder.buildTextHtml(mQuotedHtmlContent); } else { body = textBodyBuilder.buildTextPlain(mQuotedText.getText().toString()); } return body; }</code><technical_language>unnecessary pass signature TextBodyBuilder it. suggestion is remove constructor add a method setSignature()</technical_language>

Target:
private TextBody buildText(boolean isDraft, SimpleMessageFormat messageFormat) { String messageText = mMessageContentView.getCharacters(); TextBodyBuilder textBodyBuilder = new TextBodyBuilder(messageText); boolean includeQuotedText = (isDraft || mQuotedTextMode == QuotedTextMode.SHOW); boolean isReplyAfterQuote = (mQuoteStyle == QuoteStyle.PREFIX && mAccount.isReplyAfterQuote()); textBodyBuilder.setIncludeQuotedText(false); if (includeQuotedText) { if (messageFormat == SimpleMessageFormat.HTML && mQuotedHtmlContent != null) { textBodyBuilder.setIncludeQuotedText(true); textBodyBuilder.setQuotedTextHtml(mQuotedHtmlContent); textBodyBuilder.setReplyAfterQuote(isReplyAfterQuote); } String quotedText = mQuotedText.getCharacters(); if (messageFormat == SimpleMessageFormat.TEXT && quotedText.length() > 0) { textBodyBuilder.setIncludeQuotedText(true); textBodyBuilder.setQuotedText(quotedText); textBodyBuilder.setReplyAfterQuote(isReplyAfterQuote); } } textBodyBuilder.setInsertSeparator(!isDraft); boolean useSignature = (!isDraft && mIdentity.getSignatureUse()); if (useSignature) { textBodyBuilder.setAppendSignature(true); textBodyBuilder.setSignature(mSignatureView.getCharacters()); textBodyBuilder.setSignatureBeforeQuotedText(mAccount.isSignatureBeforeQuotedText()); } else { textBodyBuilder.setAppendSignature(false); } TextBody body; if (messageFormat == SimpleMessageFormat.HTML) { body = textBodyBuilder.buildTextHtml(); } else { body = textBodyBuilder.buildTextPlain(); } return body; }
Source:
<code>public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { this.sbg = sbg; controller = new Controller(gc, sbg); soundObserver = new SoundObserver(); ArrayList<Player> players = Model.getPlayers(); <START> for(Player player: players) { <END> controller.registerObserver(player.getWallet()); } controller.registerObserver(soundObserver); controller.registerObserver(this); timers = controller.getTimers(); timers.restartTimer(); view = new View(gc, timers); try { wavEffect = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("Bubble_Trouble_Theme.wav")); } catch (IOException e) { e.printStackTrace(); } wavEffect.playAsSoundEffect(1.0f, 1.0f, true); SoundStore.get().poll(0); }</code><technical_language>for(Player player: Model.getPlayers())</technical_language>

Target:
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { this.sbg = sbg; controller = new Controller(gc, sbg); soundObserver = new SoundObserver(); for(Player player: Model.getPlayers()) { controller.registerObserver(player.getWallet()); } controller.registerObserver(soundObserver); controller.registerObserver(this); timers = controller.getTimers(); timers.restartTimer(); view = new View(gc, timers); try { wavEffect = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("Bubble_Trouble_Theme.wav")); } catch (IOException e) { e.printStackTrace(); } wavEffect.playAsSoundEffect(1.0f, 1.0f, true); SoundStore.get().poll(0); }
Source:
<code>public void testAnalysisCache() { executeTarget("testAnalysisCache"); <START> assertOutputContaining("Avoid really long methods"); <END> }</code><technical_language>check cache file exists (check line 147, checks output report), check output for cache warning present</technical_language>

Target:
public void testAnalysisCache() { executeTarget("testAnalysisCache"); assertOutputContaining("Avoid really long methods"); assertDoesntContain(buildRule.getLog(), "This analysis could be faster"); assertTrue(currentTempFile().exists()); }
Source:
<code>public static void main(String args[]) { long start = JVM.monotonicTimeMillis(); RE r1 = new RE("\\[([^\\[\\]])*\\]"); RE r2 = new RE("(\\d{3})(\\d{4})"); String number = "5555231119"; boolean m1 = false; boolean m2 = false; for (int i = 0; i < 1000; i++) { m1 = r1.match(number); m2 = r2.match(number); } System.out.println("Matches: " + m1 + " " + m2); <START> System.out.println("REGEX: " + (JVM.monotonicTimeMillis() - start)); <END> }</code><technical_language>split total time in time compile time match? Nit: move this line other System.out.println consider time spent in System.out.println</technical_language>

Target:
public static void main(String args[]) { long start = JVM.monotonicTimeMillis(); RE r1 = new RE("\\[([^\\[\\]])*\\]"); RE r2 = new RE("(\\d{3})(\\d{4})"); long initTime = JVM.monotonicTimeMillis() - start; String number = "5555231119"; boolean m1 = false; boolean m2 = false; start = JVM.monotonicTimeMillis(); for (int i = 0; i < 1000; i++) { m1 = r1.match(number); m2 = r2.match(number); } long matchTime = JVM.monotonicTimeMillis() - start; System.out.println("Matches: " + m1 + " " + m2); System.out.println("REGEX init time: " + initTime); System.out.println("REGEX match time: " + matchTime); }
Source:
<code>private void downloadUpdateData() { try { fileDownloader.setProgressTrackerWindowDescription("Checking for update", "Checking for update..."); fileDownloader.setEnableProgressWindow(false); fileDownloader.downloadFileFromUrlToFile( new URI(UPDATE_SERVER_DATA_NAME), new File(UPDATE_DIRECTORY + File.separator + UPDATE_LOCAL_DATA_NAME)); } catch (URISyntaxException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>log a logger, output place. for below</technical_language>

Target:
private boolean downloadUpdateData() { try { FileDownloader fileDownloader = new FileDownloader( new URI(UPDATE_SERVER_DATA_NAME), new File(UPDATE_DIRECTORY + File.separator + UPDATE_LOCAL_DATA_NAME), a -> {}); return fileDownloader.download(); } catch (URISyntaxException e) { logger.error(ERROR_DOWNLOAD_UPDATE_DATA, e); return false; } }
Source:
<code>public void init(Context context) { <START> this.context = ((SamzaSqlApplicationContext) context.getApplicationTaskContext()).getTranslatorContexts().get(queryId); <END> this.project = (Project) this.context.getRelNode(projectId); this.expr = this.context.getExpressionCompiler().compile(project.getInputs(), project.getProjects()); ContainerContext containerContext = context.getContainerContext(); metricsRegistry = containerContext.getContainerMetricsRegistry(); processingTimeHistogram = new SamzaHistogram(metricsRegistry, logicalOpId, PROCESSING_TIME_HISTOGRAM_NAME); messagesCounter = metricsRegistry.newCounter(logicalOpId, MESSAGES_COUNTER_NAME); messagesCounter.clear(); }</code><technical_language>related changes, change context (member variable) translatorContext ? contexts deal :)</technical_language>

Target:
public void init(Context context) { this.translatorContext = ((SamzaSqlApplicationContext) context.getApplicationTaskContext()).getTranslatorContexts().get(queryId); this.project = (Project) this.translatorContext.getRelNode(projectId); this.expr = this.translatorContext.getExpressionCompiler().compile(project.getInputs(), project.getProjects()); ContainerContext containerContext = context.getContainerContext(); metricsRegistry = containerContext.getContainerMetricsRegistry(); processingTime = new SamzaHistogram(metricsRegistry, logicalOpId, PROCESSING_TIME_NAME); numEvents = metricsRegistry.newCounter(logicalOpId, NUM_EVENTS_NAME); numEvents.clear(); }
Source:
<code>public Account find(final String nameOrEmail) throws OrmException { Matcher m = Pattern.compile("^.* \\(([1-9][0-9]*)\\)$").matcher(nameOrEmail); if (m.matches()) { return byId.get(Account.Id.parse(m.group(1))).getAccount(); } if (nameOrEmail.matches("^[1-9][0-9]*$")) { return byId.get(Account.Id.parse(nameOrEmail)).getAccount(); } Account account = findByNameOrEmail(nameOrEmail); <START> if (account != null) return account; <END> if (nameOrEmail.matches(Account.USER_NAME_PATTERN)) { return findByUserName(nameOrEmail); } return null; }</code><technical_language>Style-nit: put curly braces statement</technical_language>

Target:
public Account find(final String nameOrEmail) throws OrmException { Matcher m = Pattern.compile("^.* \\(([1-9][0-9]*)\\)$").matcher(nameOrEmail); if (m.matches()) { return byId.get(Account.Id.parse(m.group(1))).getAccount(); } if (nameOrEmail.matches("^[1-9][0-9]*$")) { return byId.get(Account.Id.parse(nameOrEmail)).getAccount(); } Account account = findByNameOrEmail(nameOrEmail); if (account != null) { return account; } if (nameOrEmail.matches(Account.USER_NAME_PATTERN)) { return findByUserName(nameOrEmail); } return null; }
Source:
<code>public void run() { setThreadName(); while (isConsuming()) { Optional<MessageBatch> inflight = Optional.empty(); try { logger.debug("Trying to create new batch for subscription {}", subscription.getId()); MessageBatchingResult result = receiver.next(subscription); inflight = of(result.getBatch()); inflight.ifPresent(batch -> { logger.debug("Delivering batch for subscription {}", subscription.getId()); deliver(batch, createRetryer(batch, subscription.getBatchSubscriptionPolicy())); logger.debug("Finished delivering batch for subscription {}", subscription.getId()); offsets.putAllDelivered(batch.getPartitionOffsets()); }); result.getDiscarded().forEach(m -> monitoring.markDiscarded(m, subscription, "too large")); } finally { logger.debug("Cleaning batch for subscription {}", subscription.getId()); inflight.ifPresent(this::clean); } } logger.info("Stopped consumer for subscription {}", subscription.getId()); <START> unsetThreadName(); <END> stoppedLatch.countDown(); }</code><technical_language>shouldnt finally</technical_language>

Target:
public void run() { setThreadName(); try { consume(); } finally { logger.info("Stopped consumer for subscription {}", subscription.getId()); unsetThreadName(); stoppedLatch.countDown(); } }
Source:
<code>public static void mongoGetExperiment(final DB dbs, final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { final Request.Builder requestBuilder = Request.newBuilder(); requestBuilder.setSessionInfo(sessionInfo); requestBuilder.setRequestType(MessageType.DATA_REQUEST); final ItemRequest.Builder build = ItemRequest.newBuilder(); build.setQuery(ItemQuery.EXPERIMENT); final DBRef myDbRef = new DBRef(dbs, EXPERIMENT_COLLECTION, new ObjectId(problemId)); final DBObject cursor = myDbRef.fetch(); if (cursor == null) { <START> LOG.warn("The student has not submitted anything for this problem: " + problemId); <END> return; } final Object sketchId = cursor.get(userId); if (sketchId == null) { LOG.warn("The student has not submitted anything for this problem: " + problemId); return; } LOG.info("SketchId: ", sketchId); build.addItemId(sketchId.toString()); final DataRequest.Builder data = DataRequest.newBuilder(); data.addItems(build); requestBuilder.setOtherData(data.build().toByteString()); try { internalConnections.send(requestBuilder.build(), null, SubmissionClientWebSocket.class); } catch (ConnectionException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); throw new DatabaseAccessException("Failed to send request to submission server for experiment", e); } }</code><technical_language>LOG.debug</technical_language>

Target:
public static void mongoGetExperiment(final DB dbs, final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { final Request.Builder requestBuilder = Request.newBuilder(); requestBuilder.setSessionInfo(sessionInfo); requestBuilder.setRequestType(MessageType.DATA_REQUEST); final ItemRequest.Builder build = ItemRequest.newBuilder(); build.setQuery(ItemQuery.EXPERIMENT); final DBRef myDbRef = new DBRef(dbs, EXPERIMENT_COLLECTION, new ObjectId(problemId)); final DBObject cursor = myDbRef.fetch(); if (cursor == null) { LOG.info("The student has not submitted anything for this problem: {}", problemId); return; } final Object sketchId = cursor.get(userId); if (sketchId == null) { LOG.info("The student has not submitted anything for this problem: {}", problemId); return; } LOG.debug("resultant SketchId: {}", sketchId); build.addItemId(sketchId.toString()); final DataRequest.Builder data = DataRequest.newBuilder(); data.addItems(build); requestBuilder.setOtherData(data.build().toByteString()); try { internalConnections.send(requestBuilder.build(), null, SubmissionClientWebSocket.class); } catch (ConnectionException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); throw new DatabaseAccessException("Failed to send request to submission server for experiment", e); } }
Source:
<code>public TypedProperties(final TypedProperties other) { other.withReadLock(() -> { properties = other.properties == null ? null : new HashMap<>(other.properties); ENCODE_SIZE_FIELD_UPDATER.set(this, other.encodeSize); return null; <START> }); <END> }</code><technical_language>I lazySet here, single writer here...(we are?)</technical_language>

Target:
public TypedProperties(final TypedProperties other) { long lock = other.readLock(); try { properties = other.properties == null ? null : new HashMap<>(other.properties); ENCODE_SIZE_FIELD_UPDATER.lazySet(this, other.encodeSize); } finally { other.unlockRead(lock); } }
Source:
<code>public synchronized void startDiskUsageService() { if (isDiskUsageServiceEnabled) { long delay = config.getDiskUsageServiceInitialDelay(); <START> long period = config.getDiskUsageServiceTasksInterval(); <END> log.info("Starting DiskUsage Service (delay: {}s, period: {}s)", delay, period); duService.runScheduled(delay, period); log.info("DiskUsage Service started."); } else { log.info("DiskUsage Service is disabled."); } }</code><technical_language>See! shoud called periodSecs</technical_language>

Target:
public synchronized void startDiskUsageService() { if (isDiskUsageServiceEnabled) { long delay = config.getDiskUsageServiceInitialDelay(); long period = config.getDiskUsageServiceTasksInterval(); log.info("Starting DiskUsage Service (delay: {}s, period: {}s)", delay, period); duService.start(delay, period); log.info("DiskUsage Service started."); } else { log.info("DiskUsage Service is disabled."); } }
Source:
<code>private DiffConfig(final Config rc) { noPrefix = rc.getBoolean("diff", "noprefix", false); final String renameString = rc.getString("diff", null, "renames"); if ("true".equals(renameString)) renameDetectionType = RenameDetectionType.TRUE; else if ("copy".equals(renameString) || "copies".equals(renameString)) renameDetectionType = RenameDetectionType.COPY; else <START> renameDetectionType = RenameDetectionType.FALSE; <END> renameLimit = rc.getInt("diff", "renamelimit", 200); }</code><technical_language>set FALSE diff.renames = diff.renames = on. match C Git, it? Fortunately getEnum want, honors yes/on aliases for true no/off aliases for false. redefine this way: - add COPIES RenameDetectionType - rc.getEnum("diff", null", "renames", RenameDetectionType.values()) - translate COPIES COPY</technical_language>

Target:
private DiffConfig(final Config rc) { noPrefix = rc.getBoolean("diff", "noprefix", false); final String renameString = rc.getString("diff", null, "renames"); if ("copy".equals(renameString) || "copies".equals(renameString)) renameDetectionType = RenameDetectionType.COPY; else { final Boolean renameBoolean = StringUtils .toBooleanOrNull(renameString); renameDetectionType = Boolean.TRUE.equals(renameBoolean) ? RenameDetectionType.TRUE : RenameDetectionType.FALSE; } renameLimit = rc.getInt("diff", "renamelimit", 200); }
Source:
<code>private static OutermostChildElements getOutermostChildElements(List<Node> children) { Element firstChildElement = null; Element lastChildElement = null; for (Node child : children) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (firstChildElement == null) { firstChildElement = (Element) child; } lastChildElement = (Element) child; } } <START> return new OutermostChildElements(firstChildElement, lastChildElement); <END> }</code><technical_language>cases null is is children ELEMENT. In case, reporting checkChildrenLine. Instead of @Nullable first/last I simply create object if null, return null</technical_language>

Target:
private static Optional<OutermostChildElements> getOutermostChildElements(List<Node> children) { Element firstChildElement = null; Element lastChildElement = null; for (Node child : children) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (firstChildElement == null) { firstChildElement = (Element) child; } lastChildElement = (Element) child; } } if (firstChildElement != null) { return Optional.of(new OutermostChildElements(firstChildElement, lastChildElement)); } return Optional.empty(); }
Source:
<code>protected void _addToBloomFilterScopeOnly(List<ScopeOnlySchemaRecord> records){ _logger.info("Adding records into scope only bloom filter.", records.size()); for(ScopeOnlySchemaRecord record : records) { String key = constructScopeOnlyKey(record.getScope()); <START> bloomFilter.put(key); <END> } }</code><technical_language>this bloomFilterScopeOnly</technical_language>

Target:
protected void _addToBloomFilterScopeOnly(List<ScopeOnlySchemaRecord> records){ _logger.info("Adding records into scope only bloom filter.", records.size()); for(ScopeOnlySchemaRecord record : records) { String key = constructScopeOnlyKey(record.getScope()); bloomFilterScopeOnly.put(key); } }
Source:
<code>public static void beforeClass() throws IOException, CommandFailedException { socketBindingResources = new SocketBindingResources(client, 3, "election-policy_"); SingletonSubsystemOperations.withOperations(operations).prepareCacheContainer(CACHE_CONTAINER_RESOURCE_ADDRESS); operations.add(SINGLETON_POLICY_ADDRESS, Values.of(CACHE_CONTAINER, CACHE_CONTAINER_RESOURCE)).assertSuccess(); operations.add(SINGLETON_POLICY_EDIT_ADDRESS, Values.of(CACHE_CONTAINER, CACHE_CONTAINER_RESOURCE)).assertSuccess(); <START> operations.add(SINGLETON_POLICY_EDIT_ADDRESS.and(ELECTION_POLICY, "simple")).assertSuccess(); <END> }</code><technical_language>I suggest batch operation, takes care of cleaning if of substeps succeed</technical_language>

Target:
public static void beforeClass() throws IOException, CommandFailedException { socketBindingResources = new SocketBindingResources(client, 3, "election-policy_"); singletonOperations.prepareCacheContainer(CACHE_CONTAINER_RESOURCE_ADDRESS); operations.add(SINGLETON_POLICY_ADDRESS, Values.of(CACHE_CONTAINER, CACHE_CONTAINER_RESOURCE)).assertSuccess(); operations.batch(new Batch() .add(SINGLETON_POLICY_EDIT_ADDRESS, Values.of(CACHE_CONTAINER, CACHE_CONTAINER_RESOURCE)) .add(SINGLETON_POLICY_EDIT_ADDRESS.and(ELECTION_POLICY, "simple"))); }
Source:
<code>public Converters(final BeanRepository beanRepository) { converterFactories = new ArrayList<>(); ServiceLoader<ConverterFactory> loader = ServiceLoader.load(ConverterFactory.class); loader.reload(); Iterator<ConverterFactory> iterator = loader.iterator(); while (iterator.hasNext()) { ConverterFactory factory = iterator.next(); LOG.trace("Found converter factory with type identifier {}", factory.getClass(), factory.getTypeIdentifier()); if(!isTypeAlreadyAdded(factory) && !isClassAlreadyAdded(factory)) { factory.init(beanRepository); converterFactories.add(factory); <START> } <END> } }</code><technical_language>exception thrown if a conflict</technical_language>

Target:
public Converters(final BeanRepository beanRepository) { converterFactories = new ArrayList<>(); ServiceLoader<ConverterFactory> loader = ServiceLoader.load(ConverterFactory.class); loader.reload(); Iterator<ConverterFactory> iterator = loader.iterator(); while (iterator.hasNext()) { ConverterFactory factory = iterator.next(); LOG.trace("Found converter factory with type identifier {}", factory.getClass(), factory.getTypeIdentifier()); if(!isTypeAlreadyAdded(factory) && !isAnyConversionTypeAlreadyAdded(factory)) { factory.init(beanRepository); converterFactories.add(factory); }else{ throw new DolphinRuntimeException("Converter of type(s) "+ Arrays.toString(factory.getSupportedTypes().toArray()) + " already added to the factory."); } } }
Source:
<code>private DisjunctionNode(List<QueryTree> children) { <START> this.children.addAll(children); <END> this.children.sort(Comparator.comparingDouble(QueryTree::weight)); }</code><technical_language>Instead of making new ArrayList in class body, move new ArrayList constructor = this.children = new ArrayList<>(children) size time</technical_language>

Target:
private DisjunctionNode(List<QueryTree> children) { this.children = new ArrayList<>(children); this.children.sort(Comparator.comparingDouble(QueryTree::weight)); }
Source:
<code>private static String getShortMid(String text) { if(text.startsWith("www.freebase.com/")) { return text.substring(17).replaceAll("/", "."); } <START> else if(text.startsWith("<LINK_0>")) { <END> return text.substring(27); } else if(text.startsWith("fb:")) { return text.substring(3); } return text; }</code><technical_language>move else if next closing brackets</technical_language>

Target:
private static String getShortMid(String text) { if(text.startsWith(FREEBASE_URI)) { return text.substring(FREEBASE_URI.length()).replaceAll("/", "."); } else if(text.startsWith(RDF_FREEBASE_URI)) { return text.substring(RDF_FREEBASE_URI.length()); } else if(text.startsWith(FREEBASE_SHORT_URI)) { return text.substring(FREEBASE_SHORT_URI.length()); } return text; }
Source:
<code>public void assertDoesNotContainIgnoringCase(AssertionInfo info, CharSequence actual, CharSequence... values) { doCommonCheckForCharSequence(info, actual, values); Set<CharSequence> foundSequences = new LinkedHashSet<>(); for (CharSequence sequence : values) { if (actual.toString().toLowerCase().contains(sequence.toString().toLowerCase())) foundSequences.add(sequence); <START> } <END> if (foundSequences.isEmpty()) return; if (foundSequences.size() == 1 && values.length == 1) { throw failures.failure(info, shouldNotContainIgnoringCase(actual, values[0])); } throw failures.failure(info, shouldNotContainIgnoringCase(actual, values, foundSequences)); }</code><technical_language>prefer functional style like: java String actualLowerCase = actual.toString().toLowerCase(); Set<CharSequence> foundValues = stream(values).filter(value -> actualLowerCase.contains(value.toString().toLowerCase())) .collect(toCollection(LinkedHashSet::new));</technical_language>

Target:
public void assertDoesNotContainIgnoringCase(AssertionInfo info, CharSequence actual, CharSequence... values) { doCommonCheckForCharSequence(info, actual, values); String actualLowerCase = actual.toString().toLowerCase(); Set<CharSequence> foundValues = stream(values).filter(value -> actualLowerCase.contains(value.toString().toLowerCase())) .collect(toCollection(LinkedHashSet::new)); if (foundValues.isEmpty()) return; if (foundValues.size() == 1 && values.length == 1) { throw failures.failure(info, shouldNotContainIgnoringCase(actual, values[0])); } throw failures.failure(info, shouldNotContainIgnoringCase(actual, values, foundValues)); }
Source:
<code>public TopicStatus(String topic, String connector, int task, long discoverTimestamp) { this.topic = topic; <START> this.connector = connector; <END> this.task = task; this.discoverTimestamp = discoverTimestamp; }</code><technical_language>ensuring topic connector names null: this.topic = Objects.requireNonNull(topic); this.connector = Objects.requireNonNull(connector);</technical_language>

Target:
public TopicStatus(String topic, String connector, int task, long discoverTimestamp) { this.topic = Objects.requireNonNull(topic); this.connector = Objects.requireNonNull(connector); this.task = task; this.discoverTimestamp = discoverTimestamp; }
Source:
<code>private void applyHighlighting(SolrQuery query) { if (highlightParams == null) { return; } query.setHighlight(true); for (Map.Entry<String, String> highlightParam : highlightParams.getParams().entrySet()) { query.set(highlightParam.getKey(), highlightParam.getValue()); } for (HighlightingFieldParams highlightFieldParams : highlightParams.getFieldsParams()) { query.addHighlightField(highlightFieldParams.getFieldName()); if (!highlightFieldParams.getHighlightFromFields().isEmpty()) { String highlightQueryString = query.getQuery(); for (String highlightFromField : highlightFieldParams.getHighlightFromFields()) { highlightQueryString = highlightQueryString.replace(highlightFromField + ":", highlightFieldParams.getFieldName() + ":"); } query.set(HighlightParams.Q, highlightQueryString); } <START> <END> for (Map.Entry<String, String> highlightFieldParam : highlightFieldParams.getParams().entrySet()) { query.set("f." + highlightFieldParams.getFieldName() + "." + highlightFieldParam.getKey(), highlightFieldParam.getValue()); } } }</code><technical_language>Divide this code self-describing private methods</technical_language>

Target:
private void applyHighlighting(SolrQuery query) { if (highlightParams == null) { return; } applyGlobalHighlightParams(query); for (HighlightingFieldParams highlightFieldParams : highlightParams.getFieldsParams()) { applyPerFieldHighlightParams(query, highlightFieldParams); } }
Source:
<code>public void testMidAirCollision() throws Exception { <START> if (BugzillaFixture.current() == BugzillaFixture.BUGS_4_4 <END> || BugzillaFixture.current() == BugzillaFixture.BUGS_HEAD) { return; } TaskData data = BugzillaFixture.current().createTask(PrivilegeLevel.USER, null, null); assertNotNull(data); String newCommentText = "BugzillaRepositoryClientTest.testMidAirCollision(): test " + (new Date()).toString(); TaskAttribute attrNewComment = data.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW); attrNewComment.setValue(newCommentText); Set<TaskAttribute> changed = new HashSet<TaskAttribute>(); changed.add(attrNewComment); TaskAttribute attrDeltaTs = data.getRoot().getMappedAttribute(TaskAttribute.DATE_MODIFICATION); attrDeltaTs.setValue("2007-01-01 00:00:00"); changed.add(attrDeltaTs); try { RepositoryResponse response = BugzillaFixture.current().submitTask(data, client); assertNotNull(response); System.err.println("\n\ntestMidAirCollision >>> ResponseKind:" + response.getReposonseKind().toString() + "\n\n"); fail("Mid-air collision expected"); } catch (CoreException e) { assertTrue(e.getStatus().getMessage().indexOf("Mid-air collision occurred while submitting") != -1); return; } fail("Mid-air collision expected"); }</code><technical_language>this test work for versions</technical_language>

Target:
public void testMidAirCollision() throws Exception { TaskData data = BugzillaFixture.current().createTask(PrivilegeLevel.USER, null, null); assertNotNull(data); ITask task = generateLocalTaskAndDownload(data.getTaskId()); ITaskDataWorkingCopy workingCopy = TasksUiPlugin.getTaskDataManager().getWorkingCopy(task); TaskData taskData = workingCopy.getLocalData(); assertNotNull(taskData); String newCommentText = "BugzillaRepositoryClientTest.testMidAirCollision(): test " + (new Date()).toString(); TaskAttribute attrNewComment = data.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW); attrNewComment.setValue(newCommentText); Set<TaskAttribute> changed = new HashSet<TaskAttribute>(); changed.add(attrNewComment); RepositoryResponse response = BugzillaFixture.current().submitTask(data, client); workingCopy = TasksUiPlugin.getTaskDataManager().getWorkingCopy(task); taskData = workingCopy.getLocalData(); assertNotNull(taskData); newCommentText = "BugzillaRepositoryClientTest.testMidAirCollision(): test #### " + (new Date()).toString(); attrNewComment = data.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW); attrNewComment.setValue(newCommentText); changed = new HashSet<TaskAttribute>(); changed.add(attrNewComment); TaskAttribute attrDeltaTs = data.getRoot().getMappedAttribute(TaskAttribute.DATE_MODIFICATION); attrDeltaTs.setValue("2007-01-01 00:00:00"); changed.add(attrDeltaTs); try { response = BugzillaFixture.current().submitTask(data, client); assertNotNull(response); System.err.println("\n\ntestMidAirCollision >>> ResponseKind:" + response.getReposonseKind().toString() + "\n\n"); fail("Mid-air collision expected"); } catch (CoreException e) { assertTrue(e.getStatus().getMessage().indexOf("Mid-air collision occurred while submitting") != -1); return; } fail("Mid-air collision expected"); }
Source:
<code>public void onClick(View v) { if (v == add) { showFilterDialog(new Filter()); } else if (v == enable) { List<Filter> enabledFilters = filterEngine.getEnabledFilters(); List<Filter> allFilters = filterEngine.getAllFilters(); if(enabledFilters.isEmpty()) { <START> for (Filter filter : allFilters) { <END> filter.enabled = true; filterEngine.createOrUpdateFilter(filter); } ((FloatingActionButton) v).setImageResource(R.drawable.ic_clear_white_24dp); } else if (enabledFilters.size() == allFilters.size()) { for(Filter filter : allFilters) { filter.enabled = false; filterEngine.createOrUpdateFilter(filter); } ((FloatingActionButton) v).setImageResource(R.drawable.ic_done_white_24dp); } else { for(Filter filter : enabledFilters) { filter.enabled = false; filterEngine.createOrUpdateFilter(filter); } ((FloatingActionButton) v).setImageResource(R.drawable.ic_done_white_24dp); } theme().applyFabColor(enable); adapter.load(); } }</code><technical_language>do beneficial wrap paramaterize this loop, reduce duplicate code conditionals? if (enabledFilters.isEmpty()) { setFiltersEnabled(allFilters, true) setDrawableTo(R.drawable.ic_clear_white_24dp, v) } else if... setFilters(List<Filter> filters, boolean enabled) set enabled attribute passed in parameter</technical_language>

Target:
public void onClick(View v) { if (v == add) { showFilterDialog(new Filter()); } else if (v == enable) { FloatingActionButton enableButton = (FloatingActionButton) v; List<Filter> enabledFilters = filterEngine.getEnabledFilters(); List<Filter> allFilters = filterEngine.getAllFilters(); if (enabledFilters.isEmpty()) { setFilters(allFilters, true); enableButton.setImageResource(R.drawable.ic_clear_white_24dp); } else if (enabledFilters.size() == allFilters.size()) { setFilters(allFilters, false); enableButton.setImageResource(R.drawable.ic_done_white_24dp); } else { setFilters(enabledFilters, false); enableButton.setImageResource(R.drawable.ic_done_white_24dp); } theme().applyFabColor(enable); adapter.load(); } }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { if (getActivity() == null) { Timber.d("Returning as activity is destroyed!"); return true; } Media m = provider.getMediaAtPosition(pager.getCurrentItem()); switch (item.getItemId()) { case R.id.menu_bookmark_current_image: bookmarkDao.updateBookmark(bookmark); updateBookmarkState(item); return true; case R.id.menu_share_current_image: Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, m.getDisplayTitle() + " \n" + m.getFilePageTitle().getCanonicalUri()); startActivity(Intent.createChooser(shareIntent, "Share image via...")); return true; case R.id.menu_browser_current_image: Intent viewIntent = new Intent(); viewIntent.setAction(ACTION_VIEW); viewIntent.setData(m.getFilePageTitle().getMobileUri()); if (viewIntent.resolveActivity(getActivity().getPackageManager()) != null){ startActivity(viewIntent); } else { Toast toast = Toast.makeText(getContext(), getString(R.string.no_web_browser), LENGTH_SHORT); toast.show(); } return true; case R.id.menu_download_current_image: <START> if (DeviceInfoUtil.getConnectionType(getActivity()) == ConnectionType.NO_INTERNET) { <END> ViewUtil.showShortSnackbar(getView(), R.string.no_internet); return false; } downloadMedia(m); return true; case R.id.menu_set_as_wallpaper: setWallpaper(m); return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>NetworkUtils:isInternetConnectionEstablished</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (getActivity() == null) { Timber.d("Returning as activity is destroyed!"); return true; } Media m = provider.getMediaAtPosition(pager.getCurrentItem()); switch (item.getItemId()) { case R.id.menu_bookmark_current_image: bookmarkDao.updateBookmark(bookmark); updateBookmarkState(item); return true; case R.id.menu_share_current_image: Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, m.getDisplayTitle() + " \n" + m.getFilePageTitle().getCanonicalUri()); startActivity(Intent.createChooser(shareIntent, "Share image via...")); return true; case R.id.menu_browser_current_image: Intent viewIntent = new Intent(); viewIntent.setAction(ACTION_VIEW); viewIntent.setData(m.getFilePageTitle().getMobileUri()); if (viewIntent.resolveActivity(getActivity().getPackageManager()) != null){ startActivity(viewIntent); } else { Toast toast = Toast.makeText(getContext(), getString(R.string.no_web_browser), LENGTH_SHORT); toast.show(); } return true; case R.id.menu_download_current_image: if (!NetworkUtils.isInternetConnectionEstablished(getActivity())) { ViewUtil.showShortSnackbar(getView(), R.string.no_internet); return false; } downloadMedia(m); return true; case R.id.menu_set_as_wallpaper: setWallpaper(m); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public void updateUserExtSourceLastAccess(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { <START> getPerunBl().getAuditer().log(sess, new UserExtSourceUpdated(userExtSource)); <END> getUsersManagerImpl().updateUserExtSourceLastAccess(sess, userExtSource); }</code><technical_language>generate message process is done. prevent unexpected issues</technical_language>

Target:
public void updateUserExtSourceLastAccess(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException { getUsersManagerImpl().updateUserExtSourceLastAccess(sess, userExtSource); getPerunBl().getAuditer().log(sess, new UserExtSourceUpdated(userExtSource)); }
Source:
<code>public static ParquetInputSplit from(org.apache.hadoop.mapred.FileSplit split) throws IOException { <START> return new ParquetInputSplit(split.getPath(), <END> split.getStart(), split.getStart() + split.getLength(), split.getLength(), split.getLocations(), null); }</code><technical_language>need public</technical_language>

Target:
static ParquetInputSplit from(org.apache.hadoop.mapred.FileSplit split) throws IOException { return new ParquetInputSplit(split.getPath(), split.getStart(), split.getStart() + split.getLength(), split.getLength(), split.getLocations(), null); }
Source:
<code>public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException{ if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); } final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA); mantaClient.head(path); Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA); Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires); HttpURLConnection connection = openHttpURLConnection(uri, mantaClient); try { connection.setReadTimeout(3000); connection.setRequestMethod("OPTIONS"); connection.connect(); if (connection.getResponseCode() != 200) { String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()); if (config.getMantaUser().contains(SEPARATOR)) { String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText); throw new SkipException(msg); } Assert.fail(errorText); } <START> String server = StringUtils.substringBefore(connection.getHeaderField("Server"), SEPARATOR); <END> Assert.assertEquals(server, "Manta"); } finally { connection.disconnect(); } }</code><technical_language>Tho this server header / com.joyent.manta.client.MantaClient.SEPARATOR /, I this code needs related them. inclined a literal '/' here. work</technical_language>

Target:
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException{ if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); } final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA); mantaClient.head(path); Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA); Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires); HttpURLConnection connection = openHttpURLConnection(uri, mantaClient); try { connection.setReadTimeout(3000); connection.setRequestMethod("OPTIONS"); connection.connect(); if (connection.getResponseCode() != 200) { String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()); if (config.getMantaUser().contains(SEPARATOR)) { String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText); throw new SkipException(msg); } Assert.fail(errorText); } String server = StringUtils.substringBefore(connection.getHeaderField("Server"), "/"); Assert.assertEquals(server, "Manta"); } finally { connection.disconnect(); } }
Source:
<code>private static void elideAcceptQuery(RequestScope requestScope, User opaqueUser, Optional<MultivaluedMap<String, String>> queryParams, String path) { if (requestScope.getElideSettings() != null) { final QueryLogger ql = requestScope.getElideSettings().getQueryLogger(); if (opaqueUser == null) { ql.acceptQuery(UUID.fromString(requestScope.getRequestId()), <START> null, <END> requestScope.getHeaders(), requestScope.getApiVersion(), queryParams, path); } else { ql.acceptQuery(UUID.fromString(requestScope.getRequestId()), opaqueUser.getPrincipal(), requestScope.getHeaders(), requestScope.getApiVersion(), queryParams, path); } } }</code><technical_language>Instead of defining this block twice, do logic check opaqueUser save user principal (or null) in a local variable</technical_language>

Target:
private static void elideAcceptQuery(RequestScope requestScope, User opaqueUser, Optional<MultivaluedMap<String, String>> queryParams, String path) { final QueryLogger ql = requestScope.getElideSettings().getQueryLogger(); Principal user = opaqueUser == null ? null : opaqueUser.getPrincipal(); ql.acceptQuery(requestScope.getRequestId(), user, requestScope.getHeaders(), requestScope.getApiVersion(), queryParams, path); }
Source:
<code>public void setUp() throws Exception { <START> dbFacadeMock = mock(DbFacade.class); <END> storagePoolDaoMock = mock(StoragePoolDAO.class); vmNicDaoMock = mock(VmNicDao.class); macPoolDaoMock = mock(MacPoolDao.class); DbFacadeLocator.setDbFacade(dbFacadeMock); when(dbFacadeMock.getStoragePoolDao()).thenReturn(storagePoolDaoMock); when(dbFacadeMock.getVmNicDao()).thenReturn(vmNicDaoMock); when(dbFacadeMock.getMacPoolDao()).thenReturn(macPoolDaoMock); macPool = createMacPool("00:1a:4a:15:c0:00", "00:1a:4a:15:c0:ff"); storagePool = createStoragePool(macPool); vmNic = createVmNic(); }</code><technical_language>@Mock annotation for mocks achieve cleaner code</technical_language>

Target:
public void setUp() throws Exception { DbFacadeLocator.setDbFacade(dbFacadeMock); when(dbFacadeMock.getStoragePoolDao()).thenReturn(storagePoolDaoMock); when(dbFacadeMock.getVmNicDao()).thenReturn(vmNicDaoMock); when(dbFacadeMock.getMacPoolDao()).thenReturn(macPoolDaoMock); macFrom = "00:1a:4a:15:c0:00"; macTo = "00:1a:4a:15:c0:ff"; macPool = createMacPool(macFrom, macTo); storagePool = createStoragePool(macPool); vmNic = createVmNic(); }
Source:
<code>public static AuthorList parse(final String authors) { Objects.requireNonNull(authors); <START> if (!AUTHOR_CACHE.containsKey(authors)) { <END> AuthorListParser parser = new AuthorListParser(); AuthorList authorList = parser.parse(authors); authorList.authorsUnformatted = new String(authors); AUTHOR_CACHE.put(authors, authorList); } return AUTHOR_CACHE.get(authors); }</code><technical_language>In case cache contains author string, new code search for occurrence: in containsKey in get. Performance wise get a if (...==null) check</technical_language>

Target:
public static AuthorList parse(final String authors) { Objects.requireNonNull(authors); AuthorList authorList = AUTHOR_CACHE.get(authors); if (authorList == null) { AuthorListParser parser = new AuthorListParser(); authorList = parser.parse(authors); AUTHOR_CACHE.put(authors, authorList); } return authorList; }
Source:
<code>public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { <START> bugzillaClient.authenticate(null); <END> } catch (CoreException e) { e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; }</code><technical_language>call authenticate logging out. Also, pass monitor</technical_language>

Target:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { bugzillaClient.authenticate(monitor); } catch (CoreException e) { e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; }
Source:
<code>protected boolean isStorageDomainTypeCorrect(StorageDomain storageDomain) { <START> if (storageDomain.getStorageDomainType() != StorageDomainType.ISO <END> && storageDomain.getStorageDomainType() != StorageDomainType.ImportExport && storageDomain.isLocal() != getStoragePool().isLocal()) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ATTACH_STORAGE_DOMAIN_STORAGE_TYPE_NOT_MATCH); return false; } return true; }</code><technical_language>Please isStorageDomainOfTypeIsoOrExport</technical_language>

Target:
protected boolean isStorageDomainTypeCorrect(StorageDomain storageDomain) { if (!isStorageDomainOfTypeIsoOrExport(storageDomain) && storageDomain.isLocal() != getStoragePool().isLocal()) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ATTACH_STORAGE_DOMAIN_STORAGE_TYPE_NOT_MATCH); return false; } return true; }
Source:
<code>public void BotTurn() { int size = tiles.size(); int mode = (int) Math.sqrt(size); Random rand = new Random(); if (GameState.getBotMode() == BOT_ON) { int <START> l = <END> rand.nextInt(mode) + 0; int z = rand.nextInt(mode) + 0; while (massiveTiles[l][z].isOpen()) { l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; } firstselected = massiveTiles[l][z]; firstselected.open(() -> { }); l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; while (massiveTiles[l][z].isOpen() || firstselected.equals(massiveTiles[l][z])) { l = rand.nextInt(mode) + 0; z = rand.nextInt(mode) + 0; } secondselected = massiveTiles[l][z]; secondselected.openBot(() -> { }); if (!firstselected.text.getText().equals(secondselected.text.getText())) { firstselected.waitBeforeClose(); secondselected.waitBeforeClose(); } else { firstselected.setOpen(); secondselected.setOpen(); } GameState.setBotMode(BOT_OFF); firstselected = null; secondselected = null; } }</code><technical_language>good name</technical_language>

Target:
public void BotTurn() { int size = tiles.size(); int mode = (int) Math.sqrt(size); Random rand = new Random(); if (GameState.getBotMode() == BOT_ON) { int i = rand.nextInt(mode) + 0; int j = rand.nextInt(mode) + 0; while (arrayOfTiles[i][j].isOpen()) { i = rand.nextInt(mode) + 0; j = rand.nextInt(mode) + 0; } firstselected = arrayOfTiles[i][j]; firstselected.open(() -> { }); i = rand.nextInt(mode) + 0; j = rand.nextInt(mode) + 0; while (arrayOfTiles[i][j].isOpen() || firstselected.equals(arrayOfTiles[i][j])) { i = rand.nextInt(mode) + 0; j = rand.nextInt(mode) + 0; } secondselected = arrayOfTiles[i][j]; secondselected.openBot(() -> { }); if (!firstselected.text.getText().equals(secondselected.text.getText())) { firstselected.waitBeforeClose(); secondselected.waitBeforeClose(); } else { firstselected.setOpen(); secondselected.setOpen(); } GameState.setBotMode(BOT_OFF); firstselected = null; secondselected = null; } }
Source:
<code>public void testAll() { StudentProfilePageData sppd = initializeFirstData(); testProfileEditBox(sppd.getProfileEditBox()); testUploadPhotoModal(sppd.getUploadPhotoModal()); sppd = initializeSecondData(); testProfileEditBox(sppd.getProfileEditBox()); testUploadPhotoModal(sppd.getUploadPhotoModal()); <START> } <END></code><technical_language>split separate tests</technical_language>

Target:
public void testAll() { testWithPictureKeyAndNoNullFields(); testWithNoPictureKeyAndNullFields(); }
Source:
<code>private void setValidMongoOnlyWithIntentResult(){ <START> jsonConfig = "{\"mongo\":{\"uri\":\"mongodb://user:pass@test.com/cgm_data\"}}"; <END> fakeActivityResult(); }</code><technical_language>single quotes string, escape them, e.g. "{'key': 'value'}"</technical_language>

Target:
private void setValidMongoOnlyWithIntentResult(){ jsonConfig = "{'mongo':{'uri':'mongodb://user:pass@test.com/cgm_data'}}"; fakeActivityResult(); }