auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>OnmsThreshdDao(JsonStore jsonStore, File configFile) { super(jsonStore); Objects.requireNonNull(configFile); extContainer = new ConfigReloadContainer.Builder<>(ThreshdConfiguration.class) .withMerger((source, target) -> { if (source == null && target == null) { return new ThreshdConfiguration(); } else if (source == null) { return target; } else if (target == null) { return source; } target.getPackages().addAll(source.getPackages()); <START> target.getThresholders().addAll(source.getThresholders()); <END> getLargestThreads(source.getThreads(), target.getThreads()) .ifPresent(target::setThreads); return target; }) .build(); saveableConfigContainer = new FileSystemSaveableConfigContainer<>(ThreshdConfiguration.class, "threshd-configuration", Collections.singleton(this::fileSystemConfigUpdated), configFile); reload(); }</code><technical_language>Thresholders threads removed</technical_language>

Target:
OnmsThreshdDao(JsonStore jsonStore, File configFile) { super(jsonStore); Objects.requireNonNull(configFile); extContainer = new ConfigReloadContainer.Builder<>(ThreshdConfiguration.class) .withFolder((accumulator, next) -> accumulator.getPackages().addAll(next.getPackages())) .build(); saveableConfigContainer = new FileSystemSaveableConfigContainer<>(ThreshdConfiguration.class, "threshd-configuration", Collections.singleton(this::fileSystemConfigUpdated), configFile); reload(); }
Source:
<code>public void delete() throws IOException { synchronized (documentStores) { DocumentStore ds = documentStores.remove(location); if (ds != null) { ((DatabaseImpl)database).close(); ((IndexManagerImpl)query).close(); } if (!location.exists()) { String msg = String.format( "Datastore %s doesn't exist on disk", location <START> ); <END> throw new IOException(msg); } else { FileUtils.deleteDirectory(location); eventBus.post(new DatabaseDeleted(databaseName)); } } }</code><technical_language>output a log message</technical_language>

Target:
public void delete() throws IOException { try { this.close(); } catch (Exception e) { logger.log(Level.WARNING, "Caught exception whilst closing DocumentStore in delete()", e); } if (!location.exists()) { String msg = String.format("Datastore %s doesn't exist on disk", location); logger.warning(msg); throw new IOException(msg); } else { FileUtils.deleteDirectory(location); eventBus.post(new DatabaseDeleted(databaseName)); } }
Source:
<code>private String extractPropertyName(String key) { int beginIndex = key.indexOf("."); int endIndex = key.indexOf(".prompt"); if(endIndex != -1){ return key.substring(beginIndex + 1, endIndex); } else { <START> endIndex = key.indexOf(".default"); <END> if (endIndex != -1) { return key.substring(beginIndex + 1, endIndex); } } return key.substring(beginIndex + 1); }</code><technical_language>default key = StringUtils.stripStart(key, "property."); if (key.endsWith(".default")) { key = StringUtils.stripEnd(key, ".default") } else { key = StringUtils.stripEnd(key, ".prompt"); }</technical_language>

Target:
private String extractPropertyName(String key) { int beginIndex = key.indexOf("."); if(key.endsWith(".default")){ return key.substring(beginIndex+1, key.length()-8); } else if(key.endsWith(".prompt")){ return key.substring(beginIndex+1, key.length()-7); } else { return key.substring(beginIndex+1); } }
Source:
<code>public void handle(String input, Console console) { String[] args = input.split(" "); if (args.length != 3) { console.warn("Usage: equipWeapon moduleName:gunName slotNumber"); return; } if (!isInt(args[2])) { console.warn("slotNumber must be a valid number!"); return; } int slot = Integer.parseInt(args[2]); SolItem gunItem = getGun(args[1]); if (slot < 1 || slot > 2) { console.warn("Available slots: 1, 2"); return; } if (gunItem == null) { console.warn("Could not find " + args[1]); return; } SolShip ship = hero.getShip(); <START> boolean canEquip = ship.maybeEquip(game, gunItem, slot == 2 ? true : false, false); <END> if (!canEquip) { console.warn("Cannot equip this weapon in that slot!"); return; } ItemContainer itemContainer = ship.getItemContainer(); boolean alreadyExists = false; for (List<SolItem> group : itemContainer) { if (group.get(0).getCode().equals(gunItem.getCode())) { gunItem = group.get(0); alreadyExists = true; break; } } if (!alreadyExists) { ship.getItemContainer().add(gunItem); } Gun gun = (Gun) gunItem; gun.ammo = gun.config.clipConf.size; ship.maybeEquip(game, gunItem, slot == 2 ? true : false, true); }</code><technical_language>suggestion boolean canEquip = ship.maybeEquip(game, gunItem, slot == 2, false);</technical_language>

Target:
public void handle(String input, Console console) { String[] args = input.split(" "); SolShip ship = hero.getShip(); if (args.length != 3) { console.warn("Usage: equipWeapon moduleName:gunName slotNumber"); console.warn("Available slots: " + (ship.getHull().getGunMount(false) != null ? "1" : "<none>") + (ship.getHull().getGunMount(true) != null ? ", 2" : "")); return; } if (!SolMath.isInt(args[2])) { console.warn("slotNumber must be a valid number!"); return; } int slot = Integer.parseInt(args[2]); Optional<SolItem> gunItem = Optional.ofNullable(getGun(args[1])); if (!gunItem.isPresent()) { console.warn("Could not find gun " + args[1]); return; } boolean canEquip = ship.maybeEquip(game, gunItem.get(), slot == 2, false); if (!canEquip) { console.warn("Cannot equip this weapon in that slot!"); return; } ItemContainer itemContainer = ship.getItemContainer(); boolean alreadyExists = false; for (List<SolItem> group : itemContainer) { if (group.get(0).getCode().equals(gunItem.get().getCode())) { gunItem = Optional.of(group.get(0)); alreadyExists = true; break; } } if (!alreadyExists) { ship.getItemContainer().add(gunItem.get()); } Gun gun = (Gun) gunItem.get(); gun.ammo = gun.config.clipConf.size; ship.maybeEquip(game, gun, slot == 2, true); }
Source:
<code>public void init() throws UserStoreException { try { claimConfig = FileBasedClaimBuilder.buildClaimMappingsFromConfigFile(); } catch (IOException e) { <START> log.error("Could not find claim configuration file ", e); <END> } catch (XMLStreamException e) { log.error("Error while parsing claim configuration file ", e); } }</code><technical_language>this exception is thrown upwards</technical_language>

