auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public LockException(int statusCode) { this.statusCode = statusCode; <START> } <END></code><technical_language>Please call super(statusCode); for 3 below</technical_language>

Target:
public LockException(int statusCode) { super(statusCode); }
Source:
<code>public void testGetConfigList() { String jdbcDriver = "com.mysql.jdbc.Driver"; <START> String mysqlURL = "jdbc:mysql://gargamel.cs.illinois.edu/openeval_db"; END> String username = "oeroot"; String password = "Fow,10#"; try { Connection conn = DriverManager.getConnection(mysqlURL, username, password); String sql = "INSERT INTO configurations (datasetName, teamName, description, evaluator, taskType) VALUES ('testDataset', 'testTeamName', 'testDescription', 'testEvaluator', 'testTaskType')"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.executeUpdate(); sql = "SELECT MAX(id) from configurations;"; stmt = conn.prepareStatement(sql); ResultSet idOfConfig = stmt.executeQuery(); idOfConfig.first(); String id = Integer.toString(idOfConfig.getInt(1)); boolean inConfigList = false; FrontEndDBInterface f = new FrontEndDBInterface(); List<models.Configuration> configList = f.getConfigList(); if (configList != null) { for (int i = 0; i < configList.size(); i++) { if (configList.get(i).configuration_id.equals(id)) { inConfigList = true; break; } } } assertTrue(inConfigList); sql = "DELETE FROM configurations WHERE datasetName = 'testDataset'"; stmt = conn.prepareStatement(sql); stmt.executeUpdate(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } }</code><technical_language>do pass Semaphore, is running campus VPN</technical_language>

Target:
public void testGetConfigList() { String jdbcDriver = "com.mysql.jdbc.Driver"; String mysqlURL = "jdbc:mysql://gargamel.cs.illinois.edu/openeval_db"; String username = "oeroot"; String password = "Fow,10#"; try { Connection conn = DriverManager.getConnection(mysqlURL, username, password); String sql = "INSERT INTO configurations (datasetName, teamName, description, evaluator, taskType) VALUES ('testDataset', 'testTeamName', 'testDescription', 'testEvaluator', 'testTaskType')"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.executeUpdate(); sql = "SELECT MAX(id) from configurations;"; stmt = conn.prepareStatement(sql); ResultSet idOfConfig = stmt.executeQuery(); idOfConfig.first(); String id = Integer.toString(idOfConfig.getInt(1)); boolean inConfigList = false; FrontEndDBInterface f = new FrontEndDBInterface(); List<models.Configuration> configList = f.getConfigList(); if (configList != null) { for (int i = 0; i < configList.size(); i++) { if (configList.get(i).configuration_id.equals(id)) { inConfigList = true; break; } } } assertTrue(inConfigList); sql = "DELETE FROM configurations WHERE datasetName = 'testDataset'"; stmt = conn.prepareStatement(sql); stmt.executeUpdate(); conn.close(); } catch (SQLException e) { if (e.getMessage().contains("The driver has not received any packets from the server.")) return; } }
Source:
<code>public void requiredFieldAttribute() { if (type == ObjectSchemaType.IMMUTABLE) { return; } String fieldName = "foo"; for (FieldType fieldType : FieldType.values()) { switch (fieldType) { case OBJECT: continue; default: schema.addField(fieldName, fieldType.getType(), FieldAttribute.REQUIRED); assertTrue(schema.isRequired(fieldName)); schema.removeField(fieldName); } } for (FieldListType fieldType : FieldListType.values()) { switch(fieldType) { case LIST: continue; default: schema.addRealmListField(fieldName, fieldType.getType()); if (fieldType.isNullable()) { <START> schema.setRequired(fieldName, true); <END> } assertTrue(schema.isRequired(fieldName)); schema.removeField(fieldName); } } }</code><technical_language>changing field non-required required</technical_language>

Target:
public void requiredFieldAttribute() { if (type == ObjectSchemaType.IMMUTABLE) { return; } String fieldName = "foo"; for (FieldType fieldType : FieldType.values()) { switch (fieldType) { case OBJECT: continue; default: schema.addField(fieldName, fieldType.getType(), FieldAttribute.REQUIRED); assertTrue(schema.isRequired(fieldName)); schema.removeField(fieldName); } } for (FieldListType fieldType : FieldListType.values()) { switch(fieldType) { case LIST: continue; default: schema.addRealmListField(fieldName, fieldType.getType()); if (fieldType.isNullable()) { schema.setRequired(fieldName, true); } assertTrue(fieldName + " should be required", schema.isRequired(fieldName)); schema.removeField(fieldName); } } }
Source:
<code>public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.MediaColumns.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int columnIndex = cursor.getColumnIndex(column); if (columnIndex != -1) { return cursor.getString(columnIndex); } } <START> } catch (Exception errReadingContentResolver) { <END> AppLog.e(AppLog.T.UTILS, "Error reading _data column for URI: " + uri, errReadingContentResolver); } finally { if (cursor != null) { cursor.close(); } } return null; }</code><technical_language>Do want catch exceptions SecurityException</technical_language>

