auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Override protected RawClient[] fromConfig(ClusterConfig<PBClientConfig> clusterConfig) throws IOException { final List<PBClientAdapter> clients = new ArrayList<PBClientAdapter>(); int totalMaxConnections = clusterConfig.getTotalMaximumConnections(); Semaphore clusterSemaphore = null; if (!(totalMaxConnections <= RiakConnectionPool.LIMITLESS)) { clusterSemaphore = RiakConnectionPool.getSemaphore(totalMaxConnections); } for (PBClientConfig node : clusterConfig.getClients()) { final RiakConnectionPool hostPool = makePool(clusterSemaphore, node); clients.add(new PBClientAdapter(new RiakClient(hostPool))); } return clients.toArray(new RawClient[clients.size()]); }

Target:
@Override protected RawClient[] fromConfig(ClusterConfig<PBClientConfig> clusterConfig) throws IOException { final List<PBClientAdapter> clients = new ArrayList<PBClientAdapter>(); int totalMaxConnections = clusterConfig.getTotalMaximumConnections(); Semaphore clusterSemaphore = null; if (totalMaxConnections > RiakConnectionPool.LIMITLESS) { clusterSemaphore = RiakConnectionPool.getSemaphore(totalMaxConnections); } for (PBClientConfig node : clusterConfig.getClients()) { final RiakConnectionPool hostPool = makePool(clusterSemaphore, node); clients.add(new PBClientAdapter(new RiakClient(hostPool))); } return clients.toArray(new RawClient[clients.size()]); }
Source:
private Symbol getDeclarationSymbol(FunctionCallTree tree) { ExpressionTree callee = tree.callee(); if (callee.is(Tree.Kind.NAMESPACE_NAME)) { return context().symbolTable().getSymbol(((NamespaceNameTree) callee).name()); } else if(isVerifiableObjectMemberAccess(callee)) { return context().symbolTable().getSymbol(((MemberAccessTree) callee).member()); } else if(isVerifiableClassMemberAccess(callee)) { return context().symbolTable().getSymbol(((MemberAccessTree) callee).member()); } return null; }

Target:
private Symbol getDeclarationSymbol(FunctionCallTree tree) { ExpressionTree callee = tree.callee(); if (callee.is(Kind.NAMESPACE_NAME)) { return context().symbolTable().getSymbol(((NamespaceNameTree) callee).name()); } else if(isVerifiableObjectMemberAccess(callee)) { return context().symbolTable().getSymbol(((MemberAccessTree) callee).member()); } else if(isVerifiableClassMemberAccess(callee)) { return context().symbolTable().getSymbol(((MemberAccessTree) callee).member()); } return null; }
Source:
public void registerQuery(Query query, final ListenableFuture future) { final String id = query.getId(); queries.put(id, future); if(queryDatasources.get(id) == null) { queryDatasources.put(id, getDataSources(query)); } future.addListener( new Runnable() { @Override public void run() { queries.remove(id, future); queryDatasources.remove(id); } }, MoreExecutors.sameThreadExecutor() ); }

Target:
public void registerQuery(Query query, final ListenableFuture future) { final String id = query.getId(); final List<String> datasources = query.getDataSource().getNames(); queries.put(id, future); queryDatasources.putAll(id, datasources); future.addListener( new Runnable() { @Override public void run() { queries.remove(id, future); for (String datasource : datasources) { queryDatasources.remove(id, datasource); } } }, MoreExecutors.sameThreadExecutor() ); }
Source:
public static OrderingScheme toOrderingScheme(OrderBy orderBy, TypeProvider types) { return toOrderingScheme( orderBy.getSortItems().stream().map(SortItem::getSortKey).map(item -> { checkArgument(item instanceof SymbolReference, "must be symbol reference"); Symbol symbol = Symbol.from(item); return variable(symbol.getName(), types.get(symbol)); }), orderBy.getSortItems().stream().map(PlannerUtils::toSortOrder)); }

Target:
public static OrderingScheme toOrderingScheme(OrderBy orderBy, TypeProvider types) { return toOrderingScheme( orderBy.getSortItems().stream() .map(SortItem::getSortKey) .map(item -> { checkArgument(item instanceof SymbolReference, "must be symbol reference"); Symbol symbol = Symbol.from(item); return variable(symbol.getName(), types.get(symbol)); }).collect(toImmutableList()), orderBy.getSortItems().stream() .map(PlannerUtils::toSortOrder) .collect(toImmutableList())); }
Source:
private void submitPutsAndAssertSuccess(boolean shouldCloseRouterAfter) throws Exception { submitPut().await(5, TimeUnit.SECONDS); assertSuccess(); if (shouldCloseRouterAfter) { assertCloseCleanup(); } }

Target:
private void submitPutsAndAssertSuccess(boolean shouldCloseRouterAfter) throws Exception { submitPut().await(MAX_WAIT_MS, TimeUnit.MILLISECONDS); assertSuccess(); if (shouldCloseRouterAfter) { assertCloseCleanup(); } }
Source:
public void importSources(FolderEntry baseFolder, String location) throws IOException { try { final String absoluteBaseFolderPath = localPathResolver.resolve(baseFolder.getVirtualFile()); GitConnection gitConnection = nativeGitConnectionFactory.getConnection(absoluteBaseFolderPath); CloneRequest cloneRequest = DtoFactory.getInstance().createDto(CloneRequest.class).withWorkingDir(absoluteBaseFolderPath).withRemoteName("origin") .withRemoteUri(location); gitConnection.clone(cloneRequest); String propertyFileContent = "{\"type\":\"" + Constants.NAMELESS_ID + "\"}"; FolderEntry projectMetaFolder = baseFolder.createFolder(".codenvy"); projectMetaFolder.createFile("project", propertyFileContent.getBytes(), MediaType.APPLICATION_JSON_TYPE.getType()); } catch (VirtualFileSystemException | GitException | URISyntaxException e) { final String error = "Selected project cannot be imported."; LOG.error(error); throw new IOException(error, e); } }

