auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String getHttpResponse(String endpoint, String requestMethod, String payload) { StringBuilder jsonString = new StringBuilder(); BufferedReader br = null; try { String line; URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("charset", "UTF-8"); connection.setReadTimeout(10000); connection.setRequestMethod(requestMethod); connection.setRequestProperty("Accept", "application/json"); if (null != payload) { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(payload.length())); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(payload); writer.close(); } br = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (null != (line = br.readLine())) { jsonString.append(line); } connection.disconnect(); } catch (IOException e) { log.error("IO exception occurred, " + e.getMessage()); } finally { try { if (null != br) { br.close(); } } catch (IOException e) { log.error("IO exception occurred while closing the reader, " + e.getMessage()); } } return jsonString.toString(); }

Target:
private String getHttpResponse(String endpoint, String requestMethod, String payload) { StringBuilder jsonString = new StringBuilder(); BufferedReader br = null; try { String line; URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("charset", "UTF-8"); connection.setReadTimeout(10000); connection.setRequestMethod(requestMethod); connection.setRequestProperty("Accept", "application/json"); if (null != payload) { connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(payload.length())); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writer.write(payload); writer.close(); } br = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (null != (line = br.readLine())) { jsonString.append(line); } connection.disconnect(); } catch (IOException e) { log.error("IO exception occurred, " + e.getMessage(), e); } finally { try { if (null != br) { br.close(); } } catch (IOException e) { log.error("IO exception occurred while closing the reader, " + e.getMessage(), e); } } return jsonString.toString(); }
Source:
private List<PID> makePidList(int numPids) { List<PID> pids = new ArrayList<PID>(); int i = 0; while(i < numPids) { PID pidMock = mock(PID.class); when(pidMock.getId()).thenReturn("uuid:" + UUID.randomUUID().toString()); pids.add(pidMock); i++; } return pids; }

Target:
private List<PID> makePidList(int numPids) { List<PID> pids = new ArrayList<>(); int i = 0; while(i < numPids) { PID pidMock = mock(PID.class); when(pidMock.getId()).thenReturn("uuid:" + UUID.randomUUID().toString()); pids.add(pidMock); i++; } return pids; }
Source:
public static String loadWikiTextContent(String filename) { StringBuilder textContent = new StringBuilder(); String separator = System.getProperty("line.separator"); Scanner scanner = null; String path = String.format(TEXT_FILES_PATH_FORMAT, filename); try { scanner = new Scanner(new File(ClassLoader.getSystemResource(path).getPath()), "UTF-8"); } catch (FileNotFoundException e) { PageObjectLogging.logError("File was not loaded", e); } if (scanner != null) { try { while (scanner.hasNextLine()) { textContent.append(scanner.nextLine()).append(separator); } } finally { scanner.close(); } } else { throw new NullPointerException("Could not initialize scanner!"); } return textContent.toString(); }