Target:
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = MediaStore.MediaColumns.DATA; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int columnIndex = cursor.getColumnIndex(column); if (columnIndex != -1) { return cursor.getString(columnIndex); } } } catch (SecurityException errReadingContentResolver) { AppLog.e(AppLog.T.UTILS, "Error reading _data column for URI: " + uri, errReadingContentResolver); } finally { if (cursor != null) { cursor.close(); } } return null; }
Source:
<code>private void reloadPluginAdapterAndVisibility(@NonNull PluginListType pluginType, @Nullable ListNetworkResource<ImmutablePluginModel> listNetworkResource) { <START> if (listNetworkResource == null || !(listNetworkResource instanceof ListNetworkResource.Ready <END> || listNetworkResource instanceof ListNetworkResource.Success)) { return; } PluginBrowserAdapter adapter = null; View cardView = null; switch (pluginType) { case SITE: adapter = (PluginBrowserAdapter) mSitePluginsRecycler.getAdapter(); cardView = findViewById(R.id.installed_plugins_cardview); break; case FEATURED: adapter = (PluginBrowserAdapter) mFeaturedPluginsRecycler.getAdapter(); cardView = findViewById(R.id.featured_plugins_cardview); break; case POPULAR: adapter = (PluginBrowserAdapter) mPopularPluginsRecycler.getAdapter(); cardView = findViewById(R.id.popular_plugins_cardview); break; case NEW: adapter = (PluginBrowserAdapter) mNewPluginsRecycler.getAdapter(); cardView = findViewById(R.id.new_plugins_cardview); break; case SEARCH: return; } if (adapter == null || cardView == null) { return; } List<ImmutablePluginModel> plugins = listNetworkResource.getData(); adapter.setPlugins(plugins); int newVisibility = plugins.size() > 0 ? View.VISIBLE : View.GONE; int oldVisibility = cardView.getVisibility(); if (newVisibility == View.VISIBLE && oldVisibility != View.VISIBLE) { AniUtils.fadeIn(cardView, AniUtils.Duration.MEDIUM); } else if (newVisibility != View.VISIBLE && oldVisibility == View.VISIBLE) { AniUtils.fadeOut(cardView, AniUtils.Duration.MEDIUM); } }</code><technical_language>This null check redundant</technical_language>

