问:
Checking the table existence and loading the data into Hbase and HIve table
I have data in HDFS. And I wanted to load that data into hbase and hive table.
I have written a bash shell script in which I have written a pig script to load the data form HDFS to HBASE  and also written hive script to load the data from HDFS to HIVE table which are working perfectly fine.Here my HDFS data files are with the same structure and I'm loading all the data files into single hbase and hive table.

Now my query is suppose if I receive some more data files in HDFS directory and if I run the shell script again it will create hbase and hive table again with the same name and tells table already exists. How can I write a hive and hbase query so that 1st it will check for the table existence, if table does not exists it create the table for the 1st time and load the data from HDFS to HBASE & Hive table. If the table is already exists then it will just insert the data into an existing hbase and hive table. It should not overwrite the data alreday exists in the tables.
How this can be done ?

Below is my script file: myScript.sh

```<code>echo "create 'goodtable','gt'" | hbase shell
pig -f a.pig -param input=/user/user/d/
hive -f h.hql
</code>```

Where a.pig  :

```<code>G = LOAD '$input' USING PigStorage(',') as (c1:chararray, c2:chararray,c3:chararray,c4:chararray,c5:chararray);
STORE G INTO 'hbase://goodtable' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('gt:name gt:state gt:phone_no gt:gender');
</code>```

h.hql:

```<code>create external table hive_table(
id int,
name string,
state string,
phone_no int,
gender string) row format delimited fields terminated by ',' stored as textfile;
LOAD DATA INPATH '/user/user/d/' INTO TABLE hive_table;
</code>```

答:
I just wanted to add an example for HBase as Hive was already covered before:</p>

```<code>if [[ $(echo "exists 'goodtable'" | hbase shell | grep 'not exist') ]];
then
    echo "create 'goodtable','gt'" | hbase shell;
fi
</code>```

Body:
I have data in HDFS. And I wanted to load that data into hbase and hive table.
I have written a bash shell script in which I have written a pig script to load the data form HDFS to HBASE  and also written hive script to load the data from HDFS to HIVE table which are working perfectly fine.Here my HDFS data files are with the same structure and I'm loading all the data files into single hbase and hive table.

Now my query is suppose if I receive some more data files in HDFS directory and if I run the shell script again it will create hbase and hive table again with the same name and tells table already exists. How can I write a hive and hbase query so that 1st it will check for the table existence, if table does not exists it create the table for the 1st time and load the data from HDFS to HBASE & Hive table. If the table is already exists then it will just insert the data into an existing hbase and hive table. It should not overwrite the data alreday exists in the tables.
How this can be done ?

Below is my script file: myScript.sh

echo "create 'goodtable','gt'" | hbase shell
pig -f a.pig -param input=/user/user/d/
hive -f h.hql

Where a.pig  :

G = LOAD '$input' USING PigStorage(',') as (c1:chararray, c2:chararray,c3:chararray,c4:chararray,c5:chararray);
STORE G INTO 'hbase://goodtable' USING org.apache.pig.backend.hadoop.hbase.HBaseStorage('gt:name gt:state gt:phone_no gt:gender');

h.hql:

create external table hive_table(
id int,
name string,
state string,
phone_no int,
gender string) row format delimited fields terminated by ',' stored as textfile;
LOAD DATA INPATH '/user/user/d/' INTO TABLE hive_table;

Body:
I just wanted to add an example for HBase as Hive was already covered before:

if [[ $(echo "exists 'goodtable'" | hbase shell | grep 'not exist') ]];
then
    echo "create 'goodtable','gt'" | hbase shell;
fi


来源: stackexchange

问:
Get sub directories list order by created date in ascending order
I want to get the sub directories list in ascending order on created date means the oldest directory should be first and so on.

List subfolders = Directory.GetDirectories(source).ToList();

答:
I think DirectoryInfo.GetDirectories will be more suitable here, you can do like the following:

```<code>string source = "source Path here";
DirectoryInfo dInfo = new DirectoryInfo(source);
var subfolders = dInfo.GetDirectories(source).OrderBy(x=>x.CreationTime).ToList();
</code>```

Here the result of dInfo.GetDirectories will be of type System.IO.DirectoryInfo[] you can get Name,path or any related from each object of the subfolders

ContentLicense: CC BY-SA 3.0

Body:
I think DirectoryInfo.GetDirectories will be more suitable here, you can do like the following:

string source = "source Path here";
DirectoryInfo dInfo = new DirectoryInfo(source);
var subfolders = dInfo.GetDirectories(source).OrderBy(x=>x.CreationTime).ToList();

Here the result of dInfo.GetDirectories will be of type System.IO.DirectoryInfo[] you can get Name,path or any related from each object of the subfolders


问:
How many users is too much when using session variables?
I'm currently using session variables as a cache to cut down the calls to the database.

I'm wondering at about how many concurrent users does this stop working at? 1,000, 10,000 ....100,000??? Also will iis start flaking out at a certain load? And are there
any alternatives?

I know it depends on how much data I'm storing per user, but I want to hear from other peoples experiences.

I do have it setup so that when the code tries to access a timed out session that it reloads from the database.

I'm currently using iis6 but I could easily use iis7 if it handles sessions better.

Edit: Yes I'm using application variables for non user specific data.

答: It's very unlikely that session variable capacity will ever be the limiting resource for your server. Any particular reason you're asking?</p>

OwnerDisplayName: Donny V

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Donny V

OwnerDisplayName: le dorfier


问:
What exactly are parameters in javascript (or any programming language for that matter)
I have this piece of code that I've written and read that in order for it to work correctly I must use parameters so I did and it works perfectly, however I cant figure out for the life of me what parameters are and how they work. I read through a ton of articles all over the web but I just couldn't figure out how parameters work. How does one parameter know to grab instructions from another. The whole idea is just really frustrating. Also this is kind of a side question. Can I getElementBy Class instead of Id or is there anything similar to get getElementById() for classes? Thanks so much in advance.

Below is the code that is in the script.js file:

```<code>function setValue(field)
{
    if(''!=field.defaultValue)
    {
        if(field.value==field.defaultValue)
        {
            field.value='';
        }
        else if(''==field.value)
        {
            field.value=field.defaultValue;
        }
    }
}
</code>```

and I called this script to run with the code below:

```<code><textarea  id="info"
           class="textArea"
           name="comment"
           cols="40" rows="10"
           onfocus="setValue(this)"
           onblur="setValue(this)">
               Whats Your Name
</textarea>
</code>```

答:
Well, I think many people call them parameters while many others call them arguments, but they are both the same:  They are what you pass to a function.  What that does with the parameters/arguments is completely dependent on the function. You could pass a DOM element, a string, an object, you name it.. but the function ultimately decides what to do with it.

Your side-question about getElementByClass, there is getElementsbyClassName, but its not cross-browser compatible, meaning it only works in certain browsers.  There are libraries that handle all of the cross-browser madness for you though, such as Sizzle.

Body:
I have this piece of code that I've written and read that in order for it to work correctly I must use parameters so I did and it works perfectly, however I cant figure out for the life of me what parameters are and how they work. I read through a ton of articles all over the web but I just couldn't figure out how parameters work. How does one parameter know to grab instructions from another. The whole idea is just really frustrating. Also this is kind of a side question. Can I getElementBy Class instead of Id or is there anything similar to get getElementById() for classes? Thanks so much in advance.

Below is the code that is in the script.js file:

function setValue(field)
{
    if(''!=field.defaultValue)
    {
        if(field.value==field.defaultValue)
        {
            field.value='';
        }
        else if(''==field.value)
        {
            field.value=field.defaultValue;
        }
    }
}

and I called this script to run with the code below:

<textarea  id="info"
           class="textArea"
           name="comment"
           cols="40" rows="10"
           onfocus="setValue(this)"
           onblur="setValue(this)">
               Whats Your Name
</textarea>


问:
Regex : How to return an array of matches that need different regex?
I have to transform txt files in json files, so I use regex to parse different type of datas. I want to record data such as first name, last name, birthday and other stuff.

The data are formatted this way :

```<code>/Indicator /
/[A-Z][a-z]+ /
/[A-Z][a-z]+ /
/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/
</code>```

More specific example :

```<code>Indicator Tom Smith 01/01/2001
</code>```

So I know how where my info begins (it always starts with "Indicator ") and that after that there is the first name then the last name then the birthday, I also know what regex to use for theses types of data individually but not how to implement them all together.

This is what I do for the moment and I doubt it is optimal or recommended :

```<code>let first_name = "";
let last_name = "";
let birthday = "";
let j = 10; // Length of "Indicator "
let regex = /Indicator /;
let match = regex.exec(data);

j += match.index;
while (data[j] !== ' ')
    first_name += data[j++];
j++;
while (data[j] !== ' ')
    last_name += data[j++];
j++;
while (data[j] !== '<')
    birthday += data[j++];
console.log(first_name);
console.log(last_name);
console.log(birthday);
</code>```

My question is, what regex rule should I use to get the array ['Tom', 'Smith', '01/01/2001'] with one execution of regex.exec ?

答:
As Dhaval Chaudhary said in his answer, in this case, you don't even need to use regex.

But let's say you want to do that (maybe because the entries are more complicated and you have more than one type of character between words, I don't know).

Then, one simple approach that works if you know the order of the elements in each entry is

```<code>line="string1<element1>string2<element2>...stringN<elementN>"
strArray = line.match(/(regex1)|(regex2)|...|(regexM)/g)
</code>```

where each regexI may match more than one element (so M may be different from N).

In your simple example, it would be like that:

```<code>line="Indicator Tom Smith 01/01/2001" /* four elements */
strArray = line.match(/(Indicator)|([A-Z][a-z]*)|([0-9]{2}\/[0-9]{2}\/[0-9]{4})/g)  /* three regexes */
console.log(strArray)
</code>```

which prints

Array [ "Indicator", "Tom", "Smith", "01/01/2001" ]

Body:
I have to transform txt files in json files, so I use regex to parse different type of datas. I want to record data such as first name, last name, birthday and other stuff.

The data are formatted this way :

