auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void updateAccountElements() { TextView userNameView = (TextView)findViewById(R.id.username_text); LoginManager loginManager = App.getLoginManager(); if (loginManager.isLoggedIn()) { findViewById(R.id.have_account_text).setVisibility(View.GONE); findViewById(R.id.login_button).setVisibility(View.GONE); try { userNameView.setText(makeUserNameString(loginManager.loggedInUser.getUserName())); userNameView.setVisibility(View.VISIBLE); } catch (JSONException e) { e.printStackTrace(); } findViewById(R.id.logout_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.have_account_text).setVisibility(View.VISIBLE); findViewById(R.id.login_button).setVisibility(View.VISIBLE); userNameView.setVisibility(View.GONE); findViewById(R.id.logout_button).setVisibility(View.GONE); } }

Target:
private void updateAccountElements() { TextView userNameView = (TextView) findViewById(R.id.username_text); LoginManager loginManager = App.getLoginManager(); if (loginManager.isLoggedIn()) { findViewById(R.id.have_account_text).setVisibility(View.GONE); findViewById(R.id.login_button).setVisibility(View.GONE); try { userNameView.setText(makeUserNameString(loginManager.loggedInUser.getUserName())); userNameView.setVisibility(View.VISIBLE); } catch (JSONException e) { Log.e(App.LOG_TAG, "Could not get username.", e); } findViewById(R.id.logout_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.have_account_text).setVisibility(View.VISIBLE); findViewById(R.id.login_button).setVisibility(View.VISIBLE); userNameView.setVisibility(View.GONE); findViewById(R.id.logout_button).setVisibility(View.GONE); } }
Source:
public synchronized void start() { if (isRunning.getAndSet(true) && !isClosed.getAndSet(false)) { logger.info("Processor is already running"); return; } receiveMessages(); if (this.scheduledExecutor == null) { this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } }

Target:
public synchronized void start() { if (isRunning.getAndSet(true)) { logger.info("Processor is already running"); return; } if (asyncClient.get() == null) { ServiceBusReceiverAsyncClient newReceiverClient = this.receiverBuilder == null ? this.sessionReceiverBuilder.buildAsyncClientForProcessor() : this.receiverBuilder.buildAsyncClient(); asyncClient.set(newReceiverClient); } receiveMessages(); if (this.scheduledExecutor == null) { this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); scheduledExecutor.scheduleWithFixedDelay(() -> { if (this.asyncClient.get().isConnectionClosed()) { restartMessageReceiver(); } }, SCHEDULER_INTERVAL_IN_SECONDS, SCHEDULER_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); } }
Source:
public void handle(Callback[] callbacks) throws UnsupportedCallbackException { NameCallback nc = null; PasswordCallback pc = null; AuthorizeCallback ac = null; for (Callback callback : callbacks) { if (callback instanceof AuthorizeCallback) { ac = (AuthorizeCallback) callback; } else if (callback instanceof NameCallback) { nc = (NameCallback) callback; } else if (callback instanceof PasswordCallback) { pc = (PasswordCallback) callback; } else if (callback instanceof RealmCallback) { } else { throw new UnsupportedCallbackException(callback, "Unrecognized SASL Callback"); } } String userName = "UNKNOWN"; if (nc != null) { LOG.debug("handleNameCallback"); userName = nc.getDefaultName(); nc.setName(nc.getDefaultName()); } if (pc != null) { LOG.error("No password found for user: {}, validate klist matches jaas conf", userName); } if (ac != null) { @SuppressWarnings("checkstyle:AbbreviationAsWordInName") String authenticationID = ac.getAuthenticationID(); LOG.debug("Successfully authenticated client: authenticationID={} authorizationID= {}", authenticationID, ac.getAuthorizationID()); if (ac.getAuthorizationID() == null) { ac.setAuthorizedID(authenticationID); } if (!ac.getAuthenticationID().equals(ac.getAuthorizationID())) { if (!impersonationAllowed) { throw new IllegalArgumentException(ac.getAuthenticationID() + " attempting to impersonate " + ac.getAuthorizationID() + ". This is not allowed by this server."); } ReqContext.context().setRealPrincipal(new SaslTransportPlugin.User(ac.getAuthenticationID())); } else { ReqContext.context().setRealPrincipal(null); } ac.setAuthorized(true); } }

Target:
public void handle(Callback[] callbacks) throws UnsupportedCallbackException { NameCallback nc = null; PasswordCallback pc = null; AuthorizeCallback ac = null; for (Callback callback : callbacks) { if (callback instanceof AuthorizeCallback) { ac = (AuthorizeCallback) callback; } else if (callback instanceof NameCallback) { nc = (NameCallback) callback; } else if (callback instanceof PasswordCallback) { pc = (PasswordCallback) callback; } else if (callback instanceof RealmCallback) { } else { throw new UnsupportedCallbackException(callback, "Unrecognized SASL Callback"); } } String userName = "UNKNOWN"; if (nc != null) { LOG.debug("handleNameCallback"); userName = nc.getDefaultName(); nc.setName(nc.getDefaultName()); } if (pc != null) { LOG.error("No password found for user: {}, validate klist matches jaas conf", userName); } if (ac != null) { String authenticationId = ac.getAuthenticationID(); LOG.debug("Successfully authenticated client: authenticationID={} authorizationID= {}", authenticationId, ac.getAuthorizationID()); if (ac.getAuthorizationID() == null) { ac.setAuthorizedID(authenticationId); } if (!ac.getAuthenticationID().equals(ac.getAuthorizationID())) { if (!impersonationAllowed) { throw new IllegalArgumentException(ac.getAuthenticationID() + " attempting to impersonate " + ac.getAuthorizationID() + ". This is not allowed by this server."); } ReqContext.context().setRealPrincipal(new SaslTransportPlugin.User(ac.getAuthenticationID())); } else { ReqContext.context().setRealPrincipal(null); } ac.setAuthorized(true); } }
Source:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GetGeoDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; initialiseMaxMindGeocode(null); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }

