问:
Configure firewall under Win7 for different interfaces command line
Im looking forward to configure my firewall under windows 7 for different interfaces throught a .bat file using netsh
In Win XP netsh has the parameter "interface" which allow me to specify the interface that I intend to enable the firewall for it, the opening ports for it...
In windows 7 the parameter interface is not supported anymore.
Any idea on how can I deal with it ?

Thank you very much for the help

答:
For those who are interested, i found a solution to my problem with vbscript :

```<code>option explicit

Const NET_FW_PROFILE2_DOMAIN = 1
Const NET_FW_PROFILE2_PRIVATE = 2
Const NET_FW_PROFILE2_PUBLIC = 4

Dim fwPolicy2
Dim InterfaceArray

Set fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")

InterfaceArray = Array("LAN")

fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_DOMAIN) = InterfaceArray
fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_PRIVATE) = InterfaceArray
fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_PUBLIC) = InterfaceArray
</code>```

-> my interface's name is LAN, if you want to disable firewall for many interfaces, just add them to the array : Array ("LAN1", "LAN2", ...). You can choose the profile on which you want to disable the firewall : domain, public or private

Body:
For those who are interested, i found a solution to my problem with vbscript :

option explicit

Const NET_FW_PROFILE2_DOMAIN = 1
Const NET_FW_PROFILE2_PRIVATE = 2
Const NET_FW_PROFILE2_PUBLIC = 4

Dim fwPolicy2
Dim InterfaceArray

Set fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")

InterfaceArray = Array("LAN")

fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_DOMAIN) = InterfaceArray
fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_PRIVATE) = InterfaceArray
fwPolicy2.ExcludedInterfaces(NET_FW_PROFILE2_PUBLIC) = InterfaceArray

-> my interface's name is LAN, if you want to disable firewall for many interfaces, just add them to the array : Array ("LAN1", "LAN2", ...). You can choose the profile on which you want to disable the firewall : domain, public or private


来源: stackexchange

问:
Is is possible to configure multiple git repositories in Spring Cloud Config Server
I would like to read some configurations from multiple git repositories, something like:

```<code>spring:
  profiles:
    active: base, app1, app2
  cloud:
    config:
      server:
        base:
          uri: http://${GIT_HOST}/base/base.git
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}
        app1:
          uri: http://${GIT_HOST}/group1/app1.git
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}
        app2:
          uri: http://${GIT_HOST}/group2/app2.git
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}
</code>```

At startup I see the following exception:

```<code>Caused by: java.lang.IllegalStateException: You need to configure a uri for the git repository
</code>```

The documentation shows an example using two different repos, git and svn. Can't we use multiple repos of the same kind?

答:
Due to the link of document you said, the svn and git after server is the type, not profile. So you cannot use base, app1, app2.
But in your case, I think you can use this kind of config: document link.

spring:
  cloud:
    config:
      server:
        git:
          uri: https://git/common/config-repo.git
          repos:
            team-a:
                pattern: team-a-*
                cloneOnStart: true
                uri: http://git/team-a/config-repo.git
            team-b:
                pattern: team-b-*
                cloneOnStart: false
                uri: http://git/team-b/config-repo.git
            team-c:
                pattern: team-c-*
                uri: http://git/team-a/config-repo.git
```

ContentLicense: CC BY-SA 3.0

Body:
I would like to read some configurations from multiple git repositories, something like:

spring:
  profiles:
    active: base, app1, app2
  cloud:
    config:
      server:
        base:
          uri: http://${GIT_HOST}/base/base.git
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}
        app1:
          uri: http://${GIT_HOST}/group1/app1.git
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}
        app2:
          uri: http://${GIT_HOST}/group2/app2.git
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}

At startup I see the following exception:

Caused by: java.lang.IllegalStateException: You need to configure a uri for the git repository

The documentation shows an example using two different repos, git and svn. Can't we use multiple repos of the same kind?


问:
How to improve performance in this DML statement?
Hi
This statements are executed in Stored Procedure. I am passing parameters and It is doing multiple updates and inserts.
I will appreciate some suggestions to
-improve the performance,
-reduce the execution time
-and improvements in code structure.
There are three different tables: Table_01, Table_02, Table_03.</p>

```<code>INSERT INTO Table_01(
    TestID,
    TestData,
    CurrentDate,
    UserID,
    Status
) VALUES (
    @testID,
    @testData,
    @iDateTime,
    @userID,
    @Status
)

IF (@Status = 1)
BEGIN

    DELETE FROM
        Table_02
    WHERE
        TestID = @testID

    UPDATE Table_03
    SET
        Status = 1,
        Date = @iDateTime,
        Work = 0
    WHERE
        TestID = @testID
END
</code>```

答:
Not really much to tweak to be honest: it's straightforward code, nothing fancy

You can add a transaction so it all writes succeed or all writes fail.

If you find the code slow then I'd look at indexes on TestID and do you have triggers

ContentLicense: CC BY-SA 2.5

Body:
Hi
This statements are executed in Stored Procedure. I am passing parameters and It is doing multiple updates and inserts.
I will appreciate some suggestions to
-improve the performance,
-reduce the execution time
-and improvements in code structure.
There are three different tables: Table_01, Table_02, Table_03.

INSERT INTO Table_01(
    TestID,
    TestData,
    CurrentDate,
    UserID,
    Status
) VALUES (
    @testID,
    @testData,
    @iDateTime,
    @userID,
    @Status
)

IF (@Status = 1)
BEGIN

    DELETE FROM
        Table_02
    WHERE
        TestID = @testID

    UPDATE Table_03
    SET
        Status = 1,
        Date = @iDateTime,
        Work = 0
    WHERE
        TestID = @testID
END


问:
Cash contract CashIssueFlow to enable only specific party to selfIssueCash
I am testing out corda's inbuilt CashIssueFlow where a participant in the network can issue cash to itself. My Question is how can i enforce this on a contract level to only allow a specific party to self-issue cash so other participants in the node will not be able to selfIssueCash?

答:
In theory, you could write your own Cash contract to prevent anyone but a specific party from issuing cash:

```<code>override fun verify(tx: LedgerTransaction) {
    requireThat {
        val allStates = tx.outputsOfType<Cash.State>() + tx.inputsOfType<Cash.State>()
        "Only DUMMY CASH ISSUER can issue cash" using (allStates.all { it.amount.token.issuer == DUMMY_CASH_ISSUER })
    }
}
</code>```

However, it's likely that different nodes will want to accept cash from different issuers. One node may only want to accept cash from Banks A, B and C, while another node may only want to accept cash from Banks X, Y and Z.

You'd achieve this by modifying the flow logic installed on each node so that transactions involving cash not issued by specific trusted banks is rejected:

```<code>@InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val signedTx = otherPartyFlow.receive<SignedTransaction>().unwrap { tx ->
            // TODO: Checking of received transaction.
            tx
        }

        val ledgerTx = signedTx.toLedgerTransaction(serviceHub, false)
        val states = ledgerTx.inputsOfType<Cash.State>() + ledgerTx.outputsOfType<Cash.State>()

        if (!states.all { it.amount.token.issuer == DUMMY_CASH_ISSUER }) {
            throw FlowException("Cash not issued by trusted party.")
        }

        ...
    }
}
</code>```

Body:
In theory, you could write your own Cash contract to prevent anyone but a specific party from issuing cash:

override fun verify(tx: LedgerTransaction) {
    requireThat {
        val allStates = tx.outputsOfType<Cash.State>() + tx.inputsOfType<Cash.State>()
        "Only DUMMY CASH ISSUER can issue cash" using (allStates.all { it.amount.token.issuer == DUMMY_CASH_ISSUER })
    }
}

However, it's likely that different nodes will want to accept cash from different issuers. One node may only want to accept cash from Banks A, B and C, while another node may only want to accept cash from Banks X, Y and Z.

You'd achieve this by modifying the flow logic installed on each node so that transactions involving cash not issued by specific trusted banks is rejected:

@InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val signedTx = otherPartyFlow.receive<SignedTransaction>().unwrap { tx ->
            // TODO: Checking of received transaction.
            tx
        }

        val ledgerTx = signedTx.toLedgerTransaction(serviceHub, false)
        val states = ledgerTx.inputsOfType<Cash.State>() + ledgerTx.outputsOfType<Cash.State>()

        if (!states.all { it.amount.token.issuer == DUMMY_CASH_ISSUER }) {
            throw FlowException("Cash not issued by trusted party.")
        }

        ...
    }
}


问:
How to enable source maps in create-react-app?
everyone.

I am a new member of react and I created my app use create-reat-app .I used node-sass-chokidar package like react's document. But I don't know how to enable "source maps" of scss file.

Thanks for any help.

答:
Add the "--source-map" option with the value "true" as in the example below:</p>

```<code>node-sass-chokidar --source-map true --include-path ./node_modules src/styles/scss -o src/styles/css
</code>```

Body:
Add the "--source-map" option with the value "true" as in the example below:

node-sass-chokidar --source-map true --include-path ./node_modules src/styles/scss -o src/styles/css


问:
window.location.href.split('/').pop() returning special characters instead of actual value
I have the following url:

```<code>gr-dev.indegene.com/el-gr/ο-πόνος/τι-είναι-ο-πόνος;
</code>```

The problem is when i do:

```<code>window.location.href.split('/').pop()
</code>```

I get a bunch of special characters , such as the below:

```<code>"%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;"
</code>```

I just want to get τι-είναι-ο-πόνος instead of the above , how do i do that ?

答:
You are getting the correct value. With one problem, you are getting the encoding version of this value. So you need to decode.

You can do that like:

```<code>window.decodeURI(window.location.href.split('/').pop())
</code>```

to get the decoded version of the string.

More Info:

URLs only uses specific allowed characters like alphabetic characters, numerals and a few special characters that have a meaning in the URL string. So, any other character should be encoded so that they don't cause problems.

The string τι-είναι-ο-πόνος is not a normal character, so is treated as a special character, because of that needs to be encoding to "%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;"

So to get back the original string you need to decode as shown above

Body:
I have the following url:

gr-dev.indegene.com/el-gr/ο-πόνος/τι-είναι-ο-πόνος;

The problem is when i do:

window.location.href.split('/').pop()

I get a bunch of special characters , such as the below:

"%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;"

I just want to get τι-είναι-ο-πόνος instead of the above , how do i do that ?

Body:
You are getting the correct value. With one problem, you are getting the encoding version of this value. So you need to decode.

You can do that like:

window.decodeURI(window.location.href.split('/').pop())

to get the decoded version of the string.

More Info:

URLs only uses specific allowed characters like alphabetic characters, numerals and a few special characters that have a meaning in the URL string. So, any other character should be encoded so that they don't cause problems.

The string τι-είναι-ο-πόνος is not a normal character, so is treated as a special character, because of that needs to be encoding to "%CF%84%CE%B9-%CE%B5%CE%AF%CE%BD%CE%B1%CE%B9-%CE%BF-%CF%80%CF%8C%CE%BD%CE%BF%CF%82;"

So to get back the original string you need to decode as shown above


问:
Spring data mongodb application design and data aggregation
I was developing a little application with spring data mongo and angularjs.
Here is model :

```<code>public class Lease {
        @Id
        private String id;
        private long created;
        private Lessor lessor;
        private Lessee lessee;
      }

