问:
Resizing checkbox in form group in Laravel
```<code><div class="col-md-3">
    <div class="white-box">
        {{ Form::open(['route' => ['resources.select'], 'method' => 'ANY', 'role' => 'select']) }}
        <div class="form-group">
                {{ Form::label('category_label', 'Categories : ') }}
                {{ Form::select('category_select', $category_select, ['class'=>'form-control']) }}
                {{ Form::button('Submit',['type'=>'submit','class'=>'btn btn-success waves-effect waves-light m-r-10', 'id'=>'select_resource']) }}
        </div>
        {{ Form::close() }}
    </div>
</div>
</code>```

This is my code. I have three different divisions that look the same. When I tried to change to a grid view, The select boxes stay overlapping the div block.
I want them to stay within the block in the view.

答:
The reason why your select is overlapping is because you are missing null as a parameter in the declaration.

Change this line;

```<code>{{ Form::select('category_select', $category_select, ['class'=>'form-control']) }}
</code>```

to this;

```<code>{{ Form::select('category_select', $category_select, null, ['class'=>'form-control']) }}
</code>```

Also you do not need the   to style the form. A more efficient way of creating the form in your question would be like the example below

```<code><div class="col-md-3">
    <div class="white-box">
        {{ Form::open(['route' => ['resources.select'], 'method' => 'ANY', 'role' => 'select']) }}
        <div class="form-group">
           {{ Form::label('category_label', 'Categories : ') }}
           {{ Form::select('category_select', $category_select, null, ['class'=>'form-control']) }}
        </div>
        {{ Form::button('Submit',['type'=>'submit','class'=>'btn btn-success waves-effect waves-light m-r-10', 'id'=>'select_resource']) }}
        {{ Form::close() }}
    </div>
</div>
</code>```

Body:
        {{ Form::open(['route' => ['resources.select'], 'method' => 'ANY', 'role' => 'select']) }}

                {{ Form::label('category_label', 'Categories : ') }}
                {{ Form::select('category_select', $category_select, ['class'=>'form-control']) }}
                {{ Form::button('Submit',['type'=>'submit','class'=>'btn btn-success waves-effect waves-light m-r-10', 'id'=>'select_resource']) }}

        {{ Form::close() }}

This is my code. I have three different divisions that look the same. When I tried to change to a grid view, The select boxes stay overlapping the div block.
I want them to stay within the block in the view.

Body:
The reason why your select is overlapping is because you are missing null as a parameter in the declaration.

Change this line;

{{ Form::select('category_select', $category_select, ['class'=>'form-control']) }} &nbsp;&nbsp;

to this;

{{ Form::select('category_select', $category_select, null, ['class'=>'form-control']) }}

Also you do not need the &nbsp; to style the form. A more efficient way of creating the form in your question would be like the example below

<div class="col-md-3">
    <div class="white-box">
        {{ Form::open(['route' => ['resources.select'], 'method' => 'ANY', 'role' => 'select']) }}
        <div class="form-group">
           {{ Form::label('category_label', 'Categories : ') }}
           {{ Form::select('category_select', $category_select, null, ['class'=>'form-control']) }}
        </div>
        {{ Form::button('Submit',['type'=>'submit','class'=>'btn btn-success waves-effect waves-light m-r-10', 'id'=>'select_resource']) }}
        {{ Form::close() }}
    </div>
</div>


来源: stackexchange

问:
SELECT WHERE IN with GROUP_CONCAT as input
Please read this before continuing: Filter an unfiltered table against a whitelist table

So, I currently have a whitelist table set up as shown in the referenced link, and I'm encountering yet another issue brought up by said table, that is, to check the UNIQUENESS of each column. As MySQL's specification, it is not possible to set NULL column as UNIQUE, so, I've decided to come up with a different solution to check if rows are duplicated or not by using a SELECT GROUP BY query as follows.

```<code>SELECT GROUP_CONCAT(ID) AS IDs, country, region, item, count(*) AS amount
FROM whitelist
</code>```

Now, to check if the item is duplicated, I've warpped it on top of another layer.

```<code>SELECT IDs, country, region, item, amount
FROM (SELECT GROUP_CONCAT(ID) AS IDs, country, region, item, count(*) AS amount
      FROM whitelist) tmp
WHERE amount > 1
</code>```

Still works fine as intended, but the question starts here.

Is it possible for me to use this data, and RE-SELECT the whitelist table so I can get each entry as a row with something like ...

```<code>SELECT ID, country, region, item
FROM whitelist
WHERE ID IN (SELECT group_concat(ID)
               FROM (SELECT group_concat(ID) AS ID, country, region, item, COUNT(*) AS AMOUNT
                       FROM whitelist
                      GROUP BY country, region, item) tmp
              WHERE AMOUNT > 1)
</code>```

Of course, I could just use PHP and explode the group_concat IDs and re-select it, but I'm wondering if it's possible to do it in one SQL query call instead of two.

Edit: Oops, the example above had an error in it (accidentally used real schema there xD)

Edit2: Doh, I suddenly thought why complicate things and why not just simply go with this ...

```<code>SELECT wl1.ID, wl1.country, wl1.region, wl1.item, wl1.reason
  FROM whitelist wl1,
       (SELECT country, region, item
          FROM whitelist
         GROUP BY country, region, item
        HAVING count(*) > 1) wl2
 WHERE wl1.country = wl2.country AND
       wl1.region = wl2.region AND
       wl1.item = wl2.reason
</code>```

... but still fails too, because you cannot use = on two NULL columns. Urgh, so close yet so far >.<

To: Bill Karwin

That is exactly the issue here. If I set a unique key on country, region, item, and I perform the following SQL, this will happen.

```<code>INSERT INTO whitelist(country, region, item) VALUES ('Taiwan', 'Asia', 'PC');
INSERT INTO whitelist(country, region, item) VALUES ('Taiwan', 'Asia', 'PC');
-- Would fail due to UNIQUE check
</code>```

However, if I include any of the wildcards, aka NULL, and this would happen.

```<code>INSERT INTO whitelist(country, region, item) VALUES (NULL, 'Asia', 'Rice');
INSERT INTO whitelist(country, region, item) VALUES (NULL, 'Asia', 'Rice');
-- Would succeed due to UNIQUE does not check NULL columns.
</code>```

Hence the idea of this post is to list all repeating whitelist in a list so that the operator can decide what to keep and what to delete.

答:
Not keen on this solution, but viable:-</p>

```<code>SELECT a.ID,
        a.country,
        a.region,
        a.item
FROM whitelist a
INNER JOIN
(
    SELECT group_concat(ID) AS ID, USERNAME, COMPNAME, PUBLISHER, NAME, VERSION, COUNT(*) AS AMOUNT
    FROM software_checklist
    GROUP BY USERNAME, COMPNAME, PUBLISHER, NAME, VERSION
    HAVING AMOUNT > 1
) tmp
ON FIND_IN_SET(a.ID, tmp.ID)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please read this before continuing: Filter an unfiltered table against a whitelist table

So, I currently have a whitelist table set up as shown in the referenced link, and I'm encountering yet another issue brought up by said table, that is, to check the UNIQUENESS of each column. As MySQL's specification, it is not possible to set NULL column as UNIQUE, so, I've decided to come up with a different solution to check if rows are duplicated or not by using a SELECT GROUP BY query as follows.

SELECT GROUP_CONCAT(ID) AS IDs, country, region, item, count(*) AS amount
FROM whitelist

Now, to check if the item is duplicated, I've warpped it on top of another layer.

SELECT IDs, country, region, item, amount
FROM (SELECT GROUP_CONCAT(ID) AS IDs, country, region, item, count(*) AS amount
      FROM whitelist) tmp
WHERE amount > 1

Still works fine as intended, but the question starts here.

Is it possible for me to use this data, and RE-SELECT the whitelist table so I can get each entry as a row with something like ...

SELECT ID, country, region, item
FROM whitelist
WHERE ID IN (SELECT group_concat(ID)
               FROM (SELECT group_concat(ID) AS ID, country, region, item, COUNT(*) AS AMOUNT
                       FROM whitelist
                      GROUP BY country, region, item) tmp
              WHERE AMOUNT > 1)

Of course, I could just use PHP and explode the group_concat IDs and re-select it, but I'm wondering if it's possible to do it in one SQL query call instead of two.

Edit: Oops, the example above had an error in it (accidentally used real schema there xD)

Edit2: Doh, I suddenly thought why complicate things and why not just simply go with this ...

SELECT wl1.ID, wl1.country, wl1.region, wl1.item, wl1.reason
  FROM whitelist wl1,
       (SELECT country, region, item
          FROM whitelist
         GROUP BY country, region, item
        HAVING count(*) > 1) wl2
 WHERE wl1.country = wl2.country AND
       wl1.region = wl2.region AND
       wl1.item = wl2.reason

... but still fails too, because you cannot use = on two NULL columns. Urgh, so close yet so far >.<

To: Bill Karwin

That is exactly the issue here. If I set a unique key on country, region, item, and I perform the following SQL, this will happen.

INSERT INTO whitelist(country, region, item) VALUES ('Taiwan', 'Asia', 'PC');
INSERT INTO whitelist(country, region, item) VALUES ('Taiwan', 'Asia', 'PC');
-- Would fail due to UNIQUE check

However, if I include any of the wildcards, aka NULL, and this would happen.

INSERT INTO whitelist(country, region, item) VALUES (NULL, 'Asia', 'Rice');
INSERT INTO whitelist(country, region, item) VALUES (NULL, 'Asia', 'Rice');
-- Would succeed due to UNIQUE does not check NULL columns.

Hence the idea of this post is to list all repeating whitelist in a list so that the operator can decide what to keep and what to delete.

Body:
Not keen on this solution, but viable:-

SELECT a.ID,
        a.country,
        a.region,
        a.item
FROM whitelist a
INNER JOIN
(
    SELECT group_concat(ID) AS ID, USERNAME, COMPNAME, PUBLISHER, NAME, VERSION, COUNT(*) AS AMOUNT
    FROM software_checklist
    GROUP BY USERNAME, COMPNAME, PUBLISHER, NAME, VERSION
    HAVING AMOUNT > 1
) tmp
ON FIND_IN_SET(a.ID, tmp.ID)


问:
Adguard blocks dataLayer.push for GTM
I have function which pushes clicked link attributes to dataLayer for Google tag manager.

https://developers.google.com/tag-manager/enhanced-ecommerce

Problem is that extension "adguard" has ability to block such tracking.
In adguard it calls 'A filter for all known counters and analytical systems'. While blocking dataLayer.push, it blocks eventCallback event too and link doesn't get opened.

Here is function:

function ga_promoTriggerClick(e)
{
    var p_id = $(e).attr("data-id");
    var p_name = $(e).attr("data-name");
    var p_creation = $(e).attr("data-creation");
    var p_pos = $(e).attr("data-pos");

    dataLayer.push({
        'event': 'promotionClick',
        'ecommerce': {
            'promoClick': {
                'promotions': [
                    {
                        'id': p_id,
                        'name': p_name,
                        'creative': p_creation,
                        'position': p_pos
                    }]
            }
        },
        'eventCallback': function()
        {
            var p_href = $(e).attr("href");
            if(typeof p_href != "undefined")
            {
                document.location = $(e).attr("href");
            }
        }
    });
}```