Target:
private void reloadPluginAdapterAndVisibility(@NonNull PluginListType pluginType, @Nullable ListNetworkResource<ImmutablePluginModel> listNetworkResource) { if (!(listNetworkResource instanceof ListNetworkResource.Ready || listNetworkResource instanceof ListNetworkResource.Success)) { return; } PluginBrowserAdapter adapter = null; View cardView = null; switch (pluginType) { case SITE: adapter = (PluginBrowserAdapter) mSitePluginsRecycler.getAdapter(); cardView = findViewById(R.id.installed_plugins_cardview); break; case FEATURED: adapter = (PluginBrowserAdapter) mFeaturedPluginsRecycler.getAdapter(); cardView = findViewById(R.id.featured_plugins_cardview); break; case POPULAR: adapter = (PluginBrowserAdapter) mPopularPluginsRecycler.getAdapter(); cardView = findViewById(R.id.popular_plugins_cardview); break; case NEW: adapter = (PluginBrowserAdapter) mNewPluginsRecycler.getAdapter(); cardView = findViewById(R.id.new_plugins_cardview); break; case SEARCH: return; } if (adapter == null || cardView == null) { return; } List<ImmutablePluginModel> plugins = listNetworkResource.getData(); adapter.setPlugins(plugins); int newVisibility = plugins.size() > 0 ? View.VISIBLE : View.GONE; int oldVisibility = cardView.getVisibility(); if (newVisibility == View.VISIBLE && oldVisibility != View.VISIBLE) { AniUtils.fadeIn(cardView, AniUtils.Duration.MEDIUM); } else if (newVisibility != View.VISIBLE && oldVisibility == View.VISIBLE) { AniUtils.fadeOut(cardView, AniUtils.Duration.MEDIUM); } }
Source:
<code>public static void loadKeyStore(String keyStorePath, String keyStorePassword) throws AuthenticationException { InputStream fis = null; try { TenantMgtAdminServiceClient.keyStorePassword = keyStorePassword.toCharArray(); keyStore = KeyStore.getInstance(keyStoreType); fis = new FileInputStream(keyStorePath); keyStore.load(fis, TenantMgtAdminServiceClient.keyStorePassword); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { throw new AuthenticationException("Error while trying to load Key Store.", e); } finally { try { <START> if (fis != null) { <END> fis.close(); } } catch (IOException e) { log.error("Failed to close file. ", e); } } }</code><technical_language>if try</technical_language>

Target:
public static void loadKeyStore(String keyStorePath, String keyStorePassword) throws AuthenticationException { InputStream fis = null; try { TenantMgtAdminServiceClient.keyStorePassword = keyStorePassword.toCharArray(); keyStore = KeyStore.getInstance(keyStoreType); fis = new FileInputStream(keyStorePath); keyStore.load(fis, TenantMgtAdminServiceClient.keyStorePassword); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { throw new AuthenticationException("Error while trying to load Key Store.", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.error("Failed to close file. ", e); } } } }
Source:
<code>public void install() { <START> String parentFQDN = entity.getParent().getAttribute(AmbariServer.FQDN); <END> String fqdn = Strings.isNullOrEmpty(parentFQDN) ? entity.getId().toLowerCase() + AmbariCluster.DOMAIN_NAME : parentFQDN; getEntity().setFqdn(fqdn); ImmutableList<String> commands = ImmutableList.<String>builder() .add(defaultAmbariInstallHelper.installAmbariRequirements(getMachine())) .addAll(BashCommands.setHostname(fqdn)) .add(installPackage("ambari-agent")) .build(); newScript(INSTALLING).body .append(commands) .failOnNonZeroResultCode() .execute(); }</code><technical_language>I instead entity.getParent() instanceOf AmbariServer ? ((AmbariServer) entity.getParent()).getFqdn() : null;</technical_language>

Target:
public void install() { String parentFQDN = entity.getParent() instanceof AmbariServer ? ((AmbariServer) entity.getParent()).getFqdn() : ""; String fqdn = parentFQDN.isEmpty() ? entity.getId().toLowerCase() + AmbariCluster.DOMAIN_NAME : parentFQDN; getEntity().setFqdn(fqdn); ImmutableList<String> commands = ImmutableList.<String>builder() .add(defaultAmbariInstallHelper.installAmbariRequirements(getMachine())) .addAll(BashCommands.setHostname(fqdn)) .add(installPackage("ambari-agent")) .build(); newScript(INSTALLING).body .append(commands) .failOnNonZeroResultCode() .execute(); }
Source:
<code>public boolean equals(Object obj) { <START> if (id == null || !(obj instanceof DummyObject)) { <END> return false; } DummyObject other = (DummyObject) obj; return other.id != null && id.equals(other.id); }</code><technical_language>if object id==null? equal</technical_language>

Target:
public boolean equals(Object obj) { if (!(obj instanceof DummyObject)) { return false; } DummyObject other = (DummyObject) obj; if (id == other.id) { return true; } return id != null && id.equals(other.id); }
Source:
<code>protected final List<ObjectComponent<T>> parseRequest(StaplerRequest req) throws ServletException, Descriptor.FormException { LOGGER.fine("Parsing request..."); DescribableList<ObjectComponent<T>, ObjectComponentDescriptor<T>> components = new DescribableList<>(Saveable.NOOP); try { JSONObject componentsSection = new JSONObject(); <START> if (req.getSubmittedForm() != null) { <END> componentsSection = req.getSubmittedForm().getJSONObject("components"); } components.rebuild(req, componentsSection, getApplicableComponentsDescriptors()); } catch (IOException e) { throw new Descriptor.FormException(e, "components"); } return components; }</code><technical_language>In main method, this checking null</technical_language>

Target:
protected final List<ObjectComponent<T>> parseRequest(StaplerRequest req) throws ServletException, Descriptor.FormException { DescribableList<ObjectComponent<T>, ObjectComponentDescriptor<T>> components = new DescribableList<>(Saveable.NOOP); try { JSONObject componentsSection = req.getSubmittedForm().getJSONObject("components"); components.rebuild(req, componentsSection, getApplicableComponentsDescriptors()); } catch (IOException e) { throw new Descriptor.FormException(e, "components"); } return components; }
Source:
<code>public static void trimSpaces(EOEnterpriseObject object) { for (Enumeration e=ERXEOControlUtilities.stringAttributeListForEntityNamed(object.editingContext(), object.entityName()).objectEnumerator(); e.hasMoreElements();) { String key=(String)e.nextElement(); String value=(String)object.storedValueForKey(key); <START> if (!EOUtilities.entityForObject(object.editingContext(), object).attributeNamed(key).isReadOnly()) { <END> if (value!=null) { String trimmedValue=value.trim(); if (trimmedValue.length()!=value.length()) object.takeStoredValueForKey(trimmedValue,key); } } } }</code><technical_language>sense test for != null? compute line time if necessary</technical_language>

Target:
public static void trimSpaces(EOEnterpriseObject object) { for (Enumeration e=ERXEOControlUtilities.stringAttributeListForEntityNamed(object.editingContext(), object.entityName()).objectEnumerator(); e.hasMoreElements();) { String key=(String)e.nextElement(); String value=(String)object.storedValueForKey(key); if (value!=null) { if (!EOUtilities.entityForObject(object.editingContext(), object).attributeNamed(key).isReadOnly()) { String trimmedValue=value.trim(); if (trimmedValue.length()!=value.length()) object.takeStoredValueForKey(trimmedValue,key); } } } }
Source:
<code>public static ResourceLocation resolveTexture(@Nullable String tex, IModelConfiguration owner) { if (tex == null) <START> return new ResourceLocation("forge:white"); <END> if (tex.startsWith("#")) return new ResourceLocation(owner.resolveTexture(tex)); Matcher match = FILESYSTEM_PATH_TO_RESLOC.matcher(tex); if (match.matches()) { String namespace = match.group("namespace"); String path = match.group("path").replace("\\", "/"); if (namespace != null) return new ResourceLocation(namespace, path); return new ResourceLocation(path); } return new ResourceLocation(tex); }</code><technical_language>this a constant</technical_language>

Target:
public static ResourceLocation resolveTexture(@Nullable String tex, IModelConfiguration owner) { if (tex == null) return new ResourceLocation(WHITE_TEXTURE); if (tex.startsWith("#")) return new ResourceLocation(owner.resolveTexture(tex)); Matcher match = FILESYSTEM_PATH_TO_RESLOC.matcher(tex); if (match.matches()) { String namespace = match.group("namespace"); String path = match.group("path").replace("\\", "/"); if (namespace != null) return new ResourceLocation(namespace, path); return new ResourceLocation(path); } return new ResourceLocation(tex); }
Source:
<code>public void completeBuilderShouldThrowExceptionIfNoQueryWasSet() { PreparedGetObject.CompleteBuilder completeBuilder = new PreparedGetObject.Builder<Object>(mock(StorIOSQLite.class), Object.class) .withQuery(Query.builder().table("test_table").build()); completeBuilder.query = null; try { completeBuilder.prepare(); failBecauseExceptionWasNotThrown(IllegalStateException.class); } catch (IllegalStateException expected) { <START> assertThat(expected).hasMessage("Please specify Query or RawQuery"); <END> } }</code><technical_language>check is</technical_language>

Target:
public void completeBuilderShouldThrowExceptionIfNoQueryWasSet() { PreparedGetObject.CompleteBuilder completeBuilder = new PreparedGetObject.Builder<Object>(mock(StorIOSQLite.class), Object.class) .withQuery(Query.builder().table("test_table").build()); completeBuilder.query = null; try { completeBuilder.prepare(); failBecauseExceptionWasNotThrown(IllegalStateException.class); } catch (IllegalStateException expected) { assertThat(expected).hasMessage("Please specify Query or RawQuery"); assertThat(expected).hasNoCause(); } }
Source:
<code>protected Issuer createIssuer(final CallbackProperties properties, final X509Certificate certificate) { String format = properties.getAssertionIssuerFormat(); String sIssuer = properties.getIssuer(); if (!(StringUtils.isNotBlank(format) && isValidNameidFormat(format))) { format = NhincConstants.AUTH_FRWK_NAME_ID_FORMAT_X509; } if (!(StringUtils.isNotBlank(sIssuer) && checkDistinguishedName(sIssuer))) { if (certificate != null) { <START> sIssuer = certificate.getIssuerDN().getName(); <END> } else { sIssuer = NhincConstants.SAML_DEFAULT_ISSUER_NAME; } } LOG.debug("Setting Assertion Issuer format to: {}", format); LOG.debug("Setting Assertion Issuer to: {}", sIssuer); return OpenSAML2ComponentBuilder.getInstance().createIssuer(format, sIssuer); }</code><technical_language>Need retrieve cert's subject name instead of issuer. is sample code certification.getSubjectX500Principal().getName()</technical_language>

Target:
protected Issuer createIssuer(final CallbackProperties properties, final X509Certificate certificate) { String format = properties.getAssertionIssuerFormat(); String sIssuer = properties.getIssuer(); if (!(StringUtils.isNotBlank(format) && isValidNameidFormat(format))) { format = NhincConstants.AUTH_FRWK_NAME_ID_FORMAT_X509; } if (!(StringUtils.isNotBlank(sIssuer) && checkDistinguishedName(sIssuer))) { if (certificate != null) { sIssuer = certificate.getSubjectX500Principal().getName(); } else { sIssuer = NhincConstants.SAML_DEFAULT_ISSUER_NAME; } } LOG.debug("Setting Assertion Issuer format to: {}", format); LOG.debug("Setting Assertion Issuer to: {}", sIssuer); return OpenSAML2ComponentBuilder.getInstance().createIssuer(format, sIssuer); }
Source:
<code>private Element getSubjectAsElement(ServerSession session) { try { return SUBJECT_CACHE .get(session.getUsername(), () -> this.cacheAndReturnSubject(session)) .getPrincipals() .oneByType(SecurityAssertion.class) .getSecurityToken() .getToken(); } catch (ExecutionException e) { <START> LOGGER.warn("Could not get Subject from token", e); <END> return null; } }</code><technical_language>pencil2: I log e.getCause() instead ExecutionException wraps real exception occurred. Also, if loader function throws unchecked exception (and I if does) get() throw UncheckedExecutionException, want handle differently</technical_language>

Target:
private Element getSubjectAsElement(ServerSession session) { try { return SUBJECT_CACHE .get(session.getUsername(), () -> this.cacheAndReturnSubject(session)) .getPrincipals() .oneByType(SecurityAssertion.class) .getSecurityToken() .getToken(); } catch (ExecutionException e) { LOGGER.warn("Could not get Subject from token", e.getCause()); return null; } }
Source:
<code>public void should_throw_error_if_consumer_array_is_null() { Consumer<String>[] consumers = null; <START> Object o = null; <END> String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); }</code><technical_language>Object o is used. suggestion</technical_language>

