auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { throw new MacroExecutionException(String.format("Cannot find Parser for syntax [%s]", syntax.toIdString()), e); } }

Target:
Line too long.
Source:
public boolean equals(Object object) { if ((object == null) || (object.getClass() != getClass())) { return false; } if (object == this) { return true; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); }

Target:
No need for those parenthesis (they will even produce a Sonar issue).
Source:
protected Map<Object, Object> createDestination( MappingContext<Map<?, ?>, Map<Object, Object>> context) { if (context.getDestinationType().isInterface()) { if (SortedMap.class.isAssignableFrom(context.getDestinationType())) { return new TreeMap<Object, Object>(); } return new HashMap<Object, Object>(); } return context.getMappingEngine().createDestination(context); }

Target:
What do you think: ```java if (!context.getDestinationType().isInterface()) return context.getMappingEngine().createDestination(context); if (SortedMap.class.isAssignableFrom(context.getDestinationType())) return new TreeMap<Object, Object>(); return new HashMap<Object, Object>(); ``` to reduce the deeply nested if statement. And we prefer no curly braces if there is only one statement in the if/else as our coding stye.
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:
coding style: ``` try { ... } catch (ClassNotFoundException e) { // Don't mind... Attempt next class loader |
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:
Should probably include the cause.
Source:
Request(HttpMethod method, String url, Map<String, Collection<String>> headers, Body body, RequestTemplate requestTemplate) { this.httpMethod = checkNotNull(method, "httpMethod of %s", method.name()); this.url = checkNotNull(url, "url"); this.headers = checkNotNull(headers, "headers of %s %s", method, url); this.body = (body != null) ? body : Body.EMPTY; this.requestTemplate = requestTemplate; }

Target:
That is going to be a problem... https://github.com/OpenFeign/feign/blob/master/httpclient/src/main/java/feign/httpclient/ApacheHttpClient.java#L135 There are clients out there that change behavior when body is null
Source:
public Options(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout, TimeUnit readTimeoutUnit, boolean followRedirects) { super(); this.connectTimeout = connectTimeout; this.connectTimeoutUnit = connectTimeoutUnit; this.readTimeout = readTimeout; this.readTimeoutUnit = readTimeoutUnit; this.followRedirects = followRedirects; this.allowStreamingMode = true; }

Target:
like the idea of defaulting to true
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:
Shouldn't we be using a `StringBuilder` ?
Source:
public String contentUTF8() { if (content != null) { return new String(content, UTF_8); } else { return null; } }

Target:
It may be better to return an empty string here instead of `null`. Unless others look into this code, we may be pushing the null pointer higher. Thoughts?
Source:
public Charset charset() { return (this.encoding != null) ? this.encoding : Util.UTF_8; }

Target:
Hrmmm, why?! if `encoding` is null usually mean this is a binary protocol
Source:
public Feign build() { if (library == null) { throw new IllegalStateException("A Reactive Streams Library has not been specified"); } super.contract(new ReactiveDelegatingContract(this.contract)); super.invocationHandlerFactory(new ReactiveInvocationHandlerFactory(this.library)); return super.build(); }

Target:
Would recommend checking if contract is an instance of `ReactiveC` and only warp of not
Source:
public JAXBContext getContext(Class<?> clazz) throws JAXBException { JAXBContext jaxbContext = this.jaxbContexts.get(clazz); if (jaxbContext == null) { jaxbContext = JAXBContext.newInstance(clazz); this.jaxbContexts.putIfAbsent(clazz, jaxbContext); } return jaxbContext; }

Target:
Sorry, how changing visibility makes caching?
Source:
private void preloadContextCache(List<Class<?>> classes) throws JAXBException { for (Class<?> clazz : classes) { getContext(clazz); } }

Target:
The list can be applied during building: ```java JAXBContextFactory.build(List<Class<?>> classes) ``` Additional classes can then be loaded on demand.
Source:
private JacksonIterator(Type type, ObjectMapper mapper, Response response, Reader reader) throws IOException { this.response = response; this.parser = mapper.getFactory().createParser(reader); this.objectReader = mapper.reader().forType(mapper.constructType(type)); }

Target:
one thing you'll notice in other feign code is that we infrequently use private access as the modifiers bloat bytecode and sharing packages isn't supported outside feign anyway. if you feel strongly about hiding things, making the type private but default modifiers on the ctor and symbols accomplishes the same.
Source:
private Type actualIteratorTypeArgument(Type type) { if (!(type instanceof ParameterizedType)) { throw new IllegalArgumentException("Not supported type " + type.toString()); } ParameterizedType parameterizedType = (ParameterizedType) type; if (!Iterator.class.equals(parameterizedType.getRawType())) { throw new IllegalArgumentException("Not an iterator type " + parameterizedType.getRawType().toString()); } return ((ParameterizedType) type).getActualTypeArguments()[0]; }

Target:
looks like this can be static
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:
make package private
Source:
private JAXBDecoder(Builder builder) { if (builder.jaxbContextFactory == null) { throw new IllegalStateException("JAXBContextFactory must be non-null"); } this.jaxbContextFactory = builder.jaxbContextFactory; this.namespaceAware = builder.namespaceAware; }

Target:
Seems like this could go in `build()`.
Source:
public Response build() { return Response.create(status, reason, headers, body, request); }

Target:
I'd call `new Response(this)`
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:
I'd initialize the builder.headers to emptyMap to clear some of this c&p
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:
why are we adding array support?
Source:
private Map<Method, Method> toFallbackMethod(Map<Method, MethodHandler> dispatch) { Map<Method, Method> result = new HashMap<Method, Method>(); for (Map.Entry<Method, MethodHandler> entry : dispatch.entrySet()) { Method key = entry.getKey(); key.setAccessible(true); result.put(key, key); } return result; }

Target:
setAccessible is mutating, so you don't need to save this off
Source:
public LBClient(ILoadBalancer lb, IClientConfig clientConfig) { super(lb, clientConfig); this.setRetryHandler(RetryHandler.DEFAULT); this.clientConfig = clientConfig; connectTimeout = clientConfig.get(CommonClientConfigKey.ConnectTimeout); readTimeout = clientConfig.get(CommonClientConfigKey.ReadTimeout); }

Target:
hide this and expose factory method
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:
Please scrub out printlns
Source:
public Set<T> getSet() { return set; }

Target:
Minor: there is also a method, `Predicates.asSet(In)`, that exposes the inner set. I think the purpose of that was to mimic the use of `Ranges.asSet(Range)`, which has to be a static method because we allow ranges of objects that aren't `Comparable` but back the `asSet` method with a Guava range that requires a `Comparable` type. I'm fine with changing to use this method everywhere, since this is more straight-forward. But I'd like to either use `Predicates.asSet(In)` or `In#getSet()`, not both.
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:
I'm not sure I'm clear on what happens here. Generally, we are using a `LinkedHashMap` or `LinkedHashSet` to preserve the order. If we aren't doing that somewhere, then I think it is a bug and should be fixed. URIs should only be normalized when needed, to avoid annoyance. I think that's what you do in this case, but I wanted to make sure.
Source:
public void testMultipleStringValuesWithEmpty() { Assert.assertEquals("In<Utf8>#toString(STRING)", ",a,b", Predicates.in(new Utf8("a"), new Utf8("b"), new Utf8("")).toString(STRING)); Assert.assertEquals("In#toString(STRING)", ",a,b", Predicates.in("a", "b", "").toString(STRING)); Assert.assertEquals("In.fromString(String, STRING)", Predicates.in("a", "b", ""), In.<String>fromString("a,b,", STRING)); }

