auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public MaterializedViewSupervisor( TaskMaster taskMaster, TaskStorage taskStorage, MetadataSupervisorManager metadataSupervisorManager, SQLMetadataSegmentManager segmentManager, IndexerMetadataStorageCoordinator metadataStorageCoordinator, MaterializedViewTaskConfig config, MaterializedViewSupervisorSpec spec ) { this.taskMaster = taskMaster; this.taskStorage = taskStorage; this.metadataStorageCoordinator = metadataStorageCoordinator; this.segmentManager = segmentManager; this.metadataSupervisorManager = metadataSupervisorManager; this.config = config; this.spec = spec; this.dataSource = spec.getDataSourceName(); this.supervisorId = StringUtils.format("MaterializedViewSupervisor-%s", dataSource); <START> this.maxTaskCount = spec.getContext().containsKey("maxTaskCount") ? Integer.parseInt(String.valueOf(spec.getContext().get("maxTaskCount"))) : MAX_TASK_COUNT; <END> }</code><technical_language>Druid's coding convention is breaking line exceed 120 characters. Please follow it. for other long lines</technical_language>

Target:
public MaterializedViewSupervisor( TaskMaster taskMaster, TaskStorage taskStorage, MetadataSupervisorManager metadataSupervisorManager, SQLMetadataSegmentManager segmentManager, IndexerMetadataStorageCoordinator metadataStorageCoordinator, MaterializedViewTaskConfig config, MaterializedViewSupervisorSpec spec ) { this.taskMaster = taskMaster; this.taskStorage = taskStorage; this.metadataStorageCoordinator = metadataStorageCoordinator; this.segmentManager = segmentManager; this.metadataSupervisorManager = metadataSupervisorManager; this.config = config; this.spec = spec; this.dataSource = spec.getDataSourceName(); this.supervisorId = StringUtils.format("MaterializedViewSupervisor-%s", dataSource); this.maxTaskCount = spec.getContext().containsKey("maxTaskCount") ? Integer.parseInt(String.valueOf(spec.getContext().get("maxTaskCount"))) : DEFAULT_MAX_TASK_COUNT; this.minDataLagMs = spec.getContext().containsKey("minDataLagMs") ? Long.parseLong(String.valueOf(spec.getContext().get("minDataLagMs"))) : DEFAULT_MIN_DATA_LAG_MS; }
Source:
<code>protected boolean isInEndState() { if (status == LRAStatus.Cancelling && allFinished(heuristicList, failedList)) { status = LRAStatus.Cancelled; } else if (status == LRAStatus.Closing && allFinished(heuristicList, failedList)) { status = LRAStatus.Closed; } <START> switch (status) { <END> case FailedToCancel: case FailedToClose: case Closed: case Cancelled: return true; default: return false; } }</code><technical_language>reuse isFinished() here</technical_language>

Target:
protected boolean isInEndState() { if (status == LRAStatus.Cancelling && allFinished(heuristicList, failedList)) { status = LRAStatus.Cancelled; } else if (status == LRAStatus.Closing && allFinished(heuristicList, failedList)) { status = LRAStatus.Closed; } return isFinished(); }
Source:
<code>private ResponseEntity<?> postEventInternal(final String eventTypeName, final String eventsAsString, final NativeWebRequest nativeWebRequest, final EventTypeMetrics eventTypeMetrics, final Client client) { final long startingNanos = System.nanoTime(); try { final JSONArray eventsAsJsonObjects = new JSONArray(eventsAsString); final int eventCount = eventsAsJsonObjects.length(); <START> final int size = eventsAsString.getBytes().length; <END> eventTypeMetrics.reportSizing(eventCount, size); final ThrottleResult result = throttlingService.mark(client.getId(), eventTypeName, size, eventCount); return result.isThrottled() ? rateLimitHeaders(ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS), result).build() : response(publisher.publish(eventsAsJsonObjects, eventTypeName, client), result); } catch (final JSONException e) { LOG.debug("Problem parsing event", e); return processJSONException(e, nativeWebRequest); } catch (final NoSuchEventTypeException e) { LOG.debug("Event type not found.", e); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.debug("Failed to publish batch", e); return create(e.asProblem(), nativeWebRequest); } finally { eventTypeMetrics.updateTiming(startingNanos, System.nanoTime()); } }</code><technical_language>getBytes() fixing encoding. This is slower, call dependent environment. pass UTF_8 Charset object this method increase speed of lookup avoid unneeded charset lookup exceptoins (<LINK_0></technical_language>

Target:
private ResponseEntity<?> postEventInternal(final String eventTypeName, final String eventsAsString, final NativeWebRequest nativeWebRequest, final EventTypeMetrics eventTypeMetrics, final Client client) { final long startingNanos = System.nanoTime(); try { final JSONArray eventsAsJsonObjects = new JSONArray(eventsAsString); final int eventCount = eventsAsJsonObjects.length(); final int size = eventsAsString.getBytes().length; eventTypeMetrics.reportSizing(eventCount, size); final ThrottleResult result = throttlingService.mark(client.getId(), eventTypeName, size); return result.isThrottled() ? rateLimitHeaders(ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS), result).build() : response(publisher.publish(eventsAsJsonObjects, eventTypeName, client), result); } catch (final JSONException e) { LOG.debug("Problem parsing event", e); return processJSONException(e, nativeWebRequest); } catch (final NoSuchEventTypeException e) { LOG.debug("Event type not found.", e); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.debug("Failed to publish batch", e); return create(e.asProblem(), nativeWebRequest); } finally { eventTypeMetrics.updateTiming(startingNanos, System.nanoTime()); } }
Source:
<code>public String run( ReportInfo ri ) { StringBuilder sb = new StringBuilder(); sb.append("Generated: ").append( new Date().toString() ).append("\n"); sb.append("From - Till: ").append( <START> new SimpleDateFormat("MM/dd/yyyy").format(ri.from().getTime()) <END> ).append(" - ").append( new SimpleDateFormat("MM/dd/yyyy").format(ri.till().getTime()) ).append("\n"); sb.append("Url: ").append( ConfigurationManager.getProperty("dspace.url") ).append("\n"); sb.append("\n"); for (String[] ss : new String[][] { new String[] { ConfigurationManager.getProperty("assetstore.dir"), "Assetstore size: ", }, new String[] { ConfigurationManager.getProperty("search.dir"), "Search dir size: ", }, new String[] { ConfigurationManager.getProperty("log.dir"), "Log dir size: ", }, }) { try { File dir = new File(ss[0]); if (dir.exists()) { long dir_size = FileUtils.sizeOfDirectory(dir); sb.append(String.format("%s: %s\n", ss[1], FileUtils.byteCountToDisplaySize(dir_size)) ); } else { sb.append(String.format("Directory [%s] does not exist!\n", ss[0])); } }catch(Exception e) { error(e, "directory - " + ss[0]); } } return sb.toString(); }</code><technical_language>please ISO 8601 :)</technical_language>