Target:
public static String loadWikiTextContent(String filename) { StringBuilder textContent = new StringBuilder(); String separator = System.getProperty("line.separator"); String path = String.format(TEXT_FILES_PATH_FORMAT, filename); try (Scanner scanner = new Scanner(new File(ClassLoader.getSystemResource(path).getPath()), "UTF-8")) { while (scanner.hasNextLine()) { textContent.append(scanner.nextLine()).append(separator); } } catch (NullPointerException | FileNotFoundException ex) { throw new ContentLoaderException("Error when loading file!", ex); } return textContent.toString(); }
Source:
public void validate(JobParameters parameters) throws JobParametersInvalidException { String configRestartabilityAllowValue = parameters.getString(JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil .checkNullOrEmptyString(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil.checkBooleanStringSyntax(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); }

Target:
public void validate(JobParameters parameters) throws JobParametersInvalidException { String configRestartabilityAllowValue = parameters.getString(JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil .checkIsNotNullOrEmptyString(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); ParametersValidatorUtil .checkIsBoolean(configRestartabilityAllowValue, JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); }
Source:
public static String getBasicUserSecretFromHttpReq(HttpServletRequest httpReq) { try { String authHeader = httpReq.getHeader("Authorization"); if (authHeader == null) { return null; } if (!authHeader.substring(0, 6).equals("Basic ")) { return null; } String encodedUserSecret = authHeader.substring(6); return StringUtils.fromUtf8(DECODER.decode(encodedUserSecret)); } catch (Exception e) { return null; } }

Target:
public static String getBasicUserSecretFromHttpReq(HttpServletRequest httpReq) { String authHeader = httpReq.getHeader("Authorization"); if (authHeader == null) { return null; } if (authHeader.length() < 7) { return null; } if (!authHeader.substring(0, 6).equals("Basic ")) { return null; } String encodedUserSecret = authHeader.substring(6); try { return StringUtils.fromUtf8(Base64.getDecoder().decode(encodedUserSecret)); } catch (IllegalArgumentException iae) { return null; } }
Source:
public JSONArray(JSONArray array) { if (array == null) { this.myArrayList = new ArrayList<Object>(); } else { this.myArrayList = new ArrayList<Object>(array.length()); this.addAll(array.myArrayList); } }

Target:
public JSONArray(JSONArray array) { if (array == null) { this.myArrayList = new ArrayList<Object>(); } else { this.myArrayList = new ArrayList<Object>(array.myArrayList); } }
Source:
private IModuleResource[] getCleanedChildren(IModuleResource[] children) { ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(); IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }

Target:
private IModuleResource[] getCleanedChildren(IModuleResource[] children) { ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(children.length); IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }
Source:
public void checkUserCredentials(final PluginTask task) { try { authorizeAndRequestWithGet(task, JiraUtil.buildPermissionUrl(task.getUri())); } catch (JiraException e) { LOGGER.error(String.format("JIRA return status (%s), reason (%s)", e.getStatusCode(), e.getMessage())); if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new ConfigException("Could not authorize with your credential."); } else { throw new ConfigException("Could not authorize with your credential due to problem when contacting JIRA API"); } } }

Target:
public void checkUserCredentials(final PluginTask task) { try { authorizeAndRequest(task, JiraUtil.buildPermissionUrl(task.getUri()), null); } catch (JiraException e) { LOGGER.error(String.format("JIRA return status (%s), reason (%s)", e.getStatusCode(), e.getMessage())); if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new ConfigException("Could not authorize with your credential."); } else { throw new ConfigException("Could not authorize with your credential due to problems when contacting JIRA API."); } } }
Source:
public static String findPermissionId(String id) { List<PermissionGroup> pgs = PermissionGroup.getAll(); Matcher m = PERMISSION_PATTERN.matcher(id); if(m.matches()) { String owner = m.group(1); String name = m.group(2); for(PermissionGroup pg : pgs) { if(pg.owner.equals(Permission.class)) { continue; } if(pg.title.toString(Locale.US).equals(owner)) { return pg.owner.getName() + "." + name; } } } return null; }

Target:
public static String findPermissionId(String id) { List<PermissionGroup> pgs = PermissionGroup.getAll(); Matcher m = PERMISSION_PATTERN.matcher(id); if(m.matches()) { String owner = m.group(1); String name = m.group(2); for(PermissionGroup pg : pgs) { if(pg.owner.equals(Permission.class)) { continue; } if(pg.getId().equals(owner)) { return pg.owner.getName() + "." + name; } } } return null; }
Source:
private void additionalValidation() throws ParseException { if(noRetry && retry!=DEFAULT_RETRY_PERIOD) throw new ParseException("The \"--retry\" and \"--no-retry\" options are mutually exclusive!"); }

Target:
private void additionalValidation() throws ParseException { if(noRetry && retry!=DEFAULT_RETRY_PERIOD) throw new ParseException("The \"--retry\" and \"--no-retry\" options are mutually exclusive"); }
Source:
public void move(String folderPath, String newFolderPath , AuthenticationInfo subject) throws IOException { LOG.info("====move folder {}:{}", folderPath, newFolderPath); if (folderPath.equals(newFolderPath)) { return; } String[] pathArray = toPathArray(folderPath, true); String[] newPathArray = toPathArray(newFolderPath, true); String[] newFolderParentArray = Arrays.copyOfRange(newPathArray, 0, newPathArray.length - 1); String id = findFolder(pathArray); String newPId = completeFolder(newFolderParentArray); String newFolderName = newPathArray[newPathArray.length - 1]; Document doc = new Document("$set" , new Document(Fields.ID, id) .append(Fields.PID, newPId) .append(Fields.IS_DIR, true) .append(Fields.NAME, newFolderName)); folders.updateOne(eq(Fields.ID, id), doc); }

Target:
public void move(String folderPath, String newFolderPath, AuthenticationInfo subject) throws IOException { LOG.debug("move folder, folderPath: {}, newFolderPath: {}", folderPath, newFolderPath); if (StringUtils.equals(folderPath, newFolderPath)) { return; } String[] pathArray = toPathArray(folderPath, true); String[] newPathArray = toPathArray(newFolderPath, true); String[] newFolderParentArray = Arrays.copyOfRange(newPathArray, 0, newPathArray.length - 1); try (AutoLock autoLock = lock.lockForWrite()) { String id = findFolder(pathArray); String newPId = completeFolder(newFolderParentArray); String newFolderName = newPathArray[newPathArray.length - 1]; Document doc = new Document("$set", new Document(Fields.ID, id) .append(Fields.PID, newPId) .append(Fields.IS_DIR, true) .append(Fields.NAME, newFolderName)); folders.updateOne(eq(Fields.ID, id), doc); } }
Source:
private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) { for (Method method : c.getDeclaredMethods()) { MethodSetEntry entry = new MethodSetEntry(method); if ((method.getModifiers() & Modifier.FINAL) != 0) { seenFinalMethods.add(new MethodSetEntry(method)); if (sink.contains(entry)) { sink.remove(entry); } continue; } if ((method.getModifiers() & STATIC) != 0) { continue; } if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) { continue; } if (seenFinalMethods.contains(entry)) { continue; } sink.add(entry); } for (Class<?> i : c.getInterfaces()) { getMethodsToProxy(sink, seenFinalMethods, i); } }

Target:
private void getMethodsToProxy(Set<MethodSetEntry> sink, Set<MethodSetEntry> seenFinalMethods, Class<?> c) { for (Method method : c.getDeclaredMethods()) { MethodSetEntry entry = new MethodSetEntry(method); if ((method.getModifiers() & Modifier.FINAL) != 0) { seenFinalMethods.add(entry); if (sink.contains(entry)) { sink.remove(entry); } continue; } if ((method.getModifiers() & STATIC) != 0) { continue; } if (method.getName().equals("finalize") && method.getParameterTypes().length == 0) { continue; } if (seenFinalMethods.contains(entry)) { continue; } sink.add(entry); } for (Class<?> i : c.getInterfaces()) { getMethodsToProxy(sink, seenFinalMethods, i); } }
Source:
protected Hardware resolveHardware(Set<? extends Hardware> hardwarel, final Iterable<? extends Image> images) { try { return super.resolveHardware(hardwarel, images); } catch (Exception NoSuchElementException) { if (super.minCores != 0 && super.minRam != 0) { return automaticHardwareForCpuAndRam(minCores, minRam); } else throw throwNoSuchElementExceptionAfterLoggingHardwareIds("Invalid hardware", hardwarel); } }