public class Payment {
        @Id
        private String id;
        private Integer month;
        private Integer year;
        private Long amount;
        private String leaseId;
     }
</code>```

I did not embed Payment model as I need it to have an id and edit it in its own form.
On the main page of the app it represents a list of leases with payments by month. The year is chosen in a select above the list.

How to better load leases with payments by year by month using rest: may be first load leases then inject ids to payments or there is a better solution? For the moment I chose to use aggregation:

```<code>LookupOperation lookupOperation = LookupOperation.newLookup().
                                  from("payment").
                                  localField("leaseId").
                                  foreignField("id").
                                  as("payments");

AggregationOperation match = Aggregation.match(Criteria.where("payments.year").is(year));
Aggregation aggregation = Aggregation.newAggregation(lookupOperation, match);

return mongoOperations.aggregate(aggregation, "lease", LeaseAggregation.class).getMappedResults();
</code>```

The problem is that match is exclusive here and for example if there are no payments in 2017, list of leases is empty. I saw "addFields" functionality in mongo by it is not yet implemented in spring data mongodb. A better json return for me would be :

```<code>{"leases" : [{"id" : 123, "created" : 12324343434, "payments" : [123, 455, 343, 323, 344, null, null, 332, 323, 232, 333, 434}]}
</code>```

where payments will represent twelve months of a particular year.

How can I obtain this with spring data mongodb?

Any help would be appreciated!

答:
Whenever Spring Data Mongo lacks an AggregationOperation you need (to reproduce $addFields, $redact...), a workaround (some may say quick and dirty solution) is to pass the raw aggregation to Spring, using directly the com.mongodb.client tools :

```<code>String collectionName = mongoTemplate.getCollectionName(Payment.class);
MongoCollection<Document> collection = mongoClient.getDatabase(mongoTemplate.getDb().getName()).getCollection(collectionName);

AggregateIterable<Document> ai = collection.aggregate(Arrays.asList(
    Document.parse(/* { "group" : { ... } } */)))
</code>```

MongoCollection.aggregate() is passed the aggregation pipeline as List<Document>  (in fact List<? extends Bson>  in raw form as suggested above using Document.parse(), and you can of course also use new Document()  to make it look more like proper OOP code. I tend to use the raw form when the raw aggregation is complex or as many nested components for nested Document are too much verbose for me, but that's a matter of taste.

2020 UPDATE.

Use this workaround instead. With this it's easy to use both AggregationOperation provided by Spring and your own "raw" aggregation stages in the same place.

Body:
I was developing a little application with spring data mongo and angularjs.
Here is model :

public class Lease {
        @Id
        private String id;
        private long created;
        private Lessor lessor;
        private Lessee lessee;
      }

public class Payment {
        @Id
        private String id;
        private Integer month;
        private Integer year;
        private Long amount;
        private String leaseId;
     }

I did not embed Payment model as I need it to have an id and edit it in its own form.
On the main page of the app it represents a list of leases with payments by month. The year is chosen in a select above the list.

How to better load leases with payments by year by month using rest: may be first load leases then inject ids to payments or there is a better solution? For the moment I chose to use aggregation:

LookupOperation lookupOperation = LookupOperation.newLookup().
                                  from("payment").
                                  localField("leaseId").
                                  foreignField("id").
                                  as("payments");

AggregationOperation match = Aggregation.match(Criteria.where("payments.year").is(year));
Aggregation aggregation = Aggregation.newAggregation(lookupOperation, match);

return mongoOperations.aggregate(aggregation, "lease", LeaseAggregation.class).getMappedResults();

The problem is that match is exclusive here and for example if there are no payments in 2017, list of leases is empty. I saw "addFields" functionality in mongo by it is not yet implemented in spring data mongodb. A better json return for me would be :

{"leases" : [{"id" : 123, "created" : 12324343434, "payments" : [123, 455, 343, 323, 344, null, null, 332, 323, 232, 333, 434}]}

where payments will represent twelve months of a particular year.

How can I obtain this with spring data mongodb?

Any help would be appreciated!

Body:
Whenever Spring Data Mongo lacks an AggregationOperation you need (to reproduce $addFields, $redact...), a workaround (some may say quick and dirty solution) is to pass the raw aggregation to Spring, using directly the com.mongodb.client tools :

String collectionName = mongoTemplate.getCollectionName(Payment.class);
MongoCollection<Document> collection = mongoClient.getDatabase(mongoTemplate.getDb().getName()).getCollection(collectionName);

AggregateIterable<Document> ai = collection.aggregate(Arrays.asList(
    Document.parse(/* { "group" : { ... } } */)))

MongoCollection.aggregate() is passed the aggregation pipeline as List<Document>  (in fact List<? extends Bson>  in raw form as suggested above using Document.parse(), and you can of course also use new Document()  to make it look more like proper OOP code. I tend to use the raw form when the raw aggregation is complex or as many nested components for nested Document are too much verbose for me, but that's a matter of taste.

2020 UPDATE.

Use this workaround instead. With this it's easy to use both AggregationOperation provided by Spring and your own "raw" aggregation stages in the same place.

ContentLicense: CC BY-SA 4.0


问:
Rounding value of BigDecimal
I want to create a method that take two parameters. The first one is the amount (String) and the second is the Rounding type based on rounding type. It should round a value up or round down or so on...

```<code>public static String roundingAmount(String amount, String mode) {
    if (amount != null) {
        double dAmt = Double.parseDouble(amount);
        if (mode.equalsIgnoreCase("Rounded"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.HALF_UP);
        else if (mode.equalsIgnoreCase("Round UP"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.CEILING);
        else if (mode.equalsIgnoreCase("Round Down"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.FLOOR);
        else if (mode.equalsIgnoreCase("NA")) {
            return amount;
        }
        String newNumber = String.format("%.2f", decimal.doubleValue());
        return newNumber;
    }
    return amount;
}
</code>```

It shows error decimal not found.
Can you help me?

答:
decimal is only defined inside each of the if branches, so it's out of scope outside them. You could declare it outside of those blocks, which may also save you some code duplication:

```<code>public static String roundingAmount(String amount,String mode){
     if(amount != null){
         double dAmt = Double.parseDouble(amount);
         BigDecimal decimal = new BigDecimal(dAmt); // Here!

        if (mode.equalsIgnoreCase("Rounded"))
            decimal = decimal.setScale(0, RoundingMode.HALF_UP);
        else if (mode.equalsIgnoreCase("Round UP"))
            decimal = decimal.setScale(0, RoundingMode.CEILING);
        else if(mode.equalsIgnoreCase("Round Down"))
            decimal = decimal.setScale(0, RoundingMode.FLOOR);
        else if(mode.equalsIgnoreCase("NA")) {
            return amount;
        }
        String newNumber = String.format("%.2f" , decimal.doubleValue());
        return newNumber;
    }
    return amount;
}
</code>```

Title: Rounding value of BigDecimal

Body:
I want to create a method that take two parameters. The first one is the amount (String) and the second is the Rounding type based on rounding type. It should round a value up or round down or so on...

public static String roundingAmount(String amount, String mode) {
    if (amount != null) {
        double dAmt = Double.parseDouble(amount);
        if (mode.equalsIgnoreCase("Rounded"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.HALF_UP);
        else if (mode.equalsIgnoreCase("Round UP"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.CEILING);
        else if (mode.equalsIgnoreCase("Round Down"))
            BigDecimal decimal = new BigDecimal(dAmt).setScale(0, RoundingMode.FLOOR);
        else if (mode.equalsIgnoreCase("NA")) {
            return amount;
        }
        String newNumber = String.format("%.2f", decimal.doubleValue());
        return newNumber;
    }
    return amount;
}

It shows error decimal not found.
Can you help me?

Body:
decimal is only defined inside each of the if branches, so it's out of scope outside them. You could declare it outside of those blocks, which may also save you some code duplication:

public static String roundingAmount(String amount,String mode){
     if(amount != null){
         double dAmt = Double.parseDouble(amount);
         BigDecimal decimal = new BigDecimal(dAmt); // Here!

        if (mode.equalsIgnoreCase("Rounded"))
            decimal = decimal.setScale(0, RoundingMode.HALF_UP);
        else if (mode.equalsIgnoreCase("Round UP"))
            decimal = decimal.setScale(0, RoundingMode.CEILING);
        else if(mode.equalsIgnoreCase("Round Down"))
            decimal = decimal.setScale(0, RoundingMode.FLOOR);
        else if(mode.equalsIgnoreCase("NA")) {
            return amount;
        }
        String newNumber = String.format("%.2f" , decimal.doubleValue());
        return newNumber;
    }
    return amount;
}


问:
fastest way to match fingerprints?
I am trying to check whether a fingerprint exists/matches in a huge collection of fingerprints (100,000 fingerprints). It will take more time to search for matches sequentially. is there any better way to search for match? is it possible to organize the fingerprints in a binary tree structure so that the number of comparisons can be reduced? if yes how can we do it? it would be helpful if the answers are in Java perspective.

edit:

I have all the fingerprints as .gif images. how can i convert the finger print images into data?

Thanks.

答:
1) You need to use Wavelet compression algorithm to encode the fingerprint in sequence of wavelet compression parameters:

0, -1, 2.4, 5.6.7.7, 32.-1.5, e.t.c.

2) You need to define match function, which will find some similarities, there are two options:

-the geometry approach (compare qudrants to qudrants, all field are spaced in continuous blocks by some space algorithm)

Pros:

hardware accelerated (SSE) pixel matching algorithm, normalization all fingerprints to a standart basis using affine transformation, f.e. to square 512x512 px

Cons:

Hight sensitivity in fingerprint quality (if a part of searched fingerprint is omittet totally)

-the topology approach (the connectivity of lines, arcs, the breakpoints, mutual positioning each other)

Pros:

Low sensibility to angle, position, and quality of fingerprint, can use the original image scale and direction;

Cons:

Low speed of analysis, highly dependent upon quality of an classification function,

3) You need to define some sort of a genetic algorithm to train the evaluate function on a known set of fingerprints

You knowledge system will be able to find fingerprints by the given sample, not known by the system, but trained to find some particular differences/matches, raises the probability of a successful search, lovering the probability of false matches upon the search.

Title: fastest way to match fingerprints?


问:
When using the OData Client for v4 to create/post a new entity we are not getting the auto-generated (auto-incremented) ID/Key back from the service
When using the OData Client (.NET) for v4 to create/post a new entity we are not getting the auto-generated (auto-incremented) ID/Key back from the service. When we create the new entity, we have no ID assigned (it is an 'int' so the value is '0'). After calling SaveChanges the result JSON response has the new auto-assigned id (e.g. '4662'). The issue is that the Entity on the client side still has '0' for its ID (it's not mapped back to the orig. entity).

I also opened the issue on GitHub: https://github.com/OData/odata.net/issues/775

Assemblies affected

Microsoft.Data.OData - v5.7.0

Microsoft.OData.Client - v6.15.0

Microsoft.OData.Core - v6.15.0

Microsoft.OData.Edm - v6.15.0

Reproduce steps

Save a new entity that will automatically have an ID assigned on the server-side (do not set this ID on the client-side)

After saving, check the ID property on your new entity (on the client-side)

Expected result

The newly created (and saved) entity will have the ID updated to match the server-side response (JSON) that came back to the client.

Actual result

JSON response form the server-side has the correct ID, but the Entity on the client-side is never updated with this new information.

答:
In order to support your scenario, some requirements want to be met.
For a full reference, see my sample project at GitHub.

Given a model:

```<code>public class Item {
    [Key] //define as key
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //used by EF to auto generate Ids and mapping them back on inserts
    public int Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string Name { get; set; }
}
</code>```

An EntityFramwork-DbContext:

```<code>public class SampleContext : DbContext {

    public SampleContext()
        : base("name=SampleContext") {
    }

    public DbSet<Person> Persons { get; set; }
    public DbSet<Item> Items { get; set; }

}
</code>```

A straight-forward OData-configuration:

```<code>var builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("Persons");
builder.EntitySet<Item>("Items");
config.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
</code>```

and a corresponding ODataController:

```<code>public class ItemsController : ODataController {

    private readonly SampleContext _Db;

    public ItemsController() {
        _Db = new SampleContext();
    }

    ...

    [ResponseType(typeof(CreatedODataResult<Item>))]
    public IHttpActionResult Post(Item p) {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        var inserted = _Db.Items.Add(p);

        _Db.SaveChanges();
        //return entity with any server side changes. This would also work for other DB-generated columns.
        return Created(inserted);
    }
}
</code>```

Should produce the desired result:

```<code>public void AddingItemTransportsServerGeneratedIdBackToClientSideModel() {

    var item = new Item() {
        Name = Guid.NewGuid().ToString()
    };

    var container = new Container(new Uri("http://localhost/ODataAutoId/odata"));
    container.AddToItems(item);
    container.SaveChanges();

    var actual = item.Id;
    var unexpected = 0;

    Assert.AreNotEqual(unexpected, actual);
}
</code>```

Your actual implementation might vary or miss some of the requirements. In order to help in your particular scenarion, provide more details, as stated in my comment.

Body:
In order to support your scenario, some requirements want to be met.
For a full reference, see my sample project at GitHub.

Given a model:

public class Item {
    [Key] //define as key
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //used by EF to auto generate Ids and mapping them back on inserts
    public int Id { get; set; }

    [Required(AllowEmptyStrings = false)]
    public string Name { get; set; }
}

An EntityFramwork-DbContext:

public class SampleContext : DbContext {

    public SampleContext()
        : base("name=SampleContext") {
    }

    public DbSet<Person> Persons { get; set; }
    public DbSet<Item> Items { get; set; }

}

A straight-forward OData-configuration:

var builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("Persons");
builder.EntitySet<Item>("Items");
config.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());

and a corresponding ODataController:

public class ItemsController : ODataController {

    private readonly SampleContext _Db;

    public ItemsController() {
        _Db = new SampleContext();
    }

    ...

    [ResponseType(typeof(CreatedODataResult<Item>))]
    public IHttpActionResult Post(Item p) {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        var inserted = _Db.Items.Add(p);

        _Db.SaveChanges();
        //return entity with any server side changes. This would also work for other DB-generated columns.
        return Created(inserted);
    }
}

Should produce the desired result:

public void AddingItemTransportsServerGeneratedIdBackToClientSideModel() {

    var item = new Item() {
        Name = Guid.NewGuid().ToString()
    };

    var container = new Container(new Uri("http://localhost/ODataAutoId/odata"));
    container.AddToItems(item);
    container.SaveChanges();

    var actual = item.Id;
    var unexpected = 0;

    Assert.AreNotEqual(unexpected, actual);
}

Your actual implementation might vary or miss some of the requirements. In order to help in your particular scenarion, provide more details, as stated in my comment.


问:
bind variable error in stored procedure
Here is my procedure code :

```<code>create or replace Procedure SP_CUSTOMER_PRODUCT_QRY
   ( PARENT_PARTYID IN varchar2,PRODUCT_ID IN varchar2,PRODUCT_STATUS IN varchar2,PAGING  IN varchar2,OFFSET IN varchar2,LIST_OF_PARTIES OUT VARCHAR2 )
AS
V_SQL_WHERE varchar2(10000):= null;
V_SQL varchar2(10000):='SELECT PARTYID FROM TABLE1';
    V_check varchar2(10000) := '' ;
BEGIN

    IF(PARENT_PARTYID IS NOT NULL) THEN
      V_SQL_WHERE := V_SQL_WHERE || ' PARENT_PARTYID=:1';
    END IF;

    IF(PRODUCT_ID IS NOT NULL) THEN

      IF (V_SQL_WHERE is not null) THEN
        V_SQL_WHERE := V_SQL_WHERE || ' AND ';
      END IF;

      V_SQL_WHERE := V_SQL_WHERE || ' PRODUCT_ID=:2';
    END IF;

    IF(PRODUCT_STATUS IS NOT NULL) THEN

      IF (V_SQL_WHERE is not null) THEN
         V_SQL_WHERE := V_SQL_WHERE || ' AND ';
      END IF;
      V_SQL_WHERE := V_SQL_WHERE || ' PRODUCT_STATUS=:3';

    END IF;

    IF (V_SQL_WHERE is not null) then
      V_SQL := V_SQL || ' WHERE ' || V_SQL_WHERE;
    end if;

    dbms_output.put_line(V_SQL);
        EXECUTE IMMEDIATE V_SQL INTO LIST_OF_PARTIES;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      V_check:= '' ;
    END;
</code>```

I have used bind variables ,unable to understand the issue.Is it mandatory to bind all parameters even if they are not used in procedure
When I am passing any input I am getting error as
java.sql.SQLException: ORA-01008: not all variables bound

答:
In this case there is no need for using dynamic plsql. Try to do this this way:</p>

```<code>CREATE OR REPLACE PROCEDURE SP_CUSTOMER_PRODUCT_QRY
   ( P_PARENT_PARTYID IN VARCHAR2,
     P_PRODUCT_ID IN VARCHAR2,
     P_PRODUCT_STATUS IN VARCHAR2,
     P_PAGING  IN VARCHAR2,
     P_OFFSET IN VARCHAR2,
     P_LIST_OF_PARTIES OUT VARCHAR2 )
AS
   CURSOR CUR_PARTYID
   IS
   SELECT PARTYID
   FROM TABLE1
   WHERE (P_PARENT_PARTYID IS NULL
        OR PARENT_PARTYID = P_PARENT_PARTYID)
        AND (P_PRODUCT_ID IS NULL
        OR PRODUCT_ID = P_PRODUCT_ID)
        AND (P_PRODUCT_STATUS IS NULL
        OR PRODUCT_STATUS = P_PRODUCT_STATUS);
BEGIN

    OPEN  CUR_PARTYID;
    FETCH CUR_PARTYID INTO P_LIST_OF_PARTIES;
    CLOSE CUR_PARTYID;

END;
/
</code>```

Title: bind variable error in stored procedure

Body:
Here is my procedure code :

create or replace Procedure SP_CUSTOMER_PRODUCT_QRY
   ( PARENT_PARTYID IN varchar2,PRODUCT_ID IN varchar2,PRODUCT_STATUS IN varchar2,PAGING  IN varchar2,OFFSET IN varchar2,LIST_OF_PARTIES OUT VARCHAR2 )
AS
V_SQL_WHERE varchar2(10000):= null;
V_SQL varchar2(10000):='SELECT PARTYID FROM TABLE1';
    V_check varchar2(10000) := '' ;
BEGIN

    IF(PARENT_PARTYID IS NOT NULL) THEN
      V_SQL_WHERE := V_SQL_WHERE || ' PARENT_PARTYID=:1';
    END IF;

    IF(PRODUCT_ID IS NOT NULL) THEN

      IF (V_SQL_WHERE is not null) THEN
        V_SQL_WHERE := V_SQL_WHERE || ' AND ';
      END IF;

      V_SQL_WHERE := V_SQL_WHERE || ' PRODUCT_ID=:2';
    END IF;

    IF(PRODUCT_STATUS IS NOT NULL) THEN

      IF (V_SQL_WHERE is not null) THEN
         V_SQL_WHERE := V_SQL_WHERE || ' AND ';
      END IF;
      V_SQL_WHERE := V_SQL_WHERE || ' PRODUCT_STATUS=:3';

    END IF;

    IF (V_SQL_WHERE is not null) then
      V_SQL := V_SQL || ' WHERE ' || V_SQL_WHERE;
    end if;

    dbms_output.put_line(V_SQL);
        EXECUTE IMMEDIATE V_SQL INTO LIST_OF_PARTIES;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      V_check:= '' ;
    END;

I have used bind variables ,unable to understand the issue.Is it mandatory to bind all parameters even if they are not used in procedure
When I am passing any input I am getting error as
java.sql.SQLException: ORA-01008: not all variables bound

Body:
In this case there is no need for using dynamic plsql. Try to do this this way:

CREATE OR REPLACE PROCEDURE SP_CUSTOMER_PRODUCT_QRY
   ( P_PARENT_PARTYID IN VARCHAR2,
     P_PRODUCT_ID IN VARCHAR2,
     P_PRODUCT_STATUS IN VARCHAR2,
     P_PAGING  IN VARCHAR2,
     P_OFFSET IN VARCHAR2,
     P_LIST_OF_PARTIES OUT VARCHAR2 )
AS
   CURSOR CUR_PARTYID
   IS
   SELECT PARTYID
   FROM TABLE1
   WHERE (P_PARENT_PARTYID IS NULL
        OR PARENT_PARTYID = P_PARENT_PARTYID)
        AND (P_PRODUCT_ID IS NULL
        OR PRODUCT_ID = P_PRODUCT_ID)
        AND (P_PRODUCT_STATUS IS NULL
        OR PRODUCT_STATUS = P_PRODUCT_STATUS);
BEGIN

    OPEN  CUR_PARTYID;
    FETCH CUR_PARTYID INTO P_LIST_OF_PARTIES;
    CLOSE CUR_PARTYID;

END;
/


问:
Javascript function inside a function -- confused about arguments

Hi everyone, I'm in the process of learning Javascript and I'm confused about having a function inside another function, in particular the argument part.

I've included a sample code from the lesson where it's looking to calculate the years until retirement for three people given their year of birth.

What I'm confused about is the year within the function yearUntilRetirement(name, year).

Shouldn't this be yearOfBirth instead of year since it's looking back at the calculateAge(yearOfBirth) function to find the age? Or is this argument only unique to the function it is currently in?

```<code>function calculateAge(yearOfBirth) {
    var age = 2016 - yearOfBirth;
    return age;
}

function yearsUntilRetirement(name, year) {
    var age = calculateAge(year);
    var retirement = 65 - age;
    console.log(name + ' retires in ' + retirement + ' years.');
}

yearsUntilRetirement('John', 1990);
yearsUntilRetirement('Mike', 1969);
yearsUntilRetirement('Mary', 1948);
</code>```

答:
Maybe this will clarify.

When you call yearsUntilRetirement(name, year), you pass in two values as the arguments. Such as yearsUntilRetirement("John", 1975). Then, inside of the function yearsUntilRetirement, the other function calculateAge is called, using the value of year as the argument. Since year is the value 1975, we get age = calculateAge(1975). Now, within the calculateAge function, the value 1975 is the value corresponding to yearOfBirth. So, running everything through, you get var age = 2016 - 1975.

If this is too drawn out, I will attempt to clarify further. Drop a comment if you need anything else.

Body:
Hi everyone, I'm in the process of learning Javascript and I'm confused about having a function inside another function, in particular the argument part.

I've included a sample code from the lesson where it's looking to calculate the years until retirement for three people given their year of birth.

What I'm confused about is the year within the function yearUntilRetirement(name, year).

Shouldn't this be yearOfBirth instead of year since it's looking back at the calculateAge(yearOfBirth) function to find the age? Or is this argument only unique to the function it is currently in?

function calculateAge(yearOfBirth) {
    var age = 2016 - yearOfBirth;
    return age;
}

function yearsUntilRetirement(name, year) {
    var age = calculateAge(year);
    var retirement = 65 - age;
    console.log(name + ' retires in ' + retirement + ' years.');
}

yearsUntilRetirement('John', 1990);
yearsUntilRetirement('Mike', 1969);
yearsUntilRetirement('Mary', 1948);


问:
How to call another variable inside ngFor loop
Need your help:

```<code>//ts file
export class SettingsPage {
  pays: [string] = [];
  gateways: string = '';
</code>```

I can successfully call both individually but when i call gateways inside pays loop it doesn't work:

```<code><ion-row>

  <ion-item *ngFor="let pay of pays">
  <ion-icon name="image" item-start></ion-icon>
  <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}">
  {{gateways.desc}}   // doesn't work inside the loop
  </ion-input>

{{gateways.desc}} // works fine outside the loop

</ion-row>
</code>```

答:
seems like you have not closed <ion-item *ngFor="let pay of pays"> tag

Try this hope it will work

```<code><ion-row>
    <ion-item *ngFor="let pay of pays">
          <ion-icon name="image" item-start></ion-icon>
          <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}">
          {{gateways.desc}}   // doesn't work inside the loop
          </ion-input>
    </ion-item> <!-- close this  tag -->
    {{gateways.desc}} // works fine outside the loop

</ion-row>
</code>```

Body:
Need your help:

//ts file
export class SettingsPage {
  pays: [string] = [];
  gateways: string = '';

I can successfully call both individually but when i call gateways inside pays loop it doesn't work:

<ion-row>

  <ion-item *ngFor="let pay of pays">
  <ion-icon name="image" item-start></ion-icon>
  <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}">
  {{gateways.desc}}   // doesn't work inside the loop
  </ion-input>

{{gateways.desc}} // works fine outside the loop

</ion-row>

Body:
seems like you have not closed <ion-item *ngFor="let pay of pays"> tag

Try this hope it will work

<ion-row>
    <ion-item *ngFor="let pay of pays">
          <ion-icon name="image" item-start></ion-icon>
          <ion-input type="text" [(ngModel)]="pay['payto']" placeholder="{{pay.name}}">
          {{gateways.desc}}   // doesn't work inside the loop
          </ion-input>
    </ion-item> <!-- close this  tag -->
    {{gateways.desc}} // works fine outside the loop

</ion-row>


问:
Fatal Exception: java.lang.NoClassDefFoundError
I have ViewDebug issue in some devices with Android OS 4.4.4. I use vector icon in my app. From fatal exeption description I don`t understand why it happened.

Crash:

```<code>Fatal Exception: java.lang.NoClassDefFoundError: android/graphics/drawable/Icon
   at java.lang.Class.getDeclaredMethods(Class.java)
   at java.lang.Class.getDeclaredMethods(Class.java:656)
   at android.view.ViewDebug.getExportedPropertyMethods(ViewDebug.java:960)
   at android.view.ViewDebug.exportMethods(ViewDebug.java:1047)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:997)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:983)
   at android.view.ViewDebug.dumpView(ViewDebug.java:900)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:870)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dump(ViewDebug.java:793)
   at android.view.ViewDebug.dispatchCommand(ViewDebug.java:416)
   at android.view.ViewRootImpl$W.executeCommand(ViewRootImpl.java:6258)
   at android.view.IWindow$Stub.onTransact(IWindow.java:65)
   at android.os.Binder.execTransact(Binder.java:404)
   at dalvik.system.NativeStart.run(NativeStart.java)
Caused by java.lang.ClassNotFoundException: Didn't find class "android.graphics.drawable.Icon" on path: DexPathList[[zip file "/data/app/com.minvideo.android-1.apk", zip file "/data/data/com.minvideo.android/code_cache/secondary-dexes/com.minvideo.android-1.apk.classes2.zip"],nativeLibraryDirectories=[/data/app-lib/com.minvideo.android-1, /vendor/lib, /system/lib]]
   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
   at java.lang.Class.getDeclaredMethods(Class.java)
   at java.lang.Class.getDeclaredMethods(Class.java:656)
   at android.view.ViewDebug.getExportedPropertyMethods(ViewDebug.java:960)
   at android.view.ViewDebug.exportMethods(ViewDebug.java:1047)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:997)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:983)
   at android.view.ViewDebug.dumpView(ViewDebug.java:900)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:870)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dump(ViewDebug.java:793)
   at android.view.ViewDebug.dispatchCommand(ViewDebug.java:416)
   at android.view.ViewRootImpl$W.executeCommand(ViewRootImpl.java:6258)
   at android.view.IWindow$Stub.onTransact(IWindow.java:65)
   at android.os.Binder.execTransact(Binder.java:404)
   at dalvik.system.NativeStart.run(NativeStart.java)
</code>```

Please, help me fix this crash, I don`t understand why i have it.

答:
Am faced same issue, fortunately it is fixed in latest released support library..

inside of app level .gradle  update library as latest version :

```<code>dependencies {
    compile 'com.android.support:appcompat-v7:27.0.0'
}
</code>```

Body:
I have ViewDebug issue in some devices with Android OS 4.4.4. I use vector icon in my app. From fatal exeption description I don`t understand why it happened.

Crash:

Fatal Exception: java.lang.NoClassDefFoundError: android/graphics/drawable/Icon
   at java.lang.Class.getDeclaredMethods(Class.java)
   at java.lang.Class.getDeclaredMethods(Class.java:656)
   at android.view.ViewDebug.getExportedPropertyMethods(ViewDebug.java:960)
   at android.view.ViewDebug.exportMethods(ViewDebug.java:1047)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:997)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:983)
   at android.view.ViewDebug.dumpView(ViewDebug.java:900)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:870)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dump(ViewDebug.java:793)
   at android.view.ViewDebug.dispatchCommand(ViewDebug.java:416)
   at android.view.ViewRootImpl$W.executeCommand(ViewRootImpl.java:6258)
   at android.view.IWindow$Stub.onTransact(IWindow.java:65)
   at android.os.Binder.execTransact(Binder.java:404)
   at dalvik.system.NativeStart.run(NativeStart.java)
