auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public SolenoidOff(SolenoidSubsystem system) { super("Turning off " + system.getName(), system, SolenoidState.OFF); }

Target:
public SolenoidOff(SolenoidSubsystem system) { this("Turning off " + system.getName(), system); }
Source:
private void processNestedFields(TreeMap<String, Type> fieldsMap, List<ElasticsearchColumn> columns, List<String> arrays) { if (fieldsMap.size() == 0) { return; } Map.Entry<String, Type> first = fieldsMap.firstEntry(); String field = first.getKey(); Type type = first.getValue(); if (field.contains(".")) { String prefix = field.substring(0, field.lastIndexOf('.')); ImmutableList.Builder<RowType.Field> fieldsBuilder = ImmutableList.builder(); int size = field.split("\\.").length; Iterator<String> iterator = fieldsMap.navigableKeySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.split("\\.").length == size && name.startsWith(prefix)) { fieldsBuilder.add(new RowType.Field(Optional.of(name.substring(name.lastIndexOf('.') + 1)), fieldsMap.get(name))); iterator.remove(); continue; } break; } fieldsMap.put(prefix, RowType.from(fieldsBuilder.build())); } else { if (!columns.stream().anyMatch(column -> column.getName().equalsIgnoreCase(field))) { columns.add(new ElasticsearchColumn(field, type, field, type.getDisplayName(), arrays.contains(field), -1)); } fieldsMap.remove(field); } processNestedFields(fieldsMap, columns, arrays); }

Target:
private void processNestedFields(TreeMap<String, Type> fieldsMap, List<ElasticsearchColumn> columns, List<String> arrays) { if (fieldsMap.size() == 0) { return; } Entry<String, Type> first = fieldsMap.firstEntry(); String field = first.getKey(); Type type = first.getValue(); if (field.contains(".")) { String prefix = field.substring(0, field.lastIndexOf('.')); ImmutableList.Builder<RowType.Field> fieldsBuilder = ImmutableList.builder(); int size = field.split("\\.").length; Iterator<String> iterator = fieldsMap.navigableKeySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.split("\\.").length == size && name.startsWith(prefix)) { fieldsBuilder.add(new RowType.Field(Optional.of(name.substring(name.lastIndexOf('.') + 1)), fieldsMap.get(name))); iterator.remove(); continue; } break; } fieldsMap.put(prefix, RowType.from(fieldsBuilder.build())); } else { boolean newFlattenColumn = columns.stream().noneMatch(column -> column.getName().equalsIgnoreCase(field)); if (newFlattenColumn) { columns.add(new ElasticsearchColumn(field, type, field, type.getDisplayName(), arrays.contains(field), -1)); } fieldsMap.remove(field); } processNestedFields(fieldsMap, columns, arrays); }
Source:
private List<DiseaseOccurrence> getOccurrencesForTable(int diseaseGroupId) { return select(diseaseService.getDiseaseOccurrencesByDiseaseGroupIdAndStatuses( diseaseGroupId, DiseaseOccurrenceStatus.READY, DiseaseOccurrenceStatus.IN_REVIEW, DiseaseOccurrenceStatus.AWAITING_BATCHING), having(on(DiseaseOccurrence.class).getLocation().getPrecision(), not(equalTo(LocationPrecision.COUNTRY)))); }

Target:
private List<DiseaseOccurrence> getOccurrencesForTable(int diseaseGroupId) { List<DiseaseOccurrence> occurrences = diseaseService.getDiseaseOccurrencesByDiseaseGroupIdAndStatuses( diseaseGroupId, DiseaseOccurrenceStatus.READY, DiseaseOccurrenceStatus.IN_REVIEW, DiseaseOccurrenceStatus.AWAITING_BATCHING ); return filter( having(on(DiseaseOccurrence.class).getLocation().getPrecision(), not(equalTo(LocationPrecision.COUNTRY))), occurrences ); }
Source:
public void doInitializeRepository(CoreSession session) { if (Framework.getService(ConfigurationService.class).getBoolean("nuxeo.picture.migration.enabled", true)) { if (log.isInfoEnabled()) { log.info( "Starting picture migration handler (this may take some time depending on the number of documents)"); } boolean txStarted = false; if (!TransactionHelper.isTransactionActive()) { txStarted = true; } try { doMigration(session); } finally { if (txStarted) { TransactionHelper.commitOrRollbackTransaction(); } } } }

Target:
public void doInitializeRepository(CoreSession session) { if (Framework.getService(ConfigurationService.class).isBooleanTrue("nuxeo.picture.migration.enabled")) { if (log.isInfoEnabled()) { log.info( "Starting picture migration handler (this may take some time depending on the number of documents)"); } boolean txStarted = false; if (!TransactionHelper.isTransactionActive()) { txStarted = true; } try { doMigration(session); } finally { if (txStarted) { TransactionHelper.commitOrRollbackTransaction(); } } } }
Source:
private String getCreateTableQuery() { StringBuilder sb = new StringBuilder(); sb.append(this.getConfig().SQL_CREATE_TABLE_PREFIX); sb.append(this.getConfig().SQL_CREATE_TABLE); sb.append(" "); if(createIfNotExists){ sb.append(this.getConfig().SQL_CREATE_TABLE_IF_NOT_EXISTS); sb.append(" "); } sb.append(escape(table)); sb.append(" "); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_START); sb.append(buildColumns()); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_END); sb.append(this.getConfig().SQL_CREATE_TABLE_SUFFIX); return sb.toString(); }

