Categories
discuss

ESLint no output

I’m trying to get started using ESLint from this tutorial: https://davidwalsh.name/eslint

I’ve copied the example file. When I run eslint uploader.js in its directory, nothing happens – there is a line break, and then the prompt returns. No output at all.

I’ve run it on a JSON file in the same directory, and used a Grunt task to run it on all JS files project wide. These return a few errors, but nothing near what I’m expecting.

When I run eslint on the command line, it acts as expected – returning arguments and options documentation. I’ve tried rebooting the instance, reinstalling ESLint, intentionally introducing egrigious errors into uploader.js, but nothing happens, much less the output displayed in the tutorial. Can someone help?

Answer

Starting from version 1.0.0 of ESLint, all linting rules are turned off by default.

That tutorial was written before this version, which would have expected some errors to show up without a configuration file. The official website provides a migration guide. In your case, you may wish to extend your “.eslintrc” file with “eslint:recommended” throughout that tutorial (or simply include the intended rules manually). Here’s the closest you can get from the previous versions, according to the guide:

{
    "extends": "eslint:recommended",
    "rules": {
        "no-alert": 2,
        "no-array-constructor": 2,
        "no-caller": 2,
        "no-catch-shadow": 2,
        "no-empty-label": 2,
        "no-eval": 2,
        "no-extend-native": 2,
        "no-extra-bind": 2,
        "no-implied-eval": 2,
        "no-iterator": 2,
        "no-label-var": 2,
        "no-labels": 2,
        "no-lone-blocks": 2,
        "no-loop-func": 2,
        "no-multi-spaces": 2,
        "no-multi-str": 2,
        "no-native-reassign": 2,
        "no-new": 2,
        "no-new-func": 2,
        "no-new-object": 2,
        "no-new-wrappers": 2,
        "no-octal-escape": 2,
        "no-process-exit": 2,
        "no-proto": 2,
        "no-return-assign": 2,
        "no-script-url": 2,
        "no-sequences": 2,
        "no-shadow": 2,
        "no-shadow-restricted-names": 2,
        "no-spaced-func": 2,
        "no-trailing-spaces": 2,
        "no-undef-init": 2,
        "no-underscore-dangle": 2,
        "no-unused-expressions": 2,
        "no-use-before-define": 2,
        "no-with": 2,
        "camelcase": 2,
        "comma-spacing": 2,
        "consistent-return": 2,
        "curly": [2, "all"],
        "dot-notation": [2, { "allowKeywords": true }],
        "eol-last": 2,
        "no-extra-parens": [2, "functions"],
        "eqeqeq": 2,
        "key-spacing": [2, { "beforeColon": false, "afterColon": true }],
        "new-cap": 2,
        "new-parens": 2,
        "quotes": [2, "double"],
        "semi": 2,
        "semi-spacing": [2, {"before": false, "after": true}],
        "space-infix-ops": 2,
        "space-return-throw-case": 2,
        "space-unary-ops": [2, { "words": true, "nonwords": false }],
        "strict": [2, "function"],
        "yoda": [2, "never"]
    }
}

Since version 3.0.0, ESLint will refuse to work without a configuration file, printing an error message instead. This will hopefully prevent people from running into this issue.

Categories
discuss

React-leaflet bounds

Right now I am setting the bounds of my react leaflet map by passing a bounds parameter as shown below:

   <div hidden={!this.props.hide && !this.props.toggle} className="map-container">

       <Leaflet.Map ref='leaflet-map' bounds={ this.getBounds()} >

       <Leaflet.TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'/>

             { this.geoResults().map(this.renderMarker) }


       </Leaflet.Map>

   </div>

The problem is that sometimes a marker is rendered on the outermost part of the map (in view) so the marker is not even visible unless I drag the map or zoom out one spot. I was trying to fix this with a buffer or trying to plot the bounds then use zoom to zoom out once but nothing seems to work. Do you guys have any ideas?