Caused by java.lang.ClassNotFoundException: Didn't find class "android.graphics.drawable.Icon" on path: DexPathList[[zip file "/data/app/com.minvideo.android-1.apk", zip file "/data/data/com.minvideo.android/code_cache/secondary-dexes/com.minvideo.android-1.apk.classes2.zip"],nativeLibraryDirectories=[/data/app-lib/com.minvideo.android-1, /vendor/lib, /system/lib]]
   at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
   at java.lang.Class.getDeclaredMethods(Class.java)
   at java.lang.Class.getDeclaredMethods(Class.java:656)
   at android.view.ViewDebug.getExportedPropertyMethods(ViewDebug.java:960)
   at android.view.ViewDebug.exportMethods(ViewDebug.java:1047)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:997)
   at android.view.ViewDebug.dumpViewProperties(ViewDebug.java:983)
   at android.view.ViewDebug.dumpView(ViewDebug.java:900)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:870)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dumpViewHierarchy(ViewDebug.java:867)
   at android.view.ViewDebug.dump(ViewDebug.java:793)
   at android.view.ViewDebug.dispatchCommand(ViewDebug.java:416)
   at android.view.ViewRootImpl$W.executeCommand(ViewRootImpl.java:6258)
   at android.view.IWindow$Stub.onTransact(IWindow.java:65)
   at android.os.Binder.execTransact(Binder.java:404)
   at dalvik.system.NativeStart.run(NativeStart.java)

