auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testInsertFirstAndAdd2() throws Exception { KieSession ksession = session.getStateful(); insertNotEvent(ksession); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isFalse(); insertNotEvent(ksession, "different value"); insertNotEvent(ksession, "different value"); insertNotEvent(ksession, "different value"); ksession.fireAllRules(); Assertions.assertThat(firedRules.isRuleFired(RULE1)).as(RULE1).isTrue(); }

Target:
Looks like a loop.
Source:
private boolean equalsIgnoreNull(Object o1, Object o2) { return o1 != null ? o1.equals(o2) : o2 != null; }

Target:
If the o1 is diff than null, o1 must equals o2. If the o1 is null, return "o2 is _diff than_ null" ? I think this second part is wrong?
Source:
public Object getResult(VarianceData data) { return new Double(data.squaredSum / data.count); }

Target:
new Double() is redundant here
Source:
public Object getResult(VarianceData data) { return new Double(Math.sqrt(data.squaredSum / data.count)); }

Target:
new Double is redundant here
Source:
private void startScanTask(long pollingInterval) { status = Status.RUNNING; this.pollingInterval = pollingInterval; timer = new Timer(true); timer.schedule(new ScanTask(this), pollingInterval, pollingInterval); }

Target:
ScanTask is a non-static inner class, so it already has a reference to this and it is not necessary to pass it.
Source:
private void logActiveFacts() { LOGGER.warn("facts: "); for (FactHandle handle : session.getFactHandles()) { LOGGER.warn(handle.toString()); } }

Target:
Again, could be a much nicer one-liner using Java 8 streams and/or `StringJoiner`.
Source:
@Override protected DataSource getDatasourceImpl( String dataSourceName ) throws Exception { IDBDatasourceService datasourceService = PentahoSystem.getObjectFactory().get( IDBDatasourceService.class, null ); return datasourceService.getDataSource( dataSourceName ); }

Target:
@jvelasques , Override is usually in the previous line
Source:
protected String getRequestParameterAsString( String parameter, String defaultValue, String encoding ) throws UnsupportedEncodingException { String enc = StringUtils.isEmpty( encoding ) ? CharsetHelper.getEncoding() : encoding; if( getRequestParameters() != null && getRequestParameters().hasParameter( parameter ) ){ return URLDecoder.decode( getRequestParameters().getStringParameter( parameter, defaultValue ) ); } return defaultValue; }

Target:
@pedrofvteixeira , enc is not being used in the decode call. Is that on purpose ?
Source:
public boolean supports(MediaType delimiter) { if (this.mediaTypes == null) { return true; } else { for (MediaType mediaType : this.mediaTypes) { if (mediaType.isCompatibleWith(delimiter)) { return true; } } return false; } }

Target:
This by definition will never happen, I think we have to check for an empty collection here.
Source:
public boolean advancePhase(float minWeight) { boolean changed = false; for (QueryTree child : children) { changed |= child.advancePhase(minWeight); } children.sort(Comparator.comparingDouble(QueryTree::weight)); return changed; }

Target:
If changed is false, do the children need to be resorted?
Source:
private DisjunctionNode(List<QueryTree> children) { this.children.addAll(children); this.children.sort(Comparator.comparingDouble(QueryTree::weight)); }

Target:
Instead of making new ArrayList in the class body, could move the new ArrayList to within constructor = this.children = new ArrayList<>(children) which would exactly size every time.
Source:
public List<String> getMetadataDatasourceIds() { List<String> metadataIds = new ArrayList<String>(); Set<String> domainIds = metadataDomainRepository.getDomainIds(); List<String> domainsIdArr = new ArrayList<>( domainIds ); for ( String id : domainsIdArr ) { if ( isMetadataDatasource( id ) ) { metadataIds.add( id ); } } return metadataIds; }

Target:
Why do this ? You can iterate over the set just fine - no need to copy it to an arraylist
Source:
public void removeDatasourceConfirm() { if ( messageBundle != null ) { XulLabel removeDatasourceConfirmationDialogLabel = (XulLabel) removeDatasourceConfirmationDialog.getElementById( "removeDatasourceConfirmationDialogLabel" ); LogicalModelSummary logicalModelSummary = getDialogResult(); removeDatasourceConfirmationDialogLabel.setValue( messageBundle.getString( REMOVE_DS_MSG_ID, logicalModelSummary.getModelName() ) ); } removeDatasourceConfirmationDialog.show(); }

Target:
This method happily returns null from time to time. Kaboom? And yeah, I know, that binding probably should not be active if there is no selection. But at the same time would it hurt to add a explicit if (datasourceSelectionDialogModel.getSelectedIndex() == -1) return; to the method to protect it?
Source:
public DatasourceService() { metadataDomainRepositoryReal = PentahoSystem.get( IMetadataDomainRepository.class, PentahoSessionHolder.getSession() ); metadataDomainRepository = new PentahoMetadataDomainRepository( getRepository() ); mondrianCatalogService = PentahoSystem.get( IMondrianCatalogService.class, PentahoSessionHolder.getSession() ); repositoryFileAclAdapter = new RepositoryFileAclAdapter(); }