Target:
public void init() throws UserStoreException { try { claimConfig = FileBasedClaimBuilder.buildClaimMappingsFromConfigFile(); } catch (IOException e) { throw new UserStoreException("Could not find claim configuration file", e); } catch (XMLStreamException e) { throw new UserStoreException("Error while parsing claim configuration file", e); } }
Source:
<code><START> public KiePMMLDroolsModelFactoryUtils() { <END> }</code><technical_language>this avoid create instances? public constructor</technical_language>

Target:
private KiePMMLDroolsModelFactoryUtils() { }
Source:
<code>public static int getSecondaryColor(Context context, String primary) { if (primary == null) return Color.parseColor("#81B4DE"); int[] COLORS = context.getResources().getIntArray(R.array.colors); int[] SECONDARY_COLORS = context.getResources().getIntArray(R.array.secondary_colors); int color = Color.parseColor(primary); int foundColor = -1; <START> for (int i = 0; i < COLORS.length; i++) { if (COLORS[i] == color) foundColor = i; } <END> if (foundColor == -1) return Color.parseColor("#81B4DE"); return SECONDARY_COLORS[foundColor]; }</code><technical_language>break if statements multiple lines? (same for loop)</technical_language>

Target:
public static int getSecondaryColor(Context context, String primary) { if (primary == null) { return Color.parseColor("#81B4DE"); } int[] COLORS = context.getResources().getIntArray(R.array.colors); int[] SECONDARY_COLORS = context.getResources().getIntArray(R.array.secondary_colors); int color = Color.parseColor(primary); int foundColor = -1; for (int i = 0; i < COLORS.length; i++) { if (COLORS[i] == color) foundColor = i; } if (foundColor == -1) { return Color.parseColor("#81B4DE"); } return SECONDARY_COLORS[foundColor]; }
Source:
<code>public void startTrigger(final FlowTrigger flowTrigger, final String flowId, final int flowVersion, final String submitUser, final Project project) { this.executorService.submit(() -> { final TriggerInstance triggerInst = createTriggerInstance(flowTrigger, flowId, flowVersion, submitUser, project); logger.info( <START> String.format("Starting the flow trigger %s[execId %s] by %s", flowTrigger, triggerInst <END> .getId(), submitUser)); this.triggerProcessor.processNewInstance(triggerInst); if (triggerInst.getStatus() == Status.CANCELLED) { logger.info(String.format("Trigger instance[id: %s] is cancelled since all dependency " + "instances fail to be created", triggerInst.getId())); this.triggerProcessor.processTermination(triggerInst); } else if (triggerInst.getStatus() == Status.CANCELLING) { logger.info( String.format("Trigger instance[id: %s] is being cancelled since some dependency " + "instances fail to be created", triggerInst.getId())); addToRunningListAndCancel(triggerInst); } else if (triggerInst.getStatus() == Status.SUCCEEDED) { this.triggerProcessor.processSucceed(triggerInst); } else { addToRunningListAndScheduleKill(triggerInst, triggerInst.getFlowTrigger() .getMaxWaitDuration(), CancellationCause.TIMEOUT); } }); }</code><technical_language>triggerInst.getId() return trigger instance id, execution id</technical_language>

Target:
public void startTrigger(final FlowTrigger flowTrigger, final String flowId, final int flowVersion, final String submitUser, final Project project) { this.executorService.submit(() -> { final TriggerInstance triggerInst = createTriggerInstance(flowTrigger, flowId, flowVersion, submitUser, project); logger.info( String.format("Starting the flow trigger %s[trigger instance id: %s] by %s", flowTrigger, triggerInst.getId(), submitUser)); this.triggerProcessor.processNewInstance(triggerInst); if (triggerInst.getStatus() == Status.CANCELLED) { logger.info(String.format("Trigger instance[id: %s] is cancelled since all dependency " + "instances fail to be created", triggerInst.getId())); this.triggerProcessor.processTermination(triggerInst); } else if (triggerInst.getStatus() == Status.CANCELLING) { logger.info( String.format("Trigger instance[id: %s] is being cancelled since some dependency " + "instances fail to be created", triggerInst.getId())); addToRunningListAndCancel(triggerInst); } else if (triggerInst.getStatus() == Status.SUCCEEDED) { this.triggerProcessor.processSucceed(triggerInst); } else { addToRunningListAndScheduleKill(triggerInst, triggerInst.getFlowTrigger() .getMaxWaitDuration(), CancellationCause.TIMEOUT); } }); }
Source:
<code>public List<RichUser> call(ApiCaller ac, Deserializer parms) throws PerunException { String roleName = parms.readString("role"); return cz.metacentrum.perun.core.api.AuthzResolver.getRichAdmins(ac.getSession(), <START> parms.readInt("complementaryObjectId"), <END> parms.readString("complementaryObjectName"), parms.readList("specificAttributes", String.class), roleName, parms.readBoolean("onlyDirectAdmins"), parms.readBoolean("allUserAttributes")); }</code><technical_language>check if role exists in database</technical_language>