Target:
public String run( ReportInfo ri ) { StringBuilder sb = new StringBuilder(); sb.append("Generated: ").append( new Date().toString() ).append("\n"); sb.append("From - Till: ").append( new SimpleDateFormat("yyyy-MM-dd").format(ri.from().getTime()) ).append(" - ").append( new SimpleDateFormat("yyyy-MM-dd").format(ri.till().getTime()) ).append("\n"); sb.append("Url: ").append( ConfigurationManager.getProperty("dspace.url") ).append("\n"); sb.append("\n"); DSBitStoreService localStore = new DSpace().getServiceManager().getServicesByType(DSBitStoreService.class).get(0); for (String[] ss : new String[][] { new String[] { localStore.getBaseDir().toString(), "Assetstore size", }, new String[] { ConfigurationManager.getProperty("search.dir"), "Search dir size", }, new String[] { ConfigurationManager.getProperty("log.dir"), "Log dir size", }, }) { try { File dir = new File(ss[0]); if (dir.exists()) { long dir_size = FileUtils.sizeOfDirectory(dir); sb.append(String.format("%-20s: %s\n", ss[1], FileUtils.byteCountToDisplaySize(dir_size)) ); } else { sb.append(String.format("Directory [%s] does not exist!\n", ss[0])); } }catch(Exception e) { error(e, "directory - " + ss[0]); } } return sb.toString(); }
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String searchQueryExtra = null; String searchUrl = null; if (savedInstanceState != null) { searchUrl = savedInstanceState.getString(INSTANCE_CURRENT_DISCOVER_URL, null); } <START> if (getArguments() != null && searchUrl == null) { <END> searchQueryExtra = getArguments().getString(Router.EXTRA_SEARCH_QUERY); } if (searchQueryExtra != null) { initSearch(searchQueryExtra); } else { loadUrl(searchUrl == null ? getInitialUrl() : searchUrl); } if (shouldShowSubjectDiscovery()) { initSubjects(); } if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } }</code><technical_language>Nullability of searchUrl checked first</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String searchQueryExtra = null; String searchUrl = null; if (savedInstanceState != null) { searchUrl = savedInstanceState.getString(INSTANCE_CURRENT_DISCOVER_URL, null); } if (searchUrl == null && getArguments() != null) { searchQueryExtra = getArguments().getString(Router.EXTRA_SEARCH_QUERY); } if (searchQueryExtra != null) { initSearch(searchQueryExtra); } else { loadUrl(searchUrl == null ? getInitialUrl() : searchUrl); } if (shouldShowSubjectDiscovery()) { initSubjects(); } if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } }
Source:
<code>public static void deleteAllUsers(final String userpoolId) { ListUsersResult listUsersResult; do { ListUsersRequest listUsersRequest = new ListUsersRequest() .withUserPoolId(userpoolId) .withLimit(60); listUsersResult = getUserpoolLL().listUsers(listUsersRequest); for (UserType user : listUsersResult.getUsers()) { if (USERNAME.equals(user.getUsername()) <START> || "bimin".equals(user.getUsername()) || "roskumr@amazon.com".equals(user.getUsername())) { <END> continue; } boolean retryConfirmSignUp = false; do { try { Log.d(TAG, "deleteAllUsers: " + user.getUsername()); getUserpoolLL().adminDeleteUser(new AdminDeleteUserRequest().withUsername(user.getUsername()).withUserPoolId(userpoolId)); } catch (UserNotConfirmedException e) { if (!retryConfirmSignUp) { AdminConfirmSignUpRequest adminConfirmSignUpRequest = new AdminConfirmSignUpRequest(); adminConfirmSignUpRequest.withUsername(user.getUsername()).withUserPoolId(userpoolId); getUserpoolLL().adminConfirmSignUp(adminConfirmSignUpRequest); retryConfirmSignUp = true; try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } } else { retryConfirmSignUp = false; } } catch (Exception e) { Log.e(TAG, "deleteAllUsers: Some error trying to delete user", e); } } while (retryConfirmSignUp); } } while (listUsersResult.getPaginationToken() != null); }</code><technical_language>set a test user hardcoded individual names</technical_language>

