auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<RepositoryLocation<? extends Repository>> loadRepositoryLocations() { List<RepositoryLocation<? extends Repository>> result = new ArrayList<>(); File repositoryListFile = new File(repositoryListPath); if (repositoryListFile.exists()) { try { result = this.objectMapper.readValue(new File(repositoryListPath), TypeFactory.defaultInstance().constructParametricType(List.class, RepositoryLocation.class)); } catch (IOException e) { LOGGER.error("Couldn't load repository location list", e); } } else { try { result.add(new GitRepositoryLocation.Builder() .withGitRepositoryUri(new URL("<LINK_0>").toURI()) <START> .withBranch("5.0-alpha").build()); <END> result.add(new ClasspathRepositoryLocation("/org/phoenicis/repository")); } catch (URISyntaxException | MalformedURLException e) { LOGGER.error("Couldn't create default repository location list", e); } } return result; }</code><technical_language>talking this string</technical_language>

Target:
public List<RepositoryLocation<? extends Repository>> loadRepositoryLocations() { List<RepositoryLocation<? extends Repository>> result = new ArrayList<>(); File repositoryListFile = new File(repositoryListPath); if (repositoryListFile.exists()) { try { result = this.objectMapper.readValue(new File(repositoryListPath), TypeFactory.defaultInstance().constructParametricType(List.class, RepositoryLocation.class)); } catch (IOException e) { LOGGER.error("Couldn't load repository location list", e); } } else { try { result.add(new GitRepositoryLocation.Builder() .withGitRepositoryUri(new URL(defaultGitUrl).toURI()) .withBranch(defaultGitBranch).build()); result.add(new ClasspathRepositoryLocation(defaultClasspath)); } catch (URISyntaxException | MalformedURLException e) { LOGGER.error("Couldn't create default repository location list", e); } } return result; }
Source:
<code>private GatewayResponse<BaseAuthoriseResponse> createGatewayBaseAuthoriseResponse(boolean isAuthorised) { GatewayResponseBuilder<BaseAuthoriseResponse> gatewayResponseBuilder = responseBuilder(); return gatewayResponseBuilder.withResponse(new BaseAuthoriseResponse() { private final String transactionId = randomUUID().toString(); @Override public AuthoriseStatus authoriseStatus() { return isAuthorised ? AuthoriseStatus.AUTHORISED : AuthoriseStatus.REJECTED; } @Override public String getTransactionId() { return transactionId; } @Override public String getErrorCode() { return null; } @Override public String getErrorMessage() { return null; } @Override <START> public Optional<GatewayParamsFor3ds> getAuth3dsDetails() { <END> return Optional.empty(); } @Override public String toString() { return "Sandbox authorisation response (transactionId: " + getTransactionId() + ", isAuthorised: " + isAuthorised + ')'; } }).build(); }</code><technical_language>Please rename this method match return type</technical_language>

Target:
private GatewayResponse<BaseAuthoriseResponse> createGatewayBaseAuthoriseResponse(boolean isAuthorised) { GatewayResponseBuilder<BaseAuthoriseResponse> gatewayResponseBuilder = responseBuilder(); return gatewayResponseBuilder.withResponse(new BaseAuthoriseResponse() { private final String transactionId = randomUUID().toString(); @Override public AuthoriseStatus authoriseStatus() { return isAuthorised ? AuthoriseStatus.AUTHORISED : AuthoriseStatus.REJECTED; } @Override public String getTransactionId() { return transactionId; } @Override public String getErrorCode() { return null; } @Override public String getErrorMessage() { return null; } @Override public Optional<GatewayParamsFor3ds> getGatewayParamsFor3ds() { return Optional.empty(); } @Override public String toString() { return "Sandbox authorisation response (transactionId: " + getTransactionId() + ", isAuthorised: " + isAuthorised + ')'; } }).build(); }
Source:
<code>private void loadValidUrl(final boolean shouldShowError) { if (mWebView != null) { if (PreferencesState.getCredentialsFromPreferences().isDemoCredentials()) { showHideWebView(false); mErrorDemoText.setTextTranslation(R.string.demo_page_text); } else { new ApiAvailabilityFactory().getGetWebViewAvailableUseCase().execute( new GetWebAvailableUseCase.Callback() { @Override public void onSuccess() { executeOnWebAvailable(); } @Override public void onError() { if(shouldShowError) { <START> showError(); <END> } } }); } } }</code><technical_language>In this case, show API Status message user</technical_language>

Target:
private void loadValidUrl(final boolean shouldShowError) { if (mWebView != null) { if (PreferencesState.getCredentialsFromPreferences().isDemoCredentials()) { showHideWebView(false); mErrorDemoText.setTextTranslation(R.string.demo_page_text); } else { new ApiAvailabilityFactory().getGetWebViewAvailableUseCase().execute( new GetWebAvailableUseCase.Callback() { @Override public void onSuccess() { executeOnWebAvailable(); } @Override public void onError(ApiStatus apiStatus) { if(shouldShowError) { showApiNotAvailableError(apiStatus.getMessage()); } } }); } } }
Source:
<code>public static String saveIptablesRules() { return BashCommands.alternatives( <START> BashCommands.ifExecutableElse1("apt-get", BashCommands.installPackage("iptables-persistent")), <END> iptablesService("save")); }</code><technical_language>apt-getting this package rules saved immediately? i want command run irrespective of result of former. try running iptables-save worked somewhere, work service iptables save /sbin/service iptables save work ... if understood correctly? /cc @grkvlt suggest (with import static BashCommands.* here, for brevity): chain( ok(install("iptables-persistent")), alternatives( iptablesService("save"), "iptables-save" ))</technical_language>