Target:
public void importSources(FolderEntry baseFolder, String location) throws IOException { try { final String absoluteBaseFolderPath = localPathResolver.resolve(baseFolder.getVirtualFile()); GitConnection gitConnection = nativeGitConnectionFactory.getConnection(absoluteBaseFolderPath); CloneRequest cloneRequest = DtoFactory.getInstance().createDto(CloneRequest.class).withWorkingDir(absoluteBaseFolderPath).withRemoteName("origin") .withRemoteUri(location); gitConnection.clone(cloneRequest); String propertyFileContent = "{\"type\":\"" + Constants.NAMELESS_ID + "\"}"; FolderEntry projectMetaFolder = baseFolder.createFolder(".codenvy"); projectMetaFolder.createFile("project", propertyFileContent.getBytes(), MediaType.APPLICATION_JSON_TYPE.getType()); } catch (VirtualFileSystemException | GitException | URISyntaxException e) { throw new IOException("Selected project cannot be imported.", e); } }
Source:
protected String visitLikePredicate(LikePredicate node, Void context) { StringBuilder builder = new StringBuilder(); builder.append('(') .append(process(node.getValue(), context)) .append(" LIKE ") .append(process(node.getPattern(), context)); node.getEscape().ifPresent(escape -> { if (node.getEscape().isPresent()) { builder.append(" ESCAPE ") .append(process(node.getEscape().get(), context)); } }); builder.append(')'); return builder.toString(); }

Target:
protected String visitLikePredicate(LikePredicate node, Void context) { StringBuilder builder = new StringBuilder(); builder.append('(') .append(process(node.getValue(), context)) .append(" LIKE ") .append(process(node.getPattern(), context)); node.getEscape().ifPresent(escape -> { builder.append(" ESCAPE ") .append(process(escape, context)); }); builder.append(')'); return builder.toString(); }
Source:
public String getHelpNote() { String s = "\n\n\n" + "### Notes:\n" + "## 1. Passwords: password can be set in interactive mode ie:\n" + "### engine-config -s PasswordEntry=interactive\n" + "### or via file with one of the following options:\n" + "### engine-config -s PasswordEntry --admin-pass-file=/tmp/mypass\n" + "### engine-config -s PasswordEntry=/tmp/mypass\n" + "### 2. In order for your change(s) to take effect,\n" + "### restart the oVirt engine service (using: 'service ovirt-engine restart').\n" + "################################################################################\n\n"; return s; }

Target:
public String getHelpNote() { return String.format("%n%n%n" + "### Notes:%n" + "### 1. Passwords: password can be set in interactive mode ie:%n" + "### engine-config -s PasswordEntry=interactive%n" + "### or via file with one of the following options:%n" + "### engine-config -s PasswordEntry --admin-pass-file=/tmp/mypass%n" + "### engine-config -s PasswordEntry=/tmp/mypass%n" + "### 2. In order for your change(s) to take effect,%n" + "### restart the oVirt engine service (using: 'service ovirt-engine restart').%n" + "################################################################################%n%n"); }
Source:
public String toString() { StringBuilder ret = new StringBuilder(); ret.append( this.attributeName ); if ( NO_LOOP.getAttributeName().equals( attributeName ) ) { ret.append( " " ); ret.append( this.value == null ? "true" : this.value ); } else if ( SALIENCE.getAttributeName().equals( this.attributeName ) || DURATION.getAttributeName().equals( this.attributeName ) ) { ret.append( " " ); ret.append( this.value ); } else if (ENABLED.getAttributeName().equals( this.attributeName ) || AUTO_FOCUS.getAttributeName().equals( this.attributeName ) || LOCK_ON_ACTIVE.getAttributeName().equals( this.attributeName ) ) { ret.append( " " ); ret.append( this.value.equals( "true" ) ? "true" : "false" ); } else if (TIMER.getAttributeName().equals( this.attributeName ) ) { ret.append( " " ); if ( this.value.startsWith( "(" ) && this.value.endsWith( ")" ) ) { ret.append( this.value ); } else { ret.append( "(" ).append( this.value ).append( ")" ); } } else if (CALENDARS.getAttributeName().equals( this.attributeName ) ) { final String raw = this.value.replaceAll( "\"|\\s", "" ); final String[] calendars = raw.split( "," ); ret.append( " " ); for ( String calendar : calendars ) { ret.append( "\"" ).append( calendar ).append( "\", " ); } ret.delete( ret.length() - 2, ret.length() ); } else if ( this.value != null ) { ret.append( " \"" ); ret.append( this.value ); ret.append( "\"" ); } return ret.toString(); }

Target:
public String toString() { final StringBuilder ret = new StringBuilder(); ret.append( this.attributeName ); ret.append( ' ' ); if ( NO_LOOP.getAttributeName().equals( attributeName ) ) { ret.append( this.value == null ? "true" : this.value ); } else if ( SALIENCE.getAttributeName().equals( this.attributeName ) || DURATION.getAttributeName().equals( this.attributeName ) ) { ret.append( this.value ); } else if (ENABLED.getAttributeName().equals( this.attributeName ) || AUTO_FOCUS.getAttributeName().equals( this.attributeName ) || LOCK_ON_ACTIVE.getAttributeName().equals( this.attributeName ) ) { ret.append( this.value.equals( "true" ) ? "true" : "false" ); } else if (TIMER.getAttributeName().equals( this.attributeName ) ) { if ( this.value.startsWith( "(" ) && this.value.endsWith( ")" ) ) { ret.append( this.value ); } else { ret.append( '(' ).append( this.value ).append( ')' ); } } else if (CALENDARS.getAttributeName().equals( this.attributeName ) ) { final String raw = this.value.replaceAll( "\"|\\s", "" ); final String[] calendars = raw.split( "," ); for ( String calendar : calendars ) { ret.append( '"' ).append( calendar ).append( "\", " ); } ret.delete( ret.length() - 2, ret.length() ); } else if ( this.value != null ) { ret.append( '"' ); ret.append( this.value ); ret.append( '"' ); } return ret.toString(); }
Source:
private <T> T getOrInstantiate(Class<T> tClass) { try { return applicationContext.getBean(tClass); } catch (NoSuchBeanDefinitionException e) { try { return tClass.cast(tClass.newInstance()); } catch (Exception exception) { throw new IllegalStateException(e.getMessage(), exception); } } }