Target:
public static void deleteAllUsers(final String userpoolId) { ListUsersResult listUsersResult; do { ListUsersRequest listUsersRequest = new ListUsersRequest() .withUserPoolId(userpoolId) .withLimit(60); listUsersResult = getUserpoolLL().listUsers(listUsersRequest); for (UserType user : listUsersResult.getUsers()) { if (USERNAME.equals(user.getUsername()) || "bimin".equals(user.getUsername()) || "customAuthTestUser".equals(user.getUsername())) { continue; } boolean retryConfirmSignUp = false; do { try { Log.d(TAG, "deleteAllUsers: " + user.getUsername()); getUserpoolLL().adminDeleteUser(new AdminDeleteUserRequest().withUsername(user.getUsername()).withUserPoolId(userpoolId)); } catch (UserNotConfirmedException e) { if (!retryConfirmSignUp) { AdminConfirmSignUpRequest adminConfirmSignUpRequest = new AdminConfirmSignUpRequest(); adminConfirmSignUpRequest.withUsername(user.getUsername()).withUserPoolId(userpoolId); getUserpoolLL().adminConfirmSignUp(adminConfirmSignUpRequest); retryConfirmSignUp = true; try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } } else { retryConfirmSignUp = false; } } catch (Exception e) { Log.e(TAG, "deleteAllUsers: Some error trying to delete user", e); } } while (retryConfirmSignUp); } } while (listUsersResult.getPaginationToken() != null); }
Source:
<code>public static void cleanup() { if (scs_kafka_test_embedded != null) { System.setProperty("SCS_KAFKA_TEST_EMBEDDED", scs_kafka_test_embedded); <START> } else { <END> System.clearProperty("SCS_KAFKA_TEST_EMBEDDED"); } }</code><technical_language>else new line. catch, finally etc.</technical_language>

Target:
public static void cleanup() { System.clearProperty("SCS_KAFKA_TEST_EMBEDDED"); }
Source:
<code>public static String getFormattedFileName(Artifact artifact) { <START> StringBuilder destFileName = buildMainFileName(artifact); <END> String extension = new DefaultArtifactHandler(artifact.getType()).getExtension(); destFileName.append(extension); return destFileName.toString(); }</code><technical_language>Docs please. I understand public static methods "api" stuff</technical_language>

Target:
public static String getFormattedFileName(Artifact artifact) { String destFileName = buildMainFileName(artifact); String extension = new DefaultArtifactHandler(artifact.getType()).getExtension(); return destFileName + "." + extension; }
Source:
<code>public void put( Locator locator, String key, String value ) throws IOException { Timer.Context ctx = Instrumentation.getWriteTimerContext( CassandraModel.CF_METRICS_METADATA_NAME ); Session session = DatastaxIO.getSession(); try { Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME ) .value( KEY, locator.toString() ) .value( COLUMN1, key ) .value( VALUE, serDes.serialize( value ) ); <START> insert.setConsistencyLevel( ConsistencyLevel.ONE ); <END> ResultSet result = session.execute( insert ); LOG.debug( "result.size=" + result.all().size() ); } finally { ctx.stop(); } }</code><technical_language>If forget maven plugin, is consistency level currently use? If is "ConsistencyLevel.ONE", arent sacrificing data consistency support this plugin</technical_language>

Target:
public void put( Locator locator, String key, String value ) throws IOException { Timer.Context ctx = Instrumentation.getWriteTimerContext( CassandraModel.CF_METRICS_METADATA_NAME ); Session session = DatastaxIO.getSession(); try { Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME ) .value( KEY, locator.toString() ) .value( COLUMN1, key ) .value( VALUE, serDes.serialize( value ) ); insert.setConsistencyLevel( ConsistencyLevel.ONE ); ResultSet result = session.execute( insert ); LOG.trace( "result.size=" + result.all().size() ); } finally { ctx.stop(); } }
Source:
<code>protected void parseCurrencyPairsFromJsonObject(int requestId, JSONObject jsonObject, List<CurrencyPairInfo> pairs) throws Exception { final JSONArray data = jsonObject.getJSONArray("data"); for(int i=0; i< data.length(); ++i) { String symbol = data.getJSONObject(i).getString("symbol"); <START> String[] currencies = symbol.split("-"); <END> if(currencies.length!=2) continue; String currencyBase = currencies[0].toUpperCase(Locale.ENGLISH); String currencyCounter = currencies[1].toUpperCase(Locale.ENGLISH); pairs.add(new CurrencyPairInfo(currencyBase, currencyCounter, symbol)); } }</code><technical_language>I is need do a split, fields called coinType coinTypePair stored individual currency names. is need uppercase uppercase</technical_language>

Target:
protected void parseCurrencyPairsFromJsonObject(int requestId, JSONObject jsonObject, List<CurrencyPairInfo> pairs) throws Exception { final JSONArray data = jsonObject.getJSONArray("data"); for(int i=0; i< data.length(); ++i) { final JSONObject pairJsonObject = data.getJSONObject(i); pairs.add(new CurrencyPairInfo( pairJsonObject.getString("coinType"), pairJsonObject.getString("coinTypePair"), pairJsonObject.getString("symbol") )); } }
Source:
<code>public void truncateTable(TableName tableName, boolean preserveSplits) throws IOException { HTableDescriptor tableDescriptor = getTableDescriptor(tableName); <START> LOG.info("Deleting table %s", tableName); <END> deleteTable(tableName); LOG.info("Creating table %s", tableName); createTable(tableDescriptor); }</code><technical_language>this log misleading, table is deleted. "Deleting table %s for truncation"</technical_language>

Target:
public void truncateTable(TableName tableName, boolean preserveSplits) throws IOException { byte[][] splitKeys = null; if (preserveSplits) { splitKeys = getSplits(tableName); } HTableDescriptor tableDescriptor = getTableDescriptor(tableName); LOG.info("Deleting table %s for truncation.", tableName); deleteTable(tableName); LOG.info("Recreating table %s for truncation", tableName); createTable(tableDescriptor, splitKeys); }
Source:
<code>public void setupContext() { super.setupContext(); NodeMetadata node = null; try { node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group))); } catch (RunNodesException e) { <START> e.printStackTrace(); <END> } String resourceid = String.format("/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s", IdReference.extractResourceGroup(node.getProviderId()), IdReference.extractName(node.getProviderId())); location = view.getComputeService().templateBuilder().build().getLocation().getId(); view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null); metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceid); }</code><technical_language>Fail test instead of silently printing error stdout</technical_language>