Answer

Solution

You can use boundsOptions attribute of the Map component to pass options to the leaflet’s fitBounds() method. In those options you can define padding for example to “pad” the bounds.

From react-leaflet Map documentation:

boundsOptions: object (optional): Options passed to the fitBounds() method.

From leaflet fitBounds options documentation:

padding: Equivalent of setting both top left and bottom right padding to the same value.

Example

So something like this should work (didn’t test in action):

<Leaflet.Map
  ref='leaflet-map'
  bounds={this.getBounds()}
  boundsOptions={{padding: [50, 50]}}
/>

Defining your Map element like that should pad the bounds. Tune the padding values to suite your needs.

Another approach

You could add padding to the bounds in your getBounds() function.

Categories
discuss

How to animate full screen stripes moving from left to right

I would like to create an animation but I don’t know how to get started with it. Here‘s this image.

I want the red and with stripes to animate from left to right. (Translate)Animations are not new to me. Moving an object on the screen is easy, because we have a background behind it. In my case it’s the background that should be moving.

If I use an image then there will be no way to fill the empty space the image leaves behind while moving to the right. One idea is to fill the screen initially with the stripes programmatically, start moving them from left to right and when one starts leaving the screen then draw a new line on the left but considering the stripes are not 1px wide I don’t know how to do this.

Another way would be to use an image that is wider by 2 stripes than the screen. The 2 stripes are invisible on the left. Once the image is moved to the right (end of animation), we restart the animation. I wonder if that would cause any interruption or will it look like smooth to the user.

Any ideas? Should I use andengine or something similar for this?

Answer

You can use a custom drawable that just draws rectangles to the canvas. Following is a basic sample, just use it like

BackgroundDrawable bg = new BackgroundDrawable();
anyView.setBackground(bg);
bg.start();

Here is the basic working implementation:

public class BackgroundDrawable extends Drawable implements Runnable, Animatable {
    private static final long FRAME_DELAY = 1000 / 60;
    private boolean mRunning = false;
    private long mStartTime;
    private int mDuration = 1000;

    private Paint mPaint;
    private int mStripes = 7;


    private void init() {
        if (mPaint == null) {
            mPaint = new Paint();
            mPaint.setColor(Color.WHITE);
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.FILL);
        }
    }

    @Override
    public void draw(Canvas canvas) {
        Rect bounds = getBounds();
        if (isRunning()) {
            // animation in progress
            final int save = canvas.save();

            long timeDiff = SystemClock.uptimeMillis() - mStartTime;
            canvas.clipRect(bounds);

            float progress = ((float) timeDiff) / ((float) mDuration); // 0..1

            float width = bounds.width() / (mStripes * 2);

            for (int i = 0; i < mStripes * 2 + 2; i++) {
                mPaint.setColor(i % 2 == 0 ? Color.RED : Color.WHITE);
                canvas.drawRect(bounds.left + width * (i - 1) + progress * 2 * width, bounds.top, bounds.left + width * i + progress * 2* width, bounds.bottom, mPaint);
            }

            canvas.restoreToCount(save);
        } else {
            // todo draw normal
        }
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        super.setBounds(left, top, right, bottom);
        init();
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return 0;
    }

    @Override
    public void start() {
        if (mRunning) stop();
        mRunning = true;
        mStartTime = SystemClock.uptimeMillis();
        invalidateSelf();
        scheduleSelf(this, SystemClock.uptimeMillis() + FRAME_DELAY);
    }

    @Override
    public void stop() {
        unscheduleSelf(this);
        mRunning = false;
    }

    @Override
    public boolean isRunning() {
        return mRunning;
    }

    @Override
    public void run() {
        invalidateSelf();
        long uptimeMillis = SystemClock.uptimeMillis();
        if (uptimeMillis + FRAME_DELAY < mStartTime + mDuration) {
            scheduleSelf(this, uptimeMillis + FRAME_DELAY);
        } else {
            mRunning = false;
            start();
        }
    }
}