Target:
public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if (arguments.length != 1) { throw new UDFArgumentLengthException("The GetGeoDataUDF takes an array with only 1 element as argument"); } ObjectInspector arg1 = arguments[0]; if (arg1.getCategory() != Category.PRIMITIVE) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arg1).getPrimitiveCategory(); if (primitiveCategory != PrimitiveCategory.STRING) { throw new UDFArgumentTypeException(0, "A string argument was expected but an argument of type " + arg1.getTypeName() + " was given."); } argumentOI = arg1; initialiseMaxMindReader(); return ObjectInspectorFactory.getStandardMapObjectInspector( PrimitiveObjectInspectorFactory.javaStringObjectInspector, PrimitiveObjectInspectorFactory.javaStringObjectInspector); }
Source:
private Type createParameterizedType(AST ast, ITypeBinding typeBinding) { if (typeBinding.isParameterizedType() && !typeBinding.isRawType()) { Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); ParameterizedType newType= ast.newParameterizedType(baseType); for (int i= 0; i < typeBinding.getTypeArguments().length; i++) { ITypeBinding typeArg= typeBinding.getTypeArguments()[i]; Type argType= createParameterizedType(ast, typeArg); newType.typeArguments().add(argType); } return newType; } else { if (!typeBinding.isTypeVariable()) { if (typeBinding.isWildcardType()) { String newName= typeBinding.isUpperbound() ? typeBinding.getErasure().getName() : typeBinding.getBound().getName(); WildcardType newWildcardType= ast.newWildcardType(); newWildcardType.setBound(ast.newSimpleType(ast.newSimpleName(newName)), typeBinding.isUpperbound()); return newWildcardType; } return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); } return ast.newSimpleType(ast.newSimpleName(typeBinding.getName())); } }

Target:
private Type createParameterizedType(AST ast, ITypeBinding typeBinding) { if (typeBinding.isParameterizedType() && !typeBinding.isRawType()) { Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); ParameterizedType newType= ast.newParameterizedType(baseType); for (int i= 0; i < typeBinding.getTypeArguments().length; i++) { ITypeBinding typeArg= typeBinding.getTypeArguments()[i]; Type argType= createParameterizedType(ast, typeArg); newType.typeArguments().add(argType); } return newType; } else { if (!typeBinding.isTypeVariable()) { if (typeBinding.isWildcardType()) { String newName= typeBinding.getBound().getName(); WildcardType newWildcardType= ast.newWildcardType(); newWildcardType.setBound(ast.newSimpleType(ast.newSimpleName(newName)), typeBinding.isUpperbound()); return newWildcardType; } return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName())); } return ast.newSimpleType(ast.newSimpleName(typeBinding.getName())); } }
Source:
public void sendEmail(String receiverEmail, String subject, String message) throws MessagingException { Properties props = buildProperties(); try { Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail,senderPassword); } }); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(senderEmail)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverEmail, false)); msg.setSubject(subject); msg.setText(message); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { throw e; } }

Target:
public void sendEmail(String receiverEmail, String subject, String message) throws MessagingException { Properties props = buildProperties(); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail, senderPassword); } }); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(senderEmail)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverEmail, false)); msg.setSubject(subject); msg.setText(message); msg.setSentDate(new Date()); Transport.send(msg); }
Source:
protected void createFile(FileVersion reconstructedFileVersion) throws IOException { File reconstructedFileInCache; try { reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); }

Target:
protected void createFile(FileVersion reconstructedFileVersion) throws IOException { try { File reconstructedFileInCache = assembleFileToCache(reconstructedFileVersion); moveFileToFinalLocation(reconstructedFileInCache, reconstructedFileVersion); } catch (NoSuchAlgorithmException | ChecksumMismatchException e) { throw new IOException(e); } }
Source:
protected void endSuccessfully() { RunVmParams runVmParams = getChildRunVmParameters(); if (runVmParams != null) { setVmId(runVmParams.getVmId()); if (getSnapshotDao().exists(getVmId(), SnapshotType.STATELESS)) { setSucceeded(Backend.getInstance().endAction(VdcActionType.RunVm, runVmParams, cloneContext().withoutLock().withoutExecutionContext()).getSucceeded()); if (!getSucceeded()) { log.warn("endSuccessfully: endAction of RunVm failed, detaching user from Vm"); detachUserFromVmFromPool(); getReturnValue().setEndActionTryAgain(false); } } else { log.warn("endSuccessfully: No images were created for Vm, detaching user from Vm"); detachUserFromVmFromPool(); getReturnValue().setEndActionTryAgain(false); } } else { setCommandShouldBeLogged(false); log.warn("endSuccessfully: Vm is null - not performing full endAction"); setSucceeded(true); } }