Target:
public void setupContext() { super.setupContext(); NodeMetadata node = null; try { node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group))); } catch (RunNodesException e) { fail(); } String resourceId = String.format("/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s", IdReference.extractResourceGroup(node.getProviderId()), IdReference.extractName(node.getProviderId())); location = view.getComputeService().templateBuilder().build().getLocation().getId(); view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null); metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceId); }
Source:
<code>public void testParquetTupleDomainPrimitiveArray() { HiveColumnHandle columnHandle = new HiveColumnHandle("my_array", HiveType.valueOf("array<int>"), parseTypeSignature(StandardTypes.ARRAY), 0, REGULAR, Optional.empty()); TupleDomain<HiveColumnHandle> domain = withColumnDomains(ImmutableMap.of(columnHandle, Domain.notNull(new ArrayType(INTEGER)))); MessageType fileSchema = new MessageType("hive_schema", new GroupType(OPTIONAL, "my_array", new GroupType(REPEATED, "bag", new PrimitiveType(OPTIONAL, INT32, "array_element")))); <START> Map<Type, HiveColumnHandle> typeColumns = new HashMap<>(); <END> typeColumns.put(getParquetType(columnHandle, fileSchema, true), columnHandle); Map<List<String>, RichColumnDescriptor> descriptorsByPath = getDescriptors(fileSchema, fileSchema, typeColumns); TupleDomain<ColumnDescriptor> tupleDomain = getParquetTupleDomain(descriptorsByPath, domain); assertTrue(tupleDomain.getDomains().get().isEmpty()); }</code><technical_language>Map<Type, HiveColumnHandle> typeColumns = ImmutableMap.of(getParquetType(columnHandle, fileSchema, true), columnHandle); Please update changes below</technical_language>

Target:
public void testParquetTupleDomainPrimitiveArray() { HiveColumnHandle columnHandle = new HiveColumnHandle("my_array", HiveType.valueOf("array<int>"), parseTypeSignature(StandardTypes.ARRAY), 0, REGULAR, Optional.empty()); TupleDomain<HiveColumnHandle> domain = withColumnDomains(ImmutableMap.of(columnHandle, Domain.notNull(new ArrayType(INTEGER)))); MessageType fileSchema = new MessageType("hive_schema", new GroupType(OPTIONAL, "my_array", new GroupType(REPEATED, "bag", new PrimitiveType(OPTIONAL, INT32, "array_element")))); Map<Type, HiveColumnHandle> typeColumns = ImmutableMap.of(getParquetType(columnHandle, fileSchema, true), columnHandle); Map<List<String>, RichColumnDescriptor> descriptorsByPath = getDescriptors(fileSchema, fileSchema, typeColumns); TupleDomain<ColumnDescriptor> tupleDomain = getParquetTupleDomain(descriptorsByPath, domain); assertTrue(tupleDomain.getDomains().get().isEmpty()); }
Source:
<code>public void editFilenamelNonFileObjTest() { when(repoObjLoader.getRepositoryObject(any(PID.class))).thenReturn(workObj); <START> doThrow(new IllegalArgumentException()).when(aclService) <END> .assertHasAccess(anyString(), eq(pid), any(AccessGroupSet.class), eq(Permission.editDescription)); try { service.editLabel(agent, pid, "label"); } catch (Exception e) { assertEquals(e.getCause().getClass(), IllegalArgumentException.class); } }</code><technical_language>need this throw, fact repoObjLoader returns a work trigger expected exception</technical_language>

