auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Object execute(final RebaseOperation rebase) throws ExecutionException { String jobname = getJobName(rebase); final Repository repository = rebase.getRepository(); final RebaseCommand.Operation operation = rebase.getOperation(); JobUtil.scheduleUserJob(rebase, jobname, JobFamilies.REBASE, new JobChangeAdapter() { @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (operation == Operation.BEGIN && result.getSeverity() == IStatus.ERROR) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { try { new RebaseOperation(repository, Operation.ABORT).execute(null); } catch (CoreException e) { Activator .error(UIText.AbstractRebaseCommandHandler_CleanUpFailed, e); } } } if (result.getSeverity() == IStatus.CANCEL) Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(); MessageDialog.openInformation(shell, dialogTitle, dialogMessage); } }); else if (result.isOK()) RebaseResultDialog.show(rebase.getResult(), repository); } }); return null; }

Target:
protected Object execute(final RebaseOperation rebase) throws ExecutionException { final Repository repository = rebase.getRepository(); final RebaseCommand.Operation operation = rebase.getOperation(); JobUtil.scheduleUserJob(rebase, jobname, JobFamilies.REBASE, new JobChangeAdapter() { @Override public void aboutToRun(IJobChangeEvent event) { if (operation == Operation.BEGIN && !repository.getRepositoryState().equals( RepositoryState.SAFE)) { throw new IllegalStateException( "Can't start rebase if repository state isn't SAFE"); } super.aboutToRun(event); } @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (operation == Operation.BEGIN && result.getSeverity() == IStatus.ERROR) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { RuntimeException e = new RuntimeException( result.getException()); try { new RebaseOperation(repository, Operation.ABORT).execute(null); throw e; } catch (CoreException e1) { IStatus multiStatus = createMultiStatus(result.getException(), e1); CoreException multiStatusCoreException = new CoreException( multiStatus); throw new RuntimeException( multiStatusCoreException); } } } if (result.getSeverity() == IStatus.CANCEL) Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(); MessageDialog.openInformation(shell, dialogTitle, dialogMessage); } }); else if (result.isOK()) RebaseResultDialog.show(rebase.getResult(), repository); } }); return null; }
Source:
public String getDescriptionUsage() { StringBuilder sb = new StringBuilder(); sb.append("<form>Use a template to publish a document or diff the document against a different version.<br/>"); sb.append("Select Parameters<br/>"); sb.append("<li>Select Update Paragraph Numbers if authorized to update them</li>"); sb.append("<li>Choose whether or not you want the UUIDs published</li>"); sb.append("<li>Select the Document Link format(s)</li>"); sb.append("<li>Choose an artifact type to exclude</li>"); sb.append("<li>Select Master or Master/Slave (for SRS) template. Only use non-recursive templates</li>"); sb.append("<li>Drag &amp; Drop the IS Artifacts into the box</li>"); sb.append("<li>Decide to Publish as Diff and select WAS branch as desired</li>"); sb.append("<br/>Click the play button at the top right or in the Execute section.</form>"); return sb.toString(); }

Target:
public String getDescriptionUsage() { StringBuilder sb = new StringBuilder(); sb.append("<form>Use a template to publish a document or diff the document against a different version.<br/>"); sb.append("Select Parameters<br/>"); sb.append("<li>Select Update Paragraph Numbers if authorized to update them</li>"); sb.append("<li>Choose whether or not you want the UUIDs published</li>"); sb.append("<li>Select the Document Link format(s)</li>"); sb.append("<li>Choose artifact type(s) to exclude</li>"); sb.append("<li>Select Master or Master/Slave (for SRS) template. Only use non-recursive templates</li>"); sb.append("<li>Drag &amp; Drop the IS Artifacts into the box</li>"); sb.append("<li>Decide to Publish as Diff and select WAS branch as desired</li>"); sb.append("<br/>Click the play button at the top right or in the Execute section.</form>"); return sb.toString(); }
Source:
public Map<String, String> getExtraEnvParams() { String envParams = config.get(CONFIG_EXTRA_ENV_PARAMS); if (envParams == null) { logger.info("getExtraEnvParams: No extra env params"); return null; } Map<String, String> extraEnvParamsMap = new HashMap<String, String>(); String[] pairs = envParams.split(","); logger.info("getExtraEnvParams: Extra cass params. From config :" +envParams); if ( pairs.length > 0) { for (int i = 0; i < pairs.length; i++) { String[] pair = pairs[i].split("="); if (pair.length > 1) { String priamKey = pair[0]; String cassKey = pair[1]; String cassVal = config.get(priamKey); logger.info("getExtraEnvParams: Start-up/ env params: Priamkey[" + priamKey + "], CassStartupKey[" + cassKey + "], Val[" + cassVal + "]"); if(!StringUtils.isBlank(cassKey) && !StringUtils.isBlank(cassVal)) { extraEnvParamsMap.put(cassKey, cassVal); } } } } return extraEnvParamsMap; }