Target:
public List<String> call(ApiCaller ac, Deserializer parms) throws PerunException { List<String> roles = cz.metacentrum.perun.core.api.AuthzResolver.getPrincipalRoleNames(ac.getSession()); roles.replaceAll(String::toLowerCase); return roles; }
Source:
<code>public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final Socket socket = Mockito.mock(Socket.class); final String requests = Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", "Hello World!" ); <START> final InputStream input = new ByteArrayInputStream(requests.getBytes()); <END> final OutputStream output = new ByteArrayOutputStream(); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getPort()).thenReturn(0); Mockito.when(socket.getInputStream()).thenReturn(input); Mockito.when(socket.getOutputStream()).thenReturn(output); new BkBasic(new TkText(text)).accept(socket); MatcherAssert.assertThat( socket.getOutputStream().toString(), Matchers.containsString(text) ); }</code><technical_language>@danff get rid time variable</technical_language>

Target:
public void acceptsNoContentLengthOnClosedConnection() throws Exception { final String text = "Close Test"; final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText(text)).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "Connection: Close", "", "Hello World!" ).getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString(text) ); }
Source:
<code>public JsonDocument readNextRecord(BufferedReader bRdr) throws IOException { <START> if (node == null || i >= node.size()) { <END> String line; while ((line = bRdr.readLine()) != null) { JsonNode json = new JsonFactory().createParser(line).readValueAsTree(); id = json.get("id").asText(); contents = json.get("contents").asText(); return this; } } else { JsonNode json = node.get(i); id = json.get("id").asText(); contents = json.get("contents").asText(); i++; return this; } return null; }</code><technical_language>condition i >= node.size()</technical_language>

Target:
public JsonDocument readNextRecord(BufferedReader bRdr) throws IOException { if (node == null) { String line; while ((line = bRdr.readLine()) != null) { JsonNode json = new JsonFactory().createParser(line).readValueAsTree(); id = json.get("id").asText(); contents = json.get("contents").asText(); return this; } } else if (i < node.size()) { JsonNode json = node.get(i); id = json.get("id").asText(); contents = json.get("contents").asText(); i++; return this; } return null; }
Source:
<code>public void interceptor() { MessageChannel channel = context.getBean("channelWithInterceptor", MessageChannel.class); List<?> interceptorList = TestUtils.getPropertyValue(channel, "interceptors.interceptors", List.class); assertEquals(1, interceptorList.size()); assertEquals(TestInterceptor.class, interceptorList.get(0).getClass()); assertEquals(Integer.MAX_VALUE, TestUtils.getPropertyValue( TestUtils.getPropertyValue(channel, "dispatcher"), "maxSubscribers", Integer.class).intValue()); channel = context.getBean("pubSub", MessageChannel.class); Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); <START> assertNotSame(mbf, TestUtils.getPropertyValue(channel, "dispatcher.messageBuilderFactory")); <END> assertSame(mbf, TestUtils.getPropertyValue(channel, "container.messageListener.messageBuilderFactory")); assertTrue(TestUtils.getPropertyValue(channel, "container.missingQueuesFatal", Boolean.class)); assertFalse(TestUtils.getPropertyValue(channel, "container.transactional", Boolean.class)); assertFalse(TestUtils.getPropertyValue(channel, "amqpTemplate.transactional", Boolean.class)); }</code><technical_language>This sense me; goal global MBF for **all** message builds</technical_language>

Target:
public void interceptor() { MessageChannel channel = context.getBean("channelWithInterceptor", MessageChannel.class); List<?> interceptorList = TestUtils.getPropertyValue(channel, "interceptors.interceptors", List.class); assertEquals(1, interceptorList.size()); assertEquals(TestInterceptor.class, interceptorList.get(0).getClass()); assertEquals(Integer.MAX_VALUE, TestUtils.getPropertyValue( TestUtils.getPropertyValue(channel, "dispatcher"), "maxSubscribers", Integer.class).intValue()); channel = context.getBean("pubSub", MessageChannel.class); Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); assertSame(mbf, TestUtils.getPropertyValue(channel, "container.messageListener.messageBuilderFactory")); assertTrue(TestUtils.getPropertyValue(channel, "container.missingQueuesFatal", Boolean.class)); assertFalse(TestUtils.getPropertyValue(channel, "container.transactional", Boolean.class)); assertFalse(TestUtils.getPropertyValue(channel, "amqpTemplate.transactional", Boolean.class)); }
Source:
<code><START> protected void waitForLiveServerToReload(int timeout) { <END> long start = System.currentTimeMillis(); ModelNode operation = new ModelNode(); operation.get(OP_ADDR).setEmptyList(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(NAME).set("server-state"); while (System.currentTimeMillis() - start < timeout) { recreateClient(); ModelControllerClient liveClient = client.getControllerClient(); try { ModelNode result = liveClient.execute(operation); if ("running".equals(result.get(RESULT).asString())) { return; } } catch (IOException e) { } try { Thread.sleep(100); } catch (InterruptedException e) { } } fail("Live Server did not reload in the imparted time."); }</code><technical_language>org.jboss.as.test.integration.management.util.ServerReload, ported full core</technical_language>

Target:
void waitForLiveServerToReload(int timeout) { long start = System.currentTimeMillis(); ModelNode operation = new ModelNode(); operation.get(OP_ADDR).setEmptyList(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(NAME).set("server-state"); while (System.currentTimeMillis() - start < timeout) { recreateClient(); ModelControllerClient liveClient = client.getControllerClient(); try { ModelNode result = liveClient.execute(operation); if ("running".equals(result.get(RESULT).asString())) { return; } } catch (IOException e) { } try { Thread.sleep(100); } catch (InterruptedException e) { } } fail("Live Server did not reload in the imparted time."); }
Source:
<code>public void init() { get( "/user", (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); res.type(APPLICATION_JSON); return getSubjectAttributes(subject); }, util::getJson); put( "/user/preferences", APPLICATION_JSON, (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); if (subject.isGuest()) { res.status(401); return ImmutableMap.of("message", "Guest cannot save preferences."); } Map<String, Object> preferences = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE); if (preferences == null) { preferences = new HashMap<>(); } setUserPreferences(subject, preferences); return preferences; }, util::getJson); put( "/user/notifications", APPLICATION_JSON, (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); if (subject.isGuest()) { res.status(401); return ImmutableMap.of("message", "Guest cannot save notifications."); } Map<String, List<String>> notification = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE); <START> deleteNotifications(notification.get("alerts")); <END> return ""; }, util::getJson); exception(EntityTooLargeException.class, util::handleEntityTooLargeException); exception(IOException.class, util::handleIOException); exception(RuntimeException.class, util::handleRuntimeException); }</code><technical_language>this delete method instead</technical_language>