Target:
public static String saveIptablesRules() { return alternatives(sudo("service iptables save"), chain(installPackage("iptables-persistent"), sudo("/etc/init.d/iptables-persistent save"))); }
Source:
<code><START> public static Map.Entry<String, Map<String, ?>> powerACCommand( <END> PowerACState powerACState) { return new AbstractMap.SimpleEntry<>(POWER_AC_STATE, prepareArguments("state", powerACState.toString())); }</code><technical_language>methods extra space return type method name</technical_language>

Target:
public static Map.Entry<String, Map<String, ?>> powerACCommand( PowerACState powerACState) { return new AbstractMap.SimpleEntry<>(POWER_AC_STATE, prepareArguments("state", powerACState.name().toLowerCase())); }
Source:
<code>public void spec317_mustSignalOnErrorWhenPendingAboveLongMaxValue() throws Throwable { activePublisherTest(Integer.MAX_VALUE, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { ManualSubscriberWithSubscriptionSupport<T> sub = new BlackholeSubscriberWithSubscriptionSupport<T>(env) { int maxCalls = 10; @Override public void onNext(T element) { env.debug(this + "::onNext(" + element + ")"); if (subscription.isCompleted()) { if (maxCalls > 0) { subscription.value().request(Long.MAX_VALUE - 1); maxCalls--; } } else { env.flop("Subscriber::onNext(" + element + ") called before Subscriber::onSubscribe"); } } }; env.subscribe(pub, sub, env.defaultTimeoutMillis()); sub.request(1); sub.request(1); <START> sub.request(1); <END> sub.expectErrorWithMessage(IllegalStateException.class, "3.17"); env.verifyNoAsyncErrors(env.defaultTimeoutMillis()); } }); }</code><technical_language>Issuing 3 test, issue 10*(Long.MAX_VALUE-1)</technical_language>

Target:
public void spec317_mustSignalOnErrorWhenPendingAboveLongMaxValue() throws Throwable { activePublisherTest(Integer.MAX_VALUE, new PublisherTestRun<T>() { @Override public void run(Publisher<T> pub) throws Throwable { ManualSubscriberWithSubscriptionSupport<T> sub = new BlackholeSubscriberWithSubscriptionSupport<T>(env) { int callsCounter = 10; @Override public void onNext(T element) { env.debug(String.format("%s::onNext(%s)", this, element)); if (subscription.isCompleted()) { if (callsCounter > 0) { subscription.value().request(Long.MAX_VALUE - 1); callsCounter--; } } else { env.flop(String.format("Subscriber::onNext(%s) called before Subscriber::onSubscribe", element)); } } }; env.subscribe(pub, sub, env.defaultTimeoutMillis()); sub.request(1); sub.expectErrorWithMessage(IllegalStateException.class, "3.17"); env.verifyNoAsyncErrors(env.defaultTimeoutMillis()); } }); }
Source:
<code>CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nonnull final K key) { <START> return get(tableName, null, key); <END> }</code><technical_language>this return getRecord(tableName, null, key)</technical_language>

Target:
CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nonnull final K key) { return getRecord(tableName, null, key); }
Source:
<code>private static URL mapToURL(String path) { try { <START> File file = new File(path); <END> return file.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } }</code><technical_language>if this works in case. build url out of string in case of failure try File</technical_language>

Target:
private static URL mapToURL(String path) { try { return new URL(path); } catch (MalformedURLException e) { try { return new File(path).toURI().toURL(); } catch (MalformedURLException e1) { throw new IllegalArgumentException(e1); } } }
Source:
<code>public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { scheduleTimeTickEvent(); } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) { TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY)); int gmtOffset = zone.getRawOffset(); if (zone.inDaylightTime(new Date(System.currentTimeMillis()))) { gmtOffset += zone.getDSTSavings(); <START> } <END> setKernelTimezone(mDescriptor, -(gmtOffset / 60000)); scheduleDateChangedEvent(); } }</code><technical_language>change this to: int gmtOffest = zone.getOffest(System.currentTimeMillis());</technical_language>

Target:
public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { scheduleTimeTickEvent(); } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) { TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY)); int gmtOffset = zone.getOffset(System.currentTimeMillis()); setKernelTimezone(mDescriptor, -(gmtOffset / 60000)); scheduleDateChangedEvent(); } }
Source:
<code>public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { if (baseRequest.isHandled()) { return; } String resourcePath = getResourcePath(request); if (resourcePath == null) { return; } <START> if (resourcePath.equals("")) { <END> response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setHeader("Location", response.encodeRedirectURL(baseUri + "/")); baseRequest.setHandled(true); return; } URL resource = getResource(resourcePath); if (resource == null) { return; } baseRequest.setHandled(true); String method = request.getMethod(); boolean skipContent = false; if (!HttpMethod.GET.is(method)) { if (HttpMethod.HEAD.is(method)) { skipContent = true; } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } InputStream resourceStream = null; try { resourceStream = resource.openStream(); String contentType = MIME_TYPES.getMimeByExtension(resource.toString()); response.setContentType(contentType); if (skipContent) { return; } ByteStreams.copy(resourceStream, response.getOutputStream()); } finally { closeQuietly(resourceStream); } }</code><technical_language>isEmpty()</technical_language>