Also, I wrote a detailed explanation on drawables and basic animation handling here: Custom drawables and animations.

Categories
discuss

List of devices on which Renderscript doesn’t work

My app needs Renderscript since it performs some image processing that would take several seconds in Java. Before publishing I have tested it on a number of devices, even some older models (e.g. Samsung Galaxy Tab 2, API 17), and the app worked quite well, even on these devices. From this, I didn’t see a reason to set the minimum API higher than 17. Now, some weeks after publishing on Google Play I see that the app crashes on certain devices such as Galaxy S3 (m0) with API 17 or Galaxy S3 Mini Value Edition (goldenvess3g) with API 18.

 android.support.v8.renderscript.s: Error loading RS jni library: java.lang.UnsatisfiedLinkError: unknown failure

As such that is not surprising, since I knew about certain processor types that do not support Renderscript or other device specific issues that can cause problems. Questions:

  1. Is there a (approximative) way to find out, which of the 6’811 Android devices with API >= 17 do NOT support Renderscript? For example based on the terms in brackets (m0, goldenvess3g) which are possibly related to processor types? If so, I could exclude these devices on Google Play.
  2. If there is no such possibility, would you recommend to set minimum API higher, e.g. API 19? Sounds naive, but I didn’t find consistent info on this.

Thanks a lot for your feedback.

Answer

According to android.renderscript documentation, it is available since API level 11. Since your min API level is 17, I would recommend to use it instead of android.support.v8.renderscript.

Support library APIs are meant to be used if one is targeting devices running lower versions of Android, which, apparently, is not the case for you.

Categories
discuss

What Java 8 Stream.collect equivalents are available in the standard Kotlin library?

In Java 8, there is Stream.collect which allows aggregations on collections. In Kotlin, this does not exist in the same way, other than maybe as a collection of extension functions in the stdlib. But it isn’t clear what the equivalences are for different use cases.

For example, at the top of the JavaDoc for Collectors are examples written for Java 8, and when porting them to Kolin you can’t use the Java 8 classes when on a different JDK version, so likely they should be written differently.

In terms of resources online showing examples of Kotlin collections, they are typically trivial and don’t really compare to the same use cases. What are good examples that really match the cases such as documented for Java 8 Stream.collect? The list there is:

  • Accumulate names into a List
  • Accumulate names into a TreeSet
  • Convert elements to strings and concatenate them, separated by commas
  • Compute sum of salaries of employee
  • Group employees by department
  • Compute sum of salaries by department
  • Partition students into passing and failing

With details in the JavaDoc linked above.

Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin topics are present in SO. Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.

Answer

There are functions in the Kotlin stdlib for average, count, distinct,filtering, finding, grouping, joining, mapping, min, max, partitioning, slicing, sorting, summing, to/from arrays, to/from lists, to/from maps, union, co-iteration, all the functional paradigms, and more. So you can use those to create little 1-liners and there is no need to use the more complicated syntax of Java 8.

I think the only thing missing from the built-in Java 8 Collectors class is summarization (but in another answer to this question is a simple solution).

One thing missing from both is batching by count, which is seen in another Stack Overflow answer and has a simple answer as well. Another interesting case is this one also from Stack Overflow: Idiomatic way to spilt sequence into three lists using Kotlin. And if you want to create something like Stream.collect for another purpose, see Custom Stream.collect in Kotlin

EDIT 11.08.2017: Chunked/windowed collection operations were added in kotlin 1.2 M2, see https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-2-m2-is-out/


It is always good to explore the API Reference for kotlin.collections as a whole before creating new functions that might already exist there.

Here are some conversions from Java 8 Stream.collect examples to the equivalent in Kotlin:

Accumulate names into a List

// Java:  
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
// Kotlin:
val list = people.map { it.name }  // toList() not needed

Convert elements to strings and concatenate them, separated by commas

