问:
Best way to use Realm database
using this code:

```<code>public class App extends Application {
            private static App instance;

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

            private void initRealmDB() {
                instance = this;
                Realm.init(this);
                RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().modules(new SimpleRealmModule()).name("RealmSample.realm").build();
                Realm realm = null;
                try {
                    realm = Realm.getInstance(realmConfiguration);
                    realm.setDefaultConfiguration(realmConfiguration);
                } finally {
                    if (realm != null) {
                        realm.close();
                    }
                }
            }
    }

**In use:**

    Realm realm = Realm.getDefaultInstance();
            RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
            if(realm.isInTransaction())
            {
                realm.cancelTransaction();
            }
            realm.beginTransaction();
            if (results != null) {
                if(membershipList != null)
                {
                    membershipList.clear();
                }
                for (int i = 0; i < results.size(); i++) {
                    Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid());
    }
    }
</code>```

Is this best way to use?
Should i use singleton approach?
If there is another good approach to fulfill this task, please share with me.
i followed this https://dzone.com/articles/realm-practical-use-in-android
but this code is not working with this dependency: classpath "io.realm:realm-gradle-plugin:3.3.1"

```<code>Realm realm = Realm.getInstance(SimpleRealmApp.getInstance());
</code>```

答:
Is this best way to use?

No

```<code>Realm realm = Realm.getDefaultInstance(); // <-- opens Realm
        RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
        if(realm.isInTransaction())
        {
            realm.cancelTransaction(); // <-- what if that transaction was important?
        }
        realm.beginTransaction();
        if (results != null) {
            if(membershipList != null)
            {
                membershipList.clear(); // <-- ??
            }
            for (int i = 0; i < results.size(); i++) {
                Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid()); // <-- if the result set was modified here because of the transaction, then the RealmResults will update, and you'll skip elements
}
           // <-- where is the commit?
} // <-- where is realm.close()?
</code>```

Instead

```<code>try(Realm r = Realm.getDefaultInstance()) {
    r.executeTransaction((realm) -> { // AS 3.0+ desugar
        RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll(); // <-- get in transaction
        for (OrganizationModelClass model : results) { // uses snapshot() internally
           Log.i(model.getClass().getName(), getCurrentMembershipUuid());
        }
    }
} // <-- auto-close because of try-with-resources
</code>```

Should i use singleton approach?

Realm instances you open with getInstance()/getDefaultInstance() are thread-local and reference counted, so it is NOT suitable for being used as a singleton across the application. You need to open thread-local instances.

So on UI Thread, based on documentation:

```<code>// Setup Realm in your Application
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
             //.deleteIfMigrationNeeded()
             .migration(new MyMigration())
             .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

// onCreate()/onDestroy() overlap when switching between activities.
// Activity2.onCreate() will be called before Activity1.onDestroy()
// so the call to getDefaultInstance in Activity2 will be fast.
public class MyActivity extends Activity {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        realm = Realm.getDefaultInstance();

        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(this, realm.where(MyModel.class).findAllSortedAsync(MyModelFields.ID)));

        // ...
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

// Use onCreateView()/onDestroyView() for Fragments.
// Note that if the db is large, getting the Realm instance may, briefly, block rendering.
// In that case it may be preferable to manage the Realm instance and RecyclerView from
// onStart/onStop instead. Returning a view, immediately, from onCreateView allows the
// fragment frame to be rendered while the instance is initialized and the view loaded.
public class MyFragment extends Fragment {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        realm = Realm.getDefaultInstance();

        View root = inflater.inflate(R.layout.fragment_view, container, false);

        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(getActivity(), realm.where(MyModel.class).findAllSortedAsync(MyModelFields.ID)));

        // ...

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.close();
    }
}
</code>```

For background thread, see the docs:

```<code>Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try (Realm realm = Realm.getDefaultInstance()) {
            // No need to close the Realm instance manually
        }
    }
});

thread.start();
</code>```

If you want to use Realm as a singleton, you have to use a class that can increment, decrement, and get instance without incrementing ref count for thread local Realms, kinda like this experiment here.

Title: Best way to use Realm database

Body:
using this code:

public class App extends Application {
            private static App instance;

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

            private void initRealmDB() {
                instance = this;
                Realm.init(this);
                RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().modules(new SimpleRealmModule()).name("RealmSample.realm").build();
                Realm realm = null;
                try {
                    realm = Realm.getInstance(realmConfiguration);
                    realm.setDefaultConfiguration(realmConfiguration);
                } finally {
                    if (realm != null) {
                        realm.close();
                    }
                }
            }
    }

**In use:**

    Realm realm = Realm.getDefaultInstance();
            RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
            if(realm.isInTransaction())
            {
                realm.cancelTransaction();
            }
            realm.beginTransaction();
            if (results != null) {
                if(membershipList != null)
                {
                    membershipList.clear();
                }
                for (int i = 0; i < results.size(); i++) {
                    Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid());
    }
    }

Is this best way to use?
Should i use singleton approach?
If there is another good approach to fulfill this task, please share with me.
i followed this https://dzone.com/articles/realm-practical-use-in-android
but this code is not working with this dependency: classpath "io.realm:realm-gradle-plugin:3.3.1"

Realm realm = Realm.getInstance(SimpleRealmApp.getInstance());

Body:
Is this best way to use?

No

Realm realm = Realm.getDefaultInstance(); // <-- opens Realm
        RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll();
        if(realm.isInTransaction())
        {
            realm.cancelTransaction(); // <-- what if that transaction was important?
        }
        realm.beginTransaction();
        if (results != null) {
            if(membershipList != null)
            {
                membershipList.clear(); // <-- ??
            }
            for (int i = 0; i < results.size(); i++) {
                Log.d(OrganizationActivity.class.getName(), " i :" + results.get(i).getCurrent_membership_uuid()); // <-- if the result set was modified here because of the transaction, then the RealmResults will update, and you'll skip elements
}
           // <-- where is the commit?
} // <-- where is realm.close()?

Instead

try(Realm r = Realm.getDefaultInstance()) {
    r.executeTransaction((realm) -> { // AS 3.0+ desugar
        RealmResults<OrganizationModelClass> results = realm.where(OrganizationModelClass.class).findAll(); // <-- get in transaction
        for (OrganizationModelClass model : results) { // uses snapshot() internally
           Log.i(model.getClass().getName(), getCurrentMembershipUuid());
        }
    }
} // <-- auto-close because of try-with-resources

Should i use singleton approach?

Realm instances you open with getInstance()/getDefaultInstance() are thread-local and reference counted, so it is NOT suitable for being used as a singleton across the application. You need to open thread-local instances.

So on UI Thread, based on documentation:

// Setup Realm in your Application
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Realm.init(this);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
             //.deleteIfMigrationNeeded()
             .migration(new MyMigration())
             .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

// onCreate()/onDestroy() overlap when switching between activities.
// Activity2.onCreate() will be called before Activity1.onDestroy()
// so the call to getDefaultInstance in Activity2 will be fast.
public class MyActivity extends Activity {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        realm = Realm.getDefaultInstance();

        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(this, realm.where(MyModel.class).findAllSortedAsync(MyModelFields.ID)));

        // ...
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

// Use onCreateView()/onDestroyView() for Fragments.
// Note that if the db is large, getting the Realm instance may, briefly, block rendering.
// In that case it may be preferable to manage the Realm instance and RecyclerView from
// onStart/onStop instead. Returning a view, immediately, from onCreateView allows the
// fragment frame to be rendered while the instance is initialized and the view loaded.
public class MyFragment extends Fragment {
    private Realm realm;
    private RecyclerView recyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        realm = Realm.getDefaultInstance();

        View root = inflater.inflate(R.layout.fragment_view, container, false);

        recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        recyclerView.setAdapter(
            new MyRecyclerViewAdapter(getActivity(), realm.where(MyModel.class).findAllSortedAsync(MyModelFields.ID)));

        // ...

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.close();
    }
}

For background thread, see the docs:

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        try (Realm realm = Realm.getDefaultInstance()) {
            // No need to close the Realm instance manually
        }
    }
});

thread.start();

If you want to use Realm as a singleton, you have to use a class that can increment, decrement, and get instance without incrementing ref count for thread local Realms, kinda like this experiment here.


来源: stackexchange

问:
Hibernate join inheritance wrong type on query result
I'm new to spring/hibernate. I have written a webservice that should return full objects and sometimes reduced objects. For example, I have a Member class that inherits from a MemberBase class :

```<code>...

**
 * MemberBase
 */

@Entity
@Table(name = "MemberBase")
@Inheritance(strategy = InheritanceType.JOINED)
@SequenceGenerator(name = "idgen", sequenceName = "seq_Member")
public class MemberBase extends BasePojo {

    @Column(name = "alias")
    private String alias = null;
    @Column(name = "firstName")
    private String firstName = null;

    @Column(name = "gender")
    @Enumerated(EnumType.STRING)
    private Gender gender = null;

    @Transient
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "creator")
    @ElementCollection(targetClass=OutingBase.class)
    private Set<OutingBase> outings = null;

...
}
</code>```