Target:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { if (baseRequest.isHandled()) { return; } String resourcePath = getResourcePath(request); if (resourcePath == null) { return; } if (resourcePath.isEmpty()) { response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); response.setHeader(HttpHeaders.LOCATION, response.encodeRedirectURL(baseUri + "/")); baseRequest.setHandled(true); return; } URL resource = getResource(resourcePath); if (resource == null) { return; } baseRequest.setHandled(true); String method = request.getMethod(); boolean skipContent = false; if (!HttpMethod.GET.is(method)) { if (HttpMethod.HEAD.is(method)) { skipContent = true; } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } InputStream resourceStream = null; try { resourceStream = resource.openStream(); String contentType = MIME_TYPES.getMimeByExtension(resource.toString()); response.setContentType(contentType); if (skipContent) { return; } ByteStreams.copy(resourceStream, response.getOutputStream()); } finally { closeQuietly(resourceStream); } }
Source:
<code>public void onBannerLoaded(BannerView bannerView) { mBannerView = bannerView; bannerListener.onAdLoaded(UnityAdapter.this); Log.v(TAG, "Unity Ads Banner finished loading banner for placement: " + mBannerView.getPlacementId()); <START> } <END></code><technical_language>Adaptive banner code is removed, I if publisher requests a banner ad custom size, adapter map AdMob supported AdSize. I adapter Adaptive banner implementation</technical_language>

Target:
public void onBannerLoaded(BannerView bannerView) { Log.v(TAG, "Unity Ads Banner finished loading banner for placement: " + mBannerView.getPlacementId()); bannerListener.onAdLoaded(UnityAdapter.this); }
Source:
<code>private void querySubprocess() { try { _process.writeSpoutMsg(spoutMsg); while (true) { Emission emission = _process.readEmission(); String command = emission.getCommand(); if (command.equals("sync")) { return; } else if (command.equals("log")) { String msg = emission.getMsg(); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { String stream = emission.getStream(); Long task = emission.getTask(); List<Object> tuple = emission.getTuple(); Object messageId = emission.getId(); if (task == 0) { List<Integer> outtasks = _collector.emit(stream, tuple, messageId); <START> _process.writeTaskIds(outtasks); <END> } else { _collector.emitDirect((int)task.longValue(), stream, tuple, messageId); } } } } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>this need_task_ids logic is removed</technical_language>

Target:
private void querySubprocess() { try { _process.writeSpoutMsg(spoutMsg); while (true) { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command.equals("sync")) { return; } else if (command.equals("log")) { String msg = shellMsg.getMsg(); LOG.info("Shell msg: " + msg); } else if (command.equals("emit")) { String stream = shellMsg.getStream(); Long task = shellMsg.getTask(); List<Object> tuple = shellMsg.getTuple(); Object messageId = shellMsg.getId(); if (task == 0) { List<Integer> outtasks = _collector.emit(stream, tuple, messageId); if (shellMsg.areTaskIdsNeeded()) { _process.writeTaskIds(outtasks); } } else { _collector.emitDirect((int) task.longValue(), stream, tuple, messageId); } } else { throw new RuntimeException("Unknown command received: " + command); } } } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public ServerTemplate update(ServerTemplate serverTemplate) { ServerTemplate updated = null; synchronized (templateMap) { if (templateKeyMap.isEmpty()) { <START> loadTemplateMapsFromFile(); <END> } templateKeyMap.put(serverTemplate.getId(), new ServerTemplateKey(serverTemplate.getId(),serverTemplate.getName())); updated = templateMap.put(serverTemplate.getId(),serverTemplate); writeTemplateMap(); } return updated; }</code><technical_language>well</technical_language>

Target:
public ServerTemplate update(ServerTemplate serverTemplate) { ServerTemplate updated = null; synchronized (templateMap) { templateKeyMap.put(serverTemplate.getId(), new ServerTemplateKey(serverTemplate.getId(),serverTemplate.getName())); updated = templateMap.put(serverTemplate.getId(),serverTemplate); writeTemplateMap(); } return updated; }
Source:
<code>public void deployQueue(final String address, final String name, final String filterStr, final boolean durable) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.deployQueue(this.server, address, name, filterStr, durable); } checkStarted(); clearIO(); try { server.createQueue(new QueueConfiguration(name) .setAddress(address) <START> .setName(name) <END> .setFilterString(filterStr) .setDurable(durable)); } finally { blockOnIO(); } }</code><technical_language>remove setName(name) this is care of passing name constructor. bug is setName(name) is called instead of setAddress(address)</technical_language>

Target:
public void deployQueue(final String address, final String name, final String filterStr, final boolean durable) throws Exception { if (AuditLogger.isEnabled()) { AuditLogger.deployQueue(this.server, address, name, filterStr, durable); } checkStarted(); clearIO(); try { server.createQueue(new QueueConfiguration(name) .setAddress(address) .setFilterString(filterStr) .setDurable(durable)); } finally { blockOnIO(); } }
Source:
<code>private PluginProperties parsePluginConfigs(InputStream inputStream) { <START> ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); <END> try { PluginProperties pluginConfigs = objectMapper.readValue(inputStream, PluginProperties.class); return pluginConfigs; } catch (IOException e) { throw new PluginLoaderException("Unable to parse plugin configurations", e); } }</code><technical_language>do handle loading right plugin if versions exist in source directory</technical_language>

Target:
private PluginProperties parsePluginConfigs(InputStream inputStream) { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); try { PluginProperties pluginConfigs = objectMapper.readValue(inputStream, PluginProperties.class); pluginConfigs.validate(); return pluginConfigs; } catch (IOException e) { throw new MalformedPluginConfigurationException("Unable to parse plugin configurations", e); } }
Source:
<code>public void run(final Callback callback) { final Deque<Node<View, Edge>> nodes = new ArrayDeque(); processedConnectors.clear(); if (!keepChildren) { childrenTraverseProcessor .setRootUUID(candidate.getUUID()) .traverse(graph, new AbstractChildrenTraverseCallback<Node<View, Edge>, Edge<Child, Node>>() { @Override public void startNodeTraversal(final Node<View, Edge> node) { super.startNodeTraversal(node); if (isDockedNode(node)) { return; } nodes.add(node); } @Override public boolean startNodeTraversal(final List<Node<View, Edge>> parents, final Node<View, Edge> node) { super.startNodeTraversal(parents, node); if (isDockedNode(node)) { return true; } nodes.add(node); return true; } }); } <START> if (!keepChildren) { <END> nodes.descendingIterator().forEachRemaining(node -> processNode(node, callback, false)); } processNode(candidate, callback, true); }</code><technical_language>if statements (!keepChildren) I introduce new if condition</technical_language>

