auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Boolean getDayNightRenderer() { if (dayNightMode.isDay()) { return Boolean.TRUE; } else if (dayNightMode.isNight()) { return Boolean.FALSE; } else if (dayNightMode.isAuto()) { long currentTime = System.currentTimeMillis(); if (currentTime - lastAutoCall > 60000) { lastAutoCall = System.currentTimeMillis(); try { Location lastKnownLocation = getLocation(); if (lastKnownLocation == null) { return null; } double longitude = lastKnownLocation.getLongitude(); Date actualTime = new Date(); SunriseSunset daynightSwitch = new SunriseSunset(lastKnownLocation.getLatitude(), longitude < 0 ? 360 - longitude : longitude, actualTime, (-1.0 * TimeZone.getDefault().getOffset(actualTime.getTime())) / 3600000); boolean daytime = daynightSwitch.isDaytime(); log.debug("Sunrise/sunset setting to day: " + daytime); lastAutoValue = Boolean.valueOf(daytime); return lastAutoValue; } catch (IllegalArgumentException e) { log.warn("Network location provider not available"); } catch (SecurityException e) { log.warn("Missing permitions to get actual location!"); } return null; } else { return lastAutoValue; } } else if (dayNightMode.isSensor()) { log.debug("lux value:" + lux + " setting to day: " + (lux > SensorManager.LIGHT_CLOUDY)); return lux > SensorManager.LIGHT_CLOUDY ? Boolean.TRUE : Boolean.FALSE; } return null; }

Target:
public Boolean getDayNightRenderer() { if (dayNightMode.isDay()) { return Boolean.TRUE; } else if (dayNightMode.isNight()) { return Boolean.FALSE; } else if (dayNightMode.isAuto()) { long currentTime = System.currentTimeMillis(); if (currentTime - lastAutoCall > 60000) { lastAutoCall = System.currentTimeMillis(); try { Location lastKnownLocation = getLocation(); if (lastKnownLocation == null) { return null; } double longitude = lastKnownLocation.getLongitude(); Date actualTime = new Date(); SunriseSunset daynightSwitch = new SunriseSunset(lastKnownLocation.getLatitude(), longitude < 0 ? 360 - longitude : longitude, actualTime, TimeZone.getDefault()); boolean daytime = daynightSwitch.isDaytime(); log.debug("Sunrise/sunset setting to day: " + daytime); lastAutoValue = Boolean.valueOf(daytime); return lastAutoValue; } catch (IllegalArgumentException e) { log.warn("Network location provider not available"); } catch (SecurityException e) { log.warn("Missing permitions to get actual location!"); } return null; } else { return lastAutoValue; } } else if (dayNightMode.isSensor()) { log.debug("lux value:" + lux + " setting to day: " + (lux > SensorManager.LIGHT_CLOUDY)); return lux > SensorManager.LIGHT_CLOUDY ? Boolean.TRUE : Boolean.FALSE; } return null; }
Source:
public static TruthState getVar(final int allele0idx, final int allele1idx) { if (allele0idx == 0 && allele1idx == 1) return HET_REF_VAR1; if (allele0idx == 1 && allele1idx == 0) return HET_REF_VAR1; if (allele0idx == 1 && allele1idx == 2) return HET_VAR1_VAR2; if (allele0idx == 2 && allele1idx == 1) return HET_VAR1_VAR2; ValidationUtils.validateArg(false,"Shouldn't be here."); return null; }

Target:
public static TruthState getVar(final int allele0idx, final int allele1idx) { if (allele0idx == 0 && allele1idx == 1) return HET_REF_VAR1; if (allele0idx == 1 && allele1idx == 0) return HET_REF_VAR1; if (allele0idx == 1 && allele1idx == 2) return HET_VAR1_VAR2; if (allele0idx == 2 && allele1idx == 1) return HET_VAR1_VAR2; throw new IllegalStateException("Shouldn't be here."); }
Source:
public void onRuntimeModelRemoved(@Observes RemovedRuntimeModelEvent event) { String externalComponentsDir = loader.getExternalComponentsDir(); String runtimeModelId = event.getRuntimeModelId(); if (options.isComponentPartition()) { File runtimeModelComponentsFile = Paths.get(externalComponentsDir, runtimeModelId).toFile(); FileUtils.deleteQuietly(runtimeModelComponentsFile); } }

Target:
public void onRuntimeModelRemoved(@Observes RemovedRuntimeModelEvent event) { if (options.isComponentPartition()) { String componentsDir = loader.getExternalComponentsDir(); String runtimeModelId = event.getRuntimeModelId(); if (componentsDir != null && runtimeModelId != null) { File runtimeModelComponentsFile = Paths.get(componentsDir, runtimeModelId).toFile(); FileUtils.deleteQuietly(runtimeModelComponentsFile); } } }
Source:
public NatsMessage(String subject, String replyTo, Headers headers, byte[] data, boolean utf8mode) { if (subject == null || subject.length() == 0) { throw new IllegalArgumentException("Subject is required"); } if (replyTo != null && replyTo.length() == 0) { throw new IllegalArgumentException("ReplyTo cannot be the empty string"); } kind = Kind.REGULAR; this.subject = subject; this.replyTo = replyTo; this.headers = headers; this.data = data == null ? EMPTY_BODY : data; this.utf8mode = utf8mode; int replyToLen = replyTo == null ? 0 : replyTo.length(); dataLen = this.data.length; if (headers != null && !headers.isEmpty()) { hdrLen = headers.serializedLength(); } else { hdrLen = 0; } totLen = hdrLen + dataLen; ByteArrayBuilder bab = new ByteArrayBuilder(32 + (subject.length() * 2) + replyToLen + totLen); if (hdrLen > 0) { bab.append(HPUB_BYTES, HPUB_BYTES_LEN); } else { bab.append(PUB_BYTES, PUB_BYTES_LEN); } bab.append(subject, utf8mode ? UTF_8 : US_ASCII); bab.appendSpace(); if (replyToLen > 0) { bab.append(replyTo); bab.appendSpace(); } if (hdrLen > 0) { bab.append(Integer.toString(hdrLen)); bab.appendSpace(); } bab.append(Integer.toString(totLen)); protocolBytes = bab.toByteArray(); }

