auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected SSLContext getSslContext(ElasticSearchClientConfig config) { if (StringUtils.isBlank(config.getOption(KEYSTORE_PATH_OPT))) { return null; } try { Path keyStorePath = Paths.get(config.getOption(KEYSTORE_PATH_OPT)); String keyStorePass = config.getOption(KEYSTORE_PASSWORD_OPT); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream is = Files.newInputStream(keyStorePath)) { keyStore.load(is, keyStorePass.toCharArray()); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(keyStore, null); return sslBuilder.build(); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException <START> | KeyManagementException e) { <END> throw new NuxeoException("Cannot setup SSL for RestClient: " + config, e); } }</code><technical_language>GeneralSecurityException for of those</technical_language>

Target:
protected SSLContext getSslContext(ElasticSearchClientConfig config) { if (StringUtils.isBlank(config.getOption(KEYSTORE_PATH_OPT))) { return null; } try { Path keyStorePath = Paths.get(config.getOption(KEYSTORE_PATH_OPT)); String keyStorePass = config.getOption(KEYSTORE_PASSWORD_OPT); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream is = Files.newInputStream(keyStorePath)) { keyStore.load(is, keyStorePass.toCharArray()); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(keyStore, null); return sslBuilder.build(); } catch (GeneralSecurityException | IOException e) { throw new NuxeoException("Cannot setup SSL for RestClient: " + config, e); } }
Source:
<code>public void processEvent(final Map<String, String> dispatchMap) { final Object countObject = dispatchMap.get(EventStrings.HTTP_EVENT_COUNT); if (countObject == null) { dispatchMap.put(EventStrings.HTTP_EVENT_COUNT, "1"); } else { dispatchMap.put(EventStrings.HTTP_EVENT_COUNT, Integer.toString(Integer.parseInt((String) countObject) + 1)); } final List eventList = getEventList(); final int size = eventList.size(); for (int i = 0; i < size; i++) { final Pair eventPair = (Pair<String, String>) eventList.get(i); final String name = (String) eventPair.first; if (name.equals(EventStrings.HTTP_RESPONSE_CODE) || name.equals(EventStrings.REQUEST_ID_HEADER) || name.equals(EventStrings.OAUTH_ERROR_CODE) || name.equals(EventStrings.HTTP_PATH)) { dispatchMap.put(name, (String) eventPair.second); } <START> } <END> }</code><technical_language>for events, consider refactoring? #Pending</technical_language>

Target:
public void processEvent(final Map<String, String> dispatchMap) { final Object countObject = dispatchMap.get(EventStrings.HTTP_EVENT_COUNT); if (countObject == null) { dispatchMap.put(EventStrings.HTTP_EVENT_COUNT, "1"); } else { dispatchMap.put(EventStrings.HTTP_EVENT_COUNT, Integer.toString(Integer.parseInt((String) countObject) + 1)); } if (dispatchMap.containsKey(EventStrings.HTTP_RESPONSE_CODE)) { dispatchMap.put(EventStrings.HTTP_RESPONSE_CODE, ""); } if (dispatchMap.containsKey(EventStrings.OAUTH_ERROR_CODE)) { dispatchMap.put(EventStrings.OAUTH_ERROR_CODE, ""); } if (dispatchMap.containsKey(EventStrings.HTTP_PATH)) { dispatchMap.put(EventStrings.HTTP_PATH, ""); } if (dispatchMap.containsKey(EventStrings.REQUEST_ID_HEADER)) { dispatchMap.put(EventStrings.REQUEST_ID_HEADER, ""); } final List<Pair<String, String>> eventList = getEventList(); for (Pair<String, String> eventPair : eventList) { final String name = eventPair.first; if (name.equals(EventStrings.HTTP_RESPONSE_CODE) || name.equals(EventStrings.REQUEST_ID_HEADER) || name.equals(EventStrings.OAUTH_ERROR_CODE) || name.equals(EventStrings.HTTP_PATH)) { dispatchMap.put(name, eventPair.second); } } }
Source:
<code>public Collection<ManagedThreadPoolExecutor> getMBeans() { <START> return mBeans; <END> }</code><technical_language>want callers modify collection, sense wrap in a Collections.unmodifiableList()</technical_language>

Target:
public Collection<ManagedThreadPoolExecutor> getMBeans() { return Collections.unmodifiableList(mBeans); }
Source:
<code>public SimpleActionButton() { <START> super(); <END> initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); button.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { button.removeStyleName(style.buttonMouseOver()); button.addStyleName(style.buttonMouseOut()); } }); button.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { button.removeStyleName(style.buttonMouseOut()); button.addStyleName(style.buttonMouseOver()); } }); button.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { button.removeStyleName(style.buttonMouseOver()); button.addStyleName(style.buttonMouseOut()); } }); }</code><technical_language>super() is implied</technical_language>

Target:
public SimpleActionButton() { initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this)); button.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { button.removeStyleName(style.buttonMouseOver()); button.addStyleName(style.buttonMouseOut()); } }); button.addMouseOverHandler(new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { button.removeStyleName(style.buttonMouseOut()); button.addStyleName(style.buttonMouseOver()); } }); button.addMouseOutHandler(new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { button.removeStyleName(style.buttonMouseOver()); button.addStyleName(style.buttonMouseOut()); } }); }
Source:
<code>private Object loadCompilerShim(ExecutionContext context) { try { ClassLoaderCache classLoaderCache = context.getClassLoaderCache(); classLoaderCache.addRef(); ClassLoader classLoader = classLoaderCache.getClassLoaderForClassPath( <START> ToolProvider.getSystemToolClassLoader(), <END> ImmutableList.copyOf( compilerClassPath .stream() .map(p -> ((PathSourcePath) p).getRelativePath()) .map(PATH_TO_URL) .iterator())); return classLoader.loadClass(COMPILER_CLASS).newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } }</code><technical_language>ToolProvider is thread safe, need synchronize this (currently single) other usage of ToolProvider, else strange intermittent failures running buckd</technical_language>