Target:
protected void endSuccessfully() { RunVmParams runVmParams = getChildRunVmParameters(); if (runVmParams != null) { setVmId(runVmParams.getVmId()); if (!isRunVmSucceeded()) { log.warn("endSuccessfully: RunVm failed, detaching user from VM"); detachUserFromVmFromPool(); getReturnValue().setEndActionTryAgain(false); } } else { setCommandShouldBeLogged(false); log.warn("endSuccessfully: VM is null"); } setSucceeded(true); }
Source:
private Map<String, Object> serializeStackframe(StackTraceElement el, List<String> projectPackages) { Map<String, Object> map = new HashMap<>(); try { String methodName; if (el.getClassName().length() > 0) { methodName = el.getClassName() + "." + el.getMethodName(); } else { methodName = el.getMethodName(); } map.put("method", methodName); String filename = el.getFileName() == null ? "Unknown" : el.getFileName(); map.put("file", filename); map.put("lineNumber", el.getLineNumber()); if (inProject(el.getClassName(), projectPackages)) { map.put("inProject", true); } return map; } catch (Exception lineEx) { return null; } }

Target:
private Map<String, Object> serializeStackframe(StackTraceElement el, List<String> projectPackages) { Map<String, Object> map = new HashMap<>(); try { String methodName; if (el.getClassName().length() > 0) { methodName = el.getClassName() + "." + el.getMethodName(); } else { methodName = el.getMethodName(); } map.put("method", methodName); String filename = el.getFileName() == null ? "Unknown" : el.getFileName(); map.put("file", filename); map.put("lineNumber", el.getLineNumber()); if (inProject(el.getClassName(), projectPackages)) { map.put("inProject", true); } return map; } catch (Exception lineEx) { Logger.warn("Failed to serialize stacktrace", lineEx); return null; } }
Source:
public void drafts() throws Exception { PushOneCommit.Result r = createChange(); DraftInput in = new DraftInput(); in.line = 1; in.message = "nit: trailing hitespace"; in.path = FILE_NAME; DraftApi draftApi = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .createDraft(in); assertThat(draftApi .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .hasSize(1); in.message = "good catch!"; assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .update(in) .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .author .email) .isEqualTo(admin.email); draftApi.delete(); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .isEmpty(); }

Target:
public void drafts() throws Exception { PushOneCommit.Result r = createChange(); DraftInput in = new DraftInput(); in.line = 1; in.message = "nit: trailing whitespace"; in.path = FILE_NAME; DraftApi draftApi = gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .createDraft(in); assertThat(draftApi .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .hasSize(1); in.message = "good catch!"; assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .update(in) .message) .isEqualTo(in.message); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .draft(draftApi.get().id) .get() .author .email) .isEqualTo(admin.email); draftApi.delete(); assertThat(gApi.changes() .id(r.getChangeId()) .revision(r.getCommit().name()) .drafts()) .isEmpty(); }
Source:
public static void writeSegmentDescriptor( final FileSystem outputFS, final DataSegment segment, final Path descriptorPath, final FileContext fileContext, final Progressable progressable ) throws IOException { final DataPusher descriptorPusher = (DataPusher) RetryProxy.create( DataPusher.class, new DataPusher() { @Override public void push() throws IOException { try { progressable.progress(); if (outputFS.exists(descriptorPath)) { if (!fileContext.delete(descriptorPath, false)) { throw new IOException(String.format("Failed to delete descriptor at [%s]", descriptorPath)); } } try (final OutputStream descriptorOut = fileContext.create( descriptorPath, EnumSet.of(CreateFlag.OVERWRITE, CreateFlag.CREATE), Options.CreateOpts.bufferSize(256 * 1024), Options.CreateOpts.createParent() )) { HadoopDruidIndexerConfig.jsonMapper.writeValue(descriptorOut, segment); descriptorOut.flush(); } } catch (RuntimeException | IOException ex) { log.info(ex, "Error in retry loop"); throw ex; } } }, RetryPolicies.retryUpToMaximumCountWithFixedSleep(6, 10, TimeUnit.SECONDS) ); descriptorPusher.push(); }

Target:
public static void writeSegmentDescriptor( final FileSystem outputFS, final DataSegment segment, final Path descriptorPath, final FileContext fileContext, final Progressable progressable ) throws IOException { final DataPusher descriptorPusher = (DataPusher) RetryProxy.create( DataPusher.class, new DataPusher() { @Override public void push() throws IOException { try { progressable.progress(); if (outputFS.exists(descriptorPath)) { if (!fileContext.delete(descriptorPath, false)) { throw new IOException(String.format("Failed to delete descriptor at [%s]", descriptorPath)); } } try (final OutputStream descriptorOut = fileContext.create( descriptorPath, EnumSet.of(CreateFlag.OVERWRITE, CreateFlag.CREATE), Options.CreateOpts.bufferSize(256 * 1024), Options.CreateOpts.createParent() )) { HadoopDruidIndexerConfig.jsonMapper.writeValue(descriptorOut, segment); descriptorOut.flush(); } } catch (RuntimeException | IOException ex) { log.info(ex, "Error in retry loop"); throw ex; } } }, RetryPolicies.retryUpToMaximumCountWithFixedSleep(NUM_RETRIES, SECONDS_BETWEEN_RETRIES, TimeUnit.SECONDS) ); descriptorPusher.push(); }
Source:
public URI getWebUri() { if (webUri == null) { try { webUri = new URI("http://localhost:8080"); } catch (URISyntaxException e) { throw new RuntimeException(e); } try { if (undertowSubsystem == null) { ModelNode address = new ModelNode(); address.add("subsystem", UNDERTOW); undertowSubsystem = readResource(address); } } catch (Exception e) { undertowSubsystem = new ModelNode(); } if (undertowSubsystem.isDefined()) { List<Property> vhosts = undertowSubsystem.get("server").asPropertyList(); ModelNode socketBinding = new ModelNode(); if (!vhosts.isEmpty()) { socketBinding = vhosts.get(0).getValue().get("http-listener", "default").get("socket-binding"); } if (socketBinding.isDefined()) { webUri = getBinding("http", socketBinding.asString()); } } } return webUri; }