How can i send user to link if "adguard" is blocking the dataLayer.push?

Some thoughts:

Error / Success / Fail function, but none of them exists.

Set timeout 1 second ( this way user will have 'lag' )

Check if adguard is turned on ( somehow ) and on click check the variable

Thanks for suggestions

答:
Solution which worked for me is pretty simple. All i needed is to check if tag manager works.

```<code><script type="text/javascript">
window.addEventListener('load', function()
{
    if(window.ga && ga.create)
    {
        console.log('Google Analytics is loaded');
    }
    else
    {
        console.log('Google Analytics is not loaded');
    }

    if(window.google_tag_manager)
    {
        console.log('Google Tag Manager is loaded');
    }
    else
    {
        console.log('Google Tag Manager is not loaded');
    }
}, false);
</script>
</code>```

Solution was found here: https://marthijnhoiting.com/detect-if-someone-is-blocking-google-analytics-or-google-tag-manager/

Title: Adguard blocks dataLayer.push for GTM

Body:
I have function which pushes clicked link attributes to dataLayer for Google tag manager.

https://developers.google.com/tag-manager/enhanced-ecommerce

Problem is that extension "adguard" has ability to block such tracking.
In adguard it calls 'A filter for all known counters and analytical systems'. While blocking dataLayer.push, it blocks eventCallback event too and link doesn't get opened.

Here is function:

function ga_promoTriggerClick(e)
{
    var p_id = $(e).attr("data-id");
    var p_name = $(e).attr("data-name");
    var p_creation = $(e).attr("data-creation");
    var p_pos = $(e).attr("data-pos");

    dataLayer.push({
        'event': 'promotionClick',
        'ecommerce': {
            'promoClick': {
                'promotions': [
                    {
                        'id': p_id,
                        'name': p_name,
                        'creative': p_creation,
                        'position': p_pos
                    }]
            }
        },
        'eventCallback': function()
        {
            var p_href = $(e).attr("href");
            if(typeof p_href != "undefined")
            {
                document.location = $(e).attr("href");
            }
        }
    });
}

How can i send user to link if "adguard" is blocking the dataLayer.push?

Some thoughts:

Error / Success / Fail function, but none of them exists.

Set timeout 1 second ( this way user will have 'lag' )

Check if adguard is turned on ( somehow ) and on click check the variable

Thanks for suggestions

Body:
Solution which worked for me is pretty simple. All i needed is to check if tag manager works.

<script type="text/javascript">
window.addEventListener('load', function()
{
    if(window.ga && ga.create)
    {
        console.log('Google Analytics is loaded');
    }
    else
    {
        console.log('Google Analytics is not loaded');
    }

    if(window.google_tag_manager)
    {
        console.log('Google Tag Manager is loaded');
    }
    else
    {
        console.log('Google Tag Manager is not loaded');
    }
}, false);
</script>

Solution was found here: https://marthijnhoiting.com/detect-if-someone-is-blocking-google-analytics-or-google-tag-manager/


问:
jmeter - Is there any simple way to handle dynamic viewstates when the viewstate count is more?
My request has 3800 viewstates that are coming from the previous request's response. Its very hard to capture the values one by one using reg expression and replacing them with variables.

Is there any simple way to handle them?

答:
There is an alternative way of recording a JMeter test using a cloud-based proxy service. It is capable of exporting recordings in SmartJMX format with automatic detection and correlation of dynamic parameters so you won't have to handle them manually - the necessary PostProcessors and variables substitutions will be added to the test plan automatically.

Check out How to Cut Your JMeter Scripting Time by 80% article for more details.

In general I would recommend talking to your application developers as almost 4k dynamic parameters are too much, it will create at least massive network IO overhead to pass them back and forth and immense CPU/RAM to parse on both sides.


问:
Adding elements in a list
I have a list named p. It contains some elements like this.

```<code>p = [['mon', '1006'], ['mon', '769']].
</code>```

I want to add the values like (1006 + 769) and print the summation. How Can I do that??

答:
If you are saying that you want to sum up the second values of the elements in your list, try this:</p>

```<code>print(sum([int(element[1]) for element in p]))
</code>```

Title: Adding elements in a list

Body:
I have a list named p. It contains some elements like this.

p = [['mon', '1006'], ['mon', '769']].

I want to add the values like (1006 + 769) and print the summation. How Can I do that??

Body:
If you are saying that you want to sum up the second values of the elements in your list, try this:

print(sum([int(element[1]) for element in p]))


答:
This is a very basic question, so you should probably work through the Python tutorial. Also, asking for the solution without attempting anything on your own won't teach you Python.

Here's the most straight forward, naive approach you could have come up with:

```<code>>>> p = [['mon', '1006'], ['mon', '769']]
>>> total = 0
>>>
>>> for sublist in p:
...     value = sublist[1]
...     value_as_int = int(value)
...     total = total + value_as_int
...
>>> print(total)
1775
</code>```

That's just a for loop, basic summation and indexing into a list.
I'll spare you the fancier oneliners for now, I'm sure other answer will show you those.

Title: Adding elements in a list

Body:
This is a very basic question, so you should probably work through the Python tutorial. Also, asking for the solution without attempting anything on your own won't teach you Python.

Here's the most straight forward, naive approach you could have come up with:

>>> p = [['mon', '1006'], ['mon', '769']]
>>> total = 0
>>>
>>> for sublist in p:
...     value = sublist[1]
...     value_as_int = int(value)
...     total = total + value_as_int
...
>>> print(total)
1775

That's just a for loop, basic summation and indexing into a list.
I'll spare you the fancier oneliners for now, I'm sure other answer will show you those.


问:
Django one-to-many relationship in models (not about lookups)
I am trying to figure out how to define a one-to-many relationship between two models. The difficulty here is that I do not want to touch one of the models and therefore can not use the usual ForeignKey (Many-to-one).

There are many question on this topic but they all either talk about how to do the lookup (reverse ForeignKey lookup) or they suggest to just add a Foreign Key to one side.
Here is a similar question. I will use the same code example.
This is what I am looking for:

```<code>class Dude(models.Model):
    numbers = models.OneToManyField('PhoneNumber')

class PhoneNumber(models.Model):
    number = models.CharField()
</code>```

Usually I would go ahead and just add a Foreign Key to PhoneNumber as suggested in many answers:

```<code>class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude, related_name='numbers')
</code>```

But in my situation I would like to not touch the PhoneNumber model and therefore define something on the Dude model.

The reason for this is that I am defining a model describing a special circumstance which is rarely used. If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all instances leave this field blank. I do not really like the idea to have a field which is always blank - maybe this is my problem.

A possible work-around is to define a many-to-many field and then add some logic actually preventing 'many' on one side and enforcing that the other side is not empty.

I hope I could describe my problem clearly.

Question:
Is there some way to define a one-to-many relationship? Is there a better solution with a different approach for my problem?

P.S. The only hit on this I get from the django docs is a field attribute one_to_many which, I am guessing, is used for the lookup.

答:
If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all models leave this field blank. I do not really like the idea to have a field which is always blank - maybe this is my problem.

It kind of is. To define a one-to-many you use ForeignKey, and this will need to be on the PhoneNumber model. This doesn't provide any drawbacks to your approach, as far as I can see. It sounds like the main issue is that you're used to using a library that does this the other way round, and so doing it this way round seems strange to you.

I'm afraid I don't understand what you mean by

99.9% of all models leave this field blank

They can't leave it blank unless you allow them to by setting null=True, blank=True etc.

Body:
I am trying to figure out how to define a one-to-many relationship between two models. The difficulty here is that I do not want to touch one of the models and therefore can not use the usual ForeignKey (Many-to-one).

There are many question on this topic but they all either talk about how to do the lookup (reverse ForeignKey lookup) or they suggest to just add a Foreign Key to one side.
Here is a similar question. I will use the same code example.
This is what I am looking for:

class Dude(models.Model):
    numbers = models.OneToManyField('PhoneNumber')

class PhoneNumber(models.Model):
    number = models.CharField()

Usually I would go ahead and just add a Foreign Key to PhoneNumber as suggested in many answers:

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude, related_name='numbers')

But in my situation I would like to not touch the PhoneNumber model and therefore define something on the Dude model.

The reason for this is that I am defining a model describing a special circumstance which is rarely used. If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all instances leave this field blank. I do not really like the idea to have a field which is always blank - maybe this is my problem.

A possible work-around is to define a many-to-many field and then add some logic actually preventing 'many' on one side and enforcing that the other side is not empty.

I hope I could describe my problem clearly.

Question:
Is there some way to define a one-to-many relationship? Is there a better solution with a different approach for my problem?

