auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AuditLogType getAuditLogTypeValue() { UserProfile existingProfile = getUserProfile(); if (existingProfile != null && isSSHPublicKeyUpdate(existingProfile)) { return getSucceeded() ? AuditLogType.USER_UPDATE_PROFILE : AuditLogType.USER_UPDATE_PROFILE_FAILED; } else { return getSucceeded() ? AuditLogType.USER_ADD_PROFILE : AuditLogType.USER_ADD_PROFILE_FAILED; } }

Target:
public AuditLogType getAuditLogTypeValue() { UserProfile existingProfile = getUserProfile(); if (existingProfile != null) { /* same as executeCommand below */ return getSucceeded() ? AuditLogType.USER_UPDATE_PROFILE : AuditLogType.USER_UPDATE_PROFILE_FAILED; } else { return getSucceeded() ? AuditLogType.USER_ADD_PROFILE : AuditLogType.USER_ADD_PROFILE_FAILED; } }
Source:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); // Off heap and compatibility don't work together configurationBuilder.compatibility().disable(); return configurationBuilder; }

Target:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); return configurationBuilder; }
Source:
public boolean counter(String key, int magnitude) { String stat = String.format(Locale.ENGLISH, "%s:%d|c", key, magnitude); return maybeAppend(stat); }

Target:
public boolean counter(String key, int magnitude) { String stat = String.format("%s:%d|c", key, magnitude); return maybeAppend(stat); }
Source:
public String parse() { StringBuilder myCommandBuilder = new StringBuilder(""); for (String argument:mArgs) { myCommandBuilder.append(argument+" "); } return myCommandBuilder.toString(); }