Target:
public URI getWebUri() { if (webUri == null) { try { webUri = new URI("http://localhost:8080"); } catch (URISyntaxException e) { throw new RuntimeException(e); } try { if (undertowSubsystem == null) { ModelNode address = new ModelNode(); address.add("subsystem", UNDERTOW); undertowSubsystem = readResource(address); } } catch (Exception e) { logger.warn("Unable to retrieve Undertow configuration from server"); undertowSubsystem = new ModelNode(); } if (undertowSubsystem.isDefined()) { List<Property> vhosts = undertowSubsystem.get("server").asPropertyList(); ModelNode socketBinding = new ModelNode(); if (!vhosts.isEmpty()) { socketBinding = vhosts.get(0).getValue().get("http-listener", "default").get("socket-binding"); } if (socketBinding.isDefined()) { webUri = getBinding("http", socketBinding.asString()); } } } return webUri; }
Source:
private boolean connectToUserSelectNetwork(int netId, int uid) { if (!mWifiConfigManager.enableNetwork(netId, true, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to enable=" + netId); return false; } if (!mWifiConfigManager.checkAndUpdateLastConnectUid(netId, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to connect=" + netId); mWifiConnectivityManager.forceConnectivityScan(); } else { mWifiConnectivityManager.setUserConnectChoice(netId); if (SupplicantState.isConnecting(mWifiInfo.getSupplicantState()) && mWifiInfo.getNetworkId() == netId) { logi("connectToUserSelectNetwork already connecting/connected=" + netId); } else { startConnectToNetwork(netId, SUPPLICANT_BSSID_ANY); } } return true; }