Target:
We very rarely, almost never, directly construct an Implementation like this. What happens if an OEM has their own MetadataDomainRepository which needs to be used? A better solution is query for the "real" and the "plain" beans metadataDomainRepositoryReal = PentahoSystem.get( IMetadataDomainRepository.class, "IMetadataDomainRepositoryImpl", PentahoSessionHolder.getSession() ); metadataDomainRepository = PentahoSystem.get( IMetadataDomainRepository.class, "IMetadataDomainRepository", PentahoSessionHolder.getSession() );
Source:
private String getPropertySortOrder(Sort.Order order) { StringBuilder sb = new StringBuilder(); if(order.isIgnoreCase()){ sb.append("toLower(").append(order.getProperty()).append(")"); } else { sb.append(order.getProperty()); } sb.append(" ").append(order.getDirection()); return sb.toString(); }

Target:
```suggestion private static String getPropertySortOrder(Sort.Order order) { ```
Source:
private Filter createLowerBoundFilter(Object value, boolean inclusive) { Filter filter = createBoundFilter(Bound.LOWER, value, inclusive); filter.setBooleanOperator(booleanOperator); return filter; }

Target:
Can we pass on the operator on both of those (lower and upper)? The "and" is used for the boolean operator between previous and this or this and next?
Source:
private static DatabaseHolder createAndStartEmbeddedInstance() throws IOException { final File dataStore1 = Files.createTempDirectory("neo4j.db").toFile(); final GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(dataStore1) .newGraphDatabase(); return new DatabaseHolder(dataStore1, graphDatabaseService); }

Target:
Why `final` at variable level?
Source:
public List<Filter> build(Stack<Object> params) { final Object value = params.pop(); final Filter filter = new Filter(propertyName(), convertToComparisonOperator(part.getType()), value); filter.setOwnerEntityType(entityType); filter.setBooleanOperator(booleanOperator); filter.setNegated(isNegated()); setNestedAttributes(part, filter); applyCaseInsensitivityIfShouldIgnoreCase(part, filter); return Collections.singletonList(filter); }