// Java:
String joined = things.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining(", "));
// Kotlin:
val joined = things.joinToString(", ")

Compute sum of salaries of employee

// Java:
int total = employees.stream()
                      .collect(Collectors.summingInt(Employee::getSalary)));
// Kotlin:
val total = employees.sumBy { it.salary }

Group employees by department

// Java:
Map<Department, List<Employee>> byDept
     = employees.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment));
// Kotlin:
val byDept = employees.groupBy { it.department }

Compute sum of salaries by department

// Java:
Map<Department, Integer> totalByDept
     = employees.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment,
                     Collectors.summingInt(Employee::getSalary)));
// Kotlin:
val totalByDept = employees.groupBy { it.dept }.mapValues { it.value.sumBy { it.salary }}

Partition students into passing and failing

// Java:
Map<Boolean, List<Student>> passingFailing =
     students.stream()
             .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
// Kotlin:
val passingFailing = students.partition { it.grade >= PASS_THRESHOLD }

Names of male members

// Java:
List<String> namesOfMaleMembers = roster
    .stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .map(p -> p.getName())
    .collect(Collectors.toList());
// Kotlin:
val namesOfMaleMembers = roster.filter { it.gender == Person.Sex.MALE }.map { it.name }

Group names of members in roster by gender

// Java:
Map<Person.Sex, List<String>> namesByGender =
      roster.stream().collect(
        Collectors.groupingBy(
            Person::getGender,                      
            Collectors.mapping(
                Person::getName,
                Collectors.toList())));
// Kotlin:
val namesByGender = roster.groupBy { it.gender }.mapValues { it.value.map { it.name } }   

Filter a list to another list

// Java:
List<String> filtered = items.stream()
    .filter( item -> item.startsWith("o") )
    .collect(Collectors.toList());
// Kotlin:
val filtered = items.filter { it.startsWith('o') } 

Finding shortest string a list

// Java:
String shortest = items.stream()
    .min(Comparator.comparing(item -> item.length()))
    .get();
// Kotlin:
val shortest = items.minBy { it.length }

Counting items in a list after filter is applied

// Java:
long count = items.stream().filter( item -> item.startsWith("t")).count();
// Kotlin:
val count = items.filter { it.startsWith('t') }.size
// but better to not filter, but count with a predicate
val count = items.count { it.startsWith('t') }

and on it goes… In all cases, no special fold, reduce, or other functionality was required to mimic Stream.collect. If you have further use cases, add them in comments and we can see!

About laziness

If you want to lazy process a chain, you can convert to a Sequence using asSequence() before the chain. At the end of the chain of functions, you usually end up with a Sequence as well. Then you can use toList(), toSet(), toMap() or some other function to materialize the Sequence at the end.

// switch to and from lazy
val someList = items.asSequence().filter { ... }.take(10).map { ... }.toList()

// switch to lazy, but sorted() brings us out again at the end
val someList = items.asSequence().filter { ... }.take(10).map { ... }.sorted()

Why are there no Types?!?

You will notice the Kotlin examples do not specify the types. This is because Kotlin has full type inference and is completely type safe at compile time. More so than Java because it also has nullable types and can help prevent the dreaded NPE. So this in Kotlin:

val someList = people.filter { it.age <= 30 }.map { it.name }

is the same as:

val someList: List<String> = people.filter { it.age <= 30 }.map { it.name }

Because Kotlin knows what people is, and that people.age is Int therefore the filter expression only allows comparison to an Int, and that people.name is a String therefore the map step produces a List<String> (readonly List of String).

Now, if people were possibly null, as-in a List<People>? then:

val someList = people?.filter { it.age <= 30 }?.map { it.name }

Returns a List<String>? that would need to be null checked (or use one of the other Kotlin operators for nullable values, see this Kotlin idiomatic way to deal with nullable values and also Idiomatic way of handling nullable or empty list in Kotlin)

See also:

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..