Target:
public void editFilenamelNonFileObjTest() { when(repoObjLoader.getRepositoryObject(any(PID.class))).thenReturn(workObj); try { service.editLabel(agent, pid, "label"); } catch (Exception e) { assertEquals(e.getCause().getClass(), IllegalArgumentException.class); } }
Source:
<code><START> private void removeAllStores(JSONArray args, CallbackContext callbackContext) throws JSONException { <END> List<String> userDatabaseNames = SmartStoreSDKManager.getInstance().getUserStoresPrefixList(); for(String storeName : userDatabaseNames) { SmartStoreSDKManager.getInstance().removeSmartStore(storeName,UserAccountManager.getInstance().getCurrentUser(),UserAccountManager.getInstance().getCurrentUser().getCommunityId()); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }</code><technical_language>a removeAllStores method SmartStoreSDKManager do iOS</technical_language>

Target:
private void removeAllStores(JSONArray args, CallbackContext callbackContext) throws JSONException { SmartStoreSDKManager.getInstance().removeAllUserStores(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }
Source:
<code>public StaticMethodInformation(String name, String[] parameterTypes, String returnType, String declaringClass) { this.name = name; <START> this.parameterTypes = parameterTypes.clone(); <END> this.returnType = returnType; this.declaringClass = declaringClass; StringBuilder builder = new StringBuilder("("); for (String p : this.parameterTypes) { builder.append(p); } builder.append(')'); builder.append(returnType); descriptor = builder.toString(); this.modifiers = AccessFlag.PUBLIC; }</code><technical_language>This is necessary control, suppress</technical_language>

Target:
public StaticMethodInformation(String name, String[] parameterTypes, String returnType, String declaringClass) { this.name = name; this.parameterTypes = parameterTypes; this.returnType = returnType; this.declaringClass = declaringClass; StringBuilder builder = new StringBuilder("("); for (String p : this.parameterTypes) { builder.append(p); } builder.append(')'); builder.append(returnType); descriptor = builder.toString(); this.modifiers = AccessFlag.PUBLIC; }
Source:
<code>public Result updateElementRevision(String id, String revisionString) { UserSession session = getAuthenticatedSession(DEVELOPER); Long revision = BridgeUtils.getLongOrDefault(revisionString, 0L); AppConfigElement element = parseJson(request(), AppConfigElement.class); element.setId(id); <START> element.setRevision(revision); <END> VersionHolder holder = service.updateElementRevision(session.getStudyIdentifier(), element); return okResult(holder); }</code><technical_language>this logic in controller service</technical_language>

Target:
public Result updateElementRevision(String id, String revisionString) { UserSession session = getAuthenticatedSession(DEVELOPER); Long revision = BridgeUtils.getLongOrDefault(revisionString, null); if (revision == null) { throw new BadRequestException("Revision is not a valid revision number"); } AppConfigElement element = parseJson(request(), AppConfigElement.class); element.setId(id); element.setRevision(revision); VersionHolder holder = service.updateElementRevision(session.getStudyIdentifier(), element); return okResult(holder); }
Source:
<code>private boolean checkForHypervisorIdUpdate(Consumer existing, ConsumerDTO incoming) { HypervisorIdDTO incomingId = incoming.getHypervisorId(); if (incomingId != null) { HypervisorId existingId = existing.getHypervisorId(); if (incomingId.getHypervisorId() == null || incomingId.getHypervisorId().isEmpty()) { existing.setHypervisorId(null); } else { if (existingId != null) { if (existingId.getHypervisorId() != null && !existingId.getHypervisorId().equals(incomingId.getHypervisorId())) { existingId.setHypervisorId(incomingId.getHypervisorId()); Owner owner = ownerCurator.findOwnerById(existing.getOwnerId()); existingId.setOwner(owner); } else { return false; } } else { <START> Owner owner = ownerCurator.findOwnerById(existing.getOwnerId()); <END> if (isUsedByOwner(incomingId, owner)) { throw new BadRequestException(i18n.tr( "Problem updating unit {0}. Hypervisor id: {1} is already used.", incoming, incomingId.getHypervisorId())); } HypervisorId hypervisorId = new HypervisorId(incomingId.getHypervisorId()); hypervisorId.setOwner(owner); existing.setHypervisorId(hypervisorId); } } return true; } return false; }</code><technical_language>understand condition this error is encountered</technical_language>

Target:
private boolean checkForHypervisorIdUpdate(Consumer existing, ConsumerDTO incoming) { HypervisorIdDTO incomingId = incoming.getHypervisorId(); if (incomingId != null) { HypervisorId existingId = existing.getHypervisorId(); if (incomingId.getHypervisorId() == null || incomingId.getHypervisorId().isEmpty()) { existing.setHypervisorId(null); } else { Owner owner = ownerCurator.findOwnerById(existing.getOwnerId()); if (isUsedByOwner(incomingId, owner)) { throw new BadRequestException(i18n.tr( "Problem updating unit {0}. Hypervisor id: {1} is already used.", incoming, incomingId.getHypervisorId())); } if (existingId != null) { if (existingId.getHypervisorId() != null && !existingId.getHypervisorId().equals(incomingId.getHypervisorId())) { existingId.setHypervisorId(incomingId.getHypervisorId()); existingId.setOwner(owner); } else { return false; } } else { HypervisorId hypervisorId = new HypervisorId(incomingId.getHypervisorId()); hypervisorId.setOwner(owner); existing.setHypervisorId(hypervisorId); } } return true; } return false; }
Source:
<code>public boolean isPanelValid() { <START> return true; <END> }</code><technical_language>do validation occurs in run method here? a minimum, need some folder path entered in text field</technical_language>

Target:
public boolean isPanelValid() { configPanel.clearErrorText(); String selectedFilePath = configPanel.getSelectedFilePath(); if(selectedFilePath.isEmpty()) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_noPathSelected()); return false; } File selectedFile = new File(selectedFilePath); Path selectedPath = selectedFile.toPath(); if (!Files.isReadable(selectedPath)) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_notReadable()); return false; } try { if (!XRYFolder.isXRYFolder(selectedPath)) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_notXRYFolder()); return false; } } catch (IOException ex) { configPanel.setErrorText(Bundle.XRYDataSourceProcessor_ioError()); logger.log(Level.WARNING, "[XRY DSP] I/O exception encountered trying to test the XRY folder.", ex); return false; } return true; }
Source:
<code>public void finish() { IConsumerAggregator aggregator = fXAggregator; if (aggregator != null) { <START> fSeries.stream().map(s -> s.getXConsumer()).forEach(aggregator::accept); <END> } aggregator = fYAggregator; if (aggregator != null) { fSeries.stream().map(s -> s.getYConsumer()).forEach(aggregator::accept); } }</code><technical_language>avoid stream here: fSeries.forEach(s -> aggregator.accept(s.getXConsumer())); slightly characters! This force separate variables for X Y aggregators, is a bad thing</technical_language>

Target:
public void finish() { IConsumerAggregator aggregatorX = fXAggregator; if (aggregatorX != null) { fSeries.forEach(s -> aggregatorX.accept(s.getXConsumer())); } IConsumerAggregator aggregatorY = fYAggregator; if (aggregatorY != null) { fSeries.forEach(s -> aggregatorY.accept(s.getYConsumer())); } }
Source:
<code>private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception { context.turnOffAuthorisationSystem(); <START> parentCommunity = CommunityBuilder.createCommunity(context).withName("Community").build(); <END> String token = getAuthToken(asUser.getEmail(), password); new MetadataPatchSuite().runWith(getClient(token), "/api/core/communities/" + parentCommunity.getID(), expectedStatus); }</code><technical_language>Again, needs a context.restoreAuthSystemState();</technical_language>