Target:
public Map<String, String> getExtraEnvParams() { String envParams = config.get(CONFIG_EXTRA_ENV_PARAMS); if (envParams == null) { logger.info("getExtraEnvParams: No extra env params"); return null; } Map<String, String> extraEnvParamsMap = new HashMap<String, String>(); String[] pairs = envParams.split(","); logger.info("getExtraEnvParams: Extra cass params. From config :" +envParams); for (int i = 0; i < pairs.length; i++) { String[] pair = pairs[i].split("="); if (pair.length > 1) { String priamKey = pair[0]; String cassKey = pair[1]; String cassVal = config.get(priamKey); logger.info("getExtraEnvParams: Start-up/ env params: Priamkey[" + priamKey + "], CassStartupKey[" + cassKey + "], Val[" + cassVal + "]"); if(!StringUtils.isBlank(cassKey) && !StringUtils.isBlank(cassVal)) { extraEnvParamsMap.put(cassKey, cassVal); } } } return extraEnvParamsMap; }
Source:
protected List<T> peekInternal(String queue, Double min, Double max, int offset, int count) { List<T> jobInfos = Lists.newArrayList(); try (Handle handle = rdbi.open()) { Set<Tuple> tupleSet = handle.jedis().zrangeByScoreWithScores(queue, min, max, offset, count); for (Tuple tuple : tupleSet) { jobInfos.add(newJobInfo(tuple.getElement(), tuple.getScore())); } return jobInfos; } }

Target:
protected List<T> peekInternal(String queue, Double min, Double max, int offset, int count) { List<T> jobInfos = Lists.newArrayList(); try (Handle handle = rdbi.open()) { Set<Tuple> tupleSet = handle.jedis().zrangeByScoreWithScores(queue, min, max, offset, count); for (Tuple tuple : tupleSet) { jobInfos.add(createJobInfo(tuple.getElement(), tuple.getScore())); } return jobInfos; } }
Source:
public void computeNext(MapValue mapValue, Record record) { double lat1 = toRad(mapValue.getDouble(valueIndex)); double lon1 = toRad(mapValue.getDouble(valueIndex + 1)); double lat2 = toRad(this.latDegree.getDouble(record)); double lon2 = toRad(this.lonDegree.getDouble(record)); mapValue.putDouble(this.valueIndex, this.latDegree.getDouble(record)); mapValue.putDouble(this.valueIndex + 1, this.lonDegree.getDouble(record)); if (Double.isNaN(lat1) || Double.isNaN(lat2) || Double.isNaN(lon1) || Double.isNaN(lon2)) { return; } double halfLatDist = (lat2 - lat1) / 2; double halfLonDist = (lon2 - lon1) / 2; double a = sin(halfLatDist) * sin(halfLatDist) + cos(lat1) * cos(lat2) * sin(halfLonDist) * sin(halfLonDist); double c = 2 * atan2(sqrt(a), sqrt(1 - a)); double storedDistance = mapValue.getDouble(this.valueIndex + 2); double distance = Double.isNaN(storedDistance) ? 0 : storedDistance; distance += EARTH_RADIUS * c; mapValue.putDouble(this.valueIndex + 2, distance); }

Target:
public void computeNext(MapValue mapValue, Record record) { double lat1Degrees = getLastLatitude(mapValue); double lon1Degrees = getLastLongitude(mapValue); long timestamp1 = getLastTimestamp(mapValue); double lat2Degrees = this.latDegree.getDouble(record); double lon2Degrees = this.lonDegree.getDouble(record); long timestamp2 = this.timestamp.getTimestamp(record); if (!Double.isNaN(lat1Degrees) && !Double.isNaN(lon1Degrees) && timestamp1 != Numbers.LONG_NaN) { if (!Double.isNaN(lat2Degrees) && !Double.isNaN(lon2Degrees) && timestamp2 != Numbers.LONG_NaN) { double currentTotalDistance = getDistance(mapValue); double distance = calculateHaversineDistanceFromDegrees(lat1Degrees, lon1Degrees, lat2Degrees, lon2Degrees, currentTotalDistance); saveLastItem(mapValue, lat2Degrees, lon2Degrees, timestamp2); saveDistance(mapValue, distance); } } else { saveLastItem(mapValue, lat2Degrees, lon2Degrees, timestamp2); } }
Source:
private static String readFromOsRelease() throws Exception { FileReader fileReader; File releaseFile = new File("/etc/os-release"); fileReader = new FileReader(releaseFile); Properties properties = new Properties(); properties.load(fileReader); return StringUtils.strip(properties.getProperty("PRETTY_NAME"), "\""); }

Target:
private static String readFromOsRelease() throws Exception { try (FileReader fileReader = new FileReader(new File("/etc/os-release"))) { Properties properties = new Properties(); properties.load(fileReader); return unQuote(properties.getProperty("PRETTY_NAME")); } }
Source:
private void regenerateDiskIds() { if (getParameters().isImportAsNewEntity()) { Map<Guid, Guid> imageMappings = new HashMap(); Guid oldImageId = null; for (DiskImage disk : getVm().getImages()) { oldImageId = disk.getImageId(); generateNewDiskId(getVm().getImages(), disk); updateManagedDeviceMap(disk, getVm().getStaticData().getManagedDeviceMap()); imageMappings.put(disk.getImageId(), oldImageId); } getParameters().setImageMappings(imageMappings); } }

Target:
private void regenerateDiskIds() { if (getParameters().isImportAsNewEntity()) { Map<Guid, Guid> imageMappings = new HashMap<>(); for (DiskImage disk : getVm().getImages()) { Guid oldImageId = disk.getImageId(); generateNewDiskId(getVm().getImages(), disk); updateManagedDeviceMap(disk, getVm().getStaticData().getManagedDeviceMap()); imageMappings.put(disk.getImageId(), oldImageId); } getParameters().setImageMappings(imageMappings); } }
Source:
public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); final Context context1 = startTracingSpan(method, context); final Mono<HttpResponse> asyncResponse = validateLength(request).then( send(request, context1)); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }

Target:
public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }
Source:
protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestAccount(req.getQuery(), Boolean.TRUE, req.getLimit(), new GerritCallback<List<AccountInfo>>() { public void onSuccess(final List<AccountInfo> result) { final List<AccountOrAccountGroupSuggestion> r = new ArrayList<AccountOrAccountGroupSuggestion>(result .size()); for (final AccountInfo p : result) { r.add(new AccountOrAccountGroupSuggestion(p)); } SuggestUtil.SVC.suggestAccountGroup(req.getQuery(), req.getLimit(), new GerritCallback<List<GroupReference>>() { public void onSuccess(final List<GroupReference> result) { for (final GroupReference groupRef : result) { r.add(new AccountOrAccountGroupSuggestion(groupRef)); } Collections.sort(r); if (r.size() <= req.getLimit()) { callback.onSuggestionsReady(req, new Response(r)); } else { callback.onSuggestionsReady(req, new Response(r.subList(0, req.getLimit()))); } } }); } }); } }); }

Target:
protected void onRequestSuggestions(final Request req, final Callback callback) { RpcStatus.hide(new Runnable() { public void run() { SuggestUtil.SVC.suggestReviewer(req.getQuery(), req.getLimit(), new GerritCallback<List<ReviewerInfo>>() { public void onSuccess(final List<ReviewerInfo> result) { final List<AccountOrAccountGroupSuggestion> r = new ArrayList<AccountOrAccountGroupSuggestion>(result .size()); for (final ReviewerInfo reviewer : result) { r.add(new AccountOrAccountGroupSuggestion(reviewer)); } callback.onSuggestionsReady(req, new Response(r)); } }); } }); }
Source:
private void testSchemaSerializationSchema(Map<String, String> options) { final DynamicTableSink actualSink = createTableSink(options); assert actualSink instanceof TestDynamicTableFactory.DynamicTableSinkMock; TestDynamicTableFactory.DynamicTableSinkMock sinkMock = (TestDynamicTableFactory.DynamicTableSinkMock) actualSink; SerializationSchema<RowData> actualSer = sinkMock.sinkValueFormat .createSinkFormat( new SinkRuntimeProviderContext(false), SCHEMA.toRowDataType()); assertThat(actualSer, instanceOf(JsonRowDataSerializationSchema.class)); }

Target:
private void testSchemaSerializationSchema(Map<String, String> options) { final JsonRowDataSerializationSchema expectedSer = new JsonRowDataSerializationSchema(ROW_TYPE); final DynamicTableSink actualSink = createTableSink(options); assert actualSink instanceof TestDynamicTableFactory.DynamicTableSinkMock; TestDynamicTableFactory.DynamicTableSinkMock sinkMock = (TestDynamicTableFactory.DynamicTableSinkMock) actualSink; SerializationSchema<RowData> actualSer = sinkMock.sinkValueFormat .createSinkFormat( new SinkRuntimeProviderContext(false), SCHEMA.toRowDataType()); assertEquals(expectedSer, actualSer); }
Source:
private <ClusterID> void runClusterAction(CustomCommandLine activeCommandLine, CommandLine commandLine, ClusterAction<ClusterID> clusterAction) throws FlinkException { final Configuration effectiveConfiguration = new Configuration(configuration); final Configuration commandLineConfiguration = activeCommandLine.toConfiguration(commandLine); effectiveConfiguration.addAll(commandLineConfiguration); LOG.debug("Effective configuration: {}", effectiveConfiguration); final ClusterClientFactory<ClusterID> clusterClientFactory = clusterClientServiceLoader.getClusterClientFactory(effectiveConfiguration); final ClusterID clusterId = clusterClientFactory.getClusterId(effectiveConfiguration); if (clusterId == null) { throw new FlinkException("No cluster id was specified. Please specify a cluster to which you would like to connect."); } try (final ClusterDescriptor<ClusterID> clusterDescriptor = clusterClientFactory.createClusterDescriptor(effectiveConfiguration)) { try (final ClusterClient<ClusterID> clusterClient = clusterDescriptor.retrieve(clusterId).getClusterClient()) { clusterAction.runAction(clusterClient); } } }

Target:
private <ClusterID> void runClusterAction(CustomCommandLine activeCommandLine, CommandLine commandLine, ClusterAction<ClusterID> clusterAction) throws FlinkException { final Configuration effectiveConfiguration = getEffectiveConfiguration(activeCommandLine, commandLine); LOG.debug("Effective configuration after Flink conf, and custom commandline: {}", effectiveConfiguration); final ClusterClientFactory<ClusterID> clusterClientFactory = clusterClientServiceLoader.getClusterClientFactory(effectiveConfiguration); final ClusterID clusterId = clusterClientFactory.getClusterId(effectiveConfiguration); if (clusterId == null) { throw new FlinkException("No cluster id was specified. Please specify a cluster to which you would like to connect."); } try (final ClusterDescriptor<ClusterID> clusterDescriptor = clusterClientFactory.createClusterDescriptor(effectiveConfiguration)) { try (final ClusterClient<ClusterID> clusterClient = clusterDescriptor.retrieve(clusterId).getClusterClient()) { clusterAction.runAction(clusterClient); } } }
Source:
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { if (tree.expression().is(Kind.IDENTIFIER)) { String objectName = ((IdentifierTree) tree.expression()).name(); Symbol symbol = tree.identifier().symbol(); if (!symbol.isStatic() && !"this".equals(objectName) && isField(symbol)) { fieldsReadOnAnotherInstance.add(symbol); } } super.visitMemberSelectExpression(tree); }

