答:
Only once by id_test means you have to take distinct id_test. If 29.00 is a fixed static value, you can take the distinct id_test and multiply it by 29.00

You can Insert the values of the above query to a temporary table ( #tempTable). Then your above output values will be temporary saved to a table

```<code>SELECT
  DISTINCT(id_test) * 29.00 AS fee
FROM
  #tempTable
</code>```

Title: SQL Query SUM with conditions

Body:
I'm having some difficulties finding the good query I need, looking for help.
After multiple JOIN and a lot of WHERE, I have this columns and values :

+---------+----------+--------+-------+
| id_test | quantity | price  |  fee  |
+---------+----------+--------+-------+
| "1-3"   |        1 | 33.52  | 29.00 |
| "1-5"   |        1 | 33.52  | 29.00 |
| "1-6"   |        1 | 33.52  | 29.00 |
| "1-8"   |        1 | 86.49  | 29.00 |
| "19-1"  |        1 | 176.54 | 29.00 |
| "19-4"  |        1 | 176.54 | 29.00 |
| "19-5"  |        4 | 176.54 | 29.00 |
| "19-6"  |        1 | 199.47 | 29.00 |
| "19-6"  |        1 | 176.54 | 29.00 |
| "20-10" |        2 | 72.67  | 29.00 |
| "20-11" |        2 | 18.95  | 29.00 |
| "20-9"  |        1 | 22.13  | 29.00 |
+---------+----------+--------+-------+

Each id_test object as a quantity, a price and a fee. I would like to SUM everything so to have a global price : (quantity*price)+fee
The thing is, and that's where I'm stuck, the fee has to be added only once by id_test. Yet, I have here two id_test "19-6".

If I SUM everything I have 1827.67 (price*quantity) + 348 (fee).

Since I have two "19-6", I need 1827.67 (price*quantity) + 319 (fee).

How would you do in SQL ?

Thanks

Body:
Only once by id_test means you have to take distinct id_test. If 29.00 is a fixed static value, you can take the distinct id_test and multiply it by 29.00

You can Insert the values of the above query to a temporary table ( #tempTable). Then your above output values will be temporary saved to a table

SELECT
  DISTINCT(id_test) * 29.00 AS fee
FROM
  #tempTable


来源: stackexchange

问:
Array filter is not returning correct for Zero?

function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

I want to return the no. of zero present in the array using filter.

答:
function zeroCount(arr){
   const zero = arr.filter(el=> el === 0);
   return zero.length;
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

ContentLicense: CC BY-SA 4.0

Body:
function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));

I want to return the no. of zero present in the array using filter.


问:
Hyperledger IROHA get_acc_ast_tx in CLI mode dont work
I just finished the pluralsigt course and completed the tutorial of the official project documentation without problems, but nevertheless using the CLI I could not use the functions get_acc_ast_tx, get_acc_tx, I checked that the peer keys and the configuration files and correspond to genesis file, where admin@test is allowed to use these functions and I get:

[2019-12-08 04: 55: 57.883070400] [E] [CLI/ResponseHandler/Query]: Query is stateless invalid.

The genesis file I use is the initial one of the git repository:

```<code>{
"blockV1": {
    "payload": {
        "transactions": [{
            "payload": {
                "reducedPayload": {
                    "commands": [{
                        "addPeer": {
                            "peer": {
                                "address": "127.0.0.1:10001",
                                "peerKey": "bddd58404d1315e0eb27902c5d7c8eb0602c16238f005773df406bc191308929"
                            }
                        }
                    }, {
                        "createRole": {
                            "roleName": "admin",
                            "permissions": ["can_add_peer", "can_add_signatory", "can_create_account", "can_create_domain", "can_get_all_acc_ast", "can_get_all_acc_ast_txs", "can_get_all_acc_detail", "can_get_all_acc_txs", "can_get_all_accounts", "can_get_all_signatories", "can_get_all_txs", "can_get_blocks", "can_get_roles", "can_read_assets", "can_remove_signatory", "can_set_quorum"]
                        }
                    }, {
                        "createRole": {
                            "roleName": "user",
                            "permissions": ["can_add_signatory", "can_get_my_acc_ast", "can_get_my_acc_ast_txs", "can_get_my_acc_detail", "can_get_my_acc_txs", "can_get_my_account", "can_get_my_signatories", "can_get_my_txs", "can_grant_can_add_my_signatory", "can_grant_can_remove_my_signatory", "can_grant_can_set_my_account_detail", "can_grant_can_set_my_quorum", "can_grant_can_transfer_my_assets", "can_receive", "can_remove_signatory", "can_set_quorum", "can_transfer"]
                        }
                    }, {
                        "createRole": {
                            "roleName": "money_creator",
                            "permissions": ["can_add_asset_qty", "can_create_asset", "can_receive", "can_transfer"]
                        }
                    }, {
                        "createDomain": {
                            "domainId": "test",
                            "defaultRole": "user"
                        }
                    }, {
                        "createAsset": {
                            "assetName": "coin",
                            "domainId": "test",
                            "precision": 2
                        }
                    }, {
                        "createAccount": {
                            "accountName": "admin",
                            "domainId": "test",
                            "publicKey": "313a07e6384776ed95447710d15e59148473ccfc052a681317a72a69f2a49910"
                        }
                    }, {
                        "createAccount": {
                            "accountName": "test",
                            "domainId": "test",
                            "publicKey": "716fe505f69f18511a1b083915aa9ff73ef36e6688199f3959750db38b8f4bfc"
                        }
                    }, {
                        "appendRole": {
                            "accountId": "admin@test",
                            "roleName": "admin"
                        }
                    }, {
                        "appendRole": {
                            "accountId": "admin@test",
                            "roleName": "money_creator"
                        }
                    }],
                    "quorum": 1
                }
            }
        }],
        "txNumber": 1,
        "height": "1",
        "prevBlockHash": "0000000000000000000000000000000000000000000000000000000000000000"
    }
}
</code>```

}

I use the hyperledger image of docker, in MAC OS CATALINA.

I followed the tutorial according to this manual: https://iroha.readthedocs.io/en/latest/build/index.html

Thank you very much for the help.

答:
Unfortunately, CLI is rather outdated – we are working on new solution for it, but meanwhile it is better to use one of the SDKs available – for Java, Python, JS or iOS (if you prefer mobile development).
All of them contain examples, so it should not be too tricky to use those. Although, if you encounter any issues, please contact us using one of the chats here.</p>

Body:
I just finished the pluralsigt course and completed the tutorial of the official project documentation without problems, but nevertheless using the CLI I could not use the functions get_acc_ast_tx, get_acc_tx, I checked that the peer keys and the configuration files and correspond to genesis file, where admin@test is allowed to use these functions and I get:

[2019-12-08 04: 55: 57.883070400] [E] [CLI/ResponseHandler/Query]: Query is stateless invalid.

The genesis file I use is the initial one of the git repository:

{
"blockV1": {
    "payload": {
        "transactions": [{
            "payload": {
                "reducedPayload": {
                    "commands": [{
                        "addPeer": {
                            "peer": {
                                "address": "127.0.0.1:10001",
                                "peerKey": "bddd58404d1315e0eb27902c5d7c8eb0602c16238f005773df406bc191308929"
                            }
                        }
                    }, {
                        "createRole": {
                            "roleName": "admin",
                            "permissions": ["can_add_peer", "can_add_signatory", "can_create_account", "can_create_domain", "can_get_all_acc_ast", "can_get_all_acc_ast_txs", "can_get_all_acc_detail", "can_get_all_acc_txs", "can_get_all_accounts", "can_get_all_signatories", "can_get_all_txs", "can_get_blocks", "can_get_roles", "can_read_assets", "can_remove_signatory", "can_set_quorum"]
                        }
                    }, {
                        "createRole": {
                            "roleName": "user",
                            "permissions": ["can_add_signatory", "can_get_my_acc_ast", "can_get_my_acc_ast_txs", "can_get_my_acc_detail", "can_get_my_acc_txs", "can_get_my_account", "can_get_my_signatories", "can_get_my_txs", "can_grant_can_add_my_signatory", "can_grant_can_remove_my_signatory", "can_grant_can_set_my_account_detail", "can_grant_can_set_my_quorum", "can_grant_can_transfer_my_assets", "can_receive", "can_remove_signatory", "can_set_quorum", "can_transfer"]
                        }
                    }, {
                        "createRole": {
                            "roleName": "money_creator",
                            "permissions": ["can_add_asset_qty", "can_create_asset", "can_receive", "can_transfer"]
                        }
                    }, {
                        "createDomain": {
                            "domainId": "test",
                            "defaultRole": "user"
                        }
                    }, {
                        "createAsset": {
                            "assetName": "coin",
                            "domainId": "test",
                            "precision": 2
                        }
                    }, {
                        "createAccount": {
                            "accountName": "admin",
                            "domainId": "test",
                            "publicKey": "313a07e6384776ed95447710d15e59148473ccfc052a681317a72a69f2a49910"
                        }
                    }, {
                        "createAccount": {
                            "accountName": "test",
                            "domainId": "test",
                            "publicKey": "716fe505f69f18511a1b083915aa9ff73ef36e6688199f3959750db38b8f4bfc"
                        }
                    }, {
                        "appendRole": {
                            "accountId": "admin@test",
                            "roleName": "admin"
                        }
                    }, {
                        "appendRole": {
                            "accountId": "admin@test",
                            "roleName": "money_creator"
                        }
                    }],
                    "quorum": 1
                }
            }
        }],
        "txNumber": 1,
        "height": "1",
        "prevBlockHash": "0000000000000000000000000000000000000000000000000000000000000000"
    }
}

}

I use the hyperledger image of docker, in MAC OS CATALINA.

I followed the tutorial according to this manual: https://iroha.readthedocs.io/en/latest/build/index.html