Target:
private <T> T getOrInstantiate(Class<T> tClass) { try { return applicationContext.getBean(tClass); } catch (NoSuchBeanDefinitionException e) { return BeanUtils.instantiateClass(tClass); } }
Source:
public void onStart() { Log.d(TAG, "onStart()"); handler.postDelayed(moveAround, 30000); handler.postDelayed(fadeClock, 30000); handler.postDelayed(backgroundChange, 15000 * settings.backgroundImageDuration); }

Target:
public void onStart() { Log.d(TAG, "onStart()"); handler.postDelayed(moveAround, 30000); handler.postDelayed(fadeClock, 30000); }
Source:
static void dbconnect(Config config) throws InterruptedException, Exception { final Splitter COMMA_SPLITTER = Splitter.on(",").omitEmptyStrings().trimResults(); log.info("Connecting to VoltDB Interface..."); ClientConfig clientConfig = new ClientConfig(config.username, config.password); clientConfig.setMaxTransactionsPerSecond(config.ratelimit); if (config.sslfile.trim().length() > 0) { clientConfig.setTrustStoreConfigFromPropertyFile(config.sslfile); clientConfig.enableSSL(); } if (config.autoreconnect) { clientConfig.setReconnectOnConnectionLoss(true); } else { clientConfig.setTopologyChangeAware(true); } client = ClientFactory.createClient(clientConfig); for (String server: COMMA_SPLITTER.split(config.servers)) { log.info("..." + server); client.createConnection(server); } }

Target:
static void dbconnect(Config config) throws InterruptedException, Exception { final Splitter COMMA_SPLITTER = Splitter.on(",").omitEmptyStrings().trimResults(); log.info("Connecting to VoltDB Interface..."); ClientConfig clientConfig = new ClientConfig(config.username, config.password); clientConfig.setMaxTransactionsPerSecond(config.ratelimit); if (config.sslfile.trim().length() > 0) { clientConfig.setTrustStoreConfigFromPropertyFile(config.sslfile); clientConfig.enableSSL(); } if (config.connectoption.equalsIgnoreCase("autoreconnect")) { clientConfig.setReconnectOnConnectionLoss(true); } else { clientConfig.setTopologyChangeAware(true); } client = ClientFactory.createClient(clientConfig); for (String server: COMMA_SPLITTER.split(config.servers)) { log.info("..." + server); client.createConnection(server); } }
Source:
public void run() { super.run(); isClosed = false; if (endingDocument != null) { endingDocument.prepareDocument(); } if (getDocument() != null && endingDocument != null) { String startingContent = getDocument().getContent(); String endingContent = endingDocument.getContent(); if (startingContent != null && endingContent != null) { int startLength = startingContent.length(); int endLength = endingContent.length(); charLengthDiffBetweenStartAndEndDoc = Math.abs(startLength - endLength); long lengthProduct = startLength*endLength; if(startLength == 0) { lengthProduct = endLength; } else if (endLength == 0) { lengthProduct = startLength; } if(lengthProduct <= LENGTH_PRODUCT_THRESHOLD) { editDistance = new JsonifiedLong( StringUtils.getLevenshteinDistance(startingContent, endingContent)); } } } isClosed = true; }

Target:
public void run() { super.run(); isClosed = false; if (endingDocument != null) { endingDocument.prepareDocument(); } if (getDocument() != null && endingDocument != null) { String startingContent = getDocument().getContent(); String endingContent = endingDocument.getContent(); if (startingContent != null && endingContent != null) { int startLength = startingContent.length(); int endLength = endingContent.length(); charLengthDiff = Math.abs(startLength - endLength); long lengthProduct = startLength*endLength; if(startLength == 0) { lengthProduct = endLength; } else if (endLength == 0) { lengthProduct = startLength; } if(lengthProduct <= LENGTH_PRODUCT_THRESHOLD) { editDistance = new JsonifiedLong( StringUtils.getLevenshteinDistance(startingContent, endingContent)); } } } isClosed = true; }
Source:
public double priceDerivativeStrike(double strike, PutCall putCall) { double pDK = 0.0; if (strike <= cutOffStrike) { BlackPriceFunction blackFunction = new BlackPriceFunction(); ValueDerivatives volatilityAdjoint = sabrFunction.getVolatilityAdjoint(forward, strike, timeToExpiry, sabrData); EuropeanVanillaOption option = EuropeanVanillaOption.of(strike, timeToExpiry, putCall); BlackFunctionData dataBlack = BlackFunctionData.of(forward, 1.0, volatilityAdjoint.getValue()); ValueDerivatives bsAdjoint = blackFunction.getPriceAdjoint(option, dataBlack); pDK = bsAdjoint.getDerivative(2) + bsAdjoint.getDerivative(1) * volatilityAdjoint.getDerivative(1); } else { pDK = extrapolationDerivative(strike); if (putCall.isPut()) { pDK += 1.0; } } return pDK; }

Target:
public double priceDerivativeStrike(double strike, PutCall putCall) { if (strike <= cutOffStrike) { BlackPriceFunction blackFunction = new BlackPriceFunction(); ValueDerivatives volatilityAdjoint = sabrFunction.getVolatilityAdjoint(forward, strike, timeToExpiry, sabrData); EuropeanVanillaOption option = EuropeanVanillaOption.of(strike, timeToExpiry, putCall); BlackFunctionData dataBlack = BlackFunctionData.of(forward, 1.0, volatilityAdjoint.getValue()); ValueDerivatives bsAdjoint = blackFunction.getPriceAdjoint(option, dataBlack); return bsAdjoint.getDerivative(2) + bsAdjoint.getDerivative(1) * volatilityAdjoint.getDerivative(1); } double pDK = extrapolationDerivative(strike); if (putCall.isPut()) { pDK += 1.0; } return pDK; }
Source:
public InternalPushConnection(PackTransport transport, final ReceivePackFactory<C> receivePackFactory, final C req, final Repository remote) throws TransportException { super(transport); final PipedInputStream in_r; final PipedOutputStream in_w; final PipedInputStream out_r; final PipedOutputStream out_w; try { in_r = new PipedInputStream(); in_w = new PipedOutputStream(in_r); out_r = new PipedInputStream(); out_w = new PipedOutputStream(out_r); } catch (IOException err) { remote.close(); throw new TransportException(uri, JGitText.get().cannotConnectPipes, err); } worker = new Thread("JGit-Receive-Pack") { @Override public void run() { try { final ReceivePack rp = receivePackFactory.create(req, remote); rp.receive(out_r, in_w, System.err); } catch (Exception e) { System.err.println("Exception while receiving pack: " + e.toString()); } finally { try { out_r.close(); } catch (IOException e2) { } try { in_w.close(); } catch (IOException e2) { } remote.close(); } } }; worker.start(); init(in_r, out_w); readAdvertisedRefs(); }