Target:
private Object loadCompilerShim(ExecutionContext context) { try { ClassLoaderCache classLoaderCache = context.getClassLoaderCache(); classLoaderCache.addRef(); ClassLoader classLoader = classLoaderCache.getClassLoaderForClassPath( SynchronizedToolProvider.getSystemToolClassLoader(), ImmutableList.copyOf( compilerClassPath .stream() .map(p -> ((PathSourcePath) p).getRelativePath()) .map(PATH_TO_URL) .iterator())); return classLoader.loadClass(COMPILER_CLASS).newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } }
Source:
<code>public T update(final T object) { validateCredentials(object); <START> if (JDOHelper.getObjectState(object) == ObjectState.TRANSIENT) { <END> throw new UpdateFromTransientException(); } updateModificationData(object); final T updatedInstance = repository.update(object); if (!getComboboxStringFields().isEmpty()) { updateComboList(object); } if (recordHistory) { historyService.record(updatedInstance); } TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { if (allowUpdateEvent) { sendEvent((Long) getId(updatedInstance), UPDATE); } } }); return updatedInstance; }</code><technical_language>if, if in this case, try fetch database ID, PropertyUtil copy properties? If id is set, object throw exception</technical_language>

Target:
public T update(final T object) { validateCredentials(object); if (JDOHelper.getObjectState(object) == ObjectState.TRANSIENT) { return updateFromTransient(object); } updateModificationData(object); final T updatedInstance = repository.update(object); if (recordHistory) { historyService.record(updatedInstance); } TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { if (allowUpdateEvent) { sendEvent((Long) getId(updatedInstance), UPDATE); } } }); return updatedInstance; }
Source:
<code>public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof ThriftMessage) { ThriftMessage message = (ThriftMessage) e.getMessage(); if (taskTimeoutMillis > 0) { message.setProcessStartTimeMillis(System.currentTimeMillis()); } checkResponseOrderingRequirements(ctx, message); TNiftyTransport messageTransport = new TNiftyTransport(ctx.getChannel(), message); TTransportPair transportPair = TTransportPair.fromSingleTransport(messageTransport); TProtocolPair protocolPair = duplexProtocolFactory.getProtocolPair(transportPair); TProtocol inProtocol = protocolPair.getInputProtocol(); TProtocol outProtocol = protocolPair.getOutputProtocol(); try { processRequest(ctx, message, messageTransport, inProtocol, outProtocol); } catch (RejectedExecutionException ex) { TApplicationException x = new TApplicationException(TApplicationException.INTERNAL_ERROR, "Server overloaded"); <START> sendTApplicationException(x, ctx, message, dispatcherSequenceId.get(), messageTransport, inProtocol, outProtocol); <END> } } else { ctx.sendUpstream(e); } }</code><technical_language>a good idea move catch (RejectedExecutionException) processRequest need .get() atomic, local requestSequenceId</technical_language>

Target:
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof ThriftMessage) { ThriftMessage message = (ThriftMessage) e.getMessage(); if (taskTimeoutMillis > 0) { message.setProcessStartTimeMillis(System.currentTimeMillis()); } checkResponseOrderingRequirements(ctx, message); TNiftyTransport messageTransport = new TNiftyTransport(ctx.getChannel(), message); TTransportPair transportPair = TTransportPair.fromSingleTransport(messageTransport); TProtocolPair protocolPair = duplexProtocolFactory.getProtocolPair(transportPair); TProtocol inProtocol = protocolPair.getInputProtocol(); TProtocol outProtocol = protocolPair.getOutputProtocol(); processRequest(ctx, message, messageTransport, inProtocol, outProtocol); } else { ctx.sendUpstream(e); } }
Source:
<code>private HttpResponse handleResponse(final HttpHost httpHost, final HttpRequest request, final HttpResponse originalResponse, final HttpContext context) throws IOException { final GoodDataChallengeType challenge = identifyGoodDataChallenge(originalResponse); if (challenge == GoodDataChallengeType.UNKNOWN) { return originalResponse; } EntityUtils.consume(originalResponse.getEntity()); <START> final boolean entered = authLock.tryLock(); <END> if (entered) { try { final Lock writeLock = rwLock.writeLock(); writeLock.lock(); boolean doSST = true; try { if (challenge == GoodDataChallengeType.TT && sst != null) { if (refreshTt()) { doSST = false; } } if (doSST) { sst = sstStrategy.obtainSst(httpClient, authHost); if (!refreshTt()) { throw new GoodDataAuthException("Unable to obtain TT after successfully obtained SST"); } } } catch (GoodDataAuthException e) { return new BasicHttpResponse(new BasicStatusLine(originalResponse.getProtocolVersion(), HttpStatus.SC_UNAUTHORIZED, e.getMessage())); } finally { writeLock.unlock(); } } finally { authLock.unlock(); } } return this.execute(httpHost, request, context); }</code><technical_language>please consider inlineing</technical_language>

