auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private E makeRecord() { START if (recordClass != null && recordClass != GenericData.Record.class) { END E record = makeReflectRecord(); if (record != null) { return record; } } return makeGenericRecord(); } Rather than allowing this to be null if null is passed in, we should add a Precondition check

Target:
private E makeRecord() { if (recordClass != GenericData.Record.class) { E record = makeReflectRecord(); if (record != null) { return record; } } return makeGenericRecord(); }
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( START UUID.randomUUID().toString()); END // set the temporary repository conf.set(KITE_TEMP_REPO_URI, tempRepo.getUri().toString()); } return this; } Use getJobDatasetName instead of UUID since it's already unique, and makes it easy to debug.

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); START if (!defaultValue.equals(value)) { END return value; } } // return null to default the value when parsed return null; } Possible NPE here unless I am mistaken -- there may be no defaultValue.

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:
public static <E> ReadableSource<E> asSource(URI uri, Class<E> type) { START View<E> view = Datasets.<E, View<E>>view(uri); END return new DatasetSourceTarget<E>(view, type); } 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.

Target:
public static <E> ReadableSource<E> asSource(URI uri, Class<E> type) { return new DatasetSourceTarget<E>(uri, type); }
Source:
public Table getTable(String dbName, String tableName) { Table table; try { synchronized(client) { table = HCatUtil.getTable(client, dbName, tableName); } } catch (RuntimeException e) { START throw new RuntimeException("Hive metastore exception", e); END } 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; } 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.

Target:
public Table getTable(String dbName, String tableName) { Table table; try { synchronized(client) { table = HCatUtil.getTable(client, dbName, tableName); } } catch (RuntimeException e) { throw 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; }
Source:
public ElasticTimeOutStrategy(String timeoutPercentage, String timeoutMinutesElasticDefault, String numberOfBuilds) { this.timeoutPercentage = timeoutPercentage; this.timeoutMinutesElasticDefault = timeoutMinutesElasticDefault; START this.numberOfBuilds = numberOfBuilds; END } Please call the new constructor passing the dafault value to `failSafeTimeoutDuration`. That makes what you want to do clear.

Target:
public ElasticTimeOutStrategy(String timeoutPercentage, String timeoutMinutesElasticDefault, String numberOfBuilds) { this(timeoutPercentage, timeoutMinutesElasticDefault, numberOfBuilds, false); }
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(); } } START finally { END synchronized(disposed) { disposed = true; } } } ABSOLUTE SHOW STOPPER.

Target:
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 { disposed = true; } }
Source:
protected boolean isAnyAppConfiguredInSourceServerXml() { boolean bConfigured = false; Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); START bConfigured = true; END } return bConfigured; } Here I would just say `return true`. Then fall through `return false`, instead of creating a variable.

Target:
protected boolean isAnyAppConfiguredInSourceServerXml() { Set<String> locations = getAppConfigLocationsFromSourceServerXml(); if (locations.size() > 0) { log.debug("Application configuration is found in server.xml."); return true; } else { return false; } }
Source:
START private boolean isSupportedType(String type) throws Exception { END 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; } 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.

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. START assertFalse(line.equals(Constants.CONFIGURE_ARQUILLIAN_COMMENT)); END } } Wouldn't the contains method be more reliable here, in case some spacing was different at the beginning or end of the line?

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"); } START END if (configDropins == null || !configDropins.exists()) { configDropins = new File(getServerXML().getParent(), "configDropins"); } return configDropins; } 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`.

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)); START doc.getDocumentElement().appendChild(child); END } this could replace 147-149 with createElement(doc.getDocumentElement, key, value);

Target:
public void createElement(String key, String value) { 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; START mSettings = Application.getPrefs(); END } 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().