Target:
I don't think these should be changed. The `In` implementation should generally preserve order unless normalized to produce a `String`. Normalization should probably be a peer of `toString(Schema)`, `toNormalizedString(Schema)`.
Source:
public void tearDown() { if (morphline != null) { Notifications.notifyShutdown(morphline); Notifications.notifyShutdown(morphline); morphline = null; } }

Target:
Let's also call super.tearDown()
Source:
public URI build() { try { URI optionsUri = pattern.construct(options); StringBuilder uri = new StringBuilder(); uri.append(isView ? VIEW_SCHEME : DATASET_SCHEME).append(":") .append(optionsUri.getScheme()).append(":") .append(optionsUri.getRawSchemeSpecificPart()); return new URI(uri.toString()); } catch (URISyntaxException e) { throw new IllegalArgumentException("Could not build URI", e); } }

Target:
Does it work with fewer changes here? Maybe just concatenate: ``` java return new URI(isView ? VIEW_SCHEME : DATASET_SCHEME + ":" + pattern.construct(options).toString()); ```
Source:
public static Configuration get() { return conf; }

Target:
Configuration is mutable so it would be safer to return a new instance here. Global mutable state is a recipe for hard-to-diagnose bugs.
Source:
public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); }

Target:
Should be namespace, not name.
Source:
public ConfigBuilder readFrom(View<?> view) { if (view instanceof Dataset && view instanceof FileSystemDataset) { FileSystemDataset dataset = (FileSystemDataset) view; conf.set(KITE_PARTITION_DIR, String.valueOf(dataset.getDescriptor().getLocation())); } withType(view.getType()); return readFrom(view.getUri()); }