Target:
private String getCreateTableQuery() { StringBuilder sb = new StringBuilder(); sb.append(this.getConfig().SQL_CREATE_TABLE_PREFIX); sb.append(this.getConfig().SQL_CREATE_TABLE); sb.append(" "); if(createIfNotExists){ sb.append(this.getConfig().SQL_CREATE_TABLE_IF_NOT_EXISTS); sb.append(" "); } sb.append(buildFullTableName(fullTableName, this.getConfig().SQL_FULL_NAME_SEGMENT_SEP, true)); sb.append(" "); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_START); sb.append(buildColumns()); sb.append(this.getConfig().SQL_CREATE_TABLE_FIELD_ENCLOSURE_END); sb.append(this.getConfig().SQL_CREATE_TABLE_SUFFIX); return sb.toString(); }
Source:
public FormValidation doCheckEnvironment(@QueryParameter(value = "credential") @RelativePath(value = "..") String credential, @QueryParameter(value = "credential") String credential2, @QueryParameter final String value, @AncestorInPath AbstractProject<?,?> project) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); if (isNullOrEmpty(value) || "Environments/".equals(value)) return ok("Fill in the target environment ID, eg Environments/MyEnv"); String creds = !isNullOrEmpty(credential) ? credential : credential2; Credential overridingCredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(creds, overridingCredential, project); DeployitNotifier.DeployitDescriptor deployitDescriptor = getDeployitDescriptor(); String resolvedValue = deployitDescriptor.expandValue(value, project); final String environment = DeployitServerFactory.getNameFromId(resolvedValue).trim(); List<String> candidates = deployitServer.search(DeployitDescriptorRegistry.UDM_ENVIRONMENT, environment); if(candidates.isEmpty()) { return warning("Environment '%s' does not exist, please ensure it exists during deployment", environment); } return ok(); }

Target:
public FormValidation doCheckEnvironment(@QueryParameter(value = "credential") @RelativePath(value = "..") String credential, @QueryParameter(value = "credential") String credential2, @QueryParameter final String value, @AncestorInPath AbstractProject<?,?> project) { project.checkPermission(Jenkins.ADMINISTER); if (isNullOrEmpty(value) || "Environments/".equals(value)) return ok("Fill in the target environment ID, eg Environments/MyEnv"); String creds = !isNullOrEmpty(credential) ? credential : credential2; Credential overridingCredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(creds, overridingCredential, project); DeployitNotifier.DeployitDescriptor deployitDescriptor = getDeployitDescriptor(); String resolvedValue = deployitDescriptor.expandValue(value, project); final String environment = DeployitServerFactory.getNameFromId(resolvedValue).trim(); List<String> candidates = deployitServer.search(DeployitDescriptorRegistry.UDM_ENVIRONMENT, environment); if(candidates.isEmpty()) { return warning("Environment '%s' does not exist, please ensure it exists during deployment", environment); } return ok(); }
Source:
public T getItem(int index) { int activeDataEnd = activeStart + activeKeyOrder.size() - 1; if (index < activeStart || index > activeDataEnd) { int dataSize = getItemCount(); if (dataSize == 0) { throw new IndexOutOfBoundsException(String .format("Requested index %d on empty data.", index)); } if (index < 0 || index >= dataSize) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", index, dataSize - 1)); } return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); } else { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } }

Target:
public T getItem(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index must be non-negative"); } int activeDataEnd = activeStart + activeKeyOrder.size() - 1; if (index >= activeStart && index <= activeDataEnd) { return getKeyMapper().get(activeKeyOrder.get(index - activeStart)); } else { final int itemCount = getItemCount(); if (isDefinedSize()) { if (itemCount == 0) { throw new IndexOutOfBoundsException(String .format("Requested index %d on empty data.", index)); } else if (index >= itemCount) { throw new IndexOutOfBoundsException(String.format( "Given index %d is outside of the accepted range '0 - %d'", index, itemCount - 1)); } } return (T) getDataProvider().fetch(buildQuery(index, 1)).findFirst() .orElse(null); } }
Source:
private String guessRealIconPath(String path) { File file = new File(path); if (!file.exists()) { try { File productFolder = defaults.getLocation().getParentFile(); String productPath = productFolder.getCanonicalPath(); String iconPath = file.getCanonicalPath(); if (iconPath.startsWith(productPath)) { String rawPath = iconPath.substring(productPath.length()); if (rawPath.startsWith("/") || rawPath.startsWith(File.separator)) { rawPath = rawPath.substring(1); } File parentDirectory = productFolder.getParentFile(); if (parentDirectory != null) { File guessedFile = new File(parentDirectory, rawPath); String absolutePath = guessedFile.getAbsolutePath(); logger.debug("raw path is " + rawPath + ", guessed path is " + absolutePath); if (guessedFile.exists()) { return absolutePath; } } } logger.warn("Icon path " + path + " does not exits and can't be determined by tycho, make sure that either the icon path is relative to the product file, or denoted a folder in the parent path of the product! (current product path is " + productPath + ")"); } catch (IOException e) { logger.warn("can't guess icon path because of I/O problem", e); } } return path; }

Target:
private String guessRealIconPath(String path) { File file = new File(path); if (!file.exists()) { try { File productFolder = defaults.getLocation().getParentFile(); String productPath = productFolder.getCanonicalPath(); String iconPath = file.getCanonicalPath(); if (iconPath.startsWith(productPath)) { String rawPath = iconPath.substring(productPath.length()); if (rawPath.startsWith("/") || rawPath.startsWith(File.separator)) { rawPath = rawPath.substring(1); } File parentDirectory = productFolder.getParentFile(); if (parentDirectory != null) { File guessedFile = new File(parentDirectory, rawPath); String absolutePath = guessedFile.getAbsolutePath(); logger.debug("raw path is " + rawPath + ", guessed path is " + absolutePath); if (guessedFile.exists()) { return absolutePath; } } } logger.warn("Icon path " + path + " does not exist and can't be determined by tycho, make sure that either the icon path is relative to the product file, or denotes a folder in the parent path of the product! (current product path is " + productPath + ")"); } catch (IOException e) { logger.warn("can't guess icon path because of I/O problem", e); } } return path; }
Source:
private void appendClientIpToCallerContext() { final CallerContext ctx = CallerContext.getCurrent(); String origContext = ctx == null ? null : ctx.getContext(); byte[] origSignature = ctx == null ? null : ctx.getSignature(); CallerContext.setCurrent( new CallerContext.Builder(origContext, clientConfiguration) .append(CLIENT_IP_STR, Server.getRemoteAddress()) .setSignature(origSignature).build()); }

Target:
private void appendClientIpToCallerContext() { final CallerContext ctx = CallerContext.getCurrent(); String origContext = ctx == null ? null : ctx.getContext(); byte[] origSignature = ctx == null ? null : ctx.getSignature(); CallerContext.setCurrent( new CallerContext.Builder(origContext, contextFieldSeparator) .append(CLIENT_IP_STR, Server.getRemoteAddress()) .setSignature(origSignature).build()); }
Source:
public void setGeoLocation(String geoLocationString) { String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) return; this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); }

Target:
public void setGeoLocation(String geoLocationString) { if (geoLocationString == null) { return; } String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) { return; } this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); }
Source:
public void setIpAddress(String ip) { this.ip = ip; }