Target:
private void runPatchMetadataTests(EPerson asUser, int expectedStatus) throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context).withName("Community").build(); context.restoreAuthSystemState(); String token = getAuthToken(asUser.getEmail(), password); new MetadataPatchSuite().runWith(getClient(token), "/api/core/communities/" + parentCommunity.getID(), expectedStatus); }
Source:
<code>public void validate(final List<LotDepositDto> lotDepositDtos){ errors = new MapBindingResult(new HashMap<String, String>(), LotGeneratorInputDto.class.getName()); <START> if (lotDepositDtos == null) { <END> errors.reject("lot.deposit.input.null", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } lotDepositDtos.forEach((LotDepositDto lotDepositDto) ->{ inventoryCommonValidator.validateTransactionNotes(lotDepositDto.getNotes(), errors); if(lotDepositDto.getAmount() == null || lotDepositDto.getAmount() <= 0){ errors.reject("lot.amount.invalid", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }); }</code><technical_language>BaseValidator</technical_language>

Target:
public void validate(final List<LotDepositDto> lotDepositDtos){ errors = new MapBindingResult(new HashMap<String, String>(), LotGeneratorInputDto.class.getName()); BaseValidator.checkNotEmpty(lotDepositDtos,"lot.deposit.input.null"); lotDepositDtos.forEach((LotDepositDto lotDepositDto) ->{ inventoryCommonValidator.validateTransactionNotes(lotDepositDto.getNotes(), errors); if(lotDepositDto.getAmount() == null || lotDepositDto.getAmount() <= 0){ errors.reject("lot.amount.invalid", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }); }
Source:
<code>public Token<OzoneTokenIdentifier> getDelegationToken(Text renewer) throws IOException { Token<OzoneTokenIdentifier> token = ozoneManagerClient.getDelegationToken(renewer); if (token != null) { token.setService(dtService); LOG.debug("Created token for dtService {}", token, dtService); } else { <START> LOG.debug("Cannot get ozone delegation token from for service {}", <END> renewer, dtService); } return token; }</code><technical_language>rephrase "Cannot get ozone delegation token for renwer:{} service:{}"</technical_language>

Target:
public Token<OzoneTokenIdentifier> getDelegationToken(Text renewer) throws IOException { Token<OzoneTokenIdentifier> token = ozoneManagerClient.getDelegationToken(renewer); if (token != null) { token.setService(dtService); LOG.debug("Created token for dtService {}", token, dtService); } else { LOG.debug("Cannot get ozone delegation token for renewer to access " + "service {}", renewer, dtService); } return token; }
Source:
<code>private void sendTakeMastershipEvent(long uso) { Pair<Mailbox, ImmutableList<Long>> p = m_ackMailboxRefs.get(); Mailbox mbx = p.getFirst(); if (mbx != null && p.getSecond().size() > 0 && m_newLeaderHostId != null) { final int msgLen = 1 + 4 + 4 + m_signatureBytes.length + 8; ByteBuffer buf = ByteBuffer.allocate(msgLen); buf.put(ExportManager.TAKE_MASTERSHIP); buf.putInt(m_partitionId); buf.putInt(m_signatureBytes.length); buf.put(m_signatureBytes); buf.putLong(uso); BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array()); for(Long siteId: p.getSecond()) { if (CoreUtils.getHostIdFromHSId(siteId) != m_newLeaderHostId) { continue; } mbx.send(siteId, bpm); if (exportLog.isDebugEnabled()) { exportLog.debug("Partition " + m_partitionId + " mailbox hsid (" + CoreUtils.hsIdToString(mbx.getHSId()) + ") send TAKE_MASTERSHIP message to " + CoreUtils.hsIdToString(siteId)); <START> } <END> } m_usoToDrain = -1L; m_newLeaderHostId = null; } }</code><technical_language>break out of for loop here, correct</technical_language>

Target:
private void sendTakeMastershipEvent(long uso) { Pair<Mailbox, ImmutableList<Long>> p = m_ackMailboxRefs.get(); Mailbox mbx = p.getFirst(); if (mbx != null && p.getSecond().size() > 0 && m_newLeaderHostId != null) { final int msgLen = 1 + 4 + 4 + m_signatureBytes.length + 8; ByteBuffer buf = ByteBuffer.allocate(msgLen); buf.put(ExportManager.TAKE_MASTERSHIP); buf.putInt(m_partitionId); buf.putInt(m_signatureBytes.length); buf.put(m_signatureBytes); buf.putLong(uso); BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array()); for(Long siteId: p.getSecond()) { if (CoreUtils.getHostIdFromHSId(siteId) == m_newLeaderHostId) { mbx.send(siteId, bpm); if (exportLog.isDebugEnabled()) { exportLog.debug("Partition " + m_partitionId + " mailbox hsid (" + CoreUtils.hsIdToString(mbx.getHSId()) + ") send TAKE_MASTERSHIP message to " + CoreUtils.hsIdToString(siteId)); } break; } } m_usoToDrain = -1L; m_newLeaderHostId = null; } }
Source:
<code>public String getRequestSpecificParams() { <START> StringWriter writer = new StringWriter(); <END> writer.write("/json?indicator="); writer.write(getIndicator()); for (String year : getYears()) { if (!year.isEmpty()) { writer.write("&years="); writer.write(year); } } if (!getGender().isEmpty()) { writer.write("&genders="); writer.write(getGender()); } return writer.toString(); }</code><technical_language>StringBuilder instead of StringWriter. StringWriter internally StringBuffer is basically synchronized version of StringBuilder. StringBuilder allows function chaining (e.g. sb.append("foo).append("bar");) is nice</technical_language>

Target:
public String getRequestSpecificParams() { Map<String, String> params = new HashMap<>(); params.put("indicator", getIndicator()); params.put("genders", getGender()); String url = IOHelper.constructUrl("/json", params); Map<String, String[]> years = new HashMap<>(); years.put("years", getYears()); return url + "&" + IOHelper.getParamsMultiValue(years); }
Source:
<code>public void concurrentDeleteAndPutTest() throws Exception { MockId id = getUniqueId(); final CountDownLatch getEndOffsetLatch = new CountDownLatch(1); final CountDownLatch findKeyLatch = new CountDownLatch(1); ((MockBlobStore) store).setBetweenGetEndOffsetAndFindKeyFunc(() -> { getEndOffsetLatch.countDown(); try { findKeyLatch.await(); } catch (Exception e) { } }); ExecutorService executorService = Executors.newFixedThreadPool(2); try { <START> Future<Void> deleteFuture = executorService.submit(new Callable<Void>() { <END> @Override public Void call() throws Exception { MessageInfo info = new MessageInfo(id, DELETE_RECORD_SIZE, id.getAccountId(), id.getContainerId(), time.milliseconds(), MessageInfo.LIFE_VERSION_FROM_FRONTEND); store.delete(Collections.singletonList(info)); return null; } }); getEndOffsetLatch.await(); Future<Void> putFuture = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { putOneBlobWithId(id, PUT_RECORD_SIZE, Utils.Infinite_Time); return null; } }); putFuture.get(); findKeyLatch.countDown(); try { deleteFuture.get(); fail("Should fail with ID_NOT_FOUND error"); } catch (Exception e) { assertTrue(e.getCause() instanceof StoreException); assertEquals(StoreErrorCodes.ID_Not_Found, ((StoreException) e.getCause()).getErrorCode()); } } finally { ((MockBlobStore) store).setBetweenGetEndOffsetAndFindKeyFunc(null); executorService.shutdownNow(); } }</code><technical_language>lambda callables well</technical_language>

Target:
public void concurrentDeleteAndPutTest() throws Exception { MockId id = getUniqueId(); final CountDownLatch getEndOffsetLatch = new CountDownLatch(1); final CountDownLatch findKeyLatch = new CountDownLatch(1); ((MockBlobStore) store).setInDeleteBetweenGetEndOffsetAndFindKey(() -> { getEndOffsetLatch.countDown(); findKeyLatch.await(); return null; }); ExecutorService executorService = Executors.newFixedThreadPool(2); try { Future<Void> deleteFuture = executorService.submit(() -> { MessageInfo info = new MessageInfo(id, DELETE_RECORD_SIZE, id.getAccountId(), id.getContainerId(), time.milliseconds(), MessageInfo.LIFE_VERSION_FROM_FRONTEND); store.delete(Collections.singletonList(info)); return null; }); Future<Void> putFuture = executorService.submit(() -> { getEndOffsetLatch.await(); putOneBlobWithId(id, PUT_RECORD_SIZE, Utils.Infinite_Time); findKeyLatch.countDown(); return null; }); putFuture.get(); try { deleteFuture.get(); fail("Should fail with ID_NOT_FOUND error"); } catch (Exception e) { assertTrue(e.getCause() instanceof StoreException); assertEquals(StoreErrorCodes.ID_Not_Found, ((StoreException) e.getCause()).getErrorCode()); } } finally { ((MockBlobStore) store).setInDeleteBetweenGetEndOffsetAndFindKey(null); executorService.shutdownNow(); } }
Source:
<code>private static <T> void runUntilEmpty(Queue<T> queue, Consumer<T> consumer) { while (!queue.isEmpty()) { T element = queue.poll(); if (element == null) { break; } <START> consumer.accept(element); <END> } }</code><technical_language>avoid some contention shared queue empty check: for (T element = queue.poll(); element != null; element = queue.poll()) { consumer.accept(element); }</technical_language>

Target:
private static <T> void runUntilEmpty(Queue<T> queue, Consumer<T> consumer) { for (T element = queue.poll(); element != null; element = queue.poll()) { consumer.accept(element); } }
Source:
<code>public Vote checkXid(Xid xid) { if (xid.getFormatId() != XATxConverter.FORMAT_ID) { return Vote.ABSTAIN; } if (!TxControl.getXANodeName().equals(XATxConverter.getSubordinateNodeName(new XidImple(xid).getXID()))) { return Vote.ABSTAIN; <START> } <END> if (!validatePosition()) { return Vote.LEAVE_ALONE; } XidImple theXid = new XidImple(xid); SubordinateTransaction importedTransaction = null; try { importedTransaction = SubordinationManager.getTransactionImporter().getImportedTransaction(theXid); } catch (XAException e) { return Vote.LEAVE_ALONE; } if (importedTransaction != null) { return Vote.LEAVE_ALONE; } else { return Vote.ROLLBACK; } }</code><technical_language>happen XATxConverter.getSubordinateNodeName getXID match NodeNameXAResourceOrphanFilter match XATxConverter.getNodeName for XID. This - this filter votes for {{ABSTAIN}} orphan filter votes for rollback. I find some situation reach this top of head. I mention possibility</technical_language>

Target:
public Vote checkXid(Xid xid) { if (xid.getFormatId() != XATxConverter.FORMAT_ID) { return Vote.ABSTAIN; } if (!TxControl.getXANodeName().equals(XATxConverter.getSubordinateNodeName(new XidImple(xid).getXID()))) { return Vote.ABSTAIN; } if (!getSubordinateAtomicActionRecoveryModule().isRecoveryScanCompletedWithoutError()) { return Vote.LEAVE_ALONE; } XidImple theXid = new XidImple(xid); SubordinateTransaction importedTransaction = null; try { importedTransaction = SubordinationManager.getTransactionImporter().getImportedTransaction(theXid); } catch (XAException e) { return Vote.LEAVE_ALONE; } if (importedTransaction != null) { return Vote.LEAVE_ALONE; } else { return Vote.ROLLBACK; } }
Source:
<code>public ServiceInstancePool() { <START> this(300000); <END> }</code><technical_language>this configurable</technical_language>

Target:
public ServiceInstancePool() { this.timer.schedule(new TimerTask() { @Override public void run() { expire(); } }, this.HOUSEKEEPING_INTERVAL, this.HOUSEKEEPING_INTERVAL); }
Source:
<code>public static String encrypt(String apiKey, Map<String, Object> options) throws ScopedKeyException { if (apiKey.length() == 64) { return encrypt(KeenClient.client(), apiKey, options); } else { <START> return oldEncrypt(KeenClient.client(), apiKey, options); <END> } }</code><technical_language>Suggestion: call encrypt64CharacterKey encrypt32CharacterKey instead of encrypt oldEncrypt; provide a lot of insight difference, need get renamed if/when change algorithm again</technical_language>

Target:
public static String encrypt(String apiKey, Map<String, Object> options) throws ScopedKeyException { if (apiKey.length() == 64) { return encrypt(KeenClient.client(), apiKey, options); } else { return encrypt32CharacterKey(KeenClient.client(), apiKey, options); } }
Source:
<code>public static void main(String[] args) { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; EventHubClient client = new EventHubClientBuilder() .connectionString(connectionString) .build(); EventHubProducer producer = client.createProducer(); <START> List<EventData> dataList = new ArrayList<>(); <END> dataList.add(new EventData("EventData Sample 1".getBytes(UTF_8))); dataList.add(new EventData("EventData Sample 2 ".getBytes(UTF_8))); dataList.add(new EventData("EventData Sample 3".getBytes(UTF_8))); String firstPartition = client.getPartitionIds().blockFirst(OPERATION_TIMEOUT); SendOptions sendOptions = new SendOptions().partitionKey(firstPartition); producer.send(dataList, sendOptions).subscribe( (ignored) -> System.out.println("A list of event sent to specific partition, partition ID = " + firstPartition), error -> { System.err.println("There was an error sending the event batch: " + error.toString()); if (error instanceof AmqpException) { AmqpException amqpException = (AmqpException) error; System.err.println(String.format("Is send operation retriable? %s. Error condition: %s", amqpException.isTransient(), amqpException.getErrorCondition())); } }, () -> { try { producer.close(); } catch (IOException e) { System.err.println("Error encountered while closing producer: " + e.toString()); } client.close(); }); }</code><technical_language>Flux.just</technical_language>

Target:
public static void main(String[] args) { String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; EventHubClient client = new EventHubClientBuilder() .connectionString(connectionString) .buildAsyncClient(); EventHubProducer producer = client.createProducer(); Flux<EventData> data = Flux.just( new EventData("Ball".getBytes(UTF_8)), new EventData("Net".getBytes(UTF_8)), new EventData("Players".getBytes(UTF_8))); SendOptions sendOptions = new SendOptions().partitionKey("basketball"); producer.send(data, sendOptions).subscribe( (ignored) -> System.out.println("Sending a list of events to a partition that the partition key maps to..."), error -> { System.err.println("There was an error sending the event batch: " + error.toString()); if (error instanceof AmqpException) { AmqpException amqpException = (AmqpException) error; System.err.println(String.format("Is send operation retriable? %s. Error condition: %s", amqpException.isTransient(), amqpException.getErrorCondition())); } }, () -> { try { producer.close(); } catch (IOException e) { System.err.println("Error encountered while closing producer: " + e.toString()); } client.close(); }); }
Source:
<code>public View getDropDownView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(context); convertView = inflater.inflate(R.layout.custom_spinner_item, parent, false); } TextView tv = (TextView)convertView.findViewById(android.R.id.text1); if(position == 0){ tv.setHeight(0); }else{ <START> tv.setHeight(3*(int)textSize+12); <END> tv.setText(items[position]); tv.setTextSize(textUnit, textSize); tv.setPadding(10, 10, 10, 10); } return convertView; }</code><technical_language>This feels weird - manually setting height this</technical_language>

Target:
public View getDropDownView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(context); convertView = inflater.inflate(R.layout.custom_spinner_item, parent, false); } TextView tv = (TextView)convertView.findViewById(android.R.id.text1); tv.setText(items[position]); tv.setTextSize(textUnit, textSize); tv.setPadding(10, 10, 10, 10); return convertView; }
Source:
<code>public OutputColumns getOutputColumns() { OutputColumns outCols; try { CreateInput createInput = new CreateInput(); createInput.configuration = getConfiguration(getUsedInputColumns()); if(lastOutputColumns != null && createInput.equals(lastCreateInput)) { logger.debug("Reusing cached output columns, nothing changed"); outCols = lastOutputColumns; } else { logger.debug("Getting output columns from server"); boolean wasInit = false; if(client == null) { wasInit = true; initClient(); } try { org.datacleaner.restclient.OutputColumns columnsSpec = client.getOutputColumns(componentDisplayName, createInput); outCols = new OutputColumns(columnsSpec.getColumns().size(), Object.class); int i = 0; for (org.datacleaner.restclient.OutputColumns.OutputColumn colSpec : columnsSpec.getColumns()) { outCols.setColumnName(i, colSpec.name); try { outCols.setColumnType(i, Class.forName(colSpec.type)); } catch (ClassNotFoundException e) { Class type; if (isOutputColumnEnumeration(colSpec.schema)) { <START> type = EnumerationValue.class; <END> } else { type = JsonNode.class; } outCols.setColumnType(i, type); } i++; } lastOutputColumns = outCols; lastCreateInput = createInput; } finally { if(wasInit) { closeClient(); } } } return outCols; } catch(Exception e) { return new OutputColumns(String.class, "Unknown"); } }</code><technical_language>return enum values strings? client side kind of type-based mapping of columns EnumerationValue class is (because is non-concrete). do string based mapping of columns instead</technical_language>