Target:
private boolean connectToUserSelectNetwork(int netId, int uid) { if (!mWifiConfigManager.enableNetwork(netId, true, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to enable=" + netId); return false; } if (!mWifiConfigManager.checkAndUpdateLastConnectUid(netId, uid)) { loge("connectToUserSelectNetwork uid " + uid + " did not have the permissions to connect=" + netId); mWifiConnectivityManager.forceConnectivityScan(); } else { mWifiConnectivityManager.setUserConnectChoice(netId); if (mWifiInfo.getNetworkId() == netId) { logi("connectToUserSelectNetwork already connecting/connected=" + netId); } else { startConnectToNetwork(netId, SUPPLICANT_BSSID_ANY); } } return true; }
Source:
public ListWorkflowInstanceResponse fetchWorkflowInstance( @ApiParam("Internal id for workflow instance") @PathParam("id") int id, @QueryParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include) { Collection<ListWorkflowInstanceResponse> instances = listWorkflowInstances(Arrays.asList(id), Collections.<String>emptyList(), null, null, Collections.<String>emptyList(), Collections.<WorkflowInstanceStatus>emptyList(), null, null, include, 1L); if (instances.isEmpty()) { throw new NotFoundException(format("Workflow instance %s not found", id)); } return instances.iterator().next(); }

Target:
public ListWorkflowInstanceResponse fetchWorkflowInstance( @ApiParam("Internal id for workflow instance") @PathParam("id") int id, @QueryParam("include") @ApiParam(value = INCLUDE_PARAM_DESC, allowableValues = INCLUDE_PARAM_VALUES, allowMultiple = true) String include) { Collection<ListWorkflowInstanceResponse> instances = listWorkflowInstances(asList(id), Collections.<String>emptyList(), null, null, Collections.<String>emptyList(), Collections.<WorkflowInstanceStatus>emptyList(), null, null, include, 1L); if (instances.isEmpty()) { throw new NotFoundException(format("Workflow instance %s not found", id)); } return instances.iterator().next(); }
Source:
public void testArrayRemoveFunctionBigint() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); String tableName = initTables(conn); ResultSet rs; rs = conn.createStatement().executeQuery("SELECT ARRAY_REMOVE(bigints,56) FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); assertTrue(rs.next()); Long[] longs = new Long[]{12l, 34l, 78l, 910l}; Array array = conn.createArrayOf("BIGINT", longs); assertEquals(array, rs.getArray(1)); assertFalse(rs.next()); }

Target:
public void testArrayRemoveFunctionBigint() throws Exception { ResultSet rs = conn.createStatement().executeQuery( "SELECT ARRAY_REMOVE(bigints,56),bigints FROM " + tableName + " WHERE region_name = 'SF Bay Area'"); assertTrue(rs.next()); assertEquals(conn.createArrayOf("BIGINT", new Long[] { 12l, 34l, 78l, 910l }), rs.getArray(1)); assertEquals(conn.createArrayOf("BIGINT", new Long[] { 12l, 34l, 56l, 78l, 910l }), rs.getArray(2)); assertFalse(rs.next()); }
Source:
synchronized public void updateExportingLabel() { String text = lblExporting.getText(); if (text.equals(EXPORTING_DOT_ETC)) { text = "Exporting."; } else { text += "."; } lblExporting.setText(text); scheduledHideExportingLabel.ifPresent(scheduledFuture -> scheduledFuture.cancel(false)); scheduledHideExportingLabel = Optional.of(SCHEDULED_EXECUTOR.schedule(this::hideExporting, 5, TimeUnit.SECONDS)); }

Target:
synchronized public void updateExportingLabel() { String text = exportingLabel.getText(); if (text.equals(EXPORTING_DOT_ETC)) { text = "Exporting."; } else { text += "."; } exportingLabel.setText(text); scheduledHideExportingLabel.ifPresent(scheduledFuture -> scheduledFuture.cancel(false)); scheduledHideExportingLabel = Optional.of(SCHEDULED_EXECUTOR.schedule(this::hideExporting, 3, SECONDS)); }
Source:
public void assertCglibProxyForGetTarget() { ElasticJob target = new TargetJob(); ProxyFactory pf = new ProxyFactory(target); pf.setProxyTargetClass(true); ElasticJob proxy = (ElasticJob) pf.getProxy(); assertTrue(AopUtils.isCglibProxy(proxy)); assertEquals(AopTargetUtils.getTarget(proxy), target); }

Target:
public void assertCglibProxyForGetTarget() { ElasticJob target = new TargetJob(); ProxyFactory pf = new ProxyFactory(target); pf.setProxyTargetClass(true); ElasticJob proxy = (ElasticJob) pf.getProxy(); assertTrue(AopUtils.isCglibProxy(proxy)); assertThat(AopTargetUtils.getTarget(proxy), is(target)); }
Source:
public List<MoneyItem> moneyToItems(float amount) { return moneyToItems(amount, -1); }

Target:
public List<MoneyItem> moneyToItems(float amount) { return moneyToItems(amount, 60); }
Source:
private SymbolStatsEstimate buildSymbolStatistics(List<Object> values, Session session, Type type) { List<Object> nonNullValues = values.stream() .filter(Objects::nonNull) .collect(toImmutableList()); if (nonNullValues.isEmpty()) { return SymbolStatsEstimate.builder() .setLowValue(Double.NaN) .setHighValue(Double.NaN) .setNullsFraction(values.isEmpty() ? 0.0 : 1.0) .setDistinctValuesCount(0.0) .build(); } else { double[] valuesAsDoubles = nonNullValues.stream() .map(value -> toStatsRepresentation(metadata, session, type, value)) .filter(OptionalDouble::isPresent) .mapToDouble(OptionalDouble::getAsDouble) .toArray(); double lowValue = DoubleStream.of(valuesAsDoubles).min().orElse(Double.NEGATIVE_INFINITY); double highValue = DoubleStream.of(valuesAsDoubles).max().orElse(Double.POSITIVE_INFINITY); double valuesCount = values.size(); double nonNullValuesCount = nonNullValues.size(); long distinctValuesCount = nonNullValues.stream().distinct().count(); return SymbolStatsEstimate.builder() .setNullsFraction((valuesCount - nonNullValuesCount) / valuesCount) .setLowValue(lowValue) .setHighValue(highValue) .setDistinctValuesCount(distinctValuesCount) .build(); } }

Target:
private SymbolStatsEstimate buildSymbolStatistics(List<Object> values, Session session, Type type) { List<Object> nonNullValues = values.stream() .filter(Objects::nonNull) .collect(toImmutableList()); if (nonNullValues.isEmpty()) { return SymbolStatsEstimate.ZERO_STATS; } double[] valuesAsDoubles = nonNullValues.stream() .map(value -> toStatsRepresentation(metadata, session, type, value)) .filter(OptionalDouble::isPresent) .mapToDouble(OptionalDouble::getAsDouble) .toArray(); double lowValue = DoubleStream.of(valuesAsDoubles).min().orElse(Double.NEGATIVE_INFINITY); double highValue = DoubleStream.of(valuesAsDoubles).max().orElse(Double.POSITIVE_INFINITY); double valuesCount = values.size(); double nonNullValuesCount = nonNullValues.size(); long distinctValuesCount = nonNullValues.stream().distinct().count(); return SymbolStatsEstimate.builder() .setNullsFraction((valuesCount - nonNullValuesCount) / valuesCount) .setLowValue(lowValue) .setHighValue(highValue) .setDistinctValuesCount(distinctValuesCount) .build(); }
Source:
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { if (msg.getResponseBody().length() == 0 || !msg.getResponseHeader().isHtml()) { return; } List<Element> links = source.getAllElements(HTMLElementName.A); for (Element link : links) { if (_BLANK.equals(link.getAttributeValue(TARGET_ATTRIBUTE))) { if (!NOOPENER.equals(link.getAttributeValue(REL_ATTRIBUTE))) { Alert alert = new Alert(getPluginId(), Alert.RISK_MEDIUM, Alert.CONFIDENCE_MEDIUM, getName()); alert.setDetail( getDescription(), msg.getRequestHeader().getURI().toString(), "", "", "", getSolution(), getReference(), link.toString(), 0, 0, msg); parent.raiseAlert(id, alert); return; } } } }

Target:
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { if (msg.getResponseBody().length() == 0 || !msg.getResponseHeader().isHtml()) { return; } String host = msg.getRequestHeader().getHostName(); List<Context> contextList = getModel().getSession().getContextsForUrl(msg.getRequestHeader().getURI().toString()); for (Element link : source.getAllElements(HTMLElementName.A)) { if (this.isLinkFromOtherDomain(host, link.getAttributeValue("href"), contextList)) { if (this.checkElement(link, msg, id)) { return; } } } for (Element link : source.getAllElements(HTMLElementName.AREA)) { if (this.isLinkFromOtherDomain(host, link.getAttributeValue("href"), contextList)) { if (this.checkElement(link, msg, id)) { return; } } } }
Source:
private void sortDuplicatePatients(List<Patient> patients, List<Integer> patientIds) { Map<Integer, Integer> patientIdOrder = new HashMap<Integer, Integer>(); int startPos = 0; for (Integer id : patientIds) { patientIdOrder.put(id, startPos++); } class PatientIdComparator implements Comparator<Patient> { private Map<Integer, Integer> sortOrder; public PatientIdComparator(Map<Integer, Integer> sortOrder) { this.sortOrder = sortOrder; } @Override public int compare(Patient i1, Patient i2) { Integer weekdayPos1 = sortOrder.get(i1.getPatientId()); if (weekdayPos1 == null) { throw new IllegalArgumentException("Bad patient encountered: " + i1.getPatientId()); } Integer weekdayPos2 = sortOrder.get(i2.getPatientId()); if (weekdayPos2 == null) { throw new IllegalArgumentException("Bad patient encountered: " + i2.getPatientId()); } return weekdayPos1.compareTo(weekdayPos2); } } Collections.sort(patients, new PatientIdComparator(patientIdOrder)); }

Target:
private void sortDuplicatePatients(List<Patient> patients, List<Integer> patientIds) { Map<Integer, Integer> patientIdOrder = new HashMap<Integer, Integer>(); int startPos = 0; for (Integer id : patientIds) { patientIdOrder.put(id, startPos++); } class PatientIdComparator implements Comparator<Patient> { private Map<Integer, Integer> sortOrder; public PatientIdComparator(Map<Integer, Integer> sortOrder) { this.sortOrder = sortOrder; } @Override public int compare(Patient patient1, Patient patient2) { Integer patPos1 = sortOrder.get(patient1.getPatientId()); if (patPos1 == null) { throw new IllegalArgumentException("Bad patient encountered: " + patient1.getPatientId()); } Integer patPos2 = sortOrder.get(patient2.getPatientId()); if (patPos2 == null) { throw new IllegalArgumentException("Bad patient encountered: " + patient2.getPatientId()); } return patPos1.compareTo(patPos2); } } Collections.sort(patients, new PatientIdComparator(patientIdOrder)); }
Source:
public WMSCoverageReader(WebMapServer wms, Layer layer, String style, String preferredFormat) { this.wms = wms; addLayer(layer, style); List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats(); this.format = preferredFormat; if (!formats.contains(preferredFormat)) { LOGGER.warning(preferredFormat + " format is not supported, falling back to defaults"); for (String format : formats) { if ("image/png".equals(format) || "image/png24".equals(format) || "png".equals(format) || "png24".equals(format) || "image/png; mode=24bit".equals(format)) { this.format = format; break; } } } }

Target:
public WMSCoverageReader(WebMapServer wms, Layer layer, String style, String preferredFormat) { this.wms = wms; addLayer(layer, style); List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats(); this.format = preferredFormat; if (!formats.contains(preferredFormat)) this.format = getDefaultFormat(formats); }
Source:
public Class<?> resolveClass(final Unmarshaller unmarshaller, final String className, final long serialVersionUID) throws IOException, ClassNotFoundException { final String name = (String) unmarshaller.readObject(); if (name == null) { final ClassLoader classLoader; if (System.getSecurityManager() == null) { classLoader = Module.class.getClassLoader(); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return Module.class.getClassLoader(); } }); } return Class.forName(className, false, classLoader); } final String slot = (String) unmarshaller.readObject(); final ModuleIdentifier identifier = ModuleIdentifier.create(name, slot); try { final ClassLoader classLoader; final Module module = moduleLoader.loadModule(identifier); if (System.getSecurityManager() == null) { classLoader = module.getClassLoader(); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return module.getClassLoader(); } }); } return Class.forName(className, false, classLoader); } catch (ModuleLoadException e) { final InvalidClassException ce = new InvalidClassException(className, "Module load failed"); ce.initCause(e); throw ce; } }