Target:
public void setIpAddress(String ip) { if (ip == null) { this.ip = null; } else { try { InetAddress inet = InetAddress.getByName(ip); this.ip = (inet != null ? inet.getHostAddress() : null); } catch (IOException e) { log.error("Error getting InetAddress from given ip " + ip, e); throw new IllegalArgumentException("Error getting InetAddress from given ip " + ip, e); } } }
Source:
private SearchCursor searchOneLevel(Dn parent) throws NoSuchNodeException, MissingParentException { try { if (!connection.exists(parent.getParent())) { throw new MissingParentException(lastMatch(parent)); } else if (!connection.exists(parent)) { throw new NoSuchNodeException(parent); } } catch (LdapException e) { throw new RuntimeException(e); } SearchRequest searchRequest = new SearchRequestImpl(); searchRequest.setBase(parent); searchRequest.setScope(SearchScope.ONELEVEL); try { searchRequest.setFilter("(objectclass=*)"); return connection.search(searchRequest); } catch (LdapException e) { throw new RuntimeException(e); } }

Target:
private SearchCursor searchOneLevel(Dn parent) throws NoSuchNodeException, MissingParentException { try { if (!connection.exists(parent.getParent())) { throw new MissingParentException(lastMatch(parent)); } else if (!connection.exists(parent)) { throw new NoSuchNodeException(parent); } } catch (LdapException e) { throw new LdapDaoException(e); } SearchRequest searchRequest = new SearchRequestImpl(); searchRequest.setBase(parent); searchRequest.setScope(SearchScope.ONELEVEL); try { searchRequest.setFilter("(objectclass=*)"); return connection.search(searchRequest); } catch (LdapException e) { throw new LdapDaoException(e); } }
Source:
String render(String iconName, IconSet iconSet) throws IconException; String renderHTML(String iconName, IconSet iconSet) throws IconException; default String renderIcon(String iconName, IconSet iconSet, String renderer) throws IconException { throw new UnsupportedOperationException(); }

Target:
String render(String iconName, IconSet iconSet) throws IconException; default String render(String iconName, IconSet iconSet, String renderer) throws IconException { throw new UnsupportedOperationException(); }
Source:
public static String encode(String URL, String force, boolean ascii, String extraSafeChars) { StringBuilder enc = new StringBuilder(URL.length()); for (int i = 0; i < URL.length(); ++i) { char c = URL.charAt(i); if (((safeURLCharacters.indexOf(c) >= 0) || ((!ascii) && c >= 0200 && Character.isDefined(c) && !Character.isISOControl(c)) || extraSafeChars.indexOf(c) >= 0) && (force == null || force.indexOf(c) < 0)) { enc.append(c); } else { try { for (byte b: ( String.valueOf(c)).getBytes("UTF-8")) { int x = b & 0xFF; if (x < 16) enc.append("%0"); else enc.append('%'); enc.append(Integer.toHexString(x)); } } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } } } return enc.toString(); }

