Categories
discuss

How to delete local file with fs.unlink?

CODE:

fs.unlink("/public/images/uploads/"+req.file.filename, (err) => {
        if (err) {
            console.log("failed to delete local image:"+err);
        } else {
            console.log('successfully deleted local image');                                
        }
});

ERROR MESSAGE IN CONSOLE/TERMINAL:

failed to delete local image:Error: ENOENT: no such file or directory, unlink '/public/images/uploads/ed6d810405e42d0dfd03d7668e356db3'

SITUATION

I must have specified the wrong path. I don’t understand why it would be wrong, the “public” folder is at the same level as the “app.js” file. The “upload.js” is in a folder called “routes” which is at the same level as “app.js“.

And I have specified a route “/public” to my public folder in my app.js:

//Static Folder
app.use("/public",express.static(path.join(__dirname, "/public")));

QUESTION:

What have I done wrong ?

Answer

I bet you want to delete file inside project directory. Try with this (dot before “/”):

fs.unlink("./public/images/uploads/"+req.file.filename, (err) => {
        if (err) {
            console.log("failed to delete local image:"+err);
        } else {
            console.log('successfully deleted local image');                                
        }
});
Categories
discuss

Is my leakcanary working? How to know?

I believe to have successfully installed LeakCanary.

I added the debug, release, and test dependencies to the build.gradle file.

I added the necessary files to my Application Class. Imported as necessary. Confirmed the application class is properly added to manifest. Does my application class need to be explicitly called?

<application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"

I run my app on the emulator and don’t see anything different. I monitor the Android Monitor and don’t see any difference. How do I know if it’s all working? I’ve shared my Application class.

import android.app.Application;
import android.content.res.Configuration;
import com.squareup.leakcanary.LeakCanary;

public class MyApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();

    if (LeakCanary.isInAnalyzerProcess(this)) {
        return;
    }
    LeakCanary.install(this);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

@Override
public void onLowMemory() {
    super.onLowMemory();
}

}

Answer

Does my application class need to be explicitly called?

No.

How do I know if it’s all working?

Leak something intentionally. For example, assign your launcher activity instance to a static field.

Categories
discuss

invalid escape in pattern HTML/Javascript

I am trying to make an <input> field that uses a pattern to check if the input is a valid windows file path.

The pattern I have is

/^(?:[w]:|\)(\[a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$/g

However, when putting this into the pattern attribute of an <input> field:

<input id="path" type="text" pattern="^(?:[w]:|)([a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$">

An error is displayed in the console saying:

Pattern attribute value
^(?:[w]:|\)(\[a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$ is
not a valid regular expression:  Uncaught SyntaxError: Invalid regular
expression: /^(?:[w]:|\)(\[a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$/:
Invalid escape

I have tried several ways of writing this pattern, but none seem to work.

Answer

You only need to escape the characters in the character class that must be escaped otherwise, you will always get this error.

Use

pattern="(?:w:|\)(\[ws.()~!@#$%^&=+';,{}[]-]+)+.exe"

See the JSFiddle

Details:

  • The hyphen must be at the end of the character class
  • The ] inside the character class must be escaped
  • The [ and . must not be escaped
  • The : must never be esacaped, it is never a special character
  • [a-zA-Z0-9_] = w
  • The pattern is always anchored by default, you need no ^ and $ anchors.
Categories
discuss

Deserialization of JavaScript array to Java LinkedHashSet using Jackson and Spring doesn’t remove duplicates

Let’s say I have this client-side JSON input:

{
   id: "5",
   types: [
      {id: "1", types:[]},
      {id: "2", types:[]},
      {id: "1", types[]}
   ]
}

I have this class:

class Entity {
    private String id;
    private Set<Entity> types = new LinkedHashSet<>();

    public String getId() {
        return this.id;
    }

    public String setId(String id) {
        this.id = id;
    }

    public Set<Entity> getTypes() {
        return types;
    }

    @JsonDeserialize(as=LinkedHashSet.class)
    public void setTypes(Set<Entity> types) {
        this.types = types;
    }

    @Override
    public boolean equals(Object o){
        if (o == null || !(o instanceof Entity)){
            return false;
        }
        return this.getId().equals(((Entity)o).getId());
    }
}

I have this Java Spring endpoint where I pass the input in the body of a POST request:

@RequestMapping(value = "api/entity", method = RequestMethod.POST)
public Entity createEntity(@RequestBody final Entity in) {
    Set<Entity> types = in.getTypes();
    [...]
}

I would like in:

Set<Entity> types = in.getTypes();

to have only two entries in the correct order… since one of them is a duplicate based on the id… Instead I get duplicates in the LinkedHashSet (!)

I thought from the code I have that removing duplicates would work automatically, but apparently it is not.

This question has a broader context than Why do I need to override the equals and hashCode methods in Java? since it is using implicit Jackson serialization through Java Spring.

Answer

Only overriding equals method will not work because hash-based collections use both the equals and hashCode method to see if two objects are the same. You’ll need to override hashCode() method in Entity class as both hashCode() and equals() method are required to be properly implemented to work with Hash based collections.

If your requirement is that if the some or all of the fields of two objects of the Entity class are same, then the two objects are to be considered equivalent, in that case, you’ll have to override both equals() and hashCode() method.

For e.g. – if only id field in the Entity class is required to determine if the two objects are equal, then you’ll override equals(), something like this:

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o instanceof Entity){
        Entity that = (Entity) o;
        return this.id == null ? that.id == null : this.id.equals(that.id);
    }
    return false;

}

but along with it, the hashCode() method need to be overridden in a way to produce same hashcode if id has the same value, maybe something like this:

@Override
public int hashCode() {
    int h = 17;
    h = h * 31 + id == null ? 0 : id.hashCode();
    return h;
}

Only now it’ll work properly with Hash based collections, as both these methods are used to identify an object uniquely.


More on this:

Categories
discuss

How to get a Bitmap from an ImageView

I wish to get a Bitmap from an ImageView loaded with Glide like such:

Glide.with(getContext()).load(URL)
            .thumbnail(0.5f)
            .crossFade()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(my_imageView);

I have tried the following:

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

and

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

And none of them has worked for me so far.

How can this be achieved?

Answer

Oh, this is a simple error. You need to add this before the code where you are trying to get Bitmap out of the ImageView:

imageView.setDrawingCacheEnabled(true);

In order to get the Bitmap out of the ImageView using DrawingCache, you first need to enable ImageView to draw image cache.

then:

Bitmap bmap = imageView.getDrawingCache();

Also, calling buildDrawingCache(); is equivalent to calling buildDrawingCache(false);

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..