Target:
public Class<?> resolveClass(final Unmarshaller unmarshaller, final String className, final long serialVersionUID) throws IOException, ClassNotFoundException { final String name = (String) unmarshaller.readObject(); if (name == null) { return Class.forName(className, false, MODULE_CLASS_LOADER); } final String slot = (String) unmarshaller.readObject(); final ModuleIdentifier identifier = ModuleIdentifier.create(name, slot); try { final ClassLoader classLoader; final Module module = moduleLoader.loadModule(identifier); if (System.getSecurityManager() == null) { classLoader = module.getClassLoader(); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return module.getClassLoader(); } }); } return Class.forName(className, false, classLoader); } catch (ModuleLoadException e) { final InvalidClassException ce = new InvalidClassException(className, "Module load failed"); ce.initCause(e); throw ce; } }
Source:
public void handleError(HttpCommand command, HttpResponse response) { String message = parseMessage(response); Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (message != null ){ if (message.indexOf("Unable to determine package for") != -1) { exception = new ResourceNotFoundException(message, exception); } else if (message.indexOf("currently an active transaction") != -1) { exception = new IllegalStateException(message, exception); } else if (message.indexOf("SoftLayer_Exception_Order_Item_Duplicate") != -1) { exception = new SoftLayerOrderItemDuplicateException(command.getCurrentRequest(), message); } } } } finally { Closeables.closeQuietly(response.getPayload()); command.setException(exception); } }