P.S. The only hit on this I get from the django docs is a field attribute one_to_many which, I am guessing, is used for the lookup.


问:
403 access forbidden error when access custom url or special character at the end of page
I am creating a website and my client doing audit of website for security purpose. The error is 403 access forbidden error. When i try to use below url then error shows:

```<code> http://localhost/cis_s3/welcome.php::
</code>```

I am trying to do by htaccess. But it didn't access the htaccess. How to remove 404 access forbidden error when user try to access "::" at the end of URL. Currently i am using xampp on localhost. Please help us.

答:
remove the ::
 on the browser just type localhost/cis_s3/welcome.php in the url

Body:
I am creating a website and my client doing audit of website for security purpose. The error is 403 access forbidden error. When i try to use below url then error shows:

 http://localhost/cis_s3/welcome.php::

I am trying to do by htaccess. But it didn't access the htaccess. How to remove 404 access forbidden error when user try to access "::" at the end of URL. Currently i am using xampp on localhost. Please help us.


问:
Node OracleDB Error: The specified procedure could not be found
Error when using OracleDB with Error "The specified procedure could not be found".Node Install OracleDB went through fine.
Steps executed for build are

Installed Visual Studio 2017 Visual C++ 14.0

Downloaded and followed oracle instant client and sdk, OCI_BIN and OCI_INC added

npm install npm@latest