Target:
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; }
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; START int padding = (int) (width * 0.12); // offset from edges of the map 12% of screen END mMap.animateCamera((CameraUpdateFactory.newLatLngBounds(b, width, height, padding))); } } Any reason in particular that exactly 12% is used here?

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); START String focusedStopId = mController.getFocusedStopId(); END if (focusedStopId != null) { TripDetailsActivity.start(mActivity, status.getActiveTripId(), focusedStopId); } else { TripDetailsActivity.start(mActivity, status.getActiveTripId()); } } You should check if `mController` is null before calling `mController.getFocusedStopId()`, to prevent potential NPEs.

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); START onFocusChanged(null,null,l); END } } 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.

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) { START if (isAnalyticsActive() == false) { END //Disable Google Analytics GoogleAnalytics.getInstance(context).setAppOptOut(true); } if (BuildConfig.DEBUG) { //Disables reporting when app runs on debug GoogleAnalytics.getInstance(context).setDryRun(true); } } Let's change to `!isAnalyticsActive()`

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 initialise() { infoArea = find("infoArea", UIText.class); updateInfoButton = find("updateInfoButton", UIButton.class); if (updateInfoButton != null) { updateInfoButton.subscribe(button -> { infoArea.setText(infoItems[infoIndex]); START if (infoIndex > infoItems.length() - 2) END infoIndex = 0; else infoIndex++; }); } } We always use brackets, even if the if only has one statement. Same goes for the else clause below.

Target:
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++; } }); } }
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 -> { START infoArea.setText(LatinQuotes[random.nextInt(LatinQuotes.length-1)]); END }); } } `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.

Target:
public void initialise() { infoArea = find("infoArea", UIText.class); updateInfoButton = find("updateInfoButton", UIButton.class); if (updateInfoButton != null) { updateInfoButton.subscribe(button -> { infoArea.setText(LatinQuotes[random.nextInt(LatinQuotes.length)]); }); } }
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 ); START } catch ( final IOException e ) { END _log.warn( "Caught exception when trying to release lock for session " + sessionId, e ); } } I'd catch still Exception here.

Target:
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 ) ).get(); _stats.registerSince( RELEASE_LOCK, start ); } catch ( final Exception e ) { _log.warn( "Caught exception when trying to release lock for session " + sessionId, e ); } }
Source:
START public void saveValidityBackup() throws IOException { END 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 ); } This shouldn't block.

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:
public void refresh() { query = getStringExtra(QUERY); START super.refresh(true); END } We should not force all of the refreshes

Target:
public void refresh() { query = getStringExtra(QUERY); super.refresh(); }
Source:
public void setup() { event = GitHubEvent.builder() START .repo(new GitHubEvent.RepoIdentifier() { END @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(); } This need to be fixed, I'll get to today. `GitHubEvent.RepoIdentifier` should really have a builder. There will be a new release today.

Target:
public void setup() { repo = GitHubEvent.RepoIdentifier.builder() .repoWithUserName(REPO_NAME) .build(); event = GitHubEvent.builder() .repo(repo) .build(); }
Source:
private void reorderRepositories() { Collections.sort(cachedRepos, recentRepos); START getActivity().runOnUiThread(new Runnable() { END @Override public void run() { getListAdapter().getWrappedAdapter().setItems(cachedRepos.toArray()); updateHeaders(cachedRepos); } }); } why do you explicitly mark this to run on UI thread? it looks like this method will always be called from the main thread

Target:
private void reorderRepositories() { Collections.sort(cachedRepos, recentRepos); getListAdapter().getWrappedAdapter().setItems(cachedRepos.toArray()); updateHeaders(cachedRepos); }
Source:
public DirContext bind(String principalName, String password, List<SocketInfo> ldapServers) { Hashtable<String, String> props = new Hashtable<String, String>(); props.put(Context.REFERRAL, "follow"); START props.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid"); END props.put("java.naming.ldap.factory.socket", TrustAllSocketFactory.class.getName()); return bind(principalName, password, ldapServers, props); } you are adding these three anyway in the `bind(String principalName, String password, List<SocketInfo> ldapServers, Hashtable<String, String> props)` method.

Target:
public DirContext bind(String principalName, String password, List<SocketInfo> ldapServers) { return bind(principalName, password, ldapServers, new Hashtable<String, String>()); }
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; } START return null; END } better to return an Empty Map, otherwise callers would need to check

Target:
public static Map<String,String> toMap(List<EnvironmentProperty> properties) { final Map<String, String> result = new LinkedHashMap<String, String>(); if (properties != null) { for (EnvironmentProperty property:properties) { result.put(property.getName(), property.getValue()); } return result; } return result; }
Source:
START public InvalidApiKeyException(String apiKey, ErrorCode errorCode) { END super(apiKey, errorCode); } Code style. Private constructor + static factory method

Target:
private InvalidApiKeyException(String apiKey, ErrorCode errorCode) { super(apiKey, errorCode); }
Source:
public Command exec(String command) throws ConnectionException, TransportException { checkReuse(); log.debug("Will request to exec `{}`", command); START sendChannelRequest("exec", true, new Buffer.PlainBuffer().putString(command.getBytes(getRemoteCharset()))) END .await(conn.getTimeoutMs(), TimeUnit.MILLISECONDS); usedUp = true; return this; } 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`.