Target:
public NatsMessage(String subject, String replyTo, Headers headers, byte[] data, boolean utf8mode) { if (subject == null || subject.length() == 0) { throw new IllegalArgumentException("Subject is required"); } if (replyTo != null && replyTo.length() == 0) { throw new IllegalArgumentException("ReplyTo cannot be the empty string"); } kind = Kind.REGULAR; this.subject = subject; this.replyTo = replyTo; this.headers = headers; this.data = data; this.utf8mode = utf8mode; int replyToLen = replyTo == null ? 0 : replyTo.length(); dataLen = data == null ? 0 : data.length; if (headers != null && !headers.isEmpty()) { hdrLen = headers.serializedLength(); } else { hdrLen = 0; } totLen = hdrLen + dataLen; ByteArrayBuilder bab = new ByteArrayBuilder(32 + (subject.length() * 2) + replyToLen + totLen); if (hdrLen > 0) { bab.append(HPUB_SP_BYTES); } else { bab.append(PUB_SP_BYTES); } bab.append(subject, utf8mode ? UTF_8 : US_ASCII); bab.appendSpace(); if (replyToLen > 0) { bab.append(replyTo); bab.appendSpace(); } if (hdrLen > 0) { bab.append(Integer.toString(hdrLen)); bab.appendSpace(); } bab.append(Integer.toString(totLen)); protocolBytes = bab.toByteArray(); }
Source:
private void populateClassNameMapping(Set<String> classNames) { Map<String, Class<?>> newMappings = new ConcurrentHashMap<String, Class<?>>(); synchronized (this.classNameMappings) { this.classNameMappings.clear(); for (String className : classNames) { this.classNameMappings.put(className, resolveClassFromName(className)); } } }

Target:
private void populateClassNameMapping(Set<String> classNames) { Map<String, Class<?>> newClassNameMappings = new ConcurrentHashMap<String, Class<?>>(); for (String className : classNames) { newClassNameMappings.put(className, resolveClassFromName(className)); } this.classNameMappings = newClassNameMappings; }
Source:
synchronized void startMigration(final String operationId, final String senderId, final String receiverId, final int numBlocks, @Nullable final TraceInfo parentTraceInfo, @Nullable final EventHandler<AvroElasticMemoryMessage> finishedCallback) { Trace.setProcessId(MigrationManager.class.getSimpleName()); final TraceScope migrationTraceScope = Trace.startSpan(MIGRATION + String.format(". op_id: %s, sender: %s," + " receiver: %s, num_blocks: %d ", operationId, senderId, receiverId, numBlocks), parentTraceInfo); if (ongoingMigrations.containsKey(operationId)) { LOG.log(Level.WARNING, "Failed to register migration with id {0}. Already exists", operationId); return; } callbackRouter.register(operationId, finishedCallback); final List<Integer> blocks = blockManager.chooseBlocksToMove(senderId, numBlocks); if (blocks.size() == 0) { final String reason = "There is no block to move in " + senderId + " of type. Requested numBlocks: " + numBlocks; notifyFailure(operationId, reason); return; } ongoingMigrations.put(operationId, new Migration(senderId, receiverId, blocks, migrationTraceScope)); sender.get().sendCtrlMsg(senderId, receiverId, blocks, operationId, TraceInfo.fromSpan(migrationTraceScope.getSpan())); }

Target:
synchronized void startMigration(final String operationId, final String senderId, final String receiverId, final int numBlocks, @Nullable final TraceInfo parentTraceInfo, @Nullable final EventHandler<AvroElasticMemoryMessage> finishedCallback) { Trace.setProcessId("migration_manager"); final TraceScope migrationTraceScope = Trace.startSpan( String.format("migration. op_id: %s, sender: %s, receiver: %s, num_blocks: %d ", operationId, senderId, receiverId, numBlocks), parentTraceInfo); if (ongoingMigrations.containsKey(operationId)) { LOG.log(Level.WARNING, "Failed to register migration with id {0}. Already exists", operationId); return; } callbackRouter.register(operationId, finishedCallback); final List<Integer> blocks = blockManager.chooseBlocksToMove(senderId, numBlocks); if (blocks.size() == 0) { final String reason = "There is no block to move in " + senderId + " of type. Requested numBlocks: " + numBlocks; notifyFailure(operationId, reason); return; } ongoingMigrations.put(operationId, new Migration(senderId, receiverId, blocks, migrationTraceScope)); sender.get().sendCtrlMsg(senderId, receiverId, blocks, operationId, TraceInfo.fromSpan(migrationTraceScope.getSpan())); }
Source:
public void startElement(TagNode node) { if (isLabel(node) || insideLabelNode()) { elementStack.push(node); } if (getNodeId(node) != null) { ids.add(getNodeId(node)); } if (isInputRequiredLabel(node) || isSelect(node) || isTextarea(node)) { if (node.getPropertyValue("aria-label") != null || insideLabelNode()) { return; } if (node.getPropertyValue("aria-labelledby") != null) { expectedIds.put(node, Arrays.stream(node.getPropertyValue("aria-labelledby").split(" ")).collect(Collectors.toSet())); return; } String id = getNodeId(node); if (id == null) { createViolation(node.getStartLinePosition(), "Add an \"id\" attribute to this input field and associate it with a label."); } else { inputIdToLine.put(getNodeId(node), node.getStartLinePosition()); } } else if (isLabel(node) && node.getAttribute("for") != null) { labelFor.add(node.getAttribute("for")); } }

Target:
public void startElement(TagNode node) { if (isLabel(node) || insideLabelNode()) { elementStack.push(node); } if (getNodeId(node) != null) { ids.add(getNodeId(node)); } if (isInputRequiredLabel(node) || isSelect(node) || isTextarea(node)) { if (node.getPropertyValue("aria-label") != null || insideLabelNode()) { return; } if (node.getPropertyValue("aria-labelledby") != null) { expectedIds.put(node, Arrays.stream(node.getPropertyValue("aria-labelledby").split(" ")).collect(Collectors.toSet())); return; } String id = getNodeId(node); if (id == null) { createViolation(node.getStartLinePosition(), "Add an \"id\" attribute to this input field and associate it with a label."); } else { inputIdToLine.put(id, node.getStartLinePosition()); } } else if (isLabel(node) && node.getAttribute("for") != null) { labelFor.add(node.getAttribute("for")); } }
Source:
public void newLimitedEntryActionInsertColumn() { final LimitedEntryActionInsertFactCol52 column = new LimitedEntryActionInsertFactCol52(); final ActionInsertFactPopup popup = new ActionInsertFactPopup( model, oracle, presenter, new ActionColumnCommand() { public void execute( final ActionCol52 column ) { presenter.appendColumn( column ); } }, column, true, !access.isEditable() ); popup.show(); }