Target:
public InternalPushConnection(PackTransport transport, final ReceivePackFactory<C> receivePackFactory, final C req, final Repository remote) throws TransportException { super(transport); final PipedInputStream in_r; final PipedOutputStream in_w; final PipedInputStream out_r; final PipedOutputStream out_w; try { in_r = new PipedInputStream(); in_w = new PipedOutputStream(in_r); out_r = new PipedInputStream(); out_w = new PipedOutputStream(out_r); } catch (IOException err) { remote.close(); throw new TransportException(uri, JGitText.get().cannotConnectPipes, err); } worker = new Thread("JGit-Receive-Pack") { @Override public void run() { try { final ReceivePack rp = receivePackFactory.create(req, remote); rp.receive(out_r, in_w, System.err); } catch (ServiceNotEnabledException e) { } catch (ServiceNotAuthorizedException e) { } catch (IOException e) { throw new RuntimeException(e); } finally { try { out_r.close(); } catch (IOException e2) { } try { in_w.close(); } catch (IOException e2) { } remote.close(); } } }; worker.start(); init(in_r, out_w); readAdvertisedRefs(); }
Source:
public void addNewMailNotification(Account account, LocalMessage message, int previousUnreadMessageCount) { boolean hasHighPriority = false; for (String iter : message.getHeader("X-Priority")) { if (iter.contains(context.getString(R.string.x_priority))) hasHighPriority = true; } newMailNotifications.addNewMailNotification(account, message, previousUnreadMessageCount, hasHighPriority); }

Target:
public void addNewMailNotification(Account account, LocalMessage message, int previousUnreadMessageCount) { newMailNotifications.addNewMailNotification(account, message, previousUnreadMessageCount); }
Source:
setVoiceMessageWaiting(int line, int countWaiting) { if (line != 1) { return; } if (countWaiting < 0) { countWaiting = -1; } else if (countWaiting > 0xff) { countWaiting = 0xff; } countVoiceMessages = countWaiting; phone.setSystemProperty(PROPERTY_LINE1_VOICE_MAIL_WAITING, (countVoiceMessages != 0) ? "true" : "false"); ((GSMPhone) phone).notifyMessageWaitingIndicator(); try { if (efMWIS != null) { efMWIS[0] = (byte)((efMWIS[0] & 0xfe) | (countVoiceMessages == 0 ? 0 : 1)); if (countWaiting < 0) { efMWIS[1] = 0; } else { efMWIS[1] = (byte) countWaiting; } ((SIMFileHandler)phone.getIccFileHandler()).updateEFLinearFixed( EF_MWIS, 1, efMWIS, null, obtainMessage (EVENT_UPDATE_DONE, EF_MWIS)); } if (efCPHS_MWI != null) { efCPHS_MWI[0] = (byte)((efCPHS_MWI[0] & 0xf0) | (countVoiceMessages == 0 ? 0x5 : 0xa)); ((SIMFileHandler)phone.getIccFileHandler()).updateEFTransparent( EF_VOICE_MAIL_INDICATOR_CPHS, efCPHS_MWI, obtainMessage (EVENT_UPDATE_DONE, EF_VOICE_MAIL_INDICATOR_CPHS)); } } catch (ArrayIndexOutOfBoundsException ex) { Log.w(LOG_TAG, "Error saving voice mail state to SIM. Probably malformed SIM record", ex); } }

Target:
setVoiceMessageWaiting(int line, int countWaiting) { if (line != 1) { return; } if (countWaiting < 0) { countWaiting = -1; } else if (countWaiting > 0xff) { countWaiting = 0xff; } countVoiceMessages = countWaiting; phone.setSystemProperty(PROPERTY_LINE1_VOICE_MAIL_WAITING, (countVoiceMessages != 0) ? "true" : "false"); ((GSMPhone) phone).notifyMessageWaitingIndicator(); try { if (efMWIS != null) { efMWIS[0] = (byte)((efMWIS[0] & 0xfe) | (countVoiceMessages == 0 ? 0 : 1)); if (countWaiting < 0) { efMWIS[1] = 0; } else { efMWIS[1] = (byte) countWaiting; } phone.getIccFileHandler().updateEFLinearFixed( EF_MWIS, 1, efMWIS, null, obtainMessage (EVENT_UPDATE_DONE, EF_MWIS)); } if (efCPHS_MWI != null) { efCPHS_MWI[0] = (byte)((efCPHS_MWI[0] & 0xf0) | (countVoiceMessages == 0 ? 0x5 : 0xa)); phone.getIccFileHandler().updateEFTransparent( EF_VOICE_MAIL_INDICATOR_CPHS, efCPHS_MWI, obtainMessage (EVENT_UPDATE_DONE, EF_VOICE_MAIL_INDICATOR_CPHS)); } } catch (ArrayIndexOutOfBoundsException ex) { Log.w(LOG_TAG, "Error saving voice mail state to SIM. Probably malformed SIM record", ex); } }
Source:
public void should_warn_when_non_bind_marker_has_cql_name() { should_succeed_with_expected_warning( "Parameter id does not refer " + "to a bind marker, @CqlName annotation will be ignored", MethodSpec.methodBuilder("delete") .addAnnotation( AnnotationSpec.builder(Delete.class) .addMember("entityClass", ENTITY_CLASS_NAME + ".class") .addMember("customIfClause", "$S", "description = :description") .build()) .addParameter( ParameterSpec.builder(UUID.class, "id") .addAnnotation( AnnotationSpec.builder(CqlName.class) .addMember("value", "$S", "irrelevant") .build()) .build()) .addParameter(String.class, "description") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .build()); }

