auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isLoggedIn() { Token accessToken = getAccessToken(); return (accessToken != null) ? true : false; }

Target:
public boolean isLoggedIn() { Token accessToken = getAccessToken(); return accessToken != null; }
Source:
private void animateViewTransitions() { fadeOutMotto(); delayButtonHandler = new Handler(); delayButtonHandler.postDelayed(new Runnable() { @Override public void run() { setMottoInvisible(); fadeInLoginView(); } } , 2000); }

Target:
private void animateViewTransitions() { fadeOutMotto(); delayButtonHandler = new Handler(); delayButtonHandler.postDelayed(new Runnable() { @Override public void run() { fadeInLoginView(); } }, 2000); }
Source:
protected void onServiceConnectionLost(int errorCode) { Logger.e(TAG + "onServiceConectionLost for peer = " + mConnectionId + "error code =" + errorCode); if (GearAgentService.getConnection() != null) { GearAgentService.setConnection(null); } }

Target:
protected void onServiceConnectionLost(int errorCode) { Logger.e(TAG + "onServiceConectionLost for peer = " + mConnectionId + "error code =" + errorCode); GearAgentService.setConnection(null); }
Source:
public void onCreate_debugViewShouldBeVisible() throws Exception { enableDebugMode(Robolectric.application.getApplicationContext()); BaseActivity act = TestHelper.initBaseActivity(); assertThat(act.findViewById(R.id.debugging)).isVisible(); }

Target:
public void onCreate_debugViewShouldBeVisible() throws Exception { enableDebugMode(Robolectric.application); BaseActivity act = TestHelper.initBaseActivity(); assertThat(act.findViewById(R.id.debugging)).isVisible(); }
Source:
public AutoCompleteAdapter(Context context, BaseActivity act, String[] columns) { super(context, new MatrixCursor(columns), 0); this.context = context; this.app = (MapzenApplication) act.getApplication(); this.act = act; }