/Indicator /
/[A-Z][a-z]+ /
/[A-Z][a-z]+ /
/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/

More specific example :

Indicator Tom Smith 01/01/2001

So I know how where my info begins (it always starts with "Indicator ") and that after that there is the first name then the last name then the birthday, I also know what regex to use for theses types of data individually but not how to implement them all together.

This is what I do for the moment and I doubt it is optimal or recommended :

let first_name = "";
let last_name = "";
let birthday = "";
let j = 10; // Length of "Indicator "
let regex = /Indicator /;
let match = regex.exec(data);

j += match.index;
while (data[j] !== ' ')
    first_name += data[j++];
j++;
while (data[j] !== ' ')
    last_name += data[j++];
j++;
while (data[j] !== '<')
    birthday += data[j++];
console.log(first_name);
console.log(last_name);
console.log(birthday);

My question is, what regex rule should I use to get the array ['Tom', 'Smith', '01/01/2001'] with one execution of regex.exec ?

Body:
As Dhaval Chaudhary said in his answer, in this case, you don't even need to use regex.

But let's say you want to do that (maybe because the entries are more complicated and you have more than one type of character between words, I don't know).

Then, one simple approach that works if you know the order of the elements in each entry is

line="string1<element1>string2<element2>...stringN<elementN>"
strArray = line.match(/(regex1)|(regex2)|...|(regexM)/g)

where each regexI may match more than one element (so M may be different from N).

In your simple example, it would be like that:

line="Indicator Tom Smith 01/01/2001" /* four elements */
strArray = line.match(/(Indicator)|([A-Z][a-z]*)|([0-9]{2}\/[0-9]{2}\/[0-9]{4})/g)  /* three regexes */
console.log(strArray)

which prints

Array [ "Indicator", "Tom", "Smith", "01/01/2001" ]


问:
Regex - match words which only consists of certain characters and certain char is repeated certain times
I have words database containing of 300 000+ words

I want to match words which length is known (7 for example) and it contains
only certain characters and some of them can be repeated certain times but not all of them

for example

I have a,p,p,l,e,r,t,h,o  chars and I want to find words which length is 5

so, it can match

apple

earth

but not

hello because l is specified more than one time

My attempts

```<code> ^([a,p,p,l,e,r,t,h,o]{1}) # capture first char

 (!/1 [a,p,p,l,e,r,t,h,o]{1}) # capture second char but without firstly captured symbol

 (!/1 !/2 [a,p,p,l,e,r,t,h,o]{1}) # capture third char but without first and second captured symbol

and so on  ...
</code>```

答:
Try the following regex:

```<code>\b(?!\w*([alertho])\w*\1)(?!\w*([p])(\w*\2){2})[aplertho]{5}\b
</code>```

Details:

\b - Word boundary (opening).

(?!\w*([alertho])\w*\1) - Negative lookahead, test for more than 1
occurrence of the mentioned chars):

some word chars (optional),

one of chars allowed to occur once (capturing groupp #1),

some word chars (optional),

the same char as captured by groupp #1.

(?!\w*([p])(\w*\2){2}) - Negative lookahead, test for occurrence more
than 2 times.
Like before, but this time:

the capturing group has No 2,

the set of chars allowed contains only p,

this lookahead "fires" if the char captured by groupp #2 occured
two times thereafter.

[aplertho]{5} - What we are looking for - any of the allowed chars,
5 occurrences.

\b - Word boundary (closing).

Body:
I have words database containing of 300 000+ words

I want to match words which length is known (7 for example) and it contains
only certain characters and some of them can be repeated certain times but not all of them

for example

I have a,p,p,l,e,r,t,h,o  chars and I want to find words which length is 5

so, it can match

apple

earth

but not

hello because l is specified more than one time

My attempts

 ^([a,p,p,l,e,r,t,h,o]{1}) # capture first char

 (!/1 [a,p,p,l,e,r,t,h,o]{1}) # capture second char but without firstly captured symbol

 (!/1 !/2 [a,p,p,l,e,r,t,h,o]{1}) # capture third char but without first and second captured symbol

and so on  ...

Body:
Try the following regex:

\b(?!\w*([alertho])\w*\1)(?!\w*([p])(\w*\2){2})[aplertho]{5}\b

Details:

\b - Word boundary (opening).

(?!\w*([alertho])\w*\1) - Negative lookahead, test for more than 1
occurrence of the mentioned chars):

some word chars (optional),

one of chars allowed to occur once (capturing groupp #1),

some word chars (optional),

the same char as captured by groupp #1.

(?!\w*([p])(\w*\2){2}) - Negative lookahead, test for occurrence more
than 2 times.
Like before, but this time:

the capturing group has No 2,

the set of chars allowed contains only p,

this lookahead "fires" if the char captured by groupp #2 occured
two times thereafter.

[aplertho]{5} - What we are looking for - any of the allowed chars,
5 occurrences.

\b - Word boundary (closing).


问:
Issue compiling with different version of gcc and g++
I want to compile a program by entering through SSH the computer at my institution. I want to compile this program by using a different version of gcc and g++, namely a more recent one with repsect to the default installed one. This means that instead of using gcc-4.9.2 and g++-4.9.2 I would like to use gcc-6.3 and g++-6.3. I can find them already on my computer, in fact I have the folder /opt/gcc-6.3, so I don't have to download them. So what I do is the following

```<code>export PATH=/opt/gcc-6.3/bin/:$PATH
export LD_LIBRARY_PATH=/opt/gcc-6.3/lib/:$LD_LIBRARY_PATH
</code>```

but while gcc seems to work, when I try to compile a c++ program with g++ I get

```<code>./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by ./[name_of_the_program].x)
./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./[name_of_the_program].x)
</code>```

Obviously, if that's relevant information, I am not root on this machine.

答:
Don't do this:

```<code>export PATH=/opt/gcc-6.3/bin/:$PATH
export LD_LIBRARY_PATH=/opt/gcc-6.3/lib/:$LD_LIBRARY_PATH
</code>```

Instead, add:

```<code>-B/opt/gcc-6.3/lib/
</code>```

to your invocation options for either of the frontends gcc or g++ (assuming that /opt/gcc-6.3/lib/ is indeed the directory that directly
contains the GCC 6.3 toolchain executables and libraries).

See the documentation of the -Bprefix option

Example:

```<code>$ cat prog.cpp
#include <iostream>

int main()
{
    std::cout << "I was compiled with GCC "
        << __GNUC__ << '.' <<  __GNUC_MINOR__ << '.' << __GNUC_PATCHLEVEL__
        << " to C++ standard " << __cplusplus << std::endl;
    return 0;
}

$ which g++-4.9
/usr/bin/g++-4.9

$ which g++-6
/usr/bin/g++-6

$ g++-4.9 -o prog prog.cpp && ./prog
I was compiled with GCC 4.9.4 to C++ standard 199711

$ g++-4.9 -B/usr/lib/gcc/x86_64-linux-gnu/6.2.0 -o prog prog.cpp && ./prog
I was compiled with GCC 6.2.0 to C++ standard 201402
</code>```

As per others' comments, be aware g++ >= 5 is ABI incompatible with g++ < 5.

Body:
I want to compile a program by entering through SSH the computer at my institution. I want to compile this program by using a different version of gcc and g++, namely a more recent one with repsect to the default installed one. This means that instead of using gcc-4.9.2 and g++-4.9.2 I would like to use gcc-6.3 and g++-6.3. I can find them already on my computer, in fact I have the folder /opt/gcc-6.3, so I don't have to download them. So what I do is the following

export PATH=/opt/gcc-6.3/bin/:$PATH
export LD_LIBRARY_PATH=/opt/gcc-6.3/lib/:$LD_LIBRARY_PATH

but while gcc seems to work, when I try to compile a c++ program with g++ I get

./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by ./[name_of_the_program].x)
./[name_of_the_program].x: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./[name_of_the_program].x)

Obviously, if that's relevant information, I am not root on this machine.

Body:
Don't do this:

export PATH=/opt/gcc-6.3/bin/:$PATH
export LD_LIBRARY_PATH=/opt/gcc-6.3/lib/:$LD_LIBRARY_PATH

Instead, add:

-B/opt/gcc-6.3/lib/

to your invocation options for either of the frontends gcc or g++ (assuming that /opt/gcc-6.3/lib/ is indeed the directory that directly
contains the GCC 6.3 toolchain executables and libraries).

See the documentation of the -Bprefix option

Example:

$ cat prog.cpp
#include <iostream>

int main()
{
    std::cout << "I was compiled with GCC "
        << __GNUC__ << '.' <<  __GNUC_MINOR__ << '.' << __GNUC_PATCHLEVEL__
        << " to C++ standard " << __cplusplus << std::endl;
    return 0;
}

$ which g++-4.9
/usr/bin/g++-4.9

$ which g++-6
/usr/bin/g++-6

$ g++-4.9 -o prog prog.cpp && ./prog
I was compiled with GCC 4.9.4 to C++ standard 199711

$ g++-4.9 -B/usr/lib/gcc/x86_64-linux-gnu/6.2.0 -o prog prog.cpp && ./prog
I was compiled with GCC 6.2.0 to C++ standard 201402

As per others' comments, be aware g++ >= 5 is ABI incompatible with g++ < 5.


问:
unable to access web UI of oozie from Ambari in HDI 3.6 spark HDInsight cluster
I have set up the HDI 3.6 spark 2.1.0 HDInsight cluster.

Now I need to submit a spark job using oozie workflow,for doing this I need to configure the workflow.xml using Ambari.

The problem arises when accessing oozie webUI from Ambari as below:

while click on Oozie web UI I am getting the following error for loading the url:
https://samplecluster.azurehdinsight.net/da/host/hn0-cloudo.fabtnv3ti3juvluair5dbgfudc.hx.internal.cloudapp.net/port/11000/oozie?user.name=sathyaraj

error:

```<code>{
  "status": 404,
  "message": "Not Found"
}
</code>```

答:
To access the Oozie Web UI, use the following steps:

Create an SSH tunnel to the HDInsight cluster. For information, see the Use SSH Tunneling with HDInsight document.