Target:
public void run(final Callback callback) { final Deque<Node<View, Edge>> nodes = createNodesDequeue(); processedConnectors.clear(); if (!keepChildren) { deleteChildren(callback, nodes); } processNode(candidate, callback, true); }
Source:
<code>private static Action getFindAction() { if (findAction == null) { findAction = new AbstractAction("findAction") { private static final long serialVersionUID = 8365172573382425660L; @Override public void actionPerformed(ActionEvent e) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (focusOwner instanceof JTextComponent) { <START> FindDialog findDialog = new FindDialog(SwingUtilities.getWindowAncestor(focusOwner), false); <END> findDialog.setLastInvoker((JTextComponent) focusOwner); } } }; } return findAction; }</code><technical_language>Instead of creating a new FindDialog requested (e.g. FindDialog.getDialog(Window), returns existing creates if exists), statement effect if dialogue is open</technical_language>

Target:
private static Action getFindAction() { if (findAction == null) { findAction = new AbstractAction("findAction") { private static final long serialVersionUID = 8365172573382425660L; @Override public void actionPerformed(ActionEvent e) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (focusOwner instanceof JTextComponent) { FindDialog findDialog = FindDialog.getDialog(SwingUtilities.getWindowAncestor(focusOwner), false); findDialog.setLastInvoker((JTextComponent) focusOwner); } } }; } return findAction; }
Source:
<code>public Builder withInstructions(Text instructions) { <START> feedbackSessionAttributes.setInstructions(instructions); <END> return this; }</code><technical_language>Similarly here, null values in setters handled (if necessary)</technical_language>

Target:
public Builder withInstructions(Text instructions) { Text instructionsToSet = instructions == null ? new Text("") : instructions; feedbackSessionAttributes.setInstructions(instructionsToSet); return this; }
Source:
<code>public void should_initialise_actual() { Iterator<String> names = asList("Luke", "Leia").iterator(); <START> Iterable<String> actual = (Iterable<String>) assertThat(names).toIterable().actual; <END> assertThat(actual).containsOnly("Leia", "Luke"); }</code><technical_language>this test class deal Iterator, actual Iterator Iterable</technical_language>

Target:
public void should_initialise_actual() { Iterator<String> names = asList("Luke", "Leia").iterator(); Iterator<String> actual = (Iterator<String>) assertThat(names).actual; assertThat(actual).hasNext(); }
Source:
<code>KubernetesWatcher(@Named(BaragonKubernetesIntegrationModule.EVENT_LISTENERS) Map<KubernetesEvent, KubernetesEventListener> eventListeners) { <START> this.client = new DefaultKubernetesClient(); <END> this.executorService = Executors.newCachedThreadPool(); this.eventListeners = eventListeners; }</code><technical_language>eventually need a auth here. Default client works if env vars set if running in k8s, need a a token</technical_language>

Target:
KubernetesWatcher(@Named(BaragonKubernetesIntegrationModule.EVENT_LISTENERS) Map<KubernetesEvent, KubernetesEventListener> eventListeners) { Config config = new ConfigBuilder() .withMasterUrl(TEST_CLUSTER_URL) .build(); this.client = new DefaultKubernetesClient(config); this.executorService = Executors.newCachedThreadPool(); this.eventListeners = eventListeners; }
Source:
<code>protected void startScan() { for (RemoteDevice device : upnpService.getRegistry().getRemoteDevices()) { remoteDeviceAdded(upnpService.getRegistry(), device); } upnpService.getRegistry().addListener(this); upnpService.getControlPoint().search(); <START> upnpService.getControlPoint().search(new RootDeviceHeader()); <END> }</code><technical_language>UPnP expert: calls intention</technical_language>

Target:
protected void startScan() { for (RemoteDevice device : upnpService.getRegistry().getRemoteDevices()) { remoteDeviceAdded(upnpService.getRegistry(), device); } upnpService.getRegistry().addListener(this); upnpService.getControlPoint().search(); }
Source:
<code>public StepExecutionResult execute(ExecutionContext context) { if (skeletonManifestPath.getNameCount() == 0) { throw new HumanReadableException("Skeleton manifest filepath is missing"); } if (outManifestPath.getNameCount() == 0) { throw new HumanReadableException("Output Manifest filepath is missing"); } outManifestPath = filesystem.resolve(outManifestPath); try { Files.createParentDirs(outManifestPath.toFile()); } catch (IOException e) { e.printStackTrace(context.getStdErr()); return StepExecutionResult.ERROR; } List<File> libraryManifestFiles = Lists.newArrayList(); for (Path path : libraryManifestPaths) { Path manifestPath = filesystem.getPathForRelativeExistingPath(path).toAbsolutePath(); libraryManifestFiles.add(manifestPath.toFile()); } File skeletonManifestFile = filesystem.getPathForRelativeExistingPath(skeletonManifestPath).toAbsolutePath().toFile(); BuckEventAndroidLogger logger = new ManifestMergerLogger(context.getBuckEventBus()); MergingReport mergingReport = mergeManifests(skeletonManifestFile, libraryManifestFiles, logger); String xmlText = mergingReport.getMergedDocument(MergingReport.MergedManifestKind.MERGED); if (context.getPlatform() == Platform.WINDOWS) { xmlText = xmlText.replace("\r\n", "\n"); } try { <START> File outManifestFile = outManifestPath.toFile(); <END> Files.write(xmlText.getBytes(Charsets.UTF_8), outManifestFile); } catch (IOException e) { throw new HumanReadableException("Error converting line endings of manifest file"); } return StepExecutionResult.SUCCESS; }</code><technical_language>ProjectFileSystem.writeContentsToPath here</technical_language>