npm install node-gyp -g ( before this step removed c:\users\.node-gyp

npm install oracledb

OCI_INC_DIR Points to 'C:\Oracle\instantclient\lib\msvc'

OCI_LIB_DIR
Points to 'C:\Oracle\instantclient\include' npm done was for
oracledb@1.13.1

Error when running the code with node app.js
/app.js contents

```<code>var oracle = require("oracledb");
console.log(oracle)

Windows 8.1 x64 64 Bit OS
gyp info using node-gyp@3.6.2
gyp info using node@6.3.1 | win32 | x64
6.3.1
node 6.3.1
npm 5.3.0

D:\test\node_modules\oracledb\lib\oracledb.js:38
    throw err;
    ^
Error: The specified procedure could not be found.
\\?\D:\test\node_modules\oracledb\build\Release\oracledb.node
    at Error (native)
    at Object.Module._extensions..node (module.js:568:18)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> D:\test\\node_modules\oracledb\lib\oracledb
.js:35:19)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
```
```

The same error when using strongloop /loopback CLI.
Any pointers would be helpful

答:
I hit the same problem.
This error is related with oracle client.

Possible troubles:

Wrong PATH env. variable

Wrong OCI_INC_DIR and OCI_LIB_DIR paths

Wrong version of oracle client (32-bit vs 64-bit). Version must be the same as node version

My problem was the version of the oracle client, so i installed another one. I also fixed PATH variable and OCI_INC_DIR & OCI_LIB_DIR paths to the new oracle client, but still no success.

The problem went away after I deleted both oracle clients, and installed only the one I needed.

Conclusion: Even though you specify the paths to the correct oracle driver, the installer can pick the other one, so be careful.

Body:
Error when using OracleDB with Error "The specified procedure could not be found".Node Install OracleDB went through fine.
Steps executed for build are

Installed Visual Studio 2017 Visual C++ 14.0

Downloaded and followed oracle instant client and sdk, OCI_BIN and OCI_INC added

npm install npm@latest

npm install node-gyp -g ( before this step removed c:\users\.node-gyp

npm install oracledb

OCI_INC_DIR Points to 'C:\Oracle\instantclient\lib\msvc'

OCI_LIB_DIR
Points to 'C:\Oracle\instantclient\include' npm done was for
oracledb@1.13.1

Error when running the code with node app.js
/app.js contents

var oracle = require("oracledb");
console.log(oracle)

Windows 8.1 x64 64 Bit OS
gyp info using node-gyp@3.6.2
gyp info using node@6.3.1 | win32 | x64
6.3.1
node 6.3.1
npm 5.3.0

D:\test\node_modules\oracledb\lib\oracledb.js:38
    throw err;
    ^
Error: The specified procedure could not be found.
\\?\D:\test\node_modules\oracledb\build\Release\oracledb.node
    at Error (native)
    at Object.Module._extensions..node (module.js:568:18)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> D:\test\\node_modules\oracledb\lib\oracledb
.js:35:19)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
```

The same error when using strongloop /loopback CLI.
Any pointers would be helpful


问:
How can i print %d in c
I want to print like %d in C but it's showing some number.

答: printf("%%d"), or just fputs("%d", stdout).

ContentLicense: CC BY-SA 2.5

Title: How can i print %d in c


问:
PRNG MTRand mt.seed() not working as intended (?)
In a simulation project where I need different PRNG with common random numbers (reproducability) I am using the Mersenne Twister implementation by Jasper Bedaux (http://www.bedaux.net/mtrand/). Now, the following loop should, in my understanding, produce a unique random number associated to the integer (i.e. the different instances should yield the same random numbers if initialised with the same seed):

```<code>#include <iostream>
#include "mtrand.cpp"

int main()
{
  MTRand tester_sh;
  MTRand tester_se;
  std::cout << std::fixed;
  std::cout << "This is a simple test program.\n";
  for (int sh = 1; sh < 3; sh++) {
    for (int se = 1; se < 3; se++) {
      tester_sh.seed( sh );
      tester_se.seed( se );
      std::cout << "\n" << sh << "\t" << tester_sh() << "\t" << se << "\t" << tester_se() ;
    }
  }
  return 0;
}
</code>```

The output I do get, however is:

Neither are the random numbers the same, nor does the "resetting" work for the individual generator. [edit: there is a pattern, of course, but I do not understand it / it is not as it should be]

As I am not a programmer, I am more than puzzled and do not know what I should do.

If important, I am compiling the model with cygwin64\bin\x86_64-w64-mingw32-g++.exe and the options -g  -Wall  -lm -std=gnu++14 -o %Name%.exe %Name%%Ext%, using a current version of cygwin on windows 7, 64bit.

Any help is welcome!

答:
Indeed the Mersenne Twister state vector is static in this port, as it is in many implementations, including the original implementation at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html.

This is not for "some weird reason" and whether it is a "really bad decision" is up for discussion.

In the C++ standard implementation it is not static. The drawback of this is that it is quite easy to (accidentally) create multiple state vectors if you e.g. construct a new MT engine in some class. Every time a new MT engine is constructed, a new state vector is initialized and seeded. Probably most programmers will not realize this and may forget to properly seed each new instance, which may lead to problems with the quality of the pseudo random numbers depending on the implementation of the default seed (chance of repeating sequences), see e.g. http://www.pcg-random.org/posts/cpp-seeding-surprises.html.
In normal circumstances you should only use one generator engine, but the problem is programmers might not realize this.
Taking the next number from one properly seeded and used MT state vector will probably always be better then initialize and seed a separate state vector (which is also expensive). That is the reason for choosing one static (centralized) state vector: protecting users from accidentally creating multiple state vectors.
I agree however that this is not a good solution and is confusing when you are trying by purpose to create two separate state vectors, which is by the way only useful in very specific cases, like studying the behavior of the engine. When you are only looking for good quality random numbers it is probably only harmful to use more than 1 state vector.

Which solution is best depends on what you are trying to accomplish and how well programmers understand the implementation of the RNG.

Anyway, the lines

```<code>tester_sh.seed( sh );
tester_se.seed( se );
</code>```

in the example are with this implementation equivalent to

```<code>tester_se.seed( se );
</code>```

Edit: as geza and Sebastian point out in the comments below, the way the class is designed is not a good choice because it does not reflect the internal working.

Body:
In a simulation project where I need different PRNG with common random numbers (reproducability) I am using the Mersenne Twister implementation by Jasper Bedaux (http://www.bedaux.net/mtrand/). Now, the following loop should, in my understanding, produce a unique random number associated to the integer (i.e. the different instances should yield the same random numbers if initialised with the same seed):

#include <iostream>
#include "mtrand.cpp"

int main()
{
  MTRand tester_sh;
  MTRand tester_se;
  std::cout << std::fixed;
  std::cout << "This is a simple test program.\n";
  for (int sh = 1; sh < 3; sh++) {
    for (int se = 1; se < 3; se++) {
      tester_sh.seed( sh );
      tester_se.seed( se );
      std::cout << "\n" << sh << "\t" << tester_sh() << "\t" << se << "\t" << tester_se() ;
    }
  }
  return 0;
}

The output I do get, however is:

Neither are the random numbers the same, nor does the "resetting" work for the individual generator. [edit: there is a pattern, of course, but I do not understand it / it is not as it should be]

As I am not a programmer, I am more than puzzled and do not know what I should do.

If important, I am compiling the model with cygwin64\bin\x86_64-w64-mingw32-g++.exe and the options -g  -Wall  -lm -std=gnu++14 -o %Name%.exe %Name%%Ext%, using a current version of cygwin on windows 7, 64bit.

Any help is welcome!

Body:
Indeed the Mersenne Twister state vector is static in this port, as it is in many implementations, including the original implementation at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html.

This is not for "some weird reason" and whether it is a "really bad decision" is up for discussion.

In the C++ standard implementation it is not static. The drawback of this is that it is quite easy to (accidentally) create multiple state vectors if you e.g. construct a new MT engine in some class. Every time a new MT engine is constructed, a new state vector is initialized and seeded. Probably most programmers will not realize this and may forget to properly seed each new instance, which may lead to problems with the quality of the pseudo random numbers depending on the implementation of the default seed (chance of repeating sequences), see e.g. http://www.pcg-random.org/posts/cpp-seeding-surprises.html.
In normal circumstances you should only use one generator engine, but the problem is programmers might not realize this.
Taking the next number from one properly seeded and used MT state vector will probably always be better then initialize and seed a separate state vector (which is also expensive). That is the reason for choosing one static (centralized) state vector: protecting users from accidentally creating multiple state vectors.
I agree however that this is not a good solution and is confusing when you are trying by purpose to create two separate state vectors, which is by the way only useful in very specific cases, like studying the behavior of the engine. When you are only looking for good quality random numbers it is probably only harmful to use more than 1 state vector.

Which solution is best depends on what you are trying to accomplish and how well programmers understand the implementation of the RNG.

Anyway, the lines

tester_sh.seed( sh );
tester_se.seed( se );

in the example are with this implementation equivalent to

tester_se.seed( se );

Edit: as geza and Sebastian point out in the comments below, the way the class is designed is not a good choice because it does not reflect the internal working.


问:
FirebaseListAdapter<> Not Working
I am following this tutorial to create a chat app. This is my displayChatMessages() method:

ListView listOfMessages = (ListView)findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessages>(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessages model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView)v.findViewById(R.id.message_text);
            TextView messageTime = (TextView)v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageBody());
            // Format the date before showing it
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);
```

<p>But I get a red underline at this part: </p>

<pre class="lang-java prettyprint-override"><code>(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference())
</code>```

Android Studio says

Firebaselistadapter() in Firebaselistadapter cannot be applied to...

UPDATE: This is the error message:

Error:(76, 19) error: constructor FirebaseListAdapter in class FirebaseListAdapter cannot be applied to given types;
  required: FirebaseListOptions
  found: MainActivity,Class,int,DatabaseReference
  reason: actual and formal argument lists differ in length
  where T is a type-variable:
  T extends Object declared in class FirebaseListAdapter

答:
As the error says, you need FirebaseListOptions, please use this:

```<code>Query query=FirebaseDatabase.getInstance().getReference().orderByChild("name").equalTo(name);
FirebaseListOptions<ChatMessages> options = new FirebaseListOptions.Builder<ChatMessages>()
    .setQuery(query, ChatMessages.class)
    .build();

FirebaseListAdapter<ChatMessages> adapter = new FirebaseListAdapter<ChatMessages>(options) {
@Override
protected void populateView(View v, ChatMessages model, int position) {
    //code here

 }
};
</code>```

Title: FirebaseListAdapter<> Not Working

Body:
I am following this tutorial to create a chat app. This is my displayChatMessages() method:

ListView listOfMessages = (ListView)findViewById(R.id.list_of_messages);

    adapter = new FirebaseListAdapter<ChatMessages>(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference()) {
        @Override
        protected void populateView(View v, ChatMessages model, int position) {
            // Get references to the views of message.xml
            TextView messageText = (TextView)v.findViewById(R.id.message_text);
            TextView messageTime = (TextView)v.findViewById(R.id.message_time);

            // Set their text
            messageText.setText(model.getMessageBody());
            // Format the date before showing it
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
        }
    };

    listOfMessages.setAdapter(adapter);

But I get a red underline at this part:

(this, ChatMessages.class, R.layout.message, FirebaseDatabase.getInstance().getReference())

Android Studio says

Firebaselistadapter() in Firebaselistadapter cannot be applied to...

UPDATE: This is the error message:

Error:(76, 19) error: constructor FirebaseListAdapter in class FirebaseListAdapter cannot be applied to given types;
  required: FirebaseListOptions
  found: MainActivity,Class,int,DatabaseReference
  reason: actual and formal argument lists differ in length
  where T is a type-variable:
  T extends Object declared in class FirebaseListAdapter

Body:
As the error says, you need FirebaseListOptions, please use this:

Query query=FirebaseDatabase.getInstance().getReference().orderByChild("name").equalTo(name);
FirebaseListOptions<ChatMessages> options = new FirebaseListOptions.Builder<ChatMessages>()
    .setQuery(query, ChatMessages.class)
    .build();

FirebaseListAdapter<ChatMessages> adapter = new FirebaseListAdapter<ChatMessages>(options) {
@Override
protected void populateView(View v, ChatMessages model, int position) {
    //code here

 }
};


问:
Asp.net web page not prompting for login credentials
I am writing an application using Asp.net web API. I use OpenId for login. Login page(has a button "login") is displayed every time I logout. when the login button is clicked, it logs in using OpenId by providing credentials. when I logout and try login again, the credentials are not asked, but logged in directly.
I want the credentials to be asked every time I login.

Thanks in advance.

答:
This is a browser feature to prevent your login credentials potentially being stolen by keyloggers. When you've logged in, it saves your credentials so that you don't have to re-type them again whenever you return at a later date.

I use Chrome, but you can find the same shortcuts to whatever browser you use too. Here are some options:

Press Ctrl+Shift+N to open Incognito mode and try this again - it should ask for credentials

Open your browsers settings page and tell it to forget all password / login form data

Open another browser (like Firefox or Edge) and test this with cookies / cache disabled

Upon logging in again, the browser may ask if you want to "Save" those credentials for that website. Simply select "Never" and it won't ask you again. You will always be prompted for your username / password combination


问:
how to rotate a "triangle down" to a "triangle up" using css and jquery
i have the following triangle

created by the following css:

```<code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
</code>```

html:

```<code><div class=triangle></div>
</code>```

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

```<code>.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}
</code>```

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

答:
You can use toggleClass() and transform to rotate the arrow

$(".triangle").click(function() {
  $(this).toggleClass("triangle-up");

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.triangle {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 50px solid transparent;
  border-top: 80px solid red;
  transition: all .5s;
}

.triangle-up {
 transform:rotateX(180deg);
 margin-top:-50px;
}</code>```

```

Body:
i have the following triangle

created by the following css:

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

html:

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

Body:
You can use toggleClass() and transform to rotate the arrow

$(".triangle").click(function() {
  $(this).toggleClass("triangle-up");

})

.triangle {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 50px solid transparent;
  border-top: 80px solid red;
  transition: all .5s;
}

.triangle-up {
 transform:rotateX(180deg);
 margin-top:-50px;
}

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


问:
ajax textbox value no response auto suggestion
I'm trying to create an auto-suggestion AJAX box but there is no response from the server.

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>

    <?php
        include 'search.php';
    ?>

    <script>
    $(document).ready(function() {
      $("#textbox1").keyup(function() {
        $.ajax({
            type: "GET",
            url: "search.php",
            data: {textbox1: $(this).val()},
            success: function (data) {
                  $("#main").html(data);
            }
        });
      });
    });
    </script>

    <form method="POST">
              enter keyword to search<br>
              <input type="text" name="textbox1" id="textbox1">
              <br><br>
              <div id="main"></div>
    </form>

</head>
<body>
</code>```

this is search.php

```<code><?php

    include 'connection.php';

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        $search_value = $_POST['textbox1'];
        $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
        $conn_status = mysqli_query($conn, $query);

        while($row = $conn_status->fetch_assoc())
        {
            echo $row['username'] . '<br>';
        }
    }

?>
</code>```

答:
You Missed Following

Ajax Request is Get And you use POST request in PHP

Second is not matter but it is good practice if you define action in

Change Code As follow

```<code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>

    <?php
        include 'search.php';
    ?>

    <script>
    $(document).ready(function() {
      $("#textbox1").keyup(function() {
        $.ajax({
            type: "POST",
            url: "search.php",
            data: {textbox1: $(this).val()},
            success: function (data) {
                  $("#main").html(data);
            }
        });
      });
    });
    </script>

    <form method="POST" action="">
              enter keyword to search<br>
              <input type="text" name="textbox1" id="textbox1">
              <br><br>
              <div id="main"></div>
    </form>

</head>
<body>
</code>```

Body:
I'm trying to create an auto-suggestion AJAX box but there is no response from the server.

<!DOCTYPE html>

<title></title>

    <?php
        include 'search.php';
    ?>

    <form method="POST">
              enter keyword to search

              <input type="text" name="textbox1" id="textbox1">

    </form>

this is search.php

<?php

    include 'connection.php';

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        $search_value = $_POST['textbox1'];
        $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
        $conn_status = mysqli_query($conn, $query);

        while($row = $conn_status->fetch_assoc())
        {
            echo $row['username'] . '
';
        }
    }

?>

Body:
You Missed Following

Ajax Request is Get And you use POST request in PHP

Second is not matter but it is good practice if you define action in

Change Code As follow

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>

    <?php
        include 'search.php';
    ?>

    <script>
    $(document).ready(function() {
      $("#textbox1").keyup(function() {
        $.ajax({
            type: "POST",
            url: "search.php",
            data: {textbox1: $(this).val()},
            success: function (data) {
                  $("#main").html(data);
            }
        });
      });
    });
    </script>

    <form method="POST" action="">
              enter keyword to search<br>
              <input type="text" name="textbox1" id="textbox1">
              <br><br>
              <div id="main"></div>
    </form>

</head>
<body>


问:
Persist multiple states using LocalStorage in Redux
I need to persist multiple states in Redux store using LocalStorage. I already have working one key in my case it is drivers. also need to do with buses and carriers states.

Store.js

```<code>import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import Reducers from './reducers';
import { loadState, saveState } from '../../utils/localstorage';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// LOCAL STORAGE FOR DRIVERS, BUSES, CARRIERS

const persistedState = loadState()

const store = createStore(
  Reducers,
  persistedState,
  composeEnhancers(
    applyMiddleware(
      ReduxThunk
    )
  )
);

store.subscribe(() => {
  saveState({
    drivers: store.getState().drivers
  });
});

export default store;
</code>```

localstorage.js

```<code>export const loadState = () => {
  try {

    const serializedDriversState = localStorage.getItem('drivers')

    if (serializedDriversState === null) {
      return undefined;
    }
    return JSON.parse(serializedDriversState);
  } catch (err) {
    return undefined;
  }
};

export const saveState = (drivers) => {
  try {
    const serializedDriversState = JSON.stringify(drivers);
    localStorage.setItem('drivers', serializedDriversState)
  } catch (err) {
    // Ignore errors.
  }
}
</code>```

I'm using Dan Abramov's example: Redux LocalStorage.

So how to store multiple states using LocalStorage in Redux store? Is it good approach or use some middleware like redux-persist?

答:
I think, you should add forEach over state in store.subscribe function and you can save the whole store partly.</p>

```<code>export const saveState = (key, data) => {
  try {
    const serialized = JSON.stringify(data);
    localStorage.setItem(key, serialized);
  } catch (err) {
    // Ignore errors.
  }
}

store.subscribe(() => {
    const state = store.getState();
    Object.keys(state).forEach( key => {
      saveState(key, state[key])
    })
});
</code>```

Body:
I need to persist multiple states in Redux store using LocalStorage. I already have working one key in my case it is drivers. also need to do with buses and carriers states.

Store.js

import ReduxThunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import Reducers from './reducers';
import { loadState, saveState } from '../../utils/localstorage';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// LOCAL STORAGE FOR DRIVERS, BUSES, CARRIERS

const persistedState = loadState()

const store = createStore(
  Reducers,
  persistedState,
  composeEnhancers(
    applyMiddleware(
      ReduxThunk
    )
  )
);

store.subscribe(() => {
  saveState({
    drivers: store.getState().drivers
  });
});

export default store;

localstorage.js

export const loadState = () => {
  try {

    const serializedDriversState = localStorage.getItem('drivers')

    if (serializedDriversState === null) {
      return undefined;
    }
    return JSON.parse(serializedDriversState);
  } catch (err) {
    return undefined;
  }
};

export const saveState = (drivers) => {
  try {
    const serializedDriversState = JSON.stringify(drivers);
    localStorage.setItem('drivers', serializedDriversState)
  } catch (err) {
    // Ignore errors.
  }
}

I'm using Dan Abramov's example: Redux LocalStorage.

So how to store multiple states using LocalStorage in Redux store? Is it good approach or use some middleware like redux-persist?

Body:
I think, you should add forEach over state in store.subscribe function and you can save the whole store partly.

export const saveState = (key, data) => {
  try {
    const serialized = JSON.stringify(data);
    localStorage.setItem(key, serialized);
  } catch (err) {
    // Ignore errors.
  }
}

store.subscribe(() => {
    const state = store.getState();
    Object.keys(state).forEach( key => {
      saveState(key, state[key])
    })
});


问:
glob() expects parameter 1 to be a valid path
I am trying to retrieve a directory saved from database and open all the images inside that directory. The problem is, when I run the code, the result is "Warning: glob() expects parameter 1 to be a valid path, object given in C:\xampp\htdocs\try\test.php on line 5". BTW I'm just starting php and I'm not yet knowledgeable enough on it. Any help will be appreciated. Thanks.

Here is my code in test.php

```<code><?php
require_once 'config.php';
$path = 'SELECT directory FROM path WHERE id = 1';

$files = glob($link, $path);
for ($i=0; $i<count($files); $i++)
{
    $num = $files[$i];
    echo '<a href="'.$num.'"><img src="'.$num.'" alt="random image" style="width:300px;height:200px;"></a>'."  ";
}
?>
</code>```

And this is the config.php

```<code><?php
session_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'sam');

$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
?>
</code>```

答:
It looks like you're misunderstanding the purpose of glob() and how to execute MySQL queries using PHP.

glob() doesn't execute MySQL queries. glob() checks the files in the current directory. Check the link here, http://php.net/manual/en/function.glob.php.

What you need to do is research how to execute MySQL statements and parse the returned values.

Check out this question, it explains how to use PDO to execute MySQL queries: PDO MYSQL PHP prepare() and execute().

And this explains how to retrieve values after executing a PDO query: return one value from database with mysql php pdo.

Body:
I am trying to retrieve a directory saved from database and open all the images inside that directory. The problem is, when I run the code, the result is "Warning: glob() expects parameter 1 to be a valid path, object given in C:\xampp\htdocs\try\test.php on line 5". BTW I'm just starting php and I'm not yet knowledgeable enough on it. Any help will be appreciated. Thanks.

Here is my code in test.php

<?php
require_once 'config.php';
$path = 'SELECT directory FROM path WHERE id = 1';

$files = glob($link, $path);
for ($i=0; $i<count($files); $i++)
{
    $num = $files[$i];
    echo ''."  ";
}
?>

And this is the config.php

<?php
session_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'sam');

$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
?>


问:
AngularJS multi select checkboxes saves in comma separated String
I want to get comma separated string from selected check-box items in angularJS.  At the same time, when comma separated string is retrived from database, I want check-boxes to be checked accordingly.

```<code><div class="col-md-5">
    <input type="checkbox" ng-model="Drawings.CarMDrawings" ng-change="Update(Drawings)"> Car
    <br />

    <input type="checkbox" ng-model="Drawings.SignalMDrawings" ng-change="Update(Drawings)"> Signal
    <br />

    <input type="checkbox" ng-model="Drawings.DoorMDawings" ng-change="Update(Drawings)"> Door
    <br />

  </div>
</code>```

I have solved the problem in very simplistic way is Plunker http://plnkr.co/edit/YYd5bN5Chmyjt6gSH1Bw?p=preview

```<code> $scope.Update = function(Drawings) {
    var str = "";
    if (Drawings.CarMDrawings) {
      str = "Car";
    }
    if (Drawings.SignalMDrawings) {
      str = str + ",Signal";
    }
    if (Drawings.DoorMDawings) {
      str = str + ",Door";
    }
    if (str.charAt(0) === ',') {
      str = str.substr(1);
    }
    $scope.data = str;
  }

  $scope.revUpdate = function(data) {
    var str = data;
    $scope.Drawings = {};
    if (str.indexOf('Car') != -1) {

      $scope.Drawings.CarMDrawings = true;
    }
    if (str.indexOf('Signal') != -1) {

      $scope.Drawings.SignalMDrawings = true;
    }
    if (str.indexOf('Door') != -1) {

      $scope.Drawings.DoorMDawings = true;
    }
</code>```

}

But it is not helpful when I have many similar items. Could any one help me building a directive or extension so that I could reuse them frequently.
P.S. I don't want array of objects but simple comma separated string items.

答:
If you use 'indexOf', you'll get many garbage items those include text what you want to find.

So I think this is the most nearest way to get more precise value.

```<code>if (new RegExp("\\b"+"Car"+"\\b").test(str)) {
    $scope.Drawings.CarMDrawings = true;
}

var str="test ,Car ,test";  //true
var str="test, Car, test";  //true
var str="test Cartest";     //false
var str="testCar test";     //false
</code>```

Maybe this is very late answer but I hope this is right for your intent,

and helpful for other people who'll look this. :)

Body:
I want to get comma separated string from selected check-box items in angularJS.  At the same time, when comma separated string is retrived from database, I want check-boxes to be checked accordingly.

    <input type="checkbox" ng-model="Drawings.CarMDrawings" ng-change="Update(Drawings)"> Car

    <input type="checkbox" ng-model="Drawings.SignalMDrawings" ng-change="Update(Drawings)"> Signal

    <input type="checkbox" ng-model="Drawings.DoorMDawings" ng-change="Update(Drawings)"> Door

I have solved the problem in very simplistic way is Plunker http://plnkr.co/edit/YYd5bN5Chmyjt6gSH1Bw?p=preview

 $scope.Update = function(Drawings) {
    var str = "";
    if (Drawings.CarMDrawings) {
      str = "Car";
    }
    if (Drawings.SignalMDrawings) {
      str = str + ",Signal";
    }
    if (Drawings.DoorMDawings) {
      str = str + ",Door";
    }
    if (str.charAt(0) === ',') {
      str = str.substr(1);
    }
    $scope.data = str;
  }

  $scope.revUpdate = function(data) {
    var str = data;
    $scope.Drawings = {};
    if (str.indexOf('Car') != -1) {

      $scope.Drawings.CarMDrawings = true;
    }
    if (str.indexOf('Signal') != -1) {

      $scope.Drawings.SignalMDrawings = true;
    }
    if (str.indexOf('Door') != -1) {

      $scope.Drawings.DoorMDawings = true;
    }

}

But it is not helpful when I have many similar items. Could any one help me building a directive or extension so that I could reuse them frequently.
P.S. I don't want array of objects but simple comma separated string items.

Body:
If you use 'indexOf', you'll get many garbage items those include text what you want to find.

So I think this is the most nearest way to get more precise value.

if (new RegExp("\\b"+"Car"+"\\b").test(str)) {
    $scope.Drawings.CarMDrawings = true;
}

var str="test ,Car ,test";  //true
var str="test, Car, test";  //true
var str="test Cartest";     //false
var str="testCar test";     //false

Maybe this is very late answer but I hope this is right for your intent,

and helpful for other people who'll look this. :)


问:
Xamarin.Forms - InitializeComponent doesn't exist when creating a new page
I'm using Visual Studio to try out Xamarin.Forms. I'm trying to follow the guide:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/xaml-for-xamarin-forms/getting_started_with_xaml/

In short, I create a Xamarin.Forms solution using a PCL and then try to add a Forms XAML Page to the PCL-project.

The code-behind that gets created looks like this:

    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();
        }
    }
```

<p>The problem here is that <code>InitializeComponent();</code> is red.
When I try to build I get informed that <code>The name 'InitializeComponent' does not exist in the current context</code>  </p>

<p>I've been looking around for solutions and even though others have had the same trouble, their solutions wont work for me. Here is one suggestion i tried to use:
http://blog.falafel.com/xamarin-error-initializecomponent-does-not-exist-in-the-current-context/</p>

<p>Please let me know if you have a solution for this problem. Thanks!</p>

<p>Update:</p>

<p>My PCL (which is where I also want to add my XAML-page) contains:</p>

<p>App.cs:</p>

<pre class="lang-cs prettyprint-override"><code>    public class App : Application
    {
        public App()
        {
            // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        new Label {
                            XAlign = TextAlignment.Center,
                            Text = "Welcome to Xamarin Forms!"
                        }
                    }
                }
            };
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
</code>```

And my XAML-page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamaTest.MyXamlPage">

</ContentPage>
```