Once a tunnel has been created, open the Ambari web UI in your web browser. The URI for the Ambari site is https://CLUSTERNAME.azurehdinsight.net. Replace CLUSTERNAME with the name of your Linux-based HDInsight cluster.

From the left side of the page, select Oozie, then Quick Links, and finally Oozie Web UI.

For more details, refer “Oozie Web UI”.

Body:
I have set up the HDI 3.6 spark 2.1.0 HDInsight cluster.

Now I need to submit a spark job using oozie workflow,for doing this I need to configure the workflow.xml using Ambari.

The problem arises when accessing oozie webUI from Ambari as below:

while click on Oozie web UI I am getting the following error for loading the url:
https://samplecluster.azurehdinsight.net/da/host/hn0-cloudo.fabtnv3ti3juvluair5dbgfudc.hx.internal.cloudapp.net/port/11000/oozie?user.name=sathyaraj

error:

{
  "status": 404,
  "message": "Not Found"
}


问:
Two return statements for one method? Python
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

```<code>count = 80
a = 20
if a > count:
    return xyz
else:
    return abc
</code>```

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

```<code>            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }
</code>```

答:
So now that we know exactly what is going on, Python's return statement actually 'exits' the function not continue it afterwards. What you need is to keep track of all the reports and then return it rather than doing so immediately. A way to do so is with a list or tuple.

I prefer lists as they are mutable for future use but if you need to use a tuple use ( ) instead of [ ].

```<code>reports = []
for inv_no in each:
    if inv_no.invoice_date > '2017-06-30':
        reports.append({
                        'type': 'ir.actions.report.xml',
                        'report_name': 'gst_invoice_print',
                        'datas': datas,
                        })
    else:
        reports.append({
                        'type': 'ir.actions.report.xml',
                        'report_name': 'invoice_print',
                        'datas': datas,
                        })

return reports
</code>```

This way you can get the appropriate reports for each date. To access the reports later on in the code, you do so with reports["index of list"]["key of dict"]

Body:
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

count = 80
a = 20
if a > count:
    return xyz
else:
    return abc

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }

Body:
So now that we know exactly what is going on, Python's return statement actually 'exits' the function not continue it afterwards. What you need is to keep track of all the reports and then return it rather than doing so immediately. A way to do so is with a list or tuple.

I prefer lists as they are mutable for future use but if you need to use a tuple use ( ) instead of [ ].

reports = []
for inv_no in each:
    if inv_no.invoice_date > '2017-06-30':
        reports.append({
                        'type': 'ir.actions.report.xml',
                        'report_name': 'gst_invoice_print',
                        'datas': datas,
                        })
    else:
        reports.append({
                        'type': 'ir.actions.report.xml',
                        'report_name': 'invoice_print',
                        'datas': datas,
                        })

return reports

This way you can get the appropriate reports for each date. To access the reports later on in the code, you do so with reports["index of list"]["key of dict"]


问:
DB Design for storing dynamic form data with multi select fields
How to store data from dynamic form with multi select fields.

I have read various post and  all example has only list key,value  input. But if the form has multi select input.  what is the best way to store the data.
I am not looking for NoSQL solution.

current design

```<code> forms
-----
  id (PK)
  name
  (other fields)

form_elements
-------------
  id (PK)
  form_id (FK to forms.id)
  element_type_id (FK to element_types.id)
  name
  list_group (nullable, it will be related only for multiselect inputs)
  (other fields)

element_types
-------------
  id (PK)
  name

list_values
-------------------
  id (PK)
  value
  group
  (other fields??)
</code>```

Form Table sample data

```<code>| form_id |    form_name    |
|:-------:|:---------------:|
|    1    |   Enquiry Form  |
|    2    | Test Drive Form |
|    3    |  Feedback Form  |
</code>```

Form_elements sample

```<code>| id | form_id | element_type_id |    name   | list_group |
|:--:|:-------:|:---------------:|:---------:|:-------:|
|  1 |    1    |        1        | firstName |         |
|  2 |    1    |        1        |  LastName |         |
|  3 |    1    |        2        |   color   |    color|
</code>```

element_types

```<code>| id    |   name    |
|:--:   |:--------: |
|  1    |   text    |
|  2    | checkbox  |
|  3    |   radio   |
</code>```

list_values sample data

```<code>| id    | value     | group     |
|:--:   |:-----:    |-------    |
|  1    |  red      | color     |
|  2    |  blue     | color     |
|  3    | green     | color     |
| 4     | Dell      | brand     |
| 5     | HP        | brand     |
</code>```

sample json posted

```<code>{
  "firstName": "john",
  "lastName": "Doe",
  "color": "red"
}
</code>```

form_submit table  will have the following rows

```<code>| form_id   | Column_id     | value     |
|:-------:  |:---------:    |:-----:    |
|    1      |     1         |  John     |
|    1      |     2         |  Doe      |
|    1      |     3         |  Red      |
|    1      |     1         | James     |
|    1      |     2         | Smith     |
|    1      |     3         |  Blue     |
</code>```

if the dynamic form has multi select option
sample json posted will be

```<code>{
  "firstName": "John",
  "lastName": "Doe",
  "color": [
    "red",
    "green",
    "blue"
  ]
}
</code>```

how do you store this data.

Do we need to store it in same form_submit table. or store in different table

答:
Firstly... I must warn that dynamic schemas like this are usually a bad idea.

Secondly it appears that your form_submit can store only one set of answers

I'm making assumptions here - its not clear if you need to support multiple sets or not, but it would make sense if it did.

So firstly let us extend form_submit to support multiple sets of questions from different people. We'll add a column submit_id, which is the instance of a questionaire (set of questions) that someone is answering.

```<code>submit_id   form_id   Column_id   value
    1           1        1        Block
    1           1        2        Rough
    1           1        3        Red
    2           1        1        Cylinder
    2           1        2        Smooth
    2           1        3        Blue
</code>```

Now we know that submit_id=1 is one set of questions answered by one person and submit_id=2 is another different set of questions answered by another

You might want to create a submit header that describes this:

```<code>submit_id      form_id    submit_datetime          submit_by
    1             1        2017-07-06 09:37:00       Fred
    2             1        2017-07-02 07:31:00       Fred
</code>```

Now we can create a table, say multiselect that lets us define the relationship between many possible questions and many possible multiselects

```<code>submit_id   column_id   list_value_id
     1          3            1   (red)
     1          3            2   (blue)
     1          3            3   (green)
     2          3            4   (dell)
</code>```

This set of rows tells us that questionaire 1 had a multiselect on column 3 and they picked red, blue green.

Questionaire 2 had a multiselect on column 3 and they just picked Dell

You don't even need a row in your form_submit table for this. It depends what else your form_submit stores.

That's just one way to do it. But it's really dictated by your business processes, relationships between entities, how you want to get data in and out etc. You might want to research questionairre data models online because this is nothing new.

I suspect this may just prompt more questions but lets try this first

Body:
How to store data from dynamic form with multi select fields.

I have read various post and  all example has only list key,value  input. But if the form has multi select input.  what is the best way to store the data.
I am not looking for NoSQL solution.

current design

 forms
-----
  id (PK)
  name
  (other fields)

form_elements
-------------
  id (PK)
  form_id (FK to forms.id)
  element_type_id (FK to element_types.id)
  name
  list_group (nullable, it will be related only for multiselect inputs)
  (other fields)

element_types
-------------
  id (PK)
  name

list_values
-------------------
  id (PK)
  value
  group
  (other fields??)

Form Table sample data

| form_id |    form_name    |
|:-------:|:---------------:|
|    1    |   Enquiry Form  |
|    2    | Test Drive Form |
|    3    |  Feedback Form  |

Form_elements sample

| id | form_id | element_type_id |    name   | list_group |
|:--:|:-------:|:---------------:|:---------:|:-------:|
|  1 |    1    |        1        | firstName |         |
|  2 |    1    |        1        |  LastName |         |
|  3 |    1    |        2        |   color   |    color|

element_types

| id    |   name    |
|:--:   |:--------: |
|  1    |   text    |
|  2    | checkbox  |
|  3    |   radio   |

list_values sample data

| id    | value     | group     |
|:--:   |:-----:    |-------    |
|  1    |  red      | color     |
|  2    |  blue     | color     |
|  3    | green     | color     |
| 4     | Dell      | brand     |
| 5     | HP        | brand     |

sample json posted

{
  "firstName": "john",
  "lastName": "Doe",
  "color": "red"
}

form_submit table  will have the following rows

| form_id   | Column_id     | value     |
|:-------:  |:---------:    |:-----:    |
|    1      |     1         |  John     |
|    1      |     2         |  Doe      |
|    1      |     3         |  Red      |
|    1      |     1         | James     |
|    1      |     2         | Smith     |
|    1      |     3         |  Blue     |

if the dynamic form has multi select option
sample json posted will be

{
  "firstName": "John",
  "lastName": "Doe",
  "color": [
    "red",
    "green",
    "blue"
  ]
}

how do you store this data.

Do we need to store it in same form_submit table. or store in different table

Body:
Firstly... I must warn that dynamic schemas like this are usually a bad idea.

Secondly it appears that your form_submit can store only one set of answers

I'm making assumptions here - its not clear if you need to support multiple sets or not, but it would make sense if it did.

So firstly let us extend form_submit to support multiple sets of questions from different people. We'll add a column submit_id, which is the instance of a questionaire (set of questions) that someone is answering.

submit_id   form_id   Column_id   value
    1           1        1        Block
    1           1        2        Rough
    1           1        3        Red
    2           1        1        Cylinder
    2           1        2        Smooth
    2           1        3        Blue

Now we know that submit_id=1 is one set of questions answered by one person and submit_id=2 is another different set of questions answered by another

You might want to create a submit header that describes this:

submit_id      form_id    submit_datetime          submit_by
    1             1        2017-07-06 09:37:00       Fred
    2             1        2017-07-02 07:31:00       Fred

Now we can create a table, say multiselect that lets us define the relationship between many possible questions and many possible multiselects

submit_id   column_id   list_value_id
     1          3            1   (red)
     1          3            2   (blue)
     1          3            3   (green)
     2          3            4   (dell)