Target:
We usually don `final` local variables.
Source:
private static void attachShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { LOGGER.info("JMXFetch is closing"); // Properly close log handlers LogManager.shutdown(); } } ); }

Target:
Definitely not! JMXFetch is known to have quite a bit of code that could use some cleanup, so this is definitely welcome.
Source:
public void displayMatchingAttributeName(JMXAttribute jmxAttribute, int rank, int limit) { LOGGER.debug(" Matching: " + rank + "/" + limit + ". " + jmxAttribute); }

Target:
These methods have associated commands in `datadog-agent` (stuff like `datadog-agent jmxfetch list-matching`) that is expected to print to stdout always, as it's a debugging command. These `LOGGER.debug` changes, unless I'm missing something, would make it subject to the log level, thus potentially breaking the agent commands. If we're going to keep this, it should probably be `info` or `warning` at the least - still maybe preferable to print to `stdout`.... 🤔
Source:
private String getCassandraAlias() { if (renameCassandraMetrics()) { Map<String, String> beanParameters = getBeanParameters(); String type = beanParameters.get("type"); String metricName = beanParameters.get("name"); String attributeName = getAttributeName(); if (attributeName.equals("Value")) { return "cassandra." + metricName; } return "cassandra." + metricName + "." + attributeName; } //Deprecated Cassandra metric. Remove domain prefix. return getDomain().replace("org.apache.", "") + "." + getAttributeName(); }

Target:
This variable is never used.
Source:
protected void sendMetricPoint(String metricName, double value, String[] tags) { if (System.currentTimeMillis() - this.initializationTime > 300 * 1000) { this.statsDClient.stop(); init(); } statsDClient.gauge(StatsdReporter.formatDataName(metricName), value, tags); }

Target:
`metricName` should be alias names defined in user configurations. I don't think we want/need to format it.
Source:
private void sendEvent(E e) { String message = _layout.doLayout(e); if (message == null) { throw new IllegalArgumentException(String.format( "The logback layout %s is probably incorrect, " + "and fails to format the message.", _layout.toString())); } this.sender.send( "", message, "", "", null, null, "" ); }

Target:
This looks a bit odd by passing in several empty args. Is there a better way of doing this?
Source:
protected BaseCommand(SelectedOptions selectedOptions) { this.options = selectedOptions; this.paths = selectedOptions.getPaths(); if (options.isQuiet()) { this.printStream = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { // throw away output } }); } }

Target:
There's a setter for the printstream. This should use that but also it's also interesting that this shows a design flaw that we could set the printstream and override the quiet option without knowing it.
Source:
public BitOutputStream(Object outputBase, long outputAddress, int outputSize) { checkArgument(outputSize >= SIZE_OF_LONG, "Output buffer too small"); this.outputBase = outputBase; container = 0; bitCount = 0; this.outputAddress = outputAddress; outputLimit = this.outputAddress + outputSize - SIZE_OF_LONG; currentAddress = this.outputAddress; }

Target:
Did you want to initialize these to Java defaults?
Source:
public int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) { int tableSize = computeTableSize(inputLength); Arrays.fill(table, 0, tableSize, 0); long inputAddress = ARRAY_BYTE_BASE_OFFSET + inputOffset; long outputAddress = ARRAY_BYTE_BASE_OFFSET + outputOffset; return Lz4RawCompressor.compress(input, inputAddress, inputLength, output, outputAddress, maxOutputLength, table, tableSize); }

Target:
I find it a bit strange that you calculate and initialize the table outside of the compressor instead of leaving these private details to the raw compressor code. It is also strange that there is a min table size but it is defined outside the compressor logic
Source:
public void readyToForward() { started = true; if(created.get() == 0) forward(); }

Target:
This needs to be synchronised, as otherwise threads might not see the updated value of 'started'.
Source:
private static Client setupClient(HttpClient httpClient, Duration timeout) { ReactorNettyClientHttpEngine engine = new ReactorNettyClientHttpEngine( httpClient, new DefaultChannelGroup(new DefaultEventExecutor()), HttpResources.get(), timeout); final ClientBuilder builder = ClientBuilder.newBuilder(); ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder)builder; clientBuilder.httpEngine(engine); return builder.build(); }

Target:
`final` please.
Source:
public Set<Class<?>> getProviderClasses() { if (providerClasses == null && parent != null) return parent.getProviderClasses(); if(initialized) { return providerClasses; } Set<Class<?>> set = new HashSet<Class<?>>(); if (parent != null) set.addAll(parent.getProviderClasses()); set.addAll(providerClasses); return set; }

Target:
I think you can remove the check
Source:
public static String createHeader(String username, String password) { StringBuffer buf = new StringBuffer(username); buf.append(':').append(password); return "Basic " + java.util.Base64.getEncoder().encodeToString(buf.toString().getBytes(StandardCharsets.UTF_8)); }

Target:
there is no need for using FQDN because only one Base64 is imported now
Source:
public boolean close(final long timeout, final TimeUnit unit) { internalClose(); try { // mimic executor.awaitTermination giving time for tasks to complete long duration = TimeUnit.MILLISECONDS.convert(timeout, unit); Thread.sleep(duration); } catch (InterruptedException e) { onErrorConsumers.forEach(consumer -> { consumer.accept(e); }); Thread.currentThread().interrupt(); return false; } return true; }

Target:
Is it possible to run internalClose() with schduleExecutor.scheduleWithFixedDelay() without thread.sleep? Is it better ?
Source:
public static String getTracingInfoFormat(HttpRequest request) { return getHeaderString(request, RESTEasyTracing.HEADER_ACCEPT_FORMAT); }

Target:
This would be better as package protected instead of public.
Source:
public Response register() throws Exception { ResteasyProviderFactory factory = ResteasyProviderFactory.newInstance(); factory.registerProviderInstance(paramConvertrProvider); factory.registerProviderInstance(exceptionMapper); return Response.ok("ok").build(); }

Target:
I have some doubts about the change here. In this case, the attempt is exactly to alter the current ResteasyProviderFactory instance (yes, I agree, that's not a best practice at all). By creating a new instance and not setting it in the singleton reference within ResteasyProviderFactory, you're altering the test. I suspect this is not spotted by Travis CI because the test here is likely not running due to the exclusions for RESTEASY-1935.
Source:
public boolean configure(FeatureContext context) { // this is tied to the deployment, which is what we want for the reactive context if(context.getConfiguration().getRuntimeType() == RuntimeType.CLIENT) return false; Dispatcher dispatcher = ResteasyProviderFactory.getContextData(Dispatcher.class); if(dispatcher == null) { System.err.println("Creating new context for "+context.getConfiguration().getRuntimeType()+" deployment because it looks like we're in a special thread"); return false; } dispatcher.getDefaultContextObjects().put(Context.class, new Context()); return true; }

Target:
This should probably be i18n log
Source:
public static void addToVisitedProcessors(String item) { visitedProcessors.add(item); }

Target:
Shouldn't this be synchronized?
Source:
public PostResourceMethodInvokers() { this.invokers = new LinkedHashSet<>(); }

Target:
Do we really need a Set internally relying on a Map here? Can't we simply have an ArrayList ? I don't think we really care about duplicates (it's really an internal abstraction), do we? Basically, I'd rather not affecting the memory footprint, considering this object is created for each invocation.
Source:
public void subscribe(@Context SseEventSink sink) throws IOException { synchronized (outputLock) { if (sink == null) { throw new IllegalStateException("No client connected."); } } eventSink = sink; //subscribe if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }

Target:
So, the line here above (eventSink = sink;) is really a bug fix, as it stores a reference to the sink in the resource, allowing the close() method to actually do something. Nice catch.
Source:
public void process(ClientInvocationBuilder invocation, Object param) { invocation.getInvocation().setEntity(Entity.entity(param == null? null : new GenericEntity<Object>(param, genericType), mediaType, annotations)) }

Target:
Missing ";" ... ;-)
Source:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(AtomProviderTest.class.getSimpleName()); war.addClass(AtomProviderTest.class); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new FilePermission("<<ALL FILES>>", "read"), new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader")), "permissions.xml"); return TestUtil.finishContainerPrepare(war, null, AtomProviderResource.class, AtomProviderCustomer.class, AtomProviderDataCollectionRecord.class, ObjectFactory.class); }

Target:
With https://github.com/resteasy/Resteasy/pull/1126 only permission `new RuntimePermission("accessDeclaredMembers"))` is required to make the test pass.
Source:
public static Archive<?> deploy_charset() { WebArchive war = TestUtil.prepareArchive(DefaultCharsetTest.class.getSimpleName() + "_true"); war.addAsWebInfResource(DefaultCharsetTest.class.getPackage(), "DefaultCharsetTestWeb_true.xml", "web.xml"); System.out.println(war.toString(true)); return TestUtil.finishContainerPrepare(war, null, DefaultCharsetResource.class); }

Target:
Not really a major problem, but can we get rid of System.out? :-)
Source:
public Response post(CharSetCustomer cust) throws UnsupportedEncodingException { logger.info(cust.getName()); String name = "bill\u00E9"; boolean equal = false; String test = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); if (test.compareTo(cust.getName()) == 0) { equal = true; } return equal ? Response.ok().build() : Response.serverError().build(); }

Target:
@CathrineTeng Please look at this.
Source:
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) { Object entity = responseContext.getEntity(); if (entity != null && entity instanceof String) { String tmpEscapedMsg = StringEscapeUtils.escapeXml((String) entity); String escapedMsg = tmpEscapedMsg.replaceAll("/", "&#x2F;"); responseContext.setEntity(escapedMsg); } } }

Target:
I've a minor (performance) concern here. By looking at the StringEscapeUtils code, in case of xml escape, what ends up being done is a 5 chars replacement (double-quote, ampersand, less-than, greater-than, xml apostrophe). The entity string is scanned linearly. Then we use String#replaceAll for the slash replacement, which builds up a pattern, matches on it and replaces. How about we manually create the Pattern, provide a regexp matching all 6 chars and perform the replacement with that? Alternatively, how about we do the linear string scan in our code and replace the 6 chars in the same pass ?
Source:
public OkCancelShell(String text) { super(ShellLookup.getInstance().getShell(text)); }

Target:
you can call just super(text), the same applies for constructor with matchers, and also the empty one
Source:
public void ok() { new OkButton(this).click(); new WaitWhile(new ShellIsAvailable(SHELL_TITLE)); new WaitWhile(new JobIsRunning(), TimePeriod.LONG, false); }

Target:
can you please also add method ok(TimePeriod waitForJobs). TimePeriod.LONG may not be enough for all cases
Source:
public boolean test() { shell = ShellLookup.getInstance().getCurrentActiveShell(); return shell != null ? true : false; }

Target:
there is no difference between shell != null and shell != null ? true : false. IMHO we have nothing to do here. We simply call SWT API and when it returns null active shell than we do not have a way to find out if really no shell is active
Source:
public LabeledText(ReferencedComposite referencedComposite, String label) { super(referencedComposite, 0, new WithLabelMatcher(new RegexMatcher(label + "\\s*\\**"))); }

Target:
I wouldnt use regex matcher inside this in this way. Because if a label contains a special char... it would not be matched properly.
Source:
default long getPriority() { return 1; }

Target:
value could be 0, as the default one. So other requirement could choose from positive range (to be executed sooner) or negative range (to be executed later) in comparison to default implementation.
Source:
public void addExecutedTest(Class<?> testClass) { System.out.println("Adding class with a run: " + testClass.getName()); addTest(testClass); executedTestClasses.add(testClass); }

Target:
logger
Source:
private boolean visible(final Widget w) { if (w.isDisposed()) return false; return Display.syncExec(new ResultRunnable<Boolean>() { @Override public Boolean run() { return !((w instanceof Control) && !((Control) w).getVisible()); } }); }

Target:
Use braces even if condition is one line
Source:
public boolean isVisible(Widget widget) { if (widget.isDisposed()) return false; boolean ret = true; Object o = null; try { o = ObjectUtil.invokeMethod(widget, "isVisible"); } catch (RuntimeException e) { throw new CoreLayerException( "Runtime error during checking widget visibility", e); } if (o instanceof Boolean) { ret = ((Boolean) o).booleanValue(); } return ret; }

Target:
Roll back those changes in handler. We do not check whether a widget is disposed in handler methods.
Source:
public ContentAssistant openContentAssistant(String assistantLabel) { activate(); log.info("Open editor's " + assistantLabel + " content assistant"); AbstractWait.sleep(TimePeriod.SHORT); Shell[] shells1 = ShellLookup.getInstance().getShells(); new ShellMenu("Edit", "Content Assist", assistantLabel).select(); ContentAssistantShellIsOpened caw = new ContentAssistantShellIsOpened( shells1); new WaitUntil(caw); return new ContentAssistant(caw.getContentAssistTable()); }

Target:
if I pass non-existing assistantLabel, I should get some meaningful exception like "Content assistant "+assistantLabel+ " does not exist". or another case is if assistantLabel is found but is disabled - "Content assistant "+assistantLabel+ " is disabled".
Source:
public void getAvailableContextAssistantTest(){ TextEditor javaTextEditor = TextEditorTest.openJavaFile(); assertFalse(javaTextEditor.getAvailableContentAssistants().isEmpty()); AbstractWait.sleep(TimePeriod.SHORT); }

Target:
why sleep ?
Source:
public void cleanup() { org.jboss.reddeer.common.util.Display.syncExec(new Runnable() { @Override public void run() { for (Shell shell : org.jboss.reddeer.common.util.Display.getDisplay().getShells()) { if (shell.getText().equals(title)) { shell.dispose(); break; } } new WaitWhile(new ShellWithTextIsAvailable(title)); } }); }

Target:
you have here waiting inside UI thread. It was done this way already but we can fix it, could you look at it?
Source:
public int getLineOfText(final String text) { return TextEditorHandler.getInstance().getLineOfText((ITextEditor)getEditorPart(), text); }

Target:
call getLineOfText(text,0) instead of TextEditorHandler...
Source:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } // do not exceed max value of Long if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { return Math.round(seconds * FACTOR); } }

Target:
Use this expression Math.round((double)seconds \* factor) otherwise round method will return Integer.MAX_VALUE for each input greater then Integer.MAX_VALUE. It's because input parameter for round method is evaluated to float and therefore it returns integer instead of long.
Source:
public ExactNumberOfProblemsExists(ProblemType type, int count) { if(type == null) { throw new NullPointerException("Problem Type cannot be null"); } if(count < 0) { throw new IllegalArgumentException("Number of problems must be greater than zero."); } this.problemType = type; this.expectedProblemsCount = count; matchers = new AbstractProblemMatcher[]{}; problemsView = new ProblemsView(); }

Target:
Call constructors in the other way around please: ExactNumberOfProblemsExists(ProblemType type, int count) should call this (type, count, new AbstractProblemMatcher[]{}) and all logic should be there. Use this. also for matchers field
Source:
private static RedDeerProperties getByName(String name){ RedDeerProperties rdProperty; try { rdProperty = RedDeerProperties.getByName(name); } catch (RedDeerException e) { rdProperty = RedDeerProperties.getByName("reddeer." + name); } return rdProperty; }

Target:
Do not use try catch please instead use if (!name.startsWith("reddeer.") ...
Source:
public void saveTask () { new ShellMenu("File", "Save").select(); new ShellMenu("File", "Properties").select(); new PushButton("OK").click(); }

Target:
I was not able to find any use case when File -> Save menu is enabled. So Im wondering if there's any ? Also at line 37 you are calling shell menu File -> Properties and then clicking on OK. This seems to be needless operation ..?
Source:
public void setNewHighScoreMode(boolean mode) { if (mode) { this.clearTouchAreas(); this.registerTouchArea(inputText); inputText.setVisible(true); inTopText.setVisible(true); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); } else { this.clearTouchAreas(); inputText.setVisible(false); inTopText.setVisible(false); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); } }

Target:
this.clearTouchAreas можно вынести из if и можно написать inputText.setVisible(mode) и по аналогии для других
Source:
private void fire() { Gun gun = activity.getSceneSwitcher().getGameScene().getGun(); activity.getSceneSwitcher().getGameScene().createTorpedo( gun.getShootStartPoint() , gun.getGunAngle()); }

Target:
я вообще думал, что выстрел будет делаться так gun.fire(); т.е. activity.getSceneSwitcher().getGameScene().createTorpedo( gun.getShootStartPoint(),gun.getGunAngle()); выполнять в методе класса Gun
Source:
private void stopGun() { Gun gun = activity.getSceneSwitcher().getGameScene().getGun(); gun.stopRotate(); }

Target:
Часто повторяется, лучше сделать метод getGun в классе SceletoneActivity или Events
Source:
public List<String> getLines() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); List<String> lines = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }

Target:
remove the explicit initialization?
Source:
private String readRequestToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringWriter writer = new StringWriter(); String line; while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { break; } writer.write(line); writer.write('\n'); } return writer.toString(); }

Target:
please dont remove explicit initialization
Source:
public String getContentAsString() { String content; try { final InputStream contentStream = Samples.class.getResourceAsStream(filePath); content = StreamUtils.readToString(contentStream, StreamUtils.UTF_8); } catch (Throwable e) { e.printStackTrace(); throw new RuntimeException("Could not read file " + filePath + ": " + e.getMessage()); } return content; }

Target:
please dont remove explicit initialization
Source:
public static List<String> getAllPaths(InputStream in) throws IOException { Assert.notNull(in); List<String> paths = new ArrayList<String>(); TarArchiveInputStream archiveIn = new TarArchiveInputStream(new GZIPInputStream(in)); try { for (ArchiveEntry nextEntry; (nextEntry = archiveIn.getNextEntry()) != null;) { paths.add(nextEntry.getName()); } return paths; } finally { StreamUtils.close(archiveIn); } }

Target:
please dont remove explicit initialization
Source:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { IDomain domain; try { // pre-condition domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); // operation domain.destroy(); // verification fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { // verification } }

Target:
please dont remove explicit initialization
Source:
private HttpServerFake startHttpServerFake(String statusLine) throws Exception { int port = new Random().nextInt(9 * 1024) + 1024; HttpServerFake serverFake; if (statusLine == null) { serverFake = new HttpServerFake(port); } else { serverFake = new HttpServerFake(port, null, statusLine); } serverFake.start(); return serverFake; }

Target:
please dont remove explicit initialization
Source:
public AbstractConnectionBuilder<CredentialsConnectionBuilder> credentials(String username, String password) { return new CredentialsConnectionBuilder(username, password, this.serverUrl); }

Target:
If we end up getting some config attributes from the express.conf we could overload this one and set the username ``` public AbstractConnectionBuilder<CredentialsConnectionBuilder> credentials(String password) { return new CredentialsConnectionBuilder(config.getRhLogin(), password, this.serverUrl); } ```
Source:
public List<String> getLines(Channel channel) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream(channel))); List<String> lines = new ArrayList<String>(); String line; // Read File Line By Line while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }

Target:
I doesnt really matter, just nitpicking: local vars are non-initialized. Good practice is to initialize them to a defined value. But sure, it doesnt matter here since the code right below will do it.
Source:
protected void updateEnvironmentVariables() throws OpenShiftException { if (!canGetEnvironmentVariables()) { return; } if (environmentVariablesMap == null) { environmentVariablesMap = loadEnvironmentVariables(); } else { environmentVariablesMap.clear(); environmentVariablesMap.putAll(loadEnvironmentVariables()); } }

Target:
here we're still checking for env map to be null, which is not possible any more, right (since you initialize it as empty map)?
Source:
private boolean isInPowerSaveMode() { PowerManager powerManager = (PowerManager) requireActivity().getSystemService(Context.POWER_SERVICE); if (powerManager != null) { return powerManager.isPowerSaveMode(); } else { return false; } }

Target:
It is simpler this way, don't you think? `return (powerManager != null) && powerManager.isPowerSaveMode();`
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActivity = this; generateAndStoreKey(); if (initCipher()) { mCryptoObject = new BiometricPrompt.CryptoObject(mCipher); } BiometricManager biometricManager = BiometricManager.from(this); switch (biometricManager.canAuthenticate()) { case BiometricManager.BIOMETRIC_SUCCESS: showBiometricPrompt(); break; default: authError(); } }