Target:
private HttpResponse handleResponse(final HttpHost httpHost, final HttpRequest request, final HttpResponse originalResponse, final HttpContext context) throws IOException { final GoodDataChallengeType challenge = identifyGoodDataChallenge(originalResponse); if (challenge == GoodDataChallengeType.UNKNOWN) { return originalResponse; } EntityUtils.consume(originalResponse.getEntity()); if (authLock.tryLock()) { try { final Lock writeLock = rwLock.writeLock(); writeLock.lock(); boolean doSST = true; try { if (challenge == GoodDataChallengeType.TT && sst != null) { if (refreshTt()) { doSST = false; } } if (doSST) { sst = sstStrategy.obtainSst(httpClient, authHost); if (!refreshTt()) { throw new GoodDataAuthException("Unable to obtain TT after successfully obtained SST"); } } } catch (GoodDataAuthException e) { return new BasicHttpResponse(new BasicStatusLine(originalResponse.getProtocolVersion(), HttpStatus.SC_UNAUTHORIZED, e.getMessage())); } finally { writeLock.unlock(); } } finally { authLock.unlock(); } } return this.execute(httpHost, request, context); }
Source:
<code>public GrasSimulatedUser(User other, ISchedulingState cluster) { super(other, cluster); Map<String, Double> guaranteedGenericResources = new HashMap<>(); <START> Map<String, Double> availGenericResources = cluster.getClusterTotalGenericResource(); END> for (Map.Entry<String, Double> entry : availGenericResources.entrySet()) { String resource = entry.getKey(); Double guaranteedAmount = other.getGenericGuaranteed().getOrDefault(resource, 0.0); guaranteedGenericResources.put(resource, guaranteedAmount); } this.guaranteedGenericResources = guaranteedGenericResources; }</code><technical_language>Instead of getClusterTotalGenericResource here, adding getClusterTotalGenericResourceType cluster avoid calculations.. like: @Override public Set<String> getClusterGenericResourceTypes() { Set<String> resourceTypes = supervisors.values().parallelStream().map(sup -> sup.getTotalGenericResources().keySet()).flatMap(Set::stream).collect(Collectors.toSet()); return resourceTypes; }</technical_language>

Target:
public GrasSimulatedUser(User other, ISchedulingState cluster) { super(other, cluster); Map<String, Double> guaranteedGenericResources = new HashMap<>(); Set<String> availGenericResourceTypes = cluster.getClusterTotalGenericResources().keySet(); for (String resourceType : availGenericResourceTypes) { Double guaranteedAmount = other.getGenericGuaranteed().getOrDefault(resourceType, 0.0); guaranteedGenericResources.put(resourceType, guaranteedAmount); } this.guaranteedGenericResources = guaranteedGenericResources; }
Source:
<code>private ValidationResult referencedNetworkAttachmentActuallyExists(Guid networkAttachmentId) { boolean doesNotReferenceExistingNetworkAttachment = networkAttachmentId == null; if (doesNotReferenceExistingNetworkAttachment) { return ValidationResult.VALID; } for (NetworkAttachment existingAttachment : existingAttachments) { if (existingAttachment.getId().equals(networkAttachmentId)) { return ValidationResult.VALID; } } <START> return new ValidationResult(EngineMessage.NETWORK_ATTACHMENT_NOT_EXISTS); <END> }</code><technical_language>message is- NETWORK_ATTACHMENT_NOT_EXISTS=Cannot ${action} ${type}. Network Attachment (id '${NETWORK_ATTACHMENT_NOT_EXISTS_ENTITY}') exist. pass id replacement</technical_language>

Target:
private ValidationResult referencedNetworkAttachmentActuallyExists(Guid networkAttachmentId) { boolean doesNotReferenceExistingNetworkAttachment = networkAttachmentId == null; if (doesNotReferenceExistingNetworkAttachment) { return ValidationResult.VALID; } for (NetworkAttachment existingAttachment : existingAttachments) { if (existingAttachment.getId().equals(networkAttachmentId)) { return ValidationResult.VALID; } } EngineMessage engineMessage = EngineMessage.NETWORK_ATTACHMENT_NOT_EXISTS; String id = networkAttachmentId.toString(); String replacement = ReplacementUtils.getVariableAssignmentString(engineMessage, id); return new ValidationResult(engineMessage, replacement); }
Source:
<code><START> public void updatePerson(Person person) { <END> person.setLastUpdated(new DateTime(DateTimeZones.UTC)); person.setMediaType(null); DBObject idQuery = translator.idQuery(person.getCanonicalUri()).build(); persistenceAuditLog.logWrite(person); collection.update(idQuery, translator.writeUpdate(idQuery, person), true, false); lookupEntryStore.store(LookupEntry.lookupEntryFrom(person)); writeEquivalences(person); }</code><technical_language>Override annotation</technical_language>

Target:
public void updatePerson(Person person) { person.setLastUpdated(new DateTime(DateTimeZones.UTC)); person.setMediaType(null); DBObject idQuery = translator.idQuery(person.getCanonicalUri()).build(); persistenceAuditLog.logWrite(person); collection.update(idQuery, translator.mainPersonFieldsToDBObject(idQuery, person), true, false); lookupEntryStore.store(LookupEntry.lookupEntryFrom(person)); writeEquivalences(person); }
Source:
<code>protected BookieServer startBookie(ServerConfiguration conf) throws Exception { BookieServer server = new BookieServer(conf); BookieSocketAddress address = Bookie.getBookieAddress(conf); if (bkc == null) { bkc = new BookKeeperTestClient(baseClientConf); } Future<?> waitForBookie = bkc.waitForBookie(address); server.start(); waitForBookie.get(30, TimeUnit.SECONDS); <START> LOG.info("New bookie, {}, has been created.", address); <END> try { startAutoRecovery(server, conf); } catch (CompatibilityException ce) { LOG.error("Exception while starting AutoRecovery!", ce); } catch (UnavailableException ue) { LOG.error("Exception while starting AutoRecovery!", ue); } return server; }</code><technical_language>nit: "New bookie '{}' created."</technical_language>