Thank you very much for the help.


问:
list the files with minimum sequence
I have some files in a directory as below (not necessarily sorted):

```<code>A_10
A_20
A_30
B_10
B_30
C_10
C_20
D_20
D_30
E_10
E_20
E_30
</code>```

10, 20 and 30 are the sequence numbers of A,B,C,D,E respectively.

I want to select only those files with minimum sequence of all A,B,C,D,E
the output should be :

```<code>A_10
B_10
C_10
D_20
E_10
</code>```

could anybody help me?

答:
In bash:</p>

```<code>for x in A B C D E; do
    ls -1 ${x}_* | sort | head -n1
done
</code>```

ContentLicense: CC BY-SA 3.0

Title: list the files with minimum sequence

Body:
I have some files in a directory as below (not necessarily sorted):

A_10
A_20
A_30
B_10
B_30
C_10
C_20
D_20
D_30
E_10
E_20
E_30

10, 20 and 30 are the sequence numbers of A,B,C,D,E respectively.

I want to select only those files with minimum sequence of all A,B,C,D,E
the output should be :

A_10
B_10
C_10
D_20
E_10

could anybody help me?

Body:
In bash:

for x in A B C D E; do
    ls -1 ${x}_* | sort | head -n1
done


答:
This is due to outdated cli. A newer version that is developed will replace it, but is not yet ready.

The exact problem is that there was pagination metadata added for these queries in iroha, but the cli was not updated to set it properly. Protobuf transport allows cli to send a query without some fields that were added later, but iroha refuses to handle it.

You can use one of client libraries that are always kept up to date: https://iroha.readthedocs.io/en/latest/develop/libraries.html.

Title: Hyperledger IROHA get_acc_ast_tx in CLI mode dont work


问:
Get Value from JSON for a given Key where parent key names are dynamic
I have a json string which starts like this:

```<code>{ "0" :
{"Jquery77768" :
    {"nodeData":
        {"id":32, "name": "Bob"}
        ----
</code>```

I need to get the value which is there in the id key.
I tried to do something like this:

```<code>var obj = JSON.parse(myJsonString);
var myID = obj[0].Jquery77768.nodeData.id;
</code>```

but this does not work. Also the second node name Jquery77768 is dynamic and will change every time.

How can I get the value of the id field?

答:
What about a general function ? But suppose order of keys may not be same everywhere...

var obj = '{ "0" : {"Jquery77768" : {"nodeData": {"id":32, "name": "Bob"} }}}';
obj = JSON.parse(obj);
console.log(goDownNth(obj[0], 1).nodeData.id);
console.log(goDownNth(obj[0], 1).nodeData.id === goDownNth(goDownNth(goDownNth(goDownNth(obj, 1), 1), 1), 1));
console.log(goDownNth(goDownNth(goDownNth(goDownNth(obj, 1), 1), 1), 2));

function goDownNth (obj, n) {
    for (var a in obj) {
        if (!--n) return obj[a];
    }
}```

Body:
I have a json string which starts like this:

{ "0" :
{"Jquery77768" :
    {"nodeData":
        {"id":32, "name": "Bob"}
        ----

I need to get the value which is there in the id key.
I tried to do something like this:

var obj = JSON.parse(myJsonString);
var myID = obj[0].Jquery77768.nodeData.id;

but this does not work. Also the second node name Jquery77768 is dynamic and will change every time.

How can I get the value of the id field?


问:
Java reflection error Java.lang.NoSuchMethodException, but method exists
I can't get to work java reflection in Spring boot with Controller and JdbcTemplate.

Default controller looks like:

```<code>public class DefaultController {

private static final Logger logger = LoggerFactory.getLogger(DefaultController.class);

public JsonResponseDataModel selectOneAuto(Long id, Class<?> repository, HttpServletResponse response){

    final JsonResponseDataModel result = new JsonResponseDataModel();
    System.out.println("The name of class is " + repository.getName());

    Method[] methods = repository.getMethods();
    for (Method method : methods) {
        System.out.println("Method: " + method.getName());
    }

    try {
        //Method method = repository.getClass().getMethod("selectOne", Long.class);
        Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);
        method.invoke(repository, id);

        logger.info("selectOneAuto : id={} ", id);
    } catch (EmptyResultDataAccessException e) {
        result.setEmptyResultDataAccessException("id", id.toString());
    } catch (DataAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return result;
}

}
</code>```

Inside CompanyRepository class is defined selectOne method with Long input:

```<code>@Transactional(readOnly=true)
     public CompanyModel selectOne(Long id) {
     CompanyModel result = null;
     final String sql = "SELECT * FROM company WHERE id=?";
     return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CompanyRowMapper());
}
</code>```

When I create a new class "CompanyController extends DefaultController" and call method selectOneAuto:

```<code>selectOneAuto(id, new CompanyRepository().getClass(), response);
</code>```

Then it ends with error on line "Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);"

```<code>"Java.lang.NoSuchMethodException: java.lang.Class.selectOne(java.lang.Long)"
</code>```

But the for loop inside "selectOneAuto" method outputs method named "selectOne". What is wrong here?

答:
Your code attempts to call the method on an instance of Class.

method.invoke(repository, id);

repository object is an instance of Class since you are passing new CompanyRepository().getClass() as parameter.

The second point to be noted is repository is an instance of Class already so there is no need to call getClass() on this object.

You should obtain the method object using the following code :

```<code>Method method = repository.getDeclaredMethod("selectOne", Long.class);
</code>```

And then this should work :

```<code>CompanyRepository repsitoryObj = new CompanyRepository();
method.invoke(repsitoryObj, id);
</code>```

Or a better and cleaner way is to simply change the type of your repository parameter as CompanyRepository your method will look as follows:

```<code>public JsonResponseDataModel selectOneAuto(Long id, CompanyRepository repository, HttpServletResponse response){

    final JsonResponseDataModel result = new JsonResponseDataModel();
    System.out.println("The name of class is " + repository.getClass().getName());

    Method[] methods = repository.getClass().getMethods();
    for (Method method : methods) {
    System.out.println("Method: " + method.getName());
    }

    try {
    //Method method = repository.getClass().getMethod("selectOne", Long.class);
    Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);
    method.invoke(repository, id);

    logger.info("selectOneAuto : id={} ", id);
    } catch (EmptyResultDataAccessException e) {
    result.setEmptyResultDataAccessException("id", id.toString());
    } catch (DataAccessException e) {
    e.printStackTrace();
    } catch (NoSuchMethodException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    e.printStackTrace();
    }
    return result;
}
</code>```

Body:
I can't get to work java reflection in Spring boot with Controller and JdbcTemplate.

Default controller looks like:

public class DefaultController {

private static final Logger logger = LoggerFactory.getLogger(DefaultController.class);

public JsonResponseDataModel selectOneAuto(Long id, Class<?> repository, HttpServletResponse response){

    final JsonResponseDataModel result = new JsonResponseDataModel();
    System.out.println("The name of class is " + repository.getName());

    Method[] methods = repository.getMethods();
    for (Method method : methods) {
        System.out.println("Method: " + method.getName());
    }

    try {
        //Method method = repository.getClass().getMethod("selectOne", Long.class);
        Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);
        method.invoke(repository, id);

        logger.info("selectOneAuto : id={} ", id);
    } catch (EmptyResultDataAccessException e) {
        result.setEmptyResultDataAccessException("id", id.toString());
    } catch (DataAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return result;
}

}

Inside CompanyRepository class is defined selectOne method with Long input:

@Transactional(readOnly=true)
     public CompanyModel selectOne(Long id) {
     CompanyModel result = null;
     final String sql = "SELECT * FROM company WHERE id=?";
     return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CompanyRowMapper());
}

When I create a new class "CompanyController extends DefaultController" and call method selectOneAuto:

selectOneAuto(id, new CompanyRepository().getClass(), response);

Then it ends with error on line "Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);"

"Java.lang.NoSuchMethodException: java.lang.Class.selectOne(java.lang.Long)"

But the for loop inside "selectOneAuto" method outputs method named "selectOne". What is wrong here?

Body:
Your code attempts to call the method on an instance of Class.

method.invoke(repository, id);

repository object is an instance of Class since you are passing new CompanyRepository().getClass() as parameter.

The second point to be noted is repository is an instance of Class already so there is no need to call getClass() on this object.

You should obtain the method object using the following code :

Method method = repository.getDeclaredMethod("selectOne", Long.class);

And then this should work :

CompanyRepository repsitoryObj = new CompanyRepository();
method.invoke(repsitoryObj, id);

Or a better and cleaner way is to simply change the type of your repository parameter as CompanyRepository your method will look as follows:

public JsonResponseDataModel selectOneAuto(Long id, CompanyRepository repository, HttpServletResponse response){

    final JsonResponseDataModel result = new JsonResponseDataModel();
    System.out.println("The name of class is " + repository.getClass().getName());

    Method[] methods = repository.getClass().getMethods();
    for (Method method : methods) {
    System.out.println("Method: " + method.getName());
    }

    try {
    //Method method = repository.getClass().getMethod("selectOne", Long.class);
    Method method = repository.getClass().getDeclaredMethod("selectOne", Long.class);
    method.invoke(repository, id);

    logger.info("selectOneAuto : id={} ", id);
    } catch (EmptyResultDataAccessException e) {
    result.setEmptyResultDataAccessException("id", id.toString());
    } catch (DataAccessException e) {
    e.printStackTrace();
    } catch (NoSuchMethodException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    e.printStackTrace();
    }
    return result;
}


问:
Get instance of subtype of a model with Eloquent
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

```<code>class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }
</code>```

Yet, being able to fetch an animal like this :

```<code>$animal = Animal::find($id);
</code>```

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

答:
You can use the Polymorphic Relationships in Laravel as explained in Official Laravel Docs. Here is how you can do that.

Define the relationships in the model as given

class Animal extends Model{
    public function animable(){
        return $this->morphTo();
    }
}

class Dog extends Model{
    public function animal(){
        return $this->morphOne('App\Animal', 'animable');
    }
}

class Cat extends Model{
    public function animal(){
        return $this->morphOne('App\Animal', 'animable');
    }
}
```
<p>Here you'll need two columns in the <b><code>animals</code></b> table, first is <b><code>animable_type</code></b> and another is <b><code>animable_id</code></b> to determine the type of model attached to it at runtime.</p>
<p>You can fetch the Dog or Cat model as given,</p>
<pre class="lang-php prettyprint-override"><code>$animal = Animal::find($id);
$anim = $animal->animable; //this will return either Cat or Dog Model
</code>```

After that, you can check the $anim object's class by using instanceof.

This approach will help you for future expansion if you add another animal type (i.e fox or lion) in the application. It will work without changing your codebase. This is the correct way to achieve your requirement. However, there is no alternative approach to achieve polymorphism and eager loading together without using a polymorphic relationship. If you don't use a Polymorphic relationship, you'll end up with more then one database call. However, if you have a single column that differentiates the modal type, maybe you have a wrong structured schema. I suggest you improve that if you want to simplify it for future development as well.

Rewriting the model's internal newInstance() and newFromBuilder() isn't a good/recommended way and you have to rework on it once you'll get the update from framework.

Body:
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }

Yet, being able to fetch an animal like this :

$animal = Animal::find($id);

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

Body:
You can use the Polymorphic Relationships in Laravel as explained in Official Laravel Docs. Here is how you can do that.

Define the relationships in the model as given

class Animal extends Model{
    public function animable(){
        return $this->morphTo();
    }
}

class Dog extends Model{
    public function animal(){
        return $this->morphOne('App\Animal', 'animable');
    }
}

class Cat extends Model{
    public function animal(){
        return $this->morphOne('App\Animal', 'animable');
    }
}

Here you'll need two columns in the animals table, first is animable_type and another is animable_id to determine the type of model attached to it at runtime.

You can fetch the Dog or Cat model as given,

$animal = Animal::find($id);
$anim = $animal->animable; //this will return either Cat or Dog Model

After that, you can check the $anim object's class by using instanceof.

This approach will help you for future expansion if you add another animal type (i.e fox or lion) in the application. It will work without changing your codebase. This is the correct way to achieve your requirement. However, there is no alternative approach to achieve polymorphism and eager loading together without using a polymorphic relationship. If you don't use a Polymorphic relationship, you'll end up with more then one database call. However, if you have a single column that differentiates the modal type, maybe you have a wrong structured schema. I suggest you improve that if you want to simplify it for future development as well.

Rewriting the model's internal newInstance() and newFromBuilder() isn't a good/recommended way and you have to rework on it once you'll get the update from framework.


问:
Caller id faker
I want to develop an android application to fake my mobile number to outgoing call. How to do this in android? I havent seen any api/control available to do this? Does android allow this? Is it legal for all the countries? Please give me some insight in this.</p>

答: the caller id is submitted by your provider, you can only tell your provider not to send the id (emergency calls will ever send the id), but there are some VoIp Providers whiche are able to fake the caller id.</p>

Title: Caller id faker


问:
CRON Example for Strapi
Hi I was wondering If anyone got examples of using Cron Schedule functions on Strapi: https://strapi.io/documentation/3.x.x/configurations/configurations.html#functions
like sending email, accessing the strapi config, etc.</p>

答:
My requirement was to fetch data from an external MSSQL DB (master data) hosted under RDS (AWS) and update the strapi product catolog (mongodb) every minute.

I've created a custom "cron" folder under "root" to keep all my custom modules in order keep a clean "cron.js".

Under "cron.js" i've simply imported my custom module to call the external module:

```<code>const fwSync = require('../../cron/dataSync');
</code>```

Title: CRON Example for Strapi

Body:
My requirement was to fetch data from an external MSSQL DB (master data) hosted under RDS (AWS) and update the strapi product catolog (mongodb) every minute.

I've created a custom "cron" folder under "root" to keep all my custom modules in order keep a clean "cron.js".

Under "cron.js" i've simply imported my custom module to call the external module:

const fwSync = require('../../cron/dataSync');


问:
Python Find all subarrays of given array. (what mistakes have I done )
```<code>def findSubarray(self, arrayList):
    newArray = []
    for i in range(len(arrayList)):
        for n in range(i, len(arrayList)):
            newArray.append(arrayList[i:n])
    print(newArray)