Target:
instanceof Dataset is redundant -- why not just a single instanceof FilesystemDataset check?
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:
Closeables.closeQuietly is deprecated in Guava 14 so we should avoid using it. See https://code.google.com/p/guava-libraries/issues/detail?id=1118&can=1&q=closeQuietly&sort=id%20-owner&colspec=ID%20Type%20Status%20Milestone%20Summary We could just call `Closeables.close(reader, false)` so the IOException is never swallowed, then if we declare the test method to throw IOException we will fail the test if this condition ever happens.
Source:
private E makeRecord() { if (recordClass != null && recordClass != GenericData.Record.class) { E record = makeReflectRecord(); if (record != null) { return record; } } return makeGenericRecord(); }

Target:
Rather than allowing this to be null if null is passed in, we should add a Precondition check
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:
Use getJobDatasetName instead of UUID since it's already unique, and makes it easy to debug.
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:
Possible NPE here unless I am mistaken -- there may be no defaultValue.
Source:
public static <E> ReadableSource<E> asSource(URI uri, Class<E> type) { View<E> view = Datasets.<E, View<E>>view(uri); return new DatasetSourceTarget<E>(view, type); }

Target:
Rather than instantiating the view here, I think you should just pass it to the [`DatasetSourceTarget` constructor](https://github.com/ben-roling/kite/blob/CDK-474-CrunchDatasets-by-uri/kite-data/kite-data-crunch/src/main/java/org/kitesdk/data/crunch/DatasetSourceTarget.java#L79). That way we keep the number of places where views are instantiated to a minimum because we always want to push that as late as possible. For example, support for `handleExisting` will probably push that until when the job is being committed.
Source:
public Table getTable(String dbName, String tableName) { Table table; try { synchronized(client) { table = HCatUtil.getTable(client, dbName, tableName); } } catch (RuntimeException e) { throw new RuntimeException("Hive metastore exception", e); } catch (Exception e) { throw new DatasetNotFoundException("Hive table lookup exception", e); } if (table == null) { throw new DatasetNotFoundException("Could not find info for table: " + tableName); } return table; }

Target:
Any reason this is needed given we already catch Exception? (Also, it's only been added in a few cases - e.g. tableExists doesn't catch RuntimeException.) If we do need it it might be better to make this a DatasetException so we know it came from Kite.
Source:
public ElasticTimeOutStrategy(String timeoutPercentage, String timeoutMinutesElasticDefault, String numberOfBuilds) { this.timeoutPercentage = timeoutPercentage; this.timeoutMinutesElasticDefault = timeoutMinutesElasticDefault; this.numberOfBuilds = numberOfBuilds; }

Target:
Please call the new constructor passing the dafault value to `failSafeTimeoutDuration`. That makes what you want to do clear.
Source:
public void dispose() { if (disposed) { throw new IllegalStateException("Attempt to invoke ApplicationInstance.dispose() on disposed instance."); } try { if (defaultWindow != null) { defaultWindow.doDispose(); defaultWindow.register(null); } synchronized (taskQueueMap) { taskQueueMap.clear(); } } finally { synchronized(disposed) { disposed = true; } } }

Target:
ABSOLUTE SHOW STOPPER.
Source:
protected boolean isAnyAppConfiguredInSourceServerXml() { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); bConfigured = true; } return bConfigured; }