Target:
public OutputColumns getOutputColumns() { OutputColumns outCols; try { CreateInput createInput = new CreateInput(); createInput.configuration = getConfiguration(getUsedInputColumns()); if(lastOutputColumns != null && createInput.equals(lastCreateInput)) { logger.debug("Reusing cached output columns, nothing changed"); outCols = lastOutputColumns; } else { logger.debug("Getting output columns from server"); boolean wasInit = false; if(client == null) { wasInit = true; initClient(); } try { org.datacleaner.restclient.OutputColumns columnsSpec = client.getOutputColumns(componentDisplayName, createInput); outCols = new OutputColumns(columnsSpec.getColumns().size(), Object.class); int i = 0; for (org.datacleaner.restclient.OutputColumns.OutputColumn colSpec : columnsSpec.getColumns()) { outCols.setColumnName(i, colSpec.name); try { outCols.setColumnType(i, Class.forName(colSpec.type)); } catch (ClassNotFoundException e) { Class type; if (isOutputColumnEnumeration(colSpec.schema)) { type = String.class; } else { type = JsonNode.class; } outCols.setColumnType(i, type); } i++; } lastOutputColumns = outCols; lastCreateInput = createInput; } finally { if(wasInit) { closeClient(); } } } return outCols; } catch(Exception e) { return new OutputColumns(String.class, "Unknown"); } }