Target:
protected Hardware resolveHardware(Set<? extends Hardware> hardwarel, final Iterable<? extends Image> images) { try { return super.resolveHardware(hardwarel, images); } catch (NoSuchElementException ex) { if (super.minCores != 0 && super.minRam != 0) { return automaticHardwareForCpuAndRam(minCores, minRam); } else throw new IllegalArgumentException("No hardware profile matching the given criteria was found. If " + "you want to use exact values, please set the minCores and minRam values", ex); } }
Source:
protected void handlePrimaryRequest(final ConcreteShardRequest<Request> request, final TransportChannel channel, final Task task) { Releasable releasable = checkPrimaryLimits(request.getRequest()); ActionListener<Response> listener = ActionListener.runAfter(new ChannelActionListener<>(channel, transportPrimaryAction, request), releasable::close); threadPool.executor(executor).execute(new ActionRunnable<>(listener) { @Override protected void doRun() { new AsyncPrimaryAction(request, listener, (ReplicationTask) task).run(); } }); }

Target:
protected void handlePrimaryRequest(final ConcreteShardRequest<Request> request, final TransportChannel channel, final Task task) { Releasable releasable = checkPrimaryLimits(request.getRequest()); ActionListener<Response> listener = ActionListener.runAfter(new ChannelActionListener<>(channel, transportPrimaryAction, request), releasable::close); try { new AsyncPrimaryAction(request, listener, (ReplicationTask) task).run(); } catch (RuntimeException e) { listener.onFailure(e); } }
Source:
void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { new File(strPath); new File(StrParent, StrChild); File parent = new File(uri); new File(parent, StrChild); File.createTempFile(prefix, suffix); }

Target:
void fun(String strPath, String StrParent, String StrChild, String prefix, String suffix, java.net.URI uri) throws Exception { new File(strPath); new File(StrParent, StrChild); File parent = new File(uri); new File(parent, StrChild); File.createTempFile(prefix, suffix); File.createTempFile(prefix, suffix, parent); }
Source:
public boolean solutionEquals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Match match = (Match) o; return Objects.equals(id, match.id) && Objects.equals(homeTeam, match.homeTeam) && Objects.equals(awayTeam, match.awayTeam) && Objects.equals(day, match.day); }

Target:
public boolean solutionEquals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Match other = (Match) o; return Objects.equals(id, other.id) && Objects.equals(homeTeam, other.homeTeam) && Objects.equals(awayTeam, other.awayTeam) && Objects.equals(day, other.day); }
Source:
public void enable(Integer pin) { lastActivityTime = System.currentTimeMillis(); controller.servoEnable(this); this.pin = pin + ""; enabled = true; broadcastState(); invoke("publishServoEnable", getName()); }

Target:
public void enable(Integer pin) { log.info("Enable called on {}", getName()); if (this.pin != null && this.pin != pin) { disable(); } lastActivityTime = System.currentTimeMillis(); this.pin = pin; if (controller != null) { enabled = true; controller.servoEnable(this); } broadcastState(); }
Source:
private void buildUnaryExpression(UnaryExpressionTree tree) { if(tree.is(Tree.Kind.PREFIX_DECREMENT, Tree.Kind.PREFIX_INCREMENT)) { build(tree.expression()); currentBlock.elements.add(tree); } else { currentBlock.elements.add(tree); build(tree.expression()); } }

Target:
private void buildUnaryExpression(UnaryExpressionTree tree) { currentBlock.elements.add(tree); build(tree.expression()); }
Source:
public synchronized void stop() { synchronized (lifecycleLock) { if (!lifecycleLock.canStop()) { throw new ISE("LookupCoordinatorManager can't stop."); } try { LOG.debug("Stopping"); if (backgroundManagerFuture != null && !backgroundManagerFuture.cancel(true)) { LOG.warn("Background lookup manager thread could not be cancelled"); } if (executorService != null) { executorService.shutdownNow(); } LOG.debug("Stopped"); } catch (Exception ex) { LOG.makeAlert(ex, "Got Exception while stop()").emit(); } finally { lifecycleLock.exitStop(); lifecycleLock.reset(); } } }

Target:
public void stop() { synchronized (lifecycleLock) { if (!lifecycleLock.canStop()) { throw new ISE("LookupCoordinatorManager can't stop."); } try { LOG.debug("Stopping"); if (backgroundManagerFuture != null && !backgroundManagerFuture.cancel(true)) { LOG.warn("Background lookup manager thread could not be cancelled"); } if (executorService != null) { executorService.shutdownNow(); } LOG.debug("Stopped"); } catch (Exception ex) { LOG.makeAlert(ex, "Got Exception while stop()").emit(); } finally { lifecycleLock.exitStop(); lifecycleLock.reset(); } } }
Source:
public static Condition text(String text) { if (StringUtils.isBlank(text)) { throw new IllegalArgumentException("No expected text given"); } return new Text(text); }

Target:
public static Condition text(String text) { if (StringUtils.isBlank(text)) { throw new IllegalArgumentException("Text condition must not be null or empty string"); } return new Text(text); }
Source:
public ElasticsearchQueryBuilder(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { ElasticsearchTableDescription table = split.getTable(); tupleDomain = split.getTupleDomain(); index = table.getIndex(); type = table.getType(); shard = split.getShard(); try { Settings settings = Settings.builder().put("cluster.name", table.getClusterName()).build(); client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(split.getSearchNode()), table.getPort())); } catch (IOException e) { throw new PrestoException(ELASTIC_SEARCH_CLIENT_ERROR, e); } columns = columnHandles; scrollTime = config.getScrollTime(); scrollSize = config.getScrollSize(); }