Target:
public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { Symbol symbol = tree.identifier().symbol(); if (isField(symbol) && !symbol.isStatic()) { if (tree.expression().is(Kind.IDENTIFIER)) { String objectName = ((IdentifierTree) tree.expression()).name(); if (!"this".equals(objectName)) { fieldsReadOnAnotherInstance.add(symbol); } } else { fieldsReadOnAnotherInstance.add(symbol); } } super.visitMemberSelectExpression(tree); }
Source:
@Override public void run() { List<String> describeType = describeActionConfig.describeType; if (describeType == null || describeType.isEmpty()) { throw new IllegalArgumentException("Must specify a single type to describe."); } if (describeActionConfig.name == null || !validName(describeActionConfig.name)) { throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN)); } String firstType = describeType.get(0).toLowerCase().trim(); String name = describeActionConfig.name; switch (firstType) { case "group": try { Group group = keywhizClient.getGroupByName(name); printing.printGroupWithDetails(group, Arrays.asList("clients", "secrets")); } catch (NotFoundException e) { throw new AssertionError("Group not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "client": try { Client client = keywhizClient.getClientByName(name); printing.printClientWithDetails(client, Arrays.asList("groups", "secrets")); } catch (NotFoundException e) { throw new AssertionError("Client not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "secret": SanitizedSecret sanitizedSecret; try { sanitizedSecret = keywhizClient.getSanitizedSecretByName(name); printing.printSanitizedSecretWithDetails(sanitizedSecret, Arrays.asList("groups", "clients", "secret_data")); } catch (NotFoundException e) { throw new AssertionError("Secret not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; default: throw new IllegalArgumentException("Invalid describe type specified: " + firstType); } }

Target:
@Override public void run() { List<String> describeType = describeActionConfig.describeType; if (describeType == null || describeType.isEmpty()) { throw new IllegalArgumentException("Must specify a single type to describe."); } if (describeActionConfig.name == null || !validName(describeActionConfig.name)) { throw new IllegalArgumentException(format("Invalid name, must match %s", VALID_NAME_PATTERN)); } String firstType = describeType.get(0).toLowerCase().trim(); String name = describeActionConfig.name; switch (firstType) { case "group": try { Group group = keywhizClient.getGroupByName(name); printing.printGroupWithDetails(group); } catch (NotFoundException e) { throw new AssertionError("Group not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "client": try { Client client = keywhizClient.getClientByName(name); printing.printClientWithDetails(client); } catch (NotFoundException e) { throw new AssertionError("Client not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; case "secret": SanitizedSecret sanitizedSecret; try { sanitizedSecret = keywhizClient.getSanitizedSecretByName(name); printing.printSanitizedSecretWithDetails(sanitizedSecret); } catch (NotFoundException e) { throw new AssertionError("Secret not found."); } catch (IOException e) { throw Throwables.propagate(e); } break; default: throw new IllegalArgumentException("Invalid describe type specified: " + firstType); } }
Source:
public void setUp() throws ServletException { service = new SchedulerServiceImpl(); ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath("scheduler.conf")).thenReturn(resourceAsFilePath("/scheduler.conf")); when(servletContext.getRealPath("scheduler-portal.conf")).thenReturn(resourceAsFilePath("/scheduler-portal.conf")); service.init(mockServletContext(servletContext)); }

Target:
public void setUp() throws ServletException { service = new SchedulerServiceImpl(); ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath("scheduler.conf")).thenReturn(resourceAsFilePath("/scheduler.conf")); when(servletContext.getRealPath("scheduler-portal-display.conf")).thenReturn(resourceAsFilePath("/scheduler-portal-display.conf")); service.init(mockServletContext(servletContext)); }
Source:
protected void executeCommand() { MoveOrCopyImageGroupParameters p = prepareChildParameters(); VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), p); if (!vdcRetValue.getSucceeded()) { setSucceeded(false); getReturnValue().setFault(vdcRetValue.getFault()); } else { setSucceeded(true); if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) { DiskImage disk = getImage(); disk.setVmSnapshotId(null); disk.setParentId(Guid.Empty); disk.setImageTemplateId(Guid.Empty); ImagesHandler.addDiskImageWithNoVmDevice(disk); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } }

Target:
protected void executeCommand() { MoveOrCopyImageGroupParameters p = prepareChildParameters(); VdcReturnValueBase vdcRetValue = runInternalActionWithTasksContext( getImagesActionType(), p); if (!vdcRetValue.getSucceeded()) { setSucceeded(false); getReturnValue().setFault(vdcRetValue.getFault()); } else { setSucceeded(true); if (getParameters().getOperation() == ImageOperation.Copy && !isTemplate()) { ImagesHandler.addDiskImageWithNoVmDevice(updateDiskImageCopy()); } getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } }
Source:
public void testRequestNetworkCallback_onUnavailable() { final boolean previousWifiEnabledState = mWifiManager.isWifiEnabled(); if (previousWifiEnabledState) { disconnectFromWifi(null); } final TestNetworkCallback callback = new TestNetworkCallback(); mCm.requestNetwork(new NetworkRequest.Builder() .addTransportType(TRANSPORT_WIFI) .build(), 100, callback); try { assertTrue("Did not receive NetworkCallback.onUnavailable", callback.waitForUnavailable()); } catch (InterruptedException e) { fail("Broadcast receiver or NetworkCallback wait was interrupted."); } finally { mCm.unregisterNetworkCallback(callback); if (previousWifiEnabledState) { connectToWifi(); } } }

Target:
public void testRequestNetworkCallback_onUnavailable() { final boolean previousWifiEnabledState = mWifiManager.isWifiEnabled(); if (previousWifiEnabledState) { disconnectFromWifi(null); } final TestNetworkCallback callback = new TestNetworkCallback(); mCm.requestNetwork(new NetworkRequest.Builder() .addTransportType(TRANSPORT_WIFI) .build(), 100, callback); try { assertTrue("Did not receive NetworkCallback#onUnavailable", callback.waitForUnavailable()); } catch (InterruptedException e) { fail("NetworkCallback wait was interrupted."); } finally { mCm.unregisterNetworkCallback(callback); if (previousWifiEnabledState) { connectToWifi(); } } }
Source:
public boolean isOnline(Context context) { if (sAdBlockerEnabled) return false; boolean isOnline; try { final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); isOnline = netInfo != null && netInfo.isConnectedOrConnecting(); if (MPConfig.DEBUG) { Log.v(LOGTAG, "ConnectivityManager says we " + (isOnline ? "are" : "are not") + " online"); } } catch (final SecurityException e) { isOnline = true; if (MPConfig.DEBUG) { Log.v(LOGTAG, "Don't have permission to check connectivity, will assume we are online"); } } return isOnline; }

Target:
public boolean isOnline(Context context) { if (sIsMixpanelBlocked) return false; boolean isOnline; try { final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = cm.getActiveNetworkInfo(); isOnline = netInfo != null && netInfo.isConnectedOrConnecting(); if (MPConfig.DEBUG) { Log.v(LOGTAG, "ConnectivityManager says we " + (isOnline ? "are" : "are not") + " online"); } } catch (final SecurityException e) { isOnline = true; if (MPConfig.DEBUG) { Log.v(LOGTAG, "Don't have permission to check connectivity, will assume we are online"); } } return isOnline; }
Source:
public TypeSpec createTypeAdapter(ClassName className, ClassName autoValueClassName, List<Property> properties) { ClassName typeAdapterClass = ClassName.get(TypeAdapter.class); ParameterizedTypeName superClass = ParameterizedTypeName.get(typeAdapterClass, autoValueClassName); ImmutableMap<Property, FieldSpec> adapters = createFields(properties); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(Gson.class, "gson"); for (Map.Entry<Property, FieldSpec> entry : adapters.entrySet()) { Property prop = entry.getKey(); FieldSpec field = entry.getValue(); if (entry.getKey().type instanceof ParameterizedTypeName) { constructor.addStatement("this.$N = gson.getAdapter($L)", field, makeType((ParameterizedTypeName) prop.type)); } else { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; constructor.addStatement("this.$N = gson.getAdapter($T.class)", field, type); } } String customTypeAdapterClass = String.format("%sTypeAdapter", autoValueClassName.simpleName()); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(customTypeAdapterClass) .addModifiers(PUBLIC, STATIC, FINAL) .addModifiers(PUBLIC, STATIC, FINAL) .superclass(superClass) .addFields(adapters.values()) .addMethod(constructor.build()) .addMethod(createWriteMethod(autoValueClassName, adapters)) .addMethod(createReadMethod(className, autoValueClassName, adapters)); return classBuilder.build(); }

Target:
public TypeSpec createTypeAdapter(ClassName className, ClassName autoValueClassName, List<Property> properties) { ClassName typeAdapterClass = ClassName.get(TypeAdapter.class); ParameterizedTypeName superClass = ParameterizedTypeName.get(typeAdapterClass, autoValueClassName); ImmutableMap<Property, FieldSpec> adapters = createFields(properties); ParameterSpec gsonParam = ParameterSpec.builder(Gson.class, "gson").build(); MethodSpec.Builder constructor = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(gsonParam); for (Map.Entry<Property, FieldSpec> entry : adapters.entrySet()) { Property prop = entry.getKey(); FieldSpec field = entry.getValue(); if (entry.getKey().type instanceof ParameterizedTypeName) { constructor.addStatement("this.$N = $N.getAdapter($L)", field, gsonParam, makeType((ParameterizedTypeName) prop.type)); } else { TypeName type = prop.type.isPrimitive() ? prop.type.box() : prop.type; constructor.addStatement("this.$N = $N.getAdapter($T.class)", field, gsonParam, type); } } String customTypeAdapterClass = String.format("%sTypeAdapter", autoValueClassName.simpleName()); TypeSpec.Builder classBuilder = TypeSpec.classBuilder(customTypeAdapterClass) .addModifiers(PUBLIC, STATIC, FINAL) .addModifiers(PUBLIC, STATIC, FINAL) .superclass(superClass) .addFields(adapters.values()) .addMethod(constructor.build()) .addMethod(createWriteMethod(autoValueClassName, adapters)) .addMethod(createReadMethod(className, autoValueClassName, adapters)); return classBuilder.build(); }
Source:
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { User target = getPlayer(server, args, 0, true); sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } }

Target:
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { User target = getPlayer(server, args, 0, true, false); sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } }
Source:
protected ModelNode createAddPeriodicRotatingFileHandlerOperation(String handlerName, String formatterName, String fileName, String suffix) { ModelNode op = Util.createAddOperation(createPeriodicRotatingFileHandlerAddress(handlerName)); op.get(ModelDescriptionConstants.RELATIVE_TO).set("log.dir"); op.get(ModelDescriptionConstants.PATH).set(fileName); op.get(ModelDescriptionConstants.FORMATTER).set(formatterName); if (suffix != null) op.get(ModelDescriptionConstants.SUFFIX).set(suffix); return op; }