Target:
public void init() { get( "/user", (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); res.type(APPLICATION_JSON); return getSubjectAttributes(subject); }, util::getJson); put( "/user/preferences", APPLICATION_JSON, (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); if (subject.isGuest()) { res.status(401); return ImmutableMap.of("message", "Guest cannot save preferences."); } Map<String, Object> preferences = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE); if (preferences == null) { preferences = new HashMap<>(); } setUserPreferences(subject, preferences); return preferences; }, util::getJson); put( "/user/notifications", APPLICATION_JSON, (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); if (subject.isGuest()) { res.status(401); return ImmutableMap.of("message", "Guest cannot save notifications."); } Map<String, Object> notification = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE); addUserNotification(subject, notification); return ""; }, util::getJson); delete( "/user/notifications", APPLICATION_JSON, (req, res) -> { Subject subject = (Subject) SecurityUtils.getSubject(); if (subject.isGuest()) { res.status(401); return ImmutableMap.of("message", "Guest cannot save notifications."); } Map<String, List<String>> notification = GSON.fromJson(util.safeGetBody(req), MAP_STRING_TO_OBJECT_TYPE); deleteNotifications(notification.get("alerts")); return ""; }, util::getJson); exception(EntityTooLargeException.class, util::handleEntityTooLargeException); exception(IOException.class, util::handleIOException); exception(RuntimeException.class, util::handleRuntimeException); }
Source:
<code>public QueryResponse getFilesByStudy(@PathVariable("study") String study, @RequestParam("species") String species, HttpServletResponse response) throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); QueryResult queryResult = Utils.buildQueryResult(variantSourceEntityRepository.findByStudyId(study)); if (queryResult.getResult().size() == 0) { queryResult = Utils.buildQueryResult(Collections.emptyList()); queryResult.setErrorMsg("Study identifier not found"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return setQueryResponse(queryResult); } VariantSourceEntity variantSourceEntity = (VariantSourceEntity) queryResult.getResult().get(0); QueryResult finalResult <START> = Utils.buildQueryResult(variantSourceEntityRepository.findByStudyId(variantSourceEntity.getStudyId())); <END> finalResult.setDbTime(finalResult.getDbTime() - queryResult.getDbTime()); return setQueryResponse(finalResult); }</code><technical_language>I understand this query is needed. return queryResult line 76? Ah, ok thinking a bit, I code a findStudyNameOrStudyId, now, variantSourceEntityRepository.findByStudyId search in sid field. need add a variantSourceEntityRepository.findByStudyIdOrStudyName(String studyId, String studyName) call (line 76) findByStudyId(study, study). Renaming study studyIdOrName improve clarity</technical_language>

Target:
public QueryResponse getFilesByStudy(@PathVariable("study") String study, @RequestParam("species") String species, HttpServletResponse response) throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); List variantSourceEntityList = variantSourceEntityRepository.findByStudyIdOrStudyName(study, study); QueryResult queryResult; if (variantSourceEntityList.size() == 0) { queryResult = Utils.buildQueryResult(Collections.emptyList()); queryResult.setErrorMsg("Study identifier not found"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return setQueryResponse(queryResult); } queryResult = Utils.buildQueryResult(variantSourceEntityList); return setQueryResponse(queryResult); }
Source:
<code>public void onBindViewHolder(final RvViewHolder holder, int position) { final int pos=position; holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { holder.onClick(v); selection[pos]=!selection[pos]; if(selection[pos]){ holder.cardView.setBackgroundColor(selectionColor); }else{ holder.cardView.setBackgroundColor(backgroundColor); } } }); if(layoutType==0){ String first =firstItem[position]; holder.textViewFirst.setText(first); }else if(layoutType==1){ String first =firstItem[position]; String second=secondItem[position]; holder.textViewFirst.setText(first); <START> holder.textViewSecond.setText(second); <END> }else if(layoutType==2){ String first =firstItem[position]; String second=secondItem[position]; holder.textViewFirst.setText(first); holder.textViewSecond.setText(second); }else if(layoutType==3){ String first =firstItem[position]; Drawable drawable = images.get(position); ViewUtil.setImage(holder.imageVieww, drawable); holder.textViewFirst.setText(first); } else if(layoutType==4){ String first =firstItem[position]; String second=secondItem[position]; Drawable drawable = images.get(position); ViewUtil.setImage(holder.imageVieww, drawable); holder.textViewFirst.setText(first); holder.textViewSecond.setText(second); } }</code><technical_language>necessary for text strings separate text views for layout side-by-side. in testing this sorts of unexpected formatting behavior. fine text view setText **_first + ' ' + second_**</technical_language>