Target:
public StepExecutionResult execute(ExecutionContext context) { if (skeletonManifestPath.getNameCount() == 0) { throw new HumanReadableException("Skeleton manifest filepath is missing"); } if (outManifestPath.getNameCount() == 0) { throw new HumanReadableException("Output Manifest filepath is missing"); } outManifestPath = filesystem.resolve(outManifestPath); try { Files.createParentDirs(outManifestPath.toFile()); } catch (IOException e) { e.printStackTrace(context.getStdErr()); return StepExecutionResult.ERROR; } List<File> libraryManifestFiles = Lists.newArrayList(); for (Path path : libraryManifestPaths) { Path manifestPath = filesystem.getPathForRelativeExistingPath(path).toAbsolutePath(); libraryManifestFiles.add(manifestPath.toFile()); } File skeletonManifestFile = filesystem.getPathForRelativeExistingPath(skeletonManifestPath).toAbsolutePath().toFile(); BuckEventAndroidLogger logger = new ManifestMergerLogger(context.getBuckEventBus()); MergingReport mergingReport = mergeManifests(skeletonManifestFile, libraryManifestFiles, logger); String xmlText = mergingReport.getMergedDocument(MergingReport.MergedManifestKind.MERGED); if (context.getPlatform() == Platform.WINDOWS) { xmlText = xmlText.replace("\r\n", "\n"); } try { filesystem.writeContentsToPath(xmlText, outManifestPath); } catch (IOException e) { throw new HumanReadableException(e, "Error writing manifest file"); } return StepExecutionResult.SUCCESS; }
Source:
<code>public MethodOutcome updateLocationByName(@ResourceParam Location theLocation, @IdParam IdDt theId, @ConditionalUrlParam String theConditional) { MethodOutcome outcome = new MethodOutcome(); OperationOutcome operationoutcome = null; if (theConditional != null) { List<Location> locationList = null; String locationName = null; try { int startIndex = theConditional.lastIndexOf('='); locationName = theConditional.substring(startIndex + 1); } <START> catch (Exception e) { END> operationoutcome = new OperationOutcome(); operationoutcome.addIssue().setDetails("Please check Condition URL format"); outcome.setOperationOutcome(operationoutcome); return outcome; } StringParam nameParam = new StringParam(); nameParam.setValue(locationName); locationList = locationResource.searchLocationsByName(nameParam); if (locationList.size() == 0) { outcome = updateLocation(theLocation, null); } else if (locationList.size() == 1) { outcome = updateLocation(theLocation, locationList.get(0).getId()); } else { throw new PreconditionFailedException("There are more than one Location for the given condition"); } } else { outcome = updateLocation(theLocation, theId); } return outcome; }</code><technical_language>catch need align java } catch(Exception e) java is wise do is check null pointer. array out of bounds here? catching generic exceptions</technical_language>

Target:
public MethodOutcome updateLocationByName(@ResourceParam Location theLocation, @IdParam IdDt theId, @ConditionalUrlParam String theConditional) { MethodOutcome outcome = new MethodOutcome(); OperationOutcome operationoutcome = null; if (theConditional != null) { List<Location> locationList = null; int startIndex = theConditional.lastIndexOf('='); String locationName = theConditional.substring(startIndex + 1); if (locationName == null) { operationoutcome = new OperationOutcome(); operationoutcome.addIssue().setDetails("Please check Condition URL format"); outcome.setOperationOutcome(operationoutcome); return outcome; } StringParam nameParam = new StringParam(); nameParam.setValue(locationName); locationList = locationResource.searchLocationsByName(nameParam); if (locationList.size() == 0) { outcome = updateLocation(theLocation, null); } else if (locationList.size() == 1) { outcome = updateLocation(theLocation, locationList.get(0).getId()); } else { throw new PreconditionFailedException("There are more than one Location for the given condition"); } } else { outcome = updateLocation(theLocation, theId); } return outcome; }
Source:
<code>public void tagAllBodyMassIndexAttributesManually() throws InterruptedException { openTagWizard(driver); selectEntityName(driver); <START> clealAllTagsConfirmationModalAndOK(driver); <END> assertEquals(getSelectedEntityName(driver), AbstractMappingServiceAppModel.TARGET_ENTITY_NAME); clickAutomaticTaggingButton(driver); checkGenderTagContent(); checkHeightTagContent(); checkWeightTagContentAfterRemovingOneTag(); clealAllTagsConfirmationModalAndCancel(driver); clealAllTagsConfirmationModalAndOK(driver); addTagsForBodyMadIndexAttributes(9); addTagsForBodyMadIndexAttributes(10); addTagsForBodyMadIndexAttributes(11); }</code><technical_language>cleal</technical_language>

Target:
public void tagAllBodyMassIndexAttributesManually() throws InterruptedException { openTagWizard(driver); selectEntityName(driver); clearAllTagsConfirmationModalAndOK(driver); assertEquals(getSelectedEntityName(driver), AbstractMappingServiceAppModel.TARGET_ENTITY_NAME); clickAutomaticTaggingButton(driver); checkGenderTagContent(); checkHeightTagContent(); checkWeightTagContentAfterRemovingOneTag(); clearAllTagsConfirmationModalAndCancel(driver); clearAllTagsConfirmationModalAndOK(driver); addTagsForBodyMadIndexAttributes(9); addTagsForBodyMadIndexAttributes(10); addTagsForBodyMadIndexAttributes(11); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_save) { oAuthBrowser(); } <START> if (mDrawerToggle.onOptionsItemSelected(item)) { <END> return true; } return super.onOptionsItemSelected(item); }</code><technical_language>This replaced return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_save) { oAuthBrowser(); } return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); }
Source:
<code>public long recreateAndLoadConglomerate(boolean isExternal, String implementation, boolean recreate_ifempty, DataValueDescriptor[] template, ColumnOrdering[] columnOrder, int[] collationIds, Properties properties, int temporaryFlag, long orig_conglomId, RowLocationRetRowSource rowSource, long[] rowCount) throws StandardException { long conglomId = createConglomerate(isExternal,implementation, template, <START> columnOrder, collationIds, properties, temporaryFlag, 0); <END> long rows_loaded = loadConglomerate(conglomId, true, rowSource); if (rowCount != null) rowCount[0] = rows_loaded; if (!recreate_ifempty && (rows_loaded == 0)) { dropConglomerate(conglomId); conglomId = orig_conglomId; } return conglomId; }</code><technical_language>constant</technical_language>