Target:
public void should_warn_when_non_bind_marker_has_cql_name() { should_succeed_with_expected_warning( "Parameter id does not refer to a bind marker, @CqlName annotation will be ignored", MethodSpec.methodBuilder("delete") .addAnnotation( AnnotationSpec.builder(Delete.class) .addMember("entityClass", ENTITY_CLASS_NAME + ".class") .addMember("customIfClause", "$S", "description = :description") .build()) .addParameter( ParameterSpec.builder(UUID.class, "id") .addAnnotation( AnnotationSpec.builder(CqlName.class) .addMember("value", "$S", "irrelevant") .build()) .build()) .addParameter(String.class, "description") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .build()); }
Source:
private static boolean isEjbModule(IModule module) { IModuleType type = module.getModuleType(); return IWTPConstants.FACET_EJB.equals(type.getId()); }

Target:
private static boolean isEjbModule(IModule module) { IModuleType type = module.getModuleType(); if (type == null) { return false; } return IWTPConstants.FACET_EJB.equals(type.getId()); }
Source:
protected void onBackupWithoutLoadedSession( @Nonnull final String sessionId, @Nonnull final String requestId, @Nonnull final BackupSessionService backupSessionService ) { if ( !_sessionIdFormat.isValid( sessionId ) ) { return; } try { final long start = System.currentTimeMillis(); final String validityKey = _sessionIdFormat.createValidityInfoKeyName( sessionId ); final SessionValidityInfo validityInfo = loadSessionValidityInfoForValidityKey( validityKey ); if ( validityInfo == null ) { _log.warn( "Found no validity info for session id " + sessionId ); return; } final int maxInactiveInterval = validityInfo.getMaxInactiveInterval(); final byte[] validityData = encode( maxInactiveInterval, System.currentTimeMillis(), System.currentTimeMillis() ); final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval; _memcached.set( validityKey, toMemcachedExpiration(expiration), validityData ); final Callable<?> backupSessionTask = new OnBackupWithoutLoadedSessionTask( sessionId, _storeSecondaryBackup, validityKey, validityData, maxInactiveInterval ); _executor.submit( backupSessionTask ); if ( _log.isDebugEnabled() ) { _log.debug( "Stored session validity info for session " + sessionId ); } _stats.registerSince( NON_STICKY_ON_BACKUP_WITHOUT_LOADED_SESSION, start ); } catch( final Throwable e ) { _log.warn( "An error when trying to load/update validity info.", e ); } }

Target:
protected void onBackupWithoutLoadedSession( @Nonnull final String sessionId, @Nonnull final String requestId, @Nonnull final BackupSessionService backupSessionService ) { if ( !_sessionIdFormat.isValid( sessionId ) ) { return; } try { final long start = System.currentTimeMillis(); final String validityKey = _sessionIdFormat.createValidityInfoKeyName( sessionId ); final SessionValidityInfo validityInfo = loadSessionValidityInfoForValidityKey( validityKey ); if ( validityInfo == null ) { _log.warn( "Found no validity info for session id " + sessionId ); return; } final int maxInactiveInterval = validityInfo.getMaxInactiveInterval(); final byte[] validityData = encode( maxInactiveInterval, System.currentTimeMillis(), System.currentTimeMillis() ); final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval; final Future<Boolean> validityResult = _memcached.set( validityKey, toMemcachedExpiration(expiration), validityData ); if ( !_manager.isSessionBackupAsync() ) { validityResult.get( _manager.getSessionBackupTimeout(), TimeUnit.MILLISECONDS ); } final Callable<?> backupSessionTask = new OnBackupWithoutLoadedSessionTask( sessionId, _storeSecondaryBackup, validityKey, validityData, maxInactiveInterval ); _executor.submit( backupSessionTask ); if ( _log.isDebugEnabled() ) { _log.debug( "Stored session validity info for session " + sessionId ); } _stats.registerSince( NON_STICKY_ON_BACKUP_WITHOUT_LOADED_SESSION, start ); } catch( final Throwable e ) { _log.warn( "An error when trying to load/update validity info.", e ); } }
Source:
private boolean hasMembership(String userId, String roleExpression) { if(roleExpression.equals("*") || roleExpression.equals(IdentityConstants.ANY)) return true; ConversationState conversationState = ConversationState.getCurrent(); Identity identity = conversationState.getIdentity(); String membershipType = roleExpression.substring(0, roleExpression.indexOf(":")); String groupName = roleExpression.substring(roleExpression.indexOf(":") + 1); try { MembershipHandler membershipHandler = organizationService_.getMembershipHandler(); if ("*".equals(membershipType)) { if (userId.equals(ConversationState.getCurrent().getIdentity().getUserId())) { return identity.isMemberOf(groupName); } else { return !membershipHandler.findMembershipsByUserAndGroup( userId,groupName).isEmpty(); } } if (userId.equals(ConversationState.getCurrent().getIdentity().getUserId())) { return identity.isMemberOf(groupName, membershipType); } else { return membershipHandler.findMembershipByUserGroupAndType(userId,groupName,membershipType) != null; } } catch(Exception e) { return false; } }

