auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { boolean needMore = false; while (true) { if (needMore) { readMore(buffer, input, bytesRemaining); needMore = false; } if (buffer.remaining() < 1 && bytesRemaining.value > 0) { needMore = true; } else { return buffer.get(); } } }

Target:
I think we can simplify these functions. Something like this: ```java private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 1) readMore(buffer, input, bytesRemaining); return buffer.get(); } private static long readVarLong(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 10 && bytesRemaining.value > 0) readMore(buffer, input, bytesRemaining); return ByteUtils.readVarlong(buffer); } private static int readVarInt(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 10 && bytesRemaining.value > 0) readMore(buffer, input, bytesRemaining); return ByteUtils.readVarint(buffer); } ``` I think we shouldn't need more than one call to `readMore`.
Source:
public Object evaluate(Object feature) { Map map = getExpression(0).evaluate(feature, Map.class); String key = getExpression(1).evaluate(feature, String.class); if (map.containsKey(key)) { return map.get(key); } return null; }

Target:
NPE prone, check if map is not null. Also, no need to check if the map contains, one can simply call get: ```suggestion if (map != null) { return map.get(key); } ```
Source:
public boolean eIsSet(int featureID) { switch (featureID) { case Csw20Package.QUERY_TYPE__ELEMENT_SET_NAME: return elementSetName != null; case Csw20Package.QUERY_TYPE__ELEMENT_NAME: return elementName != null && !elementName.isEmpty(); case Csw20Package.QUERY_TYPE__CONSTRAINT: return constraint != null; case Csw20Package.QUERY_TYPE__SORT_BY: return SORT_BY_EDEFAULT == null ? sortBy != null : !Arrays.equals(SORT_BY_EDEFAULT, sortBy); case Csw20Package.QUERY_TYPE__TYPE_NAMES: return typeNames != null; } return super.eIsSet(featureID); }