Target:
public void handleError(HttpCommand command, HttpResponse response) { String message = parseMessage(response); Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 500: if (message != null ){ if (message.indexOf("Unable to determine package for") != -1) { exception = new ResourceNotFoundException(message, exception); } else if (message.indexOf("currently an active transaction") != -1) { exception = new IllegalStateException(message, exception); } else if (message.indexOf("SoftLayer_Exception_Order_Item_Duplicate") != -1) { exception = new SoftLayerOrderItemDuplicateException(message, exception); } } } } finally { Closeables.closeQuietly(response.getPayload()); command.setException(exception); } }
Source:
protected RelNode visitChild(RelNode parent, int i, RelNode child) { child.accept(this); parent.getCluster().setMetadataProvider(metadataProvider); return parent; }

Target:
protected RelNode visitChild(RelNode parent, int i, RelNode child) { parent = super.visitChild(parent, i, child); parent.getCluster().setMetadataProvider(metadataProvider); return parent; }
Source:
public void recognizeBatchEntities() { List<TextDocumentInput> textDocumentInputs = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); textAnalyticsAsyncClient.recognizeBatchEntities(textDocumentInputs).subscribe(recognizeEntitiesResults -> { System.out.printf("Model version: %s%n", recognizeEntitiesResults.getModelVersion()); final TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (RecognizeEntitiesResult recognizeEntitiesResult : recognizeEntitiesResults) { for (NamedEntity entity : recognizeEntitiesResult.getNamedEntities()) { System.out.printf( "Recognized Named Entity: %s, Type: %s, Score: %s.%n", entity.getText(), entity.getType(), entity.getScore()); } } }); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeBatchEntities#List }

Target:
public void recognizeBatchEntities() { List<TextDocumentInput> textDocumentInputs = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); textAnalyticsAsyncClient.recognizeBatchEntities(textDocumentInputs).subscribe(recognizeEntitiesResults -> { TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (RecognizeEntitiesResult recognizeEntitiesResult : recognizeEntitiesResults) { for (NamedEntity entity : recognizeEntitiesResult.getNamedEntities()) { System.out.printf( "Recognized Named Entity: %s, Type: %s, Score: %s.%n", entity.getText(), entity.getType(), entity.getScore()); } } }); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.recognizeBatchEntities#List }
Source:
public boolean checkOperandTypes(SqlCallBinding callBinding, boolean throwOnFailure) { for (int i = 0; i < callBinding.operands().size(); i++) { final SqlNode operand = callBinding.operands().get(i); if (literalOperands.contains(i)) { if (!SqlUtil.isLiteral(operand)) { return throwOrReturn( throwOnFailure, callBinding, cb -> cb.getValidator() .newValidationError( operand, Static.RESOURCE.argumentMustBeLiteral(callBinding.getOperator().getName()) ) ); } if (!nullableOperands.contains(i) && SqlUtil.isNullLiteral(operand, true)) { return throwOrReturn( throwOnFailure, callBinding, cb -> cb.getValidator().newValidationError(operand, Static.RESOURCE.nullIllegal()) ); } } final RelDataType operandType = callBinding.getValidator().deriveType(callBinding.getScope(), operand); final SqlTypeFamily expectedFamily = operandTypes.get(i); if (expectedFamily == SqlTypeFamily.ANY) { } else if (expectedFamily.getTypeNames().contains(operandType.getSqlTypeName())) { } else if (operandType.getSqlTypeName() == SqlTypeName.NULL) { if (!nullableOperands.contains(i)) { return throwOrReturn( throwOnFailure, callBinding, cb -> cb.getValidator().newValidationError(operand, Static.RESOURCE.nullIllegal()) ); } } else { return throwOrReturn( throwOnFailure, callBinding, SqlCallBinding::newValidationSignatureError ); } } return true; }