Target:
protected ModelNode createAddPeriodicRotatingFileHandlerOperation(String handlerName, String formatterName, String fileName, String suffix) { ModelNode op = Util.createAddOperation(createPeriodicRotatingFileHandlerAddress(handlerName)); op.get(ModelDescriptionConstants.RELATIVE_TO).set("log.dir"); op.get(ModelDescriptionConstants.PATH).set(fileName); op.get(ModelDescriptionConstants.FORMATTER).set(formatterName); op.get(ModelDescriptionConstants.SUFFIX).set(suffix); return op; }
Source:
public VmStatic(VmBase vmBase) { super(vmBase.getName(), vmBase.getId(), vmBase.getVdsGroupId(), vmBase.getOsId(), vmBase.getCreationDate(), vmBase.getDescription(), vmBase.getComment(), vmBase.getMemSizeMb(), vmBase.getNumOfSockets(), vmBase.getCpuPerSocket(), vmBase.getNumOfMonitors(), vmBase.getSingleQxlPci(), vmBase.getDomain(), vmBase.getTimeZone(), vmBase.getVmType(), vmBase.getUsbPolicy(), vmBase.isFailBack(), vmBase.getDefaultBootSequence(), vmBase.getNiceLevel(), vmBase.getCpuShares(), vmBase.getPriority(), vmBase.isAutoStartup(), vmBase.isStateless(), vmBase.getIsoPath(), vmBase.getOrigin(), vmBase.getKernelUrl(), vmBase.getKernelParams(), vmBase.getInitrdUrl(), vmBase.getQuotaId(), vmBase.isSmartcardEnabled(), vmBase.isDeleteProtected(), vmBase.getSsoMethod(), vmBase.getTunnelMigration(), vmBase.getVncKeyboardLayout(), vmBase.getMinAllocatedMem(), vmBase.isRunAndPause(), vmBase.getCreatedByUserId(), vmBase.getMigrationSupport(), vmBase.isAllowConsoleReconnect(), vmBase.getDedicatedVmForVds(), vmBase.getDefaultDisplayType()); }