Target:
public void onBindViewHolder(final RvViewHolder holder, int position) { final int pos=position; holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { holder.onClick(v); selection[pos]=!selection[pos]; if(selection[pos]){ holder.cardView.setBackgroundColor(selectionColor); }else{ holder.cardView.setBackgroundColor(backgroundColor); } } }); if(layoutType==Component.LISTVIEW_LAYOUT_SINGLE_TEXT){ String first =firstItem[position]; holder.textViewFirst.setText(first); }else if(layoutType==Component.LISTVIEW_LAYOUT_TWO_TEXT){ String first =firstItem[position]; String second=secondItem[position]; holder.textViewFirst.setText(first); holder.textViewSecond.setText(second); }else if(layoutType==Component.LISTVIEW_LAYOUT_TWO_TEXT_LINEAR){ String first =firstItem[position]; String second=secondItem[position]; holder.textViewFirst.setText(first); holder.textViewSecond.setText(second); }else if(layoutType==Component.LISTVIEW_LAYOUT_IMAGE_SINGLE_TEXT){ String first =firstItem[position]; Drawable drawable = images.get(position); ViewUtil.setImage(holder.imageVieww, drawable); holder.textViewFirst.setText(first); } else if(layoutType==Component.LISTVIEW_LAYOUT_IMAGE_TWO_TEXT){ String first =firstItem[position]; String second=secondItem[position]; Drawable drawable = images.get(position); ViewUtil.setImage(holder.imageVieww, drawable); holder.textViewFirst.setText(first); holder.textViewSecond.setText(second); } }
Source:
<code>public Object executeCommand(ExtendedExecuteCommandParams extendedExecuteCommandParams) { final Object[] result = new Object[1]; try { List<InitializedLanguageServer> servers = registry .getApplicableLanguageServers(extendedExecuteCommandParams.getFileUri()) .stream() .flatMap(Collection::stream) .collect(Collectors.toList()); <START> OperationUtil.doInParallel( <END> servers, new LSOperation<InitializedLanguageServer, Object>() { @Override public boolean canDo(InitializedLanguageServer element) { return element.getServer().getWorkspaceService() != null; } @Override public CompletableFuture<Object> start(InitializedLanguageServer element) { return element .getServer() .getWorkspaceService() .executeCommand(extendedExecuteCommandParams); } @Override public boolean handleResult(InitializedLanguageServer element, Object response) { result[0] = response; return true; } }, 10_000); return result[0]; } catch (LanguageServerException e) { LOG.error("error executing command", e); throw new JsonRpcException(-27000, e.getMessage()); } }</code><technical_language>doInParallel ask language servers execute command, however, throwing results last. doInSequence()" is want</technical_language>

Target:
public Object executeCommand(ExtendedExecuteCommandParams extendedExecuteCommandParams) { final Object[] result = new Object[1]; try { List<InitializedLanguageServer> servers = registry .getApplicableLanguageServers(extendedExecuteCommandParams.getFileUri()) .stream() .flatMap(Collection::stream) .collect(Collectors.toList()); OperationUtil.doInSequence( servers, new LSOperation<InitializedLanguageServer, Object>() { @Override public boolean canDo(InitializedLanguageServer element) { return element.getServer().getWorkspaceService() != null; } @Override public CompletableFuture<Object> start(InitializedLanguageServer element) { return element .getServer() .getWorkspaceService() .executeCommand(extendedExecuteCommandParams); } @Override public boolean handleResult(InitializedLanguageServer element, Object response) { result[0] = response; return true; } }, 10_000); return result[0]; } catch (LanguageServerException e) { LOG.error("error executing command", e); throw new JsonRpcException(-27000, e.getMessage()); } }
Source:
<code>public void setLastPullCursor(FormStatus fs, String cursor) { lastPullCursorsByFormId.put(fs.getFormId(), cursor); <START> } <END></code><technical_language>form ID formal parameter this method concerned a FormStatus</technical_language>