Target:
public long recreateAndLoadConglomerate(boolean isExternal, String implementation, boolean recreate_ifempty, DataValueDescriptor[] template, ColumnOrdering[] columnOrder, int[] collationIds, Properties properties, int temporaryFlag, long orig_conglomId, RowLocationRetRowSource rowSource, long[] rowCount) throws StandardException { long conglomId = createConglomerate(isExternal,implementation, template, columnOrder, collationIds, properties, temporaryFlag, Conglomerate.Priority.NORMAL); long rows_loaded = loadConglomerate(conglomId, true, rowSource); if (rowCount != null) rowCount[0] = rows_loaded; if (!recreate_ifempty && (rows_loaded == 0)) { dropConglomerate(conglomId); conglomId = orig_conglomId; } return conglomId; }
Source:
<code>public void testNotEliminateSorts() { @Language("SQL") String sql = "SELECT quantity, row_number() OVER (ORDER BY quantity) FROM lineitem ORDER BY tax"; PlanMatchPattern pattern = anyTree( sort( <START> window(windowMatcherBuilder -> windowMatcherBuilder <END> .specification(windowSpec) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), anyTree(LINEITEM_TABLESCAN_Q)))); assertUnitPlan(sql, pattern); }</code><technical_language>curious: remove anyTree</technical_language>

Target:
public void testNotEliminateSorts() { @Language("SQL") String sql = "SELECT quantity, row_number() OVER (ORDER BY quantity) FROM lineitem ORDER BY tax"; PlanMatchPattern pattern = anyTree( sort( anyTree( window(windowMatcherBuilder -> windowMatcherBuilder .specification(windowSpec) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), anyTree(LINEITEM_TABLESCAN_Q))))); assertUnitPlan(sql, pattern); }
Source:
<code>private boolean executeSshSoftFencingCommand(String version) { boolean result = true; EngineSSHClient sshClient = null; ByteArrayOutputStream cmdOut = null, cmdErr = null; try { sshClient = new EngineSSHClient(); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); cmdOut = new ByteArrayOutputStream(); cmdErr = new ByteArrayOutputStream(); sshClient.executeCommand(Config.<String> GetValue(ConfigValues.SshSoftFencingCommand, version), null, cmdOut, cmdErr); log.infoFormat("SSH Soft Fencing command executed on host {0}", getVds().getHostName()); } catch (Exception ex) { log.errorFormat("SSH Soft Fencing command failed on host {0}: {1}\nStdout: {2}\nStderr: {3}\nStacktrace: {4}", <START> getVds().getHostName(), ex.getMessage(), getCommandOutput(cmdOut), getCommandOutput(cmdErr), ex); <END> result = false; } finally { closeSshConnection(sshClient); } return result; }</code><technical_language>instead of adding a function initialize cmdOut cmdErr empty string instead of null..</technical_language>

Target:
private boolean executeSshSoftFencingCommand(String version) { boolean result = true; EngineSSHClient sshClient = null; ByteArrayOutputStream cmdOut = null, cmdErr = null; try { sshClient = new EngineSSHClient(); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); cmdOut = new ByteArrayOutputStream(); cmdErr = new ByteArrayOutputStream(); sshClient.executeCommand(Config.<String> GetValue(ConfigValues.SshSoftFencingCommand, version), null, cmdOut, cmdErr); log.infoFormat("SSH Soft Fencing command executed on host {0}", getVds().getHostName()); } catch (Exception ex) { log.errorFormat("SSH Soft Fencing command failed on host {0}: {1}", getVds().getHostName(), ex); logCommandOutput(cmdOut, "SSH Soft Fencing command standard output: {0}"); logCommandOutput(cmdErr, "SSH Soft Fencing command error output: {0}"); result = false; } finally { closeSshConnection(sshClient); } return result; }
Source:
<code>public void testSimpleScan() { <START> DefaultPlatformConfiguration defaultPlatformConfiguration = ConfigurationFileLoader.loadConfiguration(); <END> final DefaultClasspathScanner scanner = new DefaultClasspathScanner(defaultPlatformConfiguration.getListProperty(ROOT_PACKAGE_FOR_CLASSPATH_SCAN)); Set<Class<?>> classes = scanner.getTypesAnnotatedWith(Resources.class); assertNotNull(classes); assertEquals(classes.size(), 0); classes = scanner.getTypesAnnotatedWith(AnnotationForClasspathScanTest.class); assertNotNull(classes); assertEquals(classes.size(), 1); assertTrue(classes.contains(AnnotatedClassForClasspathScan.class)); }</code><technical_language>final</technical_language>