Target:
public void should_throw_error_if_consumer_array_is_null() { Consumer<String>[] consumers = null; String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); }
Source:
<code>public void run() { List<Future> futures = new ArrayList<>(); for (Map.Entry<String, String> query : queries.entrySet()) { futures.add(executorService.submit(() -> { String metricName = query.getKey(); String measuresUrl = query.getValue() + "start=" + intervalStart(); try { URL url = new URL(measuresUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(AUTHORIZATION, basicAuth); conn.setRequestMethod(GET); conn.setDoInput(true); List measures = JsonUtil.getMapper().readValue(conn.getInputStream(), List.class); List<Data> data = new ArrayList<>(); for (int i = 0; i < measures.size(); i++) { List measure = (List)measures.get(i); if (measure != null && measure.size() == 3) { String timestamp = (String)measure.get(0); Double value = (Double)measure.get(2); <START> data.add(Data.forNumeric(trigger.getTenantId(), metricName, parseTimestamp(timestamp), value)); <END> } } log.debugf("Sending [%s]", data); if (alerts != null) { alerts.sendData(data, true); } } catch (IOException e) { log.errorf(e,"Error querying Gnochi URL %s", measuresUrl); } catch (Exception e) { log.errorf(e, "Error sending data to the Alerting Engine"); } })); } for (Future future : futures) { try { future.get(); } catch (Exception e) { log.error(e); } } }</code><technical_language>i is missing (or building queries). in gnocchi, if dont' a granularity (<LINK_0>, return granularities metric. if 'low' archive policy, this is granularity fine. if 'medium', 'high', custom policy, multiple granularities returned if ignore it, effectively squashing multiple series one</technical_language>

Target:
public void run() { List<Future> futures = new ArrayList<>(); for (Map.Entry<String, String> query : queries.entrySet()) { futures.add(executorService.submit(() -> { String metricName = query.getKey(); String measuresUrl = query.getValue() + "start=" + intervalStart(); try { URL url = new URL(measuresUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(AUTHORIZATION, basicAuth); conn.setRequestMethod(GET); conn.setDoInput(true); List measures = JsonUtil.getMapper().readValue(conn.getInputStream(), List.class); List<Data> data = new ArrayList<>(); for (int i = 0; i < measures.size(); i++) { List measure = (List)measures.get(i); if (measure != null && measure.size() == 3) { String timestamp = (String) measure.get(0); Double granularity = (Double) measure.get(1); Double value = (Double) measure.get(2); Map<String, String> context = new HashMap<>(); context.put("granularity", String.valueOf(granularity)); data.add(Data.forNumeric(trigger.getTenantId(), metricName, parseTimestamp(timestamp), value, context)); } } log.debugf("Sending [%s]", data); if (alerts != null) { alerts.sendData(data, true); } } catch (IOException e) { log.errorf(e,"Error querying Gnochi URL %s", measuresUrl); } catch (Exception e) { log.errorf(e, "Error sending data to the Alerting Engine"); } })); } for (Future future : futures) { try { future.get(); } catch (Exception e) { log.error(e); } } }
Source:
<code>protected void addResponseHandlers(ChannelPipeline p, Fulfiller<? super StreamedResponse> fulfiller) { <START> if (requestSpecBacking.isDecompressResponse()) { <END> p.addLast(new HttpContentDecompressor()); } p.addLast("httpResponseHandler", new SimpleChannelInboundHandler<HttpResponse>(false) { @Override public void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { p.channel().config().setAutoRead(false); execution.onCleanup(() -> { if (!subscribedTo.get() && ctx.channel().isOpen()) { ctx.close(); } }); final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); final Status status = new DefaultStatus(msg.status()); success(fulfiller, new DefaultStreamedResponse(p, status, headers)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); }</code><technical_language>this in RequestActionSupport</technical_language>

Target:
protected void addResponseHandlers(ChannelPipeline p, Fulfiller<? super StreamedResponse> fulfiller) { p.addLast("httpResponseHandler", new SimpleChannelInboundHandler<HttpResponse>(false) { @Override public void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception { p.channel().config().setAutoRead(false); execution.onCleanup(() -> { if (!subscribedTo.get() && ctx.channel().isOpen()) { ctx.close(); } }); final Headers headers = new NettyHeadersBackedHeaders(msg.headers()); final Status status = new DefaultStatus(msg.status()); success(fulfiller, new DefaultStreamedResponse(p, status, headers)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); }
Source:
<code>public void doNotSaveUserSettingsWithNonExistingLanguage() { userRepository.save(new User(ID, USERNAME, FULL_NAME, AVATAR_URL, PROFILE_URL)); thrown.expect(ConstraintViolationException.class); UserSettings userSettings = new UserSettings(); <START> userSettings.language = "xx"; <END> userService.updateUserSettings(ID, userSettings); }</code><technical_language>sex language, exists</technical_language>

Target:
public void doNotSaveUserSettingsWithNonExistingLanguage() { userRepository.save(new User(ID, USERNAME, FULL_NAME, AVATAR_URL, PROFILE_URL)); UserSettings userSettings = new UserSettings(); userSettings.language = "xx"; userService.updateUserSettings(ID, userSettings); }
Source:
<code>public DocumentModelList query(String query, String queryType, Filter filter, long limit, long offset, long countUpTo) { Span span = Tracing.getTracer().getCurrentSpan(); <START> Map<String, AttributeValue> attributes = new HashMap<>(); <END> attributes.put("nxql", AttributeValue.stringAttributeValue(query)); if (filter != null) { attributes.put("filter", AttributeValue.stringAttributeValue(filter.toString())); } attributes.put("limit", AttributeValue.longAttributeValue(limit)); attributes.put("offset", AttributeValue.longAttributeValue(offset)); attributes.put("countUpTo", AttributeValue.longAttributeValue(countUpTo)); span.addAnnotation("query", attributes); DocumentModelList ret = tracedQuery(query, queryType, filter, limit, offset, countUpTo); attributes.clear(); attributes.put("match", AttributeValue.longAttributeValue(ret.totalSize())); span.addAnnotation("query.done", attributes); return ret; }</code><technical_language>call map in other uses</technical_language>

Target:
public DocumentModelList query(String query, String queryType, Filter filter, long limit, long offset, long countUpTo) { Span span = Tracing.getTracer().getCurrentSpan(); Map<String, AttributeValue> map = new HashMap<>(); map.put("nxql", AttributeValue.stringAttributeValue(query)); if (filter != null) { map.put("filter", AttributeValue.stringAttributeValue(filter.toString())); } map.put("limit", AttributeValue.longAttributeValue(limit)); map.put("offset", AttributeValue.longAttributeValue(offset)); map.put("countUpTo", AttributeValue.longAttributeValue(countUpTo)); span.addAnnotation("AbstractSession#query", map); DocumentModelList ret = tracedQuery(query, queryType, filter, limit, offset, countUpTo); map.clear(); map.put("totalSize", AttributeValue.longAttributeValue(ret.totalSize())); span.addAnnotation("AbstractSession#query.done", map); return ret; }
Source:
<code>public List<TypeSpec> generateTypes(final TypeElement annotatedTypeElement) { final List<ExecutableElement> propertyMethods = getPropertyMethodsSorted(annotatedTypeElement); final List<TypeSpec> typeSpecList = propertyMethods.stream() .filter(m -> isPrimitiveType(PropertyGenModel.of(m).getType())) .map(propertyMethod -> { <START> final PropertyGenModel property = PropertyGenModel.of(propertyMethod); <END> final MethodSpec getMethod = createGetMethodBuilder(propertyMethod).build(); final String actionPrefix = property.isOptional() ? "set" : "change"; final FieldSpec fieldSpec = createFieldBuilder(property, Modifier.PRIVATE) .addModifiers(Modifier.FINAL) .build(); final String updateAction = actionPrefix + StringUtils.capitalize(fieldSpec.name); final String updateActionClassName = StringUtils.capitalize(updateAction); final TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(updateActionClassName) .addJavadoc("$L $L to $L\n", property.isOptional() ? "Sets" : "Updates", fieldSpec.name, ClassName.get(annotatedTypeElement).simpleName()) .addJavadoc("\n") .addJavadoc("{@doc.gen intro}\n") .superclass(ParameterizedTypeName.get(ClassName.get(UpdateActionImpl.class), ClassName.get(annotatedTypeElement))) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(AnnotationSpec.builder(Generated.class) .addMember("value", "$S", getClass().getCanonicalName()) .addMember("comments", "$S", "Generated from: " + annotatedTypeElement.getQualifiedName().toString()).build()) .addField(createFieldBuilder(property, Modifier.PRIVATE) .addModifiers(Modifier.FINAL) .build()) .addMethod(createConstructor(property, updateAction)) .addMethod(getMethod) .addMethod(createFactoryMethod(property, updateActionClassName)); if (property.isOptional()) { typeSpecBuilder.addMethod(createUnsetMethod(updateActionClassName)); } return typeSpecBuilder.build(); }).collect(Collectors.toList()); return typeSpecList; }</code><technical_language>extracting this lambda a separate method? replace lambda a method handle extracted method. discuss this separately</technical_language>

Target:
public List<TypeSpec> generateTypes(final TypeElement annotatedTypeElement) { final List<ExecutableElement> propertyMethods = getPropertyMethodsSorted(annotatedTypeElement); final List<TypeSpec> typeSpecList = propertyMethods.stream() .filter(m -> typeUtils.isPrimitiveType(PropertyGenModel.of(m).getType())) .map(propertyMethod -> generateUpdateAction(annotatedTypeElement, propertyMethod)).collect(Collectors.toList()); return typeSpecList; }
Source:
<code>private Map<String, List<NameOccurrence>> getRuleAnnotatedExpectedExceptions(Scope classScope) { Map<String, List<NameOccurrence>> result = new HashMap<>(); Map<NameDeclaration, List<NameOccurrence>> decls = classScope.getDeclarations(); for (NameDeclaration decl : decls.keySet()) { Node parent = decl.getNode().jjtGetParent().jjtGetParent().jjtGetParent(); if (parent.hasDescendantOfType(ASTAnnotation.class) && parent.getFirstChildOfType(ASTFieldDeclaration.class) != null) { <START> if (!"Rule" <END> .equals(parent.getFirstDescendantOfType(ASTMarkerAnnotation.class).jjtGetChild(0).getImage())) { System.out.println( parent.getFirstDescendantOfType(ASTMarkerAnnotation.class).jjtGetChild(0).getImage()); continue; } Node type = parent.getFirstDescendantOfType(ASTReferenceType.class); if (!"ExpectedException".equals(type.jjtGetChild(0).getImage())) { System.out.println(type.jjtGetChild(0).getImage()); continue; } result.put(decl.getName(), decls.get(decl)); } } return result; }</code><technical_language>bare in mind that, if non-conventional, people simply write @org.junit.Ruletoo</technical_language>

Target:
private Map<String, List<NameOccurrence>> getRuleAnnotatedExpectedExceptions(Scope classScope) { Map<String, List<NameOccurrence>> result = new HashMap<>(); Map<NameDeclaration, List<NameOccurrence>> decls = classScope.getDeclarations(); for (NameDeclaration decl : decls.keySet()) { Node parent = decl.getNode().jjtGetParent().jjtGetParent().jjtGetParent(); if (parent.hasDescendantOfType(ASTAnnotation.class) && parent.getFirstChildOfType(ASTFieldDeclaration.class) != null) { String annot = parent.getFirstDescendantOfType(ASTMarkerAnnotation.class).jjtGetChild(0).getImage(); if (!"Rule".equals(annot) && !"org.junit.Rule".equals(annot)) { continue; } Node type = parent.getFirstDescendantOfType(ASTReferenceType.class); if (!"ExpectedException".equals(type.jjtGetChild(0).getImage())) { continue; } result.put(decl.getName(), decls.get(decl)); } } return result; }
Source:
<code>public Matrix bernoulli(final int rows, final int columns, final float prob) { final int length = rows * columns; final float[] data = new float[length]; for (int i = 0; i < length; ++i) { <START> if (randomGenerator.nextFloat() > prob) { <END> data[i] = 1; } else { data[i] = 0; } } return create(data, rows, columns); }</code><technical_language>I thought prob = 1 generates a matrix filled ones, code generate a matrix zeros</technical_language>

Target:
public Matrix bernoulli(final int rows, final int columns, final float prob) { return bernoulli(rows, columns, prob, 1); }
Source:
<code>public void addPremisEventsTest() throws IOException { File premisEventsDir = job.getEventsDirectory(); premisEventsDir.mkdir(); PID folderObjPid = repository.mintContentPid(); <START> folderObjPid = repository.mintContentPid(); <END> File premisEventsFile = new File(premisEventsDir, folderObjPid.getUUID() + ".xml"); premisEventsFile.createNewFile(); String label = "testfolder"; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); Bag folderBag = model.createBag(folderObjPid.getRepositoryPath()); folderBag.addProperty(RDF.type, Cdr.Folder); folderBag.addProperty(CdrDeposit.label, label); depBag.add(folderBag); FilePremisLogger premisLogger = new FilePremisLogger(folderObjPid, premisEventsFile, repository); Resource event1 = premisLogger.buildEvent(Premis.Normalization) .addEventDetail("Event 1") .addAuthorizingAgent(SoftwareAgent.depositService.getFullname()) .write(); Resource event2 = premisLogger.buildEvent(Premis.VirusCheck) .addEventDetail("Event 2") .addSoftwareAgent(SoftwareAgent.clamav.getFullname()) .write(); job.closeModel(); job.run(); FolderObject folder = repository.getFolderObject(folderObjPid); List<PremisEventObject> events = folder.getPremisLog().getEvents(); assertEquals(2, events.size()); assertTrue(events.contains(findPremisEventByType(events, Premis.Normalization))); assertTrue(events.contains(findPremisEventByType(events, Premis.VirusCheck))); }</code><technical_language>Reducto this duplicate line</technical_language>

Target:
public void addPremisEventsTest() throws IOException { File premisEventsDir = job.getEventsDirectory(); premisEventsDir.mkdir(); PID folderObjPid = repository.mintContentPid(); File premisEventsFile = new File(premisEventsDir, folderObjPid.getUUID() + ".xml"); premisEventsFile.createNewFile(); String label = "testfolder"; Model model = job.getWritableModel(); Bag depBag = model.createBag(depositPid.getRepositoryPath()); Bag folderBag = model.createBag(folderObjPid.getRepositoryPath()); folderBag.addProperty(RDF.type, Cdr.Folder); folderBag.addProperty(CdrDeposit.label, label); depBag.add(folderBag); FilePremisLogger premisLogger = new FilePremisLogger(folderObjPid, premisEventsFile, repository); Resource event1 = premisLogger.buildEvent(Premis.Normalization) .addEventDetail("Event 1") .addAuthorizingAgent(SoftwareAgent.depositService.getFullname()) .write(); Resource event2 = premisLogger.buildEvent(Premis.VirusCheck) .addEventDetail("Event 2") .addSoftwareAgent(SoftwareAgent.clamav.getFullname()) .write(); job.closeModel(); job.run(); FolderObject folder = repository.getFolderObject(folderObjPid); List<PremisEventObject> events = folder.getPremisLog().getEvents(); assertEquals(2, events.size()); assertTrue(events.contains(findPremisEventByType(events, Premis.Normalization))); assertTrue(events.contains(findPremisEventByType(events, Premis.VirusCheck))); }
Source:
<code>public void removeObject(WordsObject object) { object.clearReferers(); for (HashMap<String, WordsObject> scope : objectsByName) { <START> if (scope.get(object.getObjectName()) != null) { <END> scope.remove(object.getObjectName()); break; } } for (WordsClass wordsClass : objectsByClass.keySet()) { HashSet<WordsObject> objectSet = objectsByClass.get(wordsClass); if (objectSet.contains(object)) { objectSet.remove(object); } } }</code><technical_language>I technically this check is necessary, remove() method removes a key if exists if not</technical_language>

Target:
public void removeObject(WordsObject object) { object.clearReferers(); for (HashMap<String, WordsObject> scope : objectsByName) { if (scope.remove(object.getObjectName()) != null) { break; } } objectsByClass.get(object.getWordsClass()).remove(object); }
Source:
<code>public boolean hasTemplatePath(TreeReference ref) { if (caseDbSpecTemplate != null) { return followsTemplateSpec(ref, caseDbSpecTemplate, 0); } else { Logger.log("CaseDb Warning", "Using default hasTemplatePath implementation: reference resolution will break!"); <START> return super.hasTemplatePath(ref); <END> } }</code><technical_language>Honestly thinking more sense literally inline template text static content here, permgen size of this file large. uncomfortable code path for loading this is static, introduces _huge_ unpredictable hits codebase for a complex parse (And will/can weird bad times), static init happen lazily instead? (Is fine for template parse static, I think), long is stateless threadsafe)</technical_language>

Target:
public boolean hasTemplatePath(TreeReference ref) { loadTemplateSpecLazily(); return followsTemplateSpec(ref, caseDbSpecTemplate, 0); }
Source:
<code>public CloseableIterator<byte[]> keys(byte[] firstKey, byte[] lastKey) { final RocksIterator iterator = db.newIterator(optionCache); iterator.seek(firstKey); return new CloseableIterator<byte[]>() { @Override public boolean hasNext() { return iterator.isValid() && ByteComparator.compare(iterator.key(), lastKey) < 0; } @Override public byte[] next() { <START> checkArgument(iterator.isValid()); <END> byte[] key = iterator.key(); iterator.next(); return key; } @Override public void close() { iterator.close(); } }; }</code><technical_language>checkState</technical_language>

Target:
public CloseableIterator<byte[]> keys(byte[] firstKey, byte[] lastKey) { final RocksIterator iterator = db.newIterator(optionCache); iterator.seek(firstKey); return new CloseableIterator<byte[]>() { @Override public boolean hasNext() { return iterator.isValid() && ByteComparator.compare(iterator.key(), lastKey) < 0; } @Override public byte[] next() { checkState(iterator.isValid()); byte[] key = iterator.key(); iterator.next(); return key; } @Override public void close() { iterator.close(); } }; }
Source:
<code>protected void executeVmCommand() { ArrayList<String> errorMessages = new ArrayList<String>(); if (canAddVm(errorMessages, destStorages.values())) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmNetwork(); addVmStatistics(); addActiveSnapshot(); addVmPermission(); <START> addVmWatchdog(); <END> getCompensationContext().stateChanged(); return null; } }); if (addVmImages()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { copyVmDevices(); addDiskPermissions(newDiskImages); addVmPayload(); updateSmartCardDevices(); setActionReturnValue(getVm().getId()); setSucceeded(true); return null; } }); } } else { log.errorFormat("Failed to add vm . The reasons are: {0}", StringUtils.join(errorMessages, ',')); } }</code><technical_language>of compensation in this command this call in transaction below, handling need added in case is a failure</technical_language>