Please, help me fix this crash, I don`t understand why i have it.

Body:
Am faced same issue, fortunately it is fixed in latest released support library..

inside of app level .gradle  update library as latest version :

dependencies {
    compile 'com.android.support:appcompat-v7:27.0.0'
}


问:
Can't completely remove/uninstall wamp64 files

     I have recently been testing php files for a class. I've been using WampServer to test my code. The last time I used WampServer (about a year ago) I was able to have it fully functional with the green emblem appearing when running. After an update, the MySql Process had been the only process out of the 3 to stop working causing the Yellow/Orange emblem to appear.

I was able to run and test my code but ran into issues when starting to implement database features into the program. After searching online and trying different things, I decided it was best to just reinstall the program. With a clean install, things might get all things working again.

After going to the windows control panel and uninstalling WampServer, I received a message stating not all files could be removed and that I could later manually remove them.

In my computers root folder system C:\wamp64 the folder wamp64 is still there with most of the inside files being removed. All that is left is a bin file with two folders mariadb and mysql. Inside the mysql folder are 2 exe files mysql.exe and mysqlid.exe. When ever I try to delete any of these from the file explorer i get a pop up saying "The action cant be completed because the folder or a file in it is open in another program."

I have wampserver uninstalled at this point. So I dont know what can be using these processes. Im assuming it might be another program relating to MySql (but thats just a hunch an can be completely wrong).

I've opened taskmanager and cant find anything related to the files.

Ive tried to reinstall wampserver but these files are not replaced when wamperser is reinstalled and I am having the same mysql issues as before.

Ive once again uninstalled wampserver and have the same  C:\wamp64\bin folder not deleted.

If anyone as any had any similar issues and solved this please let me know what you did to resolve the issues.

答:
Type regedit in cmd and open HKEY_CURRENT_USER option in it and find wamp by pressing ctrl+F and if wamp found press delete. Finally restart the system and open C drive and press ctrl+delete on wamp folder. Hope this might helps you!

Alternatively you can use HelpUninstaller tool for complete removal. Here is the link to go helpuninstaller


问:
Firefox extensions: How to save the value of a javascript variable to local storage?
The popup of my extension has a checkbox:

```<code><div id="popup-content">
  <input id="checkBox" type="checkbox">