and Member :

```<code>...

/**
 * Member
 */
@Entity
@Table(name = "Member")
@SequenceGenerator(name = "idgen", sequenceName = "seq_Member")
public class Member extends MemberBase {

    @Enumerated(EnumType.STRING)
    private MaritalStatus maritalStatus = null;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    private LocalDate birthDate = null;

    private String locationName = null;

    private DateTime lastConnexion = null;

    private String description = null;

    private String videoMoodUrl = null;

    private String mood = null;

    private Boolean canCertify = null;

    private String fid = null;
    ...
}
</code>```

In my controller I use hibernate to get a list of member base :

```<code>public ResponseEntity<List<MemberBase>> membersGet() {
        Session session = HibernateUtils.getSessionFactory().openSession();
        session.beginTransaction();
        List<MemberBase> personList = session.createQuery("FROM " + MemberBase.class.getName(), MemberBase.class)
                .getResultList();

        session.close();
        return new ResponseEntity<List<MemberBase>>(personList, HttpStatus.OK);
    }
</code>```

And here is how I create my session factory :

```<code>private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration().configure();
            configuration.addAnnotatedClass(BasePojo.class);
            configuration.addAnnotatedClass(MemberBase.class);
            configuration.addAnnotatedClass(Member.class);
            configuration.addAnnotatedClass(OutingBase.class);
            configuration.addAnnotatedClass(Outing.class);

            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            return configuration.buildSessionFactory(builder.build());
        } catch (Throwable ex) {

            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
</code>```

My problem is that when I call membersGet(), I retrieve a List<Member> and not a list of List<MemberBase>. There is no crash, but my serialised Json contains too much fields. I implemented this inheritance to avoid getting all the Member's fields. What did I do wrong ?

答:
I recomend using the JsonIgnore anotation from FasterXML Jackson.

As the name indicates the anotation will result in ignoring the property when parsing the object.

e. g.

```<code>@JsonIgnore
private String locationName = null;
</code>```

EDIT:

Use JsonViewto specify for which view the property should be shown/parsed.
e. g.

```<code>public class JsonView {
    public static class Base {
    }
    public static class Extended extends Base {
    }
}

@JsonView(JsonView.Extended.class)
private String locationName = null;

@JsonView(JsonView.Base.class)
private String alias = null;
</code>```

And when you map it you can specify the view you want.

```<code>ObjectMapper mapper = new ObjectMapper();

    String result = mapper
      .writerWithView(JsonView.Extended.class)
      .writeValueAsString(member);
</code>```

see here: http://www.baeldung.com/jackson-json-view-annotation

ContentLicense: CC BY-SA 3.0

Body:
I'm new to spring/hibernate. I have written a webservice that should return full objects and sometimes reduced objects. For example, I have a Member class that inherits from a MemberBase class :

...

**
 * MemberBase
 */

@Entity
@Table(name = "MemberBase")
@Inheritance(strategy = InheritanceType.JOINED)
@SequenceGenerator(name = "idgen", sequenceName = "seq_Member")
public class MemberBase extends BasePojo {

    @Column(name = "alias")
    private String alias = null;
    @Column(name = "firstName")
    private String firstName = null;

    @Column(name = "gender")
    @Enumerated(EnumType.STRING)
    private Gender gender = null;

    @Transient
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "creator")
    @ElementCollection(targetClass=OutingBase.class)
    private Set<OutingBase> outings = null;

...
}

and Member :

...

/**
 * Member
 */
@Entity
@Table(name = "Member")
@SequenceGenerator(name = "idgen", sequenceName = "seq_Member")
public class Member extends MemberBase {

    @Enumerated(EnumType.STRING)
    private MaritalStatus maritalStatus = null;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    private LocalDate birthDate = null;

    private String locationName = null;

    private DateTime lastConnexion = null;

    private String description = null;

    private String videoMoodUrl = null;

    private String mood = null;

    private Boolean canCertify = null;

    private String fid = null;
    ...
}

In my controller I use hibernate to get a list of member base :

public ResponseEntity<List<MemberBase>> membersGet() {
        Session session = HibernateUtils.getSessionFactory().openSession();
        session.beginTransaction();
        List<MemberBase> personList = session.createQuery("FROM " + MemberBase.class.getName(), MemberBase.class)
                .getResultList();

        session.close();
        return new ResponseEntity<List<MemberBase>>(personList, HttpStatus.OK);
    }

And here is how I create my session factory :