Target:
protected BookieServer startBookie(ServerConfiguration conf) throws Exception { BookieServer server = new BookieServer(conf); BookieSocketAddress address = Bookie.getBookieAddress(conf); if (bkc == null) { bkc = new BookKeeperTestClient(baseClientConf); } Future<?> waitForBookie = conf.isForceReadOnlyBookie() ? bkc.waitForReadOnlyBookie(address) : bkc.waitForWritableBookie(address); server.start(); waitForBookie.get(30, TimeUnit.SECONDS); LOG.info("New bookie '{}' has been created.", address); try { startAutoRecovery(server, conf); } catch (CompatibilityException ce) { LOG.error("Exception while starting AutoRecovery!", ce); } catch (UnavailableException ue) { LOG.error("Exception while starting AutoRecovery!", ue); } return server; }
Source:
<code>private static String cpuToConstraint(CPU cpu) { switch (cpu) { case X86_32: return "@bazel_tools case X86_64: return "@bazel_tools case PPC: return "@bazel_tools case ARM: return "@bazel_tools case AARCH64: return "@bazel_tools case S390X: return "@bazel_tools } <START> return null; <END> }</code><technical_language>this crash fed ImmutableList? Is a cleaner error mode</technical_language>

Target:
static String cpuToConstraint(CPU cpu) { switch (cpu) { case X86_32: return "@bazel_tools case X86_64: return "@bazel_tools case PPC: return "@bazel_tools case ARM: return "@bazel_tools case AARCH64: return "@bazel_tools case S390X: return "@bazel_tools } return null; }
Source:
<code>private void updateSiteOrFinishActivity(Bundle savedInstanceState) { if (savedInstanceState == null) { if (getArguments() != null) { mSite = (SiteModel) getArguments().getSerializable(WordPress.SITE); <START> mPost = mPostStore.getPostByLocalPostId(getArguments().getInt(EditPostActivity.EXTRA_POST_LOCAL_ID)); <END> } else { mSite = (SiteModel) getActivity().getIntent().getSerializableExtra(WordPress.SITE); mPost = mPostStore.getPostByLocalPostId(getActivity().getIntent() .getIntExtra(EditPostActivity.EXTRA_POST_LOCAL_ID, 0)); } } else { mSite = (SiteModel) savedInstanceState.getSerializable(WordPress.SITE); mPost = mPostStore.getPostByLocalPostId(savedInstanceState.getInt(EditPostActivity.EXTRA_POST_LOCAL_ID)); } if (mSite == null) { ToastUtils.showToast(getActivity(), R.string.blog_not_found, ToastUtils.Duration.SHORT); getActivity().finish(); } }</code><technical_language>Serializing de-serializing post this do reference post. this creates a new object, is updated mPost is updated in EditPostActivity. a result preview show post opened (for new posts, preview is blank). loadPost() method account for this</technical_language>

Target:
private void updateSiteOrFinishActivity(Bundle savedInstanceState) { if (savedInstanceState == null) { if (getArguments() != null) { mSite = (SiteModel) getArguments().getSerializable(WordPress.SITE); } else { mSite = (SiteModel) getActivity().getIntent().getSerializableExtra(WordPress.SITE); } } else { mSite = (SiteModel) savedInstanceState.getSerializable(WordPress.SITE); } if (mSite == null) { ToastUtils.showToast(getActivity(), R.string.blog_not_found, ToastUtils.Duration.SHORT); getActivity().finish(); } }
Source:
<code>public void checkFillSelectionAfterSelectingDatasetAuthentication() throws Exception { enableService(); Bundle clientState = new Bundle(); clientState.putCharSequence("clientStateKey", "clientStateValue"); final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1, new CannedDataset.Builder() .setField(ID_USERNAME, "dude") .setField(ID_PASSWORD, "sweet") .setPresentation(createPresentation("Dataset")) .build()); sReplier.addResponse(new CannedFillResponse.Builder().addDataset( new CannedDataset.Builder() .setField(ID_USERNAME, "username") .setId("name") .setPresentation(createPresentation("authentication")) .setAuthentication(authentication) .build()) .setExtras(clientState).build()); mActivity.onUsername(View::requestFocus); sUiBot.selectDataset("authentication"); sReplier.getNextFillRequest(); eventually(() -> { FillEventHistory selection = InstrumentedAutoFillService.peekInstance() .getFillEventHistory(); assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo( "clientStateValue"); <START> assertThat(selection.getEvents().size()).isAtLeast(1); assertThat(selection.getEvents().size()).isAtMost(2); <END> FillEventHistory.Event event = selection.getEvents().get(0); assertThat(event.getType()).isEqualTo(TYPE_DATASET_AUTHENTICATION_SELECTED); assertThat(event.getDatasetId()).isEqualTo("name"); }); }</code><technical_language>This test check for exact number of events, contents. If currently failing due devices performance, need fix test some sort of synchronization</technical_language>

Target:
public void checkFillSelectionAfterSelectingDatasetAuthentication() throws Exception { enableService(); Bundle clientState = new Bundle(); clientState.putCharSequence("clientStateKey", "clientStateValue"); final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1, new CannedDataset.Builder() .setField(ID_USERNAME, "dude") .setField(ID_PASSWORD, "sweet") .setPresentation(createPresentation("Dataset")) .build()); sReplier.addResponse(new CannedFillResponse.Builder().addDataset( new CannedDataset.Builder() .setField(ID_USERNAME, "username") .setId("name") .setPresentation(createPresentation("authentication")) .setAuthentication(authentication) .build()) .setExtras(clientState).build()); mActivity.onUsername(View::requestFocus); sUiBot.selectDataset("authentication"); sReplier.getNextFillRequest(); eventually(() -> { FillEventHistory selection = InstrumentedAutoFillService.peekInstance() .getFillEventHistory(); assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo( "clientStateValue"); assertThat(selection.getEvents().size()).isEqualTo(2); FillEventHistory.Event event = selection.getEvents().get(0); assertThat(event.getType()).isEqualTo(TYPE_DATASET_AUTHENTICATION_SELECTED); assertThat(event.getDatasetId()).isEqualTo("name"); }); }
Source:
<code>public MapillarySequence(final String key, final String userKey, String organizationKey, final long capturedAt) { this.images = new CopyOnWriteArrayList<>(); this.key = key; this.capturedAt = capturedAt; <START> if (userKey != null) { <END> setUser(userKey); } if (organizationKey != null) { setOrganization(organizationKey); } }</code><technical_language>If userKey/organizationKey is null, reflected in object</technical_language>

