auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void startListFragment(byte[] bytes, Uri dataUri, String serverQuery, Preferences.CloudSearchPrefs cloudSearchPrefs) { Fragment listFragment = ImportKeysListFragment.newInstance(bytes, dataUri, serverQuery, false, cloudSearchPrefs); getSupportFragmentManager().beginTransaction() .replace(R.id.import_keys_list_container, listFragment, TAG_FRAG_LIST) .commitAllowingStateLoss(); // we commitAllowingStateLoss for when the Activity is already started but an Intent is // received and to be rendered }

Target:
private void startListFragment(byte[] bytes, Uri dataUri, String serverQuery, Preferences.CloudSearchPrefs cloudSearchPrefs) { Fragment listFragment = ImportKeysListFragment.newInstance(bytes, dataUri, serverQuery, false, cloudSearchPrefs); getSupportFragmentManager().beginTransaction() .replace(R.id.import_keys_list_container, listFragment, TAG_FRAG_LIST) .commit(); }
Source:
private static List<String> toStringList(final Object toCast) { // Return object as an ArrayList wherever it's defined as // list or not // // ### Example // object: // - firstValue // - secondValue // ### OR // object: singleValue // ### if (toCast instanceof List) { return (List<String>) toCast; } return Collections.singletonList((String) toCast); }

Target:
private static List<String> toStringList(final Object toCast) { // Return object as an ArrayList wherever it's defined as // list or not // // ### Example // object: // - firstValue // - secondValue // ### OR // object: singleValue // ### if (toCast instanceof List) { return (List<String>) toCast; } return new ArrayList<String>(Arrays.asList((String) toCast)); }
Source:
protected String getNameFromTopic(String topic) { if (!topic.startsWith(prefix)) { throw new IllegalArgumentException(String.format("topic %s with invalid prefix %s", topic, prefix)); } return topic.replaceFirst(prefix, ""); }

Target:
protected String getNameFromTopic(String topic) { if (!topic.startsWith(prefix)) { throw new IllegalArgumentException(String.format("topic %s with invalid prefix %s", topic, prefix)); } return topic.substring(prefix.length()); }
Source:
public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { log.info("_____spring scanning________*******************"); initializeSpring(configuration, environment); // Do the dropwizard registrations addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); }

Target:
public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { initializeSpring(configuration, environment); // Do the dropwizard registrations addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); }
Source:
private static JSONObject createJsonFileObject(InputStream stream) throws IOException, JSONException { String line; StringBuilder result = new StringBuilder(); // Reads from stream BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { // Read each line of the GeoJSON file into a string while ((line = reader.readLine()) != null) { result.append(line); } } finally { reader.close(); } // Converts the result string into a JSONObject return new JSONObject(result.toString()); }

Target:
private static JSONObject createJsonFileObject(InputStream stream) throws IOException, JSONException { String line; StringBuilder result = new StringBuilder(); // Reads from stream BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // Read each line of the GeoJSON file into a string while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); // Converts the result string into a JSONObject return new JSONObject(result.toString()); }
Source:
private boolean isNestedCopyfile(CopyFile copyfile) { if (copyfile.dest.indexOf('/') == -1) // If the copyfile is at root level then it won't be nested. return false; for (RepoProject proj : filteredProjects) { if (proj.getPath().compareTo(copyfile.dest) > 0) // Early return as remaining projects can't be ancestor of this // copyfile config (filteredProjects is sorted). return false; if (proj.isAncestorOf(copyfile.dest)) { return true; } } return false; }

Target:
private boolean isNestedCopyfile(CopyFile copyfile) { if (copyfile.dest.indexOf('/') == -1) { // If the copyfile is at root level then it won't be nested. return false; } for (RepoProject proj : filteredProjects) { if (proj.getPath().compareTo(copyfile.dest) > 0) { // Early return as remaining projects can't be ancestor of this // copyfile config (filteredProjects is sorted). return false; } if (proj.isAncestorOf(copyfile.dest)) { return true; } } return false; }
Source:
private String getCurrentUser() { // authenticator is not used if there is not any user Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); return accountList[0].name; }

Target:
private String getCurrentUser() { // authenticator is not used if there is not any user Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); if (accountList != null && accountList.length > 0) { return accountList[0].name; } return null; }
Source:
private void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to delete a .java file that could be parsed without errors, and we can calculate the //className then we can check for class usages prior to deletion. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file deletion procedure. onDelete(versionRecordManager.getPathToLatest()); } }

Target:
public void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to delete a .java file that could be parsed without errors, and we can calculate the //className then we can check for class usages prior to deletion. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file deletion procedure. onDelete(versionRecordManager.getPathToLatest()); } }
Source:
private boolean deleteRef() { if (!fs.retryFailedLockFileCommit()) return ref.delete(); // file deletion fails on windows if another // thread is reading the file concurrently // So let's try 10 times... for (int i = 0; i < 10; i++) { if (ref.delete()) { return true; } try { Thread.sleep(100); } catch (InterruptedException e) { // ignore } } return false; }

Target:
private boolean deleteRef() { if (!fs.retryFailedLockFileCommit()) return ref.delete(); // file deletion fails on windows if another // thread is reading the file concurrently // So let's try 10 times... for (int i = 0; i < 10; i++) { if (ref.delete()) return true; try { Thread.sleep(100); } catch (InterruptedException e) { return false; } } return false; }
Source:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } if (FeatureSupported.cinderProviderSupported(getStoragePool().getCompatibilityVersion())) { // Unregister all libvirt secrets if needed unregisterLibvirtSecrets(); } }

Target:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } unregisterLibvirtSecrets(); }
Source:
public static void beforeClass() throws Exception { // Create a user adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUsername(StackConfigurationSingleton.singleton().getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfigurationSingleton.singleton().getMigrationAdminAPIKey()); synapse = new SynapseClientImpl(); userId = SynapseClientHelper.createUser(adminSynapse, synapse); }

Target:
public static void beforeClass() throws Exception { // Create a user adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUsername(StackConfigurationSingleton.singleton().getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfigurationSingleton.singleton().getMigrationAdminAPIKey()); synapse = new SynapseClientImpl(); userId = SynapseClientHelper.createUser(adminSynapse, synapse); SynapseClientHelper.setEndpoints(synapse); }
Source:
public void close() { waitForSendComplete(); // Close the buffers before closing the operators; this is needed as buffer ownership // is attached to the receive operators. suppressingClose(buffers); // close operator context for (OperatorContextImpl opContext : contexts) { suppressingClose(opContext); } closeNotConsumedRFWs(); suppressingClose(bufferManager); suppressingClose(allocator); }

Target:
public void close() { waitForSendComplete(); // Close the buffers before closing the operators; this is needed as buffer ownership // is attached to the receive operators. suppressingClose(buffers); closeNotConsumedRFWs(); // close operator context for (OperatorContextImpl opContext : contexts) { suppressingClose(opContext); } suppressingClose(bufferManager); suppressingClose(allocator); }
Source:
public void onBackPressed() { Fragment currentFragment = fragmentManager .findFragmentById(R.id.fragment_holder); if (currentFragment instanceof About) { fragmentManager.popBackStack(FragmentTags.CARD_LIST, 0); return; } super.onBackPressed(); }

Target:
public void onBackPressed() { Fragment currentFragment = fragmentManager .findFragmentById(R.id.fragment_holder); if (currentFragment instanceof About) { fragmentManager.popBackStack(FragmentTags.CARD_LIST, 0); } else { super.onBackPressed(); } }
Source:
public static void createDir(String path) throws IOException { try { Files.createDirectories(Paths.get(path)); } catch (AccessDeniedException e) { LOG.info("Fail to create folder " + path + "caused by AccessDeniedException"); } }

Target:
public static void createDir(String path) throws IOException { Files.createDirectories(Paths.get(path)); }
Source:
public TraceStatusDMData() { this(false, false, false, 0, 0, 0, "", "", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ fTracingSupported = false; }

Target:
public TraceStatusDMData() { fTracingSupported = false; }
Source:
public void testWrongSelectionBug534319singleThread() throws Exception { waitForNonConsoleJobs(); // Run a few times since the problem doesn't occur always int iterations = 5; final String typeName = "Bug534319singleThread"; final String breakpointMethodName = "breakpointMethod"; doTestWrongSelectionBug534319(iterations, typeName, breakpointMethodName); }

Target:
public void testWrongSelectionBug534319singleThread() throws Exception { // Run a few times since the problem doesn't occur always int iterations = 5; final String typeName = "Bug534319singleThread"; final String breakpointMethodName = "breakpointMethod"; doTestWrongSelectionBug534319(iterations, typeName, breakpointMethodName); }
Source:
public void update() { fboId = frameBuffersManager.getFBO(fboName).fboId; task.setFboId(fboId); task.setFboName(fboName); }

Target:
public void update() { fboId = frameBuffersManager.getFBO(fboName).fboId; task.setFboId(fboId); }
Source:
public int value( ) { return rand.nextInt(); }

Target:
private int value() { return rand.nextInt(); }
Source:
public void testIterationStart(LoopIterationEvent event) { JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables(); if ((getControlledByThread() && !jMeterVariables.isSameUserOnNextIteration()) || getClearEachIteration()) { log.debug("Initialise cookies from pre-defined list"); // No need to call clear setProperty(initialCookies.clone()); } }

Target:
public void testIterationStart(LoopIterationEvent event) { JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables(); if ((getControlledByThread() && !jMeterVariables.isSameUserOnNextIteration()) || (!getControlledByThread() && getClearEachIteration())) { log.debug("Initialise cookies from pre-defined list"); // No need to call clear setProperty(initialCookies.clone()); } }
Source:
public static boolean isAllowedToSettings(String loginId, Project project) { if(loginId == null) { return false; } User user = User.findByLoginId(loginId); if(user == null || user.isAnonymous()) { return false; } if(user.isSiteManager() || ProjectUser.isManager(user.id, project.id)) { return true; } return false; }

Target:
public static boolean isAllowedToSettings(String loginId, Project project) { if(loginId == null) { return false; } User user = User.findByLoginId(loginId); if(user.isAnonymous()) { return false; } if(user.isSiteManager() || ProjectUser.isManager(user.id, project.id)) { return true; } return false; }
Source:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { // Compute the proxy object in case the proxy operation scheduled in the pooled thread is not yet completed. myProxyDelegate = reproxy(AndroidProject.class, myDelegate);; } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }

Target:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { // Compute the proxy object in case the proxy operation scheduled in the pooled thread is not yet completed. myProxyDelegate = reproxy(AndroidProject.class, myDelegate); } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }
Source:
private void print(List<List<Object>> keys, List<ValueUpdater> updaters) { for (int i = 0; i < keys.size(); i++) { ValueUpdater valueUpdater = updaters.get(i); Object arg = ((CombinerValueUpdater) valueUpdater).getArg(); LOG.debug("updateCount = {}, keys = => updaterArgs = {}", updateCount, keys.get(i), arg); } }

Target:
private void print(List<List<Object>> keys, List<ValueUpdater> updaters) { for (int i = 0; i < keys.size(); i++) { ValueUpdater valueUpdater = updaters.get(i); Object arg = ((CombinerValueUpdater) valueUpdater).getArg(); LOG.info("updateCount = {}, keys = => updaterArgs = {}", updateCount, keys.get(i), arg); } }
Source:
public LocalCacheFileSystem(FileSystem fs, FileSystemContext fsContext) { super(fs); mFsContext = fsContext; // needs to be moved outside FileSystem constructor mLocalCacheManager = new LocalCacheManager(mFsContext); }

Target:
public LocalCacheFileSystem(FileSystem fs, FileSystemContext fsContext) { super(fs); mFsContext = fsContext; }
Source:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Mono.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }

Target:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Flux.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }
Source:
private HashMap<String, String> getParamsForQuery() { HashMap<String, String> params = new HashMap<>(); params.put(METRIC_PARAM, getValidTableName(name)); params.put(AGGREGATOR_PARAM, SUM_AGGREGATOR); params.put(TIME_PARAM, DEFAULT_TIME); return params; }

Target:
private Map<String, String> getParamsForQuery() { HashMap<String, String> params = new HashMap<>(); params.put(METRIC_PARAM, getValidTableName(name)); params.put(AGGREGATOR_PARAM, SUM_AGGREGATOR); params.put(TIME_PARAM, DEFAULT_TIME); return params; }
Source:
public PagesSpatialIndexFactory(List<Type> types, List<Type> outputTypes) { this.types = ImmutableList.copyOf(types); this.outputTypes = outputTypes; }

Target:
public PagesSpatialIndexFactory(List<Type> types, List<Type> outputTypes) { this.types = ImmutableList.copyOf(types); this.outputTypes = ImmutableList.copyOf(outputTypes); }
Source:
public static List<SchemaPath> projectList(String... names) { List<SchemaPath> selected = new ArrayList<>(); for (String name : names) { if (name.equals(SchemaPath.DYNAMIC_STAR) || name.equals("*")) { selected.add(SchemaPath.STAR_COLUMN); } else { selected.add(SchemaPath.parseFromString(name)); } } return selected; }

Target:
public static List<SchemaPath> projectList(String... names) { List<SchemaPath> selected = new ArrayList<>(); for (String name : names) { if (name.equals(SchemaPath.DYNAMIC_STAR)) { selected.add(SchemaPath.STAR_COLUMN); } else { selected.add(SchemaPath.parseFromString(name)); } } return selected; }
Source:
public synchronized IResource getResource( IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new NullPointerException("Reference point is null"); if (referencePointRelativePath == null) throw new NullPointerException("Path is null"); org.eclipse.core.resources.IProject project = get(referencePoint); if (project == null) throw new NullPointerException( "For reference point " + referencePoint + " does'nt exist a project."); return project.findMember(referencePointRelativePath); }

Target:
public IResource getResource(IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new IllegalStateException("Reference point is null"); if (referencePointRelativePath == null) throw new IllegalStateException("Path is null"); org.eclipse.core.resources.IProject project = get(referencePoint); if (project == null) throw new NullPointerException( "For reference point " + referencePoint + " does'nt exist a project."); return project.findMember(referencePointRelativePath); }
Source:
public boolean matches(ILoggingEvent actual) { // Match only the first line to skip the validation of hex-dump format. actualMsg = actual.getMessage().split("(?s)[\\r\\n]+")[0]; if (actualMsg.matches(expected)) { // The presence of a newline implies a hex-dump was logged return actual.getMessage().contains(NEWLINE) == shouldContainNewline; } else { return false; } }

Target:
public boolean matches(ILoggingEvent actual) { // Match only the first line to skip the validation of hex-dump format. actualMsg = actual.getMessage().split("(?s)[\\r\\n]+")[0]; if (actualMsg.matches(expected)) { // The presence of a newline implies a hex-dump was logged return actual.getMessage().contains(NEWLINE) == shouldContainNewline; } return false; }
Source:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); List<String> extensionJobNames = new ArrayList<>(); if (null != extensionJobs && !extensionJobs.isEmpty()){ for (ExtensionJobsBean extensionJobsBean: extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } return extensionJobNames; } else { return extensionJobNames; } }

Target:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); List<String> extensionJobNames = new ArrayList<>(); if (null != extensionJobs && !extensionJobs.isEmpty()) { for (ExtensionJobsBean extensionJobsBean : extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } } return extensionJobNames; }
Source:
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } // check if the gatewayip is the part of the ip range being added. // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links // GW Netmask Stat IP End IP // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1 // https://tools.ietf.org/html/rfc3021 // Added by Wilder Rodrigues final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); return !isInRange; }

Target:
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) { if (!isValidIp(ipAddress)) { return false; } if (!isValidCIDR(cidr)) { return false; } // check if the gatewayip is the part of the ip range being added. // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links // GW Netmask Stat IP End IP // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1 // https://tools.ietf.org/html/rfc3021 // Added by Wilder Rodrigues final SubnetUtils subnetUtils = new SubnetUtils(cidr); subnetUtils.setInclusiveHostCount(true); final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress); return isInRange; }
Source:
public synchronized boolean installSingleNodeLayoutIfAbsent() { if ((Boolean) getServerConfig().get("--single") && getCurrentLayout() == null) { setCurrentLayout(getNewSingleNodeLayout()); log.error("HERE ====="); return true; } return false; }

Target:
public synchronized boolean installSingleNodeLayoutIfAbsent() { if ((Boolean) getServerConfig().get("--single") && getCurrentLayout() == null) { setCurrentLayout(getNewSingleNodeLayout()); return true; } return false; }
Source:
public DrillFileSystem(Configuration fsConf, OperatorStats operatorStats) throws IOException { // Configuration objects are mutable, and the underlying FileSystem object may directly use a passed in Configuration. // In order to avoid scenarios where a Configuration can change after a DrillFileSystem is created, we make a copy // of the Configuration. this.fsConf = new Configuration(fsConf); this.underlyingFs = FileSystem.get(this.fsConf); this.codecFactory = new CompressionCodecFactory(this.fsConf); this.operatorStats = operatorStats; this.initialized = true; }

Target:
public DrillFileSystem(Configuration fsConf, OperatorStats operatorStats) throws IOException { // Configuration objects are mutable, and the underlying FileSystem object may directly use a passed in Configuration. // In order to avoid scenarios where a Configuration can change after a DrillFileSystem is created, we make a copy // of the Configuration. fsConf = new Configuration(fsConf); this.underlyingFs = FileSystem.get(fsConf); this.codecFactory = new CompressionCodecFactory(fsConf); this.operatorStats = operatorStats; }
Source:
public void invite(final String friend) throws IOException { try { new JdbcSession(this.sql.source()) // @checkstyle LineLength (1 line) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(1) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } }

Target:
public void invite(final String friend) throws IOException { try { new JdbcSession(this.sql.source()) // @checkstyle LineLength (1 line) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } }
Source:
private void fireEventsFor(OLogSequenceNumber lsn) { // may be executed by only one thread at every instant of time final ConcurrentNavigableMap<OLogSequenceNumber, Runnable> eventsToFire = events.headMap(lsn, true); for (Runnable runnable : eventsToFire.values()) runnable.run(); eventsToFire.clear(); }

Target:
private void fireEventsFor(OLogSequenceNumber lsn) { // may be executed by only one thread at every instant of time final Iterator<Runnable> eventsToFire = events.headMap(lsn, true).values().iterator(); while (eventsToFire.hasNext()) { eventsToFire.next().run(); eventsToFire.remove(); } }
Source:
public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); // Assign GeoJSON bounding box for FeatureCollection mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); storeRenderer(mRenderer); }

Target:
public GeoJsonLayer(GoogleMap map, JSONObject geoJsonFile) { if (geoJsonFile == null) { throw new IllegalArgumentException("GeoJSON file cannot be null"); } mBoundingBox = null; GeoJsonParser parser = new GeoJsonParser(geoJsonFile); // Assign GeoJSON bounding box for FeatureCollection mBoundingBox = parser.getBoundingBox(); HashMap<GeoJsonFeature, Object> geoJsonFeatures = new HashMap<>(); for (GeoJsonFeature feature : parser.getFeatures()) { geoJsonFeatures.put(feature, null); } GeoJsonRenderer mRenderer = new GeoJsonRenderer(map, geoJsonFeatures); storeRenderer(mRenderer); }
Source:
public PathAnnotationRoutesParser() { }

Target:
protected PathAnnotationRoutesParser() { this(null); }
Source:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { // we do not store the last point of an instruction Instruction instruction = ((InstructionList) o).get(index); int size; if(instruction instanceof ViaInstruction) size = 0; else size = instruction.getPoints().size(); // the last point of instruction (i.e. first point of next instruction) is not included return size; } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); }

Target:
private int getLength(Object o, int index) { if (o instanceof InstructionList) { // we do not store the last point of an instruction Instruction instruction = ((InstructionList) o).get(index); return instruction.getLength(); } if (o instanceof List) { return ((List<PathDetail>) o).get(index).getLength(); } throw new IllegalStateException("We can only handle PathDetails or InstructionList in PathSimplification"); }
Source:
private DataPointAssignment marshallToDomain(DataPointAssignmentDto dto) { final DataPointAssignment dpa = new DataPointAssignment(); BeanUtils.copyProperties(dto, dpa); if (dto.getKeyId() != null) { dpa.setKey(KeyFactory.createKey("DataPointAssignment", dto.getKeyId())); } //Lists must be copied separately dpa.setDataPointIds(dto.getDataPointIds()); return dpa; }

Target:
private DataPointAssignment marshallToDomain(DataPointAssignmentDto dto) { final DataPointAssignment dpa = new DataPointAssignment(); BeanUtils.copyProperties(dto, dpa); if (dto.getKeyId() != null) { dpa.setKey(KeyFactory.createKey("DataPointAssignment", dto.getKeyId())); } return dpa; }
Source:
private Collection<CHGraphImpl> getAllCHGraphs() { // todo: this method is only used to have a 'view' on the two collections. we could also create this only once // as long as the graph collections are only modified in the constructor (otherwise we would have to make sure // the lists are in sync). another option would be something like guava concat. List<CHGraphImpl> result = new ArrayList<>(); result.addAll(nodeBasedCHGraphs); result.addAll(edgeBasedCHGraphs); return result; }

Target:
private Collection<CHGraphImpl> getAllCHGraphs() { // todo: this method is only used to have a 'view' on the two collections. we could also create this only once // as long as the graph collections are only modified in the constructor (otherwise we would have to make sure // the lists are in sync). another option would be something like guava concat. List<CHGraphImpl> result = new ArrayList<>(nodeBasedCHGraphs.size() + edgeBasedCHGraphs.size()); result.addAll(nodeBasedCHGraphs); result.addAll(edgeBasedCHGraphs); return result; }
Source:
public HttpRequest filter(HttpRequest request) throws HttpException { if (this.isSAS){ request = filterSAS(request, this.credential); } else { request = filterKey(request); } utils.logRequest(signatureLog, request, "<<"); return request; }

Target:
public HttpRequest filter(HttpRequest request) throws HttpException { request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request); utils.logRequest(signatureLog, request, "<<"); return request; }
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { // todo: extract common interface super.visitFunctionOrMethodDeclaration(o); check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { super.visitFunctionLit(o); check(o.getSignature(), o.getBlock(), holder); } }; }

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitFunctionOrMethodDeclaration(@NotNull GoFunctionOrMethodDeclaration o) { // todo: extract common interface check(o.getSignature(), o.getBlock(), holder); } @Override public void visitFunctionLit(@NotNull GoFunctionLit o) { check(o.getSignature(), o.getBlock(), holder); } }; }
Source:
public List<SpoonFolder> getSubFolders() { List<SpoonFolder> result = new ArrayList<>(); Set<SpoonFolder> distinctSet = new HashSet<>(); for (SpoonFile f : getAllFiles()) { SpoonFolder folder = f.getParent(); if (distinctSet.add(folder)) { result.add(folder); } } return Collections.unmodifiableList(result); }

Target:
public List<SpoonFolder> getSubFolders() { List<SpoonFolder> result = new ArrayList<>(); for (SpoonFile f : getAllFiles()) { SpoonFolder folder = f.getParent(); if (!result.contains(folder)) { result.add(folder); } } return Collections.unmodifiableList(result); }
Source:
public Page appendColumn(Block block) { requireNonNull(block, "block is null"); if (positionCount != block.getPositionCount()) { throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = Arrays.copyOf(blocks, blocks.length + 1); System.arraycopy(blocks, 0, newBlocks, 0, blocks.length); newBlocks[blocks.length] = block; return new Page(newBlocks); }

Target:
public Page appendColumn(Block block) { requireNonNull(block, "block is null"); if (positionCount != block.getPositionCount()) { throw new IllegalArgumentException("Block does not have same position count"); } Block[] newBlocks = Arrays.copyOf(blocks, blocks.length + 1); newBlocks[blocks.length] = block; return new Page(newBlocks); }
Source:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } finally { // ignored } }

Target:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } catch(Exception e) { // ignored } }
Source:
private void close() { try { closeExecutors(); m_loader.close(); if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { // Ignore } }

Target:
private void close() { try { closeExecutors(); if (m_loader != null) { m_loader.close(); m_loader = null; } if (m_client != null) { m_client.close(); m_client = null; } } catch (Exception ex) { // Ignore } }
Source:
public boolean isApplicable(UpgradeCheckRequest request) throws AmbariException { UpgradeType upgradeType = request.getUpgradeType(); UpgradeCheckInfo annotation = m_checkClass.getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return true; } // empty upgrade type or matching should return true UpgradeType[] upgradeTypes = annotation.required(); if (ArrayUtils.isEmpty(upgradeTypes) || ArrayUtils.contains(upgradeTypes, upgradeType)) { return true; } return false; }

Target:
public boolean isApplicable(UpgradeCheckRequest request) throws AmbariException { UpgradeType upgradeType = request.getUpgradeType(); UpgradeCheckInfo annotation = m_checkClass.getAnnotation(UpgradeCheckInfo.class); if (null == annotation) { return true; } // empty upgrade type or matching should return true UpgradeType[] upgradeTypes = annotation.required(); return (ArrayUtils.isEmpty(upgradeTypes) || ArrayUtils.contains(upgradeTypes, upgradeType)); }
Source:
private boolean validateHostPort(String string) { // https://stackoverflow.com/questions/2345063/java-common-way-to-validate-and-convert-hostport-to-inetsocketaddress try { // WORKAROUND: add any scheme to make the resulting URI valid. URI uri = new URI("my://" + string); // may throw URISyntaxException if (uri.getHost() == null || uri.getPort() == -1) { throw new URISyntaxException(uri.toString(), "URI must have host and port parts"); } } catch (URISyntaxException ex) { // validation failed return false; } // validation succeeded return true; }

Target:
private boolean validateHostPort(String string) { // https://stackoverflow.com/questions/2345063/java-common-way-to-validate-and-convert-hostport-to-inetsocketaddress try { // WORKAROUND: add any scheme to make the resulting URI valid. URI uri = new URI("my://" + string); // may throw URISyntaxException if (uri.getHost() == null || uri.getPort() == -1) { return false; } } catch (URISyntaxException ex) { // validation failed return false; } // validation succeeded return true; }
Source:
public synchronized static Set<Class<? extends PhysicalOperator>> getSubTypes(ScanResult classpathScan) { final Set<Class<? extends PhysicalOperator>> ops = classpathScan.getImplementations(PhysicalOperator.class); logger.debug("Found physical operator classes: {}.", ops.size(), ops); return ops; }

Target:
public static Set<Class<? extends PhysicalOperator>> getSubTypes(ScanResult classpathScan) { final Set<Class<? extends PhysicalOperator>> ops = classpathScan.getImplementations(PhysicalOperator.class); logger.debug("Found physical operator classes: {}.", ops.size(), ops); return ops; }
Source:
public DesiredCapabilities getCapability(String testName) { DesiredCapabilities capabilities = new DesiredCapabilities(); // add capabilities based on dynamic _config.properties variables capabilities = initCapabilities(capabilities); if (R.CONFIG.getBoolean(SpecialKeywords.FULL_RESET_BEFORE_SUITE) && !R.CONFIG.get(SpecialKeywords.FULL_RESET_BEFORE_SUITE).isEmpty()) { LOGGER.info("Will be execute 'fullResetBeforeSuite'!"); executeFullResetBeforeSuite(capabilities); } return capabilities; }

Target:
public DesiredCapabilities getCapability(String testName) { DesiredCapabilities capabilities = new DesiredCapabilities(); // add capabilities based on dynamic _config.properties variables capabilities = initCapabilities(capabilities); return capabilities; }
Source:
public BaseCassandraBolt withOutputFields(Fields fields) { Preconditions.checkNotNull("fields should not be null."); this.outputsFields.put(Utils.DEFAULT_STREAM_ID, fields); return this; }

Target:
public BaseCassandraBolt withOutputFields(Fields fields) { Preconditions.checkNotNull(fields, "fields should not be null."); this.outputsFields.put(Utils.DEFAULT_STREAM_ID, fields); return this; }
Source:
public synchronized void recover(TaskId taskId) throws TooManyTasksFailedException { checkState(groupedLifespanScheduler.isPresent(), "groupedLifespanScheduler is not present for recoverable grouped execution"); if (anySourceSchedulingFinished) { throw new IllegalStateException("Recover after any source scheduling finished is not supported"); } groupedLifespanScheduler.get().onTaskFailed(taskId.getId(), sourceSchedulers); }

Target:
public synchronized void recover(TaskId taskId) { checkState(groupedLifespanScheduler.isPresent(), "groupedLifespanScheduler is not present for recoverable grouped execution"); if (anySourceSchedulingFinished) { throw new IllegalStateException("Recover after any source scheduling finished is not supported"); } groupedLifespanScheduler.get().onTaskFailed(taskId.getId(), sourceSchedulers); }
Source:
private void layoutWikiDataDescription(String description) { // set the text of the description... pageDescriptionText.setText(description); // and wait for it to lay out, so that we know the height of the description text. pageDescriptionText.post(new Runnable() { @Override public void run() { if (!parentFragment.isAdded()) { return; } // only show the description if it's two lines or less if (pageDescriptionText.getLineCount() > 2) { pageDescriptionText.setVisibility(View.GONE); } else { pageDescriptionText.setVisibility(View.VISIBLE); } } }); }

Target:
private void layoutWikiDataDescription(String description) { // set the text of the description... pageDescriptionText.setText(description); // and wait for it to lay out, so that we know the height of the description text. pageDescriptionText.post(new Runnable() { @Override public void run() { if (!parentFragment.isAdded()) { return; } // only show the description if it's two lines or less pageDescriptionText.setVisibility(pageDescriptionText.getLineCount() > 2 ? View.GONE : View.VISIBLE); } }); }
Source:
private static void cleanUpOldFiles(File dir) { long cutoffTimestamp = System.currentTimeMillis() - (MAX_FILE_AGE_HOURS * Constants.HOUR_MS); File[] files = dir.listFiles(); for (File file : files) { if (!FileUtils.isFileNewer(file, cutoffTimestamp)) { delete(file); } } }

Target:
private static void cleanUpOldFiles(File dir) { long cutoffTimestamp = System.currentTimeMillis() - (MAX_FILE_AGE_HOURS * Constants.HOUR_MS); Arrays.asList(dir.listFiles()).stream() .filter(file -> !FileUtils.isFileNewer(file, cutoffTimestamp)) .forEach(file -> delete(file)); }
Source:
boolean getAsBoolean() throws Exception; } /** Wait until {@code predicate} is satisfied, or fail, with a given timeout. */ public static void waitUntil( String message, int timeoutSeconds, BooleanSupplierWithThrow predicate) throws Exception { int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); }

Target:
boolean getAsBoolean() throws Exception; } /** Wait until {@code predicate} is satisfied, or fail, with a given timeout. */ public static void waitUntil( String message, long timeoutSeconds, BooleanSupplierWithThrow predicate) throws Exception { int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); }
Source:
protected void endVmCommand() { setCommandShouldBeLogged(false); if (getVm() == null) { log.warn("VM is null, not performing full endAction"); setSucceeded(true); } getVm().setStatus(VMStatus.Down); getSnapshotDao().removeMemoryFromActiveSnapshot(getVmId()); getVmDynamicDao().update(getVm().getDynamicData()); setSucceeded(true); }

Target:
protected void endVmCommand() { setCommandShouldBeLogged(false); if (getVm() == null) { log.warn("VM is null, not performing full endAction"); setSucceeded(true); return; } getVm().setStatus(VMStatus.Down); getSnapshotDao().removeMemoryFromActiveSnapshot(getVmId()); getVmDynamicDao().update(getVm().getDynamicData()); setSucceeded(true); }
Source:
public void onRefresh() { super.onRefresh(); if (mFile != null) { // Refresh mFile mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); Log_OC.d(TAG, "Parent etag= |" + mFile.getEtag() + "|"); } }

Target:
public void onRefresh() { super.onRefresh(); if (mFile != null) { // Refresh mFile mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); } }
Source:
public void setWidth(String width, boolean isFixedLayout) { table.setWidth("100%", true); //$NON-NLS-1$ tableHeader.setWidth("100%", true); //$NON-NLS-1$ }

Target:
public void setWidth(String width, boolean isFixedLayout) { table.setWidth("100%", isFixedLayout); //$NON-NLS-1$ tableHeader.setWidth("100%", isFixedLayout); //$NON-NLS-1$ }
Source:
public HelixAccountServiceFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry) { storeConfig = new HelixPropertyStoreConfig(verifiableProperties); accountServiceConfig = new HelixAccountServiceConfig(verifiableProperties); accountServiceMetrics = new AccountServiceMetrics(metricRegistry); notifier = accountServiceConfig.zkClientConnectString.equals(HelixAccountServiceConfig.INVALID_ZK_CLIENT_CONNECT_STRING) ? null : new HelixNotifier(accountServiceConfig.zkClientConnectString, storeConfig); }

Target:
public HelixAccountServiceFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry) { this(new HelixPropertyStoreConfig(verifiableProperties), new HelixAccountServiceConfig(verifiableProperties), new AccountServiceMetrics(metricRegistry), new HelixNotifier(new HelixAccountServiceConfig(verifiableProperties).zkClientConnectString, new HelixPropertyStoreConfig(verifiableProperties))); }
Source:
public String getResourceContent(String name) throws IOException { String output = ""; if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding output = FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); } else output = IOUtils.toString(is, DEFAULT_ENCODING); } } return output; }

Target:
public String getResourceContent(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toString(is, DEFAULT_ENCODING); } } } // Resources should always be encoded as UTF-8, to reduce the dependency on the system encoding return FileUtils.readFileToString(new File(name), DEFAULT_ENCODING); }
Source:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { // The first 8 bytes is size of the request. TCP implementation uses this size to allocate buffer. See {@link BoundedReceive} // Here we just need to consume it. stream.readLong(); } catch (IOException e) { throw new InterruptedException("stream read error." + e); } requestQueue.put(request); }

Target:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { // The first 8 bytes is size of the request. TCP implementation uses this size to allocate buffer. See {@link BoundedReceive} // Here we just need to consume it. stream.readLong(); } catch (IOException e) { throw new IllegalStateException("stream read error." + e); } requestQueue.put(request); }
Source:
private void migrateDirectory(String path, String source, String destination) throws Exception { String newDir = computeTargetPath(path, source, destination); mFileSystem.createDirectory(new AlluxioURI(newDir), FileSystemOptions.createDirectoryDefaults(ServerConfiguration.global())); }

Target:
private void migrateDirectory(String path, String source, String destination) throws Exception { String newDir = computeTargetPath(path, source, destination); mFileSystem.createDirectory(new AlluxioURI(newDir)); }
Source:
public boolean isRestricted() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }

Target:
public boolean isRestricted() { return true; }
Source:
private Guid getTargetClusterId(Action action) { if (action.isSetCluster() && (action.getCluster().isSetId() || action.getCluster().isSetName())) { return getClusterId(action); } // means use the cluster of the provided host return null; }

Target:
private Guid getTargetClusterId(Action action) { if (action.isSetCluster()) { return getClusterId(action); } // means use the cluster of the provided host return null; }
Source:
private boolean isNimbus(Subject who) { Set<Principal> principals = null; boolean isNimbusInstance = false; if (who != null) { principals = who.getPrincipals(); for (Principal principal : principals) { if (principal instanceof NimbusPrincipal) { isNimbusInstance = true; } } } return isNimbusInstance; }

Target:
private boolean isNimbus(Subject who) { Set<Principal> principals; boolean isNimbusInstance = false; if (who != null) { principals = who.getPrincipals(); for (Principal principal : principals) { if (principal instanceof NimbusPrincipal) { isNimbusInstance = true; } } } return isNimbusInstance; }
Source:
ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { // The VersionLockedObject and the Transaction layer will generate // undoRecord(s) during a transaction commit, or object sync. These // undo records are stored in transient fields and are not persisted. // A missing undo record can cause a NoRollbackException, thus forcing // a complete object rebuild that generates a "scanning" behavior // which affects the LRU window. In essence, affecting other cache users // and making the VersionLockedObject very sensitive to caching behavior. // A concrete example of this would be unsynchronized readers/writes: // 1. Thread A starts replicating write1 // 2. Thread B discovers the write (via stream tail query) and // tries to read write1 // 3. Thread B's read results in a cache miss and the reader thread // starts loading the value into the cache // 4. Thread A completes its write and caches it with undo records // 5. Thread B finishes loading and caches the loaded value replacing // the cached value from step 4 (i.e. loss of undo records computed // by thread A) ILogData data = readCache.getIfPresent(address); if (data == null) { final ILogData loadedVal = fetch(address); data = readCache.asMap().computeIfAbsent(address, (k) -> loadedVal); } return data; } return fetch(address); }

Target:
ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { // The VersionLockedObject and the Transaction layer will generate // undoRecord(s) during a transaction commit, or object sync. These // undo records are stored in transient fields and are not persisted. // A missing undo record can cause a NoRollbackException, thus forcing // a complete object rebuild that generates a "scanning" behavior // which affects the LRU window. In essence, affecting other cache users // and making the VersionLockedObject very sensitive to caching behavior. // A concrete example of this would be unsynchronized readers/writes: // 1. Thread A starts replicating write1 // 2. Thread B discovers the write (via stream tail query) and // tries to read write1 // 3. Thread B's read results in a cache miss and the reader thread // starts loading the value into the cache // 4. Thread A completes its write and caches it with undo records // 5. Thread B finishes loading and caches the loaded value replacing // the cached value from step 4 (i.e. loss of undo records computed // by thread A) ILogData data = readCache.getIfPresent(address); if (data == null) { // Loading a value without the cache loader can result in // redundant loading calls (i.e. multiple threads try to // load the same value), but currently a redundant RPC // is much cheaper than the cost of a NoRollBackException, therefore // this trade-off is reasonable final ILogData loadedVal = fetch(address); return readCache.asMap().computeIfAbsent(address, (k) -> loadedVal); } return data; } return fetch(address); }