</code>```

The input I tried is [1,-1,3,5,7]. But the output is so wrong, all the subarrays don't have the last element 7, I wonder what mistakes have I done?

答:
Please note that arrayList1[i:n] does not include the n index. For example :  arrayList1:3] will only consider 1 and 2 index and output [-1, 3]

Try : add n+1

```<code>def findSubarray( arrayList):
newArray = []
for i in range(len(arrayList)):
    for n in range(i, len(arrayList)):
        newArray.append(arrayList[i:n+1])
print(newArray)

findSubarray( arrayList=[1,-1,3,5,7])
</code>```

Body:
def findSubarray(self, arrayList):
    newArray = []
    for i in range(len(arrayList)):
        for n in range(i, len(arrayList)):
            newArray.append(arrayList[i:n])
    print(newArray)

The input I tried is [1,-1,3,5,7]. But the output is so wrong, all the subarrays don't have the last element 7, I wonder what mistakes have I done?

Body:
Please note that arrayList1[i:n] does not include the n index. For example :  arrayList1:3] will only consider 1 and 2 index and output [-1, 3]

Try : add n+1

def findSubarray( arrayList):
newArray = []
for i in range(len(arrayList)):
    for n in range(i, len(arrayList)):
        newArray.append(arrayList[i:n+1])
print(newArray)

findSubarray( arrayList=[1,-1,3,5,7])


问:
Fixing GPU intensive animating frame
Thanks to @Temani Afif we have this beautiful frame. The code works fine but unfortunately, there is an issue that made the code completely useless.

It cost more than 90 percent of my GPU resources! apparently my laptop getting hot in 10 seconds of running it!

Why this happens and how to fix it?

UPDATE: I think the issue is the code renders the animation even behind the image,
if you comment addimage() you can see that.

You can test it yourself:
Please Run the code in CodePen

And here is the code: (We add an image to the page using addimage() function, all the rest are CSS and HTML)

addimage();
function addimage() {

  let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

  var node = document.getElementsByClassName('content');
  node[0].style.background = 'url("' + pictureSource + '") center/cover'

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: black;
}

.box {
 border-radius: 10px;
  background:
    repeating-linear-gradient(-45deg, white 0 7.5px, hotpink 0 15px)
    0 0/21.21px 21.21px;  /* 21.21px = sqrt(2) * 15px */
  animation: animate 1s linear infinite;
}

.box .content {
  width: calc(90vw - 30px);
  height: calc(85vh - 30px);
  border-radius: 10px;
  box-shadow: 0 0 2px deeppink, 0 0 5px rgba(0, 0, 0, 1), inset 0 0 5px rgba(0, 0, 0, 1);
  margin:15px;
}

@keyframes animate {
  to {
    background-position: 21.21px 21.21px;
  }
}</code>```

```

答:
I think the background-position for animation is a bit expensive. Check if the below code works fine. I just used the transform property for animation instead of background-position.

addimage();
function addimage() {

  let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

  var node = document.getElementsByClassName('content');
  node[0].style.background = 'url("' + pictureSource + '") center/cover'

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: 100vh;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: gray;
}

.box {
  border-radius: 10px;
  position: relative;
  overflow: hidden;
}
.box::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:
      repeating-linear-gradient(-45deg, white 0 7.5px, hotpink 0 15px) 0 0/21.21px 21.21px;

    width: calc(100% + 21.21px);
    height: calc(100% + 21.21px);
    transform: translate(-21.21px, -21.21px);
    /* transform: translate(-15px, -15px); */
    /* transform: translate(0, 0); */
    animation: animate 1s linear infinite;

  }
.box .content {
  width: calc(90vw - 30px);
  height: calc(85vh - 30px);
  border-radius: 10px;
  box-shadow: 0 0 2px deeppink, 0 0 5px rgba(0, 0, 0, 1), inset 0 0 5px rgba(0, 0, 0, 1);
  margin: 15px;
}

@keyframes animate {
  to {
    /*     background-position: 21.21px 21.21px;  */
    transform: translate(0, 0);
  }
}</code>```