</div>
</code>```

The way it's set up now, if I click on the extension icon on the toolbar and check the checkbox in the popup, the value of the checkbox isn't saved when the popup disappears i.e. if I open the popup again it shows that the checkbox is unchecked. I did some searching around and found out that I needed to use the storage api and store the variable in the storage, but I'm not sure how to proceed. I saw the examples in the storage api documentation, but all of them use keys and values instead of simple variables. This is what my js file looks right now:

```<code>document.getElementById('checkBox').addEventListener('change', function() {
  var m = document.getElementById("checkBox").checked;
  browser.storage.local.set(m);
  alert(browser.storage.local.get("m"));
});
</code>```

I'm obviously doing something wrong here because I'm not getting any alert message stating the value of the checkbox. What am I doing wrong? Also, this is only half of the problem. How do I set it up such that if I reopen the popup, the checkbox will show checked if it was checked before?

答:
Firstly, browser.storage.local.set is asynchronous, so your alert is doomed to failure

secondly, according to the documentation you actually linked to, the usage is as follows

```<code>document.getElementById('checkBox').addEventListener('change', function() {
  var m = document.getElementById("checkBox").checked;
  browser.storage.local.set({m})
  .then(() => browser.storage.local.get({m:''}))
  .then(({m}) => alert(m));
});
</code>```

when the popup opens, you would do something like the following

```<code>browser.storage.local.get({m:''}).then(value => document.getElementById("checkBox").checked = !!value);
</code>```

Though I'm a bit vague as to where in your code you do that

Body:
The popup of my extension has a checkbox:

  <input id="checkBox" type="checkbox">

The way it's set up now, if I click on the extension icon on the toolbar and check the checkbox in the popup, the value of the checkbox isn't saved when the popup disappears i.e. if I open the popup again it shows that the checkbox is unchecked. I did some searching around and found out that I needed to use the storage api and store the variable in the storage, but I'm not sure how to proceed. I saw the examples in the storage api documentation, but all of them use keys and values instead of simple variables. This is what my js file looks right now:

document.getElementById('checkBox').addEventListener('change', function() {
  var m = document.getElementById("checkBox").checked;
  browser.storage.local.set(m);
  alert(browser.storage.local.get("m"));
});

I'm obviously doing something wrong here because I'm not getting any alert message stating the value of the checkbox. What am I doing wrong? Also, this is only half of the problem. How do I set it up such that if I reopen the popup, the checkbox will show checked if it was checked before?

Body:
Firstly, browser.storage.local.set is asynchronous, so your alert is doomed to failure

secondly, according to the documentation you actually linked to, the usage is as follows

document.getElementById('checkBox').addEventListener('change', function() {
  var m = document.getElementById("checkBox").checked;
  browser.storage.local.set({m})
  .then(() => browser.storage.local.get({m:''}))
  .then(({m}) => alert(m));
});

when the popup opens, you would do something like the following

browser.storage.local.get({m:''}).then(value => document.getElementById("checkBox").checked = !!value);

Though I'm a bit vague as to where in your code you do that


问:
How can I convert link as like attached image?

What this is called?

How to implement?

Is there any Lib/API?

答:
This feature is called Rich Link.

Rich Links Can Be easily implemented using  Android Link Preview Library

It is attained by adding the following to the gradle

add following repository

```<code>repositories {
  jcenter()
  maven { url 'https://github.com/leonardocardoso/mvn-repo/raw/master/maven-deploy' }
}
</code>```

Add the following gradle file

```<code>compile 'org.jsoup:jsoup:1.8.3' // required
compile 'com.leocardz:link-preview:2.0.0@aar'
</code>```

If you are using Proguard Rules add the following rule

```<code>-keeppackagenames org.jsoup.nodes
</code>```

Implementation

Intialisation

```<code>import com.leocardz.link.preview.library.TextCrawler;
// ...
// Create an instance of the TextCrawler to parse your url into a preview.
TextCrawler textCrawler = new TextCrawler();

// ..

// Create the callbacks to handle pre and post exicution of the preview generation.
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
    @Override
    public void onPre() {
        // Any work that needs to be done before generating the preview. Usually inflate
        // your custom preview layout here.
    }

    @Override
    public void onPos(SourceContent sourceContent, boolean b) {
        // Populate your preview layout with the results of sourceContent.
    }
};
</code>```

Generate Preview

```<code>textCrawler.makePreview( linkPreviewCallback, url);
</code>```

Try this please

Here is Another Library.

Body:
This feature is called Rich Link.

Rich Links Can Be easily implemented using  Android Link Preview Library

It is attained by adding the following to the gradle

add following repository

repositories {
  jcenter()
  maven { url 'https://github.com/leonardocardoso/mvn-repo/raw/master/maven-deploy' }
}

Add the following gradle file

compile 'org.jsoup:jsoup:1.8.3' // required
compile 'com.leocardz:link-preview:2.0.0@aar'

If you are using Proguard Rules add the following rule

-keeppackagenames org.jsoup.nodes

Implementation

Intialisation

import com.leocardz.link.preview.library.TextCrawler;
// ...
// Create an instance of the TextCrawler to parse your url into a preview.
TextCrawler textCrawler = new TextCrawler();

// ..

// Create the callbacks to handle pre and post exicution of the preview generation.
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
    @Override
    public void onPre() {
        // Any work that needs to be done before generating the preview. Usually inflate
        // your custom preview layout here.
    }

    @Override
    public void onPos(SourceContent sourceContent, boolean b) {
        // Populate your preview layout with the results of sourceContent.
    }
};

Generate Preview

textCrawler.makePreview( linkPreviewCallback, url);

Try this please

Here is Another Library.


问:
Replace cell values in specific sheets with defined name
I am trying to run some code that replaces the cell values in a specific column with a defined name. In addition, I have a condition that the replacement should only take place if the first 9 characters of the values are xxxxxxxxx.

More precisely, it should change the values in C:C in 2 specific worksheets (I don't want to loop through the whole workbook).

I am not sure why nothing happens in the code (no error messages, nothing).

I presume, however, that I should not use With if I want the code to work in these 2 specific worksheets. I am also aware that my use of Range is probably not totally correct.

```<code>Sub ChangeMe()

  Dim cl As Range

  For Each cl In Worksheets("Sheet1").Range("C:C").End(xlUp)
    With Worksheets("Sheet2").Range("C:C").End(xlUp)
      If Left(cl.Value, 9) = "XXXXXXXXX" Then
        cl.Value = ThisWorkbook.Names("MyDefinedName").RefersToRange
      End If
    End With
  Next cl