This set of rows tells us that questionaire 1 had a multiselect on column 3 and they picked red, blue green.

Questionaire 2 had a multiselect on column 3 and they just picked Dell

You don't even need a row in your form_submit table for this. It depends what else your form_submit stores.

That's just one way to do it. But it's really dictated by your business processes, relationships between entities, how you want to get data in and out etc. You might want to research questionairre data models online because this is nothing new.

I suspect this may just prompt more questions but lets try this first


问:
RDTSCP and Instruction order
I'm using the rdtscp instruction to read the ecx register for detecting cpu and numa node ids (I'm developing an os).

The code looks like the following

```<code>inline static long get(unsigned char *node_id = 0, unsigned char *cpu_id = 0)
{
    unsigned int p;
    __asm__ __volatile__("rdtscp\n" : "=c" (p) : : "memory");

    if (node_id) {
        *node_id = p >> 12;
    }

    if (cpu_id) {
        *cpu_id = p & 0xfff;
    }

    return 0;
}
</code>```

On using this function, I have a not understandable behaviour: The CPU tells me a lot of exceptions (page fault, general protection fault, ...). That indicates to me, that the cpu or node id is not read, but if I log the id, all seems right and no exception appears.

So in code:

```<code>// ...
unsigned char cpu, numa;
get(&numa, &cpu);
// use cpu and numa id creates exception
</code>```

but

```<code>// ...
unsigned char cpu, numa;
get(&numa, &cpu);
print(cpu); // <--- this makes cpu reading ok?
// use cpu and numa id is ok
</code>```

Is the cpu reordering my instructions, so that he will use cpu_id/numa_id before reading it?

答:
Tell the compiler that the registers eax and edx are clobbered. Add them to the clobbered list:</p>

```<code>__asm__ __volatile__("rdtscp\n" : "=c" (p) : : "memory", "eax", "edx");
</code>```

Title: RDTSCP and Instruction order

Body:
I'm using the rdtscp instruction to read the ecx register for detecting cpu and numa node ids (I'm developing an os).

The code looks like the following

inline static long get(unsigned char *node_id = 0, unsigned char *cpu_id = 0)
{
    unsigned int p;
    __asm__ __volatile__("rdtscp\n" : "=c" (p) : : "memory");

    if (node_id) {
        *node_id = p >> 12;
    }

    if (cpu_id) {
        *cpu_id = p & 0xfff;
    }

    return 0;
}

On using this function, I have a not understandable behaviour: The CPU tells me a lot of exceptions (page fault, general protection fault, ...). That indicates to me, that the cpu or node id is not read, but if I log the id, all seems right and no exception appears.

So in code:

// ...
unsigned char cpu, numa;
get(&numa, &cpu);
// use cpu and numa id creates exception

but

// ...
unsigned char cpu, numa;
get(&numa, &cpu);
print(cpu); // <--- this makes cpu reading ok?
// use cpu and numa id is ok

Is the cpu reordering my instructions, so that he will use cpu_id/numa_id before reading it?

Body:
Tell the compiler that the registers eax and edx are clobbered. Add them to the clobbered list:

__asm__ __volatile__("rdtscp\n" : "=c" (p) : : "memory", "eax", "edx");


问:
Android listview inside tab layout inside dialog can't get scroll bars to show up
I have a custom dialog class that extends Dialog. Inside this I have a Tab Layout with 2 tabs. In each tab I have a list view. Everything works but I can't get scroll bars to show up.

Here is my XML:

```<code><?xml version="1.0" encoding="utf-8"?>

<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/TabHost01"
android:layout_width="300dp"
android:layout_height="300dp">

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <ListView
        android:id="@+id/ListView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:scrollbarAlwaysDrawVerticalTrack="true"/>

    <ListView
        android:id="@+id/ListView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:scrollbarAlwaysDrawVerticalTrack="true"/>

    </FrameLayout>
</LinearLayout>
</TabHost>
</code>```

and here is part of my code that sets this up:

```<code>    // get this window's layout parameters so we can change the position
WindowManager.LayoutParams params = getWindow().getAttributes();

    // change the position. 0,0 is center
    params.x = 0;
    params.y = 250;
    this.getWindow().setAttributes(params);

    // no title on this dialog
requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.myLayout);

// instantiate our list views for each tab
ListView listView01 = (ListView)findViewById(R.id.ListView01);
ListView listView02 = (ListView)findViewById(R.id.ListView02);

// instantiate and set our custom list view adapters
listViewAdapter01 = new ListViewAdapter01(context);
listView01.setAdapter(listViewAdapter01);

listViewAdapter02 = new ListViewAdapter02(context);
listView02.setAdapter(listViewAdapter02);

// get our tabHost from the xml
TabHost tabs = (TabHost)findViewById(R.id.TabHost01);
tabs.setup();

// create tab 1
TabHost.TabSpec tab1 = tabs.newTabSpec("tab1");
tab1.setContent(R.id.listView01);
tab1.setIndicator("List 1");
tabs.addTab(tab1);

// create tab 2
TabHost.TabSpec tab2 = tabs.newTabSpec("tab2");
tab2.setContent(R.id.listView02);
tab2.setIndicator("List 01");
tabs.addTab(tab2);
</code>```

答: Try to set all of the android:layout_width attributes within your layout xml to "fill_parent".

Body:
I have a custom dialog class that extends Dialog. Inside this I have a Tab Layout with 2 tabs. In each tab I have a list view. Everything works but I can't get scroll bars to show up.

Here is my XML:

<?xml version="1.0" encoding="utf-8"?>

<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/TabHost01"
android:layout_width="300dp"
android:layout_height="300dp">

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <ListView
        android:id="@+id/ListView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:scrollbarAlwaysDrawVerticalTrack="true"/>

    <ListView
        android:id="@+id/ListView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:scrollbarAlwaysDrawVerticalTrack="true"/>

    </FrameLayout>
</LinearLayout>
</TabHost>

and here is part of my code that sets this up:

    // get this window's layout parameters so we can change the position
WindowManager.LayoutParams params = getWindow().getAttributes();

    // change the position. 0,0 is center
    params.x = 0;
    params.y = 250;
    this.getWindow().setAttributes(params);

    // no title on this dialog
requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.myLayout);

// instantiate our list views for each tab
ListView listView01 = (ListView)findViewById(R.id.ListView01);
ListView listView02 = (ListView)findViewById(R.id.ListView02);

// instantiate and set our custom list view adapters
listViewAdapter01 = new ListViewAdapter01(context);
listView01.setAdapter(listViewAdapter01);

listViewAdapter02 = new ListViewAdapter02(context);
listView02.setAdapter(listViewAdapter02);

// get our tabHost from the xml
TabHost tabs = (TabHost)findViewById(R.id.TabHost01);
tabs.setup();

// create tab 1
TabHost.TabSpec tab1 = tabs.newTabSpec("tab1");
tab1.setContent(R.id.listView01);
tab1.setIndicator("List 1");
tabs.addTab(tab1);

// create tab 2
TabHost.TabSpec tab2 = tabs.newTabSpec("tab2");
tab2.setContent(R.id.listView02);
tab2.setIndicator("List 01");
tabs.addTab(tab2);


问:
Laravel 4.2 Vuejs
I am working in laravel 4.2 and I want to implement Vue.js into my application. When I put some testing code in my blade it only shows error that "Use of undefined constant message - assumed 'message'"I know that laravel read {{message}} like php code but do you know any solution how to add vue.js to my blade? Thanks for help.
Here is code</p>

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<script>
new Vue({
    el: '#app',
    data: {
        message: 'hello from Vue.js 2.0'
    }
})
</script>
<div id="app">
<p>{{ message }}</p>
</div>
</code>```

答:
escape the code using @

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<script>
new Vue({
    el: '#app',
    data: {
        message: 'hello from Vue.js 2.0'
    }
})
</script>
<div id="app">
<p>@{{ message }}</p>
</div>
</code>```

See Displaying Raw Text With Curly Braces section here

Title: Laravel 4.2 Vuejs

Body:
I am working in laravel 4.2 and I want to implement Vue.js into my application. When I put some testing code in my blade it only shows error that "Use of undefined constant message - assumed 'message'"I know that laravel read {{message}} like php code but do you know any solution how to add vue.js to my blade? Thanks for help.
Here is code

{{ message }}

Body:
escape the code using @

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<script>
new Vue({
    el: '#app',
    data: {
        message: 'hello from Vue.js 2.0'
    }
})
</script>
<div id="app">
<p>@{{ message }}</p>
</div>

See Displaying Raw Text With Curly Braces section here


问:
Get the value that is not matched with matching element from array with two elements
I have array of two elements

```<code>var a = ['a','b'];
</code>```

I have remover variable as var remover = 'a'

i want the result variable as var result = 'b'

i tried it as

```<code>var current_id = 'windows123456';
var allIds = People.Ids();  // this will have ['windows123456','windows123']
var index = allIds.indexOf(current_id);
  if (index >= 0) {
      allIds.splice( index, 1 );
  }
console.log(allIds[0]); //windows123
</code>```

Any Easy way to do this??

答:
You may destructure the array:</p>

```<code>var [remover,result]=a;
</code>```

Body:
I have array of two elements

var a = ['a','b'];

I have remover variable as var remover = 'a'

i want the result variable as var result = 'b'

i tried it as

var current_id = 'windows123456';
var allIds = People.Ids();  // this will have ['windows123456','windows123']
var index = allIds.indexOf(current_id);
  if (index >= 0) {
      allIds.splice( index, 1 );
  }
console.log(allIds[0]); //windows123

Any Easy way to do this??

Body:
You may destructure the array:

var [remover,result]=a;


问:
Mimic tapply behaviour in data.table
I'm looking to mimic the keeping of factors by tapply using data.table, for example

```<code>library(data.table)
amounts <- data.table(year = factor(2014:2017, levels = 2010:2017),
                      amount = 1:4)
tapply(amounts$amount, amounts$year, sum)
</code>```

yields

```<code>2010 2011 2012 2013 2014 2015 2016 2017
  NA   NA   NA   NA    1    2    3    4
</code>```