Target:
public AutoCompleteAdapter(Context context, BaseActivity act, String[] columns) { super(context, new MatrixCursor(columns), 0); this.context = context; this.app = (MapzenApplication) act.getApplication(); }
Source:
private void initResultsFragment() { pagerResultsFragment = new PagerResultsFragment(); pagerResultsFragment.setAct(this); pagerResultsFragment.setApp(app); pagerResultsFragment.setAdapter(new SearchViewAdapter(this, getSupportFragmentManager())); // TODO remove fugly HACK pagerResultsFragment.setMapFragment(mapFragment); }

Target:
private void initResultsFragment() { pagerResultsFragment = new PagerResultsFragment(); pagerResultsFragment.setAct(this); pagerResultsFragment.setAdapter(new SearchViewAdapter(this, getSupportFragmentManager())); // TODO remove fugly HACK pagerResultsFragment.setMapFragment(mapFragment); }
Source:
public static boolean isValidEmailFormat ( String email ) { boolean isValid = false; try { InternetAddress emailAddress = new InternetAddress(email); emailAddress.validate(); isValid = true; } catch (AddressException ex) { isValid = false; logger.error("Email " + email + " is invalid"); } return isValid; }

Target:
public static boolean isValidEmailFormat ( String email ) { boolean isValid = false; try { InternetAddress emailAddress = new InternetAddress(email); emailAddress.validate(); isValid = true; } catch (AddressException ex) { isValid = false; logger.warn("Email " + email + " is invalid"); } return isValid; }
Source:
public DeleteBulkFactory(Settings settings, MetadataExtractor metaExtractor, EsMajorVersion version) { // we only want a specific serializer for this particular bulk factory super(settings.copy().setSerializerValueWriterClassName(NoDataWriter.class.getName()), metaExtractor, version); }

Target:
public DeleteBulkFactory(Settings settings, MetadataExtractor metaExtractor, EsMajorVersion version) { super(settings, metaExtractor, version); }
Source:
public void setFailure(Throwable failure) { if (failure == null) { failure = new Exception(); } synchronized (resultLock) { this.failure = failure; if (! setDone()) { return; } } // call outside of lock listenerHelper.callListeners(); }

Target:
public void setFailure(Throwable failure) { synchronized (resultLock) { if (! setDone()) { return; } if (failure == null) { failure = new Exception(); } this.failure = failure; } // call outside of lock listenerHelper.callListeners(); }
Source:
Configuration(String apiKey) { this.apiKey = apiKey; // Add built-in callbacks addCallback(new AppCallback(this)); addCallback(new DeviceCallback()); DeviceCallback.initializeCache(); if (ServletCallback.isAvailable()) { addCallback(new ServletCallback()); } sessionDelivery = new AsyncHttpDelivery(); ((HttpDelivery) sessionDelivery).setEndpoint("https://sessions.bugsnag.com"); }

Target:
Configuration(String apiKey) { this.apiKey = apiKey; // Add built-in callbacks addCallback(new AppCallback(this)); addCallback(new DeviceCallback()); DeviceCallback.initializeCache(); if (ServletCallback.isAvailable()) { addCallback(new ServletCallback()); } }
Source:
public synchronized void addMetric(ReplicationMetric replicationMetric) throws SemanticException { if (metricMap.size() > maxSize) { throw new SemanticException("Metrics are not getting collected. "); } else { if (metricMap.size() > 0.8 * maxSize) { //soft limit LOG.warn("Metrics cache is more than 80 % full. Will start dropping metrics once full. "); } metricMap.put(replicationMetric.getScheduledExecutionId(), replicationMetric); } }

Target:
public synchronized void addMetric(ReplicationMetric replicationMetric) throws SemanticException { if (metricMap.size() >= maxSize) { throw new SemanticException("Metrics are not getting collected. "); } else { if (metricMap.size() > 0.8 * maxSize) { //soft limit LOG.warn("Metrics cache is more than 80 % full. Will start dropping metrics once full. "); } metricMap.put(replicationMetric.getScheduledExecutionId(), replicationMetric); } }
Source:
DataSketchesFunctions() { this.sketchClasses = new ArrayList<SketchDescriptor>(); this.descriptors = new ArrayList<HiveUDFPlugin.UDFDescriptor>(); registerHll(); registerCpc(); registerKll(); registerTheta(); registerTuple(); registerQuantiles(); registerFrequencies(); buildCalciteFns(); buildDescritors(); }

Target:
private DataSketchesFunctions() { this.sketchClasses = new ArrayList<SketchDescriptor>(); this.descriptors = new ArrayList<HiveUDFPlugin.UDFDescriptor>(); registerHll(); registerCpc(); registerKll(); registerTheta(); registerTuple(); registerQuantiles(); registerFrequencies(); buildCalciteFns(); buildDescritors(); }
Source:
private boolean shouldDump(Path previousDumpPath) throws IOException { //If no previous dump means bootstrap. So return true as there was no //previous dump to load if (previousDumpPath == null) { return true; } else { FileSystem fs = previousDumpPath.getFileSystem(conf); if (fs.exists(previousDumpPath)) { FileStatus[] latestUpdateStatuses = fs.listStatus(previousDumpPath); for (FileStatus status : latestUpdateStatuses) { if (status.getPath().getName().equalsIgnoreCase(ReplUtils.LOAD_ACKNOWLEDGEMENT)) { return true; } } } } return false; }

Target:
private boolean shouldDump(Path previousDumpPath) throws IOException { //If no previous dump means bootstrap. So return true as there was no //previous dump to load if (previousDumpPath == null) { return true; } else { FileSystem fs = previousDumpPath.getFileSystem(conf); return fs.exists(new Path(previousDumpPath, ReplUtils.LOAD_ACKNOWLEDGEMENT)); } }
Source:
public void notifyLock(LlapCacheableBuffer buffer) { // We do not proactively remove locked items from the heap, and opportunistically try to // remove from the list (since eviction is mostly from the list). If eviction stumbles upon // a locked item in either, it will remove it from cache; when we unlock, we are going to // put it back or update it, depending on whether this has happened. This should cause // most of the expensive cache update work to happen in unlock, not blocking processing. if (buffer.cacheAttribute == null || buffer.cacheAttribute.getIndex() != IN_LIST || !listLock.tryLock()) { return; } removeFromListAndUnlock(buffer); }

Target:
public void notifyLock(LlapCacheableBuffer buffer) { // We do not proactively remove locked items from the heap, and opportunistically try to // remove from the list (since eviction is mostly from the list). If eviction stumbles upon // a locked item in either, it will remove it from cache; when we unlock, we are going to // put it back or update it, depending on whether this has happened. This should cause // most of the expensive cache update work to happen in unlock, not blocking processing. if (buffer.cacheAttribute.getIndex() != IN_LIST || !listLock.tryLock()) { return; } removeFromListAndUnlock(buffer); }
Source:
public String generateInitFileName(String toVersion) throws HiveMetaException { if (toVersion == null) { toVersion = getHiveSchemaVersion(); } String initScriptName = INIT_FILE_PREFIX + toVersion + "." + dbType + SQL_FILE_EXTENSION; // check if the file exists File file = new File(getMetaStoreScriptDir() + File.separatorChar + initScriptName); if (!(file.exists())) { throw new HiveMetaException("Unknown version specified for initialization: " + toVersion, new NoSuchFileException(file.getAbsolutePath())); } return initScriptName; }

Target:
public String generateInitFileName(String toVersion) throws HiveMetaException { if (toVersion == null) { toVersion = getHiveSchemaVersion(); } String initScriptName = INIT_FILE_PREFIX + toVersion + "." + dbType + SQL_FILE_EXTENSION; // check if the file exists File file = new File(getMetaStoreScriptDir() + File.separatorChar + initScriptName); if (!file.exists()) { throw new HiveMetaException("Unknown version specified for initialization: " + toVersion, new NoSuchFileException(file.getAbsolutePath())); } return initScriptName; }
Source:
public static void unregisterLoggingContext() { // Remove the keys added, don't use clear, as it may clear all other things which are not intended to be removed. MDC.remove(SESSIONID_LOG_KEY); MDC.remove(QUERYID_LOG_KEY); MDC.remove(OPERATIONLOG_LEVEL_KEY); l4j.info("Unregistered logging context."); if (MDC.get(OPERATIONLOG_LEVEL_KEY) != null) { throw new RuntimeException("Keys removal failed from thread context MDC"); } }

Target:
public static void unregisterLoggingContext() { // Remove the keys added, don't use clear, as it may clear all other things which are not intended to be removed. MDC.remove(SESSIONID_LOG_KEY); MDC.remove(QUERYID_LOG_KEY); MDC.remove(OPERATIONLOG_LEVEL_KEY); l4j.info("Unregistered logging context."); }
Source:
public String getQueryId() throws SQLException { if (stmtHandle == null) { return null; } try { return client.GetQueryId(new TGetQueryIdReq(stmtHandle)).getQueryId(); } catch (TException e) { throw new SQLException(e); } }

Target:
public String getQueryId() throws SQLException { if (stmtHandle == null) { // If query is not running or already closed. return null; } try { return client.GetQueryId(new TGetQueryIdReq(stmtHandle)).getQueryId(); } catch (TException e) { throw new SQLException(e); } catch (Exception e) { // If concurrently the query is closed before we fetch queryID. return null; } }
Source:
private void setupHistory() throws IOException { if (this.history != null) { return; } this.history = new FileHistory(new File(getOpts().getHistoryFile())); // add shutdown hook to flush the history to history file and to close all open connections ShutdownHookManager.addShutdownHook(new Runnable() { @Override public void run() { try { history.flush(); } catch (IOException e) { error(e); } finally { close(); } } }); }

Target:
private void setupHistory() throws IOException { if (this.history != null) { return; } this.history = new FileHistory(new File(getOpts().getHistoryFile())); }
Source:
public void commentBeforeBlock() { Statement st = StaticJavaParser.parseBlock( "// a comment before parent" + System.lineSeparator() + "{ if (file != null) }"); assertTrue(st.getComment().isPresent()); assertTrue(st.getOrphanComments().isEmpty()); assertEquals(1, st.getAllContainedComments()); }

Target:
public void commentBeforeBlock() { Statement st = StaticJavaParser.parseBlock( "// a comment before parent" + System.lineSeparator() + "{ if (file != null) }"); assertTrue(st.getComment().isPresent()); assertTrue(st.getOrphanComments().isEmpty()); assertEquals(0, st.getAllContainedComments().size()); }
Source:
default boolean hasParametersOfType(String... paramTypes) { return getParameters().stream() .map(p -> p.getType().asString()) .collect(toList()) .equals(Stream.of(paramTypes).collect(toList())); }

Target:
default boolean hasParametersOfType(String... paramTypes) { return getParameters().stream() .map(p -> p.getType().asString()) .collect(toList()) .equals(Arrays.asList(paramTypes)); }
Source:
public static boolean isComment(int kind) { return getCategory(kind)== JavaToken.Category.COMMENT; }

Target:
public static boolean isComment(int kind) { return getCategory(kind).isComment(); }
Source:
private DB selectDatabase(Mongo mongo) { DB db = mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. // But we would be insane not to override this when writing lock records. LB. db.setWriteConcern(WriteConcern.JOURNALED); if (username != null) { if(authDbName != null) { // authentificating to db which gives access to all other dbs (role - readWriteAnyDatabase) // by default in mongo it should be "admin" DB authDb = mongo.getDB(authDbName) authDb.authenticate(username, password.toCharArray()); } else { db.authenticate(username, password.toCharArray()); } } return db; }

Target:
private DB selectDatabase(Mongo mongo) { DB db = mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. // But we would be insane not to override this when writing lock records. LB. db.setWriteConcern(WriteConcern.JOURNALED); if (username != null) { if(authDbName != null) { // authentificating to db which gives access to all other dbs (role - readWriteAnyDatabase) // by default in mongo it should be "admin" DB authDb = mongo.getDB(authDbName); authDb.authenticate(username, password.toCharArray()); } else { db.authenticate(username, password.toCharArray()); } } return db; }
Source:
protected boolean clientNeedAuthentication(final HttpServletRequest request, final HttpServletResponse response) { val clientId = OAuth20Utils.getClientIdAndClientSecret(new JEEContext(request, response, sessionStore)).getLeft(); val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(servicesManager, clientId); if (clientId.isEmpty() || registeredService == null) { return true; } return OAuth20Utils.doesServiceNeedAuthentication(registeredService); }

Target:
protected boolean clientNeedAuthentication(final HttpServletRequest request, final HttpServletResponse response) { val clientId = OAuth20Utils.getClientIdAndClientSecret(new JEEContext(request, response, sessionStore)).getLeft(); if (clientId.isEmpty()) { return true; } val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(servicesManager, clientId); if (registeredService == null) { return true; } return OAuth20Utils.doesServiceNeedAuthentication(registeredService); }
Source:
protected ProxyGrantingTicket produceTicketWithAdequateExpirationPolicy( final RegisteredServiceProxyGrantingTicketExpirationPolicy servicePgtPolicy, final ServiceTicket serviceTicket, final Authentication authentication, final String pgtId) { if (servicePgtPolicy != null) { LOGGER.trace("Overriding proxy-granting ticket policy with the specific policy: [{}]", servicePgtPolicy); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, new HardTimeoutExpirationPolicy(servicePgtPolicy.getMaxTimeToLiveInSeconds())); } else { LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); } }

Target:
protected ProxyGrantingTicket produceTicketWithAdequateExpirationPolicy( final RegisteredServiceProxyGrantingTicketExpirationPolicy servicePgtPolicy, final ServiceTicket serviceTicket, final Authentication authentication, final String pgtId) { if (servicePgtPolicy != null) { LOGGER.trace("Overriding proxy-granting ticket policy with the specific policy: [{}]", servicePgtPolicy); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, new HardTimeoutExpirationPolicy(servicePgtPolicy.getMaxTimeToLiveInSeconds())); } LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); }
Source:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; try { do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); } // Catch exception if any catch (Exception e) { System.err.println("Error: " + e.getMessage()); } return tempFile; }

Target:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); return tempFile; }
Source:
public SRResult similarity(String phrase1, String phrase2, Language language, boolean explanations) throws DaoException { if (phrase1 == null || phrase2 == null) { throw new NullPointerException("Null phrase passed to similarity"); } try { TIntDoubleHashMap scores1 = getConceptVector(phrase1, language); TIntDoubleHashMap scores2 = getConceptVector(phrase2, language); double sim = SimUtils.cosineSimilarity(scores1, scores2); return new SRResult(sim); // TODO: normalize } catch (WikapidiaException e) { throw new DaoException(e); } }

Target:
public SRResult similarity(String phrase1, String phrase2, Language language, boolean explanations) throws DaoException { if (phrase1 == null || phrase2 == null) { throw new NullPointerException("Null phrase passed to similarity"); } TIntDoubleHashMap scores1 = getConceptVector(phrase1, language); TIntDoubleHashMap scores2 = getConceptVector(phrase2, language); double sim = SimUtils.cosineSimilarity(scores1, scores2); return new SRResult(sim); // TODO: normalize }
Source:
public void deleteVerificationSubmission(long verificationId) { wrapSubmissionNotFound(verificationId, () -> { MapSqlParameterSource param = new MapSqlParameterSource(); param.addValue(COL_VERIFICATION_SUBMISSION_ID.toLowerCase(), verificationId); basicDao.deleteObjectByPrimaryKey(DBOVerificationSubmission.class, param); return false; }); }

Target:
public void deleteVerificationSubmission(long verificationId) { MapSqlParameterSource param = new MapSqlParameterSource(); param.addValue(COL_VERIFICATION_SUBMISSION_ID.toLowerCase(), verificationId); basicDao.deleteObjectByPrimaryKey(DBOVerificationSubmission.class, param); }
Source:
protected String getClassProperty() { return super.getClassProperty() + ' ' + this.getDescriptor().getId() + "message"; }

Target:
protected String getClassProperty() { return super.getClassProperty() + ' ' + this.getDescriptor().getId().getId() + "message"; }
Source:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (name.startsWith("org.modelmapper.internal.cglib")) return internalClassSpace.loadClass(name); for (ClassLoader additionalClassLoader : additionalClassLoaders) { try { return additionalClassLoader.loadClass(name); } catch (ClassNotFoundException e) // Don't mind... Attempt next class loader } throw new ClassNotFoundException(); }

Target:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (name.startsWith("org.modelmapper.internal.cglib")) return internalClassSpace.loadClass(name); for (ClassLoader additionalClassLoader : additionalClassLoaders) { try { return additionalClassLoader.loadClass(name); } catch (ClassNotFoundException e) { // Don't mind... Attempt next class loader } } throw new ClassNotFoundException(name); }
Source:
public boolean isPutIntoOven() throws OvenException { try { final URL url = new URL("https://www.google.com/search?q=potato"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int inOven = connection.getResponseCode(); return inOven == 200; } catch (IOException ex) { throw new OvenException(); } }

Target:
public boolean isPutIntoOven() throws OvenException { try { final URL url = new URL("https://www.google.com/search?q=potato"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int inOven = connection.getResponseCode(); return inOven == 200; } catch (IOException ex) { throw new OvenException(ex); } }
Source:
public String expand(Map<String, ?> variables) { String expanded = super.expand(variables); if (this.json) { /* decode only the first and last character */ expanded = expanded.substring( expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length()); expanded = JSON_TOKEN_START + expanded; expanded = expanded.substring(0, expanded.lastIndexOf(JSON_TOKEN_END_ENCODED)); expanded += JSON_TOKEN_END; } return expanded; }

Target:
public String expand(Map<String, ?> variables) { String expanded = super.expand(variables); if (this.json) { /* decode only the first and last character */ StringBuilder sb = new StringBuilder(); sb.append(JSON_TOKEN_START); sb.append(expanded, expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length(), expanded.lastIndexOf(JSON_TOKEN_END_ENCODED)); sb.append(JSON_TOKEN_END); return sb.toString(); } return expanded; }
Source:
public static String urlEncode(Object arg) { try { return URLEncoder.encode(String.valueOf(arg), UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }

Target:
static String urlEncode(Object arg) { try { return URLEncoder.encode(String.valueOf(arg), UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
public void reasonPhraseIsOptional() { Response response = Response.builder() .status(200) .reason(null) /* reason phrase */ .headers(Collections.<String, Collection<String>>emptyMap()) .body(new byte[0]) .build(); assertThat(response.reason()).isNull(); assertThat(response.toString()).isEqualTo("HTTP/1.1 200\n\n"); }

Target:
public void reasonPhraseIsOptional() { Response response = Response.builder() .status(200) .headers(Collections.<String, Collection<String>>emptyMap()) .body(new byte[0]) .build(); assertThat(response.reason()).isNull(); assertThat(response.toString()).isEqualTo("HTTP/1.1 200\n\n"); }
Source:
private Object expandElements(Expander expander, Object value) { if (value instanceof Iterable) { return expandIterable(expander, (Iterable) value); } else if (value.getClass().isArray()) { return expandIterable(expander, Arrays.asList((Object[])value)); } return expander.expand(value); }

Target:
private Object expandElements(Expander expander, Object value) { if (value instanceof Iterable) { return expandIterable(expander, (Iterable) value); } return expander.expand(value); }
Source:
public void encodesXml() throws Exception { EncoderBindings bindings = new EncoderBindings(); ObjectGraph.create(bindings).inject(bindings); MockObject mock = new MockObject(); mock.setValue("Test"); RequestTemplate template = new RequestTemplate(); bindings.encoder.encode(mock, template); System.out.println(new String(template.body())); assertEquals(new String(template.body(), UTF_8), "<?xml version=\"1.0\" encoding=\"UTF-8\" " + "standalone=\"yes\"?><mockObject><value>Test</value></mockObject>"); }

Target:
public void encodesXml() throws Exception { EncoderBindings bindings = new EncoderBindings(); ObjectGraph.create(bindings).inject(bindings); MockObject mock = new MockObject(); mock.setValue("Test"); RequestTemplate template = new RequestTemplate(); bindings.encoder.encode(mock, template); assertEquals(new String(template.body(), UTF_8), "<?xml version=\"1.0\" encoding=\"UTF-8\" " + "standalone=\"yes\"?><mockObject><value>Test</value></mockObject>"); }
Source:
public String toString(Schema schema) { // we want the string this returns to be consistent // ensure the set is sorted before calling toString on it. Iterable<String> strings = Iterables.transform(set, new ToString<T>(schema)); return Joiner.on(',').join(Sets.newTreeSet(strings)); }

Target:
public String toString(Schema schema) { return Joiner.on(',').join( Iterables.transform(set, new ToString<T>(schema))); }
Source:
public static <E> void assertContentEquals(Set<E> expected, View<E> view) { DatasetReader<E> reader = null; try { reader = view.newReader(); Assert.assertEquals(expected, Sets.newHashSet((Iterable<E>) reader)); } finally { Closeables.closeQuietly(reader); } }

Target:
public static <E> void assertContentEquals(Set<E> expected, View<E> view) throws IOException { DatasetReader<E> reader = null; try { reader = view.newReader(); Assert.assertEquals(expected, Sets.newHashSet((Iterable<E>) reader)); } finally { Closeables.close(reader, false); } }
Source:
public ConfigBuilder writeTo(URI viewUri) { conf.set(KITE_OUTPUT_URI, viewUri.toString()); DatasetRepository viewRepo = Datasets.repositoryFor(viewUri); if (viewRepo instanceof TemporaryRepositoryAccessor) { TemporaryDatasetRepository tempRepo = ((TemporaryRepositoryAccessor) viewRepo).getTemporaryRepository( UUID.randomUUID().toString()); // set the temporary repository conf.set(KITE_TEMP_REPO_URI, tempRepo.getUri().toString()); } return this; }

Target:
public ConfigBuilder writeTo(URI viewUri) { conf.set(KITE_OUTPUT_URI, viewUri.toString()); return this; }
Source:
private static String removeNonDefault(String key, Map<String, String> options, Map<String, String> defaults) { String defaultValue = defaults.get(key); if (options.containsKey(key)) { String value = options.remove(key); if (!defaultValue.equals(value)) { return value; } } // return null to default the value when parsed return null; }

Target:
private static String removeNonDefault(String key, Map<String, String> options, Map<String, String> defaults) { String defaultValue = defaults.get(key); if (options.containsKey(key)) { String value = options.remove(key); if (defaultValue == null || !defaultValue.equals(value)) { return value; } } // return null to default the value when parsed return null; }
Source:
private boolean isSupportedType(String type) throws Exception { boolean supported = false; switch (type) { case "ear": case "rar": case "eba": case "esa": case "liberty-assembly": if(installThinProject) { throw new MojoExecutionException("thin-project cannot be configured for installAppPackages for the " + type + " packaging type"); } else { supported = true; } break; case "war": supported = true; break; case "jar": if (installThinProject) { supported = true; } break; default: break; } return supported; }

Target:
private boolean isSupportedType(String type) { boolean supported = false; switch (type) { case "ear": case "rar": case "eba": case "esa": case "liberty-assembly": if(installThinProject) { log.warn("thin-project cannot be configured for installAppPackages for the " + type + " packaging type"); } else { supported = true; } break; case "war": supported = true; break; case "jar": if (installThinProject) { supported = true; } break; default: break; } return supported; }
Source:
public void testSkipWithXML() throws Exception { // This test has the skip flag true with the XML file already existing. // In this case, the server should use the arquillian.xml that is in // src/test/resources/arquillian.xml. File arquillianXML = new File("target/test-classes/arquillian.xml"); InputStream is = new FileInputStream(arquillianXML); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { // Make sure none of the lines indicate that the file was generated // by the configure-arquillian goal. assertFalse(line.equals(Constants.CONFIGURE_ARQUILLIAN_COMMENT)); } }

Target:
public void testSkipWithXML() throws Exception { // This test has the skip flag true with the XML file already existing. // In this case, the server should use the arquillian.xml that is in // src/test/resources/arquillian.xml. File arquillianXML = new File("target/test-classes/arquillian.xml"); InputStream is = new FileInputStream(arquillianXML); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { // Make sure none of the lines indicate that the file was generated // by the configure-arquillian goal. assertFalse(line.contains(Constants.CONFIGURE_ARQUILLIAN_COMMENT)); } }
Source:
private static File getConfigDropinsDir() { File configDropins = null; // if configDirectory exists and contains configDropins directory, // its configDropins has higher precedence. if (configDirectory != null && configDirectory.exists()) { configDropins = new File(configDirectory, "configDropins"); } if (configDropins == null || !configDropins.exists()) { configDropins = new File(getServerXML().getParent(), "configDropins"); } return configDropins; }

Target:
private static File getConfigDropinsDir() { File configDropins = null; if (configDropins == null || !configDropins.exists()) { configDropins = new File(getServerXML().getParent(), "configDropins"); } return configDropins; }
Source:
public void createElement(String key, String value) { Element child = doc.createElement(key); child.appendChild(doc.createTextNode(value)); doc.getDocumentElement().appendChild(child); }

Target:
public void createElement(String key, String value) { createElement(doc.getDocumentElement(), key, value); }
Source:
public void zoomToRegion() { // If we have a region, then zoom to it. ObaRegion region = Application.get().getCurrentRegion(); if (region != null && mMap != null) { LatLngBounds b = MapHelpV2.getRegionBounds(region); //Setting the width and height of your screen int width = getResources().getDisplayMetrics().widthPixels; int height = getResources().getDisplayMetrics().heightPixels; int padding = (int) (width * 0.12); // offset from edges of the map 12% of screen mMap.animateCamera((CameraUpdateFactory.newLatLngBounds(b, width, height, padding))); } }

Target:
public void zoomToRegion() { // If we have a region, then zoom to it. ObaRegion region = Application.get().getCurrentRegion(); if (region != null && mMap != null) { LatLngBounds b = MapHelpV2.getRegionBounds(region); //Setting the width and height of your screen int width = getResources().getDisplayMetrics().widthPixels; int height = getResources().getDisplayMetrics().heightPixels; // Set the individual padding using mMap.setPadding(left, top, right, bottom), // this padding will be permanent and below padding = 0 will not change the padding // set by the setPadding(left, top, right, bottom). // padding = 0 is the just default padding in place user will not set the padding // mMap.setPadding(left, top, right, bottom). int padding = 0; mMap.animateCamera((CameraUpdateFactory.newLatLngBounds(b, width, height, padding))); } }
Source:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); String focusedStopId = mController.getFocusedStopId(); if (focusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }

Target:
public void onInfoWindowClick(Marker marker) { // Stop any callbacks to refresh the vehicle marker popup balloons mCustomInfoWindowAdapter.cancelUpdates(); // Show trip details screen for the vehicle associated with this marker ObaTripStatus status = mMarkerData.getStatusFromMarker(marker); if (mController != null && mController.getFocusedStopId() != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), mController.getFocusedStopId()); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } }
Source:
public void onLocationChanged(Location l) { boolean firstFix = false; if (mLastLocation == null) { // mLastLocation is static, so this is a first fix across all BaseMapFragments firstFix = true; } mLastLocation = l; if (mListener != null) { // Show real-time location on map mListener.onLocationChanged(l); } if (firstFix) { // If its our first location (across all BaseMapFragments), move the camera to it setMyLocation(true, false); onFocusChanged(null,null,l); } }

Target:
public void onLocationChanged(Location l) { boolean firstFix = false; if (mLastLocation == null) { // mLastLocation is static, so this is a first fix across all BaseMapFragments firstFix = true; } mLastLocation = l; if (mListener != null) { // Show real-time location on map mListener.onLocationChanged(l); } if (firstFix) { // If its our first location (across all BaseMapFragments), move the camera to it setMyLocation(true, false); } }
Source:
public static void initAnalytics(Context context) { if (isAnalyticsActive() == false) { //Disable Google Analytics GoogleAnalytics.getInstance(context).setAppOptOut(true); } if (BuildConfig.DEBUG) { //Disables reporting when app runs on debug GoogleAnalytics.getInstance(context).setDryRun(true); } }

Target:
public static void initAnalytics(Context context) { if (!isAnalyticsActive()) { //Disable Google Analytics GoogleAnalytics.getInstance(context).setAppOptOut(true); } if (BuildConfig.DEBUG) { //Disables reporting when app runs on debug GoogleAnalytics.getInstance(context).setDryRun(true); } }
Source:
public void saveValidityBackup() throws IOException { final String backupValidityKey = _sessionIdFormat.createBackupKey( _validityKey ); final int maxInactiveInterval = _session.getMaxInactiveInterval(); // fix for #88, along with the change in session.getMemcachedExpirationTimeToSet final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval; _memcached.set( backupValidityKey, toMemcachedExpiration(expiration), _validityData ); }

Target:
public void saveValidityBackup() { final String backupValidityKey = _sessionIdFormat.createBackupKey( _validityKey ); final int maxInactiveInterval = _session.getMaxInactiveInterval(); // fix for #88, along with the change in session.getMemcachedExpirationTimeToSet final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval; _memcached.set( backupValidityKey, toMemcachedExpiration(expiration), _validityData ); }
Source:
private Target findMatchingTarget(String targetLabel) throws AndroidContainerConfigurationException { // target from config can be like "19", "android-19", // "Google Inc.:Google APIs:19" or "Google Inc.:Google APIs x86:19" Target target = null; for (Target t : availableTargets) { if (t.matches(targetLabel)) { target = t; break; } } if (target == null) { throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); } return target; }

Target:
private Target findMatchingTarget(String targetLabel) throws AndroidContainerConfigurationException { // target from config can be like "19", "android-19", // "Google Inc.:Google APIs:19" or "Google Inc.:Google APIs x86:19" for (Target target : availableTargets) { if (target.matches(targetLabel)) { return target; } } throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); }
Source:
public void unsubscribeFrom(final String channelName) { if (channelName == null) { throw new IllegalArgumentException("Cannot unsubscribe from null channel"); } final InternalChannel channel = channelNameToChannelMap.remove(channelName); if (channel == null) { return; } if (connection.getState() == ConnectionState.CONNECTED) { // only private encrypted channels need to be securely torn down if (channel instanceof PrivateEncryptedChannelImpl) { ((PrivateEncryptedChannelImpl) channel).tearDownChannel(); } sendUnsubscribeMessage(channel); } }

Target:
public void unsubscribeFrom(final String channelName) { if (channelName == null) { throw new IllegalArgumentException("Cannot unsubscribe from null channel"); } final InternalChannel channel = channelNameToChannelMap.remove(channelName); if (channel == null) { return; } if (connection.getState() == ConnectionState.CONNECTED) { sendUnsubscribeMessage(channel); } }
Source:
public String toSubscribeMessage() { String msg = super.toSubscribeMessage(); myUserID = extractUserIdFromChannelData((String)channelData); return msg; }

Target:
public String toSubscribeMessage() { String msg = super.toSubscribeMessage(); myUserID = extractUserIdFromChannelData(channelData); return msg; }
Source:
public void onClose(final int code, final String reason, final boolean remote) { if (state != ConnectionState.DISCONNECTED) { activityTimer.cancelTimeouts(); factory.queueOnEventThread(new Runnable() { @Override public void run() { updateState(ConnectionState.DISCONNECTED); factory.shutdownThreads(); } }); } else { // Sometimes expected when we disconnected due to pong timeout log.error("Received close from underlying socket when already disconnected. " + "Close code [" + code + "], Reason [" + reason + "], Remote [" + remote + "]"); } }

Target:
public void onClose(final int code, final String reason, final boolean remote) { if (state == ConnectionState.DISCONNECTED) { log.error("Received close from underlying socket when already disconnected. " + "Close code [" + code + "], Reason [" + reason + "], Remote [" + remote + "]"); return; } activityTimer.cancelTimeouts(); factory.queueOnEventThread(new Runnable() { @Override public void run() { updateState(ConnectionState.DISCONNECTED); factory.shutdownThreads(); } }); }
Source:
public void testCommitId() { try { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); }

Target:
public void testCommitId() throws IOException { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); }
Source:
public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(context); if (hasVersioning) { XWikiDocument doc = context.getDoc(); if (doc != null) { XWikiDocumentArchive documentArchive = doc.getDocumentArchive(); if (documentArchive == null) { doc.setDocumentArchive(new XWikiDocumentArchive()); } } this.getVersioningStore(context).resetRCSArchive(this, true, context); } }

Target:
public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(context); if (hasVersioning) { XWikiDocument doc = context.getDoc(); if (doc != null) { XWikiDocumentArchive documentArchive = doc.getDocumentArchive(context); if (documentArchive != null) { this.getVersioningStore(context).resetRCSArchive(this, true, context); } } } }
Source:
public void setUp(TestUtils setup, TestReference testReference) throws Exception { setup.loginAsSuperAdmin(); setup.deletePage(testReference); setup.createPageWithAttachment(testReference, "", "Test Attachments", "deletedFile1.txt", new ByteArrayInputStream("attachment content1".getBytes())); ViewPage testPage = setup.gotoPage(testReference); AttachmentsPane attachmentsPane = testPage.openAttachmentsDocExtraPane(); attachmentsPane.deleteAttachmentByFileByName("deletedFile1.txt"); }

Target:
void setUp(TestUtils setup, TestReference testReference) throws Exception { setup.loginAsSuperAdmin(); setup.deletePage(testReference); setup.createPageWithAttachment(testReference, "", "Test Attachments", "deletedFile1.txt", new ByteArrayInputStream("attachment content1".getBytes())); ViewPage testPage = setup.gotoPage(testReference); AttachmentsPane attachmentsPane = testPage.openAttachmentsDocExtraPane(); attachmentsPane.deleteAttachmentByFileByName("deletedFile1.txt"); }
Source:
public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { buffer.append(getComputedValue(name, prefix, object, context)); }

Target:
public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { try { buffer.append(getComputedValue(name, prefix, object, context)); } catch (Exception e) { // TODO: append a rendering style complete error instead buffer.append(e.getMessage()); } }
Source:
public String getRenderedContent(Syntax targetSyntax, boolean transformationContextIsolated, XWikiContext context, boolean retrieveTranslation) throws XWikiException { // Make sure the context secure document is the current document so that it's executed with its own // rights Object currentSdoc = context.get("sdoc"); try { XWikiDocument sdoc; if (retrieveTranslation) { sdoc = getTranslatedDocument(context); } else { sdoc = this; } context.put("sdoc", sdoc); return display(targetSyntax, false, transformationContextIsolated, false, retrieveTranslation); } finally { context.put("sdoc", currentSdoc); } }

Target:
private String getRenderedContent(Syntax targetSyntax, boolean transformationContextIsolated, XWikiContext context, boolean retrieveTranslation) throws XWikiException { // Make sure the context secure document is the current document so that it's executed with its own // rights Object currentSdoc = context.get("sdoc"); try { XWikiDocument sdoc; if (retrieveTranslation) { sdoc = getTranslatedDocument(context); } else { sdoc = this; } context.put("sdoc", sdoc); return display(targetSyntax, false, transformationContextIsolated, false, retrieveTranslation); } finally { context.put("sdoc", currentSdoc); } }
Source:
protected static void mountFromHostToContainer(GenericContainer container, String sourceDirectory, String targetDirectory) { // File mounting is awfully slow on Mac OSX. For example starting Tomcat with XWiki mounted takes // 45s+, while doing a COPY first and then starting Tomcat takes 8s (+5s for the copy). String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("mac os x")) { MountableFile mountableDirectory = MountableFile.forHostPath(sourceDirectory); container.withCopyFileToContainer(mountableDirectory, targetDirectory); } else { container.withFileSystemBind(sourceDirectory, targetDirectory); } }

Target:
protected void mountFromHostToContainer(GenericContainer container, String sourceDirectory, String targetDirectory) { // File mounting is awfully slow on Mac OSX. For example starting Tomcat with XWiki mounted takes // 45s+, while doing a COPY first and then starting Tomcat takes 8s (+5s for the copy). String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("mac os x")) { MountableFile mountableDirectory = MountableFile.forHostPath(sourceDirectory); container.withCopyFileToContainer(mountableDirectory, targetDirectory); } else { container.withFileSystemBind(sourceDirectory, targetDirectory); } }
Source:
public CopyRequest createCopyRequest(Collection<EntityReference> sources, EntityReference destination) { CopyRequest request = new CopyRequest(); this.initEntityRequest(request, RefactoringJobs.COPY, sources); EntityReference dest; // in case of a simple copy request, we only want it to be placed under the given destination document. if (destination.getType().equals(EntityType.DOCUMENT)) { DocumentReference documentReference = (DocumentReference) destination; dest = documentReference.getLastSpaceReference(); } else { dest = destination; } request.setDestination(dest); return request; }

Target:
public CopyRequest createCopyRequest(Collection<EntityReference> sources, EntityReference destination) { CopyRequest request = new CopyRequest(); this.initEntityRequest(request, RefactoringJobs.COPY, sources); EntityReference dest; // in case of a simple copy request, we only want it to be placed under the given destination document. if (destination.getType().equals(EntityType.DOCUMENT)) { DocumentReference documentReference = new DocumentReference(destination); dest = documentReference.getLastSpaceReference(); } else { dest = destination; } request.setDestination(dest); return request; }
Source:
public Class< ? > getType() { if (this.parameterType == null) { return String.class; } else { return ReflectionUtils.getTypeClass(this.parameterType); } }

Target:
public Class<?> getType() { Class<?> type = ReflectionUtils.getTypeClass(this.parameterType); if (type == null) { type = String.class; } return type; }
Source:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { attachment.setDoc(this); return this.attachmentList.set(attachment); }

Target:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { return this.attachmentList.set(attachment); }
Source:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { if (map.put(x.getFilename(), x) == null) { changed = true; added(x); } } if (changed) { updatedMap(); } return changed; }

Target:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { XWikiAttachment put = map.put(x.getFilename(), x); if (put != x) { changed = true; added(x); } } if (changed) { updatedMap(); } return changed; }
Source:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return !set.equals(attachment); }

Target:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return set != attachment; }
Source:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { XWikiAttachment put = map.put(x.getFilename(), x); if (!x.equals(put)) { changed = true; added(x); } } if (changed) { updatedMap(); } return changed; }

Target:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { XWikiAttachment put = map.put(x.getFilename(), x); if (put != x) { changed = true; added(x); } } if (changed) { updatedMap(); } return changed; }
Source:
public boolean retainAll(Collection<?> c) { boolean changed = false; Collection<XWikiAttachment> values = map.values(); for (XWikiAttachment x : values) { if (!c.contains(x)) { map.remove(x.getFilename(), x); changed = true; } } if (changed) { updatedMap(); } return changed; }

Target:
public boolean retainAll(Collection<?> c) { boolean changed = false; Collection<XWikiAttachment> values = map.values(); for (XWikiAttachment x : values) { if (!c.contains(x)) { map.remove(x.getFilename()); changed = true; } } if (changed) { updatedMap(); } return changed; }
Source:
public byte[] getResourceContentAsBytes(String name) throws IOException { byte output[] = new byte[0]; if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is == null) { output = FileUtils.readFileToByteArray(new File(name)); } else output = IOUtils.toByteArray(is); } } return output; }

Target:
public byte[] getResourceContentAsBytes(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toByteArray(is); } } catch (Exception e) { } } return FileUtils.readFileToByteArray(new File(name)); }
Source:
public byte[] getResourceContentAsBytes(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toByteArray(is); } } catch(Exception e){ } return FileUtils.readFileToByteArray(new File(name)); } return new byte[0]; }

Target:
public byte[] getResourceContentAsBytes(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toByteArray(is); } } catch (Exception e) { } } return FileUtils.readFileToByteArray(new File(name)); }
Source:
public BodyPart addPart(BodyPart bodyPart) { return addPart(null, bodyPart); }

Target:
public void addPart(BodyPart bodyPart) { addPart(null, bodyPart); }