Target:
public MapillarySequence(final String key, final String userKey, String organizationKey, final long capturedAt) { this.images = new CopyOnWriteArrayList<>(); this.key = key; this.capturedAt = capturedAt; setUser(userKey); setOrganization(organizationKey); }
Source:
<code>public String getDescription() { return "Split a geometry with another geometry\n." + "Supported operations are : \n" <START> + "<ul>Split a polygon with a linestring</ul>" <END> + "<ul>Split a multilinestring with a linestring or a point</ul>" + "<ul>Split a linestring with a linestring or a point</ul>" + "Note : if the second geometry is a point\n" + "the user can specify a tolerance to snap\n" + "the point to the geometry. The default tolerance is : \n" + "10E-6"; }</code><technical_language>This is [unordered list](<LINK_0> in HTML. Example: html <ul> <li>Coffee</li> <li>Milk</li> </ul> produces - Coffee - Milk</technical_language>

Target:
public String getDescription() { return "<html>Split a geometry with another geometry\n." + "Supported operations are : \n" + "<ul><li>Split a polygon with a linestring</li>" + "<li>Split a multilinestring with a linestring or a point</li>" + "<li>Split a linestring with a linestring or a point</li>" + "Note : if the second geometry is a point\n" + "the user can specify a tolerance to snap\n" + "the point to the geometry. The default tolerance is : \n" + "10^(-6) meters.</ul></html>"; }
Source:
<code>public Set<InstalledDriver> getInstalledDrivers(String profileName) { <START> Set installedDrivers = new HashSet<InstalledDriver>(); <END> if (profileName != null) { if (drivers.get(profileName) == null) { throw ROOT_LOGGER.noDriverDefinedInDefaultProfile(); } installedDrivers.addAll(drivers.get(profileName).values()); } if (drivers.get(DEFAULT_PROFILE) != null) { installedDrivers.addAll(drivers.get(DEFAULT_PROFILE).values()); } return Collections.unmodifiableSet(Collections.synchronizedSet(installedDrivers)); }</code><technical_language>fix generics this compiler warns away</technical_language>

Target:
public Set<InstalledDriver> getInstalledDrivers(String profileName) { Set<InstalledDriver> installedDrivers = new HashSet<>(); synchronized (drivers) { if (profileName != null) { if (drivers.get(profileName) != null) { installedDrivers.addAll(drivers.get(profileName).values()); } } else { if (drivers.get(DEFAULT_PROFILE) == null) { throw ROOT_LOGGER.noDriverDefinedInDefaultProfile(); } } if (drivers.get(DEFAULT_PROFILE) != null) { installedDrivers.addAll(drivers.get(DEFAULT_PROFILE).values()); } } return Collections.unmodifiableSet(installedDrivers); }
Source:
<code>private void split() { mChildren = new PointQuadTree[]{ new PointQuadTree(mBounds.minX, mBounds.minY, mBounds.midX, mBounds.midY, mDepth + 1), new PointQuadTree(mBounds.midX, mBounds.minY, mBounds.maxX, mBounds.midY, mDepth + 1), new PointQuadTree(mBounds.minX, mBounds.midY, mBounds.midX, mBounds.maxY, mDepth + 1), new PointQuadTree(mBounds.midX, mBounds.midY, mBounds.maxX, mBounds.maxY, mDepth + 1) }; List<T> items = mItems; mItems = null; for (T item : items) { add(item); } <START> items.clear(); <END> }</code><technical_language>This is unnecessary; garbage collector care of it</technical_language>

Target:
private void split() { mChildren = new PointQuadTree[]{ new PointQuadTree(mBounds.minX, mBounds.minY, mBounds.midX, mBounds.midY, mDepth + 1), new PointQuadTree(mBounds.midX, mBounds.minY, mBounds.maxX, mBounds.midY, mDepth + 1), new PointQuadTree(mBounds.minX, mBounds.midY, mBounds.midX, mBounds.maxY, mDepth + 1), new PointQuadTree(mBounds.midX, mBounds.midY, mBounds.maxX, mBounds.maxY, mDepth + 1) }; List<T> items = mItems; mItems = null; for (T item : items) { add(item); } }
Source:
<code>public static List<StreamInterceptor> getInterceptors() { if (!isLoadedAlready) { loadInterceptors(); isLoadedAlready = true; } <START> return Collections.unmodifiableList(interceptors); <END> }</code><technical_language>PassthruHttpListener.init called concurrently? If so, this method get called concurrently list of interceptors corrupted, arraylist is thread safe</technical_language>

Target:
public static List<StreamInterceptor> getInterceptors() { if (!isLoadedAlready) { try { lock.lock(); if (!isLoadedAlready) { loadInterceptors(); isLoadedAlready = true; } } finally { lock.unlock(); } } return Collections.unmodifiableList(interceptors); }
Source:
<code>protected static void assertRequestHasCommonProperties(final RecordedRequest request) { assertEquals(request.getMethod(), "POST"); assertEquals(request.getHeader(HttpHeaders.AUTHORIZATION), authHeader); <START> assertEquals(request.getHeader(HttpHeaders.ACCEPT), MediaType.TEXT_XML); <END> }</code><technical_language>want request is right endpoint. In this case, add a common assertion verify requests done "/"</technical_language>

Target:
protected static void assertRequestHasCommonProperties(final RecordedRequest request) { assertEquals(request.getMethod(), "POST"); assertEquals(request.getPath(), rootUrl); assertEquals(request.getHeader(HttpHeaders.AUTHORIZATION), authHeader); assertEquals(request.getHeader(HttpHeaders.ACCEPT), MediaType.TEXT_XML); }
Source:
<code>public void testDefaultLoggerClosesItStreams() throws Exception { final Checker checker = new Checker(); try (CloseAndFlushTestByteArrayOutputStream testInfoOutputStream = new CloseAndFlushTestByteArrayOutputStream(); CloseAndFlushTestByteArrayOutputStream testErrorOutputStream = new CloseAndFlushTestByteArrayOutputStream()) { checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.addListener(new DefaultLogger(testInfoOutputStream, OutputStreamOptions.CLOSE, testErrorOutputStream, OutputStreamOptions.CLOSE)); final File tmpFile = temporaryFolder.newFile("file.java"); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; <START> <END> verify(checker, tmpFile.getPath(), expected); assertWithMessage("Close count") .that(testInfoOutputStream.getCloseCount()) .isEqualTo(1); assertWithMessage("Flush count") .that(testInfoOutputStream.getFlushCount()) .isAnyOf(3, 4); assertWithMessage("Close count") .that(testErrorOutputStream.getCloseCount()) .isEqualTo(1); assertWithMessage("Flush count") .that(testErrorOutputStream.getFlushCount()) .isAnyOf(1, 2); } }</code><technical_language>I 2 sets of close/flush count. expand text show differences. IE: Error close count, Output close count, etc..</technical_language>

Target:
public void testDefaultLoggerClosesItStreams() throws Exception { final Checker checker = new Checker(); try (CloseAndFlushTestByteArrayOutputStream testInfoOutputStream = new CloseAndFlushTestByteArrayOutputStream(); CloseAndFlushTestByteArrayOutputStream testErrorOutputStream = new CloseAndFlushTestByteArrayOutputStream()) { checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.addListener(new DefaultLogger(testInfoOutputStream, OutputStreamOptions.CLOSE, testErrorOutputStream, OutputStreamOptions.CLOSE)); final File tmpFile = temporaryFolder.newFile("file.java"); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; verify(checker, tmpFile.getPath(), expected); assertWithMessage("Output stream close count") .that(testInfoOutputStream.getCloseCount()) .isEqualTo(1); assertWithMessage("Output stream flush count") .that(testInfoOutputStream.getFlushCount()) .isEqualTo(TestUtil.adjustFlushCountForOutputStreamClose(3)); assertWithMessage("Error stream close count") .that(testErrorOutputStream.getCloseCount()) .isEqualTo(1); assertWithMessage("Error stream flush count") .that(testErrorOutputStream.getFlushCount()) .isEqualTo(TestUtil.adjustFlushCountForOutputStreamClose(1)); } }
Source:
<code>protected final long evalLong(long left, long right) { <START> return LongMath.pow(left, (int) right); <END> }</code><technical_language>Ints.checkedCast() for sanity</technical_language>

Target:
protected final long evalLong(long left, long right) { return LongMath.pow(left, Ints.checkedCast(right)); }
Source:
<code>public String getInstanceId() { String[] parts = clusterName.split("/"); <START> Preconditions.checkState(parts.length == 6, "Malformed cluster name: " + clusterName); <END> return parts[3]; }</code><technical_language>please move Preconditions constructor? check for matching " projects/(projectId)/instances/(instanceId)/clusters/(clusterId)"</technical_language>

Target:
public String getInstanceId() { return instanceId; }
Source:
<code>private org.eclipse.swt.graphics.Image createImage() { org.eclipse.swt.graphics.Image newImage; RenderedImage image = renderManager.getImage(); <START> this.backBufferTrsf=renderManager.getMapInternal().getViewportModel().worldToScreenTransform(); <END> if (image != null) newImage = AWTSWTImageUtils.createSWTImage(image, false); else { newImage = new Image(getDisplay(), getWidth(), getHeight()); } return newImage; }</code><technical_language>explain idea storing transformation else (at beginning of repaint())? Is worth this information compare getDoubleBufferGraphics() up-to-date viewportModel Transformation. is of a non-atomar opration betwenn getImage() getDoubleBufferGraphics() calls</technical_language>

Target:
private org.eclipse.swt.graphics.Image createImage() { org.eclipse.swt.graphics.Image newImage; RenderedImage image = renderManager.getImage(); if (image != null) newImage = AWTSWTImageUtils.createSWTImage(image, false); else { newImage = new Image(getDisplay(), getWidth(), getHeight()); } return newImage; }
Source:
<code>public void testVpnMsgOrLinkToBrowser() throws Exception { doReturn(mNetwork).when(sMockConnectivityManager).getActiveNetwork(); final NetworkCapabilities nonVpnCapabilities = new NetworkCapabilities(); <START> doReturn(nonVpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities( mNetwork); <END> final String continueMsg = mActivity.getString(R.string.ssl_error_continue); final String linkMatcher = ".*<a\\s+href.*"; assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(linkMatcher)); final NetworkCapabilities vpnCapabilities = new NetworkCapabilities(); vpnCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN); doReturn(vpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities(mNetwork); final String vpnWarning = mActivity.getString(R.string.ssl_error_vpnwarning); final String vpnMatcher = ".*<div.*vpnwarning.*"; assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(vpnMatcher)); }</code><technical_language>test null NetworkCapabilities case</technical_language>