private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration().configure();
            configuration.addAnnotatedClass(BasePojo.class);
            configuration.addAnnotatedClass(MemberBase.class);
            configuration.addAnnotatedClass(Member.class);
            configuration.addAnnotatedClass(OutingBase.class);
            configuration.addAnnotatedClass(Outing.class);

            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            return configuration.buildSessionFactory(builder.build());
        } catch (Throwable ex) {

            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

My problem is that when I call membersGet(), I retrieve a List<Member> and not a list of List<MemberBase>. There is no crash, but my serialised Json contains too much fields. I implemented this inheritance to avoid getting all the Member's fields. What did I do wrong ?

Body:
I recomend using the JsonIgnore anotation from FasterXML Jackson.

As the name indicates the anotation will result in ignoring the property when parsing the object.

e. g.

@JsonIgnore
private String locationName = null;

EDIT:

Use JsonViewto specify for which view the property should be shown/parsed.
e. g.

public class JsonView {
    public static class Base {
    }
    public static class Extended extends Base {
    }
}

@JsonView(JsonView.Extended.class)
private String locationName = null;

@JsonView(JsonView.Base.class)
private String alias = null;

And when you map it you can specify the view you want.

ObjectMapper mapper = new ObjectMapper();

    String result = mapper
      .writerWithView(JsonView.Extended.class)
      .writeValueAsString(member);

see here: http://www.baeldung.com/jackson-json-view-annotation


问:
Remove underscore before extension in strings
I have got strings like tran_crossings_exp_.txt and tran_buildings_exp_.shp
How can I write a bash function to test if the last character before the dot extension starts with an underscore and replace the underscore to have a name like tran_crossings_exp.txt I know how to get the basename and extension of the file in bash

I have done this solution but I am seeking a more elegant way which also check if the file indeed has an underscore and skips it if the name already is proper.

```<code>for file in `ls *_.*`;do ext="${file##*.}"; filename="${file%.*}";non=${file::-5}; mv ${file} ${non}.${ext};done
</code>```

答:
Try with this:

```<code>#!/bin/bash

filename=tran_crossings_exp_.txt
i=${filename:${#filename}-5:1}  // Take the 5th char from back
if [ $i = "_" ]; then           // If it is an underscore
    echo "${filename/?./.}"     // Replace '?.' with just '.', this removes last '_' in this case (? means any character)
else
    echo $filename
fi
</code>```

Here you can test it

Note: this only works with .abc (dot and 3 chars) extensions

EDIT

To store in the same variable

```<code>#!/bin/bash

filename=tran_crossings_exp_.txt
i=${filename:${#filename}-5:1}

if [ $i = "_" ]; then
    filename="$(echo ${filename/?./.})"
fi

echo "$filename"
</code>```

Body:
I have got strings like tran_crossings_exp_.txt and tran_buildings_exp_.shp
How can I write a bash function to test if the last character before the dot extension starts with an underscore and replace the underscore to have a name like tran_crossings_exp.txt I know how to get the basename and extension of the file in bash

I have done this solution but I am seeking a more elegant way which also check if the file indeed has an underscore and skips it if the name already is proper.

for file in `ls *_.*`;do ext="${file##*.}"; filename="${file%.*}";non=${file::-5}; mv ${file} ${non}.${ext};done

Body:
Try with this:

#!/bin/bash

filename=tran_crossings_exp_.txt
i=${filename:${#filename}-5:1}  // Take the 5th char from back
if [ $i = "_" ]; then           // If it is an underscore
    echo "${filename/?./.}"     // Replace '?.' with just '.', this removes last '_' in this case (? means any character)
else
    echo $filename
fi

Here you can test it

Note: this only works with .abc (dot and 3 chars) extensions

EDIT

To store in the same variable

#!/bin/bash

filename=tran_crossings_exp_.txt
i=${filename:${#filename}-5:1}

if [ $i = "_" ]; then
    filename="$(echo ${filename/?./.})"
fi

echo "$filename"


问:
Does PVS-Studio know about Unicode chars?
This code produces Medium warnings at lines w/ return:

```<code>// Checks if the symbol defines two-symbols Unicode sequence
bool doubleSymbol(const char c) {
    static const char TWO_SYMBOLS_MASK = 0b110;
    return (c >> 5) == TWO_SYMBOLS_MASK;
}

// Checks if the symbol defines three-symbols Unicode sequence
bool tripleSymbol(const char c) {
    static const char THREE_SYMBOLS_MASK = 0b1110;
    return (c >> 4) == THREE_SYMBOLS_MASK;
}

// Checks if the symbol defines four-symbols Unicode sequence
bool quadrupleSymbol(const char c) {
    static const char FOUR_SYMBOLS_MASK = 0b11110;
    return (c >> 3) == FOUR_SYMBOLS_MASK;
}
</code>```

PVS says that the expressions are always false (V547), but they actually aren't: char may be a part of Unicode symbol that is read to std::string!
Here is the Unicode representation of symbols:

1 byte  - 0xxx'xxxx                               - 7 bits

2 bytes - 110x'xxxx 10xx'xxxx                     - 11 bits

3 bytes - 1110'xxxx 10xx'xxxx 10xx'xxxx           - 16 bits

4 bytes - 1111'0xxx 10xx'xxxx 10xx'xxxx 10xx'xxxx - 21 bits

The following code counts number of symbols in a Unicode text:

```<code>size_t symbolCount = 0;

std::string s;
while (getline(std::cin, s)) {
    for (size_t i = 0; i < s.size(); ++i) {
        const char c = s[i];
        ++symbolCount;
        if (doubleSymbol(c)) {
            i += 1;
        } else if (tripleSymbol(c)) {
            i += 2;
        } else if (quadrupleSymbol(c)) {
            i += 3;
        }
    }
}

std::cout << symbolCount << "\n";
</code>```

For the Hello! input the output is 6 and for Привет, мир! is 12 — this is right!

Am I wrong or doesn't PVS know something? ;)

答:
PVS-Studio analyzer knows that there are signed and unsigned char types. Whether signed/unsigned is used depends on compilation keys and PVS-Studio analyzer takes these keys into account.

I think this code is compiled, when char is of signed char type. Let's see what consequences it brings.

Let’s look only at the first case:

```<code>bool doubleSymbol(const char c) {
    static const char TWO_SYMBOLS_MASK = 0b110;
    return (c >> 5) == TWO_SYMBOLS_MASK;
}
</code>```

If the value variable 'c' is less than or equal to 01111111, the condition will always be false, because during the shift the max value you can get is 011.

It means we are interested in only cases where the highest bit in the variable 'c' is equal to 1. As this variable is of signed char type, then the highest bit means that the variable stores a negative value. Before the shift, signed char becomes a signed int and the value continues to be negative.

Now let's see what the standard says about the right-shift of negative numbers:

The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Thus, the shift of a negative number to the left is implementation-defined. This means that the highest bits are filled with nulls or ones. Both will be correct.

PVS-Studio thinks that the highest bits are filled with ones. It has a full right to think so, because it is necessary to choose any implementation. So it turns out that the expression ((c) >> 5) will have a negative value if the highest bit in the variable 'c' is originally equal to 1. A negative number cannot be equal to TWO_SYMBOLS_MASK.

It turns out that from the viewpoint of PVS-Studio, the condition will always be false, and it correctly issues a warning V547.

In practice, the compiler may behave differently: the highest bits will be filled with 0 and then everything will work correctly.

In any case, it is necessary to fix the code, as it goes to the implementation-defined behavior of the compiler.

Code might be fixed as follows:

```<code>bool doubleSymbol(const unsigned char c) {
    static const char TWO_SYMBOLS_MASK = 0b110;
    return (c >> 5) == TWO_SYMBOLS_MASK;
}
</code>```

Body:
This code produces Medium warnings at lines w/ return:

// Checks if the symbol defines two-symbols Unicode sequence
bool doubleSymbol(const char c) {
    static const char TWO_SYMBOLS_MASK = 0b110;
    return (c >> 5) == TWO_SYMBOLS_MASK;
}

// Checks if the symbol defines three-symbols Unicode sequence
bool tripleSymbol(const char c) {
    static const char THREE_SYMBOLS_MASK = 0b1110;
    return (c >> 4) == THREE_SYMBOLS_MASK;
}

// Checks if the symbol defines four-symbols Unicode sequence
bool quadrupleSymbol(const char c) {
    static const char FOUR_SYMBOLS_MASK = 0b11110;
    return (c >> 3) == FOUR_SYMBOLS_MASK;
}

PVS says that the expressions are always false (V547), but they actually aren't: char may be a part of Unicode symbol that is read to std::string!
Here is the Unicode representation of symbols:

1 byte  - 0xxx'xxxx                               - 7 bits

2 bytes - 110x'xxxx 10xx'xxxx                     - 11 bits

3 bytes - 1110'xxxx 10xx'xxxx 10xx'xxxx           - 16 bits

4 bytes - 1111'0xxx 10xx'xxxx 10xx'xxxx 10xx'xxxx - 21 bits

The following code counts number of symbols in a Unicode text:

size_t symbolCount = 0;

std::string s;
while (getline(std::cin, s)) {
    for (size_t i = 0; i < s.size(); ++i) {
        const char c = s[i];
        ++symbolCount;
        if (doubleSymbol(c)) {
            i += 1;
        } else if (tripleSymbol(c)) {
            i += 2;
        } else if (quadrupleSymbol(c)) {
            i += 3;
        }
    }
}

std::cout << symbolCount << "\n";

For the Hello! input the output is 6 and for Привет, мир! is 12 — this is right!

Am I wrong or doesn't PVS know something? ;)

Body:
PVS-Studio analyzer knows that there are signed and unsigned char types. Whether signed/unsigned is used depends on compilation keys and PVS-Studio analyzer takes these keys into account.

I think this code is compiled, when char is of signed char type. Let's see what consequences it brings.

Let’s look only at the first case:

bool doubleSymbol(const char c) {
    static const char TWO_SYMBOLS_MASK = 0b110;
    return (c >> 5) == TWO_SYMBOLS_MASK;
}

If the value variable 'c' is less than or equal to 01111111, the condition will always be false, because during the shift the max value you can get is 011.

It means we are interested in only cases where the highest bit in the variable 'c' is equal to 1. As this variable is of signed char type, then the highest bit means that the variable stores a negative value. Before the shift, signed char becomes a signed int and the value continues to be negative.

Now let's see what the standard says about the right-shift of negative numbers:

The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Thus, the shift of a negative number to the left is implementation-defined. This means that the highest bits are filled with nulls or ones. Both will be correct.

PVS-Studio thinks that the highest bits are filled with ones. It has a full right to think so, because it is necessary to choose any implementation. So it turns out that the expression ((c) >> 5) will have a negative value if the highest bit in the variable 'c' is originally equal to 1. A negative number cannot be equal to TWO_SYMBOLS_MASK.

It turns out that from the viewpoint of PVS-Studio, the condition will always be false, and it correctly issues a warning V547.

In practice, the compiler may behave differently: the highest bits will be filled with 0 and then everything will work correctly.

In any case, it is necessary to fix the code, as it goes to the implementation-defined behavior of the compiler.

Code might be fixed as follows:

bool doubleSymbol(const unsigned char c) {
    static const char TWO_SYMBOLS_MASK = 0b110;
    return (c >> 5) == TWO_SYMBOLS_MASK;
}


问:
File not found exception:java.io.FileNotFoundException: /storage/emulated/0/image.jpg: open failed: ENOENT (No such file or directory)
File not found exception:java.io.FileNotFoundException: /storage/emulated/0/FolderName/subFolderName/my_image.jpg: open failed: ENOENT (No such file or directory)

I am getting above exception in some phones only

I am getting File not found exception while saving image captured from camera.
Here is my code

I am capturing image :

```<code>Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, 0);
                    }
</code>```

In onActivityResult:

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 0)
    {
        if(data!=null)
        {
            Bundle extras = data.getExtras();
            if (extras != null)
            if (img1) {
                imgAdd1.setVisibility(View.GONE);
                Bitmap thumbnail_1 = (Bitmap) extras.get("data");
                Bitmap resized = scaleBitmap(thumbnail_1) ;
                selectedImage1 = data.getData() ;
                //Bitmap thumbnail_1 = (Bitmap) data.getExtras().get("data");
                image1.setVisibility(View.VISIBLE);
                image1.setImageBitmap(thumbnail_1);
                imageTag = 1 ;
                saveImage(resized, (int) System.currentTimeMillis());
                img1 = false ;
                imgDelete1.setVisibility(View.VISIBLE);
            }
}}
</code>```

my function to save Image is :

```<code>public void saveImage(Bitmap bitmap, int i){
    try {

        String stored = null;

        File sdCard = Environment.getExternalStorageDirectory();
        File file = new File(sdCard, "/GMC/Images"
                + File.separator + user_id + "_" + imageTag + ".jpg");

        if (file.exists()) {
            file.delete();
        }

        if (isWriteStorageAllowed()) {
            if ( isReadStorageAllowed())
            //file.createNewFile();
            try {

                FileOutputStream out = new FileOutputStream(file);//getting exception at this line
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();
                stored = "success";
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (imageTag == 1) {
                selectedImagePath1 = Environment.getExternalStorageDirectory() + "/GMC/Images"
                        + File.separator + user_id + "_" + imageTag + ".jpg";
            }
        }
        else {
            requestWriteStoragePermission();
            requestStoragePermission();
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
</code>```

already added permissions in manifest like

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA">
</code>```

also checked runtime permissions :

```<code>//We are calling this method to check the permission status
private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;
    else {
        //If permission is not granted returning false
        return false;}
}

private boolean isWriteStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;
    else {
        //If permission is not granted returning false
        return false;}
}

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_READ_EXTERNAL_STORAGE);
}

//Requesting permission
private void requestWriteStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_WRITE_EXTERNAL_STORAGE);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    {
        switch (requestCode){
            case PERMISSION_READ_EXTERNAL_STORAGE :
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(context , "Read Permission granted",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(context , "Read Permission Denied" ,Toast.LENGTH_SHORT).show();
                }
                return;
            case  PERMISSION_WRITE_EXTERNAL_STORAGE :
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(context , "Write Permission granted" ,Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(context , "write Permission Denied",Toast.LENGTH_SHORT).show();
                }
                return;
        }

    }
}
</code>```

Checked the link
java.io.FileNotFoundException: /storage/emulated/0/saved_images/grub.jpg: open failed: ENOENT (No such file or directory)

I tested the code on two different phone one is lenovo(Marshmallow) and other is samsung(marshmallow) but it gives error in samsung where as works perfectly on lenovo.

what will be the issue?
please help

答: Try adding largeheap=true in your manifest file.Lenovo phones cannot get large images whereas samsung phones are able to get large image from gallery camera etc.

Body:
File not found exception:java.io.FileNotFoundException: /storage/emulated/0/FolderName/subFolderName/my_image.jpg: open failed: ENOENT (No such file or directory)

I am getting above exception in some phones only

I am getting File not found exception while saving image captured from camera.
Here is my code

I am capturing image :

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, 0);
                    }

In onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 0)
    {
        if(data!=null)
        {
            Bundle extras = data.getExtras();
            if (extras != null)
            if (img1) {
                imgAdd1.setVisibility(View.GONE);
                Bitmap thumbnail_1 = (Bitmap) extras.get("data");
                Bitmap resized = scaleBitmap(thumbnail_1) ;
                selectedImage1 = data.getData() ;
                //Bitmap thumbnail_1 = (Bitmap) data.getExtras().get("data");
                image1.setVisibility(View.VISIBLE);
                image1.setImageBitmap(thumbnail_1);
                imageTag = 1 ;
                saveImage(resized, (int) System.currentTimeMillis());
                img1 = false ;
                imgDelete1.setVisibility(View.VISIBLE);
            }
}}

my function to save Image is :

public void saveImage(Bitmap bitmap, int i){
    try {

        String stored = null;

        File sdCard = Environment.getExternalStorageDirectory();
        File file = new File(sdCard, "/GMC/Images"
                + File.separator + user_id + "_" + imageTag + ".jpg");

        if (file.exists()) {
            file.delete();
        }

        if (isWriteStorageAllowed()) {
            if ( isReadStorageAllowed())
            //file.createNewFile();
            try {

                FileOutputStream out = new FileOutputStream(file);//getting exception at this line
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.flush();
                out.close();
                stored = "success";
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (imageTag == 1) {
                selectedImagePath1 = Environment.getExternalStorageDirectory() + "/GMC/Images"
                        + File.separator + user_id + "_" + imageTag + ".jpg";
            }
        }
        else {
            requestWriteStoragePermission();
            requestStoragePermission();
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

already added permissions in manifest like

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA">

also checked runtime permissions :

//We are calling this method to check the permission status
private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;
    else {
        //If permission is not granted returning false
        return false;}
}

private boolean isWriteStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;
    else {
        //If permission is not granted returning false
        return false;}
}

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_READ_EXTERNAL_STORAGE);
}

//Requesting permission
private void requestWriteStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_WRITE_EXTERNAL_STORAGE);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    {
        switch (requestCode){
            case PERMISSION_READ_EXTERNAL_STORAGE :
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(context , "Read Permission granted",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(context , "Read Permission Denied" ,Toast.LENGTH_SHORT).show();
                }
                return;
            case  PERMISSION_WRITE_EXTERNAL_STORAGE :
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(context , "Write Permission granted" ,Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(context , "write Permission Denied",Toast.LENGTH_SHORT).show();
                }
                return;
        }

    }
}

Checked the link
java.io.FileNotFoundException: /storage/emulated/0/saved_images/grub.jpg: open failed: ENOENT (No such file or directory)

I tested the code on two different phone one is lenovo(Marshmallow) and other is samsung(marshmallow) but it gives error in samsung where as works perfectly on lenovo.

what will be the issue?
please help


问:
Photon objects not syncing - Unity
I am working on a multlayer third person game and I am using motion controller for animations and photon for network manager.I ahve a problem: when I connect and join the room the other players don't move on others player screen. They move only on their devices. Here is what I deactivated:

```<code>using UnityEngine;
using com.ootii.Input;
using com.ootii.Actors;
using com.ootii.Actors.AnimationControllers;

public class netView : Photon.MonoBehaviour {

    public Camera cam;
    public UnityInputSource uis;
    public GameObject canvas;
    public ActorController ac;
    public MotionController mc;

    // Use this for initialization
    void Start () {
        if (photonView.isMine) {
            cam.enabled = true;
            uis._IsEnabled = true;
            canvas.active = true;
            ac.enabled = true;
            mc.enabled = true;
        } else {
            cam.enabled = false;
            uis._IsEnabled = false;
            canvas.active = false;
            ac.enabled = false;
            mc.enabled = false;
        }
    }

}
</code>```

Here is a video: https://youtu.be/mOaAejsVX04 . In it i am playing in editor and on my phone. In my device I move around and the editor player does not move. Also in editor, the player from the device just stays there, doesn't move while on phone is moveing around.
For input I am using CrossPlatformManager class. How can I repair it?

答:
In your case I think the problem is that you don't synchronize the transform to begin with. You need either a PhotonTransformView Component attached to your network object, with a photonView observing that PhotonTransformView, or inside your network behaviour manually writing and reading to that network object stream.

I strongly encourage you do go through the basic tutorial which will show you all the above technique step by step:

https://doc.photonengine.com/en-us/pun/current/demos-and-tutorials/pun-basics-tutorial/player-networking#trans_sync

https://doc.photonengine.com/en-us/pun/current/demos-and-tutorials/pun-basics-tutorial/player-networking#beams

it doesn't matter the input technique you use, what matters is the synchronization of the transform.

Title: Photon objects not syncing - Unity

Body:
I am working on a multlayer third person game and I am using motion controller for animations and photon for network manager.I ahve a problem: when I connect and join the room the other players don't move on others player screen. They move only on their devices. Here is what I deactivated:

using UnityEngine;
using com.ootii.Input;
using com.ootii.Actors;
using com.ootii.Actors.AnimationControllers;

public class netView : Photon.MonoBehaviour {

    public Camera cam;
    public UnityInputSource uis;
    public GameObject canvas;
    public ActorController ac;
    public MotionController mc;

    // Use this for initialization
    void Start () {
        if (photonView.isMine) {
            cam.enabled = true;
            uis._IsEnabled = true;
            canvas.active = true;
            ac.enabled = true;
            mc.enabled = true;
        } else {
            cam.enabled = false;
            uis._IsEnabled = false;
            canvas.active = false;
            ac.enabled = false;
            mc.enabled = false;
        }
    }

}

Here is a video: https://youtu.be/mOaAejsVX04 . In it i am playing in editor and on my phone. In my device I move around and the editor player does not move. Also in editor, the player from the device just stays there, doesn't move while on phone is moveing around.
For input I am using CrossPlatformManager class. How can I repair it?

ContentLicense: CC BY-SA 4.0


问:
Javascript-searching for a string in the properties of an array of objects
I have an array of JSON objects. Given a search string, I want to filter the array for only those objects which have that string as a substring of one of their properties. How do I do this efficiently?</p>

答:
```<code>var myStr = 'abc';
var myArr = [{abc:1,def:2}, {ghi:1,jkl:2}];
myArr.filter( obj => Object.keys(obj).some( key => key.indexOf(myStr) > -1 ) )
</code>```


问:
Writing XSLT output to the multiple objects in memory
I'm playing with XSLT and writing the result to the multiple outputs in Java as these links describe:
link1,
link2.

When it comes to writing to the files everything works perfectly, but now I'd like to store the output XMLs as either Document object or some kind of InputStream/String - anything but file on a drive. Writing the documents to the files using Transformer and than reading them to the objests(Document, String etc.) is not an option.

My question is: what should I change in my xslt map and java code to get the output as an objects, not the files on a drive. (the only solution that I came up with is to use two XSLT on this one XML but it's not the elegant way)

My Java codes are similar to the answers in the links above.
I'm using XSLT 2.0 and transform using :

```<code>transformer.transform(xmlText, new DOMResult());
</code>```

I also added

```<code>  <xsl:result-document href="{concat($jobName, '_assets.xml')}">
        <xsl:apply-templates select="GetMetadata/Metadata" mode="assets"/>
    </xsl:result-document>
    <xsl:result-document href="{concat($jobName, '_flows.xml')}">
        <xsl:apply-templates select="GetMetadata/Metadata" mode="flows"/>
    </xsl:result-document>
</code>```

to my xsl map [writing to the files works fine]

LATER

Correct implementation: (thank you Michael)

```<code>public void multipleXMLExtractor(Document inputDom, String xsltPath) throws TransformerException, UnsupportedEncodingException {

Source xmlInput = new DOMSource(inputDom);
Source xsltMap = new StreamSource(new File(xsltPath));
final Map<String, StreamResult> resultsMap = new HashMap<String, StreamResult>();
resultsMap.put("output1", new StreamResult(new ByteArrayOutputStream()));
resultsMap.put("output2", new StreamResult(new ByteArrayOutputStream()));

TransformerFactory tFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", XMLviaXSLTransformer.class.getClassLoader());
Transformer transformer = tFactory.newTransformer(xsltMap);
((net.sf.saxon.jaxp.TransformerImpl) transformer).getUnderlyingController().setOutputURIResolver(new OutputURIResolver() {
    @Override
    public OutputURIResolver newInstance() {
        return this;
    }

    @Override
    public Result resolve(String s, String s1) throws TransformerException {
        return resultsMap.get(s);
    }

    @Override
    public void close(Result result) throws TransformerException {
    }
});

StreamResult standardResult = new StreamResult(new ByteArrayOutputStream());
transformer.transform(xmlInput, standardResult);

for (Map.Entry<String, StreamResult> stringStreamResultEntry : resultsMap.entrySet()) {
    System.out.println(stringStreamResultEntry.getKey() + ": " + ((ByteArrayOutputStream) stringStreamResultEntry.getValue().getOutputStream()).toString("UTF-8"));
}
</code>```

}

答:
You need to define an OutputURIResolver - this is a Saxon-specific interface that is called to determine the destination for the output of xsl:result-document. It is given a URI as input, and returns a JAXP Result object to which the result document will be written.

https://www.saxonica.com/documentation/index.html#!javadoc/net.sf.saxon.lib/OutputURIResolver

If you're using the JAXP API to control the transformation, you will have to cast the Transformer object to net.sf.saxon.jaxp.TransformerImpl, and then call getUnderlyingController().setOutputURIResolver(), supplying your OutputURIResolver as the argument.

Body:
I'm playing with XSLT and writing the result to the multiple outputs in Java as these links describe:
link1,
link2.

When it comes to writing to the files everything works perfectly, but now I'd like to store the output XMLs as either Document object or some kind of InputStream/String - anything but file on a drive. Writing the documents to the files using Transformer and than reading them to the objests(Document, String etc.) is not an option.

My question is: what should I change in my xslt map and java code to get the output as an objects, not the files on a drive. (the only solution that I came up with is to use two XSLT on this one XML but it's not the elegant way)

My Java codes are similar to the answers in the links above.
I'm using XSLT 2.0 and transform using :

transformer.transform(xmlText, new DOMResult());

I also added

  <xsl:result-document href="{concat($jobName, '_assets.xml')}">
        <xsl:apply-templates select="GetMetadata/Metadata" mode="assets"/>
    </xsl:result-document>
    <xsl:result-document href="{concat($jobName, '_flows.xml')}">
        <xsl:apply-templates select="GetMetadata/Metadata" mode="flows"/>
    </xsl:result-document>

to my xsl map [writing to the files works fine]

LATER

Correct implementation: (thank you Michael)

public void multipleXMLExtractor(Document inputDom, String xsltPath) throws TransformerException, UnsupportedEncodingException {

Source xmlInput = new DOMSource(inputDom);
Source xsltMap = new StreamSource(new File(xsltPath));
final Map<String, StreamResult> resultsMap = new HashMap<String, StreamResult>();
resultsMap.put("output1", new StreamResult(new ByteArrayOutputStream()));
resultsMap.put("output2", new StreamResult(new ByteArrayOutputStream()));

TransformerFactory tFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", XMLviaXSLTransformer.class.getClassLoader());
Transformer transformer = tFactory.newTransformer(xsltMap);
((net.sf.saxon.jaxp.TransformerImpl) transformer).getUnderlyingController().setOutputURIResolver(new OutputURIResolver() {
    @Override
    public OutputURIResolver newInstance() {
        return this;
    }

    @Override
    public Result resolve(String s, String s1) throws TransformerException {
        return resultsMap.get(s);
    }

    @Override
    public void close(Result result) throws TransformerException {
    }
});

StreamResult standardResult = new StreamResult(new ByteArrayOutputStream());
transformer.transform(xmlInput, standardResult);

for (Map.Entry<String, StreamResult> stringStreamResultEntry : resultsMap.entrySet()) {
    System.out.println(stringStreamResultEntry.getKey() + ": " + ((ByteArrayOutputStream) stringStreamResultEntry.getValue().getOutputStream()).toString("UTF-8"));
}

}


问:
How to animate background-color center to right and left like google form?
i really lack of css animation. i try to create animation effect on div like google form.

if above link not work (like in my pc now), you can see it here https://ibb.co/cYsYKb

i try transition: all 1s ease; background: linear-gradient(to right, #673ab7);  but not work.

this is my fiddle: https://jsfiddle.net/hL8mncqa/

i try to find it in google, but still cant solve my problem, since i dont know what keyword to find it.

How to do this? any advice are welcome.

答:
You could use :before and :after pseudo elements on parent div to create such border and change its state by toggling active class.

$('.element textarea').on('focus blur', function() {
  $(this).parent('.element').toggleClass('active')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #ffffff;
}

.element {
  display: inline-block;
  position: relative;
}
textarea {
  width: 100%;
  border: 0;
  outline: 0;
}
.element:before,
.element:after {
  content: '';
  bottom: 0;
  position: absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: rgba(0, 0, 0, 0.12);
}

.element:after {
  background:  #673ab7;
  width: 0;
  left: 50%;
  transform: translateX(-50%);
  transition: all 0.3s ease-in;
}

.element.active:after {
  width: 100%;
}</code>```

  <textarea>Text</textarea>

```

Body:
You could use :before and :after pseudo elements on parent div to create such border and change its state by toggling active class.

$('.element textarea').on('focus blur', function() {
  $(this).parent('.element').toggleClass('active')
})

body {
  background-color: #ffffff;
}

.element {
  display: inline-block;
  position: relative;
}
textarea {
  width: 100%;
  border: 0;
  outline: 0;
}
.element:before,
.element:after {
  content: '';
  bottom: 0;
  position: absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: rgba(0, 0, 0, 0.12);
}

.element:after {
  background:  #673ab7;
  width: 0;
  left: 50%;
  transform: translateX(-50%);
  transition: all 0.3s ease-in;
}

.element.active:after {
  width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
  <textarea>Text</textarea>
</div>


问:
VS2010 Macro/Add In for "Run" and "Run On" commands in Visual Studio 2010
Much to annoyance of many developers Microsoft have removed the "Run" and "Run On" commands in Visual Studio 2010:

More details at:
http://social.msdn.microsoft.com/Forums/en/vstsdb/thread/f374c604-a7eb-496d-a261-9374790cdbf9

Has anyone seen or written a VS2010 Macro or Extension that fills the gaps and replicates this functionality?

答: I created a project in VS2008 that will merge your .sql files for you into 1 file from multiple directories ... feel free to use: http://www.filesavr.com/V9MSV0VUE77Z0WG</p>

ContentLicense: CC BY-SA 2.5


问:
Querying MongoDB to return only document with single value with matching condition
I want MongoDB to return an entire document if it has exactly one element in array matching the condition. I have written following:

```<code>db.myCollection.find({ $where: "this.Tags.filter(x => x.indexOf(':') < 0).length === 1" })
</code>```

It works fine, except that it's slow as hell, because $where clause doesn't use indicies.

Could this query be rewritten somehow to normal find/match/... operations that are aware of indicies or this is the only way to perform such an operation? I can defenitly add some field like NumberOfTagsThatDoNotContainSemicolon, but my question is about more generic approach that doesn't require changes to how data is inserted.

答:
After several hours of googling and stackoverflowing i have written following solution:

```<code>db.myCollection.aggregate([
    { $match : { "Tags": ":image" } },
    { $unwind : "$Tags" },
    { $match : { "Tags": /^[^:]+$/ } },
    { $group : { _id : "$_id", doc: { "$first": "$$ROOT" }, count: { $sum : 1} }} ,
    { $match : { "count": 1 } },
    { $replaceRoot : {newRoot: "$doc"} },
    { $addFields : { Tags : [ "$Tags" ] } } // we unwinded all tags, so we convert this field back to an array, otherwise we can get type error
])
</code>```

It works 10x faster than original code : 3 sec vs 31 sec on my machine.

Sample input

```<code>{
    "_id" : ObjectId("53396223ec8bd02674b1208c"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.834Z"),
    "Tags" : [
        "cars",
        " car_diler",
        " autodiler",
        " auto",
        " audi",
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208d"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208e"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "cars",
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208f"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something",
        ":image",
        ":somethingelse"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b120ff"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something",
        ":somethingelse"
    ]
}
</code>```

Current output:

```<code>{
    "_id" : ObjectId("53396223ec8bd02674b1208e"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "cars"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208f"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something"
    ]
}
</code>```

Desired output:

```<code>{
    "_id" : ObjectId("53396223ec8bd02674b1208e"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "cars",
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208f"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something",
        ":image",
        ":somethingelse"
    ]
}
</code>```

As you see, I loose here all tags starting with :. It's good enough in my case, but it could be important for someone else. I could collect IDs first and then query them, but it's crucial to perform all operations in one single query.

Body:
I want MongoDB to return an entire document if it has exactly one element in array matching the condition. I have written following:

db.myCollection.find({ $where: "this.Tags.filter(x => x.indexOf(':') < 0).length === 1" })

It works fine, except that it's slow as hell, because $where clause doesn't use indicies.

Could this query be rewritten somehow to normal find/match/... operations that are aware of indicies or this is the only way to perform such an operation? I can defenitly add some field like NumberOfTagsThatDoNotContainSemicolon, but my question is about more generic approach that doesn't require changes to how data is inserted.

Body:
After several hours of googling and stackoverflowing i have written following solution:

db.myCollection.aggregate([
    { $match : { "Tags": ":image" } },
    { $unwind : "$Tags" },
    { $match : { "Tags": /^[^:]+$/ } },
    { $group : { _id : "$_id", doc: { "$first": "$$ROOT" }, count: { $sum : 1} }} ,
    { $match : { "count": 1 } },
    { $replaceRoot : {newRoot: "$doc"} },
    { $addFields : { Tags : [ "$Tags" ] } } // we unwinded all tags, so we convert this field back to an array, otherwise we can get type error
])

It works 10x faster than original code : 3 sec vs 31 sec on my machine.

Sample input

{
    "_id" : ObjectId("53396223ec8bd02674b1208c"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.834Z"),
    "Tags" : [
        "cars",
        " car_diler",
        " autodiler",
        " auto",
        " audi",
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208d"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208e"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "cars",
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208f"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something",
        ":image",
        ":somethingelse"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b120ff"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something",
        ":somethingelse"
    ]
}

Current output:

{
    "_id" : ObjectId("53396223ec8bd02674b1208e"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "cars"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208f"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something"
    ]
}

Desired output:

{
    "_id" : ObjectId("53396223ec8bd02674b1208e"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "cars",
        ":image"
    ]
},
{
    "_id" : ObjectId("53396223ec8bd02674b1208f"),
    "UploadDate" : ISODate("2014-03-31T12:40:03.835Z"),
    "Tags" : [
        "something",
        ":image",
        ":somethingelse"
    ]
}

As you see, I loose here all tags starting with :. It's good enough in my case, but it could be important for someone else. I could collect IDs first and then query them, but it's crucial to perform all operations in one single query.


问:
How can I unit-test weakly named COM visible classes
I have a COM visible class (marked with [ComVisible(true)] and registered with RegAsm) in C# that I want to unit-test.

My assembly is an unsigned/weakly named dll (and it has to remain this). The class that I want to test has a private member that is not COM visible.
My problem is when I want to instantiate this class in a test it fails with this message:

Test method %MyTestMethod% threw exception
  System.EnterpriesServices.RegistreationException: The assembly
  %MyAssembly% does not have a strong name.

So how can I use the unit-test framework on an unsigned/weakly named dll?

```<code>using System.EnterpriseServices;
using System.Runtime.InteropServices;

[ComVisible( true )]
public class MyComClass: ServicedComponent, IMyClass
{
    //SomeAttribute

    private MyNonComClass nonCom;

    public MyComClass( MyNonComClass _nonCom )
    {
        this.nonCom = _nonCom;
    }
}
</code>```

答: As Hans Passant suggested when I removed the ServicedComponent class from inheritance, the unit-tests are running as supposed.</p>

Body:
I have a COM visible class (marked with [ComVisible(true)] and registered with RegAsm) in C# that I want to unit-test.

My assembly is an unsigned/weakly named dll (and it has to remain this). The class that I want to test has a private member that is not COM visible.
My problem is when I want to instantiate this class in a test it fails with this message:

Test method %MyTestMethod% threw exception
  System.EnterpriesServices.RegistreationException: The assembly
  %MyAssembly% does not have a strong name.

So how can I use the unit-test framework on an unsigned/weakly named dll?

using System.EnterpriseServices;
using System.Runtime.InteropServices;

[ComVisible( true )]
public class MyComClass: ServicedComponent, IMyClass
{
    //SomeAttribute

    private MyNonComClass nonCom;

    public MyComClass( MyNonComClass _nonCom )
    {
        this.nonCom = _nonCom;
    }
}


问:
CLion Installation: Cmake compilers not found, GDB not found
I'm switching from VS to CLion and they said I needed to install Cygwin and CMake. I then installed both of them. I tried use bundled, but CLion still gives me these errors make: not found C Compiler: not found C++ Compiler: not found GDB: not found.

I have installed CMake under the path C:\Users\Gaga\Downloads\cmake-3.4.1 but I don't see a cmake.exe, the closest thing is cmake.cxx.

Without these I'm not able to compile anything, please help

答:
I had the same problem.
While installing cygwin, need to select the packages of cmake, gcc, gdb
Got the answer from the below link.

Select Packages while installing cygwin

After the installation go to the configuration page and select the cygwin directory. CLion will identify the configuration and you are done...


问:
Removing substring between two words including the words, which are repeating in a string
I have to remove substrings between two words from a string which are repeating in the string.

For example, for the input:

People consider that cats and dogs are good friends but the fact is that dogs have got a problem with cats. Dogs always chase cats and bark at them.

I want the output:

People consider that are good friends but the fact is that.and bark at them.

Here "cats" and "dogs" are repeating and I have to remove all the substring between "cats" and "dogs" including "cats" and "dogs".

答:
Sounds like homework.

```<code>String temp = "People consider that cats and dogs are good friends but the fact is that dogs have got a problem with cats. Dogs always chase cats and bark at them.";

temp = temp.replaceAll("(cats)(.*)(dogs)", "");
System.out.println(temp);
</code>```

This will not yet give you your solution as its case sensitive ;-)
But if you want to do regexes, this is the way to go

Body:
Sounds like homework.

String temp = "People consider that cats and dogs are good friends but the fact is that dogs have got a problem with cats. Dogs always chase cats and bark at them.";

temp = temp.replaceAll("(cats)(.*)(dogs)", "");
System.out.println(temp);

This will not yet give you your solution as its case sensitive ;-)
But if you want to do regexes, this is the way to go


答:
This is What you Looking for..

* { box-sizing:border-box; }

/* basic stylings ------------------------------------------ */
body      { background:url(https://scotch.io/wp-content/uploads/2014/07/61.jpg); }
.container   {
  font-family:'Roboto';
  width:600px;
  margin:30px auto 0;
  display:block;
  background:#FFF;
  padding:10px 50px 50px;
}
h2    {
  text-align:center;
  margin-bottom:50px;
}
h2 small {
  font-weight:normal;
  color:#888;
  display:block;
}
.footer  { text-align:center; }
.footer a  { color:#53B2C8; }

/* form starting stylings ------------------------------- */
.group      {
  position:relative;
  margin-bottom:45px;
}
input     {
  font-size:18px;
  padding:10px 10px 10px 5px;
  display:block;
  width:300px;
  border:none;
  border-bottom:1px solid #757575;
}
input:focus   { outline:none; }

/* LABEL ======================================= */
label      {
  color:#999;
  font-size:18px;
  font-weight:normal;
  position:absolute;
  pointer-events:none;
  left:5px;
  top:10px;
  transition:0.2s ease all;
  -moz-transition:0.2s ease all;
  -webkit-transition:0.2s ease all;
}

/* active state */
input:focus ~ label, input:valid ~ label   {
  top:-20px;
  font-size:14px;
  color:#5264AE;
}

/* BOTTOM BARS ================================= */
.bar  { position:relative; display:block; width:300px; }
.bar:before, .bar:after  {
  content:'';
  height:4px;
  width:0;
  bottom:0px;
  position:absolute;
  background:#5264AE;
  transition:0.2s ease all;
  -moz-transition:0.2s ease all;
  -webkit-transition:0.2s ease all;
}
.bar:before {
  left:50%;
}
.bar:after {
  right:50%;
}

/* active state */
input:focus ~ .bar:before, input:focus ~ .bar:after {
  width:50%;
}

/* HIGHLIGHTER ================================== */
.highlight {
  position:absolute;
  height:60%;
  width:100px;
  top:25%;
  left:0;
  pointer-events:none;
  opacity:0.5;
}

/* active state */
input:focus ~ .highlight {
  -webkit-animation:inputHighlighter 0.3s ease;
  -moz-animation:inputHighlighter 0.3s ease;
  animation:inputHighlighter 0.3s ease;
}

/* ANIMATIONS ================ */
@-webkit-keyframes inputHighlighter {
 from { background:#5264AE; }
  to  { width:0; background:transparent; }
}
@-moz-keyframes inputHighlighter {
 from { background:#5264AE; }
  to  { width:0; background:transparent; }
}
@keyframes inputHighlighter {
 from { background:#5264AE; }
  to  { width:0; background:transparent; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <h2>Material Design in  CSS3<small>Inputs</small></h2>

  <form>

    <div class="group">
      <input type="text" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>Name</label>
    </div>

    <div class="group">
      <input type="text" required>
      <span class="bar"></span>
      <label>Email</label>
    </div>

    <div class="group">
      <input type="text" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>Email</label>
    </div>

  </form>

</div></code>```

happy Coding:)

Title: How to animate background-color center to right and left like google form?

Body:
i really lack of css animation. i try to create animation effect on div like google form.

if above link not work (like in my pc now), you can see it here https://ibb.co/cYsYKb

i try transition: all 1s ease; background: linear-gradient(to right, #673ab7);  but not work.

this is my fiddle: https://jsfiddle.net/hL8mncqa/

i try to find it in google, but still cant solve my problem, since i dont know what keyword to find it.

How to do this? any advice are welcome.

Body:
This is What you Looking for..

* { box-sizing:border-box; }

/* basic stylings ------------------------------------------ */
body      { background:url(https://scotch.io/wp-content/uploads/2014/07/61.jpg); }
.container   {
  font-family:'Roboto';
  width:600px;
  margin:30px auto 0;
  display:block;
  background:#FFF;
  padding:10px 50px 50px;
}
h2    {
  text-align:center;
  margin-bottom:50px;
}
h2 small {
  font-weight:normal;
  color:#888;
  display:block;
}
.footer  { text-align:center; }
.footer a  { color:#53B2C8; }

/* form starting stylings ------------------------------- */
.group      {
  position:relative;
  margin-bottom:45px;
}
input     {
  font-size:18px;
  padding:10px 10px 10px 5px;
  display:block;
  width:300px;
  border:none;
  border-bottom:1px solid #757575;
}
input:focus   { outline:none; }

/* LABEL ======================================= */
label      {
  color:#999;
  font-size:18px;
  font-weight:normal;
  position:absolute;
  pointer-events:none;
  left:5px;
  top:10px;
  transition:0.2s ease all;
  -moz-transition:0.2s ease all;
  -webkit-transition:0.2s ease all;
}

/* active state */
input:focus ~ label, input:valid ~ label   {
  top:-20px;
  font-size:14px;
  color:#5264AE;
}

/* BOTTOM BARS ================================= */
.bar  { position:relative; display:block; width:300px; }
.bar:before, .bar:after  {
  content:'';
  height:4px;
  width:0;
  bottom:0px;
  position:absolute;
  background:#5264AE;
  transition:0.2s ease all;
  -moz-transition:0.2s ease all;
  -webkit-transition:0.2s ease all;
}
.bar:before {
  left:50%;
}
.bar:after {
  right:50%;
}

/* active state */
input:focus ~ .bar:before, input:focus ~ .bar:after {
  width:50%;
}

/* HIGHLIGHTER ================================== */
.highlight {
  position:absolute;
  height:60%;
  width:100px;
  top:25%;
  left:0;
  pointer-events:none;
  opacity:0.5;
}

/* active state */
input:focus ~ .highlight {
  -webkit-animation:inputHighlighter 0.3s ease;
  -moz-animation:inputHighlighter 0.3s ease;
  animation:inputHighlighter 0.3s ease;
}

/* ANIMATIONS ================ */
@-webkit-keyframes inputHighlighter {
 from { background:#5264AE; }
  to  { width:0; background:transparent; }
}
@-moz-keyframes inputHighlighter {
 from { background:#5264AE; }
  to  { width:0; background:transparent; }
}
@keyframes inputHighlighter {
 from { background:#5264AE; }
  to  { width:0; background:transparent; }
}

<div class="container">

  <h2>Material Design in  CSS3<small>Inputs</small></h2>

  <form>

    <div class="group">
      <input type="text" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>Name</label>
    </div>

    <div class="group">
      <input type="text" required>
      <span class="bar"></span>
      <label>Email</label>
    </div>

    <div class="group">
      <input type="text" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>Email</label>
    </div>

  </form>

</div>

happy Coding:)


问:
How can I reorder a list?
Given an arbitrary array of size n, I'd like to reorganize the elements of the array based on the array's discrete indices.

Python example:

# Unique array of size n
[ "a", "b", "c", "d", "e", ... <n> ]

# Indices of array
[ 0, 1, 2, 3, 4, ... <index_of_n> ]

# Desired re-organization function 'indexMove'
indexMove(
    [ "a", "b", "c", "d", "e", ... <n> ],
    [ <index_of_n>, 4, 0, 2, 3, ... 1 ]
)

# Desired output from indexMove operation
[ <n>, "e", "a", "c", "d", ... "b" ]
```

What is the fastest way to perform this operation (achieving the smallest time complexity)?

答:
One more thing which can be considered is the other interpretation as pointed out by darkless

Code in Python 2.7

Mainly:

Reorder by value - Already solved by AJ above

Reorder by index

```<code>mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]

mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
print [item[0] for item in mylist]
</code>```

This will print ['c', 'd', 'b', 'a', 'e']

Title: How can I reorder a list?

Body:
Given an arbitrary array of size n, I'd like to reorganize the elements of the array based on the array's discrete indices.

Python example:

# Unique array of size n
[ "a", "b", "c", "d", "e", ... <n> ]

# Indices of array
[ 0, 1, 2, 3, 4, ... <index_of_n> ]

# Desired re-organization function 'indexMove'
indexMove(
    [ "a", "b", "c", "d", "e", ... <n> ],
    [ <index_of_n>, 4, 0, 2, 3, ... 1 ]
)

# Desired output from indexMove operation
[ <n>, "e", "a", "c", "d", ... "b" ]

What is the fastest way to perform this operation (achieving the smallest time complexity)?

Body:
One more thing which can be considered is the other interpretation as pointed out by darkless

Code in Python 2.7

Mainly:

Reorder by value - Already solved by AJ above

Reorder by index

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]

mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
print [item[0] for item in mylist]

This will print ['c', 'd', 'b', 'a', 'e']


问:
Perl, ppm, and trying to download module dependencies
I have Strawberry Perl and PPM installed.  I am no stranger to installing modules by hand from CPAN, but recently came into one of those situations where a module required one dependency and -that- dependency required twenty..

So I decided to give PPM a whirl (because that automatically installs dependencies, right?), and I initially thought it worked like Ruby Gems.  I loaded it and typed:

```<code>ppm> install OLE::Storage_Lite
</code>```

from this tutorial.

Then I ran into the problem saying 'Could not locate a PPDfile'.

So I followed this tutorial which walks you through hooking up a link to a repository, and it still couldn't find the PPD file.

My question is: Can anyone help me load a Perl module so I can read and write from Excel files!?

Solved: My problem turned out to be a proxy server at work that wouldn't allow me to download packages through PPM.

答:
Two things:

CPAN can install dependencies too!  :)  just do a cpan install My::Module on the command line to get your module and its dependencies installed.

Use Win32::OLE instead.

Win32::OLE is the standard module for interacting with COM and OLE objects in windows, and it works great.  It's already included with Strawberry Perl, and it works well!  You just need to look at the documents regarding Perl and 'OLE Automation'.  It would look something like this:

```<code>use strict;
use warnings;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Excel';  # brin in Excel constants

my $excel = Win32::OLE->new('Excel.Application') or die "oops\n";
</code>```

In fact, if you check out the Win32::OLE docs on CPAN, you'll see that they have several examples right there on how to get Excel automation working.

After that, a quick search for "Excel OLE Automation" will bring up a lot of tutorials showing you all the methods you need to call and quirks of Excel.  But after that, it's pretty straight forward!  Some examples:

```<code>my $sheet = $excel->Worksheets(1);  #Gets the first worksheet, 1 indexed
$sheet->Cells($row, $col); # do something to a cell
$sheet->Columns("A:D");    # do something to some columns
$sheet->Rows($row_number); # do something to a row
</code>```

There's obviously a lot more (The excel API is pretty vast) but this should get ya started.

Body:
I have Strawberry Perl and PPM installed.  I am no stranger to installing modules by hand from CPAN, but recently came into one of those situations where a module required one dependency and -that- dependency required twenty..

So I decided to give PPM a whirl (because that automatically installs dependencies, right?), and I initially thought it worked like Ruby Gems.  I loaded it and typed:

ppm> install OLE::Storage_Lite

from this tutorial.

Then I ran into the problem saying 'Could not locate a PPDfile'.

So I followed this tutorial which walks you through hooking up a link to a repository, and it still couldn't find the PPD file.

My question is: Can anyone help me load a Perl module so I can read and write from Excel files!?

Solved: My problem turned out to be a proxy server at work that wouldn't allow me to download packages through PPM.

Body:
Two things:

CPAN can install dependencies too!  :)  just do a cpan install My::Module on the command line to get your module and its dependencies installed.

Use Win32::OLE instead.

Win32::OLE is the standard module for interacting with COM and OLE objects in windows, and it works great.  It's already included with Strawberry Perl, and it works well!  You just need to look at the documents regarding Perl and 'OLE Automation'.  It would look something like this:

use strict;
use warnings;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Excel';  # brin in Excel constants

my $excel = Win32::OLE->new('Excel.Application') or die "oops\n";

In fact, if you check out the Win32::OLE docs on CPAN, you'll see that they have several examples right there on how to get Excel automation working.

After that, a quick search for "Excel OLE Automation" will bring up a lot of tutorials showing you all the methods you need to call and quirks of Excel.  But after that, it's pretty straight forward!  Some examples:

my $sheet = $excel->Worksheets(1);  #Gets the first worksheet, 1 indexed
$sheet->Cells($row, $col); # do something to a cell
$sheet->Columns("A:D");    # do something to some columns
$sheet->Rows($row_number); # do something to a row

There's obviously a lot more (The excel API is pretty vast) but this should get ya started.


答:
Assuming you want to find the substring in the property value, you can use the following code:

const arr = [
  {a:'abc', b:'efg', c:'hij'},
  {a:'abc', b:'efg', c:'hij'},
  {a:'123', b:'456', c:'789'},
];

const search = 'a';

const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));

console.log(res);```

If you want to search the property name, use Object.keys instead of Object.values.

Please note that Object.values is a feature of ES2017.

Title: Javascript-searching for a string in the properties of an array of objects

Body: I have an array of JSON objects. Given a search string, I want to filter the array for only those objects which have that string as a substring of one of their properties. How do I do this efficiently?

Body:
Assuming you want to find the substring in the property value, you can use the following code:

const arr = [
  {a:'abc', b:'efg', c:'hij'},
  {a:'abc', b:'efg', c:'hij'},
  {a:'123', b:'456', c:'789'},
];

const search = 'a';

const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));

console.log(res);

If you want to search the property name, use Object.keys instead of Object.values.

Please note that Object.values is a feature of ES2017.


问:
json to nested ul li jquery / javascript
I am creating dynamic json using javascript from a drag and drop builder, Now I am unable to convert the json to Nested Ul li. The json is below. </p>

```<code>[
  {
    "id": "11",
    "name": "BALANCE"
  },
  {
    "id": "p1",
    "name": "Conditions",
    "nodes": [
      {
        "id": "p1-13",
        "name": "SPINAL CORD INJURY",
        "nodes": [
          {
            "id": "p1-13-12",
            "name": "STROKE",
            "nodes": [
              {
                "id": "p1-13-12-17",
                "name": "REACHING"
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": "p1-16",
    "name": "STRETCHES"
  },
  {
    "id": "p1-11",
    "name": "BALANCE"
  }
]
</code>```

答:
You can create a function and call recursively if there is nodes in item.

var json = [{"id":"11","name":"BALANCE"},{"id":"p1","name":"Conditions","nodes":[{"id":"p1-13","name":"SPINAL CORD INJURY","nodes":[{"id":"p1-13-12","name":"STROKE","nodes":[{"id":"p1-13-12-17","name":"REACHING"}]}]}]},{"id":"p1-16","name":"STRETCHES"},{"id":"p1-11","name":"BALANCE"}];

function createUl(data, $elm) {
  data.forEach(function(item) {
    var $li = $('
' + item.name + '
');
    $elm.append($li);

    if (item.nodes) {
      var $ul = $('

');
      $li.append($ul);
      createUl(item.nodes, $ul);
    }
  });
};

createUl(json, $('ul'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul></code>```

Body:
I am creating dynamic json using javascript from a drag and drop builder, Now I am unable to convert the json to Nested Ul li. The json is below.

[
  {
    "id": "11",
    "name": "BALANCE"
  },
  {
    "id": "p1",
    "name": "Conditions",
    "nodes": [
      {
        "id": "p1-13",
        "name": "SPINAL CORD INJURY",
        "nodes": [
          {
            "id": "p1-13-12",
            "name": "STROKE",
            "nodes": [
              {
                "id": "p1-13-12-17",
                "name": "REACHING"
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": "p1-16",
    "name": "STRETCHES"
  },
  {
    "id": "p1-11",
    "name": "BALANCE"
  }
]

Body:
You can create a function and call recursively if there is nodes in item.

var json = [{"id":"11","name":"BALANCE"},{"id":"p1","name":"Conditions","nodes":[{"id":"p1-13","name":"SPINAL CORD INJURY","nodes":[{"id":"p1-13-12","name":"STROKE","nodes":[{"id":"p1-13-12-17","name":"REACHING"}]}]}]},{"id":"p1-16","name":"STRETCHES"},{"id":"p1-11","name":"BALANCE"}];

function createUl(data, $elm) {
  data.forEach(function(item) {
    var $li = $('<li><span>' + item.name + '</span></li>');
    $elm.append($li);

    if (item.nodes) {
      var $ul = $('<ul></ul>');
      $li.append($ul);
      createUl(item.nodes, $ul);
    }
  });
};

createUl(json, $('ul'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>


问:
Webdriverio/chimpjs - Launch Google Chrome with Gelocation permitted
I am writing a web application that depends heavily on geolocation. I am using chimpjs (combination of cucumber, webdriverio, chai) to do my BDD. I would like to launch google chrome with geolocation allowed. I think I must do this because I can find no way to click the Allow button in chrome to allow geolocation.

I have a chimp.js config file in my cucumber directory. Here are its contents:

```<code>module.exports = {
  webdriverio: {
    desiredCapabilities: {
      chromeOptions: {
        deviceName: 'Google Nexus 5'
      }
    }
  },
  browser: 'chrome',
  watch: false,
  path: './features',
  chai: true,
  screenshotsPath: '.screenshots'
};
</code>```

I know that:

chrome uses profile information that may be provided around runtime

there is an option 'geolocation' which must be set to 1

some other relevant nesting are 'prefs' and 'default_content_setting_values', which I learned about from digging through my chrome preferences

What I cannot figure out is which among these need to be passed to chromeOptions, and what needs to be nested where.

I am sure I cannot be the only person who ever needed to launch chrome with webdriver and have geolocation enabled.

答:
You can simply configure this in chromeOptions with profile.default_content_setting_values.geolocation.

```<code>chromeOptions: {
  deviceName: 'Google Nexus 5'
  prefs: {
    "profile.default_content_setting_values.geolocation": 1,
  }
},
</code>```

Body:
I am writing a web application that depends heavily on geolocation. I am using chimpjs (combination of cucumber, webdriverio, chai) to do my BDD. I would like to launch google chrome with geolocation allowed. I think I must do this because I can find no way to click the Allow button in chrome to allow geolocation.

I have a chimp.js config file in my cucumber directory. Here are its contents:

module.exports = {
  webdriverio: {
    desiredCapabilities: {
      chromeOptions: {
        deviceName: 'Google Nexus 5'
      }
    }
  },
  browser: 'chrome',
  watch: false,
  path: './features',
  chai: true,
  screenshotsPath: '.screenshots'
};

I know that:

chrome uses profile information that may be provided around runtime

there is an option 'geolocation' which must be set to 1

some other relevant nesting are 'prefs' and 'default_content_setting_values', which I learned about from digging through my chrome preferences

What I cannot figure out is which among these need to be passed to chromeOptions, and what needs to be nested where.

I am sure I cannot be the only person who ever needed to launch chrome with webdriver and have geolocation enabled.

Body:
You can simply configure this in chromeOptions with profile.default_content_setting_values.geolocation.

chromeOptions: {
  deviceName: 'Google Nexus 5'
  prefs: {
    "profile.default_content_setting_values.geolocation": 1,
  }
},


问:
How to pass json to post request with jsp?
I have problem with sending params to post method. Maybe, I'm sending the input parameters wrong there, beacause this request get 400 error

My strcuter of method:

```<code>@RequestMapping(value = "/create", method = RequestMethod.POST, headers = "Accept=application/json")
  public @ResponseBody
  String createProject(@RequestBody TestClass project) {
  return "success";
  }
</code>```

Object:

```<code>public class TestClass {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}
</code>```

JSP:

```<code><%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Result</title>
</head>
<body>
Successful create project
</body>
</html>
</code>```

And this i send from postman, but  400 error:
image of postman

答:
As per the spring documentation here,

Expressions passed to the constructor with header names 'Accept' or
  'Content-Type' are ignored.

Can you try with produces and consumes attributes for Accept and Content-Type?

Body:
I have problem with sending params to post method. Maybe, I'm sending the input parameters wrong there, beacause this request get 400 error

My strcuter of method:

@RequestMapping(value = "/create", method = RequestMethod.POST, headers = "Accept=application/json")
  public @ResponseBody
  String createProject(@RequestBody TestClass project) {
  return "success";
  }

Object:

public class TestClass {

  private String name;
  private int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }
}

JSP:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <title>Result</title>

Successful create project

And this i send from postman, but  400 error:
image of postman