Target:
public ElasticsearchQueryBuilder(List<ElasticsearchColumnHandle> columnHandles, ElasticsearchConnectorConfig config, ElasticsearchSplit split) { columns = requireNonNull(columnHandles, "columnHandles is null"); requireNonNull(config, "config is null"); requireNonNull(split, "split is null"); ElasticsearchTableDescription table = split.getTable(); tupleDomain = split.getTupleDomain(); index = split.getIndex(); type = table.getType(); shard = split.getShard(); try { Settings settings = Settings.builder().put("client.transport.ignore_cluster_name", true).build(); client = new PreBuiltTransportClient(settings).addTransportAddress(new TransportAddress(InetAddress.getByName(split.getSearchNode()), split.getPort())); } catch (IOException e) { throw new PrestoException(ELASTIC_SEARCH_CONNECTION_ERROR, "Error connecting to Elasticsearch SearchNode: " + split.getSearchNode() + " with port: " + split.getPort(), e); } scrollTimeout = config.getScrollTimeout(); scrollSize = config.getScrollSize(); }
Source:
public void onActivityResult(int requestCode, int resultCode, final Intent data) { if (settingsActivityRequested(requestCode)) { handleSettingsActivityResult(resultCode); } else if (newArticleLanguageSelected(requestCode, resultCode) || galleryPageSelected(requestCode, resultCode)) { handleLangLinkOrPageResult(data); } else if (requestCode == Constants.ACTIVITY_REQUEST_BROWSE_TABS) { if (app.getTabCount() == 0 && resultCode != TabActivity.RESULT_NEW_TAB) { finish(); return; } if (resultCode == TabActivity.RESULT_NEW_TAB) { loadMainPage(TabPosition.NEW_TAB_FOREGROUND); animateTabsButton(); } else if (resultCode == TabActivity.RESULT_LOAD_FROM_BACKSTACK) { pageFragment.reloadFromBackstack(); } } else if (requestCode == Constants.ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT && resultCode == RESULT_OK) { pageFragment.refreshPage(); FeedbackUtil.makeSnackbar(this, TextUtils.isEmpty(pageFragment.getLeadImageEditLang()) ? getString(R.string.description_edit_success_saved_image_caption_snackbar) : getString(R.string.description_edit_success_saved_image_caption_in_lang_snackbar, app.language().getAppLanguageLocalizedName(StringUtils.defaultString(pageFragment.getLeadImageEditLang(), app.language().getAppLanguageCodes().get(0)))), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.suggested_edits_article_cta_snackbar_action, v -> pageFragment.showLeadImageInGallery()).show(); } else { super.onActivityResult(requestCode, resultCode, data); } }

Target:
public void onActivityResult(int requestCode, int resultCode, final Intent data) { if (settingsActivityRequested(requestCode)) { handleSettingsActivityResult(resultCode); } else if (newArticleLanguageSelected(requestCode, resultCode) || galleryPageSelected(requestCode, resultCode)) { handleLangLinkOrPageResult(data); } else if (requestCode == Constants.ACTIVITY_REQUEST_BROWSE_TABS) { if (app.getTabCount() == 0 && resultCode != TabActivity.RESULT_NEW_TAB) { finish(); return; } if (resultCode == TabActivity.RESULT_NEW_TAB) { loadMainPage(TabPosition.NEW_TAB_FOREGROUND); animateTabsButton(); } else if (resultCode == TabActivity.RESULT_LOAD_FROM_BACKSTACK) { pageFragment.reloadFromBackstack(); } } else if (requestCode == Constants.ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT && resultCode == RESULT_OK) { pageFragment.refreshPage(); FeedbackUtil.makeSnackbar(this, TextUtils.isEmpty(pageFragment.getLeadImageEditLang()) ? getString(R.string.description_edit_success_saved_image_caption_snackbar) : getString(R.string.description_edit_success_saved_image_caption_in_lang_snackbar, app.language().getAppLanguageLocalizedName(StringUtils.defaultString(pageFragment.getLeadImageEditLang(), app.language().getAppLanguageCode()))), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.suggested_edits_article_cta_snackbar_action, v -> pageFragment.openImageInGallery()).show(); } else { super.onActivityResult(requestCode, resultCode, data); } }
Source:
public void afterCommit(final Transaction tx) { for (MessageReference ref : refsToAck) { queue.postAcknowledge(ref); } if (pagedMessagesToPostACK != null) { for (MessageReference refmsg : pagedMessagesToPostACK) { if (((PagedReference) refmsg).isLargeMessage()) { decrementRefCount(refmsg); } } } }

Target:
public void afterCommit(final Transaction tx) { for (MessageReference ref : refsToAck) { synchronized (ref.getQueue()) { queue.postAcknowledge(ref); } } if (pagedMessagesToPostACK != null) { for (MessageReference refmsg : pagedMessagesToPostACK) { if (((PagedReference) refmsg).isLargeMessage()) { decrementRefCount(refmsg); } } } }
Source:
@Override public CodeBlock render(int sdk) { if (tintAttributeId.value != -1) { return CodeBlock.of("target.$L = $T.getTintedDrawable(context, $L, $L)", name, UTILS, id.code, tintAttributeId.code); } if (sdk >= 21) { return CodeBlock.of("target.$L = context.getDrawable($L)", name, id.code); } return CodeBlock.of("target.$L = $T.getDrawable(context, $L)", name, CONTEXT_COMPAT, id.code); }