Target:
public void testVpnMsgOrLinkToBrowser() throws Exception { doReturn(mNetwork).when(sMockConnectivityManager).getActiveNetwork(); final NetworkCapabilities nonVpnCapabilities = new NetworkCapabilities(); doReturn(nonVpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities( mNetwork); final String continueMsg = mActivity.getString(R.string.ssl_error_continue); final String linkMatcher = ".*<a\\s+href.*"; assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(linkMatcher)); doReturn(null).when(sMockConnectivityManager).getNetworkCapabilities(mNetwork); assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(linkMatcher)); final NetworkCapabilities vpnCapabilities = new NetworkCapabilities(); vpnCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN); doReturn(vpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities(mNetwork); final String vpnWarning = mActivity.getString(R.string.ssl_error_vpnwarning); final String vpnMatcher = ".*<div.*vpnwarning.*"; assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(vpnMatcher)); }
Source:
<code>private void logNoSuccessWarning(long now) { long lastUpdateNanos = now - noSuccessCheckDeadlineNanos + INTERVAL_NO_SUCCESS_WARNING_NANOS; long lastUpdated = TimeUnit.NANOSECONDS.toSeconds(lastUpdateNanos); LOG.warn( "No operations completed within the last %d seconds. " <START> + "There are still %d simple operations in progress.", <END> lastUpdated, operations.size()); noSuccessWarningCount++; }</code><technical_language>need call simple anymore if type of operation</technical_language>