```

Title: Fixing GPU intensive animating frame

Body:
Thanks to @Temani Afif we have this beautiful frame. The code works fine but unfortunately, there is an issue that made the code completely useless.

It cost more than 90 percent of my GPU resources! apparently my laptop getting hot in 10 seconds of running it!

Why this happens and how to fix it?

UPDATE: I think the issue is the code renders the animation even behind the image,
if you comment addimage() you can see that.

You can test it yourself:
Please Run the code in CodePen

And here is the code: (We add an image to the page using addimage() function, all the rest are CSS and HTML)

addimage();
function addimage() {

  let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

  var node = document.getElementsByClassName('content');
  node[0].style.background = 'url("' + pictureSource + '") center/cover'

}

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: black;
}

.box {
 border-radius: 10px;
  background:
    repeating-linear-gradient(-45deg, white 0 7.5px, hotpink 0 15px)
    0 0/21.21px 21.21px;  /* 21.21px = sqrt(2) * 15px */
  animation: animate 1s linear infinite;
}

.box .content {
  width: calc(90vw - 30px);
  height: calc(85vh - 30px);
  border-radius: 10px;
  box-shadow: 0 0 2px deeppink, 0 0 5px rgba(0, 0, 0, 1), inset 0 0 5px rgba(0, 0, 0, 1);
  margin:15px;
}

@keyframes animate {
  to {
    background-position: 21.21px 21.21px;
  }
}

Body:
I think the background-position for animation is a bit expensive. Check if the below code works fine. I just used the transform property for animation instead of background-position.

addimage();
function addimage() {

  let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

  var node = document.getElementsByClassName('content');
  node[0].style.background = 'url("' + pictureSource + '") center/cover'

}

body {
  height: 100vh;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: gray;
}

.box {
  border-radius: 10px;
  position: relative;
  overflow: hidden;
}
.box::after {
    content: '';
    position: absolute;
    z-index: -1;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background:
      repeating-linear-gradient(-45deg, white 0 7.5px, hotpink 0 15px) 0 0/21.21px 21.21px;

    width: calc(100% + 21.21px);
    height: calc(100% + 21.21px);
    transform: translate(-21.21px, -21.21px);
    /* transform: translate(-15px, -15px); */
    /* transform: translate(0, 0); */
    animation: animate 1s linear infinite;

  }
.box .content {
  width: calc(90vw - 30px);
  height: calc(85vh - 30px);
  border-radius: 10px;
  box-shadow: 0 0 2px deeppink, 0 0 5px rgba(0, 0, 0, 1), inset 0 0 5px rgba(0, 0, 0, 1);
  margin: 15px;
}

@keyframes animate {
  to {
    /*     background-position: 21.21px 21.21px;  */
    transform: translate(0, 0);
  }
}

<div class="box">
  <div class="content">

  </div>
</div>


问:
Restricting string length in XML Schema
I am new to XML and JAXB, I am trying to add the AdditionalDataDeposit field with restrictions to my XML schema so I can generate the POJO with Maven. When I try to build it in maven the error:

```<code>blahBlahBlahmsgfactory: Unable to parse input schema(s). Error messages should have been provided.
org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name
'LimitedString50' to a(n) 'type definition' component.
</code>```

my code:

Under AdditionalData complex type:

```<code><xs:element name="DEPOSIT" type="trmns:AdditionalDataDEPOSIT" minOccurs="0">
  <xs:annotation>
    <xs:documentation>Additional Deposit Data</xs:documentation>
  </xs:annotation>
</xs:element>
</code>```

then:

```<code>  <xs:complexType name="AdditionalDataDEPOSIT">
    <xs:annotation>
      <xs:documentation>Additional Deposit Data</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element name="depositorID" type="LimitedString50"/>
      <xs:element name="depositorNationality" type="LimitedString50"/>
      <xs:element name="fundSource" type="LimitedString50"/>
      <xs:element name="fullName" type="LimitedString100"/>
    </xs:sequence>
  </xs:complexType>
  <xs:simpleType name="LimitedString50">
    <xs:restriction base="xs:string">
      <xs:maxLength value="50" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="LimitedString100">
    <xs:restriction base="xs:string">
      <xs:maxLength value="100" />
    </xs:restriction>
  </xs:simpleType>
</code>```

I dont understand much of XML Schema's, but advice will be appreciated.

答:
The error message says that LimitedString50 cannot be resolved to a type definition. That means that it cannot find that type definition. The simple type 'LimitedString50' is defined in the same XSD, so the most likely explanation is that your schema has a non-empty targetNamespace but your type reference does not specify that namespace.

I cannot verify this because you have not posted your entire XSD.

Title: Restricting string length in XML Schema

Body:
I am new to XML and JAXB, I am trying to add the AdditionalDataDeposit field with restrictions to my XML schema so I can generate the POJO with Maven. When I try to build it in maven the error:

blahBlahBlahmsgfactory: Unable to parse input schema(s). Error messages should have been provided.
org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name
'LimitedString50' to a(n) 'type definition' component.

my code:

Under AdditionalData complex type:

<xs:element name="DEPOSIT" type="trmns:AdditionalDataDEPOSIT" minOccurs="0">
  <xs:annotation>
    <xs:documentation>Additional Deposit Data</xs:documentation>
  </xs:annotation>
</xs:element>

then:

  <xs:complexType name="AdditionalDataDEPOSIT">
    <xs:annotation>
      <xs:documentation>Additional Deposit Data</xs:documentation>
    </xs:annotation>
    <xs:sequence>
      <xs:element name="depositorID" type="LimitedString50"/>
      <xs:element name="depositorNationality" type="LimitedString50"/>
      <xs:element name="fundSource" type="LimitedString50"/>
      <xs:element name="fullName" type="LimitedString100"/>
    </xs:sequence>
  </xs:complexType>
  <xs:simpleType name="LimitedString50">
    <xs:restriction base="xs:string">
      <xs:maxLength value="50" />
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="LimitedString100">
    <xs:restriction base="xs:string">
      <xs:maxLength value="100" />
    </xs:restriction>
  </xs:simpleType>

I dont understand much of XML Schema's, but advice will be appreciated.


问:
Getting the android context in an adapter
In many of the code samples that I find on the internet the context is obtained in the constructor of an adapter.

This context is used to get an inflater to inflate the views in getView method.

My Question is why bother getting the context in the constructor when it can easily be obtained like so

```<code>        LayoutInflater inflater;
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(inflater == null){
            Context context = parent.getContext();
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }
            ...
            ...

            return convertView;
        }
</code>```

Also is there any reason not to use the above method because it till now I have not faced any problem in using it .

答: Yes but if you need any activity reference like for example dialog alert you cannot use context reference , therefore constructor should receive activity reference from calling Activity/Fragment</p>

Body:
In many of the code samples that I find on the internet the context is obtained in the constructor of an adapter.

This context is used to get an inflater to inflate the views in getView method.

My Question is why bother getting the context in the constructor when it can easily be obtained like so

        LayoutInflater inflater;
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(inflater == null){
            Context context = parent.getContext();
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }
            ...
            ...

            return convertView;
        }

Also is there any reason not to use the above method because it till now I have not faced any problem in using it .


问:
Javascript float subtract
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

```<code>alert(-0.2-0.1);
</code>```

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

答:
toFixed() is what you must be looking for.

E.g

```<code>number.toFixed(x);
</code>```

where x is the number of digits after the decimal point. It is optional with default value of 0.

More here : Javascript Number.toFixed() Method

Title: Javascript float subtract

Body:
I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

alert(-0.2-0.1);

and the result is -0.30000000000000004. Am I doing something wrong? What do I have to do to get -0.3 ?

Body:
toFixed() is what you must be looking for.

E.g

number.toFixed(x);

where x is the number of digits after the decimal point. It is optional with default value of 0.

More here : Javascript Number.toFixed() Method


问:
Changing the color of a random div
There is a playing field with 25 div. By clicking on the "Play" button, a random div should turn blue.
By clicking on a div with blue color, it should be repainted in green.
If there was no click, after 2 seconds from the moment of tanning with blue, it should be repainted in red.

At my click, the green lights up, and after a while it turns red.
What and how to change to fulfill the above conditions?

```<code>const duel = ['duel1', 'duel2', 'duel3', 'duel4', 'duel5', 'duel6',
            'duel7', 'duel8', 'duel9', 'duel10', 'duel11', 'duel12', 'duel13',
            'duel14', 'duel15', 'duel16', 'duel17', 'duel18', 'duel19', 'duel20',
            'duel21', 'duel22', 'duel23', 'duel24', 'duel25'];

        let setBlue = (rancelBlue) => {
            const randomNumber = duel[Math.floor(Math.random() * 25)];
            rancelBlue = document.getElementById(randomNumber).style.backgroundColor = 'blue'
            setTimeout(setBlue, 2000)
            setTimeout(()=> document.getElementById(randomNumber).style.backgroundColor='red',2000)
            };

        let setGreen = (e) => {
            if (e.target.style.backgroundColor === 'blue')
                e.target.style.backgroundColor = 'green'
        };

          <div>
                <div>
                    <button onClick={setBlue}>Play</button>
                </div>
                        <div onClick={setGreen} >
                                <25 div></div>
                        </div>
          </div>
</code>```

答:
You should add a background check for blue color in the setTimeout callback. If the background color is blue, only then set the color to red.
And I don't see necessary in two call setTimeout, because both working in two seconds.</p>

```<code>    let setBlue = (rancelBlue) => {
      const randomNumber = duel[Math.floor(Math.random() * 25)];
      rancelBlue = document.getElementById(randomNumber).style.backgroundColor = 'blue'
      setTimeout(()=> {
        if (e.target.style.backgroundColor === 'blue') {
          document.getElementById(randomNumber).style.backgroundColor='red'
        }
        setBlue()
      },2000)
   }