Target:
Use if instead of switch if there are only 2 options 👍
Source:
public boolean isBiometricEnabled() { SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.Companion.getAppContext()); return (appPrefs.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false)); }

Target:
It can be private
Source:
protected boolean isShowingOnlyAvailableOffline() { Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); }

Target:
protected not needed. Android Studio warns you about that. ![Screenshot 2019-03-13 at 17 28 17](https://user-images.githubusercontent.com/15261363/54296547-6ce73680-45b5-11e9-8e8c-d75d9fb39e68.png)
Source:
private void openHelp() { final String helpWeb = (String) getText(R.string.url_help); if (helpWeb != null && helpWeb.length() > 0) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(helpWeb)); startActivity(intent); } }

Target:
Do you really need this check?
Source:
public void onNewIntent(Intent intent) { super.onNewIntent(intent); // check if its a oauth SALS callback intent if(intent.getAction().equals(ACTION_VIEW) && intent.getData().getHost().equals("android.owncloud.com")) { getOAuth2AccessTokenFromCapturedRedirection(intent.getData()); } }

Target:
Isn't there a different way to get "android.owncloud.com" instead of using a hardcoded string?
Source:
public void onClick(View v) { if (v.getId() == R.id.upload_files_btn_cancel) { setResult(RESULT_CANCELED); finish(); } else if (v.getId() == R.id.upload_files_btn_upload) { new CheckAvailableSpaceTask().execute(); } }

Target:
Move this else if just after the } above
Source:
protected void onActivityResult(int requestCode,int resultCode,Intent capturedData){ if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){ Bundle capturedImageData = capturedData.getExtras(); Bitmap capturedImage = (Bitmap) capturedImageData.get("data"); Uri capturedImageUri = getImageUri(getApplicationContext(),capturedImage); capturedImagePath = getRealPathFromUri(capturedImageUri); new CheckAvailableSpaceTask().execute(); } else if(resultCode == RESULT_CANCELED){ setResult(RESULT_CANCELED); finish(); } }

Target:
Instead of declaring capturedImagePath as global, you can declare and initialize it here and pass it to CheckAvailableSpaceTask(), look the answer of [https://stackoverflow.com/questions/3075009/android-how-can-i-pass-parameters-to-asynctasks-onpreexecute/3077050](url)
Source:
public long getImposedExpirationDate () { long imposedExpirationDate = -1; if (mCapabilities.getFilesSharingPublicExpireDateEnforced().isTrue()) { imposedExpirationDate = DateUtils.addDaysToDate( new Date(), mCapabilities.getFilesSharingPublicExpireDateDays() ).getTime(); } return imposedExpirationDate; }

Target:
I would add a ```NULL``` check for ```mCapabilities``` to this condition.
Source:
public static boolean isNetworkActive(Context context) { boolean isNetworkActive = true; ConnectivityManager cm = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); // Check network availabality (no info object implies no connectivity) if (activeNetwork == null || (activeNetwork!= null && !activeNetwork.isConnectedOrConnecting())) { isNetworkActive = false; } return isNetworkActive; }

Target:
I would simplify to ```return (activeNetwork != null && activeNetwork.isConnectedOrConnecting())``` . No ```isActiveNetwork``` variable declared nor assigned, easier condition.
Source:
public void onResume() { super.onResume(); Log_OC.v(TAG, "onResume"); if ((Util.SDK_INT <= 23 || player == null)) { preparePlayer(); } }

Target:
Why the difference depending on API level? Just curious.
Source:
private void processStopFileRequest(Intent intent) { OCFile file = intent.getExtras().getParcelable(EXTRA_FILE); try { if(file.equals(mFile)) { processStopRequest(true); } } catch (NullPointerException e) { Log_OC.e(TAG, "NullPointerException while stopping on OCFile ", e); } }

Target:
In general, `NullPointerException`s shouldn't be cached - the input of the block should be tested to prevent it occurs.
Source:
public void onCheckedChanged(CompoundButton switchView, boolean isChecked) { if (!isResumed()) { // very important, setCheched(...) is called automatically during // Fragment recreation on device rotations return; } boolean permission; if (isChecked) { permission = true; } else { permission = false; } ((FileActivity) getActivity()).getFileOperationsHelper(). setUploadPermissionsToShare( mFile, permission ); ; // undo the toggle to grant the view will be correct if the dialog is cancelled switchView.setOnCheckedChangeListener(null); switchView.toggle(); switchView.setOnCheckedChangeListener(mOnEditPermissionInteractionListener); }

Target:
The value of `permission` may be set in a single line. Moreover, there is no real need of `permission`variable, `ìsChecked``may be used directly as parameter to pass to``setUploadPermissionsToShare``
Source:
public static ShareType getShareType(String authority) { if (sShareTypes.containsKey(authority)) { return sShareTypes.get(authority); } return null; }

Target:
This method may be written in a single line; check the reference for `HashMap#get`, it returns `null` if the key doesn't exist. http://developer.android.com/intl/es/reference/java/util/HashMap.html#get(java.lang.Object)
Source:
public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: finish(); break; default: Log_OC.w(TAG, "Unknown menu item triggered"); return false; } return true; }

Target:
You can early return here
Source:
public static void saveBooleanPreference(String key, boolean value, Context context) { SharedPreferences.Editor appPreferences = getDefaultSharedPreferences(context.getApplicationContext()).edit(); appPreferences.putBoolean(key, value); appPreferences.apply(); }

Target:
I think this and the next two methods should be `private`
Source:
protected RemoteOperationResult run(OwnCloudClient client) { GetRemoteCapabilitiesOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult result = getCapabilities.execute(client); if (result.isSuccess()){ // Read data from the result OCCapability capability = (OCCapability) result.getData().get(0); // Save the capabilities into database getStorageManager().saveCapabilities(capability); } return result; }

Target:
Didn't check the mplementation behind this, but would it make sense to null check result, result.getData() and result.getDate().get(0) is this null safe by design?
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); if (DisplayUtils.isGridView(directory, getStorageManager())){ switchToGridView(); } else { switchToListView(); } }

Target:
same code fragment as line 325ff
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); switchLayout(directory); }