Target:
public Command exec(String command) throws ConnectionException, TransportException { checkReuse(); log.debug("Will request to exec `{}`", command); sendChannelRequest("exec", true, new Buffer.PlainBuffer().putString(command, getRemoteCharset())) .await(conn.getTimeoutMs(), TimeUnit.MILLISECONDS); usedUp = true; return this; }
Source:
public Session startSession() throws ConnectionException, TransportException { checkConnected(); checkAuthenticated(); START final SessionChannel sess = (remoteCharset != null)? new SessionChannel(conn, remoteCharset) : new SessionChannel(conn); END sess.open(); return sess; } No need to do the if in the case that we default to UTF_8 here already.

Target:
public Session startSession() throws ConnectionException, TransportException { checkConnected(); checkAuthenticated(); final SessionChannel sess = new SessionChannel(conn, remoteCharset); sess.open(); return sess; }
Source:
public LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters, ServerSocket serverSocket) { START if (forwarders == null) { END forwarders = new ArrayList<LocalPortForwarder>(); } LocalPortForwarder forwarder = new LocalPortForwarder(conn, parameters, serverSocket); forwarders.add(forwarder); return forwarder; } If the list is initialized this check is unnecessary.

Target:
public LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters, ServerSocket serverSocket) { LocalPortForwarder forwarder = new LocalPortForwarder(conn, parameters, serverSocket); forwarders.add(forwarder); return forwarder; }
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; START break; END } } if (target == null) { throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); } return target; } You can immediately return target here, simplifying method code.

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:
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; } } START return listeners; END } 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.

Target:
protected Set<SubscriptionEventListener> getInterestedListeners(String event) { synchronized (lock) { final Set<SubscriptionEventListener> sharedListeners = eventNameToListenerMap.get(event); if (sharedListeners == null) { return null; } return new HashSet<>(sharedListeners); } }
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) { START ((PrivateEncryptedChannelImpl) channel).tearDownChannel(); END } sendUnsubscribeMessage(channel); } } 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).

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(); START myUserID = extractUserIdFromChannelData((String)channelData); END return msg; } ```suggestion myUserID = extractUserIdFromChannelData(channelData); ``` I don't think the cast is necessary.

Target:
public String toSubscribeMessage() { String msg = super.toSubscribeMessage(); myUserID = extractUserIdFromChannelData(channelData); return msg; }
Source:
public String toString() { String returnString = ""; START if(eventData !=null) { END for (String key: eventData.keySet()){ String value = eventData.get(key); returnString = returnString + key + ": " + value + ", "; } } return returnString; } ```suggestion if (eventData !=null) { ```

Target:
public String toString() { return eventData.toString(); }
Source:
START public Object getEventName() { return eventData.get("event"); } END 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.

Target:
public String getEventName() { return (String)eventData.get("event"); }
Source:
public void subscribeTo(final InternalChannel channel, final ChannelEventListener listener, final String... eventNames) { synchronized (channelNameToChannelMap){ START validateArgumentsAndBindEvents(channel, listener, eventNames); END channelNameToChannelMap.put(channel.getName(), channel); sendOrQueueSubscribeMessage(channel); } } Do we need these non-map accesses to be inside the critical section? Some of them may also take locks...

Target:
public void subscribeTo(final InternalChannel channel, final ChannelEventListener listener, final String... eventNames) { validateArgumentsAndBindEvents(channel, listener, eventNames); channelNameToChannelMap.put(channel.getName(), channel); sendOrQueueSubscribeMessage(channel); }
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 + "]"); START } END } 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.

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 setUp() { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Runnable r = (Runnable) invocation.getArguments()[0]; START new InstantExecutor().execute(r); END return null; } }).when(factory).queueOnEventThread(any(Runnable.class)); mockListener = getEventListener(); channel = newInstance(getChannelName()); channel.setEventListener(mockListener); } 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.