</code>```

Title: Changing the color of a random div

Body:
There is a playing field with 25 div. By clicking on the "Play" button, a random div should turn blue.
By clicking on a div with blue color, it should be repainted in green.
If there was no click, after 2 seconds from the moment of tanning with blue, it should be repainted in red.

At my click, the green lights up, and after a while it turns red.
What and how to change to fulfill the above conditions?

const duel = ['duel1', 'duel2', 'duel3', 'duel4', 'duel5', 'duel6',
            'duel7', 'duel8', 'duel9', 'duel10', 'duel11', 'duel12', 'duel13',
            'duel14', 'duel15', 'duel16', 'duel17', 'duel18', 'duel19', 'duel20',
            'duel21', 'duel22', 'duel23', 'duel24', 'duel25'];

        let setBlue = (rancelBlue) => {
            const randomNumber = duel[Math.floor(Math.random() * 25)];
            rancelBlue = document.getElementById(randomNumber).style.backgroundColor = 'blue'
            setTimeout(setBlue, 2000)
            setTimeout(()=> document.getElementById(randomNumber).style.backgroundColor='red',2000)
            };

        let setGreen = (e) => {
            if (e.target.style.backgroundColor === 'blue')
                e.target.style.backgroundColor = 'green'
        };

                    <button onClick={setBlue}>Play</button>

                                <25 div>

Body:
You should add a background check for blue color in the setTimeout callback. If the background color is blue, only then set the color to red.
And I don't see necessary in two call setTimeout, because both working in two seconds.

    let setBlue = (rancelBlue) => {
      const randomNumber = duel[Math.floor(Math.random() * 25)];
      rancelBlue = document.getElementById(randomNumber).style.backgroundColor = 'blue'
      setTimeout(()=> {
        if (e.target.style.backgroundColor === 'blue') {
          document.getElementById(randomNumber).style.backgroundColor='red'
        }
        setBlue()
      },2000)
   }


问:
python dataframe merge columns according to other column values
What I want to do is merge columns according to values in another column
It is better illustrated with a simple example:
I have a dataframe with 5 columns:

```<code>| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |
</code>```

I want to get the following table:

```<code>| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |
</code>```

where the columns are filled with values from team_1.x and team_1.y for rows of players with number less than 5 and values from team_2.x and team_2.y for rows of players with number bigger than 5

答:
You can use Numpy's np.where for this:

import numpy as np
...
df['x'] = np.where(df['player_num'] < 5, df['team_1.x'], df['team_2.x'])
df['y'] = np.where(df['player_num'] < 5, df['team_1.y'], df['team_2.y'])
```

<p>EDIT:</p>

<pre class="lang-py prettyprint-override"><code># Extract column names and remove prefix to get a list of x,y,z, etc.
cols = [col.split('.')[1] for col in list(df) if 'team_' in col]

# Loop over and create new column for each prefix (x, y, z, etc)
for col in cols:
    col1 = 'team_1.' + col
    col2 = 'team_2.' + col
    df[col] = np.where(df['player_num']<5, df[col1], df[col2])
</code>```

Body:
What I want to do is merge columns according to values in another column
It is better illustrated with a simple example:
I have a dataframe with 5 columns:

| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |

I want to get the following table:

| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |

where the columns are filled with values from team_1.x and team_1.y for rows of players with number less than 5 and values from team_2.x and team_2.y for rows of players with number bigger than 5

Body:
You can use Numpy's np.where for this:

import numpy as np
...
df['x'] = np.where(df['player_num'] < 5, df['team_1.x'], df['team_2.x'])
df['y'] = np.where(df['player_num'] < 5, df['team_1.y'], df['team_2.y'])

EDIT:

# Extract column names and remove prefix to get a list of x,y,z, etc.
cols = [col.split('.')[1] for col in list(df) if 'team_' in col]

# Loop over and create new column for each prefix (x, y, z, etc)
for col in cols:
    col1 = 'team_1.' + col
    col2 = 'team_2.' + col
    df[col] = np.where(df['player_num']<5, df[col1], df[col2])


问:
I can't figure out why my filler spaces aren't being displayed in my COBOL application
Ok so I'm making this application for school, which requires a certain format of spacing between the entries read in from .txt file.  I've created the header using the filler term and the spacing works just fine, however when I apply the same method to the formatting of the records imported from the .txt it doesn't seem to work.  I've tried everything under the sun and I can't make it work for the life of me!

This is what the output looks like now:

```<code>PARTNUMBER  PARTNAME     QUANTITY  VALUE

1111111screws robertson 10 43210200Ajax
2222222screws robertson 08 41000100Ajax
2222233screws robertson 06 43210200Ajax
3333333screws robertson 04 41000100Ajax
4444444bolts dead 10       43210200Robo
5555555bolts dead 80       01000100Robo
</code>```

But, it should be something like:

```<code>PARTNUMBER PARTNAME     QUANTITY  VALUE

1111111   screws robertson 10     43210200 Ajax
2222222   screws robertson 08     41000100 Ajax
2222233   screws robertson 06     43210200 Ajax
3333333   screws robertson 04     41000100 Ajax
4444444   bolts dead       10     43210200 Robo
5555555   bolts dead.      80     01000100 Robo
</code>```

Below is the code that I think I need to make this happen, but again I'm just not sure why it isn't working

```<code> FILE SECTION.
   FD  INVENT-FILE-IN.
   01  INVENT-RECORD-IN PIC X(49).

   WORKING-STORAGE SECTION.
   01  DISPLAY-HEADERS.
       05  DISPLAY-PART-NUMBER PIC A(11)
           VALUE "PARTNUMBER".
       05  FILLER              PIC X(1).
       05  DISPLAY-PART-NAME   PIC A(9)
           VALUE "PARTNAME".
       05  FILLER              PIC X(4).
       05  DISPLAY-QUANTITY    PIC A(8)
           VALUE  "QUANTITY".
       05  FILLER              PIC X(2).
       05  DISPLAY-VALUE       PIC A(5)
           VALUE "VALUE".

   01  DISPLAY-RECORDS.
       05  WS-INVENTORY-PART-NUMBER   PIC 9(7).
       05  FILLER                     PIC X(4) VALUE SPACES.
       05  WS-INVENTORY-PART-NAME     PIC X(20).
       05  FILLER                     PIC X(4) VALUE SPACES.
       05  WS-INVENTORY-QUANTITY      PIC 9(4).
       05  FILLER                     PIC X(2) VALUE SPACES.
       05  WS-INVENTORY-VALUE         PIC 9(8).
       05  FILLER                     PIC X(1) VALUE SPACES.
       05  WS-INVENTORY-SUPPLIER-CODE PIC X(5).
   PROCEDURE DIVISION.
   100-PROCESS-INVENTORY-FILE.
       PERFORM  201-OPEN-INVENT-FILE.
       PERFORM  202-DISPLAY-HEADER.
       PERFORM  204-INPUT-INVENT-FILE
       PERFORM  206-DISPLAY-RECORDS
                     UNTIL EOF-SWITCH = "Y".
       PERFORM  205-TERMINATE-INVENTORY-FILE.
       STOP RUN.

   201-OPEN-INVENT-FILE.
       OPEN INPUT INVENT-FILE-IN.

   202-DISPLAY-HEADER.
       DISPLAY DISPLAY-HEADERS.

   206-DISPLAY-RECORDS.
       MOVE INVENT-RECORD-IN TO DISPLAY-RECORDS.
       DISPLAY DISPLAY-RECORDS.

       READ INVENT-FILE-IN
           AT END
               MOVE "Y" TO EOF-SWITCH
           NOT AT END
               COMPUTE READ-COUNTER = READ-COUNTER + 1
       END-READ.

   204-INPUT-INVENT-FILE.
       READ INVENT-FILE-IN
           AT END
               MOVE "Y" TO EOF-SWITCH
           NOT AT END
               COMPUTE READ-COUNTER = READ-COUNTER + 1
       END-READ.

   205-TERMINATE-INVENTORY-FILE.
       CLOSE  INVENT-FILE-IN.
</code>```

答:
As previously stated in the comments, in paragraph 206-DISPLAY-RECORDS, you are moving the entire input record to DISPLAY-RECORDS.

The problem here is that your input record is not formatted the same as your output record. This just means that you have to format it yourself. The easiest way to do this is to define your input input record differently. Something like this should do the trick:

```<code> FILE SECTION.
   FD  INVENT-FILE-IN.
   01  INVENT-RECORD-IN.
       05  INVENT-PART-NUMBER   PIC 9(7).
       05  INVENT-PART-NAME     PIC X(20).
       05  INVENT-QUANTITY      PIC 9(4).
       05  INVENT-VALUE         PIC 9(8).
       05  INVENT-SUPPLIER-CODE PIC X(5).
</code>```

From here, its as easy as moving this fields to their equivalent spot in you DISPLAY-RECORDS:

```<code>   206-DISPLAY-RECORDS.
       MOVE INVENT-PART-NUMBER   TO WS-INVENTORY-PART-NUMBER
       MOVE INVENT-PART-NAME     TO WS-INVENTORY-PART-NAME
       MOVE INVENT-QUANTITY      TO WS-INVENTORY-QUANTITY
       MOVE INVENT-VALUE         TO WS-INVENTORY-VALUE
       MOVE INVENT-SUPPLIER-CODE TO WS-INVENTORY-SUPPLIER-CODE

       READ INVENT-FILE-IN
           AT END
               MOVE "Y" TO EOF-SWITCH
           NOT AT END
               COMPUTE READ-COUNTER = READ-COUNTER + 1
       END-READ.