Target:
public void testSimpleScan() { final DefaultPlatformConfiguration defaultPlatformConfiguration = ConfigurationFileLoader.loadConfiguration(); final DefaultClasspathScanner scanner = new DefaultClasspathScanner(defaultPlatformConfiguration.getListProperty(ROOT_PACKAGE_FOR_CLASSPATH_SCAN)); Set<Class<?>> classes = scanner.getTypesAnnotatedWith(Resources.class); assertNotNull(classes); assertEquals(classes.size(), 0); classes = scanner.getTypesAnnotatedWith(AnnotationForClasspathScanTest.class); assertNotNull(classes); assertEquals(classes.size(), 1); assertTrue(classes.contains(AnnotatedClassForClasspathScan.class)); }
Source:
<code>protected List<Member> addIndirectMembers(PerunSession sess, Group group, List<Member> members, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException { List<Member> oldMembers = this.getGroupMembers(sess, group); for (Member member : members) { groupsManagerImpl.addMember(sess, group, member, MembershipType.INDIRECT, sourceGroupId); <START> setRequiredAttributes(sess, member, group); <END> } List<Member> newMembers = this.getGroupMembers(sess, group); newMembers.removeAll(oldMembers); for (Member member : newMembers) { getPerunBl().getAuditer().log(sess, "{} added to {}.", member, group); } return newMembers; }</code><technical_language>Move this "setRequiredAttributes" loging in newMembers cycle</technical_language>

Target:
protected List<Member> addIndirectMembers(PerunSession sess, Group group, List<Member> members, int sourceGroupId) throws InternalErrorException, AlreadyMemberException, WrongAttributeValueException, WrongReferenceAttributeValueException { List<Member> oldMembers = this.getGroupMembers(sess, group); for (Member member : members) { groupsManagerImpl.addMember(sess, group, member, MembershipType.INDIRECT, sourceGroupId); } List<Member> newMembers = this.getGroupMembers(sess, group); newMembers.removeAll(oldMembers); for (Member member : newMembers) { setRequiredAttributes(sess, member, group); getPerunBl().getAuditer().log(sess, "{} added to {}.", member, group); } return newMembers; }
Source:
<code>protected BrokerService createBroker() throws Exception, URISyntaxException { <START> System.setProperty("org.apache.activemq.SERIALIZABLE_PACKAGES", "java.lang,javax.security,java.util,org.apache.activemq,org.fusesource.hawtbuf,com.thoughtworks.xstream.mapper"); <END> return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); }</code><technical_language>java.util fixes tests in activemq-broker</technical_language>

Target:
protected BrokerService createBroker() throws Exception, URISyntaxException { System.setProperty("org.apache.activemq.SERIALIZABLE_PACKAGES", "java.util"); return BrokerFactory.createBroker(new URI("broker://()/localhost?persistent=false")); }
Source:
<code>public Table execute() { <START> if (_columnFamilies == null || _columnFamilies.isEmpty()) { <END> throw new MetaModelException("Creating a table without columnFamilies"); } final Table table = getTable(); ((HBaseDataContext) getUpdateCallback().getDataContext()).getHBaseClient().createTable(table.getName(), _columnFamilies); addNewTableToSchema(table); return getSchema().getTableByName(table.getName()); }</code><technical_language>Instead of requiring column families called out in a part of MetaModel's public API, do smart e.g. column names represent column families? For example, a dot-separated column name approach, "family1.foo" "family1.bar" represented column in column family. I need this in order retain compatibility public API. a big fan of introducing HBase-specific methods in UpdateCallback kinda idea of MetaModel in place (a uniform API for database access)</technical_language>

Target:
public Table execute() { Set<String> columnFamilies = getColumnFamilies(); if (columnFamilies == null || columnFamilies.isEmpty()) { throw new MetaModelException("Can't create a table without column families."); } final Table table = getTable(); ((HBaseDataContext) getUpdateCallback().getDataContext()).getHBaseClient().createTable(table.getName(), columnFamilies); addNewTableToSchema(table); return getSchema().getTableByName(table.getName()); }
Source:
<code>public DruidStatement prepare( final String query, final long maxRowCount, final AuthenticationResult authenticationResult ) { synchronized (lock) { try { ensure(State.NEW); sqlLifecycle.initialize(query, queryContext); this.authenticationResult = authenticationResult; PrepareResult prepareResult = sqlLifecycle.prepare(authenticationResult); this.maxRowCount = maxRowCount; this.query = query; <START> ArrayList<AvaticaParameter> params = new ArrayList<>(); <END> final RelDataType parameterRowType = prepareResult.getParameterRowType(); for (RelDataTypeField field : parameterRowType.getFieldList()) { RelDataType type = field.getType(); params.add( new AvaticaParameter( false, type.getPrecision(), type.getScale(), type.getSqlTypeName().getJdbcOrdinal(), type.getSqlTypeName().getName(), Object.class.getName(), field.getName())); } this.signature = Meta.Signature.create( createColumnMetaData(sqlLifecycle.rowType()), query, params, Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT ); this.state = State.PREPARED; } catch (Throwable t) { return closeAndPropagateThrowable(t); } return this; } }</code><technical_language>Moving building of parameter list a private helper method readability</technical_language>