However, the approach using data.table doesn't show the years for which no rows are present:

```<code>amounts[ , list(sumAmount = sum(amount)), by = year]

   year sumAmount
1: 2014         1
2: 2015         2
3: 2016         3
4: 2017         4
</code>```

Is there a clean way to do this in data.table?

答:
The idiomatic way to include missing levels is with a join, I think:</p>

```<code>amounts[.(levels(year)), on=.(year), list(sumAmount = sum(amount)), by = .EACHI]

   year sumAmount
1: 2010        NA
2: 2011        NA
3: 2012        NA
4: 2013        NA
5: 2014         1
6: 2015         2
7: 2016         3
8: 2017         4
</code>```

Title: Mimic tapply behaviour in data.table

Body:
I'm looking to mimic the keeping of factors by tapply using data.table, for example

library(data.table)
amounts <- data.table(year = factor(2014:2017, levels = 2010:2017),
                      amount = 1:4)
tapply(amounts$amount, amounts$year, sum)

yields

2010 2011 2012 2013 2014 2015 2016 2017
  NA   NA   NA   NA    1    2    3    4

However, the approach using data.table doesn't show the years for which no rows are present:

amounts[ , list(sumAmount = sum(amount)), by = year]

   year sumAmount
1: 2014         1
2: 2015         2
3: 2016         3
4: 2017         4

Is there a clean way to do this in data.table?

Body:
The idiomatic way to include missing levels is with a join, I think:

amounts[.(levels(year)), on=.(year), list(sumAmount = sum(amount)), by = .EACHI]

   year sumAmount
1: 2010        NA
2: 2011        NA
3: 2012        NA
4: 2013        NA
5: 2014         1
6: 2015         2
7: 2016         3
8: 2017         4


问:
@include a view with controller functionality - Laravel 5.4
I am working on a profile page for my web application. Within this view profile.blade.php I would like to include the view progress/index.blade.php. I have the following structure:

profile.blade.php

```<code><div class="panel panel-default">
        <div class="panel-heading clearfix">
            <h1 class="panel-title pull-left">{{ $user->name }} Progress</h1>
        </div>
        <div class="panel-body">
            @include('client.progress.index')
        </div>
</div>
</code>```

web.php

```<code>Route::group(['middleware' => ['auth', 'client'], 'prefix' => 'client', 'as' => 'client.'], function () {
    Route::get('home', 'Client\HomeController@index')->name('home');
    Route::get('profile', 'Client\UserController@profile')->name('profile');
    Route::get('progress', 'Client\UserController@progress')->name('progress.index');
});
</code>```

UserController@progress

```<code>public function progress(){

        $auth = Auth::user();
        $progressPictures = Picture::select('*')
            ->where('user_id', $auth->id)
            ->get();

        return view('client.progress.index', ['progressPictures' => $progressPictures]);
    }
</code>```

client.progress.index

```<code><p>Progress pictures</p>

@foreach($progressPictures as $progressPicture)
    <img src="/storage/uploads/progress/{{ $progressPicture }}" style="width:150px; height:150px; float:left; border-radius:50%; margin-right:25px;">
@endforeach
</code>```

When I remove the php part from the index.blade.php, the site works. but when i add the foreach loop, $progressPictures is undefined. I am not calling the UserController@progress in some way. Could some one help me with this?

答:
Change

```<code>@include('client.progress.index')
</code>```

to

```<code>@include('client.progress.index', ['progressPictures' => $progressPictures])
</code>```

Body:
I am working on a profile page for my web application. Within this view profile.blade.php I would like to include the view progress/index.blade.php. I have the following structure:

profile.blade.php

{{ $user->name }} Progress

            @include('client.progress.index')

web.php

Route::group(['middleware' => ['auth', 'client'], 'prefix' => 'client', 'as' => 'client.'], function () {
    Route::get('home', 'Client\HomeController@index')->name('home');
    Route::get('profile', 'Client\UserController@profile')->name('profile');
    Route::get('progress', 'Client\UserController@progress')->name('progress.index');
});

UserController@progress

public function progress(){

        $auth = Auth::user();
        $progressPictures = Picture::select('*')
            ->where('user_id', $auth->id)
            ->get();

        return view('client.progress.index', ['progressPictures' => $progressPictures]);
    }

client.progress.index

Progress pictures

@foreach($progressPictures as $progressPicture)

@endforeach

When I remove the php part from the index.blade.php, the site works. but when i add the foreach loop, $progressPictures is undefined. I am not calling the UserController@progress in some way. Could some one help me with this?

Body:
Change

@include('client.progress.index')

to

@include('client.progress.index', ['progressPictures' => $progressPictures])


问:
multiple uses of attached property does not work
My guess is I'm not understanding attached properties correctly.  I'm trying to convert the FlowDocument on a RichTextBox to an HTML string property in my view model.  I have two RichTextBoxes that are using my RichTextBoxAssistant class (thanks to this blog post):

```<code><RichTextBox x:Name="rtb_description"
    local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.Description,
        ValidatesOnDataErrors=True}"/>

<RichTextBox x:Name="rtb_descriptionHowTo"
    local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.DescriptionHowTo,
        ValidatesOnDataErrors=True}" />
</code>```

In my RichTextBoxAssistant class, I have this dependency property:

```<code>public static readonly DependencyProperty BoundDocument =
    DependencyProperty.RegisterAttached(
        "BoundDocument",
        typeof(string),
        typeof(RichTextBoxAssistant),
        new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            boundDocumentChanged
        )
    );
</code>```

The problem is that the boundDocumentChanged method gets hit when I change the value in my first RichTextBox, rtb_description, but not when I change the value in rtb_descriptionHowTo.  When I change the text or do anything to rtb_descriptionHowTo, I never reach boundDocumentChanged.  Is this a result of RichTextBoxAssistant being a static class?  How can I fix it so that I can use RichTextBoxAssistant with multiple RichTextBoxes?

答: ColinE had the right idea:  I tried removing the attached property from my first RichTextBox, and changing the value of the second RichTextBox still didn't put me in boundDocumentChanged.  Turns out my DescriptionHowTo property in my view model was null, instead of an HTML string.  When I initialized it to @"", things started working.

Body:
My guess is I'm not understanding attached properties correctly.  I'm trying to convert the FlowDocument on a RichTextBox to an HTML string property in my view model.  I have two RichTextBoxes that are using my RichTextBoxAssistant class (thanks to this blog post):

<RichTextBox x:Name="rtb_description"
    local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.Description,
        ValidatesOnDataErrors=True}"/>

<RichTextBox x:Name="rtb_descriptionHowTo"
    local:RichTextBoxAssistant.BoundDocument="{Binding MyVM.DescriptionHowTo,
        ValidatesOnDataErrors=True}" />

In my RichTextBoxAssistant class, I have this dependency property:

public static readonly DependencyProperty BoundDocument =
    DependencyProperty.RegisterAttached(
        "BoundDocument",
        typeof(string),
        typeof(RichTextBoxAssistant),
        new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            boundDocumentChanged
        )
    );

The problem is that the boundDocumentChanged method gets hit when I change the value in my first RichTextBox, rtb_description, but not when I change the value in rtb_descriptionHowTo.  When I change the text or do anything to rtb_descriptionHowTo, I never reach boundDocumentChanged.  Is this a result of RichTextBoxAssistant being a static class?  How can I fix it so that I can use RichTextBoxAssistant with multiple RichTextBoxes?

Body: ColinE had the right idea:  I tried removing the attached property from my first RichTextBox, and changing the value of the second RichTextBox still didn't put me in boundDocumentChanged.  Turns out my DescriptionHowTo property in my view model was null, instead of an HTML string.  When I initialized it to @"<html><body></body></html>", things started working.


问:
How to input large data into python pandas using looping or parallel computing?
I have a csv file of 8gb and I am not able to run the code as it shows memory error.

```<code>file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0, dtype=str)
</code>```

I would like to split the files into 8 small files ("sorted by id") using python. And fianlly,have a loop so that the output file will have the output of all 8 files.

Or I would like to try parallel computing. Main goal is to process 8gb data in python pandas.  Thank you.

My csv file contains numerous data with '/' as the comma separator,

```<code>id    venue           time             code    value ......
AAA   Paris      28/05/2016 09:10      PAR      45   ......
111   Budapest   14/08/2016 19:00      BUD      62   ......
AAA   Tokyo      05/11/2016 23:20      TYO      56   ......
111   LA         12/12/2016 05:55      LAX      05   ......
111   New York   08/01/2016 04:25      NYC      14   ......
AAA   Sydney     04/05/2016 21:40      SYD      2    ......
ABX   HongKong   28/03/2016 17:10      HKG      5    ......
ABX   London     25/07/2016 13:02      LON      22   ......
AAA   Dubai      01/04/2016 18:45      DXB      19   ......
.
.
.
.
</code>```

答:
pandas read_csv has two argument options that you could use to do what you want to do:

```<code>nrows : to specify the number of rows you want to read
skiprows : to specify the first row you want to read
</code>```

Refer to documentation at: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

Body:
I have a csv file of 8gb and I am not able to run the code as it shows memory error.

file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0, dtype=str)

I would like to split the files into 8 small files ("sorted by id") using python. And fianlly,have a loop so that the output file will have the output of all 8 files.

Or I would like to try parallel computing. Main goal is to process 8gb data in python pandas.  Thank you.

My csv file contains numerous data with '/' as the comma separator,

id    venue           time             code    value ......
AAA   Paris      28/05/2016 09:10      PAR      45   ......
111   Budapest   14/08/2016 19:00      BUD      62   ......
AAA   Tokyo      05/11/2016 23:20      TYO      56   ......
111   LA         12/12/2016 05:55      LAX      05   ......
111   New York   08/01/2016 04:25      NYC      14   ......
AAA   Sydney     04/05/2016 21:40      SYD      2    ......
ABX   HongKong   28/03/2016 17:10      HKG      5    ......
ABX   London     25/07/2016 13:02      LON      22   ......
AAA   Dubai      01/04/2016 18:45      DXB      19   ......
.
.
.
.

Body:
pandas read_csv has two argument options that you could use to do what you want to do:

nrows : to specify the number of rows you want to read
skiprows : to specify the first row you want to read

Refer to documentation at: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html


问:
Get sub directories list order by created date in ascending order
I want to get the sub directories list in ascending order on created date means the oldest directory should be first and so on.

List subfolders = Directory.GetDirectories(source).ToList();

答:
You can use the DirectoryInfo. DirectoryInfo contains FileSystemInfo.CreationTime property.

```<code>var di = new DirectoryInfo(source);
var subfolders= di.EnumerateDirectories()
                  .OrderBy(d => d.CreationTime)
                  .ToList();
</code>```

Body:
You can use the DirectoryInfo. DirectoryInfo contains FileSystemInfo.CreationTime property.

var di = new DirectoryInfo(source);
var subfolders= di.EnumerateDirectories()
                  .OrderBy(d => d.CreationTime)
                  .ToList();


问:
Multiple Spring @Scheduled tasks simultaneously
I'm trying to run multiple scheduled tasks at the same time on spring boot, but in practice they run queuing (one after the other, not parallel)

This is my simple service:

```<code>import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class MyScheduleDemo {

    @Scheduled(fixedDelay = 5000, initialDelay = 1000)
    public void taskA() throws InterruptedException {
        System.out.println("[A] Starting new cycle of scheduled task");

        // Simulate an operation that took 5 seconds.
        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime <= 5000);

        System.out.println("[A] Done the cycle of scheduled task");
    }

    @Scheduled(fixedDelay = 5000, initialDelay = 2000)
    public void taskB() throws InterruptedException {
        System.out.println("[B] Starting new cycle of scheduled task");

        System.out.println("[B] Done the cycle of scheduled task");
    }
}
</code>```

Output:

```<code>[A] Starting new cycle of scheduled task
[A] Done the cycle of scheduled task
[B] Starting new cycle of scheduled task
[B] Done the cycle of scheduled task
</code>```

But, It should be like:

```<code>[A] Starting new cycle of scheduled task
[B] Starting new cycle of scheduled task
[B] Done the cycle of scheduled task
[A] Done the cycle of scheduled task
</code>```

What am I doing wrong?

This is my configuration:

```<code>@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(6);
        executor.setMaxPoolSize(50);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("customer-Executor-");
        executor.initialize();
        return executor;
    }
}
</code>```

答:
You should use TaskScheduler for your purpose

```<code>@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setPoolSize(THREADS_COUNT);
    return threadPoolTaskScheduler;
}
</code>```

Where THREADS_COUNT - total count of tasks which should be executed in parallel. If I understand you correctly, you have only 2 jobs, so you need 2 threads

Body:
I'm trying to run multiple scheduled tasks at the same time on spring boot, but in practice they run queuing (one after the other, not parallel)

This is my simple service:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class MyScheduleDemo {

    @Scheduled(fixedDelay = 5000, initialDelay = 1000)
    public void taskA() throws InterruptedException {
        System.out.println("[A] Starting new cycle of scheduled task");

        // Simulate an operation that took 5 seconds.
        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime <= 5000);

        System.out.println("[A] Done the cycle of scheduled task");
    }

    @Scheduled(fixedDelay = 5000, initialDelay = 2000)
    public void taskB() throws InterruptedException {
        System.out.println("[B] Starting new cycle of scheduled task");

        System.out.println("[B] Done the cycle of scheduled task");
    }
}

Output:

[A] Starting new cycle of scheduled task
[A] Done the cycle of scheduled task
[B] Starting new cycle of scheduled task
[B] Done the cycle of scheduled task

But, It should be like:

[A] Starting new cycle of scheduled task
[B] Starting new cycle of scheduled task
[B] Done the cycle of scheduled task
[A] Done the cycle of scheduled task

What am I doing wrong?

This is my configuration:

@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(6);
        executor.setMaxPoolSize(50);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("customer-Executor-");
        executor.initialize();
        return executor;
    }
}

Body:
You should use TaskScheduler for your purpose

@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setPoolSize(THREADS_COUNT);
    return threadPoolTaskScheduler;
}

Where THREADS_COUNT - total count of tasks which should be executed in parallel. If I understand you correctly, you have only 2 jobs, so you need 2 threads


问:
SQL COUNT DISTINCT for each ID in MS Access
Say I had a table as follows:

```<code>id  category       app
------------------------
1   game           angry birds
1   game           happy dogs
2   productivity   calculator
3   health         fitness tracker
1   game           angry birds
2   game           snake
</code>```

The table shows every app that the user opens over time. For example, pretend you wrote down each time you opened an app on your phone. Now repeat this for 100 people. All of that data is stored in one table, as above.

I am trying to figure out how to count how many distinct apps each person uses within a particular category. For example, for the 'game' category, I would expect:

```<code>id  num_apps
------------
1   2
2   1
3   0
</code>```

I understand that one cannot use COUNT(DISTINCT ..) in MS-Access, and have seen other posts on how to achieve this - I haven't been able to apply it to this case though.

I have tried the following, which I believe gives me a non-distinct count of how each app anyone ever used in a particular category:

```<code>SELECT COUNT(*)
FROM
(SELECT DISTINCT id AS gamer_id
FROM UseList
WHERE category = 'game')
AS b, UseList AS ul
WHERE b.gamer_id = ul.id AND category = 'game'
GROUP BY b.gamer_id;
</code>```

How could I apply to distinct search to this? I've thought of somehow looping through each gamer_id, but that doesn't seem too straightforward either.
Thanks!

答:
I am not sure I understood, but can you try this?</p>

```<code>SELECT A.ID, A.CATEGORY , COUNT(APP) AS NUM_APPS
FROM
(SELECT A1.ID, A2.CATEGORY
 FROM ( SELECT DISTINCT ID FROM TG1) A1
      CROSS JOIN (SELECT DISTINCT  CATEGORY FROM TG1) A2
) A
LEFT JOIN (SELECT DISTINCT ID, CATEGORY, APP
          FROM TG1) B ON A.ID=B.ID AND A.CATEGORY=B.CATEGORY
GROUP BY A.ID, A.CATEGORY
</code>```

Body:
Say I had a table as follows:

id  category       app
------------------------
1   game           angry birds
1   game           happy dogs
2   productivity   calculator
3   health         fitness tracker
1   game           angry birds
2   game           snake

The table shows every app that the user opens over time. For example, pretend you wrote down each time you opened an app on your phone. Now repeat this for 100 people. All of that data is stored in one table, as above.

I am trying to figure out how to count how many distinct apps each person uses within a particular category. For example, for the 'game' category, I would expect:

id  num_apps
------------
1   2
2   1
3   0

I understand that one cannot use COUNT(DISTINCT ..) in MS-Access, and have seen other posts on how to achieve this - I haven't been able to apply it to this case though.

I have tried the following, which I believe gives me a non-distinct count of how each app anyone ever used in a particular category:

SELECT COUNT(*)
FROM
(SELECT DISTINCT id AS gamer_id
FROM UseList
WHERE category = 'game')
AS b, UseList AS ul
WHERE b.gamer_id = ul.id AND category = 'game'
GROUP BY b.gamer_id;

How could I apply to distinct search to this? I've thought of somehow looping through each gamer_id, but that doesn't seem too straightforward either.
Thanks!

Body:
I am not sure I understood, but can you try this?

SELECT A.ID, A.CATEGORY , COUNT(APP) AS NUM_APPS
FROM
(SELECT A1.ID, A2.CATEGORY
 FROM ( SELECT DISTINCT ID FROM TG1) A1
      CROSS JOIN (SELECT DISTINCT  CATEGORY FROM TG1) A2
) A
LEFT JOIN (SELECT DISTINCT ID, CATEGORY, APP
          FROM TG1) B ON A.ID=B.ID AND A.CATEGORY=B.CATEGORY
GROUP BY A.ID, A.CATEGORY


问:
Merge / convert multiple PDF files into one PDF
How could I merge / convert multiple PDF files into one large PDF file?

I tried the following, but the content of the target file was not as expected:

```<code>convert file1.pdf file2.pdf merged.pdf
</code>```

I need a very simple/basic command line (CLI) solution. Best would be if I could pipe the output of the merge / convert straight into pdf2ps ( as originally attempted in my previously asked question here: Linux piping ( convert -> pdf2ps -> lp) ).

答:
Use pdftools from PyPI.

Download the tar.gz file and uncompress it and run the command like below

```<code>python pdftools-1.1.0/pdfmerge.py -o output.pdf -d file1.pdf file2.pdf file3
</code>```

You should install python3 before you run the above command

This tools support the below

add

insert

Remove

Rotate

Split

Merge

Zip

You can find more details on GitHub and it is open source

Body:
How could I merge / convert multiple PDF files into one large PDF file?

I tried the following, but the content of the target file was not as expected:

convert file1.pdf file2.pdf merged.pdf

I need a very simple/basic command line (CLI) solution. Best would be if I could pipe the output of the merge / convert straight into pdf2ps ( as originally attempted in my previously asked question here: Linux piping ( convert -> pdf2ps -> lp) ).

Body:
Use pdftools from PyPI.

Download the tar.gz file and uncompress it and run the command like below

python pdftools-1.1.0/pdfmerge.py -o output.pdf -d file1.pdf file2.pdf file3

You should install python3 before you run the above command

This tools support the below

add

insert

Remove

Rotate

Split

Merge

Zip

You can find more details on GitHub and it is open source

ContentLicense: CC BY-SA 4.0


问:
ngFor from object?
I'm using Ionic 2 / Angular, but I realized that the ngFor function can't read objects. Also, I need it to be shown only if the cart is not empty.

Object:

```<code>{
    "48131": {
        "code":"D40905",
        "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON",
        "price":"18.99",
        "size":"STANDART",
        "qty":"1"
    },
    "49410": {
        "code":"D41821",
        "name":"ДАМСКА БЛУЗА ТРИКО",
        "price":"44.99",
        "size":"M",
        "qty":"4"
    }
}
</code>```

HTML:

```<code><ion-row *ngFor="let p of cart">
    <ion-col col-3>
        <div><img src="http://example.com/products/small/{{p.code}}-1.jpg" /></div>
    </ion-col>
    <ion-col col-9>
        <ion-row>
            <ion-col col-12>
                <div>{{p.name}}</div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div>{{p.qty}} бр ({{p.size}} размер) x <b>{{p.price}} лв</b></div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div (click)="deleteCart({{p.id}})">Изтрий <ion-icon name='trash' item-start color="danger"></ion-icon></div>
            </ion-col>
        </ion-row>
    </ion-col>
</ion-row>
</code>```

Can someone help me with this? I've tried so many things...

答:
you can use Pipe for that purpose

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'object'
})
export class ObjectForPipe implements PipeTransform {
    transform(value: any, arg1): any {
        return typeof value!=='object' ? [] : Object.keys(value);
    }
}
</code>```

In AppModule -> @NgModule

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ObjectForPipe } from 'path-to-pipe/object.pipe.ts';

@NgModule({
  declarations: [
    AppComponent,
    ObjectForPipe
  ],
  imports: [
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

HTML

```<code><div *ngFor="let key of objs | object">
</code>```

From version 6.1, Angular introduced keyValue Pipe:

```<code><div *ngFor="let item of map | keyvalue">
   {{item.key}}:{{item.value}}
</div>
</code>```

Title: ngFor from object?

Body:
I'm using Ionic 2 / Angular, but I realized that the ngFor function can't read objects. Also, I need it to be shown only if the cart is not empty.

Object:

{
    "48131": {
        "code":"D40905",
        "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON",
        "price":"18.99",
        "size":"STANDART",
        "qty":"1"
    },
    "49410": {
        "code":"D41821",
        "name":"ДАМСКА БЛУЗА ТРИКО",
        "price":"44.99",
        "size":"M",
        "qty":"4"
    }
}

HTML:

<ion-row *ngFor="let p of cart">
    <ion-col col-3>

    </ion-col>
    <ion-col col-9>
        <ion-row>
            <ion-col col-12>

{{p.name}}

            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>

{{p.qty}} бр ({{p.size}} размер) x {{p.price}} лв

            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>

Изтрий <ion-icon name='trash' item-start color="danger"></ion-icon>

            </ion-col>
        </ion-row>
    </ion-col>
</ion-row>

Can someone help me with this? I've tried so many things...

Body:
you can use Pipe for that purpose

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'object'
})
export class ObjectForPipe implements PipeTransform {
    transform(value: any, arg1): any {
        return typeof value!=='object' ? [] : Object.keys(value);
    }
}

In AppModule -> @NgModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ObjectForPipe } from 'path-to-pipe/object.pipe.ts';

@NgModule({
  declarations: [
    AppComponent,
    ObjectForPipe
  ],
  imports: [
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

HTML

<div *ngFor="let key of objs | object">

From version 6.1, Angular introduced keyValue Pipe:

<div *ngFor="let item of map | keyvalue">
   {{item.key}}:{{item.value}}
</div>


问:
Error retrieving Sku details
I have developed an app using Ionic Native In-App Purchases and submitted it to the Google Play Store as an Alpha release.

I could view the available purchase options:

```<code>this.iap.getProducts(this.PRODUCT_IDS).then((products: any[]) => {
    ...
});
</code>```

I then set up a test user to test in-app purchases. I tried to make a purchase:

```<code>this.iap.buy(item.productId).then((data) => {
  return this.iap.consume(data.productType, data.receipt, data.signature);
}).then(() => {
    ...
}).catch((err) => {
  this.loading.dismiss().then(() => {
    this.doAlert('Error: ' + JSON.stringify(err));
  });
});
</code>```

And ever since, when I try to make other purchases to test the app, I get the following when trying to get the available purchases:

Error retrieving Sku details

I have read that this error may be caused by a pending order that needs to be canceled, but I cannot find where to do so (I have looked at "Order Management", but there are no orders).

This is working perfectly on iOS, so I know my code is correct, and also on Android I could view the available purchases before I did the test purchase.

I have also read that I should wait 14 days for Google to remove test orders, but it's been 16 days today, and I still get the error.

I have also since released my app as Beta in the Play Store, but I still get the same error.

答:
I think I found the problem, I just add the play store key in the manifest.json file inside src/ folder of the Ionic 2 project.

```<code>{ "play_store_key": "<Base64-encoded public key from the Google Play Store>" }
</code>```

I hope this will help your problem too.

Title: Error retrieving Sku details

Body:
I have developed an app using Ionic Native In-App Purchases and submitted it to the Google Play Store as an Alpha release.

I could view the available purchase options:

this.iap.getProducts(this.PRODUCT_IDS).then((products: any[]) => {
    ...
});

I then set up a test user to test in-app purchases. I tried to make a purchase:

this.iap.buy(item.productId).then((data) => {
  return this.iap.consume(data.productType, data.receipt, data.signature);
}).then(() => {
    ...
}).catch((err) => {
  this.loading.dismiss().then(() => {
    this.doAlert('Error: ' + JSON.stringify(err));
  });
});

And ever since, when I try to make other purchases to test the app, I get the following when trying to get the available purchases:

Error retrieving Sku details

I have read that this error may be caused by a pending order that needs to be canceled, but I cannot find where to do so (I have looked at "Order Management", but there are no orders).

This is working perfectly on iOS, so I know my code is correct, and also on Android I could view the available purchases before I did the test purchase.

I have also read that I should wait 14 days for Google to remove test orders, but it's been 16 days today, and I still get the error.

I have also since released my app as Beta in the Play Store, but I still get the same error.

Body:
I think I found the problem, I just add the play store key in the manifest.json file inside src/ folder of the Ionic 2 project.

{ "play_store_key": "<Base64-encoded public key from the Google Play Store>" }

I hope this will help your problem too.


问:
Where to put outside-aggregate validation?
I've got a question regarding outside-aggregate validation.

In our domain partner can place orders that contain certain products (1).

Once order is placed (2) he can mark it as paid (3) in our system.

Once order is marked as paid (4) we assign licences to products in external library service (5).

Once we know licences are assigned (6) we close entire saga.

Here's a small drawing illustrating the process:

At this moment besides commands, command handlers and events there are two domain classes that are involved in entire process:

Order aggregate containing business logic
Order saga coordinating entire process and assigning licences

Now, there is one invariant that is not modelled in this process yet - before we mark order as paid we have to check if user does not already have particular licence assigned. We get this from library service as well.

Where would you put this validation? Command handler? Wrap Order in some domain service? Pass some validator to Order constructor?

```<code>class Order
{
    public function __construct(OrderValidator $validator)
    {
        if (!$validator->isValid($this)) {
            throw new \DomainException();
        }

        // else proceed
    }
}

class OrderValidator
{
    private $libraryServiceClient;

    public function isValid(Order $order)
    {
        // check licence using $libraryServiceClient
    }
}
</code>```

答:
As far as I understood the problem is in step 3 (Mark order as payed). In this step we need a user (let's call it payer) that marks the order as payed. So when creating this payer object (using factory maybe) we need to know if he is allowed to mark an order as payed. In order to get this information a call should be made to the external library.

What I suggest is to have an application service that have ->markOrderAsPayed($orderId, $payerUserId)
This method will make a call to 2 domain services. One for getting the payer and one for marking the order as payed.

```<code>$payer = $this->payerService->getPayer($payerUserId);
$this->orderService->payOrder($orderId, $payer);
</code>```

In the getPayer() function you should make a call to the external library to know how many licences the payer have.

I hope this will be helpful, it is just based on what I understood from the questions and comments.

Body:
I've got a question regarding outside-aggregate validation.

In our domain partner can place orders that contain certain products (1).

Once order is placed (2) he can mark it as paid (3) in our system.

Once order is marked as paid (4) we assign licences to products in external library service (5).

Once we know licences are assigned (6) we close entire saga.

Here's a small drawing illustrating the process:

At this moment besides commands, command handlers and events there are two domain classes that are involved in entire process:

Order aggregate containing business logic
Order saga coordinating entire process and assigning licences

Now, there is one invariant that is not modelled in this process yet - before we mark order as paid we have to check if user does not already have particular licence assigned. We get this from library service as well.

Where would you put this validation? Command handler? Wrap Order in some domain service? Pass some validator to Order constructor?

class Order
{
    public function __construct(OrderValidator $validator)
    {
        if (!$validator->isValid($this)) {
            throw new \DomainException();
        }

        // else proceed
    }
}

class OrderValidator
{
    private $libraryServiceClient;

    public function isValid(Order $order)
    {
        // check licence using $libraryServiceClient
    }
}

Body:
As far as I understood the problem is in step 3 (Mark order as payed). In this step we need a user (let's call it payer) that marks the order as payed. So when creating this payer object (using factory maybe) we need to know if he is allowed to mark an order as payed. In order to get this information a call should be made to the external library.

What I suggest is to have an application service that have ->markOrderAsPayed($orderId, $payerUserId)
This method will make a call to 2 domain services. One for getting the payer and one for marking the order as payed.

$payer = $this->payerService->getPayer($payerUserId);
$this->orderService->payOrder($orderId, $payer);

In the getPayer() function you should make a call to the external library to know how many licences the payer have.

I hope this will be helpful, it is just based on what I understood from the questions and comments.


问:
How to pause a videosphere in A-frame?
I don't want a video controller but pause the video and change its current time in JS, what should I do? I have done a lot of research and tried a lot, but it always says" Cannot read property 'pause' of null". </p>

答:
If You have a video in your :

```<code><a-assets>
   <video id="myvideo">
</a-assets>