</code>```

Body:
Ok so I'm making this application for school, which requires a certain format of spacing between the entries read in from .txt file.  I've created the header using the filler term and the spacing works just fine, however when I apply the same method to the formatting of the records imported from the .txt it doesn't seem to work.  I've tried everything under the sun and I can't make it work for the life of me!

This is what the output looks like now:

PARTNUMBER  PARTNAME     QUANTITY  VALUE

1111111screws robertson 10 43210200Ajax
2222222screws robertson 08 41000100Ajax
2222233screws robertson 06 43210200Ajax
3333333screws robertson 04 41000100Ajax
4444444bolts dead 10       43210200Robo
5555555bolts dead 80       01000100Robo

But, it should be something like:

PARTNUMBER PARTNAME     QUANTITY  VALUE

1111111   screws robertson 10     43210200 Ajax
2222222   screws robertson 08     41000100 Ajax
2222233   screws robertson 06     43210200 Ajax
3333333   screws robertson 04     41000100 Ajax
4444444   bolts dead       10     43210200 Robo
5555555   bolts dead.      80     01000100 Robo

Below is the code that I think I need to make this happen, but again I'm just not sure why it isn't working

 FILE SECTION.
   FD  INVENT-FILE-IN.
   01  INVENT-RECORD-IN PIC X(49).

   WORKING-STORAGE SECTION.
   01  DISPLAY-HEADERS.
       05  DISPLAY-PART-NUMBER PIC A(11)
           VALUE "PARTNUMBER".
       05  FILLER              PIC X(1).
       05  DISPLAY-PART-NAME   PIC A(9)
           VALUE "PARTNAME".
       05  FILLER              PIC X(4).
       05  DISPLAY-QUANTITY    PIC A(8)
           VALUE  "QUANTITY".
       05  FILLER              PIC X(2).
       05  DISPLAY-VALUE       PIC A(5)
           VALUE "VALUE".

   01  DISPLAY-RECORDS.
       05  WS-INVENTORY-PART-NUMBER   PIC 9(7).
       05  FILLER                     PIC X(4) VALUE SPACES.
       05  WS-INVENTORY-PART-NAME     PIC X(20).
       05  FILLER                     PIC X(4) VALUE SPACES.
       05  WS-INVENTORY-QUANTITY      PIC 9(4).
       05  FILLER                     PIC X(2) VALUE SPACES.
       05  WS-INVENTORY-VALUE         PIC 9(8).
       05  FILLER                     PIC X(1) VALUE SPACES.
       05  WS-INVENTORY-SUPPLIER-CODE PIC X(5).
   PROCEDURE DIVISION.
   100-PROCESS-INVENTORY-FILE.
       PERFORM  201-OPEN-INVENT-FILE.
       PERFORM  202-DISPLAY-HEADER.
       PERFORM  204-INPUT-INVENT-FILE
       PERFORM  206-DISPLAY-RECORDS
                     UNTIL EOF-SWITCH = "Y".
       PERFORM  205-TERMINATE-INVENTORY-FILE.
       STOP RUN.

   201-OPEN-INVENT-FILE.
       OPEN INPUT INVENT-FILE-IN.

   202-DISPLAY-HEADER.
       DISPLAY DISPLAY-HEADERS.

   206-DISPLAY-RECORDS.
       MOVE INVENT-RECORD-IN TO DISPLAY-RECORDS.
       DISPLAY DISPLAY-RECORDS.

       READ INVENT-FILE-IN
           AT END
               MOVE "Y" TO EOF-SWITCH
           NOT AT END
               COMPUTE READ-COUNTER = READ-COUNTER + 1
       END-READ.

   204-INPUT-INVENT-FILE.
       READ INVENT-FILE-IN
           AT END
               MOVE "Y" TO EOF-SWITCH
           NOT AT END
               COMPUTE READ-COUNTER = READ-COUNTER + 1
       END-READ.

   205-TERMINATE-INVENTORY-FILE.
       CLOSE  INVENT-FILE-IN.

Body:
As previously stated in the comments, in paragraph 206-DISPLAY-RECORDS, you are moving the entire input record to DISPLAY-RECORDS.

The problem here is that your input record is not formatted the same as your output record. This just means that you have to format it yourself. The easiest way to do this is to define your input input record differently. Something like this should do the trick:

 FILE SECTION.
   FD  INVENT-FILE-IN.
   01  INVENT-RECORD-IN.
       05  INVENT-PART-NUMBER   PIC 9(7).
       05  INVENT-PART-NAME     PIC X(20).
       05  INVENT-QUANTITY      PIC 9(4).
       05  INVENT-VALUE         PIC 9(8).
       05  INVENT-SUPPLIER-CODE PIC X(5).

From here, its as easy as moving this fields to their equivalent spot in you DISPLAY-RECORDS:

   206-DISPLAY-RECORDS.
       MOVE INVENT-PART-NUMBER   TO WS-INVENTORY-PART-NUMBER
       MOVE INVENT-PART-NAME     TO WS-INVENTORY-PART-NAME
       MOVE INVENT-QUANTITY      TO WS-INVENTORY-QUANTITY
       MOVE INVENT-VALUE         TO WS-INVENTORY-VALUE
       MOVE INVENT-SUPPLIER-CODE TO WS-INVENTORY-SUPPLIER-CODE

       READ INVENT-FILE-IN
           AT END
               MOVE "Y" TO EOF-SWITCH
           NOT AT END
               COMPUTE READ-COUNTER = READ-COUNTER + 1
       END-READ.


问:
Search for characters in a string using blueprism
str1 ="HEADINGLEY";
str2 ="HDNGLY";
how can i search string 1 to see if it contains all the characters from string 2 in the order they exist in string 2 and return a true or false value using blueprism.

I tried using contains and Filter in Utility- Collection Manipulation

答:
I can't see a way of using the provided utilities to perform this exact action.

It’s easily done in a custom VBO however.

If you create a new page in Utility - Strings, give it inputs of the TARGET and LETTERS strings and a Flag output (I've called mine ORDERMATCH), you can use some vb in a Code stage such as the below to return a True/False value.

```<code>Dim CurPosition as Integer
Dim LastPosition as Integer

ORDERMATCH = False
CurPosition = 0
LastPosition = 0

For Each c As Char in LETTERS
    CurPosition = TARGET.IndexOf(c)
    If CurPosition > LastPosition Then
        ORDERMATCH = True
    Else
        ORDERMATCH = False
        Exit For
    End If
    LastPosition = CurPosition
    CurPosition = 0
Next
</code>```

It is also possible to perform this task with an object or process that follows the same basic steps:

Body:
I can't see a way of using the provided utilities to perform this exact action.

It’s easily done in a custom VBO however.

If you create a new page in Utility - Strings, give it inputs of the TARGET and LETTERS strings and a Flag output (I've called mine ORDERMATCH), you can use some vb in a Code stage such as the below to return a True/False value.

Dim CurPosition as Integer
Dim LastPosition as Integer

ORDERMATCH = False
CurPosition = 0
LastPosition = 0

For Each c As Char in LETTERS
    CurPosition = TARGET.IndexOf(c)
    If CurPosition > LastPosition Then
        ORDERMATCH = True
    Else
        ORDERMATCH = False
        Exit For
    End If
    LastPosition = CurPosition
    CurPosition = 0
Next

It is also possible to perform this task with an object or process that follows the same basic steps:


问:
Unable to target button to separate behaviour using :not()
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

```<code><tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td><a href="/fge?id=001" class="btn-fge">Find group entries</a></td>
</tr>
</code>```

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

```<code>$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}
</code>```

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

```<code>$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}
</code>```

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

答:
You can use the target property of the event object to check what element was clicked.

$('#myTable tbody').on('click', 'td', function(e) {
  //used prevent default for demonstration purposes to avoid the href link being opened.
  e.preventDefault();
  if ($(e.target).is('a.btn-fge')) {
    console.log('clicked on anchor with the class btn-fge');
  } else {
    console.log('clicked outside of anchor with the class btn-fge');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
  <tbody>
    <tr>
      <td>ID 001</td>
      <td>Foo</td>
      <td>Bar</td>
      <td>Baz</td>
      <td>Find group entries</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

    ID 001
    Foo
    Bar
    Baz
    Find group entries

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

Body:
You can use the target property of the event object to check what element was clicked.

$('#myTable tbody').on('click', 'td', function(e) {
  //used prevent default for demonstration purposes to avoid the href link being opened.
  e.preventDefault();
  if ($(e.target).is('a.btn-fge')) {
    console.log('clicked on anchor with the class btn-fge');
  } else {
    console.log('clicked outside of anchor with the class btn-fge');
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
  <tbody>
    <tr>
      <td>ID 001</td>
      <td>Foo</td>
      <td>Bar</td>
      <td>Baz</td>
      <td><a href="/fge?id=001" class="btn-fge">Find group entries</a></td>
    </tr>
  </tbody>
</table>


问:
Return null dropdown item in Flutter
I have a dropdown widget working fine but I'd need to hide the current element I'm displaying the dropdown for.

```<code>items: Provider.of<MyInvestments>(context)
                        .list
                        .map((portfolio) {
                      // if (currentPorfolio["documentID"] ==
                      //     portfolio["documentID"]) {
                      //   return DropdownMenuItem<String>(
                      //     value: null,
                      //     child: Container(),
                      //   );
                      // } else {
                      return DropdownMenuItem<String>(
                        value: portfolio["title"],
                        child: Text(portfolio["title"]),
                      );
                      //}
                    }).toList(),
</code>```

The commented part is what doesn't work. Well, it works, but it returns the empty container. I tried returning directly null or just nothing but that gives me an error.

答:
You should remove your current portfolio from list before map method.</p>

```<code>items: Provider.of<MyInvestments>(context)
                        .list.where((portfolio) =>
                             currentPorfolio["documentID"] != portfolio["documentID"])
                             .map((portfolio) {
                      return DropdownMenuItem<String>(
                        value: portfolio["title"],
                        child: Text(portfolio["title"]),
                      );
                      //}
                    }).toList(),

</code>```

Title: Return null dropdown item in Flutter

Body:
I have a dropdown widget working fine but I'd need to hide the current element I'm displaying the dropdown for.

items: Provider.of<MyInvestments>(context)
                        .list
                        .map((portfolio) {
                      // if (currentPorfolio["documentID"] ==
                      //     portfolio["documentID"]) {
                      //   return DropdownMenuItem<String>(
                      //     value: null,
                      //     child: Container(),
                      //   );
                      // } else {
                      return DropdownMenuItem<String>(
                        value: portfolio["title"],
                        child: Text(portfolio["title"]),
                      );
                      //}
                    }).toList(),

The commented part is what doesn't work. Well, it works, but it returns the empty container. I tried returning directly null or just nothing but that gives me an error.

Body:
You should remove your current portfolio from list before map method.

items: Provider.of<MyInvestments>(context)
                        .list.where((portfolio) =>
                             currentPorfolio["documentID"] != portfolio["documentID"])
                             .map((portfolio) {
                      return DropdownMenuItem<String>(
                        value: portfolio["title"],
                        child: Text(portfolio["title"]),
                      );
                      //}
                    }).toList(),


问:
How to create nested array or multidimensional array
I am trying to figure out how to do either nested arrays or multidimensional array for iPhone SDK programming using objective-c.

My data would be something like this, 3 columns and rows from 10 to 50.

```<code>name     department     year
John     Sales          2008
Lisa     Sales          2009
Gina     Support        2007
</code>```

Any help is appreciated

答:
from @Stephen example... You can do this to get first employee name.</p>

```<code>Employee *e = (Employee *) [array objectAtIndex:0];