Target:
public VmStatic(VmBase vmBase) { super(vmBase); }
Source:
public void testNoDictionary() throws IOException { final Path liftOutput = Files.createTempFile("tmpouput", ".vcf"); liftOutput.toFile().deleteOnExit(); final Path rejectOutput = Files.createTempFile("tmpreject", ".vcf"); rejectOutput.toFile().deleteOnExit(); final Path input = TEST_DATA_PATH.toPath().resolve("testLiftoverBiallelicIndels.vcf"); final String[] args = new String[]{ "INPUT=" + input.toString(), "OUTPUT=" + liftOutput.toString(), "REJECT=" + rejectOutput.toString(), "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + REFERENCE_FILE, }; Path dictionary = REFERENCE_FILE.toPath().resolveSibling(REFERENCE_FILE.getName().replace("fasta", "dict")); dictionary.toFile().renameTo(new File(dictionary.toString().replace("dict", "dict.tmp"))); dictionary = REFERENCE_FILE.toPath().resolveSibling(REFERENCE_FILE.getName().replace("fasta", "dict.tmp")); try { Assert.assertEquals(runPicardCommandLine(args), 1); } finally { dictionary.toFile().renameTo(new File(dictionary.toString().replace("dict.tmp", "dict"))); } }

Target:
public void testNoDictionary() throws IOException { final Path liftOutput = Files.createTempFile("tmpouput", ".vcf"); liftOutput.toFile().deleteOnExit(); final Path rejectOutput = Files.createTempFile("tmpreject", ".vcf"); rejectOutput.toFile().deleteOnExit(); final Path input = TEST_DATA_PATH.toPath().resolve("testLiftoverBiallelicIndels.vcf"); final Path tmpCopyDir = Files.createTempDirectory("copy"); tmpCopyDir.toFile().deleteOnExit(); final Path referenceCopy = tmpCopyDir.resolve("refCopy.fasta"); referenceCopy.toFile().deleteOnExit(); Files.copy(REFERENCE_FILE.toPath(), referenceCopy); final String[] args = new String[]{ "INPUT=" + input, "OUTPUT=" + liftOutput, "REJECT=" + rejectOutput, "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + referenceCopy, }; Assert.assertEquals(runPicardCommandLine(args), 1); }
Source:
private void verifyValueOfConfigurationPropertyWithContext(String pidWithContext, String property, String value) { waitForAssert(() -> { Configuration configuration = getConfigurationWithContext(pidWithContext); assertThat("The configuration for the given pid cannot be found", configuration, is(notNullValue())); assertThat("There are no properties for the configuration", configuration.getProperties(), is(notNullValue())); assertThat("There is no such " + property + " in the configuration properties", configuration.getProperties().get(property), is(notNullValue())); assertThat("The value of the property " + property + " for pid " + pidWithContext + " is not as expected", configuration.getProperties().get(property), is(equalTo(value))); }); }

Target:
private void verifyValueOfConfigurationPropertyWithContext(String pidWithContext, String property, String value) { waitForAssert(() -> { Configuration configuration = getConfigurationWithContext(pidWithContext); assertThat(configuration, is(notNullValue())); assertThat(configuration.getProperties(), is(notNullValue())); assertThat(configuration.getProperties().get(property), is(equalTo(value))); }); }
Source:
public void commitDatabase() { String s = mapper.toJson(map); synchronized (map) { File rename = new File(file.getParent() + File.separator + "backup", System.currentTimeMillis() + SEPARATOR + file.getName()); file.renameTo(rename); FileOutputStream outputStream; try { outputStream = new FileOutputStream(file, false); outputStream.write(s.getBytes()); outputStream.close(); } catch (Exception e) { logger.error("Error writing JsonDB to {}. Cause {}.", file.getPath(), e.getMessage()); } deferredSince = 0; } }

Target:
public void commitDatabase() { String s = mapper.toJson(map); synchronized (map) { File rename = new File(file.getParent() + File.separator + BACKUP_EXTENSION, System.currentTimeMillis() + SEPARATOR + file.getName()); file.renameTo(rename); try (FileOutputStream outputStream = new FileOutputStream(file, false);) { outputStream.write(s.getBytes()); outputStream.close(); } catch (Exception e) { logger.error("Error writing JsonDB to {}. Cause {}.", file.getPath(), e.getMessage()); } deferredSince = 0; } }
Source:
public boolean init() { if (!initializeOpenVRLibrary()) { return false; } if (!initializeJOpenVR()) return false; int nAttempts = 0; boolean bSuccess = false; while (!bSuccess && nAttempts < 10) { try { Thread.sleep(300); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } bSuccess = initOpenVRCompositor(true); nAttempts++; } if (!initOpenVROverlay()) return false; if (!initOpenVROSettings()) return false; initialized = true; return true; }

Target:
public boolean init() { if (!initializeOpenVRLibrary()) { logger.warn("JOpenVR library loading failed."); return false; } if (!initializeJOpenVR()) { logger.warn("JOpenVR initialization failed."); return false; } int initAttempts = 0; boolean initSuccess = false; while (!initSuccess && initAttempts < 10) { try { Thread.sleep(300); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } initSuccess = initOpenVRCompositor(true); initAttempts++; } if (!initOpenVROverlay()) { logger.warn("VROverlay initialization failed."); return false; } if (!initOpenVROSettings()) { logger.warn("OpenVR settings initialization failed."); return false; } initialized = true; return true; }
Source:
public void setsTextInReadOnly() throws Exception { final SWTBotText text = bot.textInGroup("Text", 1); assertTrue(text.isReadOnly()); try { text.setText(""); fail("Expecting an exception"); } catch (Exception e) { assertEquals("TextBox is read-only", e.getMessage()); } }

Target:
public void setsTextInReadOnly() throws Exception { bot.checkBox("SWT.READ_ONLY").select(); final SWTBotText text = bot.textInGroup("Text"); assertTrue(text.isReadOnly()); try { text.setText(""); fail("Expecting an exception"); } catch (Exception e) { assertEquals("TextBox is read-only", e.getMessage()); } }
Source:
public Guid createTask( CommandBase command, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, String description, VdcObjectType entityType, Guid... entityIds) { Guid retValue = Guid.Empty; Transaction transaction = TransactionSupport.suspend(); try { Step taskStep = addTaskStep(command.getExecutionContext(), StepEnum.getStepNameByTaskType(asyncTaskCreationInfo.getTaskType()), description); if (taskStep != null) { asyncTaskCreationInfo.setStepId(taskStep.getId()); } SPMAsyncTask task = concreteCreateTask(command, asyncTaskCreationInfo, parentCommand); retValue = task.getTaskID(); task.setEntityType(entityType); task.setAssociatedEntities(entityIds); AsyncTaskUtils.addOrUpdateTaskInDB(task); commandMap.put( task.getParameters().getDbAsyncTask().getStepId(), buildGetCommandEntity( command.getCommandId(), command.getParameters().getParentParameters() == null ? Guid.Empty : command.getParameters().getParentParameters().getCommandId(), task)); getAsyncTaskManager().lockAndAddTaskToManager(task); retValue = task.getTaskID(); updateStepExternalId(taskStep, retValue, ExternalSystemType.VDSM); } catch (RuntimeException ex) { log.errorFormat("Error during CreateTask for command: {0}. Exception {1}", this.getClass().getName(), ex); } finally { TransactionSupport.resume(transaction); } return retValue; }

Target:
public Guid createTask( CommandBase command, AsyncTaskCreationInfo asyncTaskCreationInfo, VdcActionType parentCommand, String description, VdcObjectType entityType, Guid... entityIds) { Guid retValue = Guid.Empty; Transaction transaction = TransactionSupport.suspend(); try { Step taskStep = addTaskStep(command.getExecutionContext(), StepEnum.getStepNameByTaskType(asyncTaskCreationInfo.getTaskType()), description); if (taskStep != null) { asyncTaskCreationInfo.setStepId(taskStep.getId()); } SPMAsyncTask task = concreteCreateTask(command, asyncTaskCreationInfo, parentCommand); retValue = task.getTaskID(); task.setEntityType(entityType); task.setAssociatedEntities(entityIds); AsyncTaskUtils.addOrUpdateTaskInDB(task); commandEntityDAO.put( task.getParameters().getDbAsyncTask().getStepId(), command.getCommandId(), command.getParameters().getParentParameters() == null ? Guid.Empty : command.getParameters().getParentParameters().getCommandId(), task); getAsyncTaskManager().lockAndAddTaskToManager(task); retValue = task.getTaskID(); updateStepExternalId(taskStep, retValue, ExternalSystemType.VDSM); } catch (RuntimeException ex) { log.errorFormat("Error during CreateTask for command: {0}. Exception {1}", this.getClass().getName(), ex); } finally { TransactionSupport.resume(transaction); } return retValue; }
Source:
public SagaTestFixture(Class<T> sagaType) { this.sagaType = sagaType; eventScheduler = new StubEventScheduler(); EventBus eventBus = new SimpleEventBus(); sagaStore = new InMemorySagaStore(); registeredResources.add(eventBus); commandBus = new RecordingCommandBus(); registeredResources.add(commandBus); registeredResources.add(eventScheduler); registeredResources.add(new DefaultCommandGateway(commandBus)); fixtureExecutionResult = new FixtureExecutionResultImpl<>(sagaStore, eventScheduler, eventBus, commandBus, sagaType, fieldFilters); handlerDefinition = new ClasspathHandlerDefinition(Thread.currentThread().getContextClassLoader()); }

Target:
public SagaTestFixture(Class<T> sagaType) { this.sagaType = sagaType; eventScheduler = new StubEventScheduler(); EventBus eventBus = new SimpleEventBus(); sagaStore = new InMemorySagaStore(); registeredResources.add(eventBus); commandBus = new RecordingCommandBus(); registeredResources.add(commandBus); registeredResources.add(eventScheduler); registeredResources.add(new DefaultCommandGateway(commandBus)); fixtureExecutionResult = new FixtureExecutionResultImpl<>(sagaStore, eventScheduler, eventBus, commandBus, sagaType, fieldFilters); handlerDefinition = ClasspathHandlerDefinition.forClass(sagaType); }
Source:
public static ObjectNode getServerElementsRecursively(Project project, String elementId, boolean recurse, int depth, ProgressStatus progressStatus) throws ServerException, IOException, URISyntaxException { URIBuilder requestUri = getServiceWorkspacesSitesElementsUri(project); if (requestUri == null) { return null; } requestUri = MMSUtils.getServiceWorkspacesUri(project); requestUri.setPath(requestUri.getPath() + "/elements/" + elementId); if (depth > 0) { requestUri.setParameter("depth", java.lang.Integer.toString(depth)); } else if (recurse) { requestUri.setParameter("depth", java.lang.Integer.toString(9999)); } ObjectNode response = JacksonUtils.getObjectMapper().createObjectNode(); try { response = sendCancellableMMSRequest(buildRequest(HttpRequestType.GET, requestUri, null), progressStatus); } catch (ServerException e) { if (e.getCode() != 404) { throw e; } } return response; }

Target:
public static ObjectNode getServerElementsRecursively(Project project, String elementId, boolean recurse, int depth, ProgressStatus progressStatus) throws ServerException, IOException, URISyntaxException { URIBuilder requestUri = getServiceWorkspacesSitesElementsUri(project); if (requestUri == null) { return null; } requestUri = MMSUtils.getServiceWorkspacesUri(project); requestUri.setPath(requestUri.getPath() + "/elements/" + elementId); if (depth > 0) { requestUri.setParameter("depth", java.lang.Integer.toString(depth)); } else if (recurse) { requestUri.setParameter("recurse", java.lang.Boolean.toString(recurse)); } ObjectNode response = JacksonUtils.getObjectMapper().createObjectNode(); try { response = sendCancellableMMSRequest(buildRequest(HttpRequestType.GET, requestUri, null), progressStatus); } catch (ServerException e) { if (e.getCode() != 404) { throw e; } } return response; }
Source:
public Builder setId(final String id) { p.id = id; return this; }

Target:
public Builder setId(final String id) { this.id = id; return this; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return false; } fLock.lock(); try { final List<TraceSessionComponent> sessions = new ArrayList<>(); sessions.addAll(fSessions); Job job = new Job(Messages.TraceControl_SaveJob) { @Override protected IStatus run(IProgressMonitor monitor) { try { for (Iterator<TraceSessionComponent> iterator = sessions.iterator(); iterator.hasNext();) { TraceSessionComponent session = iterator.next(); session.saveSession(null, null, true, monitor); } } catch (ExecutionException e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_SaveFailure, e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } finally { fLock.unlock(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return false; } fLock.lock(); try { final List<TraceSessionComponent> sessions = new ArrayList<>(); sessions.addAll(fSessions); Job job = new Job(Messages.TraceControl_SaveJob) { @Override protected IStatus run(IProgressMonitor monitor) { try { for (TraceSessionComponent session : sessions) { session.saveSession(null, null, true, monitor); } } catch (ExecutionException e) { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.TraceControl_SaveFailure, e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); } finally { fLock.unlock(); } return null; }
Source:
public HttpServer(ResponderServlet servlet, String bindAddress, int port) throws IOException { this.server = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(this.server); if (bindAddress != null) { connector.setHost(bindAddress); } connector.setPort(port); server.addConnector(connector); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(new ServletHolder(servlet), "/*"); }

Target:
public HttpServer(ResponderServlet servlet, String bindAddress, int port) throws IOException { this.server = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(this.server); connector.setAcceptQueueSize(128); connector.setIdleTimeout(10000); if (bindAddress != null) { connector.setHost(bindAddress); } connector.setPort(port); server.addConnector(connector); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(new ServletHolder(servlet), "/*"); ServletContextHandler sch = new ServletContextHandler(); sch.setServletHandler(handler); server.setHandler(sch); }
Source:
public Mono<FunctionApp> refreshAsync() { return this.manager().functionApps().getByIdAsync(this.id()); }

Target:
public Mono<FunctionApp> refreshAsync() { return this.manager().functionApps().getByIdAsync(this.id()) .doOnNext(site -> this.setInner(site.inner())); }