auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkEmptyFormGroupDisplay(){ Assert.assertEquals(testGroup.display(DisplayMode.Edit, new String[] { "phenotype", "negative_phenotype" }), ""); START Assert.assertEquals(testGroup.display(DisplayMode.View, new String[] { "phenotype", "negative_phenotype" }), ""); END } Format for assertions is `Assert.assertSomthing(EXPECTED, ACTUAL)`. Change the order here

Target:
public void checkEmptyFormGroupDisplay(){ Assert.assertEquals("", testGroup.display(DisplayMode.Edit, new String[] { "phenotype", "negative_phenotype" })); Assert.assertEquals("", testGroup.display(DisplayMode.View, new String[] { "phenotype", "negative_phenotype" })); }
Source:
public void returnsNormallyWhenGivenNoMeasurementObjects() throws Exception { when(this.source.getXObjects(any(EntityReference.class))).thenReturn(null); NullPointerException exceptionWhenListIsNull = null; try { this.mocker.getComponentUnderTest().onEvent(event, source, data); } catch(NullPointerException e){ START exceptionWhenListIsNull = e; END } Assert.assertNull(exceptionWhenListIsNull); } You don't need to do this. If there is an exception thrown, the test will automatically fail. If, however, you do want to test that calling a method will throw an exception, then you would annotate the method with: ``` @Test(expected=NullPointerException.class) ```

Target:
public void returnsNormallyWhenGivenNoMeasurementObjects() throws Exception { when(this.source.getXObjects(any(EntityReference.class))).thenReturn(null); this.mocker.getComponentUnderTest().onEvent(event, source, data); }
Source:
START public String getId() END { return this.id; } Is this change still needed?

Target:
String getId() { return this.id; }
Source:
START private Boolean addTermAndAncestors(Term t, Observations o) END { try { int id = this.boqa.getTermIndex(t); o.observations[id] = true; this.boqa.activateAncestors(id, o.observations); } catch (Exception e) { this.logger.warn("Unable to find the boqa index of [{}].", t); return false; } return true; } There's a difference between the primitive type `boolean` and the class `Boolean`, and you seem to be using a primitive in the rest of the code. Use `boolean` as the return type.

Target:
private boolean addTermAndAncestors(Term t, Observations o) { try { int id = this.boqa.getTermIndex(t); o.observations[id] = true; this.boqa.activateAncestors(id, o.observations); } catch (Exception e) { this.logger.warn("Unable to find the boqa index of [{}].", t); return false; } return true; }
Source:
START public String getExternalId() END { try { for (ImmutablePair<String, String> identifier : this .<ImmutablePair<String, String>>getData("identifiers")) { if (identifier.getKey().equalsIgnoreCase("external_id")) { return identifier.getValue(); } } } catch (Exception ex) { return null; } return null; } Actually this is a mock patient, you should just `return null` here.

Target:
public String getExternalId() { return null; }
Source:
private VCFColumn getColumn(String token) { START String lkToken = token.toLowerCase(); END VCFColumn matchedColumn = null; for (VCFColumn column : VCFColumn.values()) { if (column.getName().equals(lkToken)) { matchedColumn = column; } } return matchedColumn; } You should read http://blog.thetaphi.de/2012/07/default-locales-default-charsets-and.html

Target:
private VCFColumn getColumn(String token) { VCFColumn matchedColumn = null; for (VCFColumn column : VCFColumn.values()) { if (column.name().equalsIgnoreCase(token)) { matchedColumn = column; } } return matchedColumn; }
Source:
public List<String> getAllExtensions() { final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); START Optional.ofNullable(otherExtensions).map(Arrays::asList).ifPresent(extensions::addAll); END return Collections.unmodifiableList(extensions); } I would prefer to assume, and fix if necessary, that `otherExtensions` cannot be `null` (it can be empty anyway), and this way code would look easier: ``` final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); extensions.addAll(Arrays.asList(otherExtensions)); return Collections.unmodifiableList(extensions); ``` Also IMO using `Optional.ofNullable` for null-checking of an instance becomes unnecessary and produce a bit of overhead, I prefer just using a conditional sentence instead... `if (null != whatever) {}`

Target:
public List<String> getAllExtensions() { final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); extensions.addAll(Arrays.asList(otherExtensions)); return Collections.unmodifiableList(extensions); }
Source:
public SpiTransaction createQueryTransaction(Object tenantId) { SpiTransaction t = transactionManager.createQueryTransaction(tenantId); try { START transactionScopeManager.set(t); END } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } return t; } This breaks MySql in theory ... DefaultBeanLoader line 224