Target:
public void setUp() { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Runnable r = (Runnable) invocation.getArguments()[0]; r.run(); return null; } }).when(factory).queueOnEventThread(any(Runnable.class)); mockListener = getEventListener(); channel = newInstance(getChannelName()); channel.setEventListener(mockListener); }
Source:
public void bind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); START Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); END synchronized (lock) { if (listeners == null) { listeners = new HashSet<SubscriptionEventListener>(); eventNameToListenerMap.put(eventName, listeners); } listeners.add(listener); } } 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.

Target:
public void bind(final String eventName, final SubscriptionEventListener listener) { validateArguments(eventName, listener); synchronized (lock) { Set<SubscriptionEventListener> listeners = eventNameToListenerMap.get(eventName); if (listeners == null) { listeners = new HashSet<SubscriptionEventListener>(); eventNameToListenerMap.put(eventName, listeners); } listeners.add(listener); } }
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); START privateChannels.add(channel); END return channel; } when are channels removed from the list ? It might leak memory otherwise.

Target:
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); return channel; }
Source:
public void testCommitId() { try { properties.load(getClass().getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { // TODO Auto-generated catch block START e.printStackTrace(); END } assertNotNull(properties.get("git.commit.id").toString()); assertEquals("b34a518cdcad80a7d750b714ce2fec18f029b489".length(),properties.get("git.commit.id").toString().length()); } why not just let it throw so it counts as a failure/error ?

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:
private MirrorOptions createMirrorOptions() { MirrorOptions options = new MirrorOptions(); START options.setFollowOnlyFilteredRequirements(followOnlyFilteredRequirements); END options.setFollowStrictOnly(followStrictOnly); options.setIncludeFeatures(includeFeature); options.setIncludeNonGreedy(includeNonGreedy); options.setIncludeOptional(includeOptional); options.setLatestVersionOnly(latestVersionOnly); return options; } should these all be this.variable instead of just variable?

Target:
private MirrorOptions createMirrorOptions() { MirrorOptions options = new MirrorOptions(); options.setFollowOnlyFilteredRequirements(this.followOnlyFilteredRequirements); options.setFollowStrictOnly(this.followStrictOnly); options.setIncludeFeatures(this.includeFeature); options.setIncludeNonGreedy(this.includeNonGreedy); options.setIncludeOptional(this.includeOptional); options.setLatestVersionOnly(this.latestVersionOnly); return options; }
Source:
public void onChapterSelected(Chapter selectedChapter) { START updateSelectionFor(selectedChapter.getGplusId()); END } here, you convert a chapter into an id and then back into a chapter. Should be made more performant.

Target:
public void onChapterSelected(Chapter selectedChapter) { updateSelectionFor(selectedChapter); }
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) START .addApi(Drive.API).addScope(Drive.SCOPE_APPFOLDER); END } return builder.build(); } 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.

Target:
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); } return builder.build(); }
Source:
public void onResume() { super.onResume(); RecyclerView recyclerView = getListView(); START for (int i = 0; i <= recyclerView.getChildCount(); i++) { END View child = recyclerView.getChildAt(i); if (child != null) { mAdapter.updatePlusOne((NewsAdapter.ViewHolder) recyclerView.getChildViewHolder(child)); } } } Should we cache the size inside the for loop? `for (int i = 0, size = recyclerView.getChildCount(); i <= size; i++)`

Target:
public void onResume() { super.onResume(); RecyclerView recyclerView = getListView(); for (int i = 0, size = recyclerView.getChildCount(); i <= size; i++) { View child = recyclerView.getChildAt(i); if (child != null) { mAdapter.updatePlusOne((NewsAdapter.ViewHolder) recyclerView.getChildViewHolder(child)); } } }
Source:
private void recordStartPageView() { START App.getInstance().getGdgXHub().getEventDetail( END 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) { } } ); } 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.

Target:
private void recordStartPageView() { if (mEventFullDetails != null) { Action viewAction = createAppIndexAction(mEventFullDetails.getTitle(), mEventId); recordStartPageView(viewAction); } }
Source:
public ChapterFragmentPagerAdapter(Context ctx, FragmentManager fm, @NonNull Chapter selectedChapter) { super(fm); mContext = ctx; START this.mSelectedChapter = selectedChapter; END } When you use the `m` prefix in a field name, you don't use the `this.`