Target:
public static String encode(String URL, String force, boolean ascii, String extraSafeChars) { StringBuilder enc = new StringBuilder(URL.length()); for (int i = 0; i < URL.length(); ++i) { char c = URL.charAt(i); if (((safeURLCharacters.indexOf(c) >= 0) || ((!ascii) && c >= 0200 && Character.isDefined(c) && !Character.isISOControl(c)) || extraSafeChars.indexOf(c) >= 0) && (force == null || force.indexOf(c) < 0)) { enc.append(c); } else { try { for (byte b: String.valueOf(c).getBytes("UTF-8")) { int x = b & 0xFF; if (x < 16) enc.append("%0"); else enc.append('%'); enc.append(Integer.toHexString(x)); } } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } } } return enc.toString(); }
Source:
private String extractErrorMessageFromResponse(HttpResponse response) { String contentType = response.getEntity().getContentType().getValue(); String responseBody = null; if(contentType.contains("application/json")) { Gson gson = GsonResponseParser.getDefaultGsonParser(false); try { responseBody = EntityUtils.toString(response.getEntity()); LOG.error("Body of error response from Canvas: " + responseBody); CanvasErrorResponse errorResponse = gson.fromJson(responseBody, CanvasErrorResponse.class); List<ErrorMessage> errors = errorResponse.getErrors(); if(errors != null) { return errors.stream().map(e -> e.getMessage()).collect(Collectors.joining(", ")); } } catch (Exception e) { if(StringUtils.isNotBlank(responseBody)) { return responseBody; } } } return responseBody; }

Target:
private String extractErrorMessageFromResponse(HttpResponse response) { String contentType = response.getEntity().getContentType().getValue(); String responseBody = ""; if(contentType.contains("application/json")) { Gson gson = GsonResponseParser.getDefaultGsonParser(false); try { responseBody = EntityUtils.toString(response.getEntity()); LOG.error("Body of error response from Canvas: " + responseBody); CanvasErrorResponse errorResponse = gson.fromJson(responseBody, CanvasErrorResponse.class); List<ErrorMessage> errors = errorResponse.getErrors(); if(errors != null) { return errors.stream().map(e -> e.getMessage()).collect(Collectors.joining(", ")); } } catch (Exception e) { if(StringUtils.isNotBlank(responseBody)) { return responseBody; } } } return responseBody; }
Source:
public void saveCredentialsInSmartLock(@NonNull final String username, @NonNull final String password, @NonNull final String displayName, @Nullable final Uri profilePicture) { if (password.isEmpty() || username.isEmpty()) { return; } Activity activity = getActivityAndCheckAvailability(); if (activity == null || mCredentialsClient == null || !mCredentialsClient.isConnected()) { return; } Credential credential = new Credential.Builder(username).setPassword(password) .setName(displayName).setProfilePictureUri(profilePicture).build(); Auth.CredentialsApi.save(mCredentialsClient, credential).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { if (!status.isSuccess() && status.hasResolution()) { try { Activity activity = getActivityAndCheckAvailability(); if (activity == null) { return; } status.startResolutionForResult(activity, SignInActivity.SMART_LOCK_SAVE); } catch (IntentSender.SendIntentException e) { } } } }); }

Target:
public void saveCredentialsInSmartLock(@NonNull final String username, @NonNull final String password, @NonNull final String displayName, @Nullable final Uri profilePicture) { if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) { AppLog.i(T.MAIN, String.format( "Cannot save Smart Lock credentials, username (%s) or password (%s) is empty", username, password)); return; } Activity activity = getActivityAndCheckAvailability(); if (activity == null || mCredentialsClient == null || !mCredentialsClient.isConnected()) { return; } Credential credential = new Credential.Builder(username).setPassword(password) .setName(displayName).setProfilePictureUri(profilePicture).build(); Auth.CredentialsApi.save(mCredentialsClient, credential).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { if (!status.isSuccess() && status.hasResolution()) { try { Activity activity = getActivityAndCheckAvailability(); if (activity == null) { return; } status.startResolutionForResult(activity, SignInActivity.SMART_LOCK_SAVE); } catch (IntentSender.SendIntentException e) { } } } }); }
Source:
public void injectAccountAndContainerForPutRequest(RestRequest restRequest, RestRequestMetricsGroup metricsGroup) throws RestServiceException { accountAndContainerSanityCheckForNamedBlob(restRequest); if (restRequest.getUri() != null) { frontendMetrics.putWithAccountAndContainerHeaderRate.mark(); injectAccountAndContainerUsingAccountAndContainerUri(restRequest, metricsGroup); } else if (frontendConfig.allowServiceIdBasedPutRequest) { ensureRequiredHeadersOrThrow(restRequest, requiredAmbryHeadersForPutWithServiceId); frontendMetrics.putWithServiceIdForAccountNameRate.mark(); String serviceId = getHeader(restRequest.getArgs(), Headers.SERVICE_ID, true); boolean isPrivate = isPrivate(restRequest.getArgs()); injectAccountAndContainerUsingServiceId(restRequest, serviceId, isPrivate, metricsGroup); } else { throw new RestServiceException( "Missing either " + Headers.TARGET_ACCOUNT_NAME + " or " + Headers.TARGET_CONTAINER_NAME + " header", RestServiceErrorCode.BadRequest); } }

Target:
public void injectAccountAndContainerForPutRequest(RestRequest restRequest, RestRequestMetricsGroup metricsGroup) throws RestServiceException { accountAndContainerSanityCheck(restRequest); if (restRequest.getUri() != null) { frontendMetrics.putWithAccountAndContainerHeaderRate.mark(); injectAccountAndContainerUsingAccountAndContainerUri(restRequest, metricsGroup); } else { throw new RestServiceException( "Missing either " + Headers.TARGET_ACCOUNT_NAME + " or " + Headers.TARGET_CONTAINER_NAME + " header", RestServiceErrorCode.BadRequest); } }
Source:
public static WsClient newWsClient() { return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() .url(orchestrator.getServer().getUrl()) .build()); }