End Sub
</code>```

答:
In answer your original questions:

I am not sure why nothing happens in the code (no error messages, nothing).

Nothing happens because your worksheet values are lowercase xxxxxxxxx, whilst your code checks for uppercase XXXXXXXXX.

I presume, however, that I should not use With if I want the code to work in these 2 specific worksheets.

Actually, you can use With with multiple sheets, as I will demonstrate below.

I am also aware that my use of Range is probably not totally correct.

That is true. If you were to fix the uppercase issue, only C1 would be changed. This is because .End() works on a single cell. If you supply a multi-cell range, it uses the top left most cell. So .Range("C:C").End(xlUp) is equivalent to .Range("C1").End(xlUp) which evaluates to just C1.

The following will answer your updated question:

```<code>Option Explicit

Public Sub ChangeMe()

  Const l_xxxxxxxxx      As String = "xxxxxxxxx"
  Const l_MyDefinedName  As String = "MyDefinedName"
  Const s_Delimiter      As String = ","
  Const s_WorkSheetNames As String = "Sheet1,Sheet2"
  Const s_ColumnToChange As String = "C:C"

  Dim varWorkSheetName As Variant
  For Each varWorkSheetName In Split(s_WorkSheetNames, s_Delimiter)
    With Worksheets(varWorkSheetName).Range(s_ColumnToChange)
      Dim rngCell As Range
      For Each rngCell In .Resize(.Cells(Rows.Count).End(xlUp).Row)
        With rngCell
          Dim strCellValue As String: strCellValue = .Value2
          If Left(strCellValue, Len(l_xxxxxxxxx)) = l_xxxxxxxxx Then
            .Value2 _
            = Names(l_MyDefinedName).RefersToRange.Value2 _
            & Right$(strCellValue, Len(strCellValue) - Len(l_xxxxxxxxx))
          End If
        End With
      Next rngCell
    End With
  Next varWorkSheetName

End Sub
</code>```

Notes:

It is a good idea to use constants so all literal values are typed once only and kept grouped together.

Using .Value2, instead of .Value, is the recommended way to access a cell's value as it avoids implicit casting and is therefore faster. (Using .Value can also sometimes cause issues.)

Surprisingly, in VBA there are good reasons to put a variable declaration as close as possible to the first use of the variable. Two such reasons are 1) it improves readability, and 2) it simplifies future refactoring. Just remember that the variable is not reinitialised every time the Dim is encountered. Initialisation only occurs the first time.

Body:
I am trying to run some code that replaces the cell values in a specific column with a defined name. In addition, I have a condition that the replacement should only take place if the first 9 characters of the values are xxxxxxxxx.

More precisely, it should change the values in C:C in 2 specific worksheets (I don't want to loop through the whole workbook).

I am not sure why nothing happens in the code (no error messages, nothing).

I presume, however, that I should not use With if I want the code to work in these 2 specific worksheets. I am also aware that my use of Range is probably not totally correct.

Sub ChangeMe()

  Dim cl As Range

  For Each cl In Worksheets("Sheet1").Range("C:C").End(xlUp)
    With Worksheets("Sheet2").Range("C:C").End(xlUp)
      If Left(cl.Value, 9) = "XXXXXXXXX" Then
        cl.Value = ThisWorkbook.Names("MyDefinedName").RefersToRange
      End If
    End With
  Next cl

End Sub

Body:
In answer your original questions:

I am not sure why nothing happens in the code (no error messages, nothing).

Nothing happens because your worksheet values are lowercase xxxxxxxxx, whilst your code checks for uppercase XXXXXXXXX.

I presume, however, that I should not use With if I want the code to work in these 2 specific worksheets.

Actually, you can use With with multiple sheets, as I will demonstrate below.

I am also aware that my use of Range is probably not totally correct.

That is true. If you were to fix the uppercase issue, only C1 would be changed. This is because .End() works on a single cell. If you supply a multi-cell range, it uses the top left most cell. So .Range("C:C").End(xlUp) is equivalent to .Range("C1").End(xlUp) which evaluates to just C1.

The following will answer your updated question:

Option Explicit

Public Sub ChangeMe()

  Const l_xxxxxxxxx      As String = "xxxxxxxxx"
  Const l_MyDefinedName  As String = "MyDefinedName"
  Const s_Delimiter      As String = ","
  Const s_WorkSheetNames As String = "Sheet1,Sheet2"
  Const s_ColumnToChange As String = "C:C"

  Dim varWorkSheetName As Variant
  For Each varWorkSheetName In Split(s_WorkSheetNames, s_Delimiter)
    With Worksheets(varWorkSheetName).Range(s_ColumnToChange)
      Dim rngCell As Range
      For Each rngCell In .Resize(.Cells(Rows.Count).End(xlUp).Row)
        With rngCell
          Dim strCellValue As String: strCellValue = .Value2
          If Left(strCellValue, Len(l_xxxxxxxxx)) = l_xxxxxxxxx Then
            .Value2 _
            = Names(l_MyDefinedName).RefersToRange.Value2 _
            & Right$(strCellValue, Len(strCellValue) - Len(l_xxxxxxxxx))
          End If
        End With
      Next rngCell
    End With
  Next varWorkSheetName

End Sub

Notes:

It is a good idea to use constants so all literal values are typed once only and kept grouped together.

Using .Value2, instead of .Value, is the recommended way to access a cell's value as it avoids implicit casting and is therefore faster. (Using .Value can also sometimes cause issues.)

Surprisingly, in VBA there are good reasons to put a variable declaration as close as possible to the first use of the variable. Two such reasons are 1) it improves readability, and 2) it simplifies future refactoring. Just remember that the variable is not reinitialised every time the Dim is encountered. Initialisation only occurs the first time.


问:
How to specify a Column for VBA's Autofilter function by name rather than by its index?
I am new to VBA and trying to autofilter a column range. The column is named "Vlookup" and sits at index position 27.

```<code>rData.AutoFilter field:=27, Criteria1:="Class" ' filter criterion
</code>```

In order to make this dynamic, I need to be able to filter according to column name rather than column index.

However, when I do

```<code>rData.AutoFilter field:=Application.Match("Vlookup", Selection.Rows(1), 0), Criteria1:="Class"  ' filter criterion
</code>```

I yield

Runtime Error '424' - Object Required

How to correctly Autofilter by column name in VBA?

答:
You can use the Find function to find "Vlookup" in the header row, and then retrieve the numeric value of the Column.

Note: there's no need to use Selection, instead fully qualify your Rows(1) with your rData sheet object (use the With rData statement).

See code and comments below:

```<code>Dim FindRng As Range
Dim FiltCol As Long

With rData
    Set FindRng = .Rows(1).Find(what:="Vlookup")

    If Not FindRng Is Nothing Then ' Find was successful
        FiltCol = FindRng.Column ' get the column number where "Vlookup" was found
    Else ' find unable to find "Vlookup"
        MsgBox "Find Error!"
        Exit Sub
    End If

    .AutoFilter Field:=FiltCol, Criteria1:="Class" ' filter criterion
End With
</code>```

Body:
I am new to VBA and trying to autofilter a column range. The column is named "Vlookup" and sits at index position 27.

rData.AutoFilter field:=27, Criteria1:="Class" ' filter criterion

In order to make this dynamic, I need to be able to filter according to column name rather than column index.

However, when I do

rData.AutoFilter field:=Application.Match("Vlookup", Selection.Rows(1), 0), Criteria1:="Class"  ' filter criterion

I yield

Runtime Error '424' - Object Required

How to correctly Autofilter by column name in VBA?

Body:
You can use the Find function to find "Vlookup" in the header row, and then retrieve the numeric value of the Column.

Note: there's no need to use Selection, instead fully qualify your Rows(1) with your rData sheet object (use the With rData statement).

See code and comments below:

Dim FindRng As Range
Dim FiltCol As Long

With rData
    Set FindRng = .Rows(1).Find(what:="Vlookup")

    If Not FindRng Is Nothing Then ' Find was successful
        FiltCol = FindRng.Column ' get the column number where "Vlookup" was found
    Else ' find unable to find "Vlookup"
        MsgBox "Find Error!"
        Exit Sub
    End If

    .AutoFilter Field:=FiltCol, Criteria1:="Class" ' filter criterion
End With


问:
com.mongodb.util.JSONParseException in Spring Boot?

I tried to create custom query using @Query annotation. But it throws some error.

This is my Repository

```<code>package com.springboot.springmongodb.user;
import java.util.List;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

public interface UserRepository extends CrudRepository<User, String>{
    @Override
    User findOne(String id);