Target:
Here I would just say `return true`. Then fall through `return false`, instead of creating a variable.
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:
I don't think throwing an exception here is right, based on what the calling method does. I think you should just log a warning with the information below and then the calling method will handle accordingly based on the return of false.
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:
Wouldn't the contains method be more reliable here, in case some spacing was different at the beginning or end of the line?
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:
If we can rely on the target for server.xml, then I think we should be able to rely on target for the configDropins directory as well. I think after we switch to target, then we don't need first `if`.
Source:
public void createElement(String key, String value) { Element child = doc.createElement(key); child.appendChild(doc.createTextNode(value)); doc.getDocumentElement().appendChild(child); }

Target:
this could replace 147-149 with createElement(doc.getDocumentElement, key, value);
Source:
public NotifierTask(Context context, TaskContext taskContext, Uri uri, String notifyTitle, String notifyText) { mContext = context; mTaskContext = taskContext; mCR = mContext.getContentResolver(); mUri = uri; mNotifyTitle = notifyTitle; mNotifyText = notifyText; mSettings = Application.getPrefs(); }

Target:
Does this need to be a member variable? It is only used once and comes from a static method so it could just be a local variable down in createNotification().
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:
Any reason in particular that exactly 12% is used here?
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:
You should check if `mController` is null before calling `mController.getFocusedStopId()`, to prevent potential NPEs.
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:
Just realized that this change is still in this branch. We changed this model in a previous PR to not using this callback on first GPS fix, so this branch should be rebased on develop to take advantage of the new structure. You can wait to do this until we merge the other PR for scripting Amazon classes so all the debasing is done in one step.
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:
Let's change to `!isAnalyticsActive()`
Source:
public void initialise() { infoArea = find("infoArea", UIText.class); updateInfoButton = find("updateInfoButton", UIButton.class); if (updateInfoButton != null) { updateInfoButton.subscribe(button -> { infoArea.setText(infoItems[infoIndex]); if (infoIndex > infoItems.length() - 2) infoIndex = 0; else infoIndex++; }); } }

Target:
We always use brackets, even if the if only has one statement. Same goes for the else clause below.
Source:
public void initialise() { infoArea = find("infoArea", UIText.class); infoArea.setText(LatinQuotes[random.nextInt(LatinQuotes.length-1)]); updateInfoButton = find("updateInfoButton", UIButton.class); if (updateInfoButton != null) { updateInfoButton.subscribe(button -> { infoArea.setText(LatinQuotes[random.nextInt(LatinQuotes.length-1)]); }); } }

Target:
`random.nextInt(n)` picks a random integer between 0 (inclusive) and n (exclusive). You do not need to do a -1 to the list length. Which means `random.nextInt(LatinQuotes.length)` would work just fine.
Source:
protected void releaseLock( @Nonnull final String sessionId ) { try { if ( _log.isDebugEnabled() ) { _log.debug( "Releasing lock for session " + sessionId ); } final long start = System.currentTimeMillis(); _memcached.delete( _sessionIdFormat.createLockName( sessionId ) ); _stats.registerSince( RELEASE_LOCK, start ); } catch ( final IOException e ) { _log.warn( "Caught exception when trying to release lock for session " + sessionId, e ); } }