Target:
private boolean hasMembership(String userId, String roleExpression) { if (userId == null || userId.length() == 0) { return false; } if(roleExpression.equals("*") || roleExpression.equals(IdentityConstants.ANY)) return true; ConversationState conversationState = ConversationState.getCurrent(); Identity identity = conversationState.getIdentity(); String membershipType = roleExpression.substring(0, roleExpression.indexOf(":")); String groupName = roleExpression.substring(roleExpression.indexOf(":") + 1); try { MembershipHandler membershipHandler = organizationService_.getMembershipHandler(); if ("*".equals(membershipType)) { if (userId.equals(ConversationState.getCurrent().getIdentity().getUserId())) { return identity.isMemberOf(groupName); } else { return !membershipHandler.findMembershipsByUserAndGroup( userId,groupName).isEmpty(); } } if (userId.equals(ConversationState.getCurrent().getIdentity().getUserId())) { return identity.isMemberOf(groupName, membershipType); } else { return membershipHandler.findMembershipByUserGroupAndType(userId,groupName,membershipType) != null; } } catch(Exception e) { return false; } }
Source:
public void onBackPressed() { boolean isDragAndDropActiveInFragment = getCurrentFragment() instanceof DragAndDropInterface && ((DragAndDropInterface) getCurrentFragment()).isCurrentlyMoving(); if (isDragAndDropActiveInFragment) { ((DragAndDropInterface) getCurrentFragment()).cancelMove(); return; } if (getCurrentFragment() instanceof FormulaEditorFragment) { ((FormulaEditorFragment) getCurrentFragment()).promptSave(); return; } if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); return; } if (getCurrentFragment() instanceof ScriptFragment && ((ScriptFragment) getCurrentFragment()).isCurrentlyHighlighted()) { ((ScriptFragment) getCurrentFragment()).cancelHighlighting(); return; } super.onBackPressed(); }

Target:
public void onBackPressed() { Fragment currentFragment = getCurrentFragment(); if (currentFragment instanceof ScriptFragment) { if (((DragAndDropInterface) currentFragment).isCurrentlyMoving()) { ((DragAndDropInterface) currentFragment).cancelMove(); return; } if (((ScriptFragment) currentFragment).isCurrentlyHighlighted()) { ((ScriptFragment) currentFragment).cancelHighlighting(); return; } } if (getCurrentFragment() instanceof FormulaEditorFragment) { ((FormulaEditorFragment) getCurrentFragment()).promptSave(); return; } if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); return; } super.onBackPressed(); }
Source:
private void loadOfflineUsers() { Disposable mLoadOfflineUserDisposable = Observable.merge(mFavoriteRepository.getFavorites()) .filter(Resource::hasData) .map(userResource -> userResource.data) .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { boolean added = mOfflineUserIds.add(user.id); if (!added) { return; } addUserToCluster(user); mMarkerClusterer.invalidate(); }); getCreateDestroyDisposable().add(mLoadOfflineUserDisposable); }

Target:
private void loadOfflineUsers() { Disposable loadOfflineUserDisposable = Observable.merge(mFavoriteRepository.getFavorites()) .filter(Resource::hasData) .map(userResource -> userResource.data) .distinct() .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { addUserToCluster(user); mMarkerClusterer.invalidate(); }); getCreateDestroyDisposable().add(loadOfflineUserDisposable); }
Source:
private void startappintro(final Context context) { mthread = new Thread(new Runnable() { @Override public void run() { SharedPreferences PREF = PreferenceManager .getDefaultSharedPreferences(context); misFirstStart = PREF.getBoolean("firstStart", true); if (misFirstStart) { final Intent INTENT = new Intent(SplashScreenActivity.this, AppIntroUser.class); runOnUiThread(new Runnable() { @Override public void run() { startActivity(INTENT); } }); SharedPreferences.Editor E = PREF.edit(); E.putBoolean("firstStart", false); E.apply(); } } }); mthread.start(); }

Target:
private void startappintro(final Context context) { mthread = new Thread(new Runnable() { @Override public void run() { mprefManager = PrefManager.getPreferences(); misFirstStart = PrefManager.getBoolean(getResources(). getString(R.string.firststart_splash_screen), true); if (misFirstStart) { final Intent INTENT = new Intent(SplashScreenActivity.this, AppIntroUser.class); runOnUiThread(new Runnable() { @Override public void run() { startActivity(INTENT); } }); SharedPreferences.Editor Editor = mprefManager.edit(); Editor.putBoolean(getResources(). getString(R.string.firststart_splash_screen), false); Editor.apply(); } } }); mthread.start(); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); if (getParameters().getInterface() != null && StringUtils.isNotEmpty(getNetworkName()) && getVm() != null) { Network network = getNetworkDAO().getByNameAndCluster(getNetworkName(), getVm().getVdsGroupId()); permissionList.add(new PermissionSubject(network == null ? null : network.getId(), VdcObjectType.Network, ActionGroup.CONFIGURE_VM_NETWORK)); if (getParameters().getInterface().isPortMirroring()) { permissionList.add(new PermissionSubject(network == null ? null : network.getId(), VdcObjectType.Network, ActionGroup.PORT_MIRRORING)); } } return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); if (getParameters().getInterface() != null && StringUtils.isNotEmpty(getNetworkName()) && getVm() != null) { Network network = getNetworkDAO().getByNameAndCluster(getNetworkName(), getVm().getVdsGroupId()); if (getParameters().getInterface().isPortMirroring()) { permissionList.add(new PermissionSubject(network == null ? null : network.getId(), VdcObjectType.Network, ActionGroup.PORT_MIRRORING)); } else { permissionList.add(new PermissionSubject(network == null ? null : network.getId(), VdcObjectType.Network, getActionType().getActionGroup())); } } return permissionList; }
Source:
public List<Challenge> getChallenges() { return challenges; }

Target:
public List<Challenge> getChallenges() { return Collections.unmodifiableList(challenges); }
Source:
public Response putService(ServiceInstance<T> instance, @PathParam("name") String name, @PathParam("id") String id) { if ( !instance.getId().equals(id) || !instance.getName().equals(name) ) { log.info("Request where path id and/or name doesn't match entity"); return Response.status(Response.Status.BAD_REQUEST).build(); } if ( instance.getServiceType() == ServiceType.DYNAMIC || instance.getServiceType() == ServiceType.DYNAMIC_SEQUENTIAL ) { log.info("Service type cannot be dynamic"); return Response.status(Response.Status.BAD_REQUEST).build(); } try { context.getServiceDiscovery().registerService(instance); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); log.error("Trying to register service", e); return Response.serverError().build(); } return Response.status(Response.Status.CREATED).build(); }