Target:
public DruidStatement prepare( final String query, final long maxRowCount, final AuthenticationResult authenticationResult ) { synchronized (lock) { try { ensure(State.NEW); sqlLifecycle.initialize(query, queryContext); this.authenticationResult = authenticationResult; PrepareResult prepareResult = sqlLifecycle.prepare(authenticationResult); this.maxRowCount = maxRowCount; this.query = query; List<AvaticaParameter> params = new ArrayList<>(); final RelDataType parameterRowType = prepareResult.getParameterRowType(); for (RelDataTypeField field : parameterRowType.getFieldList()) { RelDataType type = field.getType(); params.add(createParameter(field, type)); } this.signature = Meta.Signature.create( createColumnMetaData(prepareResult.getRowType()), query, params, Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT ); this.state = State.PREPARED; } catch (Throwable t) { return closeAndPropagateThrowable(t); } return this; } }
Source:
<code>public void experimentRangeUpdated(TmfExperimentRangeUpdatedSignal signal) { TmfExperiment experiment = signal.getExperiment(); if (!experiment.equals(TmfExperiment.getCurrentExperiment())) { return; } long startTime = signal.getRange().getStartTime().normalize(0, TIME_SCALE).getValue(); TmfTimestamp startTS = new TmfTimestamp(startTime, TIME_SCALE); TmfTimestamp endTS = new TmfTimestamp(startTime + INITIAL_WINDOW_SPAN, TIME_SCALE); TmfTimeRange timeRange = new TmfTimeRange(startTS, endTS); <START> <END> requestTimeRangeData(experiment, timeRange); requestData(experiment, signal.getRange()); }</code><technical_language>In case of streaming this method is call repeatedly. for sub-sequent calls method (requestTimeRangeData() called, for time. HistogramView for example handles this case</technical_language>

Target:
public void experimentRangeUpdated(TmfExperimentRangeUpdatedSignal signal) { TmfExperiment experiment = signal.getExperiment(); if (!experiment.equals(TmfExperiment.getCurrentExperiment())) { return; } if (fSendRangeRequest) { fSendRangeRequest = false; long startTime = signal.getRange().getStartTime().normalize(0, TIME_SCALE).getValue(); TmfTimestamp startTS = new TmfTimestamp(startTime, TIME_SCALE); TmfTimestamp endTS = new TmfTimestamp(startTime + INITIAL_WINDOW_SPAN, TIME_SCALE); TmfTimeRange timeRange = new TmfTimeRange(startTS, endTS); requestTimeRangeData(experiment, timeRange); } requestData(experiment, signal.getRange()); }
Source:
<code>public ProgramState checkPostStatement(CheckerContext context, Tree syntaxNode) { <START> final PostStatementVisitor visitor = new PostStatementVisitor(context); <END> syntaxNode.accept(visitor); return visitor.programState; }</code><technical_language>AbstractStatementVisitor ? (and remove final...)</technical_language>

Target:
public ProgramState checkPostStatement(CheckerContext context, Tree syntaxNode) { AbstractStatementVisitor visitor = new PostStatementVisitor(context); syntaxNode.accept(visitor); return visitor.programState; }
Source:
<code>public RowFilter adapt(FilterAdapterContext context, ColumnPrefixFilter filter) throws IOException { <START> <END> byte[] prefix = filter.getPrefix(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(prefix.length * 2); readerExpressionHelper.writeQuotedExpression(prefix, outputStream); outputStream.write(ReaderExpressionHelper.ALL_QUALIFIERS_BYTES); return RowFilter.newBuilder() .setColumnQualifierRegexFilter( ByteString.copyFrom( outputStream.toByteArray())) .build(); }</code><technical_language>nit: remove blank line</technical_language>

Target:
public RowFilter adapt(FilterAdapterContext context, ColumnPrefixFilter filter) throws IOException { byte[] prefix = filter.getPrefix(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(prefix.length * 2); readerExpressionHelper.writeQuotedRegularExpression(prefix, outputStream); outputStream.write(ReaderExpressionHelper.ALL_QUALIFIERS_BYTES); return RowFilter.newBuilder() .setColumnQualifierRegexFilter( ByteString.copyFrom( outputStream.toByteArray())) .build(); }
Source:
<code>public void validate(final Integer studyId, final Boolean shouldBeUnlocked) { this.errors = new MapBindingResult(new HashMap<String, String>(), Integer.class.getName()); if (studyId == null) { this.errors.reject("study.required", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } final Study study = this.studyDataManager.getStudy(studyId); if (study == null) { this.errors.reject("study.not.exist", ""); throw new ResourceNotFoundException(this.errors.getAllErrors().get(0)); } if (shouldBeUnlocked) { <START> this.checkIfStudyIsUnlocked(study); <END> } final String programUUID = ContextHolder.getCurrentProgram(); if (programUUID == null) { this.errors.reject("study.required", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } if (!programUUID.equals(study.getProgramUUID())) { this.errors.reject("invalid.program.uuid.study", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } }</code><technical_language>checkIfStudyIsUnlocked is inaccurate user edit a locked study if is owner is a superadmin</technical_language>

Target:
public void validate(final Integer studyId, final Boolean shouldBeUnlocked) { this.errors = new MapBindingResult(new HashMap<String, String>(), Integer.class.getName()); if (studyId == null) { this.errors.reject("study.required", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } final Study study = this.studyDataManager.getStudy(studyId); if (study == null) { this.errors.reject("study.not.exist", ""); throw new ResourceNotFoundException(this.errors.getAllErrors().get(0)); } if (shouldBeUnlocked) { this.checkIfStudyIsLockedForCurrentUser(study); } final String programUUID = ContextHolder.getCurrentProgram(); if (programUUID == null) { this.errors.reject("study.required", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } if (!programUUID.equals(study.getProgramUUID())) { this.errors.reject("invalid.program.uuid.study", ""); throw new ApiRequestValidationException(this.errors.getAllErrors()); } }
Source:
<code>protected Notifier getNotifierFromEditorInput(Object editorInput) { Object input = editorInput; if (input instanceof RootObject) { final EObject root = ((RootObject) input).getRoot(); <START> if (root.eResource() != null) { <END> input = root.eResource(); } else { input = root; } } if (!Notifier.class.isInstance(input)) { throw new IllegalStateException("The editor input is not a Notifier!"); } return (Notifier) input; }</code><technical_language>In case a resource? previously setting resource input. this change break existing clients of GenericEditor class, especially subclasses</technical_language>

Target:
protected Notifier getNotifierFromEditorInput(Object editorInput) { Object input = editorInput; if (input instanceof RootObject) { input = ((RootObject) input).getRoot(); } if (!Notifier.class.isInstance(input)) { throw new IllegalStateException("The editor input is not a Notifier!"); } return (Notifier) input; }