Target:
I am never quite sure how to use error prone in IntelliJ, perhaps @aaime has guidance. Does error prone require some configuration to ignore these autogenerated folders?
Source:
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { Filter f = query.getFilter(); if (f != null && f.equals(Filter.INCLUDE)) { try { return new ReferencedEnvelope( CRS.transform(mbtiles.loadMetaData().getBounds(), DEFAULT_CRS)); } catch (TransformException e) { throw new RuntimeException("Unable to retrieve bounds from mbtiles metadata", e); } } else { // summing up all feature bounds would be expensive. // returning null return null; } }

Target:
```suggestion if (f == null || f.equals(Filter.INCLUDE)) { ```
Source:
public boolean hasUserData() { return userData != null; }

Target:
A question: Omitting the map.isEmpty() check is intended? Overrided default method does the check but here only a null check is done.
Source:
public void registerSqlTypeToSqlTypeNameOverrides(Map<Integer, String> overrides) { //Step 1 Geos-7533 put the types in dialect overrides.put(4, "int4"); overrides.put(Types.VARCHAR, "VARCHAR"); overrides.put(Types.BOOLEAN, "BOOL"); overrides.put(Types.BLOB, "BYTEA"); }

Target:
Please use ``Types.INTEGER`` instead of ``4``.
Source:
private boolean isValidDomain(double minx, double maxx, double miny, double maxy) { final int width = (int) (maxx - minx); final int height = (int) (maxy - miny); if (abs(width) == 0 || height == 0) { return false; } return true; }

Target:
Can be simpler, return directly: ``return abs(width) > 0 && abs(height)== 0``
Source:
protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } if (encodeGmlId) addGmlId(result, gmlId); return result; }

Target:
Probably best at the beginning, ``if gmlId == null || !encodeGMlId``
Source:
private Object invertGeometryCoordinates(Geometry geometry) throws TransformException { return transformer.transform(geometry); }

Target:
Works anyways but a bit weird to have it return an Object, would look better returning a Geometry (that's what the transformer.tranfsorm method does). Not a critical issue, fix if you like.
Source:
public void testHiddenTables() throws IOException { String[] typenames = dataStore.getTypeNames(); for (String name:typenames) { System.out.println(name); System.out.println(tname(name)); assertFalse("Name should not end with 'MDXT_'",name.startsWith("MDXT_")); assertFalse("Name should not end with '$_BKTS'",name.endsWith("$_BKTS")); assertFalse("Name should not end with '$'",name.endsWith("$")); } }

Target:
No system outs in tests please (yes, there might be some around, they are leftovers that should not be there)
Source:
public Map<String,String> getSupportedFunctions() { if ( supportedFunctions == null ) { supportedFunctions = new HashMap(); dialect.registerFunctions(supportedFunctions); } return supportedFunctions; }

Target:
Generics, new HashMap<>();
Source:
for (PropertyAccessorFactory factory : ServiceLoader.load(PropertyAccessorFactory.class)) { boolean nonCached = factory instanceof SimpleFeaturePropertyAccessorFactory || factory instanceof DirectPropertyAccessorFactory || factory instanceof NullPropertyAccessorFactory; if (!nonCached) cache.add(factory); }

Target:
Thanks that is a clear way to describe the cache condition. We tend to use braces even for single line if statements
Source:
public void setLatLonBoundingBox(CRSEnvelope latLonBoundingBox) { if( latLonBoundingBox.getSRSName() != null ){ String srsName = latLonBoundingBox.getSRSName(); if( !srsName.equals("CRS:84")){ throw new IllegalStateException("Layer LatLonBoundingBox srsName required to be null or CRS:84"); } }else { latLonBoundingBox.setSRSName("CRS:84",false);; } this.latLonBoundingBox = latLonBoundingBox; }

Target:
Formatting, it should be "} else {". I won't repeat this for all occurrences, please check the diffs and make sure the changes (and only those) respect the coding conventions
Source:
public List<String> getTextFont() { String[] fonts; if (!(layout.get("text-font") instanceof JSONObject)) { fonts = parse.array(String.class, layout, "text-font", new String[]{"Open Sans Regular", "Arial Unicode MS Regular"}); return Arrays.asList(fonts); } else { return null; } }

Target:
Bit of a nitpick, but since we already have an if-else, using: ``` if (layout.get("text-font") instanceof JSONObject) { return null } else { ... } ``` would be a bit clearer.
Source:
protected ReferencedEnvelope calculateBounds() { ReferencedEnvelope extent = ReferencedEnvelope.create( getSchema().getCoordinateReferenceSystem() ); for( SimpleFeature feature : list ){ if( feature == null ) continue; ReferencedEnvelope bbox = ReferencedEnvelope.reference( feature.getBounds() ); if( bbox == null || bbox.isEmpty() || bbox.isNull() ) continue; extent.expandToInclude( bbox ); } return extent; }

Target:
we tend to use braces when placing a statement on a seperate line, check developers guide for sun-java-conventions + 100 cols.
Source:
public void testCreatePointStyle(){ // The following is complex, and should be built from // an SLD document and not by hand PointSymbolizer pointsym = sf.createPointSymbolizer(); pointsym.setGraphic(sf.getDefaultGraphic()); NumberRange<Double> scaleRange = NumberRange.create( 1.0,50000.0); Style2D style = sld.createPointStyle(null, pointsym, scaleRange); assertNotNull( style ); PointStyle2D ps = (PointStyle2D) style; assertEquals(0.0f, ps.getAnchorPointX(), 0.0f); assertEquals(0.5f, ps.getAnchorPointY(), 0.0f); }

Target:
okay so you already have this covered, no need for AnchorPointTest above?
Source:
public Number getLineRoundLimit() { if (paint.get("line-round_limit") != null) { return (Number) paint.get("line-round-limit"); } else { return 1.05; } }

Target:
This underscore should also be a dash
Source:
public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer copy = (PolygonSymbolizer) pages.peek(); Unit<Length> uom = copy.getUnitOfMeasure(); rescaleStroke(copy.getStroke(), uom); rescaleFill(copy.getFill(), uom); scaleIntArrayOption(copy.getOptions(), TextSymbolizer.GRAPHIC_MARGIN_KEY, uom); copy.setUnitOfMeasure(NonSI.PIXEL); }

Target:
While it's the same value, it's confusing to see TextSymbolizer referenced here, PolygonSymbolizer gets the right constant in this same pull request.
Source:
private CoverageSource getGridCoverageSource(final String coverageName) throws IOException { // Preliminar check on name availability checkIsSupported(coverageName); synchronized (coverages) { if (coverages.containsKey(coverageName)) { return coverages.get(coverageName); } // create, cache and return CoverageSource source = access.access(new NameImpl(coverageName), null, AccessType.READ_ONLY, null, null); if (source instanceof NetCDFSource) { } coverages.put(coverageName, source); return source; } }

Target:
What is this block?
Source:
private GroupByVisitor buildVisitor(String aggregateAttribute, String aggregateVisitor, String[] groupByAttributes) { GroupByVisitorBuilder visitorBuilder = new GroupByVisitorBuilder() .withAggregateAttribute(aggregateAttribute, buildingType) .withAggregateVisitor(aggregateVisitor); for (String groupByAttribute : groupByAttributes) { visitorBuilder.withGroupByAttribute(groupByAttribute, buildingType); } GroupByVisitor visitor = visitorBuilder.build(); return visitor; }

Target:
The visitor variable is not need could simply be: `return visitorBuilder.build();`
Source:
public F next() throws NoSuchElementException { if(next==null&&this.hasNext()==false) { throw new NoSuchElementException(); } F f = next; next = null; return f; }

Target:
minor suggestions: please, check the formatting (need some whitespaces). I would also personally use !this.hasNext() instead of explicit check with false. if (next == null && !this.hasNext()) {
Source:
public static String getAlternativePath(String path, boolean removeExtension) { return FOOTPRINTS_DATA_DIR != null ? getAlternativeFile(path, removeExtension).getAbsolutePath() : null; }

Target:
Public? Does not seem this method is used anywhere else
Source:
private static void checkAllInserted(int[] inserts, int size) throws IOException { int sum = 0; for (int cur: inserts) { if (cur == PreparedStatement.SUCCESS_NO_INFO) { return; // cannot check } else if (cur == PreparedStatement.EXECUTE_FAILED) { throw new IOException("Failed to insert some features"); } sum += cur; } if (sum != size) { throw new IOException("Failed to insert some features"); } }

Target:
Why static, only this class seems to be using it
Source:
public ImageWorker(RenderingHints hints) { setRenderingHints(hints); }

Target:
Shouldn't this call the empty constructor? Or the empty constructor has useless code inside of it?
Source:
public boolean hasNext() throws IOException { if( csvWriter == null ){ throw new IOException("Writer has been closed"); } if (this.appending) { return false; // reader has no more contents } return iterator.hasNext(); }

Target:
@tbarsballe has gone through and done a QA run to ensure closed writers return hasNext(): false (rather than thrown an IOException). Lets stick with that for consistency (principle of least surprise)
Source:
public StringBuilder dateToText( Date date, StringBuilder output ){ DateFormat formatter; // If the Date has millisecond resolution, print the millis. if (date.getTime() % 1000 == 0) { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"); } else { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz"); } formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); String text = formatter.format(date); // GMT is not part of CQL syntax so it is removed text = text.replace("GMT", ""); output.append( text ); return output; }

Target:
add a final to ensure it is set: `final DateFormat formatter`
Source:
protected EnvVars buildEnv(AbstractProject<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Throwable t) { LOGGER.debug("{} failed to build env ({}), skipping", contributor.getClass(), t.getMessage(), t); } } return env; }

Target:
After the discussions in other PRs we agreed that this approach is not good, because it suppresses various kinds of system <code>Error</code>s, which are supposed to be system failures
Source:
public static Predicate<GHEventsSubscriber> isApplicableFor(final AbstractProject<?, ?> project) { return new Predicate<GHEventsSubscriber>() { @Override public boolean apply(GHEventsSubscriber subscriber) { Validate.notNull(subscriber); return subscriber.isApplicable(project); } }; }

Target:
You can write it directly `notNull(subscriber).isApplicable(project);` (Same with other places, with static imports)
Source:
public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) job; for (GitHubTrigger ght : Util.filter(p.getTriggers().values(),GitHubTrigger.class)) { result.addAll(ght.getGitHubRepositories()); } }

Target:
Maybe a type-check here first?
Source:
public void visitLineNumber(int line, Label start) { _lineNumber = line; }

Target:
As a safety precaution, should we make this assignment just once to grab only the very first line number in case generated synthetic lambda method contains more than one line numbers?
Source:
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { switch (opcode) { case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: _methodInsnName = name; _methodInsnOwner = owner; _methodInsnDesc = desc; _methodInsnOpcode = opcode; break; default: //TODO: throw an exception that couldn't infer operation LOGGER.debug("Unexpected opcode, falling back"); break; } super.visitMethodInsn(opcode, owner, name, desc, itf); }

Target:
TODO + logger level to DEBUG
Source:
protected Promise<? extends T> run(Context context) { _startedAt = System.currentTimeMillis(); Task<T> task = wrap(0); context.run(task); return task; }

Target:
Nope. I missed that.
Source:
public void shutdown() throws InterruptedException { if (_zkClient != null) { _zkClient.close(); _reaper.shutdown(); } }

Target:
return Promise just to symmetric with start()...
Source:
public void start() { if (stepClassWithSpringContext != null) { testContextManager = new CucumberTestContextManager(stepClassWithSpringContext); } else { if (beanFactory == null) { beanFactory = createFallbackContext(); } } notifyContextManagerAboutTestClassStarted(); if (beanFactory == null || isNewContextCreated()) { beanFactory = testContextManager.getBeanFactory(); synchronized (beanFactory) { for (Class<?> stepClass : stepClasses) { registerStepClassBeanDefinition(beanFactory, stepClass); } } } GlueCodeContext.getInstance().start(); }

Target:
We also have a synchronization step a few lines up inside `CucumberTestContextManager`. For clarity we could synchronize all operations in the start method.
Source:
private void handleWrite(WriteEvent event) { out.println(); try(BufferedReader lines = new BufferedReader(new StringReader(event.text))) { String line = lines.readLine(); while(line != null) { out.println(STEP_SCENARIO_INDENT + line); line = lines.readLine(); } } catch (IOException e) { throw new CucumberException(e); } out.println(); }

Target:
The canonical way to write this avoids the repetition of `readLine`. It is a little bit less error prone. ``` String line; while ((line = lines.readLine()) != null) { out.println(STEP_SCENARIO_INDENT + line); } ``` Aside from that: looks good! Don't forget to indent your code properly.
Source:
private String describeNote() { return String.join("\n", this.notes); }

Target:
With the exception of constructors, non-static inner classes and setters the `this` key word isn't usually needed.
Source:
public void shouldSetStrictOnPlugin() { RuntimeOptions runtimeOptions = new RuntimeOptions("--strict"); Plugins plugins = new Plugins(getSystemClassLoader(), pluginFactory, runtimeOptions); StrictAware plugin = Mockito.mock(StrictAware.class); plugins.addPlugin(plugin); plugins.setSerialEventBusOnEventListenerPlugins(rootEventPublisher); verify(plugin).setStrict(true); }

Target:
```suggestion ```
Source:
public byte exitStatus(boolean isStrict) { byte result = 0x0; if (!failedScenarios.isEmpty() || (isStrict && (!pendingScenarios.isEmpty() || !undefinedScenarios.isEmpty() || !ambiguousScenarios.isEmpty()))) { result |= ERRORS; } return result; }

Target:
Looking at [printNonZeroResultScenarios](https://github.com/cucumber/cucumber-jvm/pull/1342/files#diff-9c2af73a8f4e34a02a035f2709e487d5R157) I think `ambiguousScenarios` should be treated the same as `failedScenarios` and always return a non zero exit status.
Source:
public void addStepDefinition(StepDefinition stepDefinition) { StepDefinition previous = stepDefinitionsByPattern.get(stepDefinition.getPattern()); if (previous == null || haveSameLocation(previous, stepDefinition)) { stepDefinitionsByPattern.put(stepDefinition.getPattern(), stepDefinition); } else { throw new DuplicateStepDefinitionException(previous, stepDefinition); } }

Target:
It is a matter of taste, but I would probably have used: ``` if (previous == null) { stepDefinitionsByPattern.put(stepDefinition.getPattern(), stepDefinition); } else if (!haveSameLocation(previous, stepDefinition)) { throw new DuplicateStepDefinitionException(previous, stepDefinition); } ``` In a method named addStepDefinition, the `if (previous == null || haveSameLocation(previous, stepDefinition))` triggered a "no, it is not right to add the stepDefinition in both these cases" in me, but it is actually ok, since put overwrites the previous step definition with the new one.
Source:
private void printSummary(cucumber.runtime.Runtime runtime) { runtime.getSummaryCounter().printSummary(out); }

Target:
Tell don't ask. Remove `getSummaryCounter()` and add a `Runtime.printSummary(out)` method instead.
Source:
public void generatesPlainSnippet() { Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have 4 cukes in my \"big\" belly", 0, null, null); String snippet = new SnippetGenerator(new ClojureSnippet()).getSnippet(step); String expected = "" + "(Given #\"^I have (\\d+) cukes in my \"([^\"]*)\" belly$\" [arg1, arg2]\n" + <<<<<<< HEAD " (comment Express the Regexp above with the code you wish you had ))\n"; assertEquals(expected, snippet); }

Target:
Looks like you keft this one out.
Source:
private final boolean isDateInvalid(Elements elements) { boolean result = false; if (!elements.isEmpty()) { Element dcTermsDateElement = elements.get(0); try { new SimpleDateFormat(MrrtReportTemplateConstants.DATE_FORMAT).parse(dcTermsDateElement.attr("content")); } catch (ParseException ex) { result = true; } } return result; }

Target:
@ivange94 can you turn this into a positive check/guard clause. so ```java if (elements.isEmpty()) { return false; } ``` this removes one level of nesting and makes it easier to read, since the reader see's immediately that if the elements is empty we return.
Source:
public void search_shouldReturnAllReportTemplatesByGivenPublisher() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_PUBLISHER, PUBLISHER_QUERY); RequestContext requestContext = new RequestContext(); requestContext.setRequest(request); when(mrrtReportTemplateService.getMrrtReportTemplates(any(MrrtReportTemplateSearchCriteria.class))) .thenReturn(mrrtReportTemplates); PageableResult pageableResult = mrrtReportTemplateSearchHandler.search(requestContext); assertThat(pageableResult, is(instanceOf(NeedsPaging.class))); }

Target:
can you move the boilerplate out of all tests add ``` java MockHttpServletRequest request; RequestContext requestContext; ``` as class fields. and ``` java request = new MockHttpServletRequest(); requestContext.setRequest(request); ``` into the setUp method. makes our tests cleaner and contain only the diferences in the request.setParameter()
Source:
public void search_shouldReturnEmptySearchResultIfTitleDoesNotExist() throws Exception { request.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_TITLE, NON_EXISTING_TITLE); requestContext.setRequest(request); PageableResult pageableResult = mrrtReportTemplateSearchHandler.search(requestContext); assertThat(pageableResult, is(instanceOf(EmptySearchResult.class))); }

Target:
this is already done in setUp.
Source:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithAccessionNumberIfAccessionNumberIsSet() throws Exception { String accessionNumber = "1"; radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withAccessionNumber(accessionNumber) .build(); assertTrue(radiologyOrderSearchCriteria.getAccessionNumber() .equals(accessionNumber)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getFromEffectiveStartDate()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); }

Target:
@bgeVam assertThat(, is())
Source:
public void getRadiologyOrders_shouldReturnAllRadiologyOrdersForGivenAccessionNumberIfAccessionNumberIsSpecified() throws Exception { RadiologyOrderSearchCriteria radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withAccessionNumber(EXISTING_RADIOLOGY_ORDER_ACCESSION_NUMBER) .build(); List<RadiologyOrder> radiologyOrders = radiologyOrderService.getRadiologyOrders(radiologyOrderSearchCriteria); assertThat(radiologyOrders.size(), is(1)); for (RadiologyOrder radiologyOrder : radiologyOrders) { assertThat(radiologyOrder.getAccessionNumber(), is(EXISTING_RADIOLOGY_ORDER_ACCESSION_NUMBER)); } }

Target:
@bgeVam why loop? size is 1
Source:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithFromEffectiveStartDateIfFromEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date fromEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withFromEffectiveStartDate(fromEffectiveStartDate) .build(); assertTrue(radiologyOrderSearchCriteria.getFromEffectiveStartDate() .equals(fromEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); }

Target:
@bgeVam assertThat(,is())
Source:
private void addDefaultProperties(DelegatingResourceDescription description) { description.addProperty("uuid"); description.addProperty("radiologyOrder", Representation.REF); description.addProperty("reportDate"); description.addProperty("reportStatus"); description.addProperty("reportBody"); description.addProperty("principalResultsInterpreter", Representation.REF); description.addProperty("display"); }

Target:
@Schwasrz94 move principalResultsInterpreter before reportStatus so we have same order as in the object itself: https://github.com/openmrs/openmrs-module-radiology/blob/master/api/src/main/java/org/openmrs/module/radiology/report/RadiologyReport.java
Source:
public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); assertThat(template.getDcTermsTitle(), is("title1")); }

Target:
@ivange94 remove assertion for title, just do the identifier
Source:
public String getReportTemplateHome() { Path templatesPath = Paths.get(getGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, true)); if (!templatesPath.isAbsolute()) { templatesPath = Paths.get(OpenmrsUtil.getApplicationDataDirectory(), templatesPath.toString()); } if (!templatesPath.toFile() .exists()) { templatesPath.toFile() .mkdirs(); } return templatesPath.toString(); }

Target:
@ivange94 why not return a java File ? you already ensure it exists and the GP_MRRT_REPORT_TEMPLATE_DIR is writable, return java file so the user of this method doesnt have to deal with some of the things you do here.
Source:
public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }

Target:
use final
Source:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenVisitIsNull() throws Exception { // given EncounterParameters encounterParameters = EncounterParameters.instance() .setEncounterType(radiologyProperties.getRadiologyOrderEncounterType()) .setEncounterUuid(VOIDED_ENCOUNTER_UUID); Visit visit = null; expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("visit is required"); radiologyEncounterMatcher.findEncounter(visit, encounterParameters); }

Target:
@bgeVam just inline null
Source:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenEncounterParametersIsNull() throws Exception { // given EncounterParameters encounterParameters = null; Visit visit = visitService.getVisit(VISIT_ID_WITH_VOIDED_ENCOUNTER); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("encounterParameters are required"); radiologyEncounterMatcher.findEncounter(visit, encounterParameters); }

Target:
@bgeVam just inline null
Source:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); else { if (this.radiologyProperties == null) return "http://localhost:8081/weasis-pacs-connector/viewer?" + "studyUID=" + study.getStudyInstanceUid(); else return this.radiologyProperties.getDicomViewerUrl() + "studyUID=" + study.getStudyInstanceUid(); } }

Target:
you shouldnt do that. hardcoding the URL here.
Source:
Study getMockStudy() throws Exception { Study mockStudy = new Study(); mockStudy.setStudyId(1); mockStudy.setStudyInstanceUid("1.2.826.0.1.3680043.8.2186.1.1"); return mockStudy; }

Target:
does this really need `throws Exception`
Source:
public void started() { try { startDicomOrderFiller(); } catch (Exception e) { // Just prints in console } typeAndRoles(); }

Target:
The try-catch block is redundant here, since the appropriate exceptions are caught and logged in the startDicomOrderFiller method
Source:
public void disableDarkTheme(boolean disabled) { darkThemeDisabled = disabled; }

Target:
Make this method `synchronized`.
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Boolean isDarkTheme = SalesforceSDKManager.getInstance().isDarkTheme(getActivity()); // Do not create a new Fragment when the Activity is re-created such as orientation changes. setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, (isDarkTheme ? R.style.SalesforceSDK_Dialog_Dark : R.style.SalesforceSDK_Dialog)); }

Target:
Lowercase `boolean` - use the primitive type.
Source:
public void storeMobilePolicyForOrg(UserAccount account, int timeout, int passLen) { if (account == null) { return; } final Context context = SalesforceSDKManager.getInstance().getAppContext(); final SharedPreferences sp = context.getSharedPreferences(MOBILE_POLICY_PREF + account.getOrgLevelFilenameSuffix(), Context.MODE_PRIVATE); final Editor e = sp.edit(); e.putInt(KEY_TIMEOUT, timeout); e.putInt(KEY_PASSCODE_LENGTH, passLen); e.commit(); }

Target:
<table data-meta="generated_by_SalesforceSDK"> <tbody> <tr> <td>:warning:</td> <td width="100%" data-sticky="false"><span data-href="https://github.com/forcedotcom/SalesforceMobileSDK-Android/blob/e8a63cd04088a6f062240bd7f6b8ab8629bcec98/libs/SalesforceSDK/src/com/salesforce/androidsdk/security/PasscodeManager.java#L195"></span>Consider using <code>apply()</code> instead; <code>commit</code> writes its data to persistent storage immediately, whereas <code>apply</code> will handle it in the background</td> </tr> </tbody> </table>
Source:
public static synchronized String getUniqueId(String name) { return getUniqueId(name, 256); }

Target:
Remove `synchronized` keyword from this method and move it to the method below.
Source:
public void tearDown() throws Exception { testContext = null; }

Target:
Don't you need a `super.tearDown()` call here at the end?
Source:
private void loadRemoteStartPage(boolean loadThroughFrontDoor) { assert !bootconfig.isLocal(); String startPage = bootconfig.getStartPage(); String url = startPage; if (loadThroughFrontDoor) { url = getFrontDoorUrl(url, false); } SalesforceHybridLogger.i(TAG, "loadRemoteStartPage called - loading: " + startPage); loadUrl(url); webAppLoaded = true; }

Target:
Minor: change this log line to `url` to correctly reflect the URL being loaded.
Source:
public static SmartSyncSDKManager getInstance() { if (INSTANCE != null) { SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_SMART_SYNC); return (SmartSyncSDKManager) INSTANCE; } else { throw new RuntimeException("Applications need to call SmartSyncSDKManager.init() first."); } }

Target:
Any app compiled with smartstore/smartsync will use SmartSyncSDKManager. Instead you should set that flag from SyncManager.java getInstance
Source:
private void removeAllGlobalStores(JSONArray args, CallbackContext callbackContext) throws JSONException { List<String> globalDBNames = SmartStoreSDKManager.getInstance().getGlobalStoresPrefixList(); for(String storeName : globalDBNames) { SmartStoreSDKManager.getInstance().removeGlobalSmartStore(storeName); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }

Target:
Should we have a removeAllGlobalStores method on SmartStoreSDKManager like we do on iOS?
Source:
public List<String> getGlobalStoresPrefixList() throws JSONException { UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; }

Target:
Should we call that method getGlobalStoreNames() instead?
Source:
public boolean loadSqlCipher(Context context) { try { loadLibs(context); } catch (UnsatisfiedLinkError ule) { // We are assuming the library loaded by sql cipher failed return extractAndLoadAgain(context, DATABASE_SQLCIPHER, getSupportedAbis()); } catch (Exception ex) { Log.e(TAG, "Error loading native libraries for Sqlcipher", ex); return false; } return true; }

Target:
This can be `static`.
Source:
public void loadLibs(Context context) throws UnsatisfiedLinkError { SQLiteDatabase.loadLibs(context); }

Target:
`static`.
Source:
public boolean canReadFile(File file) { return file.canRead(); }

Target:
`static`.
Source:
public String[] getSupportedAbis() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.SUPPORTED_ABIS.length > 0) { return Build.SUPPORTED_ABIS; } else { return new String[] { Build.CPU_ABI, Build.CPU_ABI2 }; } }

Target:
`static`.
Source:
protected void loadLibs(Context context) { new SqliteLibraryLoader().loadSqlCipher(context); }

Target:
Use `static` call. There's no need to instantiate this util class every time.
Source:
protected TokenEndpointResponse performRequest(LoginOptions options) throws Exception { try { return OAuth2.swapJWTForTokens(HttpAccess.DEFAULT, new URI(options.loginUrl), options.jwt); } catch (Exception e) { onAuthFlowError("jwt_oauth_error", e.getLocalizedMessage()); callback.finish(); } return null; }

Target:
We should remove `throws Exception` here, since we're catching it anyway and triggering `onAuthFlowError`.
Source:
public Bundle asBundle() { bundle.putString(JWT, jwt); //jwt can be updated during flow return bundle; }

Target:
I don't think we should muck around with this in this part.
Source:
public static TokenEndpointResponse swapJWTForTokens(HttpAccess httpAccessor, URI loginServerUrl, String jwt) throws IOException, URISyntaxException, OAuthFailedException { // call the token endpoint, and swap jwt for an access tokens. FormBody.Builder formBodyBuilder = new FormBody.Builder() .add(GRANT_TYPE, JWT_BEARER) .add(ASSERTION, jwt); TokenEndpointResponse tr = makeTokenEndpointRequest(httpAccessor, loginServerUrl, formBodyBuilder); return tr; }

Target:
`return` directly.
Source:
public void testResponseStreamIsReadable() throws Exception { final RestResponse response = getStreamTestResponse(); try (InputStream in = response.asInputStream()) { assertStreamTestResponseStreamIsValid(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } catch (JSONException e) { fail("Valid JSON data should have been returned"); } finally { response.consumeQuietly(); } }

Target:
@clibc I don't know if we enforce `Java 7` as a minimum, so it might be best to go with the `Java 6` syntax here.
Source:
public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); try { InputStream in = response.asInputStream() inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } // We read the entire stream but forgot to call consume() or consumeQuietly() - can another REST call be made? final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); }

Target:
Missing semi-colon at the end. No compilation error? ;-)
Source:
public UserAccount getCurrentUser() { final Account account = getCurrentAccount(); return account == null ? null : buildUserAccount(account); }

Target:
You don't need this. `buildUserAccount()` has a `null` check.
Source:
public String toString() { try { return asString(); } catch (Exception e) { Log.e("RestResponse: toString()", "Exception caught while calling asString()"); return ((response == null) ? "" : response.toString()); } }

Target:
Could you log the exception too: Log.e("RestResponse: toString()", "Exception caught while calling asString()", e);
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sf__inspector); smartStore = SalesforceSDKManagerWithSmartStore.getInstance() .getSmartStore(); queryText = (MultiAutoCompleteTextView) findViewById(R.id.sf__inspector_query_text); pageSizeText = (EditText) findViewById(R.id.sf__inspector_pagesize_text); pageIndexText = (EditText) findViewById(R.id.sf__inspector_pageindex_text); resultGrid = (GridView) findViewById(R.id.sf__inspector_result_grid); setupAutocomplete(queryText); }

Target:
You might want to move this call to `onResume()`. The reason is that, with fast user switching, if an account switch occurs, when you come back to this activity, you'll be stuck with a handle on the old SmartStore (the variable `smartStore` won't be updated).
Source:
public Op subtract(Op otherOp) { return new DoubleOp(this.val - ((DoubleOp)otherOp).val); }

Target:
Any reason for doing the instanceof check in add but not subtract?
Source:
public static DateTime weekFloor(DateTime dt) { DateTime startOfWeek = dt.minusDays(dt.getDayOfWeek() - 1); return dayFloor(dt).withYear(startOfWeek.getYear()) .withMonthOfYear(startOfWeek.getMonthOfYear()) .withDayOfMonth(startOfWeek.getDayOfMonth()); }

Target:
Having a hard time following this, can we just make it "return dayFloor(dt.minusDays(dt.getDayOfWeek() -1)"? Sorry if I'm being dense, but I can't understand the reason for the withMonth/withDay/withYear code.
Source:
public static void startRequestDetailActivity(Context ctx, Request request) { Intent i = ActivityUtil.newIntent(ctx, RequestDetailActivity.class); i.putExtra(RequestDetailActivity.REQUEST_ID, request.getObjectId()); i.putExtra(RequestDetailActivity.REQUEST_STATE, request.getState().toString()); ctx.startActivity(i); ActivityUtil.transitionRight((Activity)ctx); }

Target:
Why not just pass the enum, will that not work?
Source:
public ParseGeoPoint getLocation() { return (ParseGeoPoint) getClient().get("location"); }

Target:
Change to getParseGeoPoint("location") so we can get rid of this casting stuff?
Source:
public static UserFragment newInstance(String login) { UserFragment f = new UserFragment(); Bundle args = new Bundle(); args.putString(Constants.EXTRA_LOGIN, login); f.setArguments(args); return f; }

Target:
Keep extra in this file.
Source:
public void loadRepository(boolean refresh) { Consumer subscriber = repository -> { mRepository = (Repository) repository; updateTitle(); invalidateTabs(); // Apply initial page selection first time the repo is loaded if (mInitialPage >= PAGE_REPO_OVERVIEW && mInitialPage <= PAGE_ACTIVITY) { getPager().setCurrentItem(mInitialPage); mInitialPage = -1; } setContentShown(true); supportInvalidateOptionsMenu(); }; RepositoryService.loadRepository(this, mRepoOwner, mRepoName, refresh) .subscribe(subscriber, e -> {}); }

Target:
private Also, should put the 3 load methods in proximity to each other.
Source:
public void reloadData() { setContentShown(false); Log.d("TEST", "reloadData callleeeed"); loadReadme(true); loadPullRequestsCount(true); }

Target:
private
Source:
public static NotificationListFragment newInstance() { NotificationListFragment fragment = new NotificationListFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; }

Target:
This change isn't really needed, right?
Source:
protected void onInitExtras(Bundle extras) { super.onInitExtras(extras); mRepoOwner = extras.getString("owner"); mRepoName = extras.getString("repo"); mPullRequestNumber = extras.getInt("number"); mInitialCommentId = extras.getLong("initial_comment", -1); mInitialPage = extras.getInt("initial_page", -1); extras.remove("initial_comment"); extras.remove("target_screen"); }

Target:
Oops, right.
Source:
protected Fragment getFragment(int position) { final IssueMilestoneListFragment f = IssueMilestoneListFragment.newInstance(mRepoOwner, mRepoName, position == 1); if (position != 1) { mOpenFragment = f; } return f; }

Target:
if (position == 0) probably better expresses what this is about.
Source:
int read() { if (this.hasNext() == false) { throw new IllegalStateException("This stream hasn't any other value, all values were already read."); } int value = this.interval[nextPos]; this.nextPos++; return value; }

Target:
`if (!this.hasNext())`
Source:
public void testIntersectsOnGeometryCollection() { OGCGeometry ogcGeometry = OGCGeometry.fromText("GEOMETRYCOLLECTION (POINT (1 1))"); assertTrue(ogcGeometry.intersects(OGCGeometry.fromText("POINT (1 1)"))); }

Target:
I modified the test to ensure that if `intersects` is symmetrical and the test failed with NPE: ``` @Test public void testIntersectsOnGeometryCollection() { assertIntersects("GEOMETRYCOLLECTION (POINT (1 1))", "POINT (1 1)", true); } private void assertIntersects(String wkt, String otherWkt, boolean intersects) { assertEquals(OGCGeometry.fromText(wkt).intersects(OGCGeometry.fromText(otherWkt)), intersects); assertEquals(OGCGeometry.fromText(otherWkt).intersects(OGCGeometry.fromText(wkt)), intersects); } ``` Here is the failure: ``` java.lang.NullPointerException at com.esri.core.geometry.RelationalOperations.relate(RelationalOperations.java:45) at com.esri.core.geometry.OperatorDisjointLocal.execute(OperatorDisjointLocal.java:31) at com.esri.core.geometry.GeometryEngine.disjoint(GeometryEngine.java:376) at com.esri.core.geometry.ogc.OGCGeometry.disjoint(OGCGeometry.java:275) at com.esri.core.geometry.ogc.OGCGeometry.intersects(OGCGeometry.java:280) at com.esri.core.geometry.TestOGC.assertIntersects(TestOGC.java:1007) at com.esri.core.geometry.TestOGC.testIntersectsOnGeometryCollection(TestOGC.java:1001) ```
Source:
public Unit(String unitName, boolean enemy) { this(unitName, 1, enemy, GameController.getInstance().getUnitLife(unitName)); }

Target:
Que es este 1?