Target:
protected void executeVmCommand() { ArrayList<String> errorMessages = new ArrayList<String>(); if (canAddVm(errorMessages, destStorages.values())) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addVmStatic(); addVmDynamic(); addVmNetwork(); addVmStatistics(); addActiveSnapshot(); addVmPermission(); getCompensationContext().stateChanged(); return null; } }); if (addVmImages()) { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { copyVmDevices(); addDiskPermissions(newDiskImages); addVmPayload(); updateSmartCardDevices(); addVmWatchdog(); setActionReturnValue(getVm().getId()); setSucceeded(true); return null; } }); } } else { log.errorFormat("Failed to add vm . The reasons are: {0}", StringUtils.join(errorMessages, ',')); } }
Source:
<code>private URL getResourceUrl(ServletContext context, String path) throws MalformedURLException { <START> URL logo = context.getResource(path); <END> if (logo == null) { String cpPath = path.startsWith("/") ? META_INF_RESOURCES + path : META_INF_RESOURCES + "/" + path; logo = PwaRegistry.class.getResource(cpPath); } return logo; }</code><technical_language>Rename logo resourceUrl</technical_language>

Target:
private URL getResourceUrl(ServletContext context, String path) throws MalformedURLException { URL resourceUrl = context.getResource(path); if (resourceUrl == null) { String cpPath = path.startsWith("/") ? META_INF_RESOURCES + path : META_INF_RESOURCES + "/" + path; resourceUrl = PwaRegistry.class.getResource(cpPath); } return resourceUrl; }
Source:
<code>public List<URI> getVxLanPorts() { <START> if (vxLanPortIds == null) { return null; } List<URI> uris = new ArrayList<>(vxLanPortIds.size()); for (UUID id : vxLanPortIds) { uris.add(absoluteUri(PORTS, id)); } return uris; <END> }</code><technical_language>this: return absoluteUris(PORTS, vxLanPortIds);</technical_language>