<p>Code-behind:</p>

 <pre class="lang-cs prettyprint-override"><code>    public partial class MyXamlPage : ContentPage
    {
        public MyXamlPage()
        {
            InitializeComponent();
        }
    }
</code>```

答:
add using Xamarin.Forms.Xaml

tested on Visual Studio 2017

Body:
I'm using Visual Studio to try out Xamarin.Forms. I'm trying to follow the guide:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/xaml-for-xamarin-forms/getting_started_with_xaml/

In short, I create a Xamarin.Forms solution using a PCL and then try to add a Forms XAML Page to the PCL-project.

The code-behind that gets created looks like this:

    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent();
        }
    }

The problem here is that InitializeComponent(); is red.
When I try to build I get informed that The name 'InitializeComponent' does not exist in the current context

I've been looking around for solutions and even though others have had the same trouble, their solutions wont work for me. Here is one suggestion i tried to use:
http://blog.falafel.com/xamarin-error-initializecomponent-does-not-exist-in-the-current-context/

Please let me know if you have a solution for this problem. Thanks!

Update:

My PCL (which is where I also want to add my XAML-page) contains:

App.cs:

    public class App : Application
    {
        public App()
        {
            // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        new Label {
                            XAlign = TextAlignment.Center,
                            Text = "Welcome to Xamarin Forms!"
                        }
                    }
                }
            };
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }

And my XAML-page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamaTest.MyXamlPage">

</ContentPage>

Code-behind:

    public partial class MyXamlPage : ContentPage
    {
        public MyXamlPage()
        {
            InitializeComponent();
        }
    }


问:
List of invalid symbols for password or any string inputs (for c# and mssql)
Client wants us to allow all possible symbols for password inputs but what I know is that there are some characters that can ruin a code like

"double quotation (")" for c# coding

```<code>string name = "jose" jose"
</code>```

"single quotation (')" for mssql

```<code>DECLARE @name VARCHAR(50) = 'jose' jose'
</code>```

"ampersand (&)" and "vertical line for or (|)" possible for sql injection in mssql

and "backslash (\)" like this sample that it is used for character escape. (it is actually double slash to show)

Is there any symbols am I missing or I made a wrong idea with the symbols declared?

答:
No symbol is harmful when you store passwords correctly.

There are only 2 rules for that:

Always use parameters when passing data to the database.

This is the only effective way to prevent SQL Injection attacks.

Never store plain text passwords in your database.

Instead, store a salted hash value representing the password.

You can read this SO post on how to hash passwords,
and some more information on Microsoft Docs.

Edit:
Just found quite a long article on CodeProject that explains in details why and how to hash passwords.

Body:
Client wants us to allow all possible symbols for password inputs but what I know is that there are some characters that can ruin a code like

"double quotation (")" for c# coding

string name = "jose" jose"

"single quotation (')" for mssql

DECLARE @name VARCHAR(50) = 'jose' jose'

"ampersand (&)" and "vertical line for or (|)" possible for sql injection in mssql

and "backslash (\)" like this sample that it is used for character escape. (it is actually double slash to show)

Is there any symbols am I missing or I made a wrong idea with the symbols declared?


问:
Difference between HashMap, LinkedHashMap and TreeMap
What is the difference between HashMap, LinkedHashMap and TreeMap in Java?
I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

```<code>Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());

SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());

LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());
</code>```

答:
Following are major difference between HashMap and TreeMap

HashMap does not maintain any order. In other words , HashMap does not provide any guarantee that the element inserted first will be printed first, where as Just like TreeSet , TreeMap  elements are also sorted according to the natural ordering of its elements

Internal HashMap implementation use Hashing and TreeMap internally uses Red-Black tree implementation.

HashMap can store one null key and many  null values.TreeMap can not contain null keys but may contain many null values.

HashMap  take constant time performance for the basic operations like get and put i.e O(1).According to Oracle docs , TreeMap provides guaranteed log(n) time cost for the get and put method.

HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.

HashMap uses equals() method in comparison while TreeMap uses compareTo() method for maintaining ordering.

HashMap implements Map interface while TreeMap implements NavigableMap interface.

Body:
What is the difference between HashMap, LinkedHashMap and TreeMap in Java?
I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());

SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());

LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());


问:
Mysql : dump database along data
I want to dump my database along the table schema and the table data also using the unix command line .

I used .

```<code>mysqldump -d -u root  -p frontend > frontend.sql
</code>```

But above command is dumping only schema not the data from the database .

Please help me out how can i dump the database along the data also.

答: You just need to remove -d from your mysqldump command

Title: Mysql : dump database along data

Body:
I want to dump my database along the table schema and the table data also using the unix command line .

I used .

mysqldump -d -u root  -p frontend > frontend.sql

But above command is dumping only schema not the data from the database .

Please help me out how can i dump the database along the data also.


答:
for C# code you will need to add \ before each double quotation

```<code>string name = "jose\" jose"
</code>```

for SQL server you will need to add an extra quote:

```<code>DECLARE @name VARCHAR(50) = 'jose'' jose'
</code>```

Title: List of invalid symbols for password or any string inputs (for c# and mssql)

Body:
for C# code you will need to add \ before each double quotation

string name = "jose\" jose"

for SQL server you will need to add an extra quote:

DECLARE @name VARCHAR(50) = 'jose'' jose'


问:
Redux Action js file
i have a code that looks something like this in the redux action

```<code>fetchAction (route) => {
   return {
     action1: {}
   }[route]
}
</code>```

if route = "action1" it does return me back the whole object of action1
how does that [route] help to get back the object ?

Thank you.

答:
Understand it like this</p>

```<code>fetchAction (route) => {
   return {
     action1: {}
   }[route]
}

fetchAction (route) => {
   var obj = {
     action: {}
   }
   return obj[route]
}

fetchAction (route) => {
   var obj = {
     action: {}
   }
   var returnObj = obj[route]
   return returnObj;
}
</code>```

Title: Redux Action js file

Body:
i have a code that looks something like this in the redux action

fetchAction (route) => {
   return {
     action1: {}
   }[route]
}

if route = "action1" it does return me back the whole object of action1
how does that [route] help to get back the object ?

Thank you.

Body:
Understand it like this

fetchAction (route) => {
   return {
     action1: {}
   }[route]
}

fetchAction (route) => {
   var obj = {
     action: {}
   }
   return obj[route]
}

fetchAction (route) => {
   var obj = {
     action: {}
   }
   var returnObj = obj[route]
   return returnObj;
}


问:
How do you load a module @everywhere inside a function in Julia
I am trying to load a module in my workers after creating them with addprocs. When addprocs is called at the top level, everything is fine. However, I am not able to do the same thing when I wrap the code in a function.

In my case, I am adding workers dynamically, so it is not feasible to call @everywhere using XXX always on the top level, I would need to do this inside a function.

In short, this works:

```<code>addprocs(1)
@everywhere using XXX
</code>```

and this doesn't:

```<code>function myaddprocs()
    addprocs(1)
    @everywhere using XXX
end
</code>```

Any ideas?

答:
you don't need @everywhere. this works for me:

```<code>addprocs()
using mymodule  # loads code on all procs but brings in to scope only on master process.
</code>```

this is what you want if you want to then do pmap(x->fun(x),workers()), and fun is exported from mymodule. you can read this up here: https://docs.julialang.org/en/release-0.6/manual/parallel-computing/#Code-Availability-and-Loading-Packages-1

Body:
I am trying to load a module in my workers after creating them with addprocs. When addprocs is called at the top level, everything is fine. However, I am not able to do the same thing when I wrap the code in a function.

In my case, I am adding workers dynamically, so it is not feasible to call @everywhere using XXX always on the top level, I would need to do this inside a function.

In short, this works:

addprocs(1)
@everywhere using XXX

and this doesn't:

function myaddprocs()
    addprocs(1)
    @everywhere using XXX
end

Any ideas?

Body:
you don't need @everywhere. this works for me:

addprocs()
using mymodule  # loads code on all procs but brings in to scope only on master process.

this is what you want if you want to then do pmap(x->fun(x),workers()), and fun is exported from mymodule. you can read this up here: https://docs.julialang.org/en/release-0.6/manual/parallel-computing/#Code-Availability-and-Loading-Packages-1


问:
I have a CSV file with header. Want to remove first 5 row of csv but not header? In Python
I have a below CSV file with the header(A,B,C,D):

```<code>A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6
</code>```

I want output after removing top 5 lines but not header:

```<code>A,B,C,D
1,1,7,3
2,9,5,6
</code>```

Below is my Python code snippet, but am not able to add any header retaining code:

with open(filename.csv , 'rb') as infile:
              data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile:
              outfile.writelines(data_in[5:])

Please help me in this.In my case header is also deleting, but I want to retain header every time.

答:
How about:</p>

```<code>with open ('temp.csv', 'wb') as outfile:
    outfile.writelines(data_in[0])
    outfile.writelines(data_in[5:])
</code>```

Body:
I have a below CSV file with the header(A,B,C,D):

A,B,C,D
1,2,3,4
2,1,3,5
6,8,0,9
4,7,9,2
2,5,4,9
1,1,7,3
2,9,5,6

I want output after removing top 5 lines but not header:

A,B,C,D
1,1,7,3
2,9,5,6

Below is my Python code snippet, but am not able to add any header retaining code:

with open(filename.csv , 'rb') as infile:
              data_in = infile.readlines()

with open ('temp.csv', 'wb') as outfile:
              outfile.writelines(data_in[5:])

Please help me in this.In my case header is also deleting, but I want to retain header every time.

Body:
How about:

with open ('temp.csv', 'wb') as outfile:
    outfile.writelines(data_in[0])
    outfile.writelines(data_in[5:])


问:
R plumber package for node.js parallel processing
I would like to use the plumber package to carry out some flexible parallel processing and was hoping it would work within a node.js framework such that it is non-blocking...

I have the following plumber file.

```<code># myfile.R