Target:
public Response putService(ServiceInstance<T> instance, @PathParam("name") String name, @PathParam("id") String id) { if ( !instance.getId().equals(id) || !instance.getName().equals(name) ) { log.info("Request where path id and/or name doesn't match entity"); return Response.status(Response.Status.BAD_REQUEST).build(); } if ( instance.getServiceType().isDynamic() ) { log.info("Service type cannot be dynamic"); return Response.status(Response.Status.BAD_REQUEST).build(); } try { context.getServiceDiscovery().registerService(instance); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); log.error("Trying to register service", e); return Response.serverError().build(); } return Response.status(Response.Status.CREATED).build(); }
Source:
private Set<SitemapEvent> constructSitemapEvents(Item item, List<Widget> widgets) { Set<SitemapEvent> events = new HashSet<>(); for (Widget w : widgets) { if (w instanceof Frame) { events.addAll(constructSitemapEvents(item, itemUIRegistry.getChildren((Frame) w))); } if ((w.getItem() != null && w.getItem().equals(item.getName())) || definesVisibility(w, item.getName())) { SitemapWidgetEvent event = new SitemapWidgetEvent(); event.sitemapName = sitemapName; event.pageId = pageId; event.label = itemUIRegistry.getLabel(w); event.labelcolor = itemUIRegistry.getLabelColor(w); event.valuecolor = itemUIRegistry.getValueColor(w); event.widgetId = itemUIRegistry.getWidgetId(w); event.visibility = itemUIRegistry.getVisiblity(w); String widgetTypeName = w.eClass().getInstanceTypeName() .substring(w.eClass().getInstanceTypeName().lastIndexOf(".") + 1); event.item = EnrichedItemDTOMapper.map(item, "mapview".equalsIgnoreCase(widgetTypeName), CoreItemFactory.LOCATION, null, null); event.state = itemUIRegistry.getState(w).toFullString(); if (event.state != null && event.state.equals(event.item.state)) { event.state = null; } events.add(event); } } return events; }

Target:
private Set<SitemapEvent> constructSitemapEvents(Item item, List<Widget> widgets) { Set<SitemapEvent> events = new HashSet<>(); for (Widget w : widgets) { if (w instanceof Frame) { events.addAll(constructSitemapEvents(item, itemUIRegistry.getChildren((Frame) w))); } if ((w.getItem() != null && w.getItem().equals(item.getName())) || definesVisibility(w, item.getName())) { SitemapWidgetEvent event = new SitemapWidgetEvent(); event.sitemapName = sitemapName; event.pageId = pageId; event.label = itemUIRegistry.getLabel(w); event.labelcolor = itemUIRegistry.getLabelColor(w); event.valuecolor = itemUIRegistry.getValueColor(w); event.widgetId = itemUIRegistry.getWidgetId(w); event.visibility = itemUIRegistry.getVisiblity(w); String widgetTypeName = w.eClass().getInstanceTypeName() .substring(w.eClass().getInstanceTypeName().lastIndexOf(".") + 1); boolean drillDown = "mapview".equalsIgnoreCase(widgetTypeName); Predicate<Item> itemFilter = (i -> i.getType().equals(CoreItemFactory.LOCATION)); event.item = EnrichedItemDTOMapper.map(item, drillDown, itemFilter, null, null); event.state = itemUIRegistry.getState(w).toFullString(); if (event.state != null && event.state.equals(event.item.state)) { event.state = null; } events.add(event); } } return events; }
Source:
protected List<FileStatus> listStatus(Path... dirs) throws IOException { List<FileStatus> result = new ArrayList<FileStatus>(); if (dirs.length == 0) { throw new IOException("No input paths specified in job"); } List<IOException> errors = new ArrayList<IOException>(); List<PathFilter> filters = new ArrayList<PathFilter>(); filters.add(hiddenFileFilter); PathFilter inputFilter = new MultiPathFilter(filters); for (int i = 0; i < dirs.length; ++i) { Path p = dirs[i]; FileStatus[] matches = fs.globStatus(p, inputFilter); if (matches == null) { LOG.warn("Input path does not exist: " + p); } else if (matches.length == 0) { errors.add(new IOException("Input Pattern " + p + " matches 0 files")); } else { for (FileStatus globStat : matches) { if (globStat.isDirectory()) { for (FileStatus stat : fs.listStatus(globStat.getPath(), inputFilter)) { result.add(stat); } } else { result.add(globStat); } } } } if (!errors.isEmpty()) { throw new InvalidInputException(errors); } LOG.info("Total input paths to process : " + result.size()); return result; }

Target:
protected List<FileStatus> listStatus(Path... dirs) throws IOException { List<FileStatus> result = new ArrayList<>(); if (dirs.length == 0) { throw new IOException("No input paths specified in job"); } List<IOException> errors = new ArrayList<>(); List<PathFilter> filters = new ArrayList<>(); filters.add(hiddenFileFilter); PathFilter inputFilter = new MultiPathFilter(filters); for (int i = 0; i < dirs.length; ++i) { Path p = dirs[i]; FileStatus[] matches = fs.globStatus(p, inputFilter); if (matches == null) { LOG.warn("Input path does not exist: " + p); } else if (matches.length == 0) { LOG.warn("Input Pattern " + p + " matches 0 files"); } else { for (FileStatus globStat : matches) { if (globStat.isDirectory()) { for (FileStatus stat : fs.listStatus(globStat.getPath(), inputFilter)) { result.add(stat); } } else { result.add(globStat); } } } } if (!errors.isEmpty()) { throw new InvalidInputException(errors); } LOG.info("Total input paths to process : " + result.size()); return result; }
Source:
public CrossGammaMultiCurveCalculator(final InstrumentDerivativeVisitor<MulticurveProviderInterface, MultipleCurrencyMulticurveSensitivity> curveSensitivityCalculator) { _psc = new ParameterSensitivityParameterCalculator<>(curveSensitivityCalculator); _shift = BP1; }

Target:
public CrossGammaMultiCurveCalculator(final InstrumentDerivativeVisitor<MulticurveProviderInterface, MultipleCurrencyMulticurveSensitivity> curveSensitivityCalculator) { ArgumentChecker.notNull(curveSensitivityCalculator, "sensitivity calculator"); _psc = new ParameterSensitivityParameterCalculator<>(curveSensitivityCalculator); _shift = BP1; }
Source:
public void testEquivalence() { EquivalenceTester.equivalenceTester().addEquivalentGroup(new PinotTableHandle("connector", "schema", "table"), new PinotTableHandle("connector", "schema", "table")).addEquivalentGroup(new PinotTableHandle("connectorX", "schema", "table"), new PinotTableHandle("connectorX", "schema", "table")).addEquivalentGroup(new PinotTableHandle("connector", "schemaX", "table"), new PinotTableHandle("connector", "schemaX", "table")).addEquivalentGroup(new PinotTableHandle("connector", "schema", "tableX"), new PinotTableHandle("connector", "schema", "tableX")).check(); }