    @Transactional(readOnly=false)
    @Query("SELECT user FROM User user WHERE user.username = :username")
    public List<User> findByUsername(@Param("username") String username);

}
</code>```

I want to create custom query for check username.

Here the error which I'm getting.

2017-12-04 14:46:10.413  WARN 1452 --- [           main]
  ationConfigEmbeddedWebApplicationContext : Exception encountered
  during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'springSecurityFilterChain' defined in class
  path resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [javax.servlet.Filter]: Factory method
  'springSecurityFilterChain' threw exception; nested exception is
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'userDetailsService': Unsatisfied
  dependency expressed through field 'userRep'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'userRepository': Invocation of init method
  failed; nested exception is com.mongodb.util.JSONParseException:
  SELECT user FROM User user WHERE user.username = :username ^

答:
The exception tells that the @Query you gave gets treated as JSON. Taking a look at your imports leads us to the reason:

```<code>import org.springframework.data.mongodb.repository.Query;
</code>```

While your query SELECT user FROM User user WHERE user.username = :username would be valid for JPA (SQL), it's invalid for MongoDB. Either change your import to fit your database or change the query to fit it.

A valid mongoDB looks like from the Spring Data MongoDB example:

```<code>public interface PersonRepository extends MongoRepository<Person, String>

  @Query("{ 'username' : ?0 }")
  List<Person> findByThePersonsFirstname(String firstname);

}
</code>```

...And a valid JPA statement from the Spring Data JPA example:

```<code>public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.username = ?1")
  User findByEmailAddress(String emailAddress);
}
</code>```

This would need the import org.springframework.data.jpa.repository.Query

Body:
I tried to create custom query using @Query annotation. But it throws some error.

This is my Repository

package com.springboot.springmongodb.user;
import java.util.List;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

public interface UserRepository extends CrudRepository<User, String>{
    @Override
    User findOne(String id);

    @Transactional(readOnly=false)
    @Query("SELECT user FROM User user WHERE user.username = :username")
    public List<User> findByUsername(@Param("username") String username);

}

I want to create custom query for check username.

Here the error which I'm getting.

2017-12-04 14:46:10.413  WARN 1452 --- [           main]
  ationConfigEmbeddedWebApplicationContext : Exception encountered
  during context initialization - cancelling refresh attempt:
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'springSecurityFilterChain' defined in class
  path resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [javax.servlet.Filter]: Factory method
  'springSecurityFilterChain' threw exception; nested exception is
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'userDetailsService': Unsatisfied
  dependency expressed through field 'userRep'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'userRepository': Invocation of init method
  failed; nested exception is com.mongodb.util.JSONParseException:
  SELECT user FROM User user WHERE user.username = :username ^

Body:
The exception tells that the @Query you gave gets treated as JSON. Taking a look at your imports leads us to the reason:

import org.springframework.data.mongodb.repository.Query;

While your query SELECT user FROM User user WHERE user.username = :username would be valid for JPA (SQL), it's invalid for MongoDB. Either change your import to fit your database or change the query to fit it.

A valid mongoDB looks like from the Spring Data MongoDB example:

public interface PersonRepository extends MongoRepository<Person, String>

  @Query("{ 'username' : ?0 }")
  List<Person> findByThePersonsFirstname(String firstname);

}

...And a valid JPA statement from the Spring Data JPA example:

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.username = ?1")
  User findByEmailAddress(String emailAddress);
}

This would need the import org.springframework.data.jpa.repository.Query


问:
How to comma separate the values of an array for display
I have searched the PHP.net site and originally thought of some use for the list() function but doesn't seem to accomplish the goal:

I have an unknown number of values stored in a single array

$array1 = array(1,2,3,4,5);

or

$array1 = array(1,2,3);

I want to be able to echo (or print_r) the values contained within an array to screen and separated only by commas and spacing.

For example:

the 'idea' is to have echo $array1 to display:

1,2,3

from the second example above.

答:
You can simply use PHP's implode function for this purpose as follows:</p>

```<code>$string = implode(',', array(1,2,3,4,5));
</code>```

Body:
You can simply use PHP's implode function for this purpose as follows:

$string = implode(',', array(1,2,3,4,5));


问:
How to access recorded video filepath in react-native
**when i stop recording that capture video store in gallery so how to fetch that video so that i upload that video on server **

```<code>import Camera from 'react-native-camera';

    <Camera
                captureMode={this.state.captureMode}
                captureAudio={this.state.captureAudio}
                captureTarget={this.state.captureTarget}
                ref="camera"
                style={styles.preview}>

   { toggle? <TouchableOpacity onPress={() =>this._startRecord()}>
                           <Image style={styles.clickimage}
                             source={require('../images/icon_record_stop.png')} />
                      </TouchableOpacity>
            : <TouchableOpacity onPress={() =>this._endVideo()}>
                  <Image style={styles.clickimage}
                             source={require('../images/clickimage.png')} />
              </TouchableOpacity>
            }
      </Camera>

     _startRecord() {
      this.refs.camera.capture({mode: Camera.constants.CaptureMode.video})
        .then((data) => alert(data))
        .catch((err) => console.log(err))
      }

_endVideo() {
     this.refs.camera.stopCapture()
    .then((response) => {
               alert(response);

         // so here what i do for fetching video file path for upload
    }
</code>```

i just what to upload that recorded video on server....

答:
Read path from data.path, and then you can open file with react-native-fs.

From document:

path: Returns the path of the captured image or video file on disk

_startRecord() {
  this.refs.camera.capture({mode: Camera.constants.CaptureMode.video})
    .then((data) => {
      var path = data.path;
    })
    .catch((err) => console.log(err))
  }
}
```

Body:
**when i stop recording that capture video store in gallery so how to fetch that video so that i upload that video on server **

import Camera from 'react-native-camera';

    <Camera
                captureMode={this.state.captureMode}
                captureAudio={this.state.captureAudio}
                captureTarget={this.state.captureTarget}
                ref="camera"
                style={styles.preview}>

   { toggle? <TouchableOpacity onPress={() =>this._startRecord()}>
                           <Image style={styles.clickimage}
                             source={require('../images/icon_record_stop.png')} />
                      </TouchableOpacity>
            : <TouchableOpacity onPress={() =>this._endVideo()}>
                  <Image style={styles.clickimage}
                             source={require('../images/clickimage.png')} />
              </TouchableOpacity>
            }
      </Camera>

     _startRecord() {
      this.refs.camera.capture({mode: Camera.constants.CaptureMode.video})
        .then((data) => alert(data))
        .catch((err) => console.log(err))
      }

_endVideo() {
     this.refs.camera.stopCapture()
    .then((response) => {
               alert(response);

         // so here what i do for fetching video file path for upload
    }

i just what to upload that recorded video on server....


问:
setting up cluster between different datacenter in cassandra using apache cassandra
We have three node cluster in the same datacenter configured using private ip and every thing is working fine . We wanted to add the DR for this node.When we try to add the node using seed node as public-IP we are getting error as

ERROR [main] 2017-12-04 02:35:12,329 CassandraDaemon.java:747 - Exception encountered during startup
java.lang.RuntimeException: Unable to gossip with any seeds

Can someone help me with adding the node to the cluster which is on different data center?

答:
For the node in new DC:

Set the seeds value in cassandra.yaml to your seeds in your first DC. If you already have multiple DCs make sure to add seeds from those as well. You should have 2 seeds per DC.

Change endpoint_snitch value in cassandra.yaml to a snitch that supports multiple DCs. E.g. GossipingPropertyFileSnitch

Set dc value in cassandra-rackdc.properties.


问:
How can I get the returned value from the child_process.exec in javascript?
I tried the following code, it shows the res is undefined.
How can I return the stdout?</p>

```<code>function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
}
</code>```

答:
you can't get the return value except you use synchronous version of the exec function. if you are still hellbent on doing that, you should use a callback

```<code>function run_shell_command(command,cb) {
    exec(command, function(err,stdout,stderr){
        if(err) {
          cb(stderr);
        } else {
          cb(stdout);
       }
   });
}

run_shell_command("ls", function (result) {
   // handle errors here
} );
</code>```

or you can wrap the exec call in a promise and use async await

```<code>const util = require("util");
const { exec } = require("child_process");
const execProm = util.promisify(exec);

async function run_shell_command(command) {
   let result;
   try {
     result = await execProm(command);
   } catch(ex) {
      result = ex;
   }
   if ( Error[Symbol.hasInstance](result) )
       return ;

   return result;
}

run_shell_command("ls").then( res => console.log(res) );
</code>```

Body:
I tried the following code, it shows the res is undefined.
How can I return the stdout?

function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
}

Body:
you can't get the return value except you use synchronous version of the exec function. if you are still hellbent on doing that, you should use a callback

function run_shell_command(command,cb) {
    exec(command, function(err,stdout,stderr){
        if(err) {
          cb(stderr);
        } else {
          cb(stdout);
       }
   });
}

run_shell_command("ls", function (result) {
   // handle errors here
} );

or you can wrap the exec call in a promise and use async await

const util = require("util");
const { exec } = require("child_process");
const execProm = util.promisify(exec);

async function run_shell_command(command) {
   let result;
   try {
     result = await execProm(command);
   } catch(ex) {
      result = ex;
   }
   if ( Error[Symbol.hasInstance](result) )
       return ;

   return result;
}

run_shell_command("ls").then( res => console.log(res) );


问:
Google map api not showing in app when published to playstore
Map does not show in an app I've published.

Here is what I've done:

created API key and added Package name and SHA-1 certificate fingerprint via restricting usage to Android apps in the credentials tab of the Google API manager

I am confused as to which SHA-1 certificate fingerprint I need to use so I created a key for each. I found 4 SHA-1 certificate fingerprints from:

keytool -list -v -keystore mystore.keystore command

from the comments in the google_maps_api.xml file

from the Google Play console App signing certificate

from the Google Play console Upload certificate

I am unfamiliar with App Signing and if there is anything more I need to do please let me know.
I very much want the map to appear on the app!
If someone could show me the steps to make this happen pleas help me!!!!! :(

https://i.imgur.com/9g12KUz.png "API Keys"

https://i.imgur.com/so6haMQ.png "Terminal Command"

https://i.imgur.com/NBPIpVh.png "google_maps_api.xml comments"

https://i.imgur.com/MtQrzhp.png "App Signing"

答:
There are two google_maps_api.xml files in the app one for debug and another for release.

release : app\src\release\res\values\google_maps_api.xml

debug : app\src\debug\res\values\google_maps_api.xml

In your case the api key might be blank in release google_maps_api.xml

and if you didn't copy SHA1 App signing in Play store. replace with existing SHA1


问:
docker-compose, run a script after container has started?
I have a service that I am bringing up through Rancher via docker-compose. The issue I am running into is that I need to set a password after the container has been deployed.

The way rancher secrets work, is that I set my secret in and rancher will mount a volume on my container with a file containing my secret. I was hoping to be able to execute a script to grab that secret, and set it as a password on my config file.

I don't believe I have a way to get that secret in through the Dockerfile as I don't want the secret to be in git, so I'm left looking at doing it via docker-compose.

Does anyone know if this is possible?

答:
The trick is to overwrite the compose COMMAND to perform whatever init action you need before calling the original command.

Add a script in your image that will perform the init work that you want like set password, change internal config files, etc. Let's call it init.sh. You add it to your image.

Dockerfile:

```<code>FROM: sourceimage:tag
COPY init.sh /usr/local/bin/
ENTRYPOINT []
</code>```

The above overrides whatever ENTRYPOINT is defined in the sourceimage. That's to make this example simpler. Make sure you understand what the ENTRYPOINT is doing in the Dockerfile from the sourceimage and call it in the command: of the docker-compose.yml file.

docker-compose.yml:

```<code>services:
  myservice:
    image: something:tag
    ...
    command: sh -c "/usr/local/bin/init.sh && exec myexecutable"
</code>```

It's important to use exec before calling the main command. That will install the command as the first process (PID1) which will make it receive signals like STOP, KILL (Ctrl-C on keyboard) or HUP.

Body:
The trick is to overwrite the compose COMMAND to perform whatever init action you need before calling the original command.

Add a script in your image that will perform the init work that you want like set password, change internal config files, etc. Let's call it init.sh. You add it to your image.

Dockerfile:

FROM: sourceimage:tag
COPY init.sh /usr/local/bin/
ENTRYPOINT []

The above overrides whatever ENTRYPOINT is defined in the sourceimage. That's to make this example simpler. Make sure you understand what the ENTRYPOINT is doing in the Dockerfile from the sourceimage and call it in the command: of the docker-compose.yml file.

docker-compose.yml:

services:
  myservice:
    image: something:tag
    ...
    command: sh -c "/usr/local/bin/init.sh && exec myexecutable"

It's important to use exec before calling the main command. That will install the command as the first process (PID1) which will make it receive signals like STOP, KILL (Ctrl-C on keyboard) or HUP.


问:
Objective-C @interface nameofclass (whatisinhere)
I'm looking at NSArray.h which has

```<code>@interface NSMutableArray : NSArray
</code>```

which I understand. Just below is

```<code>@interface NSMutableArray (NSExtendedMutableArray)
</code>```

which I do not understand. I want to use the Extended version of this class, but can't figure out how. Just creating an object of class NSExtendedMutableArray doesn't seem to work.

答:
This is a language feature called categories.  It's not defining a new class named NSExtendedMutableArray; rather, it's defined a new aspect of the NSMutableArray class by adding new methods to it.

You can't create an NSExtendedMutableArray because there's no such thing, it's just a unique name that only the compiler cares about.  All NSMutableArrays in your program support the functionality defined here, so what you probably want to do is just extend NSMutableArray, or implement a new category yourself.

Body:
I'm looking at NSArray.h which has

@interface NSMutableArray : NSArray

which I understand. Just below is

@interface NSMutableArray (NSExtendedMutableArray)

which I do not understand. I want to use the Extended version of this class, but can't figure out how. Just creating an object of class NSExtendedMutableArray doesn't seem to work.


问:
Android Window title showing after requested not to show
```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        Intent i = new Intent(this, BaseActivity.class);
        startActivity(i);
    }
</code>```

and my next activity:

```<code>public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_base);
    }
</code>```

I still see blue bar with application name at top.
I tried changing my application manifest to use a no-title theme and the program crashed because the activities inherit from AppCompatActivity.

How do I inherit from AppCompatActivity and get rid of the application title name up top?

答:
Do this in your onCreate() method.

```<code>//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.your_layout_name_here);
</code>```

this refers to the Activity

OR

You can modify your AndroidManifest.xml:

```<code><activity android:name=".MainActivity"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
</code>```

You can use this for each activity in your project.

OR

also change from style.xml

```<code><style name="generalnotitle" parent="general">
    <item name="android:windowNoTitle">true</item>
</style>
</code>```

Hope this helps you.

Body:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        Intent i = new Intent(this, BaseActivity.class);
        startActivity(i);
    }

and my next activity:

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_base);
    }

I still see blue bar with application name at top.
I tried changing my application manifest to use a no-title theme and the program crashed because the activities inherit from AppCompatActivity.

How do I inherit from AppCompatActivity and get rid of the application title name up top?

Body:
Do this in your onCreate() method.

//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.your_layout_name_here);

this refers to the Activity

OR

You can modify your AndroidManifest.xml:

<activity android:name=".MainActivity"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">

You can use this for each activity in your project.

OR

also change from style.xml

<style name="generalnotitle" parent="general">
    <item name="android:windowNoTitle">true</item>
</style>

Hope this helps you.


问:
How to display html list in RecyclerView ？
Display complex styled html as list in recyclerview. It is a stupid requirement, I have tried RichText， but RichText does not support css.

答:
Display complex styled html as list in recyclerview.

You can use Webview to Load Html

WebView
  A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

Load your HTML data in WebView using WebView.loadData() method

loadData(String data, String mimeType, String encoding)

Loads the given data into this WebView using a 'data' scheme URL.

loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)