Target:
I'd catch still Exception here.
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:
This shouldn't block.
Source:
public void refresh() { query = getStringExtra(QUERY); super.refresh(true); }

Target:
We should not force all of the refreshes
Source:
public void setup() { event = GitHubEvent.builder() .repo(new GitHubEvent.RepoIdentifier() { @Nullable @Override public Long id() { return null; } @Nullable @Override public String url() { return null; } @Nullable @Override public String repoWithUserName() { return REPO_NAME; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { } }) .build(); }

Target:
This need to be fixed, I'll get to today. `GitHubEvent.RepoIdentifier` should really have a builder. There will be a new release today.
Source:
private void reorderRepositories() { Collections.sort(cachedRepos, recentRepos); getActivity().runOnUiThread(new Runnable() { @Override public void run() { getListAdapter().getWrappedAdapter().setItems(cachedRepos.toArray()); updateHeaders(cachedRepos); } }); }

Target:
why do you explicitly mark this to run on UI thread? it looks like this method will always be called from the main thread
Source:
public DirContext bind(String principalName, String password, List<SocketInfo> ldapServers) { Hashtable<String, String> props = new Hashtable<String, String>(); props.put(Context.REFERRAL, "follow"); props.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid"); props.put("java.naming.ldap.factory.socket", TrustAllSocketFactory.class.getName()); return bind(principalName, password, ldapServers, props); }

Target:
you are adding these three anyway in the `bind(String principalName, String password, List<SocketInfo> ldapServers, Hashtable<String, String> props)` method.
Source:
public static Map<String,String> toMap(List<EnvironmentProperty> properties) { if (properties != null) { final Map<String, String> result = new LinkedHashMap<String, String>(); for (EnvironmentProperty property:properties) { result.put(property.getName(), property.getValue()); } return result; } return null; }

Target:
better to return an Empty Map, otherwise callers would need to check
Source:
public InvalidApiKeyException(String apiKey, ErrorCode errorCode) { super(apiKey, errorCode); }

Target:
Code style. Private constructor + static factory method
Source:
public Command exec(String command) throws ConnectionException, TransportException { checkReuse(); log.debug("Will request to exec `{}`", command); sendChannelRequest("exec", true, new Buffer.PlainBuffer().putString(command.getBytes(getRemoteCharset()))) .await(conn.getTimeoutMs(), TimeUnit.MILLISECONDS); usedUp = true; return this; }

Target:
The main question I have when reading this, should _every_ string be written using the remote charset? If so, it is nicer to make it a property of the Buffer, rather than converting it everywhere we call `putString`.
Source:
public Session startSession() throws ConnectionException, TransportException { checkConnected(); checkAuthenticated(); final SessionChannel sess = (remoteCharset != null)? new SessionChannel(conn, remoteCharset) : new SessionChannel(conn); sess.open(); return sess; }

Target:
No need to do the if in the case that we default to UTF_8 here already.
Source:
public LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters, ServerSocket serverSocket) { if (forwarders == null) { forwarders = new ArrayList<LocalPortForwarder>(); } LocalPortForwarder forwarder = new LocalPortForwarder(conn, parameters, serverSocket); forwarders.add(forwarder); return forwarder; }

Target:
If the list is initialized this check is unnecessary.
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:
You can immediately return target here, simplifying method code.
Source:
protected Set<SubscriptionEventListener> getInterestedListeners(String event) { final Set<SubscriptionEventListener> listeners; synchronized (lock) { final Set<SubscriptionEventListener> sharedListeners = eventNameToListenerMap.get(event); if (sharedListeners != null) { listeners = new HashSet<SubscriptionEventListener>(sharedListeners); } else { listeners = null; } } return listeners; }

Target:
Because there's nothing else in this method other than the synchronized block, we don't really need the local variable, you can just replace the assignments of `listeners` with `return` statements.
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:
This class shouldn't make a dependency on specific implementation details. That could be handled within the existing `updateState`. Also I'm not sure if it's tread-safe or generally good to allow the caller's thread access and modify the channel object... (it seems that everywhere there's a barrier of the thread executor queue).
Source:
public String toSubscribeMessage() { String msg = super.toSubscribeMessage(); myUserID = extractUserIdFromChannelData((String)channelData); return msg; }

Target:
```suggestion myUserID = extractUserIdFromChannelData(channelData); ``` I don't think the cast is necessary.
Source:
public String toString() { String returnString = ""; if(eventData !=null) { for (String key: eventData.keySet()){ String value = eventData.get(key); returnString = returnString + key + ": " + value + ", "; } } return returnString; }

Target:
```suggestion if (eventData !=null) { ```
Source:
public Object getEventName() { return eventData.get("event"); }

Target:
It's exposed as `channel_name` in auth endpoint handlers for example: https://pusher.com/docs/channels/server_api/authenticating-users#implementing-the-auth-endpoint-for-a-private-channel.
Source:
public void subscribeTo(final InternalChannel channel, final ChannelEventListener listener, final String... eventNames) { synchronized (channelNameToChannelMap){ validateArgumentsAndBindEvents(channel, listener, eventNames); channelNameToChannelMap.put(channel.getName(), channel); sendOrQueueSubscribeMessage(channel); } }

Target:
Do we need these non-map accesses to be inside the critical section? Some of them may also take locks...
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:
I think a short circuit exit at the top would be much clearer than wrapping the entire effective body of the method in an `if`. Also, we should not log at `error` level in expected circumstances.
Source:
public void setUp() { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Runnable r = (Runnable) invocation.getArguments()[0]; new InstantExecutor().execute(r); return null; } }).when(factory).queueOnEventThread(any(Runnable.class)); mockListener = getEventListener(); channel = newInstance(getChannelName()); channel.setEventListener(mockListener); }