Target:
public List<URI> getVxLanPorts() { return absoluteUris(PORTS, vxLanPortIds); }
Source:
<code><START> protected FactModelTree getSimpleClassFactModelTree(Class clazz) { <END> String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); }</code><technical_language>This util method **delegation** instead of **inheritance**. Is inheritance of testeability</technical_language>

Target:
protected static FactModelTree getSimpleClassFactModelTree(Class clazz) { String key = clazz.getSimpleName(); Map<String, String> simpleProperties = new HashMap<>(); String fullName = clazz.getCanonicalName(); simpleProperties.put("value", fullName); String packageName = fullName.substring(0, fullName.lastIndexOf(".")); return new FactModelTree(key, packageName, simpleProperties); }
Source:
<code>public void start(ComponentContext context) { super.start(context); if (provider != null) { provider.close(); } List<PubSubProviderDescriptor> descs = getDescriptors(XP_CONFIG); <START> PubSubProviderDescriptor providerDescriptor = descs.isEmpty() ? null : descs.get(descs.size() - 1); <END> if (providerDescriptor == null) { provider = new MemPubSubProvider(); options = Collections.emptyMap(); } else { Class<? extends PubSubProvider> klass = providerDescriptor.klass; if (!PubSubProvider.class.isAssignableFrom(klass)) { throw new RuntimeException("Class does not implement PubSubServiceProvider: " + klass.getName()); } try { provider = klass.getDeclaredConstructor().newInstance(); options = providerDescriptor.options; } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } if (provider != null) { provider.initialize(options, subscribers); } }</code><technical_language>need a getLastDescriptors</technical_language>