Target:
Variable not used; please, remove this line.
Source:
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); mOptionsMenu = menu; MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); return true; }

Target:
Variable not used; please, remove this line.
Source:
public AuthenticatorAsyncTask(Activity activity) { mContext = activity.getApplicationContext(); mListener = new WeakReference<OnAuthenticatorTaskListener>((OnAuthenticatorTaskListener)activity); mActivity = activity; }

Target:
This attributie is not used, and not needed; please remove it.
Source:
public void cancel(Account account, OCFile file) { UploadFileOperation upload = null; synchronized (mPendingUploads) { upload = mPendingUploads.remove(buildRemoteName(account, file)); } if (upload != null) { mCurrentUpload.cancel(); } }

Target:
I'd say the change in this line is a mistake solving conflicts, right?
Source:
private void syncContents(OwnCloudClient client) { startDirectDownloads(); startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client); startContentSynchronizations(mFavouriteFilesToSyncContents, client); walkSubfolders(mFoldersToWalkDown, client); // this must be the last! }

Target:
Maybe, we can use directly mFoldersToWalkDown in walkSubfolders() without having to pass it
Source:
private static String getExtension(String filename) { String extension = filename.toLowerCase().substring(filename.lastIndexOf(".") + 1); return extension; }

Target:
I'd rather `toLowerCase()` is applied after `substring()`, not before.
Source:
public void onResume() { super.onResume(); Log_OC.e(TAG, "onResume"); loadAndShowTextPreview(); }

Target:
Please, don't reload the text in `onResume()`. Do it in `onCreateView()` or `onActivityCreated()`; `onPause()` and `onResume()` may be called when other windows partially hide the fragment (such as the menu showing apps to open the file outside of ownCloud) even though it stays visible.
Source:
public void setFooterView(View footer) { mList.addFooterView(footer); mList.invalidate(); }

Target:
Check that when user clicks on that item (the last one with the info), it is not highlighted as the others because, maybe, it is not a very good behaviour.
Source:
public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) { Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description); if (!failingUrl.equals(mLastReloadedUrlAtError)) { view.reload(); mLastReloadedUrlAtError = failingUrl; } else { mLastReloadedUrlAtError = null; } }

Target:
call super.onReceivedError();
Source:
public static void assertCompany(Company company) { assertBaseCompany(company, true); assertThat(company.headquarters).isNotNull(); assertThat(company.homepage).isNotNull(); assertThat(company.origin_country).isNotEmpty(); assertThat(company.origin_country).isNotEmpty(); if (company.parent_company != null) assertBaseCompany(company.parent_company, true); }

Target:
Any reason this is asserted twice?
Source:
public void test_upcoming() throws IOException { Call<MovieResultsPage> call = getUnauthenticatedInstance().moviesService().upcoming( null, "el" ); MovieResultsPage page = call.execute().body(); assertThat(page).isNotNull(); assertThat(page.results).isNotEmpty(); }

Target:
Any reason why you changed this from the default? If no, please revert.
Source:
public TDImportResult importBytes(String databaseName, String tableName, byte[] content) { return doPut(buildUrl(String.format("/v3/table/import/%s/%s/%s", databaseName, tableName, "msgpack.gz")), ImmutableMap.of(), content, TDImportResult.class); }

Target:
Should we support offset and length arguments as well?
Source:
public static Properties readTDConf() { Properties p = new Properties(); File file = new File(System.getProperty("user.home", "./"), String.format(".td/td.conf")); if (!file.exists()) { logger.debug(String.format("config file %s is not found", file)); return p; } return readTDConf(file); }

Target:
Since this method is designed to read `$HOME/.td/td.conf`, it is better to print the warning in case of file not found.
Source:
public static <T> void checkPresence(Optional<T> opt, String errorMessage) { if (!opt.isPresent()) { throw new TDClientException(TDClientException.ErrorType.INVALID_INPUT, errorMessage); } }