#* @get /mean
normalMean <- function(samples=10){
  Sys.sleep(5)
  data <- rnorm(samples)
  mean(data)
}
</code>```

I have also installed pm2 as suggested here http://plumber.trestletech.com/docs/hosting/

I have also made the same run-myfile.sh file i.e.

```<code>#!/bin/bash
R -e "library(plumber); pr <- plumb('myfile.R'); pr\$run(port=4000)"
</code>```

and made it executable as suggested...

I have started up pm2 using

```<code>pm2 start /path/to/run-myfile.sh
</code>```

and wanted to test to see if it could carry out a non-blocking node.js framework...

by opening up another R console and running the following...

```<code>foo <- function(){
    con <- curl::curl('http://localhost:4000/mean?samples=10000',handle = curl::new_handle())
    on.exit(close(con))
    return(readLines(con, n = 1, ok = FALSE, warn = FALSE))
}

system.time(for (i in seq(5)){
    print(foo())
})
</code>```

Perhaps it is my miss-understanding of how a node.js non-blocking framework is meant to work, but in my head the last loop should take only a bit of over 5 seconds. But it seems to take 25 seconds, suggesting everything is sequential rather than parallel.

How could I use the plumber package to carry out that non-blocking nature?

答:
Basically concurrent requests are queued by httpuv so that it is not performant by itself. The author recommends multiple docker containers but it can be complicated as well as response-demanding.

There are other tech eg Rserve and rApache. Rserve forks prosesses and it is possible to configure rApache to pre-fork so as to handle concurrent requests.

See the following posts for comparison

https://www.linkedin.com/pulse/api-development-r-part-i-jaehyeon-kim/
https://www.linkedin.com/pulse/api-development-r-part-ii-jaehyeon-kim/

Body:
I would like to use the plumber package to carry out some flexible parallel processing and was hoping it would work within a node.js framework such that it is non-blocking...

I have the following plumber file.

# myfile.R

#* @get /mean
normalMean <- function(samples=10){
  Sys.sleep(5)
  data <- rnorm(samples)
  mean(data)
}

I have also installed pm2 as suggested here http://plumber.trestletech.com/docs/hosting/

I have also made the same run-myfile.sh file i.e.

#!/bin/bash
R -e "library(plumber); pr <- plumb('myfile.R'); pr\$run(port=4000)"

and made it executable as suggested...

I have started up pm2 using

pm2 start /path/to/run-myfile.sh

and wanted to test to see if it could carry out a non-blocking node.js framework...

by opening up another R console and running the following...

foo <- function(){
    con <- curl::curl('http://localhost:4000/mean?samples=10000',handle = curl::new_handle())
    on.exit(close(con))
    return(readLines(con, n = 1, ok = FALSE, warn = FALSE))
}

system.time(for (i in seq(5)){
    print(foo())
})

Perhaps it is my miss-understanding of how a node.js non-blocking framework is meant to work, but in my head the last loop should take only a bit of over 5 seconds. But it seems to take 25 seconds, suggesting everything is sequential rather than parallel.

How could I use the plumber package to carry out that non-blocking nature?


问:
How can i print %d in c
I want to print like %d in C but it's showing some number.

答:
To get a % you need to have %%.

```<code>printf("%%d");
</code>```

prints

```<code>%d
</code>```

The printf man page says:

```<code>conversion
specifier

   %         A '%' is written.  No argument is converted.  The complete  con‐
             version specification is '%%'.
</code>```

Title: How can i print %d in c

Body:
To get a % you need to have %%.

printf("%%d");

prints

%d

The printf man page says:

conversion
specifier

   %         A '%' is written.  No argument is converted.  The complete  con‐
             version specification is '%%'.


问:
How to update record using Entity Framework 6?
I am trying to update a record using EF6. First finding the record, if it exists, update.
Here is my code:

```<code>var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries

答:
Try It....

UpdateModel(book);

```<code>var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            UpdateModel(book);
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to update a record using EF6. First finding the record, if it exists, update.
Here is my code:

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries

Body:
Try It....

UpdateModel(book);

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            UpdateModel(book);
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}


问:
Speed comparison using multiprocessing.Process versus subprocess.Popen
I am using Python3 to execute PYQT code; and at the same time, I need to call Python2.7 code, for operations that I cannot perform via Python3.

I did implement the 2.7 code execution via Popen; although it takes a considerable amount of time to run the 2.7 code, when called from Popen. The same operation is performed much faster if I run it directly from Python2.7.

Would be possible to use multiprocessing instead of subprocess.Popen for the same purpose, to speed up the execution of the 2.7 code?
And if that is appropriate; what would be the correct way to call Python2.7 code from a multiprocessing.Process? Or is it a waste to use multiprocess, since I am executing only one operation?

答:
multiprocessing is similar to subprocess only on non-POSIX systems that cannot fork processes so you could, theoretically, hack away multiprocessing to use a different interpreter. It would be more trouble than its worth, tho, because at that point you wouldn't get any performance boost between spawning a subprocess and using a multiprocessing.Process (in fact, it would probably end slower due to the communication overhead added to multiprocessing.Process).

So, if we're talking only about a single task that has to execute in a different interpreter, this is as fast as you're gonna get. If there are multiple tasks to be executed in a different interpreter you may still benefit from multiprocessing.Process by spawning a single subprocess to run the different interpreter and then using multiprocessing within it to distribute multiple tasks over your cores.


问:
Emacs with nice page break lines?
Under Emacs, how to get nice page-break-lines like these?

答:
Install the page-break-lines package, then:

```<code>M-x turn-on-page-break-lines-mode
</code>```

To insert a new page break line: C-q C-l

(this inserts a ^L char in your buffer)

You can also easily jump to next/previous page break using C-x [ or C-x ]

Title: Emacs with nice page break lines?

Body:
Install the page-break-lines package, then:

M-x turn-on-page-break-lines-mode

To insert a new page break line: C-q C-l

(this inserts a ^L char in your buffer)

You can also easily jump to next/previous page break using C-x [ or C-x ]


问:
x86 or x64 disassembler lib
I know o some disassemble libs , but what I'm looking for is one that has an api like:

```<code>void * findAddrOfFirstInstructionStartingFrom( void * startAddress , InstructionType instruction);

void* addr = findAddrOfFirstInstructionStartingFrom(startAddress , JMP);
</code>```

and other apis smiler to this one like search for something specific not disassemble all instructions stating from an address and get all sorts of info because it slow if you only want to find something specific not everything.

If you know any pls let me know , if there isn't any pls tell me one that is open source and easy to modify.

答:
I'm not aware of any API that can do this but it can be accomplished using some command line scripting:

```<code>objdump -d --start-address address file | grep -m 1 instruction | cut -d : -f 1
</code>```

So, for example, to find the first JMP instruction starting at address 0x08048664 in the file a.out, you can do this:

```<code>$ objdump -d --start-address 0x08048664 a.out | grep -m 1 jmp | cut -d : -f 1
 8048675
</code>```

Title: x86 or x64 disassembler lib

Body:
I know o some disassemble libs , but what I'm looking for is one that has an api like:

void * findAddrOfFirstInstructionStartingFrom( void * startAddress , InstructionType instruction);

void* addr = findAddrOfFirstInstructionStartingFrom(startAddress , JMP);

and other apis smiler to this one like search for something specific not disassemble all instructions stating from an address and get all sorts of info because it slow if you only want to find something specific not everything.

If you know any pls let me know , if there isn't any pls tell me one that is open source and easy to modify.

Body:
I'm not aware of any API that can do this but it can be accomplished using some command line scripting:

objdump -d --start-address address file | grep -m 1 instruction | cut -d : -f 1

So, for example, to find the first JMP instruction starting at address 0x08048664 in the file a.out, you can do this:

$ objdump -d --start-address 0x08048664 a.out | grep -m 1 jmp | cut -d : -f 1
 8048675


问:
How to take a snapshot in vlc QT?
Hello I have built VLC Qt Library in QT 5.5.1 on Ubuntu.
Now I want to add snapshot feature in it. Is there anyway or any idea?
Please mention. If you have even little bit of idea.</p>

答:
you should use the VlcVideo class in this library.
at first create a new object from this class. then use this function:

bool VlcVideo::takeSnapshot (   const QString &     path    )   const
```

<p>you can find more details about the VlcVideo class from this link:
https://vlc-qt.tano.si/reference/1.1/classVlcVideo.html#a4f3a741285dd9030f76bb996eaa011d4</p>

<p>a very simple code can be like this:</p>

<pre class="lang-c++ prettyprint-override"><code>#include "MayClass.h"
#include "VLCQtCore/Video.h"
void MayClass::initMembers()
{
    _instance = new VlcInstance(VlcCommon::args(), this);
    _player = new VlcMediaPlayer(_instance);
    _video = new VlcVideo(_player);
}
void MayClass::takeSnapShot(QString filename)
{
    _video->takeSnapshot(filename);
}
</code>```

Title: How to take a snapshot in vlc QT?

Body:
you should use the VlcVideo class in this library.
at first create a new object from this class. then use this function:

bool VlcVideo::takeSnapshot (   const QString &     path    )   const

you can find more details about the VlcVideo class from this link:
https://vlc-qt.tano.si/reference/1.1/classVlcVideo.html#a4f3a741285dd9030f76bb996eaa011d4

a very simple code can be like this:

#include "MayClass.h"
#include "VLCQtCore/Video.h"
void MayClass::initMembers()
{
    _instance = new VlcInstance(VlcCommon::args(), this);
    _player = new VlcMediaPlayer(_instance);
    _video = new VlcVideo(_player);
}
void MayClass::takeSnapShot(QString filename)
{
    _video->takeSnapshot(filename);
}


答:
I advise using pandas as it will retain the header and you can perform
  multiple operations on data with ease. A pandas dataframe can represent 2D data in form of columns and rows similar to a csv file.

Load file into pandas dataframe

```<code>df = pd.read_csv('file.csv')
</code>```

Then select the required rows

```<code>df_temp = df.loc[5:]
</code>```

Here is required output

```<code>   A  B  C  D
5  1  1  7  3
6  2  9  5  6
</code>```

you can further write it to a csv file

```<code>df_temp.to_csv('output.csv',index=False)
</code>```

Title: I have a CSV file with header. Want to remove first 5 row of csv but not header? In Python

Body:
I advise using pandas as it will retain the header and you can perform
  multiple operations on data with ease. A pandas dataframe can represent 2D data in form of columns and rows similar to a csv file.

Load file into pandas dataframe

df = pd.read_csv('file.csv')

Then select the required rows

df_temp = df.loc[5:]

Here is required output

   A  B  C  D
5  1  1  7  3
6  2  9  5  6

you can further write it to a csv file

df_temp.to_csv('output.csv',index=False)


问:
Different WPF Storyboard Animation in each ListBox.ItemTemplate>DataTemplate
I want to have different animations for each of a ListView item.

```<code><Window.Resources>
    <Storyboard x:Key="myAnimation" RepeatBehavior="Forever">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Source" Duration="0:0:2">
            <DiscreteObjectKeyFrame KeyTime="0:0:0">
                <DiscreteObjectKeyFrame.Value>
                    <BitmapImage UriSource="/img/image1.png"/>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
            <DiscreteObjectKeyFrame KeyTime="0:0:1">
                <DiscreteObjectKeyFrame.Value>
                    <BitmapImage UriSource="/img/image2.png"/>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>