Target:
public ChapterFragmentPagerAdapter(Context ctx, FragmentManager fm, @NonNull Chapter selectedChapter) { super(fm); mContext = ctx; mSelectedChapter = selectedChapter; }
Source:
ConfiguredRolesAllowedPastLoginFilter(String[] rolesAllowed) { this.denyAll = false; START this.rolesAllowed = (rolesAllowed != null) ? rolesAllowed : new String[] {}; END } if rolesAllowed is null, doesn't that make denyAll effectively true?

Target:
ConfiguredRolesAllowedPastLoginFilter(String[] rolesAllowed) { this.rolesAllowed = (rolesAllowed != null) ? rolesAllowed : null; }
Source:
START String getNewZipDestination(){ END return getNewZipDestination(getProperties().getProperty(UNZIP_BASE_PROPERTY_NAME)); } 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.

Target:
File getNewZipDestination(){ return getNewZipDestination(getProperties().getProperty(UNZIP_BASE_PROPERTY_NAME)); }
Source:
public void testDeleteCommentAsAdmin() { assertTrue(this.commentsTab.isCommentFormShown()); this.commentsTab.postComment(COMMENT_CONTENT, true); this.commentsTab.deleteCommentByID(this.commentsTab.getCommentID(COMMENT_CONTENT)); START assertEquals(this.commentsTab.getCommentID(COMMENT_CONTENT), -1); END } sounds like the expected and obtained values are swapped

Target:
public void testDeleteCommentAsAdmin() { assertTrue(this.commentsTab.isCommentFormShown()); this.commentsTab.postComment(COMMENT_CONTENT, true); this.commentsTab.deleteCommentByID(this.commentsTab.getCommentID(COMMENT_CONTENT)); assertEquals(-1, this.commentsTab.getCommentID(COMMENT_CONTENT)); }
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) { START doc.setDocumentArchive(new XWikiDocumentArchive()); END } } this.getVersioningStore(context).resetRCSArchive(this, true, context); } } I don't really understand why your are doing this.

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 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); START return vp; END } You could call the other signature here, with ``null`` credentials.

Target:
public ViewPage createPageWithAttachment(EntityReference reference, String content, String title, String attachmentName, InputStream attachmentData) throws Exception { return createPageWithAttachment(reference, content, title, attachmentName, attachmentData, null); }
Source:
START public void setUp(TestUtils setup, TestReference testReference) throws Exception END { 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"); } oops yes, "without" sorry :)

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) { START buffer.append(getComputedValue(name, prefix, object, context)); END } Either call ``getComputedValue(buffer, ...)`` here or remove the second signature of ``getComputedValue`` since I don't see it used anywhere.

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:
START public String getRenderedContent(Syntax targetSyntax, boolean transformationContextIsolated, XWikiContext context, END 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); } } 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.

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:
START protected static void mountFromHostToContainer(GenericContainer container, String sourceDirectory, END 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); } } I don't like static too much (causes all sort of issues, including for testing when it sets some states).

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)) { START DocumentReference documentReference = (DocumentReference) destination; END dest = documentReference.getLastSpaceReference(); } else { dest = destination; } request.setDestination(dest); return request; } I'm not sure you could do this cast. I think we usually write: ```suggestion DocumentReference documentReference = new DocumentReference(destination); ```

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() { START if (this.parameterType == null) { END return String.class; } else { return ReflectionUtils.getTypeClass(this.parameterType); } } I would change a bit the logic and always call ReflectionUtils.getTypeClass but check the return for null and return String in that case.

Target:
public Class<?> getType() { Class<?> type = ReflectionUtils.getTypeClass(this.parameterType); if (type == null) { type = String.class; } return type; }
Source:
public TreeElement getTreeElement() { WebElement element = getDriver() .findElement(By.className(CONTAINER_TREE_CLASS)) .findElement(By.className(TREE_CLASS)); START getDriver().waitUntilElementIsVisible(By.className(TREE_CLASS)); END return new TreeElement(element); } I would have put this line above the previous instruction to make sure `#xtree` can be found. WDYT?

Target:
public TreeElement getTreeElement() { getDriver().waitUntilElementIsVisible(By.className(TREE_CLASS)); WebElement element = getDriver() .findElement(By.className(CONTAINER_TREE_CLASS)) .findElement(By.className(TREE_CLASS)); return new TreeElement(element); }