NSLog(@"Name: %@", e.name);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to figure out how to do either nested arrays or multidimensional array for iPhone SDK programming using objective-c.

My data would be something like this, 3 columns and rows from 10 to 50.

name     department     year
John     Sales          2008
Lisa     Sales          2009
Gina     Support        2007

Any help is appreciated

Body:
from @Stephen example... You can do this to get first employee name.

Employee *e = (Employee *) [array objectAtIndex:0];

NSLog(@"Name: %@", e.name);


问:
What triggers the onsubmit event? How to configure that?
Naively you might assume that the event is triggered that when the (a?) input button of type "submit" is clicked.

In fact, as far as I'm able to ascertain, every button within a form triggers the event.

Is there some way to set a button to not trigger the event?

答: Button's default type is submit. If you want buttons that don't submit, you have to change their type to button.</p>


问:
Angular HTTP Post multiple JSON objects
I am trying to post multiple JSON objects through HTTPClient. I want to send them as one object at a time though, consecutively one after the other. How do I do that?

I am currently mapping through another object array I already have to create a new object array that I want to post. I can successfully console.log the giant object array (86 objects) one by one using the for loop; but I cannot figure out how to http post them one by one.

```<code>    this.newdailys = this.rooms.map(room => ({
      id: null,
      timeCreated0: this.date,
      roomid1: room.id,
      guestwaiting2: null,
      supervisorconfirmed3: null,
      finishedcleaning4: null,
      staffid5: null,
      bathtowelIN6: null,
      bathtowelOUT7: null,
      bathmattIN8: null,
      bathmattOUT9: null,
      sheetSIN10: null,
      sheetSOUT11: null,
      duvetSIN12: null,
      duvetSOUT13: null,
      sheetDIN14: null,
      sheetDOUT15: null,
      duvetDIN16: null,
      duvetDOUT17: null,
      pillowcaseIN18: null,
      pillowcaseOUT19: null,
      bolstercaseIN20: null,
      bolstercaseOUT21: null,
      sugarIN22: null,
      teaIN23: null,
      coffeeIN24: null,
      creamerIN25: null,
      stirerIN26: null,
      mwaterIN27: null,
      slipperIN28: null,
      barsoapIN29: null,
      shampooIN30: null,
      dentalkitIN31:null,
      cottonbudIN32: null,
      showercapIN33: null,
      roomtissueIN34: null,
      HBTIN35: null,
      coasterglassIN36: null,
      plastikbeningIN37: null,
      mug238: null,
      electricjug39:null,
      tumblerglass240:null,
      traymerah141: null,
      sugarbowl142: null,
      bedskirting43: null,
      bedpad44: null,
      hanger45:null,
      telpon46: null,
      lamp47: null,
      hairdryer48: null,
      jetshower49: null,
      television50: null,
      underbed51: null,
      timeCompleted52: null,
      deleted53: false,
      }))
      for (let i = 0; i < newdailys.length; i++) {
      return this.http.post(http://localhost:3000/dailys, newdailys[i])}}

/// what has worked was for (let i = 0; i < newdailys.length; i++) {
      console.log(newdailys[i])}

</code>```

答:
Well this:

```<code>for (let i = 0; i < newdailys.length; i++) {
      return this.http.post(http://localhost:3000/dailys, newdailys[i])
}
</code>```

will always return after it posts the first object. Your return statement will immediately return to the function caller and abort the for-loop.

Like Quentin already mentioned in his comment, it all depends on how your server side expects them to be formatted. But according to your question I assume, you just want to send each object in a separate post request.

Just remove the return statement inside your for-loop. Of course you want to do something with the responses of your requests. One solution might be to use the
rxjs forkJoin operator. And return the resulting observable.

For example you could come up with something like:

```<code>postObjects(newdailys: any[]) {
    const postObservables: Observable<any>[] = newdailys.map(daily => this.http.post('http://localhost:3000/dailys', daily));
    return forkJoin(...postObservables);
  }
</code>```

But like mentioned above this depends entirely on what you want to do with the results.

Title: Angular HTTP Post multiple JSON objects

Body:
I am trying to post multiple JSON objects through HTTPClient. I want to send them as one object at a time though, consecutively one after the other. How do I do that?

I am currently mapping through another object array I already have to create a new object array that I want to post. I can successfully console.log the giant object array (86 objects) one by one using the for loop; but I cannot figure out how to http post them one by one.

    this.newdailys = this.rooms.map(room => ({
      id: null,
      timeCreated0: this.date,
      roomid1: room.id,
      guestwaiting2: null,
      supervisorconfirmed3: null,
      finishedcleaning4: null,
      staffid5: null,
      bathtowelIN6: null,
      bathtowelOUT7: null,
      bathmattIN8: null,
      bathmattOUT9: null,
      sheetSIN10: null,
      sheetSOUT11: null,
      duvetSIN12: null,
      duvetSOUT13: null,
      sheetDIN14: null,
      sheetDOUT15: null,
      duvetDIN16: null,
      duvetDOUT17: null,
      pillowcaseIN18: null,
      pillowcaseOUT19: null,
      bolstercaseIN20: null,
      bolstercaseOUT21: null,
      sugarIN22: null,
      teaIN23: null,
      coffeeIN24: null,
      creamerIN25: null,
      stirerIN26: null,
      mwaterIN27: null,
      slipperIN28: null,
      barsoapIN29: null,
      shampooIN30: null,
      dentalkitIN31:null,
      cottonbudIN32: null,
      showercapIN33: null,
      roomtissueIN34: null,
      HBTIN35: null,
      coasterglassIN36: null,
      plastikbeningIN37: null,
      mug238: null,
      electricjug39:null,
      tumblerglass240:null,
      traymerah141: null,
      sugarbowl142: null,
      bedskirting43: null,
      bedpad44: null,
      hanger45:null,
      telpon46: null,
      lamp47: null,
      hairdryer48: null,
      jetshower49: null,
      television50: null,
      underbed51: null,
      timeCompleted52: null,
      deleted53: false,
      }))
      for (let i = 0; i < newdailys.length; i++) {
      return this.http.post(http://localhost:3000/dailys, newdailys[i])}}

/// what has worked was for (let i = 0; i < newdailys.length; i++) {
      console.log(newdailys[i])}

Body:
Well this:

for (let i = 0; i < newdailys.length; i++) {
      return this.http.post(http://localhost:3000/dailys, newdailys[i])
}

will always return after it posts the first object. Your return statement will immediately return to the function caller and abort the for-loop.

Like Quentin already mentioned in his comment, it all depends on how your server side expects them to be formatted. But according to your question I assume, you just want to send each object in a separate post request.

Just remove the return statement inside your for-loop. Of course you want to do something with the responses of your requests. One solution might be to use the
rxjs forkJoin operator. And return the resulting observable.

For example you could come up with something like:

postObjects(newdailys: any[]) {
    const postObservables: Observable<any>[] = newdailys.map(daily => this.http.post('http://localhost:3000/dailys', daily));
    return forkJoin(...postObservables);
  }

But like mentioned above this depends entirely on what you want to do with the results.


问:
How can I change datagridview table with combobox?
I try change datagridview table with combobox. But I can't change with parameters. How can I change database table?

```<code>public DataTable TableLoad()
    {
        DataSet AL2020DS = new DataSet();
        SqlDataAdapter SQLDA = new SqlDataAdapter();
        SqlCommand Cmd1;
        string Sql = "SELECT * FROM @value ORDER BY [Donanım Seri No] ASC";
        Cmd1 = new SqlCommand(Sql, con);
        Cmd1.Parameters.AddWithValue("@value", cbbox_llisteler.Text);
        SQLDA.SelectCommand = Cmd1;
        DataTable AL2020DT = new DataTable();
        SQLDA.Fill(AL2020DT);
        return AL2020DT;
    }

public Form1()
    {
        InitializeComponent();
        dataGridView1.DataSource = TableLoad();
    }
</code>```

When I try this parameters command ı get this error : Must declare the table variable "@value"

答:
I find solution

```<code>string Sql = "SELECT * FROM " + TextBox1.Text + " ORDER BY [Hardware Serial Number] ASC"
</code>```

I use this code in click function.

Body:
I try change datagridview table with combobox. But I can't change with parameters. How can I change database table?

public DataTable TableLoad()
    {
        DataSet AL2020DS = new DataSet();
        SqlDataAdapter SQLDA = new SqlDataAdapter();
        SqlCommand Cmd1;
        string Sql = "SELECT * FROM @value ORDER BY [Donanım Seri No] ASC";
        Cmd1 = new SqlCommand(Sql, con);
        Cmd1.Parameters.AddWithValue("@value", cbbox_llisteler.Text);
        SQLDA.SelectCommand = Cmd1;
        DataTable AL2020DT = new DataTable();
        SQLDA.Fill(AL2020DT);
        return AL2020DT;
    }

public Form1()
    {
        InitializeComponent();
        dataGridView1.DataSource = TableLoad();
    }

When I try this parameters command ı get this error : Must declare the table variable "@value"

Body:
I find solution

string Sql = "SELECT * FROM " + TextBox1.Text + " ORDER BY [Hardware Serial Number] ASC"

I use this code in click function.


问:
Array filter is not returning correct for Zero?

function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));```

I want to return the no. of zero present in the array using filter.

答:
You need to understand how the filter works.

the filter function will pick or remove elements based on your return true or false from inside.

you are returning el which is 0. 0 in JS is false. that's why your code doesn't work.

two possible solutions
1)

```<code>function zeroCount(arr){
 const zero = arr.filter(el=>{
        if(el===0){
            return true ;
        }
    });
   return zero.length ; // but it returns 0. I want it to return 3.
 }