Target:
public void start(ComponentContext context) { super.start(context); if (provider != null) { provider.close(); } List<PubSubProviderDescriptor> descs = getDescriptors(XP_CONFIG); PubSubProviderDescriptor providerDescriptor = descs.isEmpty() ? null : descs.get(descs.size() - 1); if (providerDescriptor == null) { provider = new MemPubSubProvider(); options = Collections.emptyMap(); } else { Class<? extends PubSubProvider> klass = providerDescriptor.klass; if (!PubSubProvider.class.isAssignableFrom(klass)) { throw new RuntimeException("Class does not implement PubSubServiceProvider: " + klass.getName()); } try { provider = klass.getDeclaredConstructor().newInstance(); options = providerDescriptor.options; } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } provider.initialize(options, subscribers); }
Source:
<code>public RoutingRequest clone() { try { RoutingRequest clone = (RoutingRequest) super.clone(); clone.bannedRoutes = bannedRoutes.clone(); clone.bannedTrips = (HashMap<AgencyAndId, BannedStopSet>) bannedTrips.clone(); clone.bannedStops = bannedStops.clone(); clone.bannedStopsHard = bannedStopsHard.clone(); clone.whiteListedAgencies = (HashSet<String>) whiteListedAgencies.clone(); clone.whiteListedRoutes = whiteListedRoutes.clone(); clone.preferredAgencies = (HashSet<String>) preferredAgencies.clone(); <START> clone.preferredRoutes = preferredRoutes.clone(); <END> if (this.bikeWalkingOptions != this) clone.bikeWalkingOptions = this.bikeWalkingOptions.clone(); else clone.bikeWalkingOptions = clone; return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } }</code><technical_language>I leave this additional fix in this PR</technical_language>