Target:
@Override public CodeBlock render(int sdk) { if (tintAttributeId.value != NO_RES_ID) { return CodeBlock.of("target.$L = $T.getTintedDrawable(context, $L, $L)", name, UTILS, id.code, tintAttributeId.code); } if (sdk >= 21) { return CodeBlock.of("target.$L = context.getDrawable($L)", name, id.code); } return CodeBlock.of("target.$L = $T.getDrawable(context, $L)", name, CONTEXT_COMPAT, id.code); }
Source:
public MedicationRequest updateFHIRMedicationRequest(MedicationRequest medicationRequest, String uuid) { List<String> errors = new ArrayList<String>(); DrugOrder requestDrugOrder = FHIRMedicationRequestUtil.generateDrugOrder(medicationRequest, errors); DrugOrder generatedDrugOrder = (DrugOrder) Context.getOrderService().getOrderByUuid(uuid); FHIRMedicationRequestUtil.copyObsAttributes(requestDrugOrder, generatedDrugOrder, errors); if (generatedDrugOrder != null) { if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } requestDrugOrder = (DrugOrder) Context.getOrderService().saveOrder(generatedDrugOrder, null); return FHIRMedicationRequestUtil.generateMedicationRequest(requestDrugOrder); } else { if (medicationRequest.getId() == null) { IdType id = new IdType(); id.setValue(uuid); medicationRequest.setId(uuid); } return createFHIRMedicationRequest(medicationRequest); } }

Target:
public MedicationRequest updateFHIRMedicationRequest(MedicationRequest medicationRequest, String uuid) { List<String> errors = new ArrayList<String>(); DrugOrder incomingDrugOrder = FHIRMedicationRequestUtil.generateDrugOrder(medicationRequest, errors); DrugOrder generatedDrugOrder = (DrugOrder) Context.getOrderService().getOrderByUuid(uuid); FHIRMedicationRequestUtil.copyObsAttributes(incomingDrugOrder, generatedDrugOrder, errors); if (generatedDrugOrder != null) { if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the " + "following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } incomingDrugOrder = (DrugOrder) Context.getOrderService().saveOrder(generatedDrugOrder, null); return FHIRMedicationRequestUtil.generateMedicationRequest(incomingDrugOrder); } else { if (medicationRequest.getId() == null) { IdType id = new IdType(); id.setValue(uuid); medicationRequest.setId(uuid); } return createFHIRMedicationRequest(medicationRequest); } }
Source:
public void participantJoined(String identifier) { if (this.participants.containsKey(identifier)) { Participant participant = participants.get(identifier); participant.joined(); TranscriptEvent event = transcript.notifyJoined(participant); if (event != null) { fireTranscribeEvent(event); } if (logger.isDebugEnabled()) logger.debug( "Removed participant with identifier " + identifier); return; } logger.warn("Participant with identifier " + identifier + " joined while it did not exist"); }

Target:
public void participantJoined(String identifier) { Participant participant = getParticipant(identifier); if (participant != null) { participant.joined(); TranscriptEvent event = transcript.notifyJoined(participant); if (event != null) { fireTranscribeEvent(event); } if (logger.isDebugEnabled()) logger.debug( "Added participant with identifier " + identifier); return; } logger.warn("Participant with identifier " + identifier + " joined while it did not exist"); }
Source:
public FixedPollingStrategy(long interval, TimeUnit units, boolean syncInit) { this.executor = Executors.newSingleThreadScheduledExecutor(ThreadFactories.newNamedDaemonThreadFactory("poller-%d")); this.interval = interval; this.units = units; this.syncInit = syncInit; }

Target:
public FixedPollingStrategy(long interval, TimeUnit units, boolean syncInit) { this.executor = Executors.newSingleThreadScheduledExecutor(ThreadFactories.newNamedDaemonThreadFactory("Archaius-Poller-%d")); this.interval = interval; this.units = units; this.syncInit = syncInit; }
Source:
public CoreMessage putByteProperty(final String key, final byte value) { messageChanged(); getOrCreateProperties().putByteProperty(key(key), value); return this; }

Target:
public CoreMessage putByteProperty(final String key, final byte value) { return putByteProperty(key(key), value); }
Source:
private String toSnakeAndLowerCase(String attrName) { if (attrName == null || attrName.isEmpty()) { return attrName; } char firstChar = attrName.subSequence(0, 1).charAt(0); boolean prevCharIsUpperCaseOrUnderscore = Character.isUpperCase(firstChar) || firstChar == '_'; StringBuilder resultBuilder = new StringBuilder(attrName.length()).append(Character.toLowerCase(firstChar)); for (char attrChar : attrName.substring(1).toCharArray()) { boolean charIsUpperCase = Character.isUpperCase(attrChar); if (attrChar == '.') { resultBuilder.append("_"); } else if (attrChar == '-') { resultBuilder.append("_"); } else { if (!prevCharIsUpperCaseOrUnderscore && charIsUpperCase) { resultBuilder.append("_"); } resultBuilder.append(Character.toLowerCase(attrChar)); } prevCharIsUpperCaseOrUnderscore = charIsUpperCase || attrChar == '_'; } return resultBuilder.toString(); }

Target:
private String toSnakeAndLowerCase(String attrName) { if (attrName == null || attrName.isEmpty()) { return attrName; } char firstChar = attrName.subSequence(0, 1).charAt(0); boolean prevCharIsUpperCaseOrUnderscore = Character.isUpperCase(firstChar) || firstChar == '_'; StringBuilder resultBuilder = new StringBuilder(attrName.length()).append(Character.toLowerCase(firstChar)); for (char attrChar : attrName.substring(1).toCharArray()) { boolean charIsUpperCase = Character.isUpperCase(attrChar); if (attrChar == '.' || attrChar == '-') { resultBuilder.append("_"); } else { if (!prevCharIsUpperCaseOrUnderscore && charIsUpperCase) { resultBuilder.append("_"); } resultBuilder.append(Character.toLowerCase(attrChar)); } prevCharIsUpperCaseOrUnderscore = charIsUpperCase || attrChar == '_'; } return resultBuilder.toString(); }
Source:
public MemorySubjectData(PermissionService service) { this.service = service; }

Target:
public MemorySubjectData(PermissionService service) { checkNotNull(service); this.service = service; }
Source:
public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(Iterables.toArray(ids, String.class))).toSet(); }