</code>```

2)

```<code>function zeroCount(arr){
  const zero = arr.filter(el=> !el);
  return zero.length ; // but it returns 0. I want it to return 3.
 }
</code>```

3) to show off

```<code>zeroCount = (arr) => arr.filter(el => !el).length
</code>```

Body:
function zeroCount(arr){
   const zero = arr.filter(el=>{
            if(el===0){
                return el ;
            }
        });
    return zero.length ; // but it returns 0. I want it to return 3.
}

console.log(zeroCount([2,3,0,5,0,2,0]));

I want to return the no. of zero present in the array using filter.

Body:
You need to understand how the filter works.

the filter function will pick or remove elements based on your return true or false from inside.

you are returning el which is 0. 0 in JS is false. that's why your code doesn't work.

two possible solutions
1)

function zeroCount(arr){
 const zero = arr.filter(el=>{
        if(el===0){
            return true ;
        }
    });
   return zero.length ; // but it returns 0. I want it to return 3.
 }

2)

function zeroCount(arr){
  const zero = arr.filter(el=> !el);
  return zero.length ; // but it returns 0. I want it to return 3.
 }

3) to show off

zeroCount = (arr) => arr.filter(el => !el).length


问:
How to enable Linux firewall(ufw) for custom program running on random port
Written program in python, which chooses random port available for TCP and UDP communication. If I enable Linux firewall(ufw) by running sudo ufw enable. where we can allow any port by giving
 sudo ufw allow port_number. As the program can take any random port on run, so can not tell ufw to allow any particular port. Is there any way to tell ufw to allow prog to access any random port by supplying program name to ufw like in windows. In windows firewall, we can supply the following command to allow access to all port for myprog

```<code>netsh advfirewall firewall add rule name=rule_name_udp dir=in action=allow protocol=UDP localport=any program=path/myprog.exe
</code>```

is there any way to allow ufw for my custom program to access for udp/tcp communication with ufw enable?

Thanks to all in advance.

答:
You can wrap your app into systemd service and use post-start hook to call extra bash script which punches holes in firewall.

/path/to/python/app/assistant-ufw-hole-puncher

#!/bin/bash

#extra sleep for prespawn script
sleep 2

#punch holes for TCP ports
ports=`sudo netstat -ntlp 2>&1 |grep yourapp | sed -r 's/(.*:)([0-9]*)(\s.*)/\2/'|sort|uniq`
for port in $ports ; do
  sudo ufw allow $port
done

#punch holes for UDP ports
ports=`sudo netstat -nulp 2>&1 |grep yourapp | sed -r 's/(.*:)([0-9]*)(\s.*)/\2/'|sort|uniq`
for port in $ports ; do
  sudo ufw allow $port
done
```

<p>Also you could spawn this script before starting your script but you would need to add extra sleep to wait for python script to start.</p>

<pre class="lang-sh prettyprint-override"><code>#!/bin/bash

/path/to/python/app/assistant-ufw-hole-puncher &
python ./your-app.py
</code>```

Body:
Written program in python, which chooses random port available for TCP and UDP communication. If I enable Linux firewall(ufw) by running sudo ufw enable. where we can allow any port by giving
 sudo ufw allow port_number. As the program can take any random port on run, so can not tell ufw to allow any particular port. Is there any way to tell ufw to allow prog to access any random port by supplying program name to ufw like in windows. In windows firewall, we can supply the following command to allow access to all port for myprog

netsh advfirewall firewall add rule name=rule_name_udp dir=in action=allow protocol=UDP localport=any program=path/myprog.exe

is there any way to allow ufw for my custom program to access for udp/tcp communication with ufw enable?

Thanks to all in advance.

Body:
You can wrap your app into systemd service and use post-start hook to call extra bash script which punches holes in firewall.

/path/to/python/app/assistant-ufw-hole-puncher

#!/bin/bash

#extra sleep for prespawn script
sleep 2

#punch holes for TCP ports
ports=`sudo netstat -ntlp 2>&1 |grep yourapp | sed -r 's/(.*:)([0-9]*)(\s.*)/\2/'|sort|uniq`
for port in $ports ; do
  sudo ufw allow $port
done

#punch holes for UDP ports
ports=`sudo netstat -nulp 2>&1 |grep yourapp | sed -r 's/(.*:)([0-9]*)(\s.*)/\2/'|sort|uniq`
for port in $ports ; do
  sudo ufw allow $port
done

Also you could spawn this script before starting your script but you would need to add extra sleep to wait for python script to start.

#!/bin/bash

/path/to/python/app/assistant-ufw-hole-puncher &
python ./your-app.py


答:
every button within a form triggers the event

No. Only submit buttons do. (As well as a few other cases such as when the Enter key is pressed in a text input).

Note that <button> elements are type="submit" by default and should be type="button" if you want a non-submit button for handing JS from.

You can also attach a JavaScript click event listener to a button and call preventDefault on the event object.

Title: What triggers the onsubmit event? How to configure that?

Body:
Naively you might assume that the event is triggered that when the (a?) input button of type "submit" is clicked.

In fact, as far as I'm able to ascertain, every button within a form triggers the event.

Is there some way to set a button to not trigger the event?


问:
How to make a WPF ScrollViewer use only the available width?
I have a wpf window, and there is a footer sections that can have multiple content which makes the width of the footer grows.

I set SizeToContent="WidthAndHeight" in my Window and when I add a lot of content to ScrollViewer, it grows accordingly, instead of just show the scrollbar.

It looks like ScrollViewer is taking into account its content, so how do I set the ScrollViewer to ignore it's content and only take the width available instead of make it grow?

thanks!

答: Try setting the MaxWidth property of the ScrollViewer. Once it has reached this width, it should start showing scrollbars.</p>


问:
VueJS components prop execution order
I'm using vuejs and vue-apollo in my project.

I have to components : GroupList and GroupForm

The thing is that I first arrive on the list, and then when I click on one of the groups, I arrive in the form view of that group.
To do that, I have a button that opens the form view by giving the id of that group :

```<code>openGroupFormView (group, index) {
  this.$router.push({ name: 'GroupFormView', params: { groupId: group.id } })
}
</code>```

In the past, I used to pass the group object as paramater and it worked but I changed my mind and now I want to pass the id so that when the component GroupForm is opened, the graphql query to retrieve this group based on the id is executed. I want to do that in order to avoid apollo-cache inconsistencies in case where someone edited the same group in the meantime.

So in my GroupForm component I have :

My prop :

```<code>props: {
  groupId: Number
}
</code>```

My component query :

```<code>apollo: {
  group: {
    query: GROUP_QUERY,
    variables () {
      return {
        id: this.groupId
      }
    },
    ..
}
</code>```

The associated query beneath that :

```<code>const GROUP_QUERY = gql`
  query ($id: ID) {
    group (id: $id) {
      id
      name
      usersCount
      userIds {
        id
        username
      }
    }
  }
`
</code>```

My problem is that in data () of my component, I used to use the group that I passed through the props as an object. Now, I still want to do things on the group but the apollo part is executed after the data () part so I have an undefined problem. How could I ensure that this problem doesn't occur ? I mean that apollo query is run first.

My data() block :

```<code>data () {
  return {
    form: {
      name: this.group === undefined ? '' : this.group.name
    }
  }
},
</code>```

Thanks in advance for your help !

EDIT : A part of my template

```<code>  <b-form>
    <b-form-group label="Name">
      <b-form-input
        type="text"
        v-model="form.name"
        required
        :disabled="!editing"/>
    </b-form-group>
    <div v-if="editing" class="mb-3">
      <b-button @click="cancelEdit()">Cancel</b-button>
      <b-button @click="group === undefined ? createGroup() : updateGroup(group)" variant="success">Save</b-button>
    </div>
  </b-form>
</code>```

答:
I don't use Apollo but it looks like you should be able to initialize name to an empty string and then use the result hook to set it when the query completes.

Untested:

apollo: {
  group: {
    ...
    result({ data, loading, networkStatus }) {
      this.form.name = data.name // something like this
    }
  }
}
```

Title: VueJS components prop execution order

Body:
I'm using vuejs and vue-apollo in my project.

I have to components : GroupList and GroupForm

The thing is that I first arrive on the list, and then when I click on one of the groups, I arrive in the form view of that group.
To do that, I have a button that opens the form view by giving the id of that group :

openGroupFormView (group, index) {
  this.$router.push({ name: 'GroupFormView', params: { groupId: group.id } })
}

In the past, I used to pass the group object as paramater and it worked but I changed my mind and now I want to pass the id so that when the component GroupForm is opened, the graphql query to retrieve this group based on the id is executed. I want to do that in order to avoid apollo-cache inconsistencies in case where someone edited the same group in the meantime.

So in my GroupForm component I have :

My prop :

props: {
  groupId: Number
}

My component query :

apollo: {
  group: {
    query: GROUP_QUERY,
    variables () {
      return {
        id: this.groupId
      }
    },
    ..
}

The associated query beneath that :

const GROUP_QUERY = gql`
  query ($id: ID) {
    group (id: $id) {
      id
      name
      usersCount
      userIds {
        id
        username
      }
    }
  }
`

My problem is that in data () of my component, I used to use the group that I passed through the props as an object. Now, I still want to do things on the group but the apollo part is executed after the data () part so I have an undefined problem. How could I ensure that this problem doesn't occur ? I mean that apollo query is run first.

My data() block :

data () {
  return {
    form: {
      name: this.group === undefined ? '' : this.group.name
    }
  }
},

Thanks in advance for your help !

EDIT : A part of my template

      Cancel
      Save