Target:
public String parse() { StringBuilder myCommandBuilder = new StringBuilder(""); for (String argument : mArgs) { myCommandBuilder.append(argument); myCommandBuilder.append(" "); } return myCommandBuilder.toString(); }
Source:
public long cyclesToNanos(long cycles) { // CTFTrace adds the clock offset in cycles to the input CTFTrace trace = fTrace; if (trace != null) { CTFClock clock = trace.getClock(); return trace.timestampCyclesToNanos(cycles - trace.getOffset()) + clock.getClockOffsetNs(); } return 0; }

Target:
public long cyclesToNanos(long cycles) { // CTFTrace adds the clock offset in cycles to the input CTFTrace trace = fTrace; if (trace != null) { return trace.timestampCyclesToNanos(cycles - trace.getOffset()); } return 0; }
Source:
public void createAndSetPhoneHome() { this.phoneHome = new PhoneHome(node); }

Target:
protected void createAndSetPhoneHome() { this.phoneHome = new PhoneHome(node); }
Source:
protected void verifySafeObject(final AnyObjectId id, final int type, final byte[] data) { try { super.verifySafeObject(id, type, data); } catch (CorruptObjectException e) { // catch the exception and continue parse the pack file CorruptObject o = new CorruptObject(id.toObjectId(), type, e.getErrorType()); corruptObjects.add(o); } }

Target:
protected void verifySafeObject(final AnyObjectId id, final int type, final byte[] data) { try { super.verifySafeObject(id, type, data); } catch (CorruptObjectException e) { corruptObjects.add( new CorruptObject(id.toObjectId(), type, e.getErrorType())); } }
Source:
public static ServerManager getInstance( final WorkspaceStatus wsStatus ) { if (instance == null) { instance = new ServerManager(); } instance.setWorkspaceStatus(wsStatus); return instance; }

Target:
public static ServerManager getInstance( final WorkspaceStatus wsStatus ) { if (instance == null) { instance = new ServerManager(); instance.wsStatus = wsStatus; } return instance; }
Source:
public WebAccess addUserAgent(String userAgent) { if (Objects.nonNull(userAgent)) this.userAgent = userAgent; return this; }

Target:
public WebAccess addUserAgent(String userAgent) { this.userAgent = userAgent; return this; }
Source:
private static MessageType getProjection(MessageType schema, Collection<SchemaPath> projectionColumns, List<SchemaPath> columnsNotFound) { projectionColumns = adaptColumnsToParquetSchema(projectionColumns, schema); List<SchemaPath> schemaColumns = getAllColumnsFrom(schema); Set<SchemaPath> selectedSchemaPaths = matchProjectionWithSchemaColumns(projectionColumns, schemaColumns, columnsNotFound); MessageType projection = convertSelectedColumnsToMessageType(schema, selectedSchemaPaths); return projection; }

Target:
private static MessageType getProjection(MessageType schema, Collection<SchemaPath> projectionColumns, List<SchemaPath> columnsNotFound) { projectionColumns = adaptColumnsToParquetSchema(projectionColumns, schema); List<SchemaPath> schemaColumns = getAllColumnsFrom(schema); Set<SchemaPath> selectedSchemaPaths = matchProjectionWithSchemaColumns(projectionColumns, schemaColumns, columnsNotFound); return convertSelectedColumnsToMessageType(schema, selectedSchemaPaths); }
Source:
private FileObject ingestFileObject(ContentObject parent, Resource parentResc, Resource childResc) throws DepositException, IOException { if (skipResumed(childResc)) { return null; } // TODO add ACLs WorkObject work = (WorkObject) parent; FileObject obj = addFileToWork(work, childResc); // Add ingestion event for file object addIngestionEventForChild(obj); addPremisEvents(obj); // add MODS addDescription(work); // Increment the count of objects deposited addClicks(1); log.info("Created file object for deposit {}", obj.getPid(), getDepositPID()); return obj; }

Target:
private void ingestFileObject(ContentObject parent, Resource parentResc, Resource childResc) throws DepositException, IOException { if (skipResumed(childResc)) { return; } // TODO add ACLs WorkObject work = (WorkObject) parent; FileObject obj = addFileToWork(work, childResc); // Add ingestion event for file object addIngestionEventForChild(obj); addPremisEvents(obj); // add MODS addDescription(obj); // Increment the count of objects deposited addClicks(1); log.info("Created file object for deposit {}", obj.getPid(), getDepositPID()); }
Source:
public int hashCode() { return hash(getHost(), getPort(), getPassword(), getUsername(), getNonProxyHosts(), ntlmDomain); }

Target:
public int hashCode() { return hash(super.hashCode(), ntlmDomain); }
Source:
protected static boolean canAttachPrestartedVmToUser(Guid vmId) { // check that there isn't another user already attached to this VM: boolean returnValue = !vmAssignedToUser(vmId, new java.util.ArrayList<String>()); // Make sure the Vm is running stateless returnValue = returnValue && vmIsRunningStateless(vmId); return returnValue; }

Target:
protected static boolean canAttachPrestartedVmToUser(Guid vmId) { // check that there isn't another user already attached to this VM // and make sure the Vm is running stateless return !vmAssignedToUser(vmId, new ArrayList<String>()) && vmIsRunningStateless(vmId); }
Source:
protected boolean handlePreloadPackage(String packagePath, String libsPath) { Log.d(TAG, "Preload package ********************************************************"); Log.d(TAG, "WebView package = " + packagePath); return false; }

Target:
protected boolean handlePreloadPackage(String packagePath, String libsPath) { // TODO: Use preload information to setup the ClassLoader. return false; }
Source:
protected void cancelled() { logger.debug("Subscriber cancelled, ignoring the rest of the body"); try { future.done(); } catch (Exception t) { // Never propagate exception once we know we are done. logger.error(t.getMessage(), t); } // The subscriber cancelled early - this channel is dead and should be closed. channelManager.releaseChannelLock(future.getPartitionKey()); channelManager.closeChannel(channel); channel.pipeline().remove(StreamedResponsePublisher.class); }

Target:
protected void cancelled() { logger.debug("Subscriber cancelled, ignoring the rest of the body"); try { future.done(); } catch (Exception t) { // Never propagate exception once we know we are done. logger.debug(t.getMessage(), t); } // The subscriber cancelled early - this channel is dead and should be closed. channelManager.closeChannel(channel); }
Source:
public void initializeDataSource(ITmfTrace trace) { TmfAbstractAnalysisModule module = createStatisticsAnalysiModule(); if (!(module instanceof AbstractSegmentStatisticsAnalysis)) { // null or not a segment analysis module return; } try { module.setTrace(trace); module.schedule(); if (fModule != null) { fModule.dispose(); } fModule = (AbstractSegmentStatisticsAnalysis) module; } catch (TmfAnalysisException e) { Activator.getDefault().logError("Error initializing statistics analysis module", e); //$NON-NLS-1$ } }

Target:
public void initializeDataSource(ITmfTrace trace) { TmfAbstractAnalysisModule module = createStatisticsAnalysiModule(); if (module == null) { return; } try { module.setTrace(trace); module.schedule(); if (fModule != null) { fModule.dispose(); } fModule = module; } catch (TmfAnalysisException e) { Activator.getDefault().logError("Error initializing statistics analysis module", e); //$NON-NLS-1$ } }
Source:
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { if (extras != null) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }

Target:
@Override public void onReceive(Context context, Intent intent) { // On some versions of Android this may be called with a null Intent if (null == intent) { return; } String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }
Source:
public Map<String, Object> introspect(String token) { TokenIntrospectionSuccessResponse response = Optional.of(this.requestEntityConverter.convert(token)) .map(this::makeRequest) .map(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) // relying solely on the authorization server to validate this token (not checking 'exp', for example) .filter(TokenIntrospectionSuccessResponse::isActive) .orElseThrow(() -> new OAuth2IntrospectionException("Provided token [" + token + "] isn't active")); return convertClaimsSet(response); }

Target:
public Map<String, Object> introspect(String token) { TokenIntrospectionSuccessResponse response = Optional.of(token) .map(this.requestEntityConverter::convert) .map(this::makeRequest) .map(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) // relying solely on the authorization server to validate this token (not checking 'exp', for example) .filter(TokenIntrospectionSuccessResponse::isActive) .orElseThrow(() -> new OAuth2IntrospectionException("Provided token [" + token + "] isn't active")); return convertClaimsSet(response); }
Source:
public static boolean validate() { boolean valid = true; for (Map.Entry<String, String> entry : toMap().entrySet()) { String propertyName = entry.getKey(); if (!PropertyKey.isValid(propertyName)) { LOG.warn("Unsupported property {}" + propertyName); valid = false; } } return valid; }

Target:
public static boolean validate() { boolean valid = true; for (Map.Entry<String, String> entry : toMap().entrySet()) { String propertyName = entry.getKey(); if (!PropertyKey.isValid(propertyName)) { LOG.warn("Unsupported property {}", propertyName); valid = false; } } return valid; }
Source:
public String BuildJSON() { if (swagger != null) { updateHostAndBasePath(); } else { synchronized (this) { log.info("Initiating Swagger specification creation"); toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); // addSubclassOperations(); //FIXME uncomment after fixing the method } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } } return createJSON(); }

Target:
private void BuildJSON() { synchronized (this) { log.info("Initiating Swagger specification creation"); toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); // addSubclassOperations(); //FIXME uncomment after fixing the method } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } }
Source:
static List<TypeName> list(Type[] types) { List<TypeName> result = new ArrayList<>(types.length); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < types.length; i++) { result.add(get(types[i])); } return result; }

Target:
static List<TypeName> list(Type[] types) { List<TypeName> result = new ArrayList<>(types.length); for (Type type : types) { result.add(get(type)); } return result; }
Source:
public Map<String, Integer> getRemainingQueries() { synchronized (this) { Map<String, Integer> queriesInfo = new HashMap<String, Integer>(); queriesInfo.put("queriesCount", queries.size()); queriesInfo.put("fragmentsCount", runningFragments.size()); return queriesInfo; } }

Target:
public synchronized Map<String, Integer> getRemainingQueries() { Map<String, Integer> queriesInfo = new HashMap<String, Integer>(); queriesInfo.put("queriesCount", queries.size()); queriesInfo.put("fragmentsCount", runningFragments.size()); return queriesInfo; }
Source:
public void connectDisconnect() throws IOException { final FtpFacade facade = FtpFacadeTest.mockFacade(); final FTPClient ftp = new FTPClient(); try { facade.listen(); ftp.connect("localhost"); final int reply = ftp.getReplyCode(); MatcherAssert.assertThat( FTPReply.isPositiveCompletion(reply), Matchers.equalTo(true) ); MatcherAssert.assertThat( ftp.logout(), Matchers.equalTo(true) ); } finally { facade.close(); } }

Target:
public void connectDisconnect() throws IOException { final FtpFacade facade = FtpFacadeTest.mockFacade(); final FTPClient ftp = new FTPClient(); try { facade.listen(); ftp.connect("localhost"); MatcherAssert.assertThat( FTPReply.isPositiveCompletion(ftp.getReplyCode()), Matchers.equalTo(true) ); MatcherAssert.assertThat( ftp.logout(), Matchers.equalTo(true) ); } finally { facade.close(); } }
Source:
public Parser<I, Stream<A>, E> repeat1() { return bind(a -> repeat().map(new F<Stream<A>, Stream<A>>() { public Stream<A> f(final Stream<A> as) { return as.cons(a); } })); }

Target:
public Parser<I, Stream<A>, E> repeat1() { return bind(a -> repeat().map(as -> as.cons(a))); }
Source:
public String getLanguage() { if (null == this.language) { return ""; //$NON-NLS-1$ } return this.language; }

Target:
public String getLanguage() { return this.language!=null ? this.language : "" ; //$NON-NLS-1$ }
Source:
public boolean isMarshallable(Object o) { // Protostream can handle all of these type as well if (o instanceof String || o instanceof Long || o instanceof Integer || o instanceof Double || o instanceof Float || o instanceof Boolean || o instanceof byte[] || o instanceof Enum) { return true; } return getSerializationContext().canMarshall(o.getClass()); }

Target:
public boolean isMarshallable(Object o) { // Protostream can handle all of these type as well if (o instanceof String || o instanceof Long || o instanceof Integer || o instanceof Double || o instanceof Float || o instanceof Boolean || o instanceof byte[]) { return true; } return getSerializationContext().canMarshall(o.getClass()); }
Source:
public String getDeepRepresentation(CtElement elem) { EqualVisitor prThis = new EqualVisitor(); prThis.scan(elem); return prThis.getRepresentation(); }

Target:
private String getDeepRepresentation(CtElement elem) { EqualVisitor prThis = new EqualVisitor(); prThis.scan(elem); return prThis.getRepresentation(); }
Source:
public KSyntax2GrammarStatesFilter(Context context) { super(KSyntax2GrammarStatesFilter.class.getName(), context); // create a NonTerminal for every declared sort for (String sort : context.definedSorts) { NonTerminal nt = new NonTerminal(new NonTerminalId(sort)); grammar.add(nt); } }

Target:
public KSyntax2GrammarStatesFilter(Context context) { super(KSyntax2GrammarStatesFilter.class.getName(), context); // create a NonTerminal for every declared sort for (String sort : context.definedSorts) { grammar.add(new NonTerminal(sort)); } }
Source:
protected void onNewIntent(Intent intent) { // This is called when the user press Home again while already browsing MainActivity // onResume() will be called right after, hiding the kissbar if any. // http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) // Animation can't happen in this method, since the activity is not resumed yet, so they'll happen in the onResume() // https://github.com/Neamar/KISS/issues/569 if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } // Hide kissbar when coming back to kiss if (isViewingAllApps()) { displayKissBar(false); } // Close the backButton context menu MainActivity.this.closeContextMenu(); }

Target:
protected void onNewIntent(Intent intent) { // This is called when the user press Home again while already browsing MainActivity // onResume() will be called right after, hiding the kissbar if any. // http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) // Animation can't happen in this method, since the activity is not resumed yet, so they'll happen in the onResume() // https://github.com/Neamar/KISS/issues/569 if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } // Hide kissbar when coming back to kiss if (isViewingAllApps()) { displayKissBar(false); } // Close the backButton context menu closeContextMenu(); }
Source:
public byte[] getData() { Object base = slice.getBase(); checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); byte[] bytes = (byte[]) base; if (slice.isCompact()) { return bytes; } // do a copy return slice.getBytes(); }

Target:
public byte[] getData() { if (slice.isCompact()) { Object base = slice.getBase(); checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); return (byte[]) base; } // do a copy return slice.getBytes(); }
Source:
public RedisPublishingMessageHandler(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "connectionFactory must not be null"); this.template = new RedisTemplate(); this.template.setConnectionFactory(connectionFactory); this.template.setEnableDefaultSerializer(false); this.template.afterPropertiesSet(); }

Target:
public RedisPublishingMessageHandler(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "connectionFactory must not be null"); this.template = new RedisTemplate<Object, Object>(); this.template.setConnectionFactory(connectionFactory); this.template.setEnableDefaultSerializer(false); this.template.afterPropertiesSet(); }
Source:
public AnnotationCommandTargetResolver build() { try { return resolver; } finally { resolver = null; // builder can only be used once. } }

Target:
public AnnotationCommandTargetResolver build() { return new AnnotationCommandTargetResolver(this); }
Source:
private void setWidgetsEnabled(final boolean enabled, final Control... controls) { for (Control control : controls) { control.setEnabled(enabled); } // set the focus on the fist element of the group. if (controls.length > 0 && enabled) { for (Control control : controls) { if (control instanceof Text) { control.setFocus(); break; } } } }

Target:
private void setWidgetsEnabled(final boolean enabled, final Control... controls) { for (Control control : controls) { control.setEnabled(enabled); } // set the focus on the fist element of the group. if (enabled) { for (Control control : controls) { if (control instanceof Text) { control.setFocus(); break; } } } }
Source:
private boolean filterInvalid(Position position) { return filterInvalid && !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180 || position.getLatitude() < -90 || position.getLongitude() < -180; }

Target:
private boolean filterInvalid(Position position) { if (filterInvalid == true) { return !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180 || position.getLatitude() < -90 || position.getLongitude() < -180; } return false; }
Source:
public CreateDDiagramElementCommand(final TransactionalEditingDomain domain, final EObject semantic, final EdgeMapping mapping, final EdgeTarget source, final EdgeTarget target) { this(domain, semantic); edgeCandidate = new DEdgeCandidate(mapping, semantic, source, target, RefreshIdsHolder.getOrCreateHolder(getParentDiagram())); /* store source as container to retrieve later parent diagram */ this.container = (DragAndDropTarget) source; }

Target:
public CreateDDiagramElementCommand(final TransactionalEditingDomain domain, final EObject semantic, final EdgeMapping mapping, final EdgeTarget source, final EdgeTarget target) { this(domain, semantic); /* store source as container to retrieve later parent diagram */ this.container = (DragAndDropTarget) source; edgeCandidate = new DEdgeCandidate(mapping, semantic, source, target, RefreshIdsHolder.getOrCreateHolder(getParentDiagram())); }
Source:
public Tuple<Table> table(final String tableName, HiveConf conf) throws HiveException { // Column statistics won't be accurate if we are dumping only metadata boolean getColStats = !conf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY); return new Tuple<>(functionForSpec, () -> db.getTable(dbName, tableName, false, false, getColStats)); }

Target:
public Tuple<Table> table(final String tableName, HiveConf conf) throws HiveException { // Column statistics won't be accurate if we are dumping only metadata boolean getColStats = !conf.getBoolVar(HiveConf.ConfVars.REPL_DUMP_METADATA_ONLY); return new Tuple<>(functionForSpec, () -> db.getTable(dbName, tableName, true, false, getColStats)); }
Source:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); // In order to enable KERBEROS authentication method for HDFS // UserGroupInformation.authenticationMethod static field must be set to KERBEROS // It is further used in many places in DfsClient configuration.set("hadoop.security.authentication", "kerberos"); // Set the static configuration to get the rules. try { HadoopKerberosName.setConfiguration(configuration); } catch (IOException exception) { throw new UncheckedIOException(exception); } UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }

Target:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); // In order to enable KERBEROS authentication method for HDFS // UserGroupInformation.authenticationMethod static field must be set to KERBEROS // It is further used in many places in DfsClient configuration.set("hadoop.security.authentication", "kerberos"); UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }
Source:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } // Cleanup directories final Path workDir = PATH.getParent(); if (Files.exists(workDir)) { Files.deleteIfExists(PATH); } }

Target:
public void tearDown() throws Exception { if (this.fileWatcher != null) { this.fileWatcher.close(); } }
Source:
List<Object> getColumn(int columnIndex) { ArrayList<Object> result = new ArrayList<Object>(); for (Object[] compoundDatum : compoundData) { result.add(compoundDatum[columnIndex]); } return result; }

Target:
public List<Object> getColumn(int columnIndex) { List<Object> result = new ArrayList<>(); for (Object[] compoundDatum : compoundData) { result.add(compoundDatum[columnIndex]); } return result; }
Source:
private static CharSequence getScreenSecuritySummary(Context context) { final int screenSecurityResId = R.string.preferences__screen_security_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isScreenSecurityEnabled(context)) return context.getString(screenSecurityResId, onRes); return context.getString(screenSecurityResId, offRes); }

Target:
private static CharSequence getScreenSecuritySummary(Context context) { final int screenSecurityResId = R.string.preferences__screen_security_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isScreenSecurityEnabled(context)) { return context.getString(screenSecurityResId, onRes); } else { return context.getString(screenSecurityResId, offRes); } }
Source:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { mLoading = true; } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1, totalItemCount); } }

Target:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { mLoading = true; } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1); } }
Source:
public void run() { try { this.thread.dispatch(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); Logger.warn(this, "%s", ex); // @checkstyle IllegalCatch (1 line) } catch (final Throwable ex) { Logger.error(this, "%s", ExceptionUtils.getStackTrace(ex)); } }

Target:
public void run() { try { this.thread.dispatch(); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); Logger.warn(this, "%s", ex); } }
Source:
private boolean acceptGroup(NuxeoPrincipal originatingPrincipal, String groupName) { return originatingPrincipal.isAdministrator() || originatingPrincipal.getAllGroups().contains(groupName); }

Target:
protected boolean acceptGroup(NuxeoPrincipal originatingPrincipal, String groupName) { return originatingPrincipal.isAdministrator() || originatingPrincipal.getAllGroups().contains(groupName); }
Source:
public static SchemaPath getCompoundPath(String... strings) { NameSegment s = null; final int length = strings.length; // loop through strings in reverse order for (int i = 0; i < length; i++) { s = new NameSegment(strings[length - 1 - i], s); } return new SchemaPath(s); }

Target:
public static SchemaPath getCompoundPath(String... strings) { NameSegment s = null; // loop through strings in reverse order for (int i = strings.length - 1; i >= 0; i--) { s = new NameSegment(strings[i], s); } return new SchemaPath(s); }
Source:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { try { lock.lock(); return map.put("key" + key, "value" + key); } finally { lock.unlock(); } }); }

Target:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { lock.lock(); try { return map.put("key" + key, "value" + key); } finally { lock.unlock(); } }); }
Source:
public QueryContext(final UserSession session, final DrillbitContext drillbitContext, QueryId queryId) { this(session, drillbitContext, queryId, null); }

Target:
public QueryContext(final UserSession session, final DrillbitContext drillbitContext, QueryId queryId) { this(session, drillbitContext, queryId, 0); }
Source:
public Statistic createHugePagesFree(HugePage page) { return setDatum( create("hugepages." + page.getSizeKB() + ".free", "Amount of free huge pages of the given size", GAUGE, NONE, INTEGER), page.getAmount()); }

Target:
private Statistic createHugePagesFree(HugePage page) { return setDatum( create("hugepages." + page.getSizeKB() + ".free", "Amount of free huge pages of the given size", GAUGE, NONE, INTEGER), page.getAmount()); }
Source:
private Optional<LocalMemoryContext> getSystemMemoryContext() { try { return Optional.of(systemMemoryContextSupplier.get()); } catch (Exception ignored) { // This is possible with races, e.g., a task is created and then immediately aborted, // so that the task context hasn't been created yet (as a result there's no memory context available). } return Optional.empty(); }

Target:
private Optional<LocalMemoryContext> getSystemMemoryContext() { try { return Optional.of(systemMemoryContextSupplier.get()); } catch (RuntimeException ignored) { // This is possible with races, e.g., a task is created and then immediately aborted, // so that the task context hasn't been created yet (as a result there's no memory context available). } return Optional.empty(); }
Source:
private boolean isFilterExpressionValid(InetAddress inetAddress, String filterExpression) { // Consider profiles without filter expression or an empty one as matching. if (Strings.isNullOrEmpty(filterExpression)) { return true; } else { try { return filterDao.isValid(inetAddress.getHostAddress(), filterExpression); } catch (FilterParseException e) { LOG.warn("Filter expression '{}' is invalid. ", e); } } return false; }

Target:
private boolean isFilterExpressionValid(InetAddress inetAddress, String filterExpression) { // Consider profiles without filter expression or an empty one as matching. if (Strings.isNullOrEmpty(filterExpression)) { return true; } else { try { return filterDao.isValid(inetAddress.getHostAddress(), filterExpression); } catch (FilterParseException e) { LOG.warn("Filter expression '{}' is invalid. ", filterExpression, e); } } return false; }
Source:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } }, new Command() { @Override public void execute() { //do nothing. } } ); } else { //just rename. rename( false ); } }

Target:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } } ); } else { //just rename. rename( false ); } }
Source:
public void disableAutoLimit() { autoLimitRowCount = null; }

Target:
public void disableAutoLimit() { autoLimitRowCount = 0; }
Source:
public void closeThisNode(long endtime) { super.closeThisNode(endtime); fListeners.stream().forEach(l -> l.nodeClosed(this, endtime)); }

Target:
public void closeThisNode(long endtime) { super.closeThisNode(endtime); fListeners.forEach(l -> l.nodeClosed(this, endtime)); }
Source:
public void dispose() { //Remove all message from the queue this.h.removeCallbacksAndMessages(null); this.parent.dispose(); this.h = null; this.owner = null; this.parent = null; }

Target:
public void dispose() { }
Source:
private static URL mapToURL(String path) { try { return new URL(path); } catch (MalformedURLException e) { try { return new File(path).toURI().toURL(); } catch (MalformedURLException e1) { throw new IllegalStateException(e1); } } }

Target:
private static URL mapToURL(String path) { try { return new URL(path); } catch (MalformedURLException e) { try { return new File(path).toURI().toURL(); } catch (MalformedURLException e1) { throw new IllegalArgumentException(e1); } } }
Source:
void addAdditionalDependencies(Set<String> back) throws Exception { if (additionalDependencies != null) { for (Dependency dependency : additionalDependencies) { addToClasspath(factory.createDependencyArtifact(dependency), back, false); } } }

Target:
protected void addAdditionalDependencies(Set<String> back) throws Exception { if (additionalDependencies != null) { for (Dependency dependency : additionalDependencies) { addToClasspath(factory.createDependencyArtifact(dependency), back, false); } } }
Source:
@Override public void track(TrackPayload track) { super.track(track); Double value = track.properties().getDouble("value", Double.MIN_VALUE); if (value.equals(Double.MIN_VALUE)) { Apptimize.track(track.event()); } else { Apptimize.track(track.event(), value); } }

Target:
@Override public void track(TrackPayload track) { super.track(track); double value = track.properties().getDouble("value", Double.MIN_VALUE); if (value == Double.MIN_VALUE) { Apptimize.track(track.event()); } else { Apptimize.track(track.event(), value); } }
Source:
Delete(String keyspace, String table, List<Selector> columns) { super(keyspace); this.table = table; this.columns = columns; this.where = new Where(this); this.usings = new Options(this); this.conditions = new Conditions(this); // This is for JAVA-1089, if the query deletes an element in a list, the statement should be non-idempotent. for (Selector sel : columns) { if (sel instanceof CollectionElementSelector) { if (((CollectionElementSelector) sel).key instanceof Integer) { setNonIdempotentOps(); } } } }

Target:
Delete(String keyspace, String table, List<Selector> columns) { this(keyspace, table, null, null, columns); }
Source:
File remove(long sizeInBytes) { File reserveFile = null; Queue<File> reserveFilesForSize = internalMap.get(sizeInBytes); if (reserveFilesForSize != null) { if (reserveFilesForSize.size() != 0) { reserveFile = reserveFilesForSize.remove(); } } return reserveFile; }

Target:
File remove(long sizeInBytes) { File reserveFile = null; Queue<File> reserveFilesForSize = internalMap.get(sizeInBytes); if (reserveFilesForSize != null && reserveFilesForSize.size() != 0) { reserveFile = reserveFilesForSize.remove(); } return reserveFile; }
Source:
public void testNestedInvalidateAndApplyCompletes() throws Exception { final AtomicBoolean hasRun = new AtomicBoolean(); final SideEffect innerSideEffect = SideEffect.createPaused(() -> { }).resume(); SideEffect.createPaused(() -> { // Make sure that there are no infinite loops. assertFalse(hasRun.get()); hasRun.set(true); innerSideEffect.markDirty(); innerSideEffect.runIfDirty(); }).resume(); runAsync(); assertTrue(hasRun.get()); }

Target:
public void testNestedInvalidateAndApplyCompletes() throws Exception { AtomicBoolean hasRun = new AtomicBoolean(); SideEffect innerSideEffect = SideEffect.createPaused(() -> { }); innerSideEffect.resume(); SideEffect.createPaused(() -> { // Make sure that there are no infinite loops. assertFalse(hasRun.get()); hasRun.set(true); innerSideEffect.markDirty(); innerSideEffect.runIfDirty(); }).resume(); runAsync(); assertTrue(hasRun.get()); }
Source:
protected void queueRequest(final ITmfDataRequest request) { if (fExecutor == null || fExecutor.isShutdown()) { request.cancel(); return; } TmfEventThread thread = new TmfEventThread(this, request); if (TmfCoreTracer.isRequestTraced()) { TmfCoreTracer.traceRequest(request, "QUEUED"); //$NON-NLS-1$ } fExecutor.execute(thread); }

Target:
protected void queueRequest(final ITmfDataRequest request) { if (fExecutor.isShutdown()) { request.cancel(); return; } TmfEventThread thread = new TmfEventThread(this, request); if (TmfCoreTracer.isRequestTraced()) { TmfCoreTracer.traceRequest(request, "QUEUED"); //$NON-NLS-1$ } fExecutor.execute(thread); }
Source:
public void onCompleted() { long r = get(); if (r != Long.MIN_VALUE) { actual.onCompleted(); } }

Target:
public void onCompleted() { if (get() != Long.MIN_VALUE) { actual.onCompleted(); } }
Source:
public void testEmailWith64CharacterLocalPartIsValid() { // Local part should allow up to 64 octets: https://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 for (int num = 1; num < 64; num++) { isValidEmail( stringOfLength( num ) + "@foo.com" ); } }

Target:
public void testEmailWith64CharacterLocalPartIsValid() { // Local part should allow up to 64 octets: https://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 for (int num = 1; num <= 64; num++) { isValidEmail( stringOfLength( num ) + "@foo.com" ); } }
Source:
public void testCrossSourceMultiFragmentJoin() throws Exception { try { client.alterSession(ExecConstants.SLICE_TARGET, 1); client.queryBuilder() .sql("select x.person_id, y.salary from h2.drill_h2_test.person x " + "join %s y on x.person_id = y.person_id ", TABLE_NAME) .run(); } finally { client.resetSession(ExecConstants.SLICE_TARGET); } }

Target:
public void testCrossSourceMultiFragmentJoin() throws Exception { try { client.alterSession(ExecConstants.SLICE_TARGET, 1); run("select x.person_id, y.salary from h2.drill_h2_test.person x " + "join %s y on x.person_id = y.person_id ", TABLE_NAME); } finally { client.resetSession(ExecConstants.SLICE_TARGET); } }
Source:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); for (String name : names) { comboBox.add(name); } // pre-selects the elements that are now in the action: comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); }

Target:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); names.forEach(comboBox::add); // pre-selects the elements that are now in the action: comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); }
Source:
public void fireModelChanged(TestModelChange change) { for (ITestModelListener listener : fListeners) { listener.testModelChanged(change); } }

Target:
public void fireModelChanged(TestModelChange change) { for (int i = 0; i < fListeners.size(); ++i) { ITestModelListener listener = fListeners.get(i); listener.testModelChanged(change); } }
Source:
public boolean isValidAuthorizations(String user, List<ByteBuffer> auths) throws AccumuloSecurityException { if (auths.size() == 0) { // avoid deserializing auths from ZK cache return true; } Authorizations userauths = getCachedUserAuthorizations(user); for (ByteBuffer auth : auths) { if (!userauths.contains(ByteBufferUtil.toBytes(auth))) { return false; } } return true; }

Target:
public boolean isValidAuthorizations(String user, List<ByteBuffer> auths) throws AccumuloSecurityException { if (auths.isEmpty()) { // avoid deserializing auths from ZK cache return true; } Authorizations userauths = getCachedUserAuthorizations(user); for (ByteBuffer auth : auths) { if (!userauths.contains(ByteBufferUtil.toBytes(auth))) { return false; } } return true; }
Source:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; // grab the original request from Spring to forward security related attributes // such as requests host, ports and headers this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(atts -> atts.getRequest()); }

Target:
public FakeHttpServletRequest( Map<String, String> parameterMap, Cookie[] cookies, String workspace) { this.parameterMap = parameterMap; this.cookies = cookies; this.workspace = workspace; // grab the original request from Spring to forward security related attributes // such as requests host, ports and headers this.original = Optional.ofNullable( (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .map(ServletRequestAttributes::getRequest); }
Source:
static Module module() { return new CacheModule() { @Override protected void configure() { final String cacheName = CACHE_NAME; final TypeLiteral<Cache<ActiveSession.Key, ActiveSession>> type = new TypeLiteral<Cache<ActiveSession.Key, ActiveSession>>() {}; core(type, cacheName) // .memoryLimit(1024) // reasonable default for many sites .maxAge(12, HOURS) // expire sessions if they are inactive .evictionPolicy(EvictionPolicy.LRU) // keep most recently used ; bind(WebSession.class).in(RequestScoped.class); } }; }

Target:
static Module module() { return new CacheModule() { @Override protected void configure() { final TypeLiteral<Cache<ActiveSession.Key, ActiveSession>> type = new TypeLiteral<Cache<ActiveSession.Key, ActiveSession>>() {}; core(type, CACHE_NAME) // .memoryLimit(1024) // reasonable default for many sites .maxAge(12, HOURS) // expire sessions if they are inactive .evictionPolicy(EvictionPolicy.LRU) // keep most recently used ; bind(WebSession.class).in(RequestScoped.class); } }; }
Source:
private void setUsernameInRequest() { Http.Session session = Http.Context.current().session(); String email = session.get(ConstantsManager.COOKIE_EMAIL_FIELD_NAME); Controller.request().setUsername(email); }

Target:
private void setUsernameInRequest() { Http.Session session = Http.Context.current().session(); String email = session.get(ConstantsManager.COOKIE_EMAIL_FIELD_NAME); Http.Context.current().request().setUsername(email); }
Source:
private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); // resources can only have three tags: "resourceDoc", "applicationDocs" or "grammars" boolean valid = false; if (xmlTag.compareTo("resourceDoc") == 0) { valid = true; } else if (xmlTag.compareTo("applicationDocs") == 0) { valid = true; } else if (xmlTag.compareTo("grammars") == 0) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } }

Target:
private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); // resources can only have three tags: "resourceDoc", "applicationDocs" or "grammars" boolean valid = false; if (xmlTag.equals("resourceDoc")) { valid = true; } else if (xmlTag.equals("applicationDocs")) { valid = true; } else if (xmlTag.equals("grammars")) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } }
Source:
private String getSetting(String settingName) { SettingKey key = settingKeyDAO.findByName(settingName); if (key != null) { Setting setting = settingDAO.findByKey(key); if (setting != null) return setting.getValue(); } return null; }

Target:
private String getSetting(String settingName) { SettingKey key = settingKeyDAO.findByName(settingName); if (key != null) { Setting setting = settingDAO.findByKey(key); if (setting != null) { return setting.getValue(); } } return null; }
Source:
public float getPrefHeight () { // Min of borders + text height or drawable height layout = new GlyphLayout(style.font, model.getValue().toString()); return Float.max(style.background.getMinHeight(), style.background.getTopHeight() + style.background.getBottomHeight() + layout.height); }

Target:
public float getPrefHeight () { // Max of borders + text height or drawable height return Math.max(style.background.getMinHeight(), style.background.getTopHeight() + style.background.getBottomHeight() + layout.height); }
Source:
public String getJBossDiscoveryDirectory() { // use commandline override -Djboss.discovery.directory.url String directory = System.getProperty(JBOSS_DISCOVERY_DIRECTORY, null); if (directory == null) { IPropertiesProvider pp = PropertiesHelper.getPropertiesProvider(); try { directory = pp.getValue(JBOSS_DISCOVERY_DIRECTORY, new NullProgressMonitor()); } catch (CoreException e) { throw new RuntimeException(e); } } return directory; }

Target:
public String getJBossDiscoveryDirectory() { // use commandline override -Djboss.discovery.directory.url String directory = System.getProperty(JBOSS_DISCOVERY_DIRECTORY, null); if (directory == null) { IPropertiesProvider pp = PropertiesHelper.getPropertiesProvider(); directory = pp.getValue(JBOSS_DISCOVERY_DIRECTORY); } return directory; }
Source:
private void waitForAppToFinish() { workers.shutdown(); try { boolean finishedInTime = workers. awaitTermination(durationMs + APPLICATION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS); String livenessState = finishedInTime ? "Success" : "Fail"; Correctness.recordOperation("Liveness, " + livenessState, false); if (!finishedInTime) { System.exit(0); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { taskProducer.shutdownNow(); checkpointer.shutdownNow(); } }

Target:
private void waitForAppToFinish() { workers.shutdown(); try { boolean finishedInTime = workers. awaitTermination(durationMs + APPLICATION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS); String livenessState = finishedInTime ? "Success" : "Fail"; Correctness.recordOperation("Liveness, " + livenessState, false); if (!finishedInTime) { System.exit(1); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { taskProducer.shutdownNow(); checkpointer.shutdownNow(); } }
Source:
public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(1,key); }

Target:
public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(key); }
Source:
private String createResults() { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", BigintType.BIGINT)), ImmutableList.of(ImmutableList.of(123)), StatementStats.builder().setState("FINISHED").build(), //new StatementStats("FINISHED", false, true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null), null, null, null, null); return QUERY_RESULTS_CODEC.toJson(queryResults); }

Target:
private String createResults() { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", BigintType.BIGINT)), ImmutableList.of(ImmutableList.of(123)), StatementStats.builder().setState("FINISHED").build(), //new StatementStats("FINISHED", false, true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null), null, ImmutableList.of(), null, null); return QUERY_RESULTS_CODEC.toJson(queryResults); }