Target:
public void testEquivalence() { EquivalenceTester.equivalenceTester() .addEquivalentGroup(new PinotTableHandle("schema", "table"), new PinotTableHandle("schema", "table")) .addEquivalentGroup(new PinotTableHandle("schemaX", "table"), new PinotTableHandle("schemaX", "table")) .addEquivalentGroup(new PinotTableHandle("schema", "tableX"), new PinotTableHandle("schema", "tableX")) .check(); }
Source:
private @CheckForNull Runnable makeBuildable(final BuildableItem p) { if (p.task instanceof FlyweightTask) { if (!isBlockedByShutdown(p.task)) { Jenkins h = Jenkins.getInstance(); Map<Node,Integer> hashSource = new HashMap<Node, Integer>(h.getNodes().size()); hashSource.put(h, Math.max(h.getNumExecutors() * 100, 1)); for (Node n : h.getNodes()) { hashSource.put(n, n.getNumExecutors() * 100); } ConsistentHash<Node> hash = new ConsistentHash<Node>(NODE_HASH); hash.addAll(hashSource); for (Node n : hash.list(p.task.getFullDisplayName())) { final Computer c = n.toComputer(); if (n.canTake(p) != null) continue; if (c==null || c.isOffline()) continue; return new Runnable() { @Override public void run() { c.startFlyWeightTask(new WorkUnitContext(p).createWorkUnit(p.task)); makePending(p); } }; } } return null; } else { return new Runnable() { @Override public void run() { p.enter(Queue.this); } }; } }

Target:
private @CheckForNull Runnable makeBuildable(final BuildableItem p) { if (p.task instanceof FlyweightTask) { if (!isBlockedByShutdown(p.task)) { Runnable runnable = makeFlyWeightTaskBuildable(p); if(runnable != null){ return runnable; } return new BuildableRunnable(p); } return null; } else { return new BuildableRunnable(p); } }
Source:
public static boolean isServiceEnabled(String prefix, String name, Properties properties) { ObjectHelper.notNull(prefix, "prefix"); ObjectHelper.notNull(name, "prefix"); ObjectHelper.notNull(properties, "prefix"); if (!prefix.endsWith(".")) { prefix = prefix + "."; } final String group = properties.getProperty(prefix + "enabled", "true"); final String item = properties.getProperty(prefix + name + ".enabled", group); return Boolean.valueOf(item); }

Target:
public static boolean isServiceEnabled(String prefix, String name, Properties properties) { ObjectHelper.notNull(prefix, "prefix"); ObjectHelper.notNull(name, "name"); ObjectHelper.notNull(properties, "properties"); if (!prefix.endsWith(".")) { prefix = prefix + "."; } final String group = properties.getProperty(prefix + "enabled", "true"); final String item = properties.getProperty(prefix + name + ".enabled", group); return Boolean.valueOf(item); }
Source:
public static AggregationFunctionType getAggregationFunctionType(String functionName) { String upperCaseFunctionName = functionName.toUpperCase().replace("_", ""); if (upperCaseFunctionName.startsWith("PERCENTILE")) { String remainingFunctionName = upperCaseFunctionName.substring(10); if (remainingFunctionName.isEmpty() || remainingFunctionName.matches("\\d+")) { return PERCENTILE; } else if (remainingFunctionName.equals("EST") || remainingFunctionName.matches("EST\\d+")) { return PERCENTILEEST; } else if (remainingFunctionName.equals("TDIGEST") || remainingFunctionName.matches("TDIGEST\\d+")) { return PERCENTILETDIGEST; } else if (remainingFunctionName.equals("MV") || remainingFunctionName.matches("\\d+MV")) { return PERCENTILEMV; } else if (remainingFunctionName.equals("ESTMV") || remainingFunctionName.matches("EST\\d+MV")) { return PERCENTILEESTMV; } else if (remainingFunctionName.equals("TDIGESTMV") || remainingFunctionName.matches("TDIGEST\\d+MV")) { return PERCENTILETDIGESTMV; } else { throw new IllegalArgumentException("Invalid aggregation function name: " + functionName); } } else { try { return AggregationFunctionType.valueOf(upperCaseFunctionName); } catch (Exception e) { throw new IllegalArgumentException("Invalid aggregation function name: " + functionName); } } }

Target:
public static AggregationFunctionType getAggregationFunctionType(String functionName) { String upperCaseFunctionName = StringUtils.remove(functionName, '_').toUpperCase(); if (upperCaseFunctionName.startsWith("PERCENTILE")) { String remainingFunctionName = upperCaseFunctionName.substring(10); if (remainingFunctionName.isEmpty() || remainingFunctionName.matches("\\d+")) { return PERCENTILE; } else if (remainingFunctionName.equals("EST") || remainingFunctionName.matches("EST\\d+")) { return PERCENTILEEST; } else if (remainingFunctionName.equals("TDIGEST") || remainingFunctionName.matches("TDIGEST\\d+")) { return PERCENTILETDIGEST; } else if (remainingFunctionName.equals("MV") || remainingFunctionName.matches("\\d+MV")) { return PERCENTILEMV; } else if (remainingFunctionName.equals("ESTMV") || remainingFunctionName.matches("EST\\d+MV")) { return PERCENTILEESTMV; } else if (remainingFunctionName.equals("TDIGESTMV") || remainingFunctionName.matches("TDIGEST\\d+MV")) { return PERCENTILETDIGESTMV; } else { throw new IllegalArgumentException("Invalid aggregation function name: " + functionName); } } else { try { return AggregationFunctionType.valueOf(upperCaseFunctionName); } catch (Exception e) { throw new IllegalArgumentException("Invalid aggregation function name: " + functionName); } } }