Target:
This `InstantExecutor` class is probably redundant now. `((Runnable)invocation.getArguments()[0]).run();` would do the trick. To stick to proper OO patterns, we should really create a `GloballySynchronizedExecutor` which takes the lock object as a constructor arg, then we could still return a dummy type here. Not going to insist on it though.
Source:
public void bind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); synchronized (lock) { if (listeners == null) { listeners = new HashSet<SubscriptionEventListener>(); eventNameToListenerMap.put(eventName, listeners); } listeners.add(listener); } }

Target:
The synchronized block needs to include this read from the map: - Thread 1 reads `eventNameToListenerMap`, gets `null` - Thread 2 reads `eventNameToListenerMap`, gets `null` - Thread 1 enters critical section, creates new HashSet containing listener 1 and stores in `eventNameToListenerMap` - Thread 2 enters critical section, creates new HashSet containing listener 2 and stores in `eventNameToListenerMap` Listener 1 has been lost.
Source:
public PrivateChannel subscribePrivate(final String channelName, final PrivateChannelEventListener listener, final String... eventNames) { throwExceptionIfNoAuthorizerHasBeenSet(); final PrivateChannelImpl channel = factory.newPrivateChannel(connection, channelName, pusherOptions.getAuthorizer()); channelManager.subscribeTo(channel, listener, eventNames); privateChannels.add(channel); return channel; }

Target:
when are channels removed from the list ? It might leak memory otherwise.
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:
why not just let it throw so it counts as a failure/error ?
Source:
private MirrorOptions createMirrorOptions() { MirrorOptions options = new MirrorOptions(); options.setFollowOnlyFilteredRequirements(followOnlyFilteredRequirements); options.setFollowStrictOnly(followStrictOnly); options.setIncludeFeatures(includeFeature); options.setIncludeNonGreedy(includeNonGreedy); options.setIncludeOptional(includeOptional); options.setLatestVersionOnly(latestVersionOnly); return options; }

Target:
should these all be this.variable instead of just variable?
Source:
public void onChapterSelected(Chapter selectedChapter) { updateSelectionFor(selectedChapter.getGplusId()); }