Target:
public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(toArray(ids, String.class))).toSet(); }
Source:
static String getFqTypeName(Class clazz) { return String.format("%s.%s", PACKAGE_NAME, clazz.getSimpleName()); }

Target:
static String getFqTypeName(Class clazz) { return PACKAGE_NAME + "." + clazz.getSimpleName(); }
Source:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); Collections.sort(res, Comparator.comparing(BundleInfo::getId)); return res; }

Target:
public List<BundleInfo> getBundles() { List<BundleInfo> res = new ArrayList<>(bundles.values()); res.sort(Comparator.comparing(BundleInfo::getId)); return res; }
Source:
public byte[] toPubsubData() { return gson.toJson(this).getBytes(); }

Target:
public byte[] toPubsubData() { return gson.toJson(this).getBytes(StandardCharsets.UTF_8); }
Source:
protected void autoDeployResources(ProcessEngine processEngine) { if (deploymentResources != null && deploymentResources.length > 0) { final DefaultAutoDeploymentStrategy strategy = getAutoDeploymentStrategy(deploymentMode); strategy.setProcessDefinitionResources(deploymentResources); strategy.setProcessExtensionResources(processExtensionResources); strategy.deployResources(deploymentName, processEngine.getRepositoryService()); } }

Target:
protected void autoDeployResources(ProcessEngine processEngine) { if (deploymentResources != null && deploymentResources.length > 0) { final AutoDeploymentStrategy strategy = getAutoDeploymentStrategy(deploymentMode); strategy.deployResources(deploymentName, deploymentResources, processEngine.getRepositoryService()); } }
Source:
public void finalize() { try { if (!m_memoryDeque.isEmpty()) { m_memoryDeque.stream().filter((block) -> (!block.isPersisted())).forEachOrdered((_item) -> { exportLog.error("Finalized StreamBlockQueue with items in the memory deque that are not persisted."); }); } } finally { try { super.finalize(); } catch (Throwable ex) { ; } } }

Target:
public void finalize() { try { int nonEmptyCnt = 0; nonEmptyCnt = m_memoryDeque.stream().filter((block) -> (!block.isPersisted())).map((_item) -> 1).reduce(nonEmptyCnt, Integer::sum); if (nonEmptyCnt > 0) { exportLog.error("Finalized StreamBlockQueue with " + nonEmptyCnt + " items in the memory deque that are not persisted."); } } finally { try { super.finalize(); } catch (Throwable ex) { ; } } }
Source:
public void testAbuseFilterTriggerStopOnArbitraryErrorCode() { PageTitle title = new PageTitle(null, ABUSE_FILTER_ERROR_PAGE_TITLE, TEST_WIKI_SITE); String wikitext = "== Section 2 ==\n\nTriggering AbuseFilter number 152 by saying" + "appcrashtest many times at " + System.currentTimeMillis(); service.edit(TEST_WIKI_SITE, title, DEFAULT_SECTION_ID, wikitext, ANONYMOUS_TOKEN, DEFAULT_SUMMARY, false, null, null, new Edit.Callback() { @Override public void success(@NonNull EditingResult result) { assertThat(result, instanceOf(AbuseFilterEditResult.class)); assertThat(((AbuseFilterEditResult) result).getType(), is(AbuseFilterEditResult.TYPE_WARNING)); } @Override public void failure(@NonNull Throwable caught) { throw new RuntimeException(caught); } }); }

Target:
public void testAbuseFilterTriggerStopOnArbitraryErrorCode() { PageTitle title = new PageTitle(null, ABUSE_FILTER_ERROR_PAGE_TITLE, TEST_WIKI_SITE); String wikitext = "== Section 2 ==\n\nTriggering AbuseFilter number 152 by saying" + "appcrashtest many times at " + System.currentTimeMillis(); final TestLatch latch = new TestLatch(); client.request(TEST_WIKI_SITE, title, DEFAULT_SECTION_ID, wikitext, ANONYMOUS_TOKEN, DEFAULT_SUMMARY, false, null, null, new EditClient.Callback() { @Override public void success(@NonNull Call<Edit> call, @NonNull EditingResult result) { assertThat(result, instanceOf(AbuseFilterEditResult.class)); assertThat(((AbuseFilterEditResult) result).getType(), is(AbuseFilterEditResult.TYPE_ERROR)); latch.countDown(); } @Override public void failure(@NonNull Call<Edit> call, @NonNull Throwable caught) { throw new RuntimeException(caught); } }); latch.await(); }
Source:
void addReplicasToPartition(AmbryPartition partition, List<AmbryReplica> replicas) { AmbryPartition currentPartition = addPartitionIfAbsent(partition, replicas.get(0).getCapacityInBytes()); ambryPartitionToAmbryReplicas.compute(currentPartition, (k, v) -> { v.addAll(replicas); return v; }); clusterWideAllocatedRawCapacityBytes.getAndAdd(replicas.get(0).getCapacityInBytes() * replicas.size()); for (ClusterMapChangeListener listener : clusterMapChangeListeners) { listener.onReplicaAddedOrRemoved(replicas, Collections.emptyList()); } }

Target:
void addReplicasToPartition(AmbryPartition partition, List<AmbryReplica> replicas) { AmbryPartition currentPartition = addPartitionIfAbsent(partition, replicas.get(0).getCapacityInBytes()); ambryPartitionToAmbryReplicas.compute(currentPartition, (k, v) -> { v.addAll(replicas); return v; }); clusterWideAllocatedRawCapacityBytes.getAndAdd(replicas.get(0).getCapacityInBytes() * replicas.size()); }
Source:
private boolean verifyEntityTypes(Item itemToProcess, EntityType entityTypeToProcess) { List<MetadataValue> list = itemService.getMetadata(itemToProcess, "relationship", "type", null, Item.ANY); if (list.isEmpty()) { return false; } String leftEntityType = list.get(0).getValue(); if (!StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel())) { return false; } return true; }