<ListBox  Name="SessionList" HorizontalContentAlignment="Stretch" >
    <ListBox.ItemTemplate>
        <DataTemplate>
           <Image x:Name="stateimage">
                <Image.Triggers>
                    <EventTrigger RoutedEvent="Loaded">
                        <BeginStoryboard Storyboard="{StaticResource myAnimation}">
                        </BeginStoryboard>
                    </EventTrigger>
                </Image.Triggers>
            </Image>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

The above XAML code works fine for showing the same animation myAnimation for each listitem. But how I can achive it to show different animations (i.e. I have to define several Storyboards in Window.Resources), depending on a Binding Property of the listitem ViewModel?

EDIT:

With the question linked below, I finally got it worked this way. Amazing!

```<code><Window.Resources>
    <Storyboard x:Key="animLOAD" RepeatBehavior="Forever">...</Storyboard>
    <Storyboard x:Key="animPREPARED" RepeatBehavior="Forever">...</Storyboard>
    <Style x:Key="animStyle" TargetType="{x:Type Image}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=st, Mode=OneWay}" Value="LOAD">
                <DataTrigger.EnterActions>
                    <BeginStoryboard Storyboard="{StaticResource animLOAD}" />
                </DataTrigger.EnterActions>
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=st, Mode=OneWay}" Value="PREPARED">
                <DataTrigger.EnterActions>
                    <BeginStoryboard Storyboard="{StaticResource animPREPARED}" />
                </DataTrigger.EnterActions>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Image Style="{StaticResource animStyle}" />
</code>```

答:
I'm not sure how accessible your model is for this approach but you should be able to use it to some measure.
You can use a set of DataTriggers, each inheriting a storyboard:

```<code><DataTrigger Binding="{Binding Property}" Value="SomeValue">
    <DataTrigger.EnterActions>
        <BeginStoryboard Storyboard="{StaticResource Storyboard}"/>
    </DataTrigger.EnterActions>
</DataTrigger>
</code>```

I would use them within a ControlTemplate:

```<code><ControlTemplate TargetType="Image">
    <ControlTemplate.Triggers>
        <!-- DataTriggers -->
    </ControlTemplate.Triggers>
</ControlTemplate>
</code>```

EDIT:

This Question has a similar solution, you may not need the ControlTemplate at all.

Body:
I want to have different animations for each of a ListView item.

<Window.Resources>
    <Storyboard x:Key="myAnimation" RepeatBehavior="Forever">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Source" Duration="0:0:2">
            <DiscreteObjectKeyFrame KeyTime="0:0:0">
                <DiscreteObjectKeyFrame.Value>
                    <BitmapImage UriSource="/img/image1.png"/>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
            <DiscreteObjectKeyFrame KeyTime="0:0:1">
                <DiscreteObjectKeyFrame.Value>
                    <BitmapImage UriSource="/img/image2.png"/>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>

<ListBox  Name="SessionList" HorizontalContentAlignment="Stretch" >
    <ListBox.ItemTemplate>
        <DataTemplate>
           <Image x:Name="stateimage">
                <Image.Triggers>
                    <EventTrigger RoutedEvent="Loaded">
                        <BeginStoryboard Storyboard="{StaticResource myAnimation}">
                        </BeginStoryboard>
                    </EventTrigger>
                </Image.Triggers>
            </Image>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The above XAML code works fine for showing the same animation myAnimation for each listitem. But how I can achive it to show different animations (i.e. I have to define several Storyboards in Window.Resources), depending on a Binding Property of the listitem ViewModel?

EDIT:

With the question linked below, I finally got it worked this way. Amazing!

<Window.Resources>
    <Storyboard x:Key="animLOAD" RepeatBehavior="Forever">...</Storyboard>
    <Storyboard x:Key="animPREPARED" RepeatBehavior="Forever">...</Storyboard>

    </Style>
</Window.Resources>

<Image Style="{StaticResource animStyle}" />

Body:
I'm not sure how accessible your model is for this approach but you should be able to use it to some measure.
You can use a set of DataTriggers, each inheriting a storyboard:

<DataTrigger Binding="{Binding Property}" Value="SomeValue">
    <DataTrigger.EnterActions>
        <BeginStoryboard Storyboard="{StaticResource Storyboard}"/>
    </DataTrigger.EnterActions>
</DataTrigger>

I would use them within a ControlTemplate:

<ControlTemplate TargetType="Image">
    <ControlTemplate.Triggers>
        <!-- DataTriggers -->
    </ControlTemplate.Triggers>
</ControlTemplate>

EDIT:

This Question has a similar solution, you may not need the ControlTemplate at all.


问:
Is it possible to access variables from another class in Typescript?

High level: I have a class A, which has a variable defined as "let _somevar".
I'm looking for ways to assign value to this variable from another class, B.

The details are a bit more involved:
Class A contains an initialization method to lazy load some module, and it has a variable "_somevar" which holds the module which is lazy loaded. Class A also has some public methods which checks whether this variable is null or not and executes accordingly.

Now Class B provides an initialization function to synchronously/directly (not lazy-load-ly) load the module. The problem is the public methods from Class A now wouldn't run because "_somevar" is not set. So I'm trying to set it from Class B so that the public methods in Class A can still be used.

I understand there's a lot of refactoring that can be done to these classes. but I don't own the codebase and I'm trying to make minimal code changes here to make it work.

I'd love to hear your suggestions. Thank you!

答:
It is not possible to access variables in another class.

You can access public members, such as properties and methods.

If you extend a class, the subclass can access protected members.

Here are some solutions, two of them promote the variable to be a property. The other doesn't.

Constructor

If ClassA depends on the initialization of somevar it can make the dependency explicit by requiring the dependency in its constructor. That way, you can't call a method that uses the dependency before the dependency is supplied.

```<code>class Example {
    constructor(private somevar: SomeVar) {
    }

    myMethod() {
        this._somevar.doSomething();
    }
}
</code>```

Set Dependency

If you are doing a light-tough change to fix your issue, you could add a method that accepts the dependency:

```<code>setDependency(somevar: SomeVar) {
    this.somevar = somevar;
}
</code>```

You can then call this before using the method that is currently failing. However, this is a form of temporal coupling. setDependency needs to be called before myMethod is called.

Pass to Method

The method that fails when the dependency isn't initialized could be changed to require the dependency...

For example, this:

```<code>myMethod() {
    this._somevar.doSomething();
}
</code>```

Becomes this:

```<code>myMethod(somevar: SomeVar) {
    somevar.doSomething();
}
</code>```

Body:
It is not possible to access variables in another class.

You can access public members, such as properties and methods.

If you extend a class, the subclass can access protected members.

Here are some solutions, two of them promote the variable to be a property. The other doesn't.

Constructor

If ClassA depends on the initialization of somevar it can make the dependency explicit by requiring the dependency in its constructor. That way, you can't call a method that uses the dependency before the dependency is supplied.

class Example {
    constructor(private somevar: SomeVar) {
    }

    myMethod() {
        this._somevar.doSomething();
    }
}

Set Dependency

If you are doing a light-tough change to fix your issue, you could add a method that accepts the dependency:

setDependency(somevar: SomeVar) {
    this.somevar = somevar;
}

You can then call this before using the method that is currently failing. However, this is a form of temporal coupling. setDependency needs to be called before myMethod is called.

Pass to Method

The method that fails when the dependency isn't initialized could be changed to require the dependency...

For example, this:

myMethod() {
    this._somevar.doSomething();
}

Becomes this:

myMethod(somevar: SomeVar) {
    somevar.doSomething();
}


问:
Convert a mySQL date to Javascript date
What would be the best way to convert a mysql date format date into a javascript Date object?

mySQL date format is 'YYYY-MM-DD' (ISO Format).

答:
While JS does possess enough basic tools to do this, it's pretty simple to use

/**
 * Ashu, You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};

var date = new Date();

document.getElementById("date").innerHTML = date;
document.getElementById("mysql_date").innerHTML = date.toMysqlFormat();
console.log(date.toMysqlFormat());```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Simple date:<div id="date"></div>

Converted Mysql Fromat: <div id="mysql_date"></div></code>```

Title: Convert a mySQL date to Javascript date

Body:
While JS does possess enough basic tools to do this, it's pretty simple to use

/**
 * Ashu, You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};

var date = new Date();

document.getElementById("date").innerHTML = date;
document.getElementById("mysql_date").innerHTML = date.toMysqlFormat();
console.log(date.toMysqlFormat());

Simple date:<div id="date"></div>

Converted Mysql Fromat: <div id="mysql_date"></div>