Target:
public void setLastPullCursor(FormStatus fs, String cursor) { lastPullCursorsByFormId.put(fs.getFormId(), cursor); triggerOnChange(); }
Source:
<code><START> private static boolean isReturnTypeCompletelySubstituted(JavaType resultType, List<TypeVariableJavaType> typeVariables){ <END> if(typeVariables.contains(resultType)) { return false; } if(resultType.isArray()) { return isReturnTypeCompletelySubstituted(((ArrayJavaType) resultType).elementType, typeVariables); } if(resultType instanceof WildCardType) { return isReturnTypeCompletelySubstituted(((WildCardType) resultType).bound, typeVariables); } if(resultType instanceof ParametrizedTypeJavaType) { for (JavaType substitutedType : ((ParametrizedTypeJavaType) resultType).typeSubstitution.substitutedTypes()) { if(!isReturnTypeCompletelySubstituted(substitutedType, typeVariables)) { return false; } } } return true; }</code><technical_language>![MAJOR](<LINK_0> Cyclomatic Complexity of this method "isReturnTypeCompletelySubstituted" is 11 is greater 10 authorized. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
private static boolean isReturnTypeCompletelySubstituted(JavaType resultType, List<TypeVariableJavaType> typeVariables){ if(typeVariables.contains(resultType)) { return false; } if(resultType.isArray()) { return isReturnTypeCompletelySubstituted(((ArrayJavaType) resultType).elementType, typeVariables); } if(resultType.isTagged(JavaType.WILDCARD)) { return isReturnTypeCompletelySubstituted(((WildCardType) resultType).bound, typeVariables); } if(resultType instanceof ParametrizedTypeJavaType) { for (JavaType substitutedType : ((ParametrizedTypeJavaType) resultType).typeSubstitution.substitutedTypes()) { if(!isReturnTypeCompletelySubstituted(substitutedType, typeVariables)) { return false; } } } return true; }
Source:
<code>public void processPacket(EntityPlayer player) { ItemStack book; if (hand == EnumHand.MAIN_HAND) { <START> if (!(player.getHeldItemMainhand().getItem().getClass() == ItemGuideBook.class)) return; <END> book = player.getHeldItemMainhand(); } else { if (!(player.getHeldItemOffhand().getItem().getClass() == ItemGuideBook.class)) return; book = player.getHeldItemOffhand(); } NBTTagCompound nbt = book.getTagCompound(); nbt.setFloat("sliderProgress", sliderProgress); nbt.setInteger("page", page); }</code><technical_language>No. Check item instance registered, class, else. ~~You save registering, though, currently doing.~~ Nevermind, object holder for it</technical_language>

Target:
public void processPacket(EntityPlayer player) { ItemStack book; book = player.getHeldItem(hand); if (book.getItem() != LPItems.itemGuideBook) return; NBTTagCompound nbt = book.getTagCompound(); if(nbt == null) nbt = new NBTTagCompound(); nbt.setFloat("sliderProgress", sliderProgress); nbt.setInteger("page", page); book.setTagCompound(nbt); }
Source:
<code>public Part findReplacement(boolean refit) { if (hasReplacementPart()) { return getReplacementPart(); } return campaign.streamSpareParts() .filter(MissingPart::isAvailableAsReplacement) .reduce(null, (bestPart, part) -> { if (isAcceptableReplacement(part, refit)) { if (bestPart == null) { return part; } else { int bestPartArmor = 0; int currentPartArmor = 0; int bestPartQuantity = 0; int currentPartQuantity = 0; for (Part p : bestPart.getChildParts()) { if (p instanceof BaArmor) { <START> bestPartArmor = ((BaArmor)p).getAmount(); <END> } else { bestPartQuantity++; } } for (Part p : part.getChildParts()) { if (p instanceof BaArmor) { currentPartArmor = ((BaArmor)p).getAmount(); } else { currentPartQuantity++; } } if (currentPartQuantity > bestPartQuantity) { return part; } else if (currentPartArmor > bestPartArmor) { return part; } } } return bestPart; }); }</code><technical_language>suggestion bestPartArmor = ((BaArmor) p).getAmount();</technical_language>

Target:
public Part findReplacement(boolean refit) { if (hasReplacementPart()) { return getReplacementPart(); } return campaign.streamSpareParts() .filter(MissingPart::isAvailableAsReplacement) .reduce(null, (bestPart, part) -> { if (isAcceptableReplacement(part, refit)) { if (bestPart == null) { return part; } else { int bestPartArmor = 0; int currentPartArmor = 0; int bestPartQuantity = 0; int currentPartQuantity = 0; for (Part p : bestPart.getChildParts()) { if (p instanceof BaArmor) { bestPartArmor = ((BaArmor) p).getAmount(); } else { bestPartQuantity++; } } for (Part p : part.getChildParts()) { if (p instanceof BaArmor) { currentPartArmor = ((BaArmor) p).getAmount(); } else { currentPartQuantity++; } } if ((currentPartQuantity > bestPartQuantity) || (currentPartArmor > bestPartArmor)) { return part; } } } return bestPart; }); }
Source:
<code>public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { LaunchConfiguration launchConfigurationRequest = (LaunchConfiguration) postParams.get("launchConfiguration"); Map<String, Object> launchConfigurationMap = Maps.newHashMap(); <START> Map<String, Object> args = Maps.newHashMap(); <END> launchConfigurationMap.put("args", args); launchConfigurationMap.put("type", launchConfigurationRequest.getType().toString()); args.put("loadBalancers", launchConfigurationRequest.getLoadBalancers()); Map<String, Object> server = Maps.newHashMap(); args.put("server", server); server.put("name", launchConfigurationRequest.getServerName()); server.put("imageRef", launchConfigurationRequest.getServerImageRef()); server.put("flavorRef", launchConfigurationRequest.getServerFlavorRef()); server.put("OS-DCF:diskConfig", launchConfigurationRequest.getServerDiskConfig()); server.put("metadata", launchConfigurationRequest.getServerMetadata()); List<Map<String, String>> networks = Lists.newArrayList(); server.put("networks", networks); for(String networkId : launchConfigurationRequest.getNetworks()) { Map<String, String> network = Maps.newHashMap(); network.put("uuid", networkId); networks.add(network); } server.put("personality", launchConfigurationRequest.getPersonalities()); return jsonBinder.bindToRequest(request, launchConfigurationMap); }</code><technical_language>Immutable*.Builders for of maps list here, is due null values</technical_language>

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { return jsonBinder.bindToRequest(request, ParseHelper.buildLaunchConfigurationRequestMap(postParams)); }
Source:
<code>private void assertFrames(byte[] source, final boolean expected) { InstrSupport.classReaderFor(source) .accept(new ClassVisitor(InstrSupport.ASM_API_VERSION) { @Override public MethodVisitor visitMethod(int access, String name, final String desc, String signature, String[] exceptions) { return new MethodVisitor(InstrSupport.ASM_API_VERSION) { boolean frames = false; @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { frames = true; } @Override public void visitEnd() { if (CondyProbeArrayStrategy.B_DESC .equals(desc)) { <START> assertEquals(Boolean.FALSE, <END> Boolean.valueOf(frames)); } else { assertEquals(Boolean.valueOf(expected), Boolean.valueOf(frames)); } } }; } }, 0); }</code><technical_language>assertFalse()</technical_language>

Target:
private void assertFrames(byte[] source, final boolean expected) { InstrSupport.classReaderFor(source) .accept(new ClassVisitor(InstrSupport.ASM_API_VERSION) { @Override public MethodVisitor visitMethod(int access, String name, final String desc, String signature, String[] exceptions) { return new MethodVisitor(InstrSupport.ASM_API_VERSION) { boolean frames = false; @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { frames = true; } @Override public void visitEnd() { if (CondyProbeArrayStrategy.B_DESC .equals(desc)) { assertFalse( "CondyProbeArrayStrategy does not need frames", frames); } else { assertEquals(Boolean.valueOf(expected), Boolean.valueOf(frames)); } } }; } }, 0); }
Source:
<code>public CompactionManagerTest() throws InterruptedException { StoreConfig config = new StoreConfig(new VerifiableProperties(properties)); messageRetentionTimeInMs = config.storeDeletedMessageRetentionDays * Time.SecsPerDay * Time.MsPerSec; time.sleep(2 * messageRetentionTimeInMs); MetricRegistry metricRegistry = new MetricRegistry(); StorageManagerMetrics metrics = new StorageManagerMetrics(metricRegistry); <START> blobStore = new MockBlobStore("", config, null, null, metrics, null, 0, null, null, null, time); <END> blobStore.capacityInBytes = CAPACITY_IN_BYTES; blobStore.usedCapacity = CAPACITY_IN_BYTES * 6 / 10; blobStore.start(); compactionManager = new CompactionManager(config); }</code><technical_language>if of null empty string arguments constructor of MockBlobStore? set null (or empty string) calling super constructor</technical_language>

Target:
public CompactionManagerTest() throws InterruptedException { config = new StoreConfig(new VerifiableProperties(properties)); messageRetentionTimeInMs = config.storeDeletedMessageRetentionDays * Time.SecsPerDay * Time.MsPerSec; time.sleep(2 * messageRetentionTimeInMs); MetricRegistry metricRegistry = new MetricRegistry(); StorageManagerMetrics metrics = new StorageManagerMetrics(metricRegistry); blobStore = new MockBlobStore(config, metrics, time, CAPACITY_IN_BYTES, DEFAULT_USED_CAPACITY_IN_BYTES); compactionManager = new CompactionManager(config, time); }
Source:
<code>public void setContent(String newContent) { if (newContent == null) { this.content = ""; this.maskedContent = ""; } else { if (isPasswordHiden(newContent)) { if (contentChanged(newContent)) { String[] splitNewContent = splitbyPasswordTag(newContent); String[] splitContent = splitbyPasswordTag(content); <START> this.content = splitNewContent[0] + splitContent[1] + splitNewContent[2]; <END> this.maskedContent = hidePassword(content); } } else { this.content = newContent; this.maskedContent = hidePassword(content); } } }</code><technical_language>splitContent splitNewContent null, a check if is null</technical_language>

Target:
public void setContent(String newContent) { if (newContent == null) { this.content = ""; this.maskedContent = ""; } else { if (PasswordTagUtil.isPasswordHidden(newContent)) { if (PasswordTagUtil.isContentChanged(newContent, maskedContent)) { String[] splitNewContent = PasswordTagUtil.splitByPasswordTag(newContent); String[] splitContent = PasswordTagUtil.splitByPasswordTag(content); if (splitContent != null) { this.content = splitNewContent[0] + splitContent[1] + splitNewContent[2]; } else { this.content = splitNewContent[0] + (PasswordTagUtil.TAG_PASSWORD_BEGIN + PasswordTagUtil.TAG_PASSWORD_END) + splitNewContent[2]; } this.maskedContent = PasswordTagUtil.hidePassword(content); } } else { this.content = newContent; this.maskedContent = PasswordTagUtil.hidePassword(content); } } }
Source:
<code>public Reply<?> findById(@Named("id") String id) { Optional<RoamingGroup> group = repository.findById(id); if (!group.isPresent()) { return Reply.saying().notFound(); } RoamingGroupDTO dto = adapt(group.get()); <START> return Reply.with(dto).as(Json.class); <END> }</code><technical_language>status ok</technical_language>

Target:
public Reply<?> findById(@Named("id") String id) { Optional<RoamingGroup> group = repository.findById(id); if (!group.isPresent()) { return Reply.saying().notFound(); } RoamingGroupDTO dto = adapt(group.get()); return Reply.with(dto).as(Json.class).ok(); }
Source:
<code>public @ResponseBody String updateContext( @RequestParam(value = "context", required = true) int context, Model model, HttpSession session) { model.addAttribute("message", ""); model.addAttribute("errorMessage", ""); Member member = (Member) session.getAttribute("member"); if (member == null) <START> return "redirect:denied"; <END> if (context == member.getContext().ordinal()) { return null; } else if (context == UserType.PLAYER.ordinal()) { member.setContext(UserType.PLAYER); } else if (context == (int) UserType.OFFICIAL.ordinal() && MemberUtils.atLeastOfficial(member)) { member.setContext(UserType.OFFICIAL); } else if (context == (int) UserType.COORDINATOR.ordinal() && MemberUtils.atLeastCoordinator(member)) { member.setContext(UserType.COORDINATOR); } else if (context == (int) UserType.ADMIN.ordinal() && member.getUserType() == UserType.ADMIN) { member.setContext(UserType.ADMIN); } else { return "redirect:denied"; } MemberDao memberDao = new MemberDao(); memberDao.save(member); session.setAttribute("member", memberDao.getMemberById(member.getId())); return null; }</code><technical_language>/denied finds page, this try redirect /context/denied,</technical_language>

Target:
public @ResponseBody String updateContext( @RequestParam(value = "context", required = true) int context, Model model, HttpSession session) { model.addAttribute("message", ""); model.addAttribute("errorMessage", ""); Member member = (Member) session.getAttribute("member"); if (member == null) return "redirect:/denied"; if (context == member.getContext().ordinal()) { return null; } else if (context == UserType.PLAYER.ordinal()) { member.setContext(UserType.PLAYER); } else if (context == (int) UserType.OFFICIAL.ordinal() && MemberUtils.atLeastOfficial(member)) { member.setContext(UserType.OFFICIAL); } else if (context == (int) UserType.COORDINATOR.ordinal() && MemberUtils.atLeastCoordinator(member)) { member.setContext(UserType.COORDINATOR); } else if (context == (int) UserType.ADMIN.ordinal() && member.getUserType() == UserType.ADMIN) { member.setContext(UserType.ADMIN); } else { return "redirect:/denied"; } MemberDao memberDao = new MemberDao(); memberDao.save(member); session.setAttribute("member", memberDao.getMemberById(member.getId())); return null; }
Source:
<code>public void testOrderWithDifferentPrefixes() throws Exception { String[] names = { "r-3", "r-2", "r-1", "w-2", "w-1" }; <START> String[] expected = { "r-1", "r-2", "r-3" }; <END> assertOrderedNodeNames(names, expected); }</code><technical_language>removed "w-1" "w-2" elements here? I expected list be: String[] expected = { "r-1", "w-1", "r-2", "w-2", "r-3"};</technical_language>

Target:
public void testOrderWithDifferentPrefixes() throws Exception { String[] names = { "r-3", "r-2", "r-1", "w-2", "w-1" }; String[] expected = { "r-1", "w-1", "r-2", "w-2", "r-3" }; assertOrderedNodeNames(names, expected); }
Source:
<code>public void sendSmsCommand(String phone, Command command) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException { if (Context.getSmppManager() != null) { if (command.getType().equals(Command.TYPE_CUSTOM)) { Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else if (supportedSmsCommands.contains(command.getType()) && smsEncoder != null) { Context.getSmppManager().sendMessageSync(phone, (String) smsEncoder.encodeCommand(command), true); } else { throw new RuntimeException( "Command " + command.getType() + " is not supported in protocol " + getName()); } } else { <START> throw new RuntimeException("Smpp client is not enabled"); <END> } }</code><technical_language>Change "Smpp" "SMPP" here. Camel-case naming convention applies Java code, log messages follow English language rules. SMPP is abbreviation, upper case, SMS</technical_language>

Target:
public void sendSmsCommand(String phone, Command command) throws Exception { if (Context.getSmppManager() != null) { if (command.getType().equals(Command.TYPE_CUSTOM)) { Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); } else if (supportedSmsCommands.contains(command.getType()) && smsEncoder != null) { Context.getSmppManager().sendMessageSync(phone, (String) smsEncoder.encodeCommand(command), true); } else { throw new RuntimeException( "Command " + command.getType() + " is not supported in protocol " + getName()); } } else { throw new RuntimeException("SMPP client is not enabled"); } }
Source:
<code>public void testConvertToDataModelTypeNullIds() { mongoVariant.remove(uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter.IDS_FIELD); <START> uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantConverter(); <END> Variant converted = converter.convert(mongoVariant); assertNotNull(converted.getIds()); assertTrue(converted.getIds().isEmpty()); variant.setIds(new HashSet<String>()); assertEquals(variant, converted); }</code><technical_language>Full qualification is needed</technical_language>

Target:
public void testConvertToDataModelTypeNullIds() { mongoVariant.remove(DBObjectToVariantConverter.IDS_FIELD); DBObjectToVariantConverter converter = new DBObjectToVariantConverter(); Variant converted = converter.convert(mongoVariant); assertNotNull(converted.getIds()); assertTrue(converted.getIds().isEmpty()); variant.setIds(new HashSet<String>()); assertEquals(variant, converted); }
Source:
<code>private static void addIteratorWorkerDirect( Graph graph, Iterator<Triple> it ) { if ( OldStyle && graph instanceof GraphWithPerform ) { GraphWithPerform g = (GraphWithPerform)graph; <START> while (it.hasNext()) <END> g.performAdd(it.next()); } else { while (it.hasNext()) graph.add(it.next()); } }</code><technical_language>@ajs6f's usual carping: I "point-free" reads more below: it.forEachRemaining(g::performAdd)</technical_language>

Target:
private static void addIteratorWorkerDirect( Graph graph, Iterator<Triple> it ) { if ( OldStyle && graph instanceof GraphWithPerform ) { GraphWithPerform g = (GraphWithPerform)graph; it.forEachRemaining(g::performAdd); } else { it.forEachRemaining(graph::add); } }
Source:
<code>private boolean isExcludedPath(URI uri) { Pattern excludedPattern = errorProneOptions.getExcludedPattern(); <START> return (excludedPattern != null) && excludedPattern.matcher(uri.toString()).matches(); <END> }</code><technical_language>ASTHelpers.getFileNameFromUri instead of URI.toString? special handling for jar entries, I here</technical_language>

Target:
private boolean isExcludedPath(URI uri) { Pattern excludedPattern = errorProneOptions.getExcludedPattern(); return (excludedPattern != null) && excludedPattern.matcher(ASTHelpers.getFileNameFromUri(uri)).matches(); }
Source:
<code>protected String contentFrom(FitNesseContext context, Request request, WikiPage requestedPage) { <START> requestData= request; <END> return prepareResponseDocument(context).html(); }</code><technical_language>suggestion requestData = request;</technical_language>

Target:
protected String contentFrom(FitNesseContext context, Request request, WikiPage requestedPage) { return prepareResponseDocument(context).html(request); }