Target:
private boolean verifyEntityTypes(Item itemToProcess, EntityType entityTypeToProcess) { List<MetadataValue> list = itemService.getMetadata(itemToProcess, "relationship", "type", null, Item.ANY); if (list.isEmpty()) { return false; } String leftEntityType = list.get(0).getValue(); return StringUtils.equals(leftEntityType, entityTypeToProcess.getLabel()); }
Source:
private Adapter buildAdapter(org.opennms.netmgt.telemetry.config.model.Adapter adapterDef) throws Exception { final Class<?> clazz = Class.forName(adapterDef.getClassName()); final Constructor<?> ctor = clazz.getConstructor(); final Object adapterInstance = ctor.newInstance(); if (!(adapterInstance instanceof Adapter)) { throw new IllegalArgumentException(String.format("%s must implement %s", adapterDef.getClassName(), Adapter.class.getCanonicalName())); } final Adapter adapter = (Adapter)adapterInstance; final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(adapter); wrapper.setPropertyValues(adapterDef.getParameterMap()); final AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); beanFactory.autowireBean(adapter); beanFactory.initializeBean(adapter, "adapter"); adapter.setProtocol(protocolDef); return adapter; }

Target:
private Adapter buildAdapter(org.opennms.netmgt.telemetry.config.model.Adapter adapterDef) throws Exception { final Object adapterInstance; try { final Class<?> clazz = Class.forName(adapterDef.getClassName()); final Constructor<?> ctor = clazz.getConstructor(); adapterInstance = ctor.newInstance(); } catch (Exception e) { throw new RuntimeException(String.format("Failed to instantiate adapter with class name '%s'.", adapterDef.getClassName(), e)); } if (!(adapterInstance instanceof Adapter)) { throw new IllegalArgumentException(String.format("%s must implement %s", adapterDef.getClassName(), Adapter.class.getCanonicalName())); } final Adapter adapter = (Adapter)adapterInstance; final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(adapter); wrapper.setPropertyValues(adapterDef.getParameterMap()); final AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); beanFactory.autowireBean(adapter); beanFactory.initializeBean(adapter, "adapter"); adapter.setProtocol(protocolDef); return adapter; }
Source:
public void testEmptyPartitionException() { InternalAggregationFunction function = getFunction(); int partitionCount = 10; List<OGCGeometry> geometries = ImmutableList.of(); Block geometryBlock = makeGeometryBlock(geometries); Block partitionCountBlock = BlockAssertions.createRLEBlock(partitionCount, geometries.size()); Page page = new Page(geometryBlock, partitionCountBlock); AccumulatorFactory accumulatorFactory = function.bind(Ints.asList(0, 1, 2), Optional.empty()); Accumulator accumulator = accumulatorFactory.createAccumulator(); accumulator.addInput(page); assertThrows(PrestoException.class, () -> getFinalBlock(accumulator)); }

Target:
public void testEmptyPartitionException() { InternalAggregationFunction function = getFunction(); Block geometryBlock = GEOMETRY.createBlockBuilder(null, 0).build(); Block partitionCountBlock = BlockAssertions.createRLEBlock(10, 0); Page page = new Page(geometryBlock, partitionCountBlock); AccumulatorFactory accumulatorFactory = function.bind(Ints.asList(0, 1, 2), Optional.empty()); Accumulator accumulator = accumulatorFactory.createAccumulator(); accumulator.addInput(page); try { getFinalBlock(accumulator); fail("Should fail creating spatial partition with no rows."); } catch (PrestoException e) { assertEquals(e.getErrorCode(), INVALID_FUNCTION_ARGUMENT.toErrorCode()); assertEquals(e.getMessage(), "No rows supplied to spatial partition."); } }
Source:
public ITestAzureBlobFileSystemCheckAccess() throws Exception { super(); super.setup(); this.superUserFs = getFileSystem(); testUserGuid = getConfiguration() .get(FS_AZURE_BLOB_FS_CHECKACCESS_TEST_USER_GUID); this.testUserFs = getTestUserFs(); isCheckAccessEnabled = getConfiguration().isCheckAccessEnabled(); }

Target:
public ITestAzureBlobFileSystemCheckAccess() throws Exception { super.setup(); this.superUserFs = getFileSystem(); testUserGuid = getConfiguration() .get(FS_AZURE_BLOB_FS_CHECKACCESS_TEST_USER_GUID); this.testUserFs = getTestUserFs(); this.isCheckAccessEnabled = getConfiguration().isCheckAccessEnabled(); this.isHNSEnabled = getConfiguration() .getBoolean(FS_AZURE_TEST_NAMESPACE_ENABLED_ACCOUNT, false); }
Source:
public <T> void execute( final Callback<T> callback ) { getSession().getCanvasValidationControl().validate( new CanvasValidatorCallback() { @Override public void onSuccess() { if ( null != callback ) { callback.onSuccess( null ); } } @Override public void onFail( final Iterable<CanvasValidationViolation> violations ) { if ( null != callback ) { callback.onSuccess( ( T ) violations ); } } } ); }

Target:
public <T> void execute( final Callback<T> callback ) { checkNotNull( "callback", callback ); getSession().getCanvasValidationControl().validate( new CanvasValidatorCallback() { @Override public void onSuccess() { callback.onSuccess( null ); } @Override public void onFail( final Iterable<CanvasValidationViolation> violations ) { callback.onSuccess( ( T ) violations ); } } ); }
Source:
private void addChangelogsToRestoreConsumer(final Set<TopicPartition> partitions) { final Set<TopicPartition> assignment = new HashSet<>(restoreConsumer.assignment()); if (assignment.removeAll(partitions)) { throw new IllegalStateException("The current assignment " + restoreConsumer.assignment() + " " + "already contains some of the new partitions " + partitions); } assignment.addAll(partitions); restoreConsumer.assign(assignment); log.debug("Added partitions to the restore consumer, current assignment is {}", partitions, assignment); }