Target:
here, you convert a chapter into an id and then back into a chapter. Should be made more performant.
Source:
private static GoogleApiClient createClient(Context context, boolean withSignIn) { GoogleApiClient.Builder builder = new GoogleApiClient.Builder(context) .addApi(AppIndex.API); if (withSignIn) { builder.addApi(Plus.API).addScope(Plus.SCOPE_PLUS_PROFILE) .addApi(Drive.API).addScope(Drive.SCOPE_APPFOLDER); } return builder.build(); }

Target:
We are using this to save game state. I think we can remove it as well. If we want to store something we can use Firebase.
Source:
public void onResume() { super.onResume(); RecyclerView recyclerView = getListView(); for (int i = 0; i <= recyclerView.getChildCount(); i++) { View child = recyclerView.getChildAt(i); if (child != null) { mAdapter.updatePlusOne((NewsAdapter.ViewHolder) recyclerView.getChildViewHolder(child)); } } }

Target:
Should we cache the size inside the for loop? `for (int i = 0, size = recyclerView.getChildCount(); i <= size; i++)`
Source:
private void recordStartPageView() { App.getInstance().getGdgXHub().getEventDetail( mEventId, new Callback<EventFullDetails>() { @Override public void success(EventFullDetails eventFullDetails, retrofit.client.Response response) { mEventFullDetails = eventFullDetails; Action viewAction = createAppIndexAction(eventFullDetails.getTitle(), mEventId); recordStartPageView(viewAction); } @Override public void failure(RetrofitError error) { } } ); }

Target:
I just realized that we are doing this network call in EventDetailFragment too. So for every event detail page, we are doing the same network request twice.
Source:
public ChapterFragmentPagerAdapter(Context ctx, FragmentManager fm, @NonNull Chapter selectedChapter) { super(fm); mContext = ctx; this.mSelectedChapter = selectedChapter; }

Target:
When you use the `m` prefix in a field name, you don't use the `this.`
Source:
ConfiguredRolesAllowedPastLoginFilter(String[] rolesAllowed) { this.denyAll = false; this.rolesAllowed = (rolesAllowed != null) ? rolesAllowed : new String[] {}; }

Target:
if rolesAllowed is null, doesn't that make denyAll effectively true?
Source:
String getNewZipDestination(){ return getNewZipDestination(getProperties().getProperty(UNZIP_BASE_PROPERTY_NAME)); }

Target:
Did you consider returning a `File` rather than a `String` here? It looks like you are only using the result in the context of a file, so it might be cleaner to make the `File` at this point.
Source:
public void testDeleteCommentAsAdmin() { assertTrue(this.commentsTab.isCommentFormShown()); this.commentsTab.postComment(COMMENT_CONTENT, true); this.commentsTab.deleteCommentByID(this.commentsTab.getCommentID(COMMENT_CONTENT)); assertEquals(this.commentsTab.getCommentID(COMMENT_CONTENT), -1); }

Target:
sounds like the expected and obtained values are swapped
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:
I don't really understand why your are doing this.
Source:
public ViewPage createPageWithAttachment(EntityReference reference, String content, String title, String attachmentName, InputStream attachmentData) throws Exception { ViewPage vp = createPage(reference, content, title); attachFile(reference, attachmentName, attachmentData, false); return vp; }

Target:
You could call the other signature here, with ``null`` credentials.
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:
oops yes, "without" sorry :)
Source:
public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { buffer.append(getComputedValue(name, prefix, object, context)); }

Target:
Either call ``getComputedValue(buffer, ...)`` here or remove the second signature of ``getComputedValue`` since I don't see it used anywhere.
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:
I would keep this new method private as internal helper since that's not the one you are using from what I understand. Otherwise it's not clear why we need to introduce displayDocument since you could use this one.
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:
I don't like static too much (causes all sort of issues, including for testing when it sets some states).
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:
I'm not sure you could do this cast. I think we usually write: ```suggestion DocumentReference documentReference = new DocumentReference(destination); ```
Source:
public Class< ? > getType() { if (this.parameterType == null) { return String.class; } else { return ReflectionUtils.getTypeClass(this.parameterType); } }