Target:
public boolean checkOperandTypes(SqlCallBinding callBinding, boolean throwOnFailure) { for (int i = 0; i < callBinding.operands().size(); i++) { final SqlNode operand = callBinding.operands().get(i); if (literalOperands.contains(i)) { if (!SqlUtil.isLiteral(operand)) { return throwOrReturn( throwOnFailure, callBinding, cb -> cb.getValidator() .newValidationError( operand, Static.RESOURCE.argumentMustBeLiteral(callBinding.getOperator().getName()) ) ); } } final RelDataType operandType = callBinding.getValidator().deriveType(callBinding.getScope(), operand); final SqlTypeFamily expectedFamily = operandTypes.get(i); if (expectedFamily == SqlTypeFamily.ANY) { } else if (expectedFamily.getTypeNames().contains(operandType.getSqlTypeName())) { } else if (operandType.getSqlTypeName() == SqlTypeName.NULL || SqlUtil.isNullLiteral(operand, true)) { if (!nullableOperands.contains(i)) { return throwOrReturn( throwOnFailure, callBinding, cb -> cb.getValidator().newValidationError(operand, Static.RESOURCE.nullIllegal()) ); } } else { return throwOrReturn( throwOnFailure, callBinding, SqlCallBinding::newValidationSignatureError ); } } return true; }
Source:
private static boolean updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); String optionVersion = option.getversion(); Object optionValue = getValue(option); boolean changed; if (values == null) { values = new HashMap<>(); _vdcOptionCache.put(option.getoption_name(), values); changed = true; } else { Object value = values.get(optionVersion); boolean newVersion = value == null; changed = newVersion || !value.equals(optionValue); } if (changed) { values.put(optionVersion, optionValue); } return changed; }

Target:
private static boolean updateOption(VdcOption option) { Map<String, Object> values = _vdcOptionCache.get(option.getoption_name()); String optionVersion = option.getversion(); Object newOptionValue = getValue(option); if (values == null) { values = new HashMap<>(); _vdcOptionCache.put(option.getoption_name(), values); values.put(optionVersion, newOptionValue); return true; } Object originalValue = values.get(optionVersion); values.put(optionVersion, newOptionValue); boolean newVersionSaved = originalValue == null; boolean changed = newVersionSaved || !originalValue.equals(newOptionValue); return changed; }
Source:
public AgentImpl(String id, String name, String version, String description, List<String> dependencies, Map<String, String> properties, String script, Map<String, ? extends ServerConf2> servers) { this.id = id; this.name = name; this.version = version; this.description = description; this.dependencies = dependencies != null ? dependencies : new ArrayList<>(); this.properties = properties != null ? properties : new HashMap<>(); this.script = script; this.servers = servers != null ? servers : new HashMap<>(); }

Target:
public AgentImpl(String id, String name, String version, String description, List<String> dependencies, Map<String, String> properties, String script, Map<String, ? extends ServerConf2> servers) { this.id = id; this.name = name; this.version = version; this.description = description; this.dependencies = dependencies; this.properties = properties; this.script = script; this.servers = servers; }
Source:
private void addCandidacy(final Map<Degree, SortedSet<SecondCycleIndividualCandidacyProcess>> result, final SecondCycleIndividualCandidacyProcess process) { for (Degree degree : process.getSelectedDegrees()) { SortedSet<SecondCycleIndividualCandidacyProcess> values = result.get(degree); if (values == null) { result.put(degree, values = new TreeSet<SecondCycleIndividualCandidacyProcess>( SecondCycleIndividualCandidacyProcess.COMPARATOR_BY_CANDIDACY_PERSON)); } values.add(process); } }

Target:
private void addCandidacy(final Map<Degree, SortedSet<SecondCycleIndividualCandidacyProcess>> result, final SecondCycleIndividualCandidacyProcess process) { for (Degree degree : process.getSelectedDegrees()) { SortedSet<SecondCycleIndividualCandidacyProcess> values = result.computeIfAbsent(degree, key -> (new TreeSet<SecondCycleIndividualCandidacyProcess>( SecondCycleIndividualCandidacyProcess.COMPARATOR_BY_CANDIDACY_PERSON))); values.add(process); } }
Source:
public boolean isAssignableFrom(IType otherType) { final boolean result; if (!queryEnvironment.getEPackageProvider().isRegistered(type)) { result = false; } else if (getType() instanceof EClass && otherType.getType() instanceof EClass) { result = getType() == otherType.getType() || ((EClass)otherType.getType()).getEAllSuperTypes().contains(getType()); } else { final Class<?> ourClass = queryEnvironment.getEPackageProvider().getClass(getType()); final Class<?> otherClass; if (otherType instanceof EClassifierType) { otherClass = queryEnvironment.getEPackageProvider().getClass( ((EClassifierType)otherType).getType()); } else if (otherType instanceof IJavaType) { otherClass = ((IJavaType)otherType).getType(); } else { otherClass = null; } result = isAssignableFrom(ourClass, otherClass); } return result; }

Target:
public boolean isAssignableFrom(IType otherType) { final boolean result; if (!queryEnvironment.getEPackageProvider().isRegistered(type)) { result = false; } else if (getType() instanceof EClass && otherType.getType() instanceof EClass) { result = getType() == otherType.getType() || queryEnvironment.getEPackageProvider().getAllSubTypes((EClass)getType()).contains( otherType.getType()); } else { final Class<?> ourClass = queryEnvironment.getEPackageProvider().getClass(getType()); final Class<?> otherClass; if (otherType instanceof EClassifierType) { otherClass = queryEnvironment.getEPackageProvider().getClass( ((EClassifierType)otherType).getType()); } else if (otherType instanceof IJavaType) { otherClass = ((IJavaType)otherType).getType(); } else { otherClass = null; } result = isAssignableFrom(ourClass, otherClass); } return result; }