Target:
public RoutingRequest clone() { try { RoutingRequest clone = (RoutingRequest) super.clone(); clone.bannedRoutes = bannedRoutes.clone(); clone.bannedTrips = (HashMap<FeedScopedId, BannedStopSet>) bannedTrips.clone(); clone.bannedStops = bannedStops.clone(); clone.bannedStopsHard = bannedStopsHard.clone(); clone.whiteListedAgencies = (HashSet<String>) whiteListedAgencies.clone(); clone.whiteListedRoutes = whiteListedRoutes.clone(); clone.preferredAgencies = (HashSet<String>) preferredAgencies.clone(); clone.preferredRoutes = preferredRoutes.clone(); if (this.bikeWalkingOptions != this) clone.bikeWalkingOptions = this.bikeWalkingOptions.clone(); else clone.bikeWalkingOptions = clone; return clone; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } }
Source:
<code>public void testSelectorWidget() { final Button b1 = new Button("click-me"); RootPanel.get().add(b1); GQuery g = $(b1); <START> assertEquals("inline-block", $(b1).css("display")); <END> g.hide(); assertEquals("none", $(b1).css("display")); }</code><technical_language>This is a bit weak, g.isVisible(), below. remember detach widget, interfere other tests</technical_language>

Target:
public void testSelectorWidget() { final Button b1 = new Button("Button click"); RootPanel.get().add(b1); GQuery g = $(b1); assertTrue(g.isVisible()); g.hide(); assertFalse(g.isVisible()); b1.removeFromParent(); }