<a-videosphere src="#myvideo>
</code>```

then You can call play()/pause() on the video asset, like:

```<code>document.querySelector("#myvideo").pause();
</code>```

If You set Your a-videosphere src as a direct link to an .mp4 file, then try to call the functions on the videosphereElReference.getAttribute('src').pause();

Working fiddle here.

Title: How to pause a videosphere in A-frame?

Body:
If You have a video in your <a-assets>:

<a-assets>
   <video id="myvideo">
</a-assets>

<a-videosphere src="#myvideo>

then You can call play()/pause() on the video asset, like:

document.querySelector("#myvideo").pause();

If You set Your a-videosphere src as a direct link to an .mp4 file, then try to call the functions on the videosphereElReference.getAttribute('src').pause();

Working fiddle here.


问:
"Driver is not defined" Python/Selenium
I want to use Selenium on Python but I have an alert message:

driver-webdriver.Chrome("D:\Selenium\Chrome\chromedriver.exe") NameError: name 'driver' is not defined

I have installed the Chrome Driver, what else must I do ?

答:
Here is the Answer to your Question:

While working with Selenium 3.4.3, chromedriver v2.30 and Google Chrome v59.0 through Python 3.6.1 you neither need to install chromedriver nor need to copy in to any path. You can save the chromedriver in any location on your machine. To initiate the WebDriver instance you can explicitly call the chromedriver by passing the absolute path of the chromedriver through the argument  executable_path as follows:

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path= r'C:\\Utility\\BrowserDrivers\\chromedriver.exe')
</code>```

Let me know if this Answers your Question.

Title: "Driver is not defined" Python/Selenium

Body:
Here is the Answer to your Question:

While working with Selenium 3.4.3, chromedriver v2.30 and Google Chrome v59.0 through Python 3.6.1 you neither need to install chromedriver nor need to copy in to any path. You can save the chromedriver in any location on your machine. To initiate the WebDriver instance you can explicitly call the chromedriver by passing the absolute path of the chromedriver through the argument  executable_path as follows:

from selenium import webdriver
driver = webdriver.Chrome(executable_path= r'C:\\Utility\\BrowserDrivers\\chromedriver.exe')

Let me know if this Answers your Question.


问:
SVG position:absolute in IE 11
of I have an SVG object placed in a container. It has the following CSS on its class.

```<code>.container{
    position: relative;
}

.svgObj{
    position: absolute;
    top: 0;
    left: 0;
    width: 2em;
    height: 2em;
}
</code>```

So, the problem is that the svg doesn't end up in 0:0 of the container but rather more like in 200px south of that.

The queer thing is that if I substiute the SVG tag for a DIV with the same class, it displays exactly where I want it to.

The problem is only apparent in IE (only tried 11, but likely there in earlier versions as well).
Well, fwiw the problem is also visible in Minori.
Works fine in Safari, Chrome, FF, Opera, well the bigs, except IE.

Any ideas are most welcome.

The HTML code looks like so

```<code><div class="container">
<svg class="svgObject" data-x="0" data-y="0" data-text="My Obj"  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <a id="h-72417" href="#">
        <path d="M12 4a8 0z"></path>
        <path d="M12 4a8 0-16z"></path>
    </a>
</svg>
</div>
</code>```

Never mind the path values, I shortened them here to save space. It shouldn't matter. The data attributes aren't relevant either. As stated, just switching SVG for DIV and adding a "hello" instead of the paths makes it work as expected.

Thanks.

答:
I know this is an old question, but I came across it as I was searching for an answer to this issue myself. The solution that worked for me was to add preserveAspectRatio="xMinYMin meet" to the  tag. This essentially makes the SVG responsive and shifts the contents to the top left of the SVG container.

I found the answer here: http://thenewcode.com/744/Make-SVG-Responsive

Title: SVG position:absolute in IE 11

Body:
of I have an SVG object placed in a container. It has the following CSS on its class.

.container{
    position: relative;
}

.svgObj{
    position: absolute;
    top: 0;
    left: 0;
    width: 2em;
    height: 2em;
}

So, the problem is that the svg doesn't end up in 0:0 of the container but rather more like in 200px south of that.

The queer thing is that if I substiute the SVG tag for a DIV with the same class, it displays exactly where I want it to.

The problem is only apparent in IE (only tried 11, but likely there in earlier versions as well).
Well, fwiw the problem is also visible in Minori.
Works fine in Safari, Chrome, FF, Opera, well the bigs, except IE.

Any ideas are most welcome.

The HTML code looks like so

<svg class="svgObject" data-x="0" data-y="0" data-text="My Obj"  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">

        <path d="M12 4a8 0z"></path>
        <path d="M12 4a8 0-16z"></path>

</svg>

Never mind the path values, I shortened them here to save space. It shouldn't matter. The data attributes aren't relevant either. As stated, just switching SVG for DIV and adding a "hello" instead of the paths makes it work as expected.

Thanks.


问:
Alignment issue in context menu

The tickmark should be aligned with the text.

Styles :

```<code>   {
content: '\2713';
display: inline-block;
color: #990000;
float:right;
vertical-align: middle;

/*padding: 0 6px 0 0;
position: absolute;
right: 0;
top: 10px;*/
  }
</code>```

How can I make the correct alignment ?

答:
.double {
border-style: double;
background-color:#50a8d8;
width:30%;
height:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

</head>
<body>

<div class="double" style="padding:5px; color:white;" > Pan   <i class="fa fa-check pull-right" aria-hidden="true" style="color:black"></i>
</div>

</body>
</html></code>```

Title: Alignment issue in context menu

Body:
The tickmark should be aligned with the text.

Styles :

   {
content: '\2713';
display: inline-block;
color: #990000;
float:right;
vertical-align: middle;

/*padding: 0 6px 0 0;
position: absolute;
right: 0;
top: 10px;*/
  }

How can I make the correct alignment ?

Body:
.double {
border-style: double;
background-color:#50a8d8;
width:30%;
height:20px;
}

<!DOCTYPE html>
<html>
<head>

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

</head>
<body>

<div class="double" style="padding:5px; color:white;" > Pan   <i class="fa fa-check pull-right" aria-hidden="true" style="color:black"></i>
</div>

</body>
</html>


问:
PHP include in JavaScript is not working
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

```<code>outputEl.innerHTML = '<?php include "./change/ud1.php";?>';
</code>```

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

答:
You can't run php inside a .js file. As I understand it, you're going to need to fetch the content of the php file from your js file.

Here's a bare-bones implementation.

```<code>var xhr = new XMLHttpRequest();

xhr.onload = function () {
    outputEl.innerHTML = this.response;
};

xhr.open('GET', './change/ud1.php', true); // you may need to correct the url to be relative to the js file
xhr.send();
</code>```

It might be easier and more robust to use jquery, in which case (once you've included the jquery library) you can just use something like this

```<code>$(outputEl).load("change/ud1.php");
</code>```

Body:
I've JavaScript and I want to run a include script in the JavaScript . I tried the following statement:

outputEl.innerHTML = '<?php include "./change/ud1.php";?>';

When I run the script I get no response.

Does someone know why I didn't get any response and how I can fix it?

I tried to replace the PHP include with an html iframe. That worked but that is not the best solution for me.

Body:
You can't run php inside a .js file. As I understand it, you're going to need to fetch the content of the php file from your js file.

Here's a bare-bones implementation.

var xhr = new XMLHttpRequest();

xhr.onload = function () {
    outputEl.innerHTML = this.response;
};

xhr.open('GET', './change/ud1.php', true); // you may need to correct the url to be relative to the js file
xhr.send();

It might be easier and more robust to use jquery, in which case (once you've included the jquery library) you can just use something like this

$(outputEl).load("change/ud1.php");


问:
phpmyadmin server conncetion localhost/login.php not posting anything
What is physically wrong with this code.

```<code><?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result > 0) {
echo "login success";
}
else{
echo "login not success";
}

?>
</code>```

(when I run it on the local host, there is nothing there [localhost/login.php])

答:
you should remove ; from the query string

before

```<code>"SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
</code>```

after

and also you can use && or and keyword

```<code> "SELECT * FROM employee_data WHERE username like '".$user_name."'
and password like '".$user_pass."'";
</code>```

and write syntax near if condition
missing rounded bracket

```<code>if(mysqli_num_rows($result) > 0) {
echo "login success";
}
else{
echo "login not success";
}
</code>```

Body:
What is physically wrong with this code.

<?php
require "conn.php";
$user_name = "1234";
$user_pass = "4321";
$mysql_qry = "SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result > 0) {
echo "login success";
}
else{
echo "login not success";
}

?>

(when I run it on the local host, there is nothing there [localhost/login.php])

Body:
you should remove ; from the query string

before

"SELECT * FROM employee_data WHERE username like '$user_name'
&& password like '$user_pass';";

after

and also you can use && or and keyword

 "SELECT * FROM employee_data WHERE username like '".$user_name."'
and password like '".$user_pass."'";

and write syntax near if condition
missing rounded bracket

if(mysqli_num_rows($result) > 0) {
echo "login success";
}
else{
echo "login not success";
}


问:
Batch / Find And Edit Lines in TXT file
I want to create a batch while which finds specific lines in a batch file and are able to edit these lines.

Example:

//TXT FILE//

```<code>ex1
ex2
ex3
ex4
</code>```

i want to let the batch file find 'ex3' and edit this to 'ex5' to let it look like this:

```<code>ex1
ex2
ex5
ex4
</code>```

答:
You can do like this:</p>

```<code>rename %CURR_DIR%\ftp\mywish1.txt text.txt
for /f %%a in (%CURR_DIR%\ftp\text.txt) do (
if "%%a" EQU "ex3" (
echo ex5 >> %CURR_DIR%\ftp\mywish1.txt
) else (
echo %%a >> %CURR_DIR%\ftp\mywish1.txt
)
)
del %CURR_DIR%\ftp\text.txt
</code>```

Title: Batch / Find And Edit Lines in TXT file

Body:
I want to create a batch while which finds specific lines in a batch file and are able to edit these lines.

Example:

//TXT FILE//

ex1
ex2
ex3
ex4

i want to let the batch file find 'ex3' and edit this to 'ex5' to let it look like this:

ex1
ex2
ex5
ex4

Body:
You can do like this:

rename %CURR_DIR%\ftp\mywish1.txt text.txt
for /f %%a in (%CURR_DIR%\ftp\text.txt) do (
if "%%a" EQU "ex3" (
echo ex5 >> %CURR_DIR%\ftp\mywish1.txt
) else (
echo %%a >> %CURR_DIR%\ftp\mywish1.txt
)
)
del %CURR_DIR%\ftp\text.txt