Target:
Should this method be private?
Source:
private static String validateTableName(String tableName) { return validateName(tableName, "Table"); }

Target:
Why is the modifier private? We should set same modifiers to validateDatabaseName and validateTableNamet methods.
Source:
public StubSchemaManagementWorkAssert matches(StubSchemaManagementWork expected) { ToStringTreeBuilder builder = new ToStringTreeBuilder( ToStringStyle.multilineDelimiterStructure() ); builder.startObject(); boolean hasAnyMismatch; boolean mismatch = checkForMismatch( builder, "type", expected.getType(), actual.getType() ); hasAnyMismatch = mismatch; builder.endObject(); if ( hasAnyMismatch ) { Assert.fail( messageBase + builder.toString() ); } return this; }

Target:
Do we need the `mismatch` variable? Shouldn't we assign the result of checkForMismatch directly to `hasAnyMismatch`?
Source:
public void setup() { setupHelper.start( BACKEND_1_NAME ) .withBackendProperty( BACKEND_1_NAME, "directory.type", directoryType ) .withIndex( INDEX_NAME_1_1, ctx -> this.indexMapping_1_1 = new IndexMapping_1_1( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_1 = indexMapping ) .withIndex( INDEX_NAME_1_2, ctx -> this.indexMapping_1_2 = new IndexMapping_1_2( ctx.getSchemaElement() ), indexMapping -> this.indexManager_1_2 = indexMapping ) .setup(); initData(); }

Target:
You no longer need to define and pass a backend name. You can call `start()` and `withBackendProperty( "directory.type", directoryType )`.
Source:
void closeOnFailure() { try ( Closer<RuntimeException> closer = new Closer<>() ) { closer.push( IdentifierMappingImplementor::close, identifierMapping ); closer.push( RoutingKeyProvider::close, routingKeyProvider ); closer.push( BeanHolder::close, providedIdentifierBridgeHolder ); } }

Target:
I don't think you need this, as `identifierMapping.close()` (above) will effectively close the bridge, and it's very unlikely (impossible?) that a failure occurs between the assignment of `providedIdentifierBridgeHolder` and the assignment of `identifierMapping`. So, to clarify: you can remove `providedIdentifierBridgeHolder` and use a local variable instead, then remove this line.
Source:
public void handle(FailureContext context) { // <1> try { String failingOperationDescription = context.getFailingOperation().toString(); // <2> Throwable throwable = context.getThrowable(); // <3> // ... report the failure ... // <4> } catch (Throwable t) { // ... handle the failure and do *not* propagate the throwable ... // <5> } }

Target:
Why leave the burden of capturing the exception to the user?
Source:
public boolean hasCompatibleAnalyzer(ElasticsearchFieldPredicateBuilderFactory other) { if ( !getClass().equals( other.getClass() ) ) { return false; } ElasticsearchTextFieldPredicateBuilderFactory castedOther = (ElasticsearchTextFieldPredicateBuilderFactory) other; return Objects.equals( analyzer, castedOther.analyzer ) && Objects.equals( searchAnalyzer, castedOther.searchAnalyzer ) && Objects.equals( normalizer, castedOther.normalizer ); }

Target:
If the search analyzers are the same but the analyzers are different, this should return true, I think. And the tests should probably reflect that... ? In fact, you could solve this easily by only keeping the search analyzer in this class, and using the analyzer as a default when the search analyzer is `null`.
Source:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } // java.sql.Date does not support toInstant(). See HSEARCH-3670. // We're using here the same strategy applied on DefaultJavaSqlDateValueBridge to handle them. return value instanceof java.sql.Date ? Instant.ofEpochMilli( value.getTime() ) : value.toInstant(); }

Target:
Couldn't we always use `Instant.ofEpochMilli( value.getTime() )`? That would spare us one `instanceof`.
Source:
void process() { sendCommandsToDelegate(); getDelegate().prepare(); }

Target:
Is there a reason to use `process` at mapper level and `prepare` at engine/backend level?
Source:
public SortField customType() { BytesRef byteRefMissingValue = new BytesRef( missingValue.toString() ); return new SortField( absoluteFieldPath, new LuceneMissingValueComparatorSource( byteRefMissingValue ), order == SortOrder.DESC ); }

Target:
I'd rather use `(String) missingValue` than `missingValue.toString()`. That way, if we ever end up with anything else than a `String` here, it will fail and we will know something is wrong. But more to the point... You could just make `org.hibernate.search.backend.lucene.types.sort.impl.LuceneTextFieldSortBuilder#encodeMissingAs` return the `BytesRef` directly. Right now `encodeMissingAs` method converts the `BytesRef` to a `String`, then `customType` converts it back to a `BytesRef`. And as far as I can tell, only `customType` uses the value, since the call to `setEffectiveMissingValue` will only ever happen if `missingValue` is `null` or `SortMissingValue.MISSING_FIRST` or `SortMissingValue.MISSING_LAST`.
Source:
public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); //Needs to have a timeout higher than zero to prevent race conditions over (network) RPCs //for distributed indexes (Infinispan but probably also NFS and similar) SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString() ); } }

Target:
I'm not sure that the parameter `eventContext` is used in the method body.
Source:
public Integer getScalingFactor() { return scalingFactor; }

Target:
I think I mentioned that: there should be a new test regarding validation of this attribute in `ElasticsearchSchemaAttributeValidationIT`. Unless I missed it, there isn't any?