Target:
private void addChangelogsToRestoreConsumer(final Set<TopicPartition> partitions) { final Set<TopicPartition> assignment = new HashSet<>(restoreConsumer.assignment()); if (assignment.removeAll(partitions)) { throw new IllegalStateException("The current assignment " + restoreConsumer.assignment() + " " + "already contains some of the new partitions " + partitions); } assignment.addAll(partitions); restoreConsumer.assign(assignment); }
Source:
public String describeTask(String container, String taskName) throws IOException { List<Map<String, Object>> list = parseBody(fetch(() -> client.tasks().list()), List.class); Optional<Map<String, Object>> task = list.stream().filter(i -> taskName.equals(i.get("name"))).findFirst(); return task.get().toString(); }

Target:
public String describeTask(String container, String taskName) throws IOException { List<Map<String, Object>> list = parseBody(fetch(() -> client.tasks().list()), List.class); Optional<Map<String, Object>> task = list.stream().filter(i -> taskName.equals(i.get("name"))).findFirst(); return task.map(Object::toString).orElseThrow(() -> MSG.noSuchResource(taskName)); }
Source:
public CompletableFuture<T> get(DataFetchingEnvironment environment) { return CompletableFuture.supplyAsync(() -> { try { return wrappedDataFetcher.get(environment); } catch (Exception e) { throw new RuntimeException(e); } }, executor); }

Target:
public CompletableFuture<T> get(DataFetchingEnvironment environment) { return CompletableFuture.supplyAsync(() -> { try { return wrappedDataFetcher.get(environment); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } }, executor); }
Source:
public void execute(CommandLineArgument[] args) { if (arguments[ARG_IMPORT_FILE_IDX].isEnabled() || arguments[ARG_IMPORT_URL_IDX].isEnabled()) { if (!arguments[ARG_END_URL_IDX].isEnabled()) { CommandLine.error("Endpoint URL must be specified."); } String endpointUriStr = arguments[ARG_END_URL_IDX].getArguments().firstElement(); URI endpointUri = null; try { new URL(endpointUriStr); endpointUri = new URI(endpointUriStr, true); } catch (Exception e) { CommandLine.error("Invalid Endpoint URL.\n" + e.getMessage()); } if (arguments[ARG_IMPORT_FILE_IDX].isEnabled()) { String filePath = args[ARG_IMPORT_FILE_IDX].getArguments().firstElement(); File file = new File(filePath); if (!file.exists() || !file.canRead()) { CommandLine.error("Cannot read file: " + file.getAbsolutePath()); } if (!file.isFile()) { CommandLine.error("Invalid File."); } try { GraphQlParser.parse(FileUtils.readFileToString(file, "UTF-8"), endpointUri); } catch (IOException e) { CommandLine.error("Cannot read file.\n" + e.getMessage()); } } if (arguments[ARG_IMPORT_URL_IDX].isEnabled()) { String schemaUriStr = arguments[ARG_IMPORT_URL_IDX].getArguments().firstElement(); URI schemaUri = null; try { new URL(schemaUriStr); schemaUri = new URI(schemaUriStr, true); } catch (Exception e) { CommandLine.error("Invalid Schema URL.\n" + e.getMessage()); } GraphQlParser.parse(schemaUri, endpointUri); } } if (arguments[ARG_END_URL_IDX].isEnabled()) { String endpointUriStr = arguments[ARG_END_URL_IDX].getArguments().firstElement(); URI endpointUri = null; try { new URL(endpointUriStr); endpointUri = new URI(endpointUriStr, true); } catch (Exception e) { CommandLine.error("Invalid Endpoint URL.\n" + e.getMessage()); } GraphQlParser.introspect(endpointUri); } }

Target:
public void execute(CommandLineArgument[] args) { if (args[ARG_IMPORT_FILE_IDX].isEnabled() || args[ARG_IMPORT_URL_IDX].isEnabled()) { if (!args[ARG_END_URL_IDX].isEnabled()) { CommandLine.error(Constant.messages.getString("graphql.error.emptyendurl")); return; } GraphQlParser parser; try { parser = new GraphQlParser( args[ARG_END_URL_IDX].getArguments().firstElement(), HttpSender.MANUAL_REQUEST_INITIATOR); parser.addRequesterListener(new HistoryPersister()); } catch (URIException e) { CommandLine.error( Constant.messages.getString("graphql.error.invalidurl", e.getMessage())); return; } if (args[ARG_IMPORT_FILE_IDX].isEnabled()) { try { parser.importFile(args[ARG_IMPORT_FILE_IDX].getArguments().firstElement()); } catch (IOException e) { CommandLine.error(e.getMessage()); } } else if (args[ARG_IMPORT_URL_IDX].isEnabled()) { try { parser.importUrl(args[ARG_IMPORT_URL_IDX].getArguments().firstElement()); } catch (IOException e) { CommandLine.error( Constant.messages.getString( "graphql.error.invalidurl", e.getMessage())); } } } else if (args[ARG_END_URL_IDX].isEnabled()) { try { GraphQlParser parser = new GraphQlParser( args[ARG_END_URL_IDX].getArguments().firstElement(), HttpSender.MANUAL_REQUEST_INITIATOR); parser.addRequesterListener(new HistoryPersister()); parser.introspect(); } catch (IOException e) { CommandLine.error( Constant.messages.getString("graphql.error.invalidurl", e.getMessage())); } } }