Target:
private static WsClient newWsClient() { return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() .url(orchestrator.getServer().getUrl()) .build()); }
Source:
public List<GBTData> parse() { final List<GBTData> retList = new LinkedList<>(); for (final Pair<LongWritable, Text> keyValue : dataSet) { final String text = keyValue.getSecond().toString().trim(); if (text.startsWith("#") || text.length() == 0) { continue; } final String[] split = text.split("\\s+"); final Vector feature = vectorFactory.createDenseZeros(numFeatures); final int identity = Integer.parseInt(split[0]); for (int index = 1; index <= numFeatures; index++) { feature.set(index - 1, Double.parseDouble(split[index])); } final double yValue = Double.parseDouble(split[numFeatures + 1]); retList.add(new GBTData(identity, feature, yValue)); } return retList; }

Target:
public List<GBTData> parse() { final List<GBTData> retList = new LinkedList<>(); for (final Pair<LongWritable, Text> keyValue : dataSet) { final String text = keyValue.getSecond().toString().trim(); if (text.startsWith("#") || text.length() == 0) { continue; } final String[] split = text.split("\\s+"); assert (split.length == numFeatures + 1); final Vector feature = vectorFactory.createDenseZeros(numFeatures); for (int index = 0; index < numFeatures; index++) { feature.set(index, Double.parseDouble(split[index])); } final double yValue = Double.parseDouble(split[numFeatures]); retList.add(new GBTData(feature, yValue)); } return retList; }
Source:
private void rotate() { long currentTimeMillis = System.currentTimeMillis(); long lastRotateTimestampMillis = this.lastRotateTimestampMillis.get(); CKMSQuantiles currentBucket = buckets.peek(); while (currentTimeMillis - lastRotateTimestampMillis > durationBetweenRotatesMillis) { CKMSQuantiles bucket = new CKMSQuantiles(quantiles); if (this.lastRotateTimestampMillis.compareAndSet( lastRotateTimestampMillis, lastRotateTimestampMillis + durationBetweenRotatesMillis) && buckets.remove(currentBucket)) { buckets.add(bucket); } lastRotateTimestampMillis = this.lastRotateTimestampMillis.get(); currentBucket = buckets.peek(); } }

Target:
private void rotate() { long currentTime = System.nanoTime(); long lastRotate = lastRotateTimestampNanos.get(); while (currentTime - lastRotate > durationBetweenRotatesNanos) { if (lastRotateTimestampNanos.compareAndSet(lastRotate, lastRotate + durationBetweenRotatesNanos)) { CKMSQuantiles[] oldBuckets = buckets.get(); int ageBuckets = oldBuckets.length; CKMSQuantiles[] newBuckets = new CKMSQuantiles[ageBuckets]; newBuckets[ageBuckets - 1] = new CKMSQuantiles(quantiles); System.arraycopy(oldBuckets, 1, newBuckets, 0, ageBuckets - 1); while (!buckets.compareAndSet(oldBuckets, newBuckets)) { oldBuckets = buckets.get(); System.arraycopy(oldBuckets, 1, newBuckets, 0, ageBuckets - 1); } } lastRotate = lastRotateTimestampNanos.get(); } }
Source:
public void testWaitForCompletionSuccess() { TestAnalysis module = setUpAnalysis(); IStatus status = module.schedule(); assertEquals(IStatus.ERROR, status.getSeverity()); try { module.setTrace(TmfTestTrace.A_TEST_10K.getTrace()); } catch (TmfAnalysisException e) { fail(e.getMessage()); } module.setParameter(TestAnalysis.PARAM_TEST, 1); status = module.schedule(); assertEquals(Status.OK_STATUS, status); boolean completed = module.waitForCompletion(); assertTrue(completed); assertEquals(1, module.getAnalysisOutput()); }

Target:
public void testWaitForCompletionSuccess() { TestAnalysis module = setUpAnalysis(); IStatus status = module.schedule(); assertEquals(IStatus.ERROR, status.getSeverity()); try { module.setTrace(TmfTestTrace.A_TEST_10K.getTrace()); } catch (TmfAnalysisException e) { fail(e.getMessage()); } module.setParameter(TestAnalysis.PARAM_TEST, 1); status = module.schedule(); assertEquals(Status.OK_STATUS, status); boolean completed = module.waitForCompletion(); assertTrue(completed); assertEquals(1, module.getAnalysisOutput()); module.dispose(); }
Source:
public void cleanup() throws DBException { try { mclient.drain(); mclient.close(); } catch (NoConnectionsException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } mclient = null; }

Target:
public void cleanup() throws DBException { if (mclient != null && mclient.getConnectedHostList().size() > 0) { try { mclient.drain(); mclient.close(); } catch (NoConnectionsException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } mclient = null; } }
Source:
private void dumpFoundVertxApplications(List<String> cmd) throws IOException, InterruptedException { boolean none = true; final Process process = new ProcessBuilder(cmd).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { final Matcher matcher = PS.matcher(line); if (matcher.find()) { out.println(matcher.group(1)); none = false; } } process.waitFor(); if (none) { out.println("No vert.x application found."); } }