Target:
I would change a bit the logic and always call ReflectionUtils.getTypeClass but check the return for null and return String in that case.
Source:
public TreeElement getTreeElement() { WebElement element = getDriver() .findElement(By.className(CONTAINER_TREE_CLASS)) .findElement(By.className(TREE_CLASS)); getDriver().waitUntilElementIsVisible(By.className(TREE_CLASS)); return new TreeElement(element); }

Target:
I would have put this line above the previous instruction to make sure `#xtree` can be found. WDYT?
Source:
public void use(String iconSetName) { try { IconSet iconSet = iconSetManager.getIconSet(iconSetName); if (iconSet == null) { iconSet = iconSetManager.getDefaultIconSet(); } iconRenderer.use(iconSet); } catch (IconException e) { setLastError(e); } }

Target:
I don't think we should do a fallback here.
Source:
public DocumentMovedEvent(DocumentReference documentReference) { this(documentReference, null); }

Target:
It's really not clear if this is the source or the target.
Source:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { attachment.setDoc(this); return this.attachmentList.set(attachment); }

Target:
Actually you do have this feature in XWikiAttachmentList#set arleady but you do it after adding the attachment instead of before :)
Source:
public boolean add(XWikiAttachment attachment) { map.put(attachment.getFilename(), attachment); this.list = new ArrayList<XWikiAttachment>(map.values()); onUpdate(); added(attachment); return true; }

Target:
Most of the method is a duplicate of #set() so you should reuse it instead.
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:
You should compare with x, not null since there could already be a different attachment in the map.
Source:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return !set.equals(attachment); }

Target:
Don't use equals for attachment instances.
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:
Don't use equals for attachment instances.
Source:
private void updatedMap() { document.setMetaDataDirty(true); this.setCollection(map.values()); }

Target:
This is not right. You need to pass a new new ArrayList to setCollection() since values() is not a List and any call to decorated() will crash.
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:
Too quick, I doubt this builds :) Also a better way to do that in term of performance is to use an Iterator in the for and call Iterator#remove() instead of making it search the entry in the Map again.
Source:
public void listClear() throws XWikiException{ attachmentList.clear(); assertEquals(attachmentList,new ArrayList<XWikiAttachment>()); }

Target:
I would assertTrue attachmentList.isEmpty() instead since that's what you want to know (not that it's equals to some list).
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:
Actually I mixed with the other pull request, there was indeed a catch before so you should put it back, sorry.
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:
Was not part of the `if (getEngineContext() != null) {` before.
Source:
public BodyPart addPart(BodyPart bodyPart) { return addPart(null, bodyPart); }

Target:
missing a `@since` and an `@Unstable` annotations.
Source:
public DocumentMovedEvent(DocumentReference documentReference) { String move; super(documentReference); this.move = move; }

Target:
This does not build.
Source:
public CompositeEvent(CompositeEvent compositeEvent) { this.events = compositeEvent.events; this.similarityBetweenEvents = compositeEvent.similarityBetweenEvents; }

Target:
It means you will the same list. So if you change `this.events`, it will impact `compositeEvent.events` too.
Source:
public boolean matches(Object o) { return (this.getClass().isInstance(o) && ((AbstractEventStreamEvent) o).getEvent().equals(this.event)); }

Target:
It means you cannot create a listener actually, because the listener will never match: ``` ((AbstractEventStreamEvent) o).getEvent().equals(this.event)) ``` You see what I mean?
Source:
private boolean isAllGroupImplicit(XWikiContext context) { return context.getWiki().isAllGroupImplicit(); }

Target:
You should not change the visibility. Since XWikiGroupServiceImpl is a public class what you do here is the same as removing a method from an API. If you build with -Pquality you should get an error.