Target:
private void logNoSuccessWarning(long now) { long lastUpdateNanos = now - noSuccessCheckDeadlineNanos + INTERVAL_NO_SUCCESS_WARNING_NANOS; long lastUpdated = TimeUnit.NANOSECONDS.toSeconds(lastUpdateNanos); LOG.warn( "No operations completed within the last %d seconds. " + "There are still %d operations in progress.", lastUpdated, operations.size()); noSuccessWarningCount++; }
Source:
<code>protected void zoomEntries(@NonNull Iterable<@NonNull TimeGraphEntry> entries, long zoomStartTime, long zoomEndTime, long resolution, @NonNull IProgressMonitor monitor) { if (resolution < 0) { return; } long start = Long.min(zoomStartTime, zoomEndTime); long end = Long.max(zoomStartTime, zoomEndTime); List<@NonNull Long> times = StateSystemUtils.getTimes(start, end, resolution); Sampling sampling = new Sampling(start, end, resolution); Multimap<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Long> providersToModelIds = filterGroupEntries(entries, zoomStartTime, zoomEndTime); SubMonitor subMonitor = SubMonitor.convert(monitor, getClass().getSimpleName() + "#zoomEntries", providersToModelIds.size()); for (Entry<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Collection<Long>> entry : providersToModelIds.asMap().entrySet()) { ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = entry.getKey(); TimeGraphStateQueryFilter filter = new TimeGraphStateQueryFilter(times, entry.getValue(), getRegexes()); TmfModelResponse<List<ITimeGraphRowModel>> response = dataProvider.fetchRowModel(filter, monitor); List<ITimeGraphRowModel> model = response.getModel(); if (model != null) { <START> Map<Long, TimeGraphEntry> map; synchronized (fEntries) { map = ImmutableMap.copyOf(fEntries.row(dataProvider)); } zoomEntries(map, model, response.getStatus() == ITmfResponse.Status.COMPLETED, sampling); <END> } subMonitor.worked(1); } }</code><technical_language>supposed zoom entries receive in parameter? fEntries this point no? ImmutableMap.copyOf done for zoom, end costly, especially if this way</technical_language>