Target:
public SpiTransaction createQueryTransaction(Object tenantId) { SpiTransaction t = transactionManager.createQueryTransaction(tenantId); // try { // transactionScopeManager.set(t); // } catch (PersistenceException existingTransactionError) { // t.end(); // throw existingTransactionError; // } return t; }
Source:
public BeanCollection<E> getShallowCopy() { BeanList<E> copy = new BeanList<>(new CopyOnFirstWriteList<>(list)); START copy.setFromOriginal(copy); END return copy; } copy.setFromOriginal(this); -- should use this here ?

Target:
public BeanCollection<E> getShallowCopy() { BeanList<E> copy = new BeanList<>(new CopyOnFirstWriteList<>(list)); copy.setFromOriginal(this); return copy; }
Source:
private boolean containsInstance(Object bean) { for (Object element : list) { START if (JHelper.objectSameReference(element, bean)) { END return true; } } return false; } Use == here. Method name makes usage clear

Target:
private boolean containsInstance(Object bean) { for (Object element : list) { if (element == bean) { return true; } } return false; }
Source:
Class<?> forName(String name) throws ClassNotFoundException { if (preferredLoader != null) { // only use the explicitly set classLoader return classForName(name, preferredLoader); } try { // try the context loader first return classForName(name, contextLoader); } catch (ClassNotFoundException e) { START if (JHelper.objectSameReference(callerLoader, contextLoader)) { END throw e; } else { // fallback to the caller classLoader return classForName(name, callerLoader); } } } It does not matter if you use == or .equals here

Target:
Class<?> forName(String name) throws ClassNotFoundException { if (preferredLoader != null) { // only use the explicitly set classLoader return classForName(name, preferredLoader); } try { // try the context loader first return classForName(name, contextLoader); } catch (ClassNotFoundException e) { if (callerLoader == contextLoader) { throw e; } else { // fallback to the caller classLoader return classForName(name, callerLoader); } } }
Source:
private DbPlatformType getJsonType(DbType type, boolean withScale) { DbPlatformType dbType = get(type); START if (JHelper.objectSameReference(dbType, JSON_CLOB_PLACEHOLDER)) { END // if we have scale that implies this maps to varchar return withScale ? get(DbType.VARCHAR) : get(DbType.CLOB); } if (JHelper.objectSameReference(dbType, JSON_BLOB_PLACEHOLDER)) { return get(DbType.BLOB); } if (JHelper.objectSameReference(dbType, JSON_VARCHAR_PLACEHOLDER)) { return get(DbType.VARCHAR); } // Postgres has specific type return get(type); } DbType is an enum, so == can be used

Target:
private DbPlatformType getJsonType(DbType type, boolean withScale) { DbPlatformType dbType = get(type); if (dbType == JSON_CLOB_PLACEHOLDER) { // if we have scale that implies this maps to varchar return withScale ? get(DbType.VARCHAR) : get(DbType.CLOB); } if (dbType == JSON_BLOB_PLACEHOLDER) { return get(DbType.BLOB); } if (dbType == JSON_VARCHAR_PLACEHOLDER) { return get(DbType.VARCHAR); } // Postgres has specific type return get(type); }
Source:
public Matrix4 rotate(double x, double y, double z, double angle) { if (angle == 0) return this; START return rotate(mQuat.fromAngleAxis(x, y, z, angle)); END } return angle == 0 ? this : rotate(mQuat.fromAngleAxis(x,y,z,angle));

Target:
public Matrix4 rotate(double x, double y, double z, double angle) { return angle == 0 ? this :rotate(mQuat.fromAngleAxis(x, y, z, angle)); }
Source:
private AuthService authService() { START if (null == authService) { END throw new IllegalStateException("The auth-server endpoint is not configured."); } return authService; } I'm no big fan of [Yoda conditions](https://en.wikipedia.org/wiki/Yoda_conditions) I think it reduces readability significantly and also we don't have it anywhere else in the code base. I would suggest that either the condition is reversed: ``` if (authservice == null) { ``` Or we actually do use an `Optional` to store the authservice here and use something like this to access it as a property: ``` private final Optional<Authservice> authservice; [...] public Authservice authservice(){ authservice.isPresent() ? return authservice.get() : throw new IllegalStateException("message"); } ```

Target:
private AuthService authService() { if (authService == null) { throw new IllegalStateException("The auth-server endpoint is not configured."); } return authService; }
Source:
START public StringAttribute(String value){ END this.value = value; } This was only made public for the sake of a test. Please revert change and fix the test. (see below: https://github.com/osiam/connector4java/pull/47/files#r8397645)

Target:
StringAttribute(String value){ this.value = value; }
Source:
protected Object doGetValue() { //System.out.println("NumberCellEditor doGetValue -->" + (data != null ? data : "null")); //BigDecimal value = NumberUtils.createBigDecimal(StringUtils.isNotEmpty(text.getText()) ? text.getText() : null ); //data = value; try { return convertToNumber(); } catch (NumberFormatException e) { START e.printStackTrace(); END } return null; } This causes errors logged in console / error view and the value is cleared for feature. I tested to override `isValueValid` which leaves the feature untouched in case of any NumberFormatException. With this change the try/catch block in doGetValue isn't required anymore.. ``` @Override public boolean isValueValid() { try { Number number = convertToNumber(); return (number != null); } catch (NumberFormatException e) { return false; } } ```

Target:
protected Object doGetValue() { return convertToNumber(); }
Source:
public void setActive(final boolean active) { super.setActive(active); DELETE_SEARCH_SIZE = Platform.getPreferencesService().getInt( START EditPlugin.ID, PreferenceConstants.P_DELETE_TOOL_RADIUS, 6, null); END DELETE_CONFIRM = Platform.getPreferencesService().getBoolean( EditPlugin.ID, PreferenceConstants.P_DELETE_TOOL_CONFIRM, true, null); setStatusBarMessage(active); } Can we use global definition of Defaults here as well?

Target:
public void setActive(final boolean active) { super.setActive(active); setStatusBarMessage(active); }
Source:
public static long getMillisFromString(String strDate) { START long millis = ISO8601.parse(strDate).getTimeInMillis(); END return millis; } I would say "return ISO8601.parse(strDate).getTimeInMillis();" would be enough.

Target:
public static long getMillisFromString(String strDate) { return ISO8601.parse(strDate).getTimeInMillis(); }
Source:
private boolean isScheduled() { long lastStatsUpdateTime = asyncIndexesSizeStatsUpdate.getLastStatsUpdateTime(indexPath); long defaultStatsUpdateTime = asyncIndexesSizeStatsUpdate.getScheduleTimeInMillis(); START return (System.currentTimeMillis() > lastStatsUpdateTime + defaultStatsUpdateTime); END } Brackets are not needed here

Target:
private boolean isScheduled() { long lastStatsUpdateTime = asyncIndexesSizeStatsUpdate.getLastStatsUpdateTime(indexPath); long defaultStatsUpdateTime = asyncIndexesSizeStatsUpdate.getScheduleTimeInMillis(); return System.currentTimeMillis() > lastStatsUpdateTime + defaultStatsUpdateTime; }
Source:
public void loggingAppenderStop() { listAppender.stop(); START System.setProperty("oak.repository.property.logWarnStringSizeThreshold", ""); END } You might want to use `TemporarySystemProperty` ... the rule would reset sys props to their initial state after test. Similarly for logger, it might be easier (better??) to use `LogCustomizer` maybe

Target:
public void loggingAppenderStop() { listAppender.stop(); }
Source:
START private String getResult(QueryResult result, String propertyName) throws RepositoryException { END StringBuilder buff = new StringBuilder(); RowIterator it = result.getRows(); while (it.hasNext()) { if (buff.length() > 0) { buff.append(", "); } buff.append(it.nextRow().getValue(propertyName).getString()); } return buff.toString(); } I think this could be static... could you make all such helper methods static please?

Target:
private static String getResult(QueryResult result, String propertyName) throws RepositoryException { StringBuilder buff = new StringBuilder(); RowIterator it = result.getRows(); while (it.hasNext()) { if (buff.length() > 0) { buff.append(", "); } buff.append(it.nextRow().getValue(propertyName).getString()); } return buff.toString(); }
Source:
START public static boolean waitForCopy(CloudBlob blob) throws StorageException, InterruptedException { END boolean continueLoop = true; CopyStatus status = CopyStatus.PENDING; while (continueLoop) { blob.downloadAttributes(); status = blob.getCopyState().getStatus(); continueLoop = status == CopyStatus.PENDING; // Sleep if retry is needed if (continueLoop) { Thread.sleep(500); } } return status == CopyStatus.SUCCESS; } Shouldn't this method should be private?

Target:
private static boolean waitForCopy(CloudBlob blob) throws StorageException, InterruptedException { boolean continueLoop = true; CopyStatus status = CopyStatus.PENDING; while (continueLoop) { blob.downloadAttributes(); status = blob.getCopyState().getStatus(); continueLoop = status == CopyStatus.PENDING; // Sleep if retry is needed if (continueLoop) { Thread.sleep(500); } } return status == CopyStatus.SUCCESS; }
Source:
public void setShouldRenderWhilePanning( boolean shouldRender ) { mShouldRenderWhilePanning = shouldRender; START if( shouldRender ) { END mTileCanvasViewGroup.setRenderBuffer( TileCanvasViewGroup.FAST_RENDER_BUFFER ); } else { mTileCanvasViewGroup.setRenderBuffer( TileCanvasViewGroup.DEFAULT_RENDER_BUFFER ); } } when a condition just determines a value (rather than an "action" - think: method), i think ternary is appropriate: ``` int buffer = shouldRender ? TileCanvasViewGroup.FAST_RENDER_BUFFER : TileCanvasViewGroup.DEFAULT_RENDER_BUFFER; mTileCanvasViewGroup.setRenderBuffer( buffer ); ```

Target:
public void setShouldRenderWhilePanning( boolean shouldRender ) { mShouldRenderWhilePanning = shouldRender; int buffer = shouldRender ? TileCanvasViewGroup.FAST_RENDER_BUFFER : TileCanvasViewGroup.DEFAULT_RENDER_BUFFER; mTileCanvasViewGroup.setRenderBuffer( buffer ); }
Source:
protected String tryResourceLookup(Resource resource) { try { // added in Java EE 6 / Java SE 7 Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); START } catch (NoSuchMethodException e) { return ""; } catch (IllegalAccessException e) { return ""; } catch (InvocationTargetException e) { return ""; } END } ```suggestion } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { return ""; } ```

Target:
protected String tryResourceLookup(Resource resource) { try { // added in Java EE 6 / Java SE 7 Method lookup = Resource.class.getDeclaredMethod("lookup"); return (String) lookup.invoke(resource); } catch (Exception e) { return ""; } }
Source:
public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); System.out.println(xml); START AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); END final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); } I would say "start doing it" - btw, you have already started in `ArquillianDescriptorClasspathPropertiesTestCase` ;-) https://github.com/arquillian/arquillian-core/pull/162/files#diff-3f0690a66704804b5e1a1a151cae218cR15

Target:
public void should_replace_classpath_in_arquillian_xml() throws Exception { // when final String xml = desc.get().exportAsString(); // then AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }
Source:
START protected void shutdown(TestRunnerAdaptor adaptor) { END State.runnerFinished(); try { if (State.isLastRunner()) { try { if (adaptor != null) { adaptor.afterSuite(); adaptor.shutdown(); } } finally { State.clean(); } } setAdaptor(null); } catch (Exception e) { throw new RuntimeException("Could not run @AfterSuite", e); } } This can be package-private

Target:
void shutdown(TestRunnerAdaptor adaptor) { State.runnerFinished(); try { if (State.isLastRunner()) { try { if (adaptor != null) { adaptor.afterSuite(); adaptor.shutdown(); } } finally { State.clean(); } } setAdaptor(null); } catch (Exception e) { throw new RuntimeException("Could not run @AfterSuite", e); } }
Source:
Set<T> doGetNextGroup(Set<T> idle, Set<T> active) { START if (active.isEmpty()) { END return idle; } else { return ImmutableSet.of(); } } I would copy the current `BatchStrategy` impl of this since it is the same: `return active.isEmpty() ? idle : ImmutableSet.of();`

Target:
Set<T> doGetNextGroup(Set<T> idle, Set<T> active) { return active.isEmpty() ? idle : ImmutableSet.of(); }
Source:
public void willReturnCommandIgnoreOnPipelineInternalLine() { final MarkupText markupText = new MarkupText("Some internal line"); markupText.addMarkup(0, "<span class=\"pipeline-new-node\">"); START System.out.println(markupText.toString(false)); END final ColorizedAction colorizedAction = ColorizedAction.parseAction(markupText, buildRun); assertEquals(ColorizedAction.Command.IGNORE, colorizedAction.getCommand()); } Debugging? Remove.

Target:
public void willReturnCommandIgnoreOnPipelineInternalLine() { final MarkupText markupText = new MarkupText("Some internal line"); markupText.addMarkup(0, "<span class=\"pipeline-new-node\">"); final ColorizedAction colorizedAction = ColorizedAction.parseAction(markupText, buildRun); assertEquals(ColorizedAction.Command.IGNORE, colorizedAction.getCommand()); }
Source:
START public String getX() { END return x; } change to package-private access

Target:
String getX() { return x; }
Source:
START public String getCurve() { END return curve; } change to package-private access

Target:
String getCurve() { return curve; }
Source:
private String getAuthorizationHeader(String clientId, String clientSecret) { if(clientId == null || clientSecret == null) { START logger.debug("Null Client ID or Client Secret detected. Endpoint that requires authentication will reject request with 401 error."); END } String creds = String.format("%s:%s", clientId, clientSecret); try { return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not convert String"); } } DEBUG is a bit of a weak signal, don't you think, given that this is almost certainly going to fail?

Target:
private String getAuthorizationHeader(String clientId, String clientSecret) { if(clientId == null || clientSecret == null) { logger.warn("Null Client ID or Client Secret detected. Endpoint that requires authentication will reject request with 401 error."); } String creds = String.format("%s:%s", clientId, clientSecret); try { return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Could not convert String"); } }
Source:
public Response getExport(ExportRequest exportRequest) throws Exception { context.getExhibitor().getLog().add(ActivityLog.Type.INFO, "Starting export"); Exporter exporter = new Exporter(context, exportRequest.getStartPath()); START return Response.ok(exporter.generate().toString()) END .header("content-disposition", "attachment; filename=exhibitor_export.json") .build(); } toString() is unnecessary

Target:
public Response getExport(ExportRequest exportRequest) throws Exception { context.getExhibitor().getLog().add(ActivityLog.Type.INFO, "Starting export"); Exporter exporter = new Exporter(context, exportRequest.getStartPath()); return Response.ok(exporter.generate()) .header("content-disposition", "attachment; filename=exhibitor_export.json") .build(); }
Source:
public String id() { START return getString("id"); END } Can you add getId() and mark id() as deprecated?

Target:
public String id() { return getId(); }
Source:
public boolean equals(Object obj){ boolean result; if (obj == null) { result = false; } else { START User other = (User) obj; END result = macAddress.equals(other.getMacAddress()) && bluetoothID.equals(other.getBluetoothID()); } return result; } Needs a test for if obj instanceof User...if it isnt, return false.

Target:
public boolean equals(Object obj){ boolean result; if ((obj == null) || !(obj instanceof User)) { result = false; } else { User other = (User) obj; result = macAddress.equals(other.getMacAddress()) && bluetoothID.equals(other.getBluetoothID()); } return result; }
Source:
public void onTerminate() { START unregisterExtranlControlClient(); END super.onTerminate(); } I'm not sure where this method is, but can we refactor it to spell external correctly?

Target:
public void onTerminate() { super.onTerminate(); }
Source:
START public void reassignColors(){ END userColors.clear(); for(User u: connectedUsers){ u.setColor(userColors.getNextAvailableColor()); } } private

Target:
private void reassignColors(){ userColors.clear(); for(User u: connectedUsers){ u.setColor(userColors.getNextAvailableColor()); } }
Source:
private UserList getUserListFromService(){ START UserList activeUsers = new UserList(); END UserListService userService = getUserListService(); if(userService != null){ return userService.getUserList(); } else { Log.i(TAG, "UserListService null, returning empty userlist"); } return activeUsers; } It seems like we make this variable for no real reason. We could just return a new UserList in the bottom return

Target:
private UserList getUserListFromService(){ UserList activeUsers; UserListService userService = getUserListService(); if(userService != null){ activeUsers = userService.getUserList(); } else { activeUsers = new UserList(); Log.i(TAG, "UserListService null, returning empty userlist"); } return activeUsers; }
Source:
public static void eToast(Context context, int resId) { START Log.e(Thread.currentThread().getStackTrace()[methodDepth].toString(), context.getString(resId)); END toastWorker(context, context.getString(resId)); } This should call the eToast method that takes a string, and pass in context.getString(resId) as that string. See iToast.

Target:
public static void eToast(Context context, int resId) { eToast(context, context.getString(resId)); }
Source:
public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { //sorts the list before returning it - for now, //order is simply alphabetical by artist, album, then song. START ArrayList<SongMetadata> music = new ArrayList<SongMetadata>(metadataList); END Collections.sort(music); //unmodifiable copy, for safety return Collections.unmodifiableList(music); } } For large libraries, sorting on each call to getLibrary may introduce a lot of latency. At a minimum, I think we want to move the sort outside the synchronized block, but what might be better in the short and long term would be to sort in updateLibrary, because that is a relatively infrequent action.

Target:
public List<SongMetadata> getLibrary() { synchronized(metadataMutex) { //unmodifiable copy, for safety return Collections.unmodifiableList(new ArrayList<SongMetadata>(metadataList)); } }
Source:
public IBinder onBind(Intent intent) { this.audioPlayer = new SingleFileAudioPlayer( new OnCompletionListener(){ @Override public void onCompletion(MediaPlayer mp) { START new BroadcastIntent(SingleFileAudioPlayer.ACTION_SONG_FINISHED).send(PlaylistService.this); END } }); this.mPlaylist = new Playlist(); // TODO: kick off a thread to feed the monster that is the audio service registerReceivers(); return new PlaylistServiceBinder(); } It looks like we send this broadcast action, receive it several lines down, and the broadcast a different action. Can we collapse that process and just broadcast the different action from here?

Target:
public IBinder onBind(Intent intent) { this.audioPlayer = new SingleFileAudioPlayer(this); this.mPlaylist = new Playlist(); // TODO: kick off a thread to feed the monster that is the audio service registerReceivers(); return new PlaylistServiceBinder(); }
Source:
START protected void onDestroy() { END super.onDestroy(); //Make sure to destroy services when the application closes Toaster.iToast(this, "Destroying MusicLibrary Service"); Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); } Hardcoded toast text :baby:

Target:
protected void onDestroy() { super.onDestroy(); //Make sure to destroy services when the application closes Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); }
Source:
public void deserialize(InputStream input) throws IOException { byte[] bytes = new byte[1024]; int read = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); START while((read = input.read(bytes)) > 0) END out.write(bytes, 0, read); this.setString(out.toString()); } Can you put brackets on the `while`?

Target:
public void deserialize(InputStream input) throws IOException { byte[] bytes = new byte[1024]; int read = 0; ByteArrayOutputStream out = new ByteArrayOutputStream(); while((read = input.read(bytes)) > 0) { out.write(bytes, 0, read); } this.setString(out.toString()); }
Source:
private static boolean isX86(IVMInstall vm) { START return (vm instanceof AbstractVMInstall) && PlatformUtil.ARCH_X86.equals(PreferencesUtil.getArchitecture((AbstractVMInstall) vm)); END } why is instanceof still needed here ?

Target:
private static boolean isX86(IVMInstall vm) { return PlatformUtil.ARCH_X86.equals(PreferencesUtil.getArchitecture(vm)); }
Source:
protected void onSetSSLParameters(SSLParameters sslParameters) { START if (endpointIdentificationAlgorithm == null) { END super.onSetSSLParameters(sslParameters); } else { sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); } } If I understand correctly, endpointIdentificationAlgorithm is never actually null in this test. An empty string is used instead.

Target:
protected void onSetSSLParameters(SSLParameters sslParameters) { if (endpointIdentificationAlgorithm != null) { sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); } }
Source:
public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { SSLEngine e = sslcontext.createSSLEngine(); e.setUseClientMode(false); START if (sslParameters != null) { END e.setSSLParameters(sslParameters); } return new SSLSocketChannel2(channel, e, exec, key); } No check needed since we throw an IllegalArgumentException()

Target:
public ByteChannel wrapChannel(SocketChannel channel, SelectionKey key) throws IOException { SSLEngine e = sslcontext.createSSLEngine(); e.setUseClientMode(false); e.setSSLParameters(sslParameters); return new SSLSocketChannel2(channel, e, exec, key); }
Source:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); try { assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); START } catch (NullPointerException e) { END // Temporary debugging code e.printStackTrace(); throw e; } } Can be removed now?

Target:
public void testBasicRoundTrip() { byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); assertSame(deserialize(kryo, serialized, UnicodeBlock.class), UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); }
Source:
public static Set<ArtifactVersion> ensureDefaultAndPreviousVersionAvailable(final Set<ArtifactVersion> versions) { // add default version final ArtifactVersion defaultVersion = parseVersion(NewSwitchYardProjectWizard.DEFAULT_RUNTIME_VERSION); START if (!versions.contains(defaultVersion)) { END versions.add(defaultVersion); } // add previous version as well final ArtifactVersion previousVersion = parseVersion(NewSwitchYardProjectWizard.PREVIOUS_RUNTIME_VERSION); if (!versions.contains(previousVersion)) { versions.add(previousVersion); } return versions; } Just realizing now: if it is a Set we don't need to check if it is contained inside first

Target:
public static Set<ArtifactVersion> ensureDefaultAndPreviousVersionAvailable(final Set<ArtifactVersion> versions) { // add default version final ArtifactVersion defaultVersion = parseVersion(NewSwitchYardProjectWizard.DEFAULT_RUNTIME_VERSION); versions.add(defaultVersion); // add previous version as well final ArtifactVersion previousVersion = parseVersion(NewSwitchYardProjectWizard.PREVIOUS_RUNTIME_VERSION); versions.add(previousVersion); return versions; }
Source:
private void refreshProject(IProgressMonitor monitor) throws CoreException { // update the project so we ensure a Project->Clean is done so the // MANIFEST.MF is built and we don't run into trouble deploying the // project on a Fuse server. START if (_projectMetatData.getNewProjectHandle() != null) { END _projectMetatData.getNewProjectHandle().refreshLocal(IProject.DEPTH_INFINITE, monitor); // also, update the maven project so we start in a deployable state // with a valid MANIFEST.MF built as part of the build process. Job updateJob = new UpdateMavenProjectJob(new IProject[] {_projectMetatData.getNewProjectHandle() }); updateJob.schedule(); } } _projectMetatData.getNewProjectHandle() can be extracted as local variable as it is used 3 times

Target:
private void refreshProject(IProgressMonitor monitor) throws CoreException { // update the project so we ensure a Project->Clean is done so the // MANIFEST.MF is built and we don't run into trouble deploying the // project on a Fuse server. IProject project = _projectMetatData.getNewProjectHandle(); if (project != null) { // update the maven project so we start in a deployable state // with a valid MANIFEST.MF built as part of the build process. Job updateJob = new UpdateMavenProjectJob(new IProject[] {project}); updateJob.schedule(); } }
Source:
public void setShipping(final Shipping shipping) { this.shipping = shipping; addUnsavedProperty("shipping"); START } END from what I remember, the `addUnsavedProperty` doesn't really do anything useful and therefore should be removed. So as not to pollute the code, please confirm it and refactor it as needed.

Target:
public void setShipping(final Shipping shipping) { this.shipping = shipping; }
Source:
public void setSplitRules(final Collection<SplitRule> splitRules) { this.splitRules = splitRules; if (this.splitRules.size() != 0) { START addUnsavedProperty("splitRules"); END } } Is the property used in any form? If not, is this line required?

Target:
public void setSplitRules(final Collection<SplitRule> splitRules) { this.splitRules = splitRules; }
Source:
public void setUpdatableParameters(String cardId, String cardHash, String planId){ this.planId = planId; if(!Strings.isNullOrEmpty(cardId)){ START this.cardHash = cardId; END }else if(!Strings.isNullOrEmpty(cardHash)){ this.cardHash = cardHash; } } Trocar cardHash para cardId, verificar a necessidade do if

Target:
public void setUpdatableParameters(String cardId, String cardHash, String planId){ this.planId = planId; this.cardId = cardId; this.cardHash = cardHash; }
Source:
public void deleteAnticipation(BulkAnticipation anticipation) throws PagarMeException{ START validateId(); END String path = String.format("/%s/%s/%s/%s", getClassName(), getId(), anticipation.getClassName(), anticipation.getId()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, path); request.execute(); } Verificar se é necessário usar o validateId(todos) no momento.

Target:
public void deleteAnticipation(BulkAnticipation anticipation) throws PagarMeException{ String path = String.format("/%s/%s/%s/%s", getClassName(), getId(), anticipation.getClassName(), anticipation.getId()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.DELETE, path); request.execute(); }
Source:
START public String getTransactionId() { END return transactionId; } Verificar essa troca de tipos. Será que irá quebrar alguém?

Target:
public Integer getTransactionId() { return transactionId; }
Source:
START public Collection<Payable> findCollection(final Integer totalPerPage, Integer page, final Map<String, Object> filters) END throws PagarMeException { String path = String.format("/%s", getClassName()); return _findCollection(path, totalPerPage, page, filters); } Seria bom reutilizar o método paginate do PagarMeModel

Target:
public Collection<Payable> findCollection(final Integer totalPerPage, Integer page, final Map<String, Object> filters) throws PagarMeException { String path = String.format("/%s", getClassName()); return findCollection(path, totalPerPage, page, filters); }
Source:
private static boolean checkForValidityOfAttributes(ArrayList<String> attributeList) { for (String str : attributeList) { START if (str == "-1") { END return false; } } return true; } `==` tests for reference equality, hence it could be error-prone -- it'd be better to use the `.equals()` method...

Target:
private static boolean checkForValidityOfAttributes(ArrayList<String> attributeList) { for (String str : attributeList) { if (str.equals("-1")) { return false; } } return true; }
Source:
private ItemGroup getItemGroup(Run<?, ?> build) { if (build instanceof AbstractBuild) { return ((AbstractBuild) build).getProject().getRootProject().getParent(); } else { // TODO: hmmm ??? START return build.getParent().getParent(); END } } This is fine. There is no equivalent of `getRootProject` for non-`AbstractProject`s, and none is needed. (The original code here is just the usual hacks to make things work with `matrix-project`.)

Target:
private ItemGroup getItemGroup(Run<?, ?> build) { return getRootProject(build.getParent()).getParent(); }
Source:
private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { START if (x instanceof KItem && ((KItem) x).klabel().toString().equals(KLabels.AND)) { END flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); } do not check equality based on `toString`

Target:
private void flattenList(List<K> unflat, List<K> flat) { unflat.forEach(x -> { if (x instanceof KItem && ((KItem) x).klabel().name().equals(KLabels.AND)) { flattenList(((KItem) x).items(), flat); } else { flat.add(x); } }); }
Source:
private Parser(Module module) throws IOException { // TODO: remove hack once the frontend is cleaner; also remove the IOException once the hack is cleared if (module.name().endsWith(RuleGrammarGenerator.RULE_CELLS)) { START org.kframework.definition.Definition definitionWithBuiltins = Definition.from("require \"domians.k\"", "K"); END this.parseInModule = new RuleGrammarGenerator(definitionWithBuiltins, true).getCombinedGrammar(module); } else { this.parseInModule = new ParseInModule(module); } } To generate parsers only `kast.k` is needed. Why are you including ALL the builtins?

Target:
private Parser(Module module) { // TODO: remove hack once the frontend is cleaner; also remove the IOException once the hack is cleared if (module.name().endsWith(RuleGrammarGenerator.RULE_CELLS)) { org.kframework.definition.Definition definitionWithBuiltins = Definition.from("require \"domians.k\"", "K"); this.parseInModule = new RuleGrammarGenerator(definitionWithBuiltins, true).getCombinedGrammar(module); } else { this.parseInModule = new ParseInModule(module); } }
Source:
public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); START this.context = context.fork(); END } are you still creating new contexts here?

Target:
public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); this.context = context; }
Source:
public List<Map<KVariable, K>> match(K k, org.kframework.definition.Rule rule) { START return (List<Map<KVariable, K>>) search(k, Optional.of(0), Optional.empty(), rule); END } I suggest instead to make it be a List<? extends Map<? extends KVariabale, ? extends K>> because technically this is not a safe cast.

Target:
public List<? extends Map<? extends KVariable,? extends K>> match(K k, org.kframework.definition.Rule rule) { return search(k, Optional.of(0), Optional.empty(), rule); }
Source:
public File mainDefinitionFile() { START File m = mainDefinitionFile; END if (m == null) { if (parameters == null || parameters.size() == 0) { throw KEMException.criticalError("You have to provide exactly one main file in order to compile."); } m = mainDefinitionFile = files.get().resolveWorkingDirectory(parameters.get(0)); } return m; } OK, I just checked the JLS and I was wrong about the read in `m = mainDefinitionFile` can see null value. It can only happen if the last line is written as `return mainDefinitionFile`. Anyway, I don't think it's a good idea to assume Guice is absolutely thread-safe when there is a simpler and equally efficient solution available.

Target:
public synchronized File mainDefinitionFile() { if (mainDefinitionFile == null) { if (parameters == null || parameters.size() == 0) { throw KEMException.criticalError("You have to provide exactly one main file in order to compile."); } mainDefinitionFile = files.get().resolveWorkingDirectory(parameters.get(0)); } return mainDefinitionFile; }
Source:
public Kompile(KompileOptions kompileOptions, FileUtil files, KExceptionManager kem, boolean cacheParses) { START this.files = files; END this.kem = kem; this.kompileOptions = kompileOptions; this.parser = new ParserUtils(files, kem, kompileOptions.global); this.cacheParses = cacheParses; this.loader = new BinaryLoader(kem); this.sw = new Stopwatch(kompileOptions.global); } can you make this constructor this() the one above?

Target:
public Kompile(KompileOptions kompileOptions, FileUtil files, KExceptionManager kem, boolean cacheParses) { this(kompileOptions, files, kem, new Stopwatch(kompileOptions.global), cacheParses); }
Source:
public boolean isGround() { if (isGround == null) { START if (variableSet == null || !variableSet.isEmpty()) { END new IsGroundFieldInitializer().visitNode(this); } else { isGround = true; } } return isGround; } `if (variableSet == null) {`

Target:
public boolean isGround() { if (isGround == null) { if (variableSet == null) { new IsGroundFieldInitializer().visitNode(this); } else { isGround = variableSet.isEmpty(); } } return isGround; }
Source:
public Definition addProgramModule(Definition d) { START Module programsModule = gen.getProgramsGrammar(d.mainSyntaxModule()).module(); END java.util.Set<Module> allModules = mutable(d.modules()); allModules.add(programsModule); return Definition(d.mainModule(), programsModule, immutable(allModules)); } again, none of this is necessary as far as I can tell.

Target:
public Definition addProgramModule(Definition d) { Module programsModule = gen.getProgramsGrammar(d.mainSyntaxModule()); java.util.Set<Module> allModules = mutable(d.modules()); allModules.add(programsModule); return Definition(d.mainModule(), programsModule, immutable(allModules)); }
Source:
START public BiFunction<String, Source, K> getProgramParser(KExceptionManager kem) { END ParseInModule parseInModule = getParserModule(kompiledDefinition.mainSyntaxModule()); return getParser(parseInModule, programStartSymbol, kem); } if you keep the getParser method's signature the same, then getGroundParser is no longer a method that needs to exist.

Target:
public BiFunction<String, Source, K> getProgramParser(KExceptionManager kem) { return getParser(kompiledDefinition.mainSyntaxModule(), programStartSymbol, kem); }
Source:
START public ParseInModule(Module seedModule) { END this.seedModule = seedModule; this.extensionModule = seedModule; this.disambModule = seedModule; this.parsingModule = seedModule; this.grammar = KSyntax2GrammarStatesFilter.getGrammar(parsingModule); } this constructor feels wrong now... I think it should be a Module and a Definition and then the constructor calls getCombinedGrammar.

Target:
ParseInModule(Module seedModule) { this(seedModule, seedModule, seedModule, seedModule); }
Source:
public static K parseWithModule(CharSequence theTextToParse, String startSymbol, org.kframework.definition.Module kastModule) { START ParseInModule parser = new ParseInModule(kastModule); END Term cleaned = parser.parseString(theTextToParse, startSymbol)._1().right().get(); return TreeNodesToKORE.apply(cleaned); } this code needs to be factored to support the fact that we will eventually need to compute Grammar objects during kompile and serialize them.

Target:
public static K parseWithModule(CharSequence theTextToParse, String startSymbol, org.kframework.definition.Module kastModule) { ParseInModule parser = new ParseInModule(kastModule); return parseWithModule(theTextToParse, startSymbol, parser); }
Source:
public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } START SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, false); END mergeSearchGraph(results.getGraph()); currentState = null; return results; } This should be true actually

Target:
public SearchResults stepAll(int steps) throws KRunExecutionException { if (currentState == null) { throw new IllegalStateException("Cannot step without a current state to step from. " + "If you previously used the search command you must" + "first select a solution with the select command before executing steps of rewrites!"); } SearchResults results = executor.search(null, steps, SearchType.PLUS, defaultPattern, getState(currentState).getRawResult(), defaultPatternInfo, true); mergeSearchGraph(results.getGraph()); currentState = null; return results; }
Source:
protected Object fastClone(final Object o, final Map<Object, Object> clones) throws IllegalAccessException { START if ((o instanceof Term && !((Term) o).isMutable())) { END return o; } else { return super.fastClone(o, clones); } } what are these extra parentheses for?

Target:
protected Object fastClone(final Object o, final Map<Object, Object> clones) throws IllegalAccessException { if (o instanceof Term && !((Term) o).isMutable()) { return o; } else { return super.fastClone(o, clones); } }
Source:
START public void save(File file, String content) { END try { File dir = file.getAbsoluteFile().getParentFile(); if (!dir.exists() && !dir.mkdirs()) { throw KExceptionManager.criticalError("Could not create directory " + dir); } FileUtils.writeStringToFile(file, content); } catch (IOException e) { throw KExceptionManager.criticalError("Could not write to file " + file.getAbsolutePath(), e); } } I know it's not part of this diff, but why isn't this function static?

Target:
public static void save(File file, String content) { try { File dir = file.getAbsoluteFile().getParentFile(); if (!dir.exists() && !dir.mkdirs()) { throw KExceptionManager.criticalError("Could not create directory " + dir); } FileUtils.writeStringToFile(file, content); } catch (IOException e) { throw KExceptionManager.criticalError("Could not write to file " + file.getAbsolutePath(), e); } }
Source:
START public AbstractVisitor(String name, Context context) { END this.context = context; this.currentDefinition = null; this.currentModule = null; this.kompileOptions = context == null ? null : context.kompileOptions; this.globalOptions = context == null ? null : context.globalOptions; this.name = name; } please use constructor inheritance for these

Target:
public AbstractVisitor(String name, Context context) { this(name, context, null, null); }
Source:
START public boolean isExactSort() { END return true; } not a big deal, but I would like to make it `final`

Target:
public final boolean isExactSort() { return true; }
Source:
START public boolean isConcreteCollection() { END return collectionPatterns.isEmpty() && collectionVariables.isEmpty() && collectionFunctions.isEmpty(); } final?

Target:
public final boolean isConcreteCollection() { return collectionPatterns.isEmpty() && collectionVariables.isEmpty() && collectionFunctions.isEmpty(); }
Source:
START public boolean isGround() { END return isConcreteCollection() && super.isGround(); } final

Target:
public final boolean isGround() { return isConcreteCollection() && super.isGround(); }
Source:
START public boolean isPattern() { END return false; } final?

Target:
public final boolean isPattern() { return false; }
Source:
public Sort sort() { // TODO(AndreiS): track the original sort from the grammar START return KSorts.MAP; END } I don't like that you have both Sort and KSorts containing Sort constants.

Target:
public Sort sort() { // TODO(AndreiS): track the original sort from the grammar return Sort.MAP; }
Source:
public static void setTool(Tool tool) { if (K.tool != null) { assert false : "Can only call setTool once"; START } END K.tool = tool; } Why not use ``` java assert (K.tool == null) : "Can only call setTool once"; ``` instead?

Target:
public static void setTool(Tool tool) { assert K.tool == null : "Can only call setTool once"; K.tool = tool; }
Source:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { /* context is unused for directory paths; the actual context is de-serialized */ /* load the definition from a binary file */ definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } /* initialize the builtin function table */ START builtins = new BuiltinFunction(definition); END this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); } seems like you're calling this constructor in a couple places. Is it really necessary to construct more than one BuiltinFunction object per definition?

Target:
public JavaSymbolicKRun(Context context) throws KRunExecutionException { /* context is unused for directory paths; the actual context is de-serialized */ /* load the definition from a binary file */ definition = (Definition) BinaryLoader.load( new File(context.kompiled, JavaSymbolicBackend.DEFINITION_FILENAME).toString()); if (definition == null) { throw new KRunExecutionException("cannot load definition"); } this.context = definition.context(); this.context.kompiled = context.kompiled; this.context.globalOptions = context.globalOptions; transformer = new KILtoBackendJavaKILTransformer(this.context); }
Source:
public void putAll(Map<Term, Term> map) { Preconditions.checkArgument(!setEntries, "Cannot put in new key-value pair once the entries are set."); START for (Map.Entry<Term, Term> e : map.entrySet()) { END entries.put(e.getKey(), e.getValue()); } } entires.putAll(map)?

Target:
public void putAll(Map<Term, Term> map) { entries.putAll(map); }
Source:
public final int hashCode() { if (hashCode == Utils.NO_HASHCODE) { START hashCode = computeHash(); END } return hashCode; } I believe this was a suggestion of @dwightguth: if computeHash() returns 0, set the hashCode to 1.

Target:
public final int hashCode() { if (hashCode == Utils.NO_HASHCODE) { hashCode = computeHash(); hashCode = hashCode == 0 ? 1 : hashCode; } return hashCode; }