Target:
private void dumpFoundVertxApplications(List<String> cmd) throws IOException, InterruptedException { boolean none = true; final Process process = new ProcessBuilder(cmd).start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { final Matcher matcher = PS.matcher(line); if (matcher.find()) { out.println(matcher.group(1)); none = false; } } process.waitFor(); reader.close(); if (none) { out.println("No vert.x application found."); } }
Source:
public void toFlowableError1() { TestSubscriber<Integer> ts = Observable.range(1, 5) .toFlowable(BackpressureStrategy.ERROR) .test(1) .assertError(MissingBackpressureException.class); }

Target:
public void toFlowableError1() { TestSubscriber<Integer> ts = Observable.range(1, 5) .toFlowable(BackpressureStrategy.ERROR) .test(1) .assertFailure(MissingBackpressureException.class, 1); }
Source:
public static void afterClass() throws Exception { if (cacheManager != null && cacheManager.getStatus() == Status.AVAILABLE) { System.out.println("====> Asking Ehcache to stop sending stats"); if (tmsAgentService != null) { Context ehcacheClient = readTopology().getClient(ehcacheClientIdentifier).get().getContext().with("cacheManagerName", "my-super-cache-manager"); tmsAgentService.stopStatisticCollector(ehcacheClient).waitForReturn(); } System.out.println("====> Closing Ehcache"); cacheManager.close(); } if (tmsAgentService != null) { System.out.println("====> Asking server to stop sending stats"); Context context = readTopology().getSingleStripe().getActiveServerEntity(tmsServerEntityIdentifier).get().getContext(); tmsAgentService.stopStatisticCollector(context); System.out.println("====> Closing management connection"); managementConnection.close(); } }

Target:
public static void afterClass() throws Exception { if (cacheManager != null && cacheManager.getStatus() == Status.AVAILABLE) { if (tmsAgentService != null) { Context ehcacheClient = readTopology().getClient(ehcacheClientIdentifier).get().getContext().with("cacheManagerName", "my-super-cache-manager"); tmsAgentService.stopStatisticCollector(ehcacheClient).waitForReturn(); } cacheManager.close(); } if (tmsAgentService != null) { Context context = readTopology().getSingleStripe().getActiveServerEntity(tmsServerEntityIdentifier).get().getContext(); tmsAgentService.stopStatisticCollector(context); managementConnection.close(); } }
Source:
private boolean isUncheckedExceptionCatchBlock(BytecodeCFG.Block b) { String exceptionTypeName = b.getExceptionType(); if (exceptionTypeName == null) { return false; } Type exceptionType = semanticModel.getClassType(exceptionTypeName); if (exceptionType == null) { return false; } return exceptionType.isSubtypeOf("java.lang.RuntimeException") || exceptionType.isSubtypeOf("java.lang.Error") || exceptionType.is("java.lang.Exception") || exceptionType.is("java.lang.Throwable"); }

Target:
private boolean isUncheckedExceptionCatchBlock(BytecodeCFG.Block b) { String exceptionTypeName = b.getExceptionType(); if (exceptionTypeName == null) { return false; } Type exceptionType = semanticModel.getClassType(exceptionTypeName); return ExceptionUtils.isUncheckedException(exceptionType); }
Source:
public Map<String, Object> asMap() { Map<String, Object> map = super.asMap(); doIfNotNull(spot, sp -> { putIfValueNotNull(map, AwsInstanceTemplate.EC2_SPOT_PERCENTAGE, sp.getPercentage()); putIfValueNotNull(map, AwsInstanceTemplate.EC2_SPOT_MAX_PRICE, sp.getMaxPrice()); }); if (encryption != null) { putIfValueNotNull(map, InstanceTemplate.VOLUME_ENCRYPTION_KEY_TYPE, encryption.getType()); putIfValueNotNull(map, AwsInstanceTemplate.EBS_ENCRYPTION_ENABLED, encryption.getType() != EncryptionType.NONE); } if (placementGroup != null) { putIfValueNotNull(map, AwsInstanceTemplate.PLACEMENT_GROUP_STRATEGY, placementGroup.getStrategy().name()); } return map; }

Target:
public Map<String, Object> asMap() { Map<String, Object> map = super.asMap(); doIfNotNull(spot, sp -> { putIfValueNotNull(map, AwsInstanceTemplate.EC2_SPOT_PERCENTAGE, sp.getPercentage()); putIfValueNotNull(map, AwsInstanceTemplate.EC2_SPOT_MAX_PRICE, sp.getMaxPrice()); }); if (encryption != null) { putIfValueNotNull(map, InstanceTemplate.VOLUME_ENCRYPTION_KEY_TYPE, encryption.getType()); putIfValueNotNull(map, AwsInstanceTemplate.EBS_ENCRYPTION_ENABLED, encryption.getType() != EncryptionType.NONE); } putIfValueNotNull(map, AwsInstanceTemplate.PLACEMENT_GROUP_STRATEGY, Optional.ofNullable(placementGroup) .map(AwsPlacementGroupV4Parameters::getStrategy) .orElse(AwsPlacementGroupStrategy.NONE).name()); return map; }
Source:
public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); replicationMetrics.trackLiveThreadsCount(replicaThreadPools, dataNodeId.getDatacenterName()); replicationMetrics.trackReplicationDisabledPartitions(replicaThreadPools); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } this.scheduler.scheduleAtFixedRate(persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }

Target:
public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); replicationMetrics.trackLiveThreadsCount(replicaThreadPools, dataNodeId.getDatacenterName()); replicationMetrics.trackReplicationDisabledPartitions(replicaThreadPools); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } this.scheduler.scheduleAtFixedRate(persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication", e); } }
Source:
private static void consumeStreamSilently(InputStream is) { char[] tmpBuff = new char[8 * 1024]; InputStreamReader isr = new InputStreamReader(is); try { try { while (isr.read(tmpBuff) > -1) { } } finally { isr.close(); } } catch (IOException e) { e.printStackTrace(); } }

Target:
private static void consumeStreamSilently(InputStream is) { char[] tmpBuff = new char[8 * 1024]; InputStreamReader isr = new InputStreamReader(is); try { try { while (isr.read(tmpBuff) > -1) { } } finally { isr.close(); } } catch (IOException e) { java.util.logging.Logger.getAnonymousLogger().log(Level.WARNING, "Error ocured during reading InputStream.", e); } }
Source:
private void resolveModuleConfigReferences(List<? extends Module> modules, Map<String, ?> ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (Exception e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations:%s", statusDescriptionStr)); } } }

Target:
private void resolveModuleConfigReferences(List<? extends Module> modules, Map<String, ?> ruleConfiguration) { if (modules != null) { StringBuffer statusDescription = new StringBuffer(); for (Module module : modules) { try { ReferenceResolver.updateConfiguration(module.getConfiguration(), ruleConfiguration, logger); } catch (IllegalArgumentException e) { statusDescription.append(" in module[" + module.getId() + "]: " + e.getLocalizedMessage() + ";"); } } String statusDescriptionStr = statusDescription.toString(); if (!statusDescriptionStr.isEmpty()) { throw new IllegalArgumentException(String.format("Incorrect configurations: %s", statusDescriptionStr)); } } }
Source:
public UserStoragePreference getUserStoragePreference(String userId, String gatewayId, String storageId) throws AppCatalogException { UserStoragePreferenceRepository userStoragePreferenceRepository = new UserStoragePreferenceRepository(); Map<String, Object> queryParameters = new HashMap<>(); queryParameters.put(DBConstants.UserStoragePreference.USER_ID, userId); queryParameters.put(DBConstants.UserStoragePreference.GATEWAY_ID, gatewayId); queryParameters.put(DBConstants.UserStoragePreference.STORAGE_RESOURCE_ID, storageId); List<UserStoragePreference> userStoragePreferenceList = userStoragePreferenceRepository.select(QueryConstants.GET_USER_STORAGE_PREFERENCE, -1, 0, queryParameters); if(!userStoragePreferenceList.isEmpty() && userStoragePreferenceList != null) { logger.debug("Return the record (there is only one record)"); return userStoragePreferenceList.get(0); } return null; }

Target:
public UserStoragePreference getUserStoragePreference(String userId, String gatewayId, String storageId) throws AppCatalogException { UserStoragePreferenceRepository userStoragePreferenceRepository = new UserStoragePreferenceRepository(); UserStoragePreferencePK userStoragePreferencePK = new UserStoragePreferencePK(); userStoragePreferencePK.setUserId(userId); userStoragePreferencePK.setGatewayId(gatewayId); userStoragePreferencePK.setStorageResourceId(storageId); UserStoragePreference userStoragePreference = userStoragePreferenceRepository.get(userStoragePreferencePK); return userStoragePreference; }
Source:
public Response getRatedUser( @PathParam("uuid") String uuid){ CommentsManager commentsManager = APIUtil.getCommentsManager(); int ratedUsers=0; try { ratedUsers= commentsManager.getRatedUser(uuid); } catch (SQLException e) { log.error("SQL Exception occurs", e); } return Response.status(Response.Status.OK).entity(ratedUsers).build(); }

Target:
public Response getRatedUser( @PathParam("uuid") String uuid) { CommentsManager commentsManager = APIUtil.getCommentsManager(); int ratedUsers = 0; try { ratedUsers = commentsManager.getRatedUser(uuid); } catch (CommentManagementException e) { log.error("Comment Management Exception occurs", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("Internal server error occurs").build(); } catch (ApplicationManagementException e) { log.error("Application Management Exception occurs", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity("Application with UUID" + uuid + " Internal server error occurs").build(); } return Response.status(Response.Status.OK).entity(ratedUsers).build(); }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartEscalationEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartEscalationEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, INTERRUPTING, ""); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartEscalationEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartEscalationEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertEscalationEventExecutionSet(emptyTop.getExecutionSet(), EMPTY_VALUE, INTERRUPTING, EMPTY_VALUE); assertDataIOSet(emptyTop.getDataIOSet(), EMPTY_VALUE); }
Source:
public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) { throw new RuntimeException( "SystemInfoEditorProvider should let the default text editor provider handle this file type, and this method should not be called."); }

Target:
public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) { throw new UnsupportedOperationException( "SystemInfoEditorProvider should let the default text editor provider handle this file type, and this method should not be called."); }
Source:
public String getSQL() { String left = getContextSQL(nodes[LEFT]); String right = getContextSQL(nodes[RIGHT]); StringBuffer sb = new StringBuffer(); sb.append(left).append(' ').append(Tokens.T_STARTS).append(Tokens.T_WITH).append(' '); sb.append(right); return sb.toString(); }

Target:
public String getSQL() { String left = getContextSQL(nodes[LEFT]); String right = getContextSQL(nodes[RIGHT]); StringBuffer sb = new StringBuffer(); sb.append(left).append(' ').append(Tokens.T_STARTS).append(' ').append(Tokens.T_WITH).append(' '); sb.append(right); return sb.toString(); }
Source:
private Set<String> listProjectsFor(final String user, final String token) throws Exception { Set<String> names = new HashSet<>(); try { ConfigBuilder builder = new ConfigBuilder(false).withOauthToken(token) .withMasterUrl(openshiftMasterUrl) .withTrustCerts(openshiftMasterUrlTrustedCert); if (openshiftCaPath != null) { builder.withCaCertFile(openshiftCaPath); } try (OpenShiftClient client = clientFactory.create(builder.build())) { List<Project> projects = client.projects().list().getItems(); for (Project project : projects) { if (!isBlacklistProject(project.getMetadata().getName())) { names.add(project.getMetadata().getName() + "." + project.getMetadata().getUid()); } } } } catch (KubernetesClientException e) { LOGGER.error("Error retrieving project list for '{}'", e, user); throw new ElasticsearchSecurityException(e.getMessage()); } catch (Exception e) { LOGGER.error("Error retrieving project list for '{}'", e, user); } return names; }

Target:
private Set<Project> listProjectsFor(final String user, final String token) throws Exception { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); } return AccessController.doPrivileged(new PrivilegedAction<Set<Project>>(){ @Override public Set<Project> run() { Set<Project> projects = apiService.projectNames(token); for (Iterator<Project> it = projects.iterator(); it.hasNext();) { if (isBlacklistProject(it.next().getName())) { it.remove(); } } return projects; } }); }
Source:
public void deleteFile(File dFile) { if ((dFile.isDirectory() && dFile.list().length == 0) || dFile.isFile()) { dFile.delete(); } else { String files[] = dFile.list(); for (String file : files) { File fileDelete = new File(dFile, file); deleteFile(fileDelete); } } if (dFile.isDirectory() && dFile.list().length == 0) { dFile.delete(); } }