Target:
protected void zoomEntries(@NonNull Iterable<@NonNull TimeGraphEntry> entries, long zoomStartTime, long zoomEndTime, long resolution, @NonNull IProgressMonitor monitor) { if (resolution < 0) { return; } long start = Long.min(zoomStartTime, zoomEndTime); long end = Long.max(zoomStartTime, zoomEndTime); List<@NonNull Long> times = StateSystemUtils.getTimes(start, end, resolution); Sampling sampling = new Sampling(start, end, resolution); Multimap<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Long> providersToModelIds = filterGroupEntries(entries, zoomStartTime, zoomEndTime); SubMonitor subMonitor = SubMonitor.convert(monitor, getClass().getSimpleName() + "#zoomEntries", providersToModelIds.size()); for (Entry<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Collection<Long>> entry : providersToModelIds.asMap().entrySet()) { ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = entry.getKey(); TimeGraphStateQueryFilter filter = new TimeGraphStateQueryFilter(times, entry.getValue(), getRegexes()); TmfModelResponse<List<ITimeGraphRowModel>> response = dataProvider.fetchRowModel(filter, monitor); List<ITimeGraphRowModel> model = response.getModel(); if (model != null) { zoomEntries(fEntries.row(dataProvider), model, response.getStatus() == ITmfResponse.Status.COMPLETED, sampling); } subMonitor.worked(1); } }
Source:
<code>private List<Pipeline> fetchHydratedPipelines() { List<Map<String, Object>> rawPipelines = front50.getPipelines(); if (rawPipelines == null) { return Collections.emptyList(); } Predicate<Map<String, Object>> isV2Pipeline = p -> { return p.getOrDefault("type", "").equals("templatedPipeline") && p.getOrDefault("schema", "").equals("v2"); }; return rawPipelines.stream() .map((Map<String, Object> p) -> { if (isV2Pipeline.test(p)) { try { return orca.v2Plan(p); } catch (Exception e) { log.error("Caught exception while planning templated pipeline: {}", p, e); return Collections.emptyMap(); } } else { return p; } }) .filter(m -> !m.isEmpty()) .map(m -> { try { return objectMapper.convertValue(m, Pipeline.class); <START> } catch (Exception e) { <END> log.warn("Pipeline failed to be converted to Pipeline.class: {}", m, e); return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); }</code><technical_language>is another try/catch in this block, sense break this out a helper planV2Template similar wrap processing in a try/catch for readability</technical_language>

Target:
private List<Pipeline> fetchHydratedPipelines() { List<Map<String, Object>> rawPipelines = front50.getPipelines(); if (rawPipelines == null) { return Collections.emptyList(); } Predicate<Map<String, Object>> isV2Pipeline = p -> { return p.getOrDefault("type", "").equals("templatedPipeline") && p.getOrDefault("schema", "").equals("v2"); }; return rawPipelines.stream() .map((Map<String, Object> p) -> planPipelineIfNeeded(p, isV2Pipeline)) .filter(m -> !m.isEmpty()) .map(m -> convertToPipeline(m)) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
<code>public static final void executeDeleteTestresultOfSummary( EntityManager session, Long resultId) { boolean isDeleteAll = resultId == null; String paramQueryBaseString = "delete from PARAMETER_DETAILS"; if (isDeleteAll) { session.createNativeQuery(paramQueryBaseString).executeUpdate(); } else { Query paramQuery = session.createNativeQuery( paramQueryBaseString + " where FK_TESTRESULT in (select ID from TESTRESULT where INTERNAL_TESTRUN_ID = #summaryId)"); paramQuery.setParameter("summaryId", resultId); paramQuery.executeUpdate(); } String additionsQueryBaseString = "delete from TESTRESULT_ADDITIONS"; if (isDeleteAll) { session.createNativeQuery(additionsQueryBaseString).executeUpdate(); } else { <START> Query paramQuery = session.createNativeQuery( <END> additionsQueryBaseString + " where FK_TESTRESULT in (select ID from TESTRESULT where INTERNAL_TESTRUN_ID = #summaryId)"); paramQuery.setParameter("summaryId", resultId); paramQuery.executeUpdate(); } StringBuilder resultQueryBuilder = new StringBuilder(); resultQueryBuilder.append( "delete from TestResultPO testResult"); if (!isDeleteAll) { resultQueryBuilder.append(" where testResult.internalTestResultSummaryID = :id"); } Query resultQuery = session.createQuery(resultQueryBuilder.toString()); if (!isDeleteAll) { resultQuery.setParameter("id", resultId); } resultQuery.executeUpdate(); }</code><technical_language>C&P naming of local variable - please adjust addition context</technical_language>

Target:
public static final void executeDeleteTestresultOfSummary( EntityManager session, Long resultId) { boolean isDeleteAll = resultId == null; String paramQueryBaseString = "delete from PARAMETER_DETAILS"; String queryExtension = " where FK_TESTRESULT in (select ID from TESTRESULT where INTERNAL_TESTRUN_ID = #summaryId)"; if (isDeleteAll) { session.createNativeQuery(paramQueryBaseString).executeUpdate(); } else { Query paramQuery = session.createNativeQuery( paramQueryBaseString + queryExtension); paramQuery.setParameter("summaryId", resultId); paramQuery.executeUpdate(); } String additionsQueryBaseString = "delete from TESTRESULT_ADDITIONS"; if (isDeleteAll) { session.createNativeQuery(additionsQueryBaseString).executeUpdate(); } else { Query commentQuery = session.createNativeQuery( additionsQueryBaseString + queryExtension); commentQuery.setParameter("summaryId", resultId); commentQuery.executeUpdate(); } StringBuilder resultQueryBuilder = new StringBuilder(); resultQueryBuilder.append( "delete from TestResultPO testResult"); if (!isDeleteAll) { resultQueryBuilder.append(" where testResult.internalTestResultSummaryID = :id"); } Query resultQuery = session.createQuery(resultQueryBuilder.toString()); if (!isDeleteAll) { resultQuery.setParameter("id", resultId); } resultQuery.executeUpdate(); }
Source:
<code>public void marshallTransaction(TxnView txn, ManagedCache<String, Optional<String>> propertyCache, TransactionController reuseTC, String localUserName, Integer sessionNumber) throws StandardException, SQLException{ <START> assert !updated; <END> try { if (LOG.isDebugEnabled()) { SpliceLogUtils.debug(LOG, "marshallTransaction with transactionID %s", txn); } cm = csf.newContextManager(); csf.setCurrentContextManager(cm); updated = true; String userName = localUserName != null ? localUserName : username; ArrayList<String> grouplist = new ArrayList<>(); grouplist.add(userName); if (propertyCache != null) { database.getDataDictionary().getDataDictionaryCache().setPropertyCache(propertyCache); } lcc=database.generateLanguageConnectionContext(txn, cm, userName,grouplist,drdaID, dbname, rdbIntTkn, DataSetProcessorType.DEFAULT_CONTROL, false, -1, ipAddress, reuseTC); } catch (Throwable t) { LOG.error("Exception during marshallTransaction", t); if (updated) close(); throw t; } }</code><technical_language>Great</technical_language>

Target:
public void marshallTransaction(TxnView txn, ManagedCache<String, Optional<String>> propertyCache, TransactionController reuseTC, String localUserName, Integer sessionNumber) throws StandardException, SQLException{ if (updated) { throw new IllegalStateException("Cannot create a new marshall Transaction as the last one wasn't closed"); } try { if (LOG.isDebugEnabled()) { SpliceLogUtils.debug(LOG, "marshallTransaction with transactionID %s", txn); } cm = csf.newContextManager(); csf.setCurrentContextManager(cm); updated = true; String userName = localUserName != null ? localUserName : username; ArrayList<String> grouplist = new ArrayList<>(); grouplist.add(userName); if (propertyCache != null) { database.getDataDictionary().getDataDictionaryCache().setPropertyCache(propertyCache); } lcc=database.generateLanguageConnectionContext(txn, cm, userName,grouplist,drdaID, dbname, rdbIntTkn, DataSetProcessorType.DEFAULT_CONTROL, false, -1, ipAddress, reuseTC); } catch (Throwable t) { LOG.error("Exception during marshallTransaction", t); if (updated) close(); throw t; } }
Source:
<code>public void removeSocketBinding_nullName() throws Exception { new RemoveSocketBinding(null); <START> fail("Creating command with null handler name should throw an exception"); <END> }</code><technical_language>handler is that? :-)</technical_language>

Target:
public void removeSocketBinding_nullName() throws Exception { new RemoveSocketBinding(null); fail("Creating command with null name should throw an exception"); }