Target:
public void newLimitedEntryActionInsertColumn() { final LimitedEntryActionInsertFactCol52 column = new LimitedEntryActionInsertFactCol52(); doNewActionInsertColumn( column ); }
Source:
public void setText(CharSequence s) { if(VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { super.setText(s); return; } if (getView() == null) { return; } try { ((TextView) getView()).setText(s); } catch (ClassCastException e) { Log.e(IcsToast.TAG, "This Toast was not created with IcsToast.makeText", e); } }

Target:
public void setText(CharSequence s) { if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) { super.setText(s); return; } if (getView() == null) { return; } try { ((TextView) getView()).setText(s); } catch (ClassCastException e) { Log.e(TAG, "This Toast was not created with IcsToast.makeText", e); } }
Source:
public boolean isLoggable(final LogRecord record) { return record != null && pattern.matcher(String.valueOf(record.getMessage())).find(); }

Target:
public boolean isLoggable(final LogRecord record) { final String msg; if (record instanceof ExtLogRecord) { msg = ((ExtLogRecord) record).getFormattedMessage(); } else { msg = MessageFormat.format(record.getMessage(), record.getParameters()); } return pattern.matcher(String.valueOf(msg)).find(); }
Source:
protected void onPostExecute(Boolean result) { if(requestCode == FileDisplayActivity.REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM) { mCurrentDialog.dismiss(); mCurrentDialog = null; } if (result) { Intent data = new Intent(); if(requestCode == FileDisplayActivity.REQUEST_CODE__UPLOAD_FROM_CAMERA){ data.putExtra(EXTRA_CHOSEN_FILES,new String[]{ capturedImagePath}); } else { data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths()); } SharedPreferences.Editor appPreferencesEditor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); if(requestCode == FileDisplayActivity.REQUEST_CODE__UPLOAD_FROM_CAMERA){ setResult(RESULT_OK, data); appPreferencesEditor.putInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_MOVE); } else { if (mRadioBtnMoveFiles.isChecked()) { setResult(RESULT_OK_AND_MOVE, data); appPreferencesEditor.putInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_MOVE); } else { setResult(RESULT_OK, data); appPreferencesEditor.putInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_COPY); } } appPreferencesEditor.apply(); finish(); } else { String[] args = {getString(R.string.app_name)}; ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance( R.string.upload_query_move_foreign_files, args, 0, R.string.common_yes, -1, R.string.common_no ); dialog.setOnConfirmationListener(UploadFilesActivity.this); dialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG); } }

Target:
protected void onPostExecute(Boolean result) { if(requestCode == FileDisplayActivity.REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM) { mCurrentDialog.dismiss(); mCurrentDialog = null; } if (result) { Intent data = new Intent(); if(requestCode == FileDisplayActivity.REQUEST_CODE__UPLOAD_FROM_CAMERA){ data.putExtra(EXTRA_CHOSEN_FILES,new String[]{ capturedImagePath}); } else { data.putExtra(EXTRA_CHOSEN_FILES, mFileListFragment.getCheckedFilePaths()); } SharedPreferences.Editor appPreferencesEditor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); if(requestCode == FileDisplayActivity.REQUEST_CODE__UPLOAD_FROM_CAMERA){ setResult(RESULT_OK_AND_MOVE, data); appPreferencesEditor.putInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_MOVE); } else { if (mRadioBtnMoveFiles.isChecked()) { setResult(RESULT_OK_AND_MOVE, data); appPreferencesEditor.putInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_MOVE); } else { setResult(RESULT_OK, data); appPreferencesEditor.putInt("prefs_uploader_behaviour", FileUploader.LOCAL_BEHAVIOUR_COPY); } } appPreferencesEditor.apply(); finish(); } else { String[] args = {getString(R.string.app_name)}; ConfirmationDialogFragment dialog = ConfirmationDialogFragment.newInstance( R.string.upload_query_move_foreign_files, args, 0, R.string.common_yes, -1, R.string.common_no ); dialog.setOnConfirmationListener(UploadFilesActivity.this); dialog.show(getSupportFragmentManager(), QUERY_TO_MOVE_DIALOG_TAG); } }
Source:
public Response getExtraEnvParams() { try { Map<String, String> returnMap; returnMap=priamServer.getConfiguration().getExtraEnvParams(); if(returnMap == null) { returnMap = new HashMap<String,String>(); } String extraEnvParamsJson=JSONValue.toJSONString(returnMap); return Response.ok(extraEnvParamsJson).build(); } catch (Exception e) { logger.error("Error while executing get_replaced_ip", e); return Response.serverError().build(); } }

Target:
public Response getExtraEnvParams() { try { Map<String, String> returnMap; returnMap=priamServer.getConfiguration().getExtraEnvParams(); if(returnMap == null) { returnMap = new HashMap<String,String>(); } String extraEnvParamsJson=JSONValue.toJSONString(returnMap); return Response.ok(extraEnvParamsJson).build(); } catch (Exception e) { logger.error("Error while executing get_extra_env_params", e); return Response.serverError().build(); } }
Source:
public String convertToString(EFactory factory, EDataType dataType, Object value) { if (dataType.equals(ViewpointPackage.eINSTANCE.getDAnalysis_SemanticResources().getEAttributeType())) { URI deresolvedURI = this.deresolve(((ResourceDescriptor) value).getResourceURI()); return deresolvedURI.toString(); } return super.convertToString(factory, dataType, value); }