Target:
public void deleteFile(File dFile) { if ((dFile.isDirectory() && dFile.list().length == 0) || dFile.isFile()) { dFile.delete(); } else { String files[] = dFile.list(); for (String file : files) { File fileDelete = new File(dFile, file); deleteFile(fileDelete); } } dFile.delete(); XmlAnalysisModuleSource.notifyModuleChange(); }
Source:
protected boolean onSubmit(String enteredPasscode) { boolean showBiometricEnrollment = !passcodeManager.getBiometricEnabled() && !passcodeManager.getBiometricEnrollmentShown() && passcodeManager.getBiometricAllowed() && canShowBiometric(); switch (getMode()) { case Create: firstPasscode = enteredPasscode; setMode(PasscodeMode.CreateConfirm); return true; case CreateConfirm: if (enteredPasscode.equals(firstPasscode)) { passcodeManager.store(this, enteredPasscode); if (showBiometricEnrollment) { setMode(PasscodeMode.EnableBiometric); } else { if (!passcodeManager.getPasscodeLengthKnown()) { passcodeManager.setPasscodeLength(this, enteredPasscode.length()); } passcodeManager.unlock(); done(); } } else { instr.setText(getString(R.string.sf__passcodes_dont_match)); } return true; case Check: if (passcodeManager.check(this, enteredPasscode)) { if (showBiometricEnrollment) { setMode(PasscodeMode.EnableBiometric); } else { passcodeManager.unlock(); done(); } } else { logoutButton.setVisibility(View.VISIBLE); int attempts = passcodeManager.addFailedPasscodeAttempt(); passcodeField.setText(""); int maxAttempts = getMaxPasscodeAttempts(); if (attempts < maxAttempts - 1) { instr.setText(getString(R.string.sf__passcode_try_again, (maxAttempts - attempts))); } else if (attempts < maxAttempts) { instr.setText(getString(R.string.sf__passcode_final)); } else { signoutAllUsers(); } } return true; case Change: firstPasscode = enteredPasscode; setMode(PasscodeMode.CreateConfirm); return true; } return false; }

Target:
protected boolean onSubmit(String enteredPasscode) { boolean showBiometricEnrollment = !passcodeManager.biometricEnabled() && !passcodeManager.biometricEnrollmentShown() && passcodeManager.biometricAllowed() && canShowBiometric(); switch (getMode()) { case Create: firstPasscode = enteredPasscode; setMode(PasscodeMode.CreateConfirm); return true; case CreateConfirm: if (enteredPasscode.equals(firstPasscode)) { passcodeManager.store(this, enteredPasscode); if (showBiometricEnrollment) { setMode(PasscodeMode.EnableBiometric); } else { if (!passcodeManager.getPasscodeLengthKnown()) { passcodeManager.setPasscodeLength(this, enteredPasscode.length()); } passcodeManager.unlock(); done(); } } else { instr.setText(getString(R.string.sf__passcodes_dont_match)); } return true; case Check: if (passcodeManager.check(this, enteredPasscode)) { if (showBiometricEnrollment) { setMode(PasscodeMode.EnableBiometric); } else { passcodeManager.unlock(); done(); } } else { logoutButton.setVisibility(View.VISIBLE); int attempts = passcodeManager.addFailedPasscodeAttempt(); passcodeField.setText(""); int maxAttempts = getMaxPasscodeAttempts(); if (attempts < maxAttempts - 1) { instr.setText(getString(R.string.sf__passcode_try_again, (maxAttempts - attempts))); } else if (attempts < maxAttempts) { instr.setText(getString(R.string.sf__passcode_final)); } else { signoutAllUsers(); } } return true; case Change: firstPasscode = enteredPasscode; setMode(PasscodeMode.CreateConfirm); return true; } return false; }