Loads the given data into this WebView, using baseUrl as the base URL for the content.

Sample Code

```<code>String htmlString = "<h1>PREM 1.</h1>\n" +
                    "<h2>PREM 2.</h2>\n" +
                    "<h3>PREM 3.</h3>";
WebView.loadData(htmlString, "text/html", "UTF-8");
</code>```

Body:
Display complex styled html as list in recyclerview.

You can use Webview to Load Html

WebView
  A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

Load your HTML data in WebView using WebView.loadData() method

loadData(String data, String mimeType, String encoding)

Loads the given data into this WebView using a 'data' scheme URL.

loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl)

Loads the given data into this WebView, using baseUrl as the base URL for the content.

Sample Code

String htmlString = "<h1>PREM 1.</h1>\n" +
                    "<h2>PREM 2.</h2>\n" +
                    "<h3>PREM 3.</h3>";
WebView.loadData(htmlString, "text/html", "UTF-8");


问:
osmdroid in Android Studio 3.0
When I try to run the osmdroid with Android Studio 3.0, there is an error:

```<code>Error:Cannot set the value of read-only property 'outputFile' for
ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=debug,
filters=[]}} of type
com.android.build.gradle.internal.api.ApkVariantOutputImpl.
</code>```

It seems a compile problem of the new version of Android Studio, but the most solutions online is to change property of varients.each to varients.all, but there is no such code in my project.

It is like this:

```<code>android.applicationVariants.all { variant ->

if (variant.getBuildType().name == "debug") {
    task "configDevice2${variant.name.capitalize()}" (type: Exec){
        dependsOn variant.install

        group = 'nameofyourtaskgroup'
        description = 'Describe your task here.'

        def adb = android.getAdbExe().toString()
        def mypermission = 'android.permission.WRITE_EXTERNAL_STORAGE '
        commandLine "$adb shell pm grant ${variant.applicationId} $mypermission".split(' ')
    }
    variant.testVariant.connectedInstrumentTest.dependsOn "configDevice2${variant.name.capitalize()}"

} }
</code>```

I really need your help, I am new to Android, and I have tried my best.

答: Finally, I just redownloaded the newest version of osmdroid, because some masters have solved the problem, I have to say thank you to the masters! Even though, there would be a little errors, it can be fixed easily.</p>

Title: osmdroid in Android Studio 3.0

Body:
When I try to run the osmdroid with Android Studio 3.0, there is an error:

Error:Cannot set the value of read-only property 'outputFile' for
ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=debug,
filters=[]}} of type
com.android.build.gradle.internal.api.ApkVariantOutputImpl.

It seems a compile problem of the new version of Android Studio, but the most solutions online is to change property of varients.each to varients.all, but there is no such code in my project.

It is like this:

android.applicationVariants.all { variant ->

if (variant.getBuildType().name == "debug") {
    task "configDevice2${variant.name.capitalize()}" (type: Exec){
        dependsOn variant.install

        group = 'nameofyourtaskgroup'
        description = 'Describe your task here.'

        def adb = android.getAdbExe().toString()
        def mypermission = 'android.permission.WRITE_EXTERNAL_STORAGE '
        commandLine "$adb shell pm grant ${variant.applicationId} $mypermission".split(' ')
    }
    variant.testVariant.connectedInstrumentTest.dependsOn "configDevice2${variant.name.capitalize()}"

} }

I really need your help, I am new to Android, and I have tried my best.


问:
How to get the current day in Java using LocalDateTime in Java?
I'm trying to get the current local day using:

```<code>LocalDateTime now = LocalDateTime.now();
DayOfWeek  CurrentDay = DayOfWeek.of(now.getDayOfMonth());
</code>```

For me it's Monday but I get Thursday. Why and how can I resolve this?

答:
You can just call now.getDayOfWeek() directly to get the current local day instead of wrapping it in DayOfWeek.of

```<code>LocalDateTime now = LocalDateTime.now();
DayOfWeek dow = now.getDayOfWeek();
</code>```

Body:
I'm trying to get the current local day using:

LocalDateTime now = LocalDateTime.now();
DayOfWeek  CurrentDay = DayOfWeek.of(now.getDayOfMonth());

For me it's Monday but I get Thursday. Why and how can I resolve this?

Body:
You can just call now.getDayOfWeek() directly to get the current local day instead of wrapping it in DayOfWeek.of

LocalDateTime now = LocalDateTime.now();
DayOfWeek dow = now.getDayOfWeek();


问:
How to filter in NaN (pandas)?
I have a pandas dataframe (df), and I want to do something like:

```<code>newdf = df[(df.var1 == 'a') & (df.var2 == NaN)]
</code>```

I've tried replacing NaN with np.NaN, or 'NaN' or 'nan' etc, but nothing evaluates to True. There's no pd.NaN.

I can use df.fillna(np.nan) before evaluating the above expression but that feels hackish and I wonder if it will interfere with other pandas operations that rely on being able to identify pandas-format NaN's later.

I get the feeling there should be an easy answer to this question, but somehow it has eluded me. Any advice is appreciated. Thank you.

答:
Simplest of all solutions:

```<code>filtered_df = df[df['var2'].isnull()]
</code>```

This filters and gives you rows which has only NaN values in 'var2' column.

Title: How to filter in NaN (pandas)?

Body:
I have a pandas dataframe (df), and I want to do something like:

newdf = df[(df.var1 == 'a') & (df.var2 == NaN)]

I've tried replacing NaN with np.NaN, or 'NaN' or 'nan' etc, but nothing evaluates to True. There's no pd.NaN.

I can use df.fillna(np.nan) before evaluating the above expression but that feels hackish and I wonder if it will interfere with other pandas operations that rely on being able to identify pandas-format NaN's later.

I get the feeling there should be an easy answer to this question, but somehow it has eluded me. Any advice is appreciated. Thank you.

Body:
Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.


问:
in-app billing: What is the "kind" field in a subscription?
When you fetch entries from the Google Play Developer API, you get a Subscription resource. I don't understand what the "kind" field is:

This kind represents a subscriptionPurchase object in the
  androidpublisher service.

What does that mean? Can anybody give me an example what the result look like?

答: google play develoepr api depends on google cloud sub/pub,this is a gcloud publisher which publish the message. </p>