Target:
public String convertToString(EFactory factory, EDataType dataType, Object value) { String str = null; if (dataType.equals(ViewpointPackage.eINSTANCE.getDAnalysis_SemanticResources().getEAttributeType())) { URI deresolvedURI = this.deresolve(((ResourceDescriptor) value).getResourceURI()); if (deresolvedURI != null) { str = deresolvedURI.toString(); } } return str != null ? str : super.convertToString(factory, dataType, value); }
Source:
public List<EmailInfo> apply(AccountResource rsrc) throws OrmException { List<EmailInfo> emails = Lists.newArrayList(); ResultSet<AccountExternalId> ids = dbProvider.get().accountExternalIds() .byAccount(rsrc.getUser().getAccountId()); for (AccountExternalId extId : ids) { if (extId.isScheme(AccountExternalId.SCHEME_MAILTO)) { EmailInfo e = new EmailInfo(); e.email = extId.getEmailAddress(); e.setPreferred(extId.getEmailAddress().equals( rsrc.getUser().getAccount().getPreferredEmail())); emails.add(e); } } return emails; }

Target:
public List<EmailInfo> apply(AccountResource rsrc) throws AuthException, OrmException { IdentifiedUser s = (IdentifiedUser) self.get(); if (s.getAccountId().get() != rsrc.getUser().getAccountId().get() && !self.get().getCapabilities().canAdministrateServer()) { throw new AuthException("not allowed to list email addresses"); } List<EmailInfo> emails = Lists.newArrayList(); ResultSet<AccountExternalId> ids = dbProvider.get().accountExternalIds() .byAccount(rsrc.getUser().getAccountId()); for (AccountExternalId extId : ids) { String email = extId.getEmailAddress(); if (email != null) { EmailInfo e = new EmailInfo(); e.email = email; e.setPreferred(email.equals(rsrc.getUser().getAccount() .getPreferredEmail())); emails.add(e); } } return emails; }
Source:
public static void toJSON(OutputWriter outputWriter, Modification modification) { outputWriter.add("id", modification.getId()) .add("revision", modification.getRevision()) .addIfNotNull("modified_time", modification.getModifiedTime()) .add("user_name", modification.getUserName()) .add("comment", modification.getComment()) .add("email_address", modification.getEmailAddress()); }

Target:
public static void toJSON(OutputWriter outputWriter, Modification modification) { outputWriter .add("revision", modification.getRevision()) .addIfNotNull("modified_time", modification.getModifiedTime()) .add("user_name", modification.getUserName()) .add("comment", modification.getComment()) .add("email_address", modification.getEmailAddress()); }
Source:
protected void channelRead0( ChannelHandlerContext ctx, final TxPullRequest msg ) throws Exception { monitor.increment(); if ( msg.previousTxId() <= 0 ) { log.error( "Illegal tx pull request" ); endInteraction( ctx, E_INVALID_REQUEST, -1 ); return; } StoreId localStoreId = storeIdSupplier.get(); StoreId expectedStoreId = msg.expectedStoreId(); long firstTxId = msg.previousTxId() + 1; IOCursor<CommittedTransactionRepresentation> txCursor = getCursor( ctx, firstTxId, localStoreId, expectedStoreId ); if ( txCursor != null ) { ChunkedTransactionStream txStream = new ChunkedTransactionStream( localStoreId, firstTxId, txCursor, protocol ); ctx.writeAndFlush( txStream ).addListener( f -> { String message = format( "Streamed transactions [%d--%d] to %s", firstTxId, txStream.lastTxId(), ctx.channel().remoteAddress() ); if ( f.isSuccess() ) { log.debug( message ); } else { log.warn( message, f.cause() ); } } ); } }

Target:
protected void channelRead0( ChannelHandlerContext ctx, final TxPullRequest msg ) throws Exception { monitor.increment(); if ( msg.previousTxId() <= 0 ) { log.error( "Illegal tx pull request" ); endInteraction( ctx, E_INVALID_REQUEST, -1 ); return; } StoreId localStoreId = storeIdSupplier.get(); StoreId expectedStoreId = msg.expectedStoreId(); long firstTxId = msg.previousTxId() + 1; IOCursor<CommittedTransactionRepresentation> txCursor = getCursor( ctx, firstTxId, localStoreId, expectedStoreId ); if ( txCursor != null ) { ChunkedTransactionStream txStream = new ChunkedTransactionStream( localStoreId, firstTxId, txCursor, protocol ); ctx.writeAndFlush( txStream ).addListener( f -> { if ( log.isDebugEnabled() || !f.isSuccess() ) { String message = format( "Streamed transactions [%d--%d] to %s", firstTxId, txStream.lastTxId(), ctx.channel().remoteAddress() ); if ( f.isSuccess() ) { log.debug( message ); } else { log.warn( message, f.cause() ); } } } ); } }
Source:
public String toFileHistory(final Branch.NameKey branch, final String file) { ParameterizedString pattern = new ParameterizedString(type.getFileHistory()); final Map<String, String> p = new HashMap<String, String>(); p.put("project", URL.encodeQueryString(branch.getParentKey().get())); p.put("branch", URL.encodeQueryString(branch.get())); p.put("file", URL.encodeQueryString(file)); return baseUrl + pattern.replace(p); }

Target:
public String toFileHistory(final Branch.NameKey branch, final String file) { ParameterizedString pattern = new ParameterizedString(type.getFileHistory()); final Map<String, String> p = new HashMap<String, String>(); p.put("project", encode(branch.getParentKey().get())); p.put("branch", encode(branch.get())); p.put("file", URL.encodeQueryString(file)); return baseUrl + pattern.replace(p); }
Source:
protected IStatus run(@Nullable IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor); Collection<ICliParser> cliParsers = getCliParsers(); subMonitor.beginTask("Executing CLI Parsers", cliParsers.size()); for (ICliParser parser : cliParsers) { if (subMonitor.isCanceled()) { return Status.CANCEL_STATUS; } subMonitor.subTask("Executing parser :" + parser.getCmdLineOptions().toString()); IStatus status = parser.workspaceLoading(fCommandLine, subMonitor); System.out.println("one cli parser parsed" + status); if (!status.isOK()) { Activator.getInstance().getLog().log(status); } } return Status.OK_STATUS; }

Target:
protected IStatus run(@Nullable IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor); Collection<ICliParser> cliParsers = getCliParsers(); subMonitor.beginTask("Executing CLI Parsers", cliParsers.size()); for (ICliParser parser : cliParsers) { if (subMonitor.isCanceled()) { return Status.CANCEL_STATUS; } subMonitor.subTask("Executing parser :" + parser.getCmdLineOptions().toString()); IStatus status = parser.workspaceLoading(fCommandLine, subMonitor); if (!status.isOK()) { Activator.getInstance().getLog().log(status); } } return Status.OK_STATUS; }
Source:
public static boolean isString(@Nullable GoType type) { GoType underlyingType = type != null ? type.getUnderlyingType() : null; return underlyingType != null && underlyingType.getText() != null && underlyingType.textMatches("string") && GoPsiImplUtil.builtin(underlyingType); }

Target:
public static boolean isString(@Nullable GoType type) { return isBuiltinType(type, "string"); }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setHeader("Cache-Control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); response.setContentType("text/html"); invalidateSession(request, response); try { URIBuilder redirectUrlBuilder; if (Strings.isNotBlank(SystemBaseUrl.EXTERNAL.getRootContext())) { redirectUrlBuilder = new URIBuilder(SystemBaseUrl.EXTERNAL.getRootContext() + redirectUri); } else { redirectUrlBuilder = new URIBuilder(redirectUri); } redirectUrlBuilder.addParameter("mustCloseBrowser", "true"); response.sendRedirect(redirectUrlBuilder.build().toString()); } catch (URISyntaxException e) { LOGGER.debug("Invalid URI: ", e); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } catch (IOException e) { LOGGER.warn("Unable to redirect to logout page.", e); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setHeader("Cache-Control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); response.setContentType("text/html"); invalidateSession(request, response); try { URIBuilder redirectUrlBuilder = new URIBuilder(SystemBaseUrl.EXTERNAL.constructUrl(redirectUri)); redirectUrlBuilder.addParameter("mustCloseBrowser", "true"); response.sendRedirect(redirectUrlBuilder.build().toString()); } catch (URISyntaxException e) { LOGGER.debug("Invalid URI: ", e); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } catch (IOException e) { LOGGER.warn("Unable to redirect to logout page.", e); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
public int compare(String s, String s2) { if(Objects.equals(s, s2)){ return 0; } return ORDERING.compare(s, s2); }

Target:
public int compare(String s, String s2) { if (s == s2) { return 0; } return ORDERING.compare(s, s2); }
Source:
public Response<ResponseBody> makeRequest() throws IOException { if(isAuthenticated && !new URL(url).getProtocol().contentEquals("https")){ throw new AuthenticationInterceptor.PlainTextPasswordException(); } if (!expectedUrlStack.isEmpty()) { assertUrlsEqual(expectedUrlStack.remove(0), buildUrlWithParams().toString()); } if (requestPayloadStack.isEmpty()) { return OkHTTPResponseMock.createResponse(responseCodeStack.remove(0)); } else { String payloadReference = requestPayloadStack.remove(0); if (payloadReference == null) { throw new IOException(ioErrorMessage); } else { InputStream payloadStream; try { payloadStream = ReferenceManager.instance().DeriveReference(payloadReference).getStream(); } catch (InvalidReferenceException ire) { throw new IOException("No payload available at " + payloadReference); } return OkHTTPResponseMock.createResponse(responseCodeStack.remove(0),payloadStream); } } }

Target:
public Response<ResponseBody> makeRequest() throws IOException { if (isAuthenticated && !new URL(url).getProtocol().contentEquals("https") && enforceSecureEndpointValidation) { throw new AuthenticationInterceptor.PlainTextPasswordException(); } if (!expectedUrlStack.isEmpty()) { assertUrlsEqual(expectedUrlStack.remove(0), buildUrlWithParams()); } if (requestPayloadStack.isEmpty()) { return OkHTTPResponseMockFactory.createResponse(responseCodeStack.remove(0)); } else { String payloadReference = requestPayloadStack.remove(0); if (payloadReference == null) { throw new IOException(ioErrorMessage); } else { InputStream payloadStream; try { payloadStream = ReferenceManager.instance().DeriveReference(payloadReference).getStream(); } catch (InvalidReferenceException ire) { throw new IOException("No payload available at " + payloadReference); } return OkHTTPResponseMockFactory.createResponse(responseCodeStack.remove(0), payloadStream); } } }
Source:
public void updateUserMetadata(final TokenDAO tokenDAO, TokenType source) { if (source == null) { if (!updateGoogleMetadata(tokenDAO) && !updateGithubMetadata(tokenDAO)) { throw new CustomWebApplicationException( "No GitHub or Google token found. Please link a GitHub or Google token to your account.", HttpStatus.SC_FORBIDDEN); } } else { switch (source) { case GOOGLE_COM: if (!updateGoogleMetadata(tokenDAO)) { throw new CustomWebApplicationException("No Google token found. Please link a Google token to your account.", HttpStatus.SC_FORBIDDEN); } break; case GITHUB_COM: if (!updateGithubMetadata(tokenDAO)) { throw new CustomWebApplicationException("No GitHub token found. Please link a GitHub token to your account.", HttpStatus.SC_FORBIDDEN); } break; default: throw new CustomWebApplicationException("Unrecognzied token type: " + source, HttpStatus.SC_BAD_REQUEST); } } }

Target:
public void updateUserMetadata(final TokenDAO tokenDAO, TokenType source) { if (source == null) { if (!updateGoogleMetadata(tokenDAO) && !updateGithubMetadata(tokenDAO)) { throw new CustomWebApplicationException( "No GitHub or Google token found. Please link a GitHub or Google token to your account.", HttpStatus.SC_FORBIDDEN); } } else { switch (source) { case GOOGLE_COM: if (!updateGoogleMetadata(tokenDAO)) { throw new CustomWebApplicationException("No Google token found. Please link a Google token to your account.", HttpStatus.SC_FORBIDDEN); } break; case GITHUB_COM: if (!updateGithubMetadata(tokenDAO)) { throw new CustomWebApplicationException("No GitHub token found. Please link a GitHub token to your account.", HttpStatus.SC_FORBIDDEN); } break; default: throw new CustomWebApplicationException("Unrecognized token type: " + source, HttpStatus.SC_BAD_REQUEST); } } }
Source:
private int getSubscriberIdBySubscriptionUUID(String subscriptionId) throws APIManagementException { Connection connection = null; ResultSet rs = null; PreparedStatement ps = null; int subscirberId = 0; try { connection = APIMgtDBUtil.getConnection(); String query = SQLConstants.GET_SUBSCRIBER_ID_BY_SUBSCRIPTION_UUID_SQL; ps = connection.prepareStatement(query); ps.setString(1, subscriptionId); rs = ps.executeQuery(); if (rs.next()) { subscirberId = rs.getInt(APIConstants.APPLICATION_SUBSCRIBER_ID); } } catch (SQLException e) { handleException("Error while retrieving Subscriber ID: ", e); } finally { APIMgtDBUtil.closeAllConnections(ps, connection, rs); } return subscirberId; }

Target:
private int getSubscriberIdBySubscriptionUUID(String subscriptionId) throws APIManagementException { int subscirberId = 0; String query = SQLConstants.GET_SUBSCRIBER_ID_BY_SUBSCRIPTION_UUID_SQL; try (Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement ps = connection.prepareStatement(query)) { ps.setString(1, subscriptionId); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { subscirberId = rs.getInt(APIConstants.APPLICATION_SUBSCRIBER_ID); } } } catch (SQLException e) { handleException("Error while retrieving Subscriber ID: ", e); } return subscirberId; }
Source:
public MockSettings useConstructor(Object... constructorArgs) { this.useConstructor = true; this.constructorArgs = constructorArgs; return this; }

Target:
public MockSettings useConstructor(Object... constructorArgs) { Checks.checkNotNull(constructorArgs, "constructorArgs", "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)"); this.useConstructor = true; this.constructorArgs = constructorArgs; return this; }
Source:
protected void send(final Message aMessage) { final Thread t = new Thread(new Runnable() { @Override public void run() { try { getMessageSender().handleSendMessage(aMessage); postSend(); } catch (IOException sslEx) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append(Constant.messages.getString("network.ssl.error.connect")); strBuilder.append(((HttpMessage) aMessage).getRequestHeader().getURI().toString()).append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.exception") + sslEx.getMessage()) .append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.help", Constant.messages.getString("network.ssl.error.help.url"))); logger.warn(strBuilder.toString()); if (logger.isDebugEnabled()) { logger.debug(sslEx, sslEx); } View.getSingleton().showWarningDialog(strBuilder.toString()); } catch (Exception e) { logger.warn(e.getMessage(), e); View.getSingleton().showWarningDialog(e.getMessage()); } finally { btnSend.setEnabled(true); } } }); t.setPriority(Thread.NORM_PRIORITY); t.start(); }

Target:
protected void send(final Message aMessage) { final Thread t = new Thread(new Runnable() { @Override public void run() { try { getMessageSender().handleSendMessage(aMessage); postSend(); } catch (SSLException sslEx) { StringBuilder strBuilder = new StringBuilder(); strBuilder.append(Constant.messages.getString("network.ssl.error.connect")); strBuilder.append(((HttpMessage) aMessage).getRequestHeader().getURI().toString()).append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.exception")).append(sslEx.getMessage()) .append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.exception.rootcause")) .append(ExceptionUtils.getRootCauseMessage(sslEx)).append('\n'); strBuilder.append(Constant.messages.getString("network.ssl.error.help", Constant.messages.getString("network.ssl.error.help.url"))); logger.warn(strBuilder.toString()); if (logger.isDebugEnabled()) { logger.debug(sslEx, sslEx); } View.getSingleton().showWarningDialog(strBuilder.toString()); } catch (Exception e) { logger.warn(e.getMessage(), e); View.getSingleton().showWarningDialog(e.getMessage()); } finally { btnSend.setEnabled(true); } } }); t.setPriority(Thread.NORM_PRIORITY); t.start(); }
Source:
private File getApnConfFile() { File confFile = new File(Environment.getRootDirectory(), PARTNER_APNS_PATH); File oemConfFile = new File(Environment.getOemDirectory(), OEM_APNS_PATH); File vendorConfFile = new File(Environment.getVendorDirectory(), PARTNER_APNS_PATH); File updatedConfFile = new File(Environment.getDataDirectory(), OTA_UPDATED_APNS_PATH); confFile = pickSecondIfExists(confFile, vendorConfFile); confFile = pickSecondIfExists(confFile, oemConfFile); confFile = pickSecondIfExists(confFile, updatedConfFile); return confFile; }

Target:
private File getApnConfFile() { File confFile = new File(Environment.getRootDirectory(), PARTNER_APNS_PATH); File oemConfFile = new File(Environment.getOemDirectory(), OEM_APNS_PATH); File updatedConfFile = new File(Environment.getDataDirectory(), OTA_UPDATED_APNS_PATH); confFile = pickSecondIfExists(confFile, oemConfFile); confFile = pickSecondIfExists(confFile, updatedConfFile); return confFile; }
Source:
@After public void agentCleanup() throws IOException, InterruptedException { if (s != null) { j.jenkins.removeNode(s); } if (BourneShellScript.FORCE_SHELL_WRAPPER) { BourneShellScript.FORCE_SHELL_WRAPPER = false; } }

Target:
@After public void agentCleanup() throws IOException, InterruptedException { if (s != null) { j.jenkins.removeNode(s); } BourneShellScript.FORCE_SHELL_WRAPPER = false; }
Source:
public synchronized float getPercentProgress() { if(writtenSize == 0) return 0f; return ((float) writtenSize / totalSize) * 100; }

Target:
public synchronized float getPercentProgress() { if(totalSize == 0) return 0f; return ((float) writtenSize / totalSize) * 100; }
Source:
public boolean verify(Write write, long timestamp, boolean exists) { for (Iterator<Write> it = iterator(write, timestamp); it.hasNext();) { this.numberOfVerifiesInitiated++; it.next(); exists ^= true; } return exists; }

Target:
public boolean verify(Write write, long timestamp, boolean exists) { numVerifyRequests.incrementAndGet(); for (Iterator<Write> it = iterator(write, timestamp); it.hasNext();) { it.next(); exists ^= true; } return exists; }
Source:
public void onDatastreamUpdate() { _log.info("Coordinator::onDatastreamUpdate is called"); synchronized (_assignedDatastreamTasks) { _datastreamCache.invalidateAllCache(); _assignedDatastreamTasks.values().forEach(task -> { Optional<DatastreamGroup> dg = _datastreamCache.getDatastreamGroups() .stream() .filter(x -> x.getTaskPrefix().equals(task.getTaskPrefix())) .findFirst(); dg.ifPresent(datastreamGroup -> ((DatastreamTaskImpl) task).setDatastreams(datastreamGroup.getDatastreams())); }); _forceOnAssignmentChange.set(true); _eventQueue.put(CoordinatorEvent.createHandleAssignmentChangeEvent()); } _log.info("Coordinator::onDatastreamUpdate completed successfully"); }

Target:
public void onDatastreamUpdate() { _log.info("Coordinator::onDatastreamUpdate is called"); synchronized (_assignedDatastreamTasks) { _datastreamCache.invalidateAllCache(); List<DatastreamGroup> datastreamGroups = _datastreamCache.getDatastreamGroups(); _assignedDatastreamTasks.values().forEach(task -> { Optional<DatastreamGroup> dg = datastreamGroups.stream().filter(x -> x.getTaskPrefix().equals(task.getTaskPrefix())).findFirst(); if (dg.isPresent()) { ((DatastreamTaskImpl) task).setDatastreams(dg.get().getDatastreams()); } else { _log.warn("Can't find datastream group for task {}", task); } }); } _eventQueue.put(CoordinatorEvent.createHandleDatastreamChangeEvent()); _log.info("Coordinator::onDatastreamUpdate completed successfully"); }
Source:
public void setUp() throws Exception { List<InternToken> internTokenList = new ArrayList<InternToken>(); InternFormulaTokenSelection internTokenSelection = new InternFormulaTokenSelection( TokenSelectionType.USER_SELECTION, 0, 1); internState = new InternFormulaState(internTokenList, null, 0); internStateToCompare = new InternFormulaState(internTokenList, internTokenSelection, 0); assertNotEquals(internState, internStateToCompare); internTokenList = new ArrayList<InternToken>(); internTokenList.add(new InternToken(InternTokenType.NUMBER)); internState = new InternFormulaState(internTokenList, null, 0); internTokenList = new ArrayList<InternToken>(); internTokenList.add(new InternToken(InternTokenType.FUNCTION_NAME)); internStateToCompare = new InternFormulaState(internTokenList, null, 0); }

Target:
public void setUp() throws Exception { List<InternToken> internTokenList = new ArrayList<InternToken>(); InternFormulaTokenSelection internTokenSelection = new InternFormulaTokenSelection( TokenSelectionType.USER_SELECTION, 0, 1); internState = new InternFormulaState(internTokenList, null, 0); unexpectedInternState = new InternFormulaState(internTokenList, internTokenSelection, 0); assertNotEquals(unexpectedInternState, internState); internTokenList = new ArrayList<InternToken>(); internTokenList.add(new InternToken(InternTokenType.NUMBER)); internState = new InternFormulaState(internTokenList, null, 0); internTokenList = new ArrayList<InternToken>(); internTokenList.add(new InternToken(InternTokenType.FUNCTION_NAME)); unexpectedInternState = new InternFormulaState(internTokenList, null, 0); }
Source:
public void initialize(TransformContext context) throws Exception { super.initialize(context); try { config.validate(); outSchema = Schema.parseJson(config.schema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format.", e); } }

Target:
public void initialize(TransformContext context) throws Exception { super.initialize(context); try { outSchema = Schema.parseJson(config.schema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format.", e); } }
Source:
public static void waitForStreamedAllocatedMemoryZero(Client client,Integer timeout) throws Exception { boolean passed = false; Instant maxTime = Instant.now().plusSeconds(timeout); VoltTable stats = null; try { System.out.println(client.callProcedure("@Quiesce").getResults()[0]); } catch (Exception ex) { } while (true) { if ( Instant.now().isAfter(maxTime) ) { throw new Exception("Test Timeout waiting for non-null Statistics" ); } try { stats = client.callProcedure("@Statistics", "table", 0).getResults()[0]; } catch (Exception ex) { } if (stats == null) { Thread.sleep(5000); continue; } boolean passedThisTime = true; while (stats.advanceRow()) { if ( Instant.now().isAfter(maxTime) ) { throw new Exception("Test Timeout expecting non-zero TUPLE_ALLOCATED_MEMORY" ); } String ttype = stats.getString("TABLE_TYPE"); if (ttype.equals("StreamedTable")) { if (0 != stats.getLong("TUPLE_ALLOCATED_MEMORY")) { passedThisTime = false; System.out.println("Partition Not Zero."); break; } } } if (passedThisTime) { passed = true; break; } Thread.sleep(5000); } System.out.println("Passed is: " + passed); System.out.println(stats); }

Target:
public static void waitForStreamedAllocatedMemoryZero(Client client,Integer timeout) throws Exception { boolean passed = false; Instant maxTime = Instant.now().plusSeconds(timeout); VoltTable stats = null; try { System.out.println(client.callProcedure("@Quiesce").getResults()[0]); } catch (Exception ex) { } while (true) { if ( Instant.now().isAfter(maxTime) ) { throw new Exception("Test Timeout waiting for non-null @Statistics call, " + "increase --timeout arg for slower tests" ); } try { stats = client.callProcedure("@Statistics", "table", 0).getResults()[0]; } catch (Exception ex) { } if (stats == null) { Thread.sleep(5000); continue; } boolean passedThisTime = true; while (stats.advanceRow()) { if ( Instant.now().isAfter(maxTime) ) { throw new Exception("Test Timeout expecting non-zero TUPLE_ALLOCATED_MEMORY Statistic, " + "increase --timeout arg for slower clients" ); } String ttype = stats.getString("TABLE_TYPE"); if (ttype.equals("StreamedTable")) { if (0 != stats.getLong("TUPLE_ALLOCATED_MEMORY")) { passedThisTime = false; System.out.println("Partition Not Zero."); break; } } } if (passedThisTime) { passed = true; break; } Thread.sleep(5000); } System.out.println("Passed is: " + passed); System.out.println(stats); }
Source:
public Optional<PlanNode> apply(PlanNode node, Context context) { TableScanNode tableScanNode = (TableScanNode) node; if (tableScanNode.getOriginalConstraint() != null) { Expression rewrittenOriginalContraint = rewriter.rewrite(tableScanNode.getOriginalConstraint(), context); if (!tableScanNode.getOriginalConstraint().equals(rewrittenOriginalContraint)) { return Optional.of(new TableScanNode( tableScanNode.getId(), tableScanNode.getTable(), tableScanNode.getOutputSymbols(), tableScanNode.getAssignments(), tableScanNode.getLayout(), tableScanNode.getCurrentConstraint(), rewrittenOriginalContraint)); } } return Optional.empty(); }

Target:
public Optional<PlanNode> apply(PlanNode node, Context context) { TableScanNode tableScanNode = (TableScanNode) node; if (tableScanNode.getOriginalConstraint() == null) { return Optional.empty(); } Expression rewrittenOriginalContraint = rewriter.rewrite(tableScanNode.getOriginalConstraint(), context); if (!tableScanNode.getOriginalConstraint().equals(rewrittenOriginalContraint)) { return Optional.of(new TableScanNode( tableScanNode.getId(), tableScanNode.getTable(), tableScanNode.getOutputSymbols(), tableScanNode.getAssignments(), tableScanNode.getLayout(), tableScanNode.getCurrentConstraint(), rewrittenOriginalContraint)); } return Optional.empty(); }
Source:
public void addTreeWalk(TreeWalk walk) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { if (done) throw new IllegalStateException(JGitText.get().renamesAlreadyFound); MutableObjectId idBuf = new MutableObjectId(); while (walk.next()) { DiffEntry entry = new DiffEntry(); walk.getObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.fromObjectId(idBuf); walk.getObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.fromObjectId(idBuf); entry.oldMode = walk.getFileMode(0); entry.newMode = walk.getFileMode(1); entry.newName = entry.oldName = walk.getPathString(); if (walk.getFileMode(0) == FileMode.MISSING) { entry.changeType = ChangeType.ADD; added.add(entry); } else if (walk.getFileMode(1) == FileMode.MISSING) { entry.changeType = ChangeType.DELETE; deleted.add(entry); } else { entry.changeType = ChangeType.MODIFY; entries.add(entry); } } }

Target:
public void addTreeWalk(TreeWalk walk) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { if (done) throw new IllegalStateException(JGitText.get().renamesAlreadyFound); MutableObjectId idBuf = new MutableObjectId(); while (walk.next()) { DiffEntry entry = new DiffEntry(); walk.getObjectId(idBuf, 0); entry.oldId = AbbreviatedObjectId.fromObjectId(idBuf); walk.getObjectId(idBuf, 1); entry.newId = AbbreviatedObjectId.fromObjectId(idBuf); entry.oldMode = walk.getFileMode(0); entry.newMode = walk.getFileMode(1); entry.newName = entry.oldName = walk.getPathString(); if (entry.oldMode == FileMode.MISSING) { entry.changeType = ChangeType.ADD; added.add(entry); } else if (entry.newMode == FileMode.MISSING) { entry.changeType = ChangeType.DELETE; deleted.add(entry); } else { entry.changeType = ChangeType.MODIFY; entries.add(entry); } } }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> { subscriptionContext = ctx; FileInput fileInput = (FileInput) ctx.syntaxNode(); ExceptionVisitor exceptionVisitor = new ExceptionVisitor(); fileInput.accept(exceptionVisitor); hasWildcardImport = exceptionVisitor.hasWildcardImport; callGlobalsOrLocals = exceptionVisitor.callGlobalsOrLocals; nameIssues.clear(); ignoredSymbols.clear(); }); context.registerSyntaxNodeConsumer(Tree.Kind.NAME, ctx -> { Name name = (Name) ctx.syntaxNode(); if (!callGlobalsOrLocals && !hasWildcardImport && name.isVariable() && name.symbol() == null) { List<Name> names = nameIssues.getOrDefault(name.name(), new ArrayList<>()); names.add(name); nameIssues.putIfAbsent(name.name(), names); } }); context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { addNameIssues(); ignoredSymbols.clear(); FunctionDef functionDef = (FunctionDef) ctx.syntaxNode(); if (TreeUtils.hasDescendant(functionDef, tree -> tree.is(Tree.Kind.TRY_STMT))) { return; } ControlFlowGraph cfg = ControlFlowGraph.build(functionDef, ctx.pythonFile()); if (cfg == null) { return; } DefinedVariablesAnalysis analysis = DefinedVariablesAnalysis.analyze(cfg, functionDef.localVariables()); Set<CfgBlock> unreachableBlocks = CfgUtils.unreachableBlocks(cfg); cfg.blocks().forEach(block -> checkCfgBlock(block, ctx, analysis.getDefinedVariables(block), unreachableBlocks, analysis)); }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> { FileInput fileInput = (FileInput) ctx.syntaxNode(); UnresolvedSymbolsVisitor unresolvedSymbolsVisitor = new UnresolvedSymbolsVisitor(); fileInput.accept(unresolvedSymbolsVisitor); if (!unresolvedSymbolsVisitor.callGlobalsOrLocals && !unresolvedSymbolsVisitor.hasWildcardImport) { addNameIssues(unresolvedSymbolsVisitor.nameIssues, ctx); } }); context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, ctx -> { List<Symbol> ignoredSymbols = new ArrayList<>(); FunctionDef functionDef = (FunctionDef) ctx.syntaxNode(); if (TreeUtils.hasDescendant(functionDef, tree -> tree.is(Tree.Kind.TRY_STMT))) { return; } ControlFlowGraph cfg = ControlFlowGraph.build(functionDef, ctx.pythonFile()); if (cfg == null) { return; } DefinedVariablesAnalysis analysis = DefinedVariablesAnalysis.analyze(cfg, functionDef.localVariables()); Set<CfgBlock> unreachableBlocks = CfgUtils.unreachableBlocks(cfg); cfg.blocks().forEach(block -> checkCfgBlock(block, ctx, analysis.getDefinedVariables(block), unreachableBlocks, analysis, ignoredSymbols)); }); }
Source:
private void assertDiskDescriptionMap(String diskAlias, String diskDescription) throws IOException { assertEquals("Should be map of disk alias and disk description", String.format("{\"DiskAlias\":\"%s\"," + "\"DiskDescription\":\"%s\"}", diskAlias, StringUtils.defaultString(diskDescription)), ImagesHandler.getJsonDiskDescription(diskAlias, diskDescription)); }

Target:
private static void assertDiskDescriptionMap(String diskAlias, String diskDescription) throws IOException { assertEquals("Should be map of disk alias and disk description", String.format("{\"DiskAlias\":\"%s\"," + "\"DiskDescription\":\"%s\"}", diskAlias, StringUtils.defaultString(diskDescription)), ImagesHandler.getJsonDiskDescription(diskAlias, diskDescription)); }