问:
Maximum sub-arrays that an array can be divided into such that GCD of any two elements in different sub-arrays is always 1?
Given n, the number of array elements and arr[n], the array of numbers, it is required to find the maximum number of sub-arrays the array can be divided into such that GCD(a,b)=1 for every a and b that belong to different sub-arrays.

Eg:

```<code>5
2 3 4 5 6
Ans: 2 ----> {(2,3,4,6),(5)}
</code>```

Every other attempt to divide it further will not satisfy the conditions.

My Approach:

1. Sort the array.

2. Keep calculating the lcmof the elements.

3. Increase the counter every time the gcd of the element and lcm of elements before is 1.

```<code>int main()
{
        int n;
        cin>>n;
        long long int arr[n];
        for(int i=0;i<n;++i)
            cin>>arr[i];
        sort(arr,arr+n);
        long long int ans=1,l=arr[n-1];
        for(int i=n-2;i>=0;i--)
        {
            if(gcd(l,arr[i])==1)
                ans++;
            l=lcm(l,arr[i]);
        }
        cout<<ans<<endl;
    return 0;
}
</code>```

After my answer being judged wrong answer multiple times, I am confused whether my solution is correct. Since the limit for n was 10^6 and array element was 10^7, another reason the solution would have failed is that the LCM can exceed the long long limit. Is there any other solution possible? Or is there any mistake in the present approach?

答:
I think this is the problem you are referring to: https://www.codechef.com/problems/CHEFGRUP

My approach is as follows (I got Time Limit Exceeded):

Step - 1: Calculate all the primes in the range [1, 10^7].

This can be done using Sieve of Eratosthenes and the complexity will be O(nlog(log(n)) where n can be upto 10^7.

Step - 2: Use the vector of primes calculated above to find prime factorization of all the numbers in the array.

This can be implemented very efficiently once we have all the required primes.

The point to note in this step is that, suppose we have 2 numbers whose prime factorization contains common prime numbers, then these two elements cannot be in different subarrays because then GCD won't be 1 (as required in the question). Hence, for all such pairs, they will have to be in the same subarray. How to achieve this?

Step - 3: Use Disjoint Set Data Structure.

We can create a disjoint set of all the prime numbers. So the number of sets in the beginning will be the number of prime numbers. Then, during each factorization, we will join all the prime numbers that is a divisor and add them all in the same group with the original number. This will be repeated for all the numbers.

Also, we will have to check once, whether some prime numbers was even required in the first place. Because before this step we just assumed that there are as many sets as the prime numbers in the range. But some might be unused. So, this can be checked by traversing a loop once and finding the number of unique representatives. This will be our answer.

My code:

```<code>#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int prime[(int)1e7+10] = {0};

struct union_find {
    std::vector <int> parent, rank;

    // Constructor to initialse 'parent' and 'rank' vector.
    union_find(int n) {
        parent = std::vector <int> (n);
        rank = std::vector <int> (n, 0);        // initialse rank vector with 0.
        for(int i = 0; i < n; i++)
            parent[i] = i;
    }

    // Find with Path Compression Heuristic.
    int find_(int a) {
        if(a == parent[a])
            return a;
        return parent[a] = find_(parent[a]);
    }

    // Union by checking rank to keep the depth of the tree as shallow as possible.
    void union_(int a, int b) {
        int aa = find_(a), bb = find_(b);
        if(rank[aa] < rank[bb])
            parent[aa] = bb;
        else
            parent[bb] = aa;
        if(rank[aa] == rank[bb])
            ++rank[aa];
    }
};

union_find ds(1e7+10);

int main() {
    int n;
    int sq = sqrt(1e7+10);
    for(int i = 4; i < 1e7+10; i += 2)
        prime[i] = 1;
    for(int i = 3; i <= sq; i += 2) {
        if(!prime[i]) {
            for(int j = i*i; j < 1e7+10; j += i)
                prime[j] = 1;
        }
    }

    vector <int> primes;
    primes.push_back(2);
    for(int i = 3; i < 1e7+10; i += 2) {
        if(!prime[i])
            primes.push_back(i);
    }

    scanf("%d", &n);
    int a[n];
    for(int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    for(int i = 0; i < n; i++) {

        int temp = a[i];
        // int sq = sqrt(temp);
        vector <int> divisors;
        for(int j = 0; j < primes.size(); j++) {
            if(primes[j] > temp)
                break;
            if(temp % primes[j] == 0) {
                divisors.push_back(primes[j]);
                while(temp % primes[j] == 0) {
                    temp /= primes[j];
                }
            }
        }
        if(temp > 2)
            divisors.push_back(temp);

        for(int i = 1; i < divisors.size(); i++)
            ds.union_(divisors[i], divisors[i-1]);
        if(divisors.size() > 0)
            ds.union_(divisors[0], a[i]);
    }

    set <int> unique;
    for(int i = 0; i < n; i++) {
        int x = ds.find_(a[i]);
        unique.insert(x);
    }

    printf("%d\n", unique.size());
    return 0;
}
</code>```

Body:
Given n, the number of array elements and arr[n], the array of numbers, it is required to find the maximum number of sub-arrays the array can be divided into such that GCD(a,b)=1 for every a and b that belong to different sub-arrays.

Eg:

5
2 3 4 5 6
Ans: 2 ----> {(2,3,4,6),(5)}

Every other attempt to divide it further will not satisfy the conditions.

My Approach:

1. Sort the array.

2. Keep calculating the lcmof the elements.

3. Increase the counter every time the gcd of the element and lcm of elements before is 1.

int main()
{
        int n;
        cin>>n;
        long long int arr[n];
        for(int i=0;i<n;++i)
            cin>>arr[i];
        sort(arr,arr+n);
        long long int ans=1,l=arr[n-1];
        for(int i=n-2;i>=0;i--)
        {
            if(gcd(l,arr[i])==1)
                ans++;
            l=lcm(l,arr[i]);
        }
        cout<<ans<<endl;
    return 0;
}

After my answer being judged wrong answer multiple times, I am confused whether my solution is correct. Since the limit for n was 10^6 and array element was 10^7, another reason the solution would have failed is that the LCM can exceed the long long limit. Is there any other solution possible? Or is there any mistake in the present approach?

Body:
I think this is the problem you are referring to: https://www.codechef.com/problems/CHEFGRUP

My approach is as follows (I got Time Limit Exceeded):

Step - 1: Calculate all the primes in the range [1, 10^7].

This can be done using Sieve of Eratosthenes and the complexity will be O(nlog(log(n)) where n can be upto 10^7.

Step - 2: Use the vector of primes calculated above to find prime factorization of all the numbers in the array.

This can be implemented very efficiently once we have all the required primes.

The point to note in this step is that, suppose we have 2 numbers whose prime factorization contains common prime numbers, then these two elements cannot be in different subarrays because then GCD won't be 1 (as required in the question). Hence, for all such pairs, they will have to be in the same subarray. How to achieve this?

Step - 3: Use Disjoint Set Data Structure.

We can create a disjoint set of all the prime numbers. So the number of sets in the beginning will be the number of prime numbers. Then, during each factorization, we will join all the prime numbers that is a divisor and add them all in the same group with the original number. This will be repeated for all the numbers.

Also, we will have to check once, whether some prime numbers was even required in the first place. Because before this step we just assumed that there are as many sets as the prime numbers in the range. But some might be unused. So, this can be checked by traversing a loop once and finding the number of unique representatives. This will be our answer.

My code:

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int prime[(int)1e7+10] = {0};

struct union_find {
    std::vector <int> parent, rank;

    // Constructor to initialse 'parent' and 'rank' vector.
    union_find(int n) {
        parent = std::vector <int> (n);
        rank = std::vector <int> (n, 0);        // initialse rank vector with 0.
        for(int i = 0; i < n; i++)
            parent[i] = i;
    }

    // Find with Path Compression Heuristic.
    int find_(int a) {
        if(a == parent[a])
            return a;
        return parent[a] = find_(parent[a]);
    }

    // Union by checking rank to keep the depth of the tree as shallow as possible.
    void union_(int a, int b) {
        int aa = find_(a), bb = find_(b);
        if(rank[aa] < rank[bb])
            parent[aa] = bb;
        else
            parent[bb] = aa;
        if(rank[aa] == rank[bb])
            ++rank[aa];
    }
};

union_find ds(1e7+10);

int main() {
    int n;
    int sq = sqrt(1e7+10);
    for(int i = 4; i < 1e7+10; i += 2)
        prime[i] = 1;
    for(int i = 3; i <= sq; i += 2) {
        if(!prime[i]) {
            for(int j = i*i; j < 1e7+10; j += i)
                prime[j] = 1;
        }
    }

    vector <int> primes;
    primes.push_back(2);
    for(int i = 3; i < 1e7+10; i += 2) {
        if(!prime[i])
            primes.push_back(i);
    }

    scanf("%d", &n);
    int a[n];
    for(int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    for(int i = 0; i < n; i++) {

        int temp = a[i];
        // int sq = sqrt(temp);
        vector <int> divisors;
        for(int j = 0; j < primes.size(); j++) {
            if(primes[j] > temp)
                break;
            if(temp % primes[j] == 0) {
                divisors.push_back(primes[j]);
                while(temp % primes[j] == 0) {
                    temp /= primes[j];
                }
            }
        }
        if(temp > 2)
            divisors.push_back(temp);

        for(int i = 1; i < divisors.size(); i++)
            ds.union_(divisors[i], divisors[i-1]);
        if(divisors.size() > 0)
            ds.union_(divisors[0], a[i]);
    }

    set <int> unique;
    for(int i = 0; i < n; i++) {
        int x = ds.find_(a[i]);
        unique.insert(x);
    }

    printf("%d\n", unique.size());
    return 0;
}


来源: stackexchange

问:
Image conversion is not working by using pdfreactor

function convertToPDF() {
               console.log("convertToPDF enters");
               var pdfReactor = new PDFreactor("https://cloud.pdfreactor.com/service/rest");
               console.log("convertToPDF enters 1");
               var content = '
'+document.getElementById("right-col").innerHTML+'';
               console.log("convertToPDF enters 2");
               var config = {
                    'document': content,
                }
                pdfReactor.convert(config, function(result) {
                    console.log("convertToPDF enters 3");
                    document.getElementById("right-col").innerHTML += '';
                    document.getElementById("result").src = "data:application/pdf;base64," + result.document;
                }
}```

I need to convert html to pdf. for that I am using pdfreactor. I am able to generate pdf with body content which are actually text. but when I am trying to convert image apart from body. I am getting error.** Failed to load resource: the server responded with a status of 500 (Server Error)**. Basiclly I want to convert image to pdf.

答:
The response code 500 likely indicates that the conversion time limit was reached. The PDFreactor Cloud Service for evaluation automatically terminates conversions if they take longer than 30 seconds.
You could add an error handler in your code to get the full error message returned by the server:

```<code>pdfReactor.convert(config, function(result) {
    //success
}, function(error) {
    console.log(error)
};
</code>```

Additionally, the image element in your source document contains a relative URL. Your HTML input is a string, in this case PDFreactor requires either an absolute image URL or an absolute base URL in order to resolve relative resource URLs against. So you could either change your image URL to an absolute one or specify an absolute base URL like this:

```<code>config = {
    'document': content,
    'baseURL': 'http://myServer/'
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
function convertToPDF() {
               console.log("convertToPDF enters");
               var pdfReactor = new PDFreactor("https://cloud.pdfreactor.com/service/rest");
               console.log("convertToPDF enters 1");
               var content = '
'+document.getElementById("right-col").innerHTML+'';
               console.log("convertToPDF enters 2");
               var config = {
                    'document': content,
                }
                pdfReactor.convert(config, function(result) {
                    console.log("convertToPDF enters 3");
                    document.getElementById("right-col").innerHTML += '';
                    document.getElementById("result").src = "data:application/pdf;base64," + result.document;
                }
}

I need to convert html to pdf. for that I am using pdfreactor. I am able to generate pdf with body content which are actually text. but when I am trying to convert image apart from body. I am getting error.** Failed to load resource: the server responded with a status of 500 (Server Error)**. Basiclly I want to convert image to pdf.

Body:
The response code 500 likely indicates that the conversion time limit was reached. The PDFreactor Cloud Service for evaluation automatically terminates conversions if they take longer than 30 seconds.
You could add an error handler in your code to get the full error message returned by the server:

pdfReactor.convert(config, function(result) {
    //success
}, function(error) {
    console.log(error)
};

Additionally, the image element in your source document contains a relative URL. Your HTML input is a string, in this case PDFreactor requires either an absolute image URL or an absolute base URL in order to resolve relative resource URLs against. So you could either change your image URL to an absolute one or specify an absolute base URL like this:

config = {
    'document': content,
    'baseURL': 'http://myServer/'
}


问:
How to migrate multiple users' Access db's to one single SQLServer db
UPDATED 2010-11-25

A legacy stand-alone application (A1) is being re-created as a web application (A2).

A1 is written in Delphi 7 and uses a MS Access database to store the data. A1 has been distributed to ~1000 active users that we have no control over during the build of A2.

The database has ~50 tables, some which contain user data, some which contain template data (which does not need to be copied); 3-4 of these user tables are larger (<5000 records), the rest is  small (<100).

Once A2 is 'live', users of A1 should be able to migrate to A2. I'm looking for a comparison of scenario's to do so.

One option is to develop a stand-alone 'update' tool for these users, and have this update tool talk to the A2 database through webservices.

Another option is to allow users to upload their Access db (~15 MB) database to our server, run some kind of SSIS package (overnight, perhaps) to get this into A2 for that user, and delete the Access db afterward.

Am I missing options? Which option is 'best' (I understand this may be somewhat subjective, but hopefully the pro's and cons for the scenario's can at least be made clear).

I'll gladly make this a community wiki if so demanded.

UPDATE 2010-11-23: it has been suggested that a variant of scenario 1 would be to have the update tool/application talk directly to the production database. Is this feasible?

UPDATE 2011-11: By now, this has been taken into production. Users upload the .zip file the .mdb is in, which is unpacked and placed in a secure location. A nightly SSIS scheduled job comes along and moves the data to staging tables, which are then moved into production through SP's.

答:
I would lean toward uploading the complete database and running the conversion on the server.

In either case you need to write a conversion program.  The real questions is how much of the conversion you deploy and run on the customers' computers. I would keep that part as simple as possible, i.e. just the upload.  That way if you find any bugs or unexpected data during the conversion you can simply update the server and not need to re-deploy your conversion program.

The total amount of data you are talking about is not too large to upload, and it sounds like the majority of it would need to be uploaded in any case.

If you install a conversion program locally it would need a way to recover from a conversion that stopped part way through.  That can be a lot more complicated than simply restarting an upload of the access database.

Also you don't indicate there would be any need for the web services after the conversions are done.  The effort to put those services together, and keep them running and secure during the conversions would be far more than a simple upload application or web form.

Another factor is how quickly your customers would convert.  If some of them will run the current application for some time period you may need to update your conversion application as the server database changes over time.  If you upload the database and run the conversion on the server then only the server conversion program would need to be updated.  There would not be any risk of a customer downloading the conversion program but not running it until after the server databases were updated.

We have a similar case where we choose to run the conversion on the server.  We built a web page for the user to upload their files.  In that case there is nothing to deploy for the new application.  The only downside we found is getting the user to select the correct file.  If you use a web form for the upload you can't pre-select file name for the user because of security restrictions.  In our case we knew where the file was located but the customers did not.  We provide directions on the upload page for the users to help them out.  You could avoid this by writing a small desktop application to perform the upload for the users.

The only downside I see to writing a server based conversion is some of your template data will be uploaded that is un-needed.  That is a small amount of data anyway.

Server Pros:
 - No need to re-deploy the conversion due to bugs, unexpected data, or changes to the server database
 - Easier to secure (possibly), there is only one access point - the upload.  Of course you are accepting customer data in the form of an access database so you still can't trust anything in it.

Server Cons:
 - Upload un-needed template data

Desktop Pros:
 - ? I'm having trouble coming up with any

Desktop Cons:
 - May need multiple versions deployed

As to talking to a server database directly.  I have one application that talks to a hosted database directly to avoid creating web services.  It works OK, but if given the chance I would not take that route again.  The internet is dropped on a regular basis and the SQL Providers do not recover very well.  We have trained our clients just to try again when that happens.  We did this to avoid creating web services for our desktop application.  We just reference the IP address in the server connection string.  There is an entire list of security reasons not to take this route - we were comfortable with our security setup and possible risks.  In the end the trade off of using the desktop application with no modifications was not worth having an unstable product.

ContentLicense: CC BY-SA 2.5


问:
how to get the date from string in C#
I have a string like

```<code> string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");
</code>```

want the output only 2017-03-10

答:
Your input string "2017-03-10T07:19:28.907" doesn't match the format string "yyyy/MM/dd hh:mm:ss".

Considering your input is already in a standard format, you can use DateTime.Parse:

```<code>var firstdate = DateTime.Parse(startdatestring);
</code>```

Title: how to get the date from string in C#

Body:
I have a string like

 string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");

want the output only 2017-03-10

Body:
Your input string "2017-03-10T07:19:28.907" doesn't match the format string "yyyy/MM/dd hh:mm:ss".

Considering your input is already in a standard format, you can use DateTime.Parse:

var firstdate = DateTime.Parse(startdatestring);


问:
Executing PowerShell from Windows Task Scheduler
I am trying to execute a very simple PowerShell script from Windows Scheduled Tasks.

My PowerShell script is this:

```<code>$currentTime = (Get-Date).ToString('yyyy-MM-ddTHH.mm.ss')
$contentToDump = "JLS"
$path = "$home\Desktop\resutfile_" + $currentTime + ".txt"
Add-Content $path $contentToDump
</code>```

So it simply writes the string "JLS" to a file on my desktop with the current time as part of the name.

If I execute it using Windows PowerShell ISE it works fine. It also works fine when executing using the command prompt.

But when I hook up at Scheduled task it doesn't work. The task returns with a valid ("0x0")-result but no file is generated.

My configuration of the task is this:

```<code>Action: Start a program
Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add Arguments: -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -Command “&{c:\Users\jls\desktop\untitled2.ps1}”
Start in (optional): C:\users\jls\desktop
</code>```

The task is set to run as "me" with highest privileges and it is running locally on my machine where I am admin.

What am I missing?

答:
You need to replace the -Command with -File in your Add Arguments

```<code>Add Arguments: -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File c:\Users\jls\desktop\untitled2.ps1
</code>```

Body:
I am trying to execute a very simple PowerShell script from Windows Scheduled Tasks.

My PowerShell script is this:

$currentTime = (Get-Date).ToString('yyyy-MM-ddTHH.mm.ss')
$contentToDump = "JLS"
$path = "$home\Desktop\resutfile_" + $currentTime + ".txt"
Add-Content $path $contentToDump

So it simply writes the string "JLS" to a file on my desktop with the current time as part of the name.

If I execute it using Windows PowerShell ISE it works fine. It also works fine when executing using the command prompt.

But when I hook up at Scheduled task it doesn't work. The task returns with a valid ("0x0")-result but no file is generated.

My configuration of the task is this:

Action: Start a program
Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add Arguments: -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -Command “&{c:\Users\jls\desktop\untitled2.ps1}”
Start in (optional): C:\users\jls\desktop

The task is set to run as "me" with highest privileges and it is running locally on my machine where I am admin.

What am I missing?

Body:
You need to replace the -Command with -File in your Add Arguments

Add Arguments: -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File c:\Users\jls\desktop\untitled2.ps1


问:
Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks
I have long titles for some of my columns in my data frame, and I would like the ability to wrap the text. I know that this functionality is built into pandas, as I do:

```<code>pd.DataFrame(np.random.randn(2, 10),
    columns=['Very Long Column Title ' + str(i) for i in range(10)])
</code>```

DataFrame with wrapped column names

But if I have fewer columns, the titles will not wrap:

```<code>pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
</code>```

DataFrame does not wrap column names

I have also tried to manually insert a newline:

```<code>import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])
</code>```

But that gives the same output as above.

I've found similar for answers on this topic:

Can I set variable column widths in pandas?

will truncate column widths, but will not affect the title and will not wrap the text

Pretty printing newlines inside a string in a Pandas DataFrame

This again touches on column contents but not the title

I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.

答:
Jupyter notebooks inherit their display properties from a number of sources.  There is no property in pandas that restricts the width of the column headers because pandas is not what causes the text to wrap, it is actually the rendered HTML.

You can overwrite the default Jupyter Notebook styles to restrict the maximum width of the table headers using:

```<code>from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")
</code>```

Run this code once at the top of your notebook to set the max column width of html table headers to 120 pixels.

Body:
I have long titles for some of my columns in my data frame, and I would like the ability to wrap the text. I know that this functionality is built into pandas, as I do:

pd.DataFrame(np.random.randn(2, 10),
    columns=['Very Long Column Title ' + str(i) for i in range(10)])

DataFrame with wrapped column names

But if I have fewer columns, the titles will not wrap:

pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long Column Title ' + str(i) for i in range(2)])

DataFrame does not wrap column names

I have also tried to manually insert a newline:

import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])

But that gives the same output as above.

I've found similar for answers on this topic:

Can I set variable column widths in pandas?

will truncate column widths, but will not affect the title and will not wrap the text

Pretty printing newlines inside a string in a Pandas DataFrame

This again touches on column contents but not the title

I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.

Body:
Jupyter notebooks inherit their display properties from a number of sources.  There is no property in pandas that restricts the width of the column headers because pandas is not what causes the text to wrap, it is actually the rendered HTML.

You can overwrite the default Jupyter Notebook styles to restrict the maximum width of the table headers using:

from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")

Run this code once at the top of your notebook to set the max column width of html table headers to 120 pixels.


问:
Blocking read from file in PHP
Here is what I want expressed in bash:

```<code>while true; do
  while read $line; do
    echo "Heard: $line"
  done < fifo
done
</code>```

Here, fifo is the path to a named pipe. This will read from the fifo, but if the fifo is empty, it will block until there is something in it.

Trying a similar thing in PHP results in a busy-loop since fgets returns when there is nothing in the pipe.

答:
Add

```<code>sleep(1);
</code>```

to avoid heavy cpu usage. This is just the most simple way to avoid busy-loops. You can also look at stream_select(), which allows to specify a timeout how long the script should wait for a readable (or writeable) stream. Or you can try to change the default behaviour of fgets() for a specific stream with stream_set_blocking(). I dont know exactly (I didnt try it myself), but it seems the last one is the one you are looking for.

```<code>stream_set_blocking($stream, 1);
$r = fgets($stream);
</code>```

Title: Blocking read from file in PHP

Body:
Here is what I want expressed in bash:

while true; do
  while read $line; do
    echo "Heard: $line"
  done < fifo
done

Here, fifo is the path to a named pipe. This will read from the fifo, but if the fifo is empty, it will block until there is something in it.

Trying a similar thing in PHP results in a busy-loop since fgets returns when there is nothing in the pipe.

Body:
Add

sleep(1);

to avoid heavy cpu usage. This is just the most simple way to avoid busy-loops. You can also look at stream_select(), which allows to specify a timeout how long the script should wait for a readable (or writeable) stream. Or you can try to change the default behaviour of fgets() for a specific stream with stream_set_blocking(). I dont know exactly (I didnt try it myself), but it seems the last one is the one you are looking for.

stream_set_blocking($stream, 1);
$r = fgets($stream);


问:
Typescript, JSON: Mapping nested array always returns empty
I am new to typescript and trying to parse a JSON from a GET request which looks like this (removed some data):

```<code>{
   "currency_rate":1,
   "data":[
     {
        "mapIdfrom":"oslo_no",
        "refr":false,
        "duration":{
        "total":75300,
        "return":0,
        "departure":75300
     },
     "flyTo":"STR"
    }
   ]
}
</code>```

I am getting the "currency_rate" for example, but the "data"-array is empty.

The GET request looks like this (only relevant parts) :

```<code>[...]
api_url = 'https://api.skypicker.com/flights';
[...]
let body =  {
              flyFrom: 'OSL',
              to: 'STR',
              dateFrom: '01%252F04%252F2017',
              dateTo: '20%2F04%2F2017',
              daysInDestinationFrom: 15,
              daysInDestinationTo: 20,
              returnFrom: '01%2F04%2F2017',
              returnTo: '20%2F04%2F2017',
              typeFlight: 'oneway',
              oneforcity: 0,
              one_per_date: 0,
              passengers: 1,
              adults: 1,
              children: 0,
              infants: 0,
              flyDays: '%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D',
              onlyWorkingDays: 0,
              directFlights: 0,
              partner: 'picky',
              partner_market: 'en',
              v: 2,
              xml: 0,
              curr: 'EUR',
              locale: 'en',
              price_from: 1,
              price_to: 10000,
              dtimefrom: '00%3A00',
              dtimeto: '00%3A00',
              atimefrom: '00%3A00',
              atimeto: '00%3A00',
              returndtimefrom: '00%3A00',
              returndtimeto: '00%3A00',
              returnatimefrom: '00%3A00',
              returnatimeto: '00%3A00',
              stopoverfrom: '00%3A00',
              stopoverto: '00%3A00',
              booking_token: 'hashed%20data',
              offset: 0,
              limit: 30,
              sort: 'price',
              asc: 1
            }

let bodyString = JSON.stringify(body)

return this.http.get(`${this.api_url}?${bodyString}`)
  .map(res => <SkyPickerFlight>res.json());
</code>```

The model "SkyPickerFlight" is defined like this:

```<code>import { SkyPickerFlightData } from '../models/skyPickerFlightData';
import { Observable } from 'rxjs/Rx';

export interface SkyPickerFlightI {
  currency: string;
  data: Observable<any[]>;
}
</code>```

I have also tried replacing data: Observable<any[]> with data: Observable<SkyPickerFlightData[]>, the actual object, but also doesn't work.

Here you can get the full GET request:

```<code>https://api.skypicker.com/flights?flyFrom=OSL&to=STR&dateFrom=01%2F04%2F2017&dateTo=20%2F04%2F2017&daysInDestinationFrom=15&daysInDestinationTo=20&returnFrom=01%2F04%2F2017&returnTo=20%2F04%2F2017&typeFlight=oneway&oneforcity=0&one_per_date=0&passengers=1&adults=1&children=0&infants=0&flyDays=%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D&onlyWorkingDays=0&onlyWeekends=0&directFlights=0&partner=picky&partner_market=en&v=2&xml=0&curr=EUR&locale=en&price_from=1&price_to=10000&dtimefrom=00%3A00&dtimeto=00%3A00&atimefrom=00%3A00&atimeto=00%3A00&returndtimefrom=00%3A00&returndtimeto=00%3A00&returnatimefrom=00%3A00&returnatimeto=00%3A00&stopoverfrom=00%3A00&stopoverto=00%3A00&booking_token=hashed%20data&offset=0&limit=30&sort=price&asc=1
</code>```

I am still looking into it but it looks like the GET request is a bit funky using this.http.get(${this.api_url}?${bodyString}) actually returns:

```<code>{"connections":[],"currency":"EUR","del":0,"time":1,"search_params":{"to_type":"anywhere","flyFrom_type":"anywhere","seats":{"infants":0,"passengers":1,"adults":1,"children":0}},"ref_tasks":{},"currency_rate":1.0,"data":[],"refresh":[]}
</code>```

A different result than the GET request above. Not sure if I was clear. But trying the GET request like this (I will spare you with the long definition of the URLSearchParams) ends in a Bad Gateway error:

```<code>return this.http.get(this.api_url, {search: params})
  .map(res => res)
</code>```

---- EDIT -----
It worked after I copy-pasted the entire URL in:

```<code>return this.http.get(<URL PASTED HERE>)
  .map(res => res)
</code>```

Would still like to know how to pass the parameters in a clean way rather than pasting the entire URL in there.

答:
A section of your json response would not be an Observable.

Try:

```<code>export interface SkyPickerFlightI {
  currency: string;
  data: any[];
}
</code>```

You will get an Observable<SkyPickerFlightI> from http which would contain both currency_rate and data

ContentLicense: CC BY-SA 4.0

Body:
I am new to typescript and trying to parse a JSON from a GET request which looks like this (removed some data):

{
   "currency_rate":1,
   "data":[
     {
        "mapIdfrom":"oslo_no",
        "refr":false,
        "duration":{
        "total":75300,
        "return":0,
        "departure":75300
     },
     "flyTo":"STR"
    }
   ]
}

I am getting the "currency_rate" for example, but the "data"-array is empty.

The GET request looks like this (only relevant parts) :

[...]
api_url = 'https://api.skypicker.com/flights';
[...]
let body =  {
              flyFrom: 'OSL',
              to: 'STR',
              dateFrom: '01%252F04%252F2017',
              dateTo: '20%2F04%2F2017',
              daysInDestinationFrom: 15,
              daysInDestinationTo: 20,
              returnFrom: '01%2F04%2F2017',
              returnTo: '20%2F04%2F2017',
              typeFlight: 'oneway',
              oneforcity: 0,
              one_per_date: 0,
              passengers: 1,
              adults: 1,
              children: 0,
              infants: 0,
              flyDays: '%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D',
              onlyWorkingDays: 0,
              directFlights: 0,
              partner: 'picky',
              partner_market: 'en',
              v: 2,
              xml: 0,
              curr: 'EUR',
              locale: 'en',
              price_from: 1,
              price_to: 10000,
              dtimefrom: '00%3A00',
              dtimeto: '00%3A00',
              atimefrom: '00%3A00',
              atimeto: '00%3A00',
              returndtimefrom: '00%3A00',
              returndtimeto: '00%3A00',
              returnatimefrom: '00%3A00',
              returnatimeto: '00%3A00',
              stopoverfrom: '00%3A00',
              stopoverto: '00%3A00',
              booking_token: 'hashed%20data',
              offset: 0,
              limit: 30,
              sort: 'price',
              asc: 1
            }

let bodyString = JSON.stringify(body)

return this.http.get(`${this.api_url}?${bodyString}`)
  .map(res => <SkyPickerFlight>res.json());

The model "SkyPickerFlight" is defined like this:

import { SkyPickerFlightData } from '../models/skyPickerFlightData';
import { Observable } from 'rxjs/Rx';

export interface SkyPickerFlightI {
  currency: string;
  data: Observable<any[]>;
}

I have also tried replacing data: Observable<any[]> with data: Observable<SkyPickerFlightData[]>, the actual object, but also doesn't work.

Here you can get the full GET request:

https://api.skypicker.com/flights?flyFrom=OSL&to=STR&dateFrom=01%2F04%2F2017&dateTo=20%2F04%2F2017&daysInDestinationFrom=15&daysInDestinationTo=20&returnFrom=01%2F04%2F2017&returnTo=20%2F04%2F2017&typeFlight=oneway&oneforcity=0&one_per_date=0&passengers=1&adults=1&children=0&infants=0&flyDays=%5B0%2C1%2C2%2C3%2C4%2C5%2C6%5D&onlyWorkingDays=0&onlyWeekends=0&directFlights=0&partner=picky&partner_market=en&v=2&xml=0&curr=EUR&locale=en&price_from=1&price_to=10000&dtimefrom=00%3A00&dtimeto=00%3A00&atimefrom=00%3A00&atimeto=00%3A00&returndtimefrom=00%3A00&returndtimeto=00%3A00&returnatimefrom=00%3A00&returnatimeto=00%3A00&stopoverfrom=00%3A00&stopoverto=00%3A00&booking_token=hashed%20data&offset=0&limit=30&sort=price&asc=1

I am still looking into it but it looks like the GET request is a bit funky using this.http.get(${this.api_url}?${bodyString}) actually returns:

{"connections":[],"currency":"EUR","del":0,"time":1,"search_params":{"to_type":"anywhere","flyFrom_type":"anywhere","seats":{"infants":0,"passengers":1,"adults":1,"children":0}},"ref_tasks":{},"currency_rate":1.0,"data":[],"refresh":[]}

A different result than the GET request above. Not sure if I was clear. But trying the GET request like this (I will spare you with the long definition of the URLSearchParams) ends in a Bad Gateway error:

return this.http.get(this.api_url, {search: params})
  .map(res => res)

---- EDIT -----
It worked after I copy-pasted the entire URL in:

return this.http.get(<URL PASTED HERE>)
  .map(res => res)

Would still like to know how to pass the parameters in a clean way rather than pasting the entire URL in there.

Body:
A section of your json response would not be an Observable.

Try:

export interface SkyPickerFlightI {
  currency: string;
  data: any[];
}

You will get an Observable<SkyPickerFlightI> from http which would contain both currency_rate and data


问:
CSRF protection with a React Form, a Flask server, and Flask-WTF
TL;DR I need to protect my form from CSRF attacks and I want to use ReactJS for the frontend and Flask/Flask-WTF for the backend.

I’m refactoring a website built with Python, Flask, and Flask-WTF for forms and I want to use React for the frontend rather than Jinja2 through PyPugjs. I’m using Flask-WTF to render the forms and it takes care of the CSRF tokens and such. I know how to make a form with React but how do I get CSRF protection?

Right now my form rendering looks like this: (uses Pug)

```<code>mixin render_form(form, id='', action='Submit')
    form(method='POST', action='', id=id)
        =form.csrf_token

        each field in form
            fieldset
                if field.errors
                    each error in field.errors
                        .notification.error
                            #{error}

                #{field(placeholder=field.label.text)}

        button(type='submit') #{action}
</code>```

答:
You'll need to send the csrf token as the header X-CSRFToken when you POST the form. See their docs here: http://flask-wtf.readthedocs.io/en/stable/csrf.html#javascript-requests

Their example w/ POSTing via jQuery sets the X-CSRFToken before sending any POST/PUT/DELETE ajax requests:

```<code><script type="text/javascript">
    var csrf_token = "{{ csrf_token() }}";

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });
</script>
</code>```

Depending on what library you're using to send the form POSTs back to the server, your implementation of setting the header X-CSRFToken will be different.

Body:
TL;DR I need to protect my form from CSRF attacks and I want to use ReactJS for the frontend and Flask/Flask-WTF for the backend.

I’m refactoring a website built with Python, Flask, and Flask-WTF for forms and I want to use React for the frontend rather than Jinja2 through PyPugjs. I’m using Flask-WTF to render the forms and it takes care of the CSRF tokens and such. I know how to make a form with React but how do I get CSRF protection?

Right now my form rendering looks like this: (uses Pug)

mixin render_form(form, id='', action='Submit')
    form(method='POST', action='', id=id)
        =form.csrf_token

        each field in form
            fieldset
                if field.errors
                    each error in field.errors
                        .notification.error
                            #{error}

                #{field(placeholder=field.label.text)}

        button(type='submit') #{action}

Body:
You'll need to send the csrf token as the header X-CSRFToken when you POST the form. See their docs here: http://flask-wtf.readthedocs.io/en/stable/csrf.html#javascript-requests

Their example w/ POSTing via jQuery sets the X-CSRFToken before sending any POST/PUT/DELETE ajax requests:

<script type="text/javascript">
    var csrf_token = "{{ csrf_token() }}";

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });
</script>

Depending on what library you're using to send the form POSTs back to the server, your implementation of setting the header X-CSRFToken will be different.


问:
Display field in TCA of pages based on the previous field value
I would like to achieve that my field in TCA will be shown or hidden based on my previous field value. How can I do that? I can do it in javascript, but is possible to include a javascript in TCA?

Here user choose value:

```<code>$fields = array(
'question_field' => array(
    'label' => 'user choose',
    'config' => array(
        'type' => 'select',
        'items' => array(
        array('Yes','1'),
        array('No','0'),
        ),
    ),
)
</code>```

);

if the value is yes, i would like to display second field:

```<code>$fields = array(
'second_field' => array(
    'label' => 'second question',
    'config' => array(
        'type' => 'select',
        'items' => array(
        array('Yes','1'),
        array('No','0'),
        ),
    ),
)
</code>```

);

答:
So in your case, it will be adding this line
'displayCond' => 'FIELD:question_field:=:1',
so final solution will looks like this:

```<code>$fields = array(
'second_field' => array(
    'label' => 'second question',
    'displayCond' => 'FIELD:question_field:=:1',
    'config' => array(
        'type' => 'select',
        'items' => array(
        array('Yes','1'),
        array('No','0'),
        ),
    ),
)
</code>```

Body:
I would like to achieve that my field in TCA will be shown or hidden based on my previous field value. How can I do that? I can do it in javascript, but is possible to include a javascript in TCA?

Here user choose value:

$fields = array(
'question_field' => array(
    'label' => 'user choose',
    'config' => array(
        'type' => 'select',
        'items' => array(
        array('Yes','1'),
        array('No','0'),
        ),
    ),
)

);

if the value is yes, i would like to display second field:

$fields = array(
'second_field' => array(
    'label' => 'second question',
    'config' => array(
        'type' => 'select',
        'items' => array(
        array('Yes','1'),
        array('No','0'),
        ),
    ),
)

);

Body:
So in your case, it will be adding this line
'displayCond' => 'FIELD:question_field:=:1',
so final solution will looks like this:

$fields = array(
'second_field' => array(
    'label' => 'second question',
    'displayCond' => 'FIELD:question_field:=:1',
    'config' => array(
        'type' => 'select',
        'items' => array(
        array('Yes','1'),
        array('No','0'),
        ),
    ),
)


问:
Replacing certain combination of characters
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

```<code>string.replaceAll("[A-Z]+". ", "");
</code>```

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

答:
```<code>input.replaceAll("[A-Z]\\.\\s", "");
</code>```

[A-Z] matches an upper case character from A to Z

\. matches the dot character

\s matches any white space character

However, this will replace every character sequence that matches the pattern.
For matching a sequence at the beginning you should use

```<code>input.replaceAll("^[A-Z]\\.\\s", "");
</code>```

Body:
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

string.replaceAll("[A-Z]+". ", "");

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

Body:
input.replaceAll("[A-Z]\\.\\s", "");

[A-Z] matches an upper case character from A to Z

\. matches the dot character

\s matches any white space character

However, this will replace every character sequence that matches the pattern.
For matching a sequence at the beginning you should use

input.replaceAll("^[A-Z]\\.\\s", "");


问:
Assistance regarding model choice
Im new to &investigating Machine Learning. I have a use case & data but I am unsure of a few things, mainly how my model will run, and what model to start with. Details of the use case and questions are below. Any advice is appreciated.

My Main question is:

When basing a result on scores that are accumulated over time, is it possible to design a model to run on a continuous basis so it gives a best guess at all times, be it run on day one or 3 months into the semester?

What model should I start with? I was thinking a classifier, but ranking might be interesting also.

Use Case Details

Apprentices take a semesterized course, 4 semesters long, each 6 months in duration. Over the course of a semester, apprentices perform various operations and processes & are scored on how well they do. After each semester, the apprentices either have sufficient score to move on to semester 2, or they fail.

We are investigating building a model that will help identify apprentices who are in danger of failing, with enough time for them to receive help.

Each procedure is assigned a complexity code of simple, intermediate or advanced, and are weighted by complexity.

Regarding Features, we have the following: -

Initial interview scores

Entry Exam Scores

Total number of simple procedures each apprentice performed

Total number of intermediate procedures each apprentice performed

Total number of advanced procedures each apprentice performed

Average score for each complexity level

Demograph information (nationality, age, gender)

I am unsure of is how the model will work and when we will run it. i.e. - if we run it on day one of the semester, I assume everyone will fail as everyone has procedure scores of 0

Current plan is to run the model 2-3 months into each semester, so there is enough score data & also enough time to help any apprentices who are in danger of failing.

答:
This definitely looks like a classification model problem:

```<code>y = f(x[0],x[1], ..., x[N-1])
</code>```

where y (boolean output) = {pass, fail} and x[i] are different features.

There is a plethora of ML classification models like Naive Bayes, Neural Networks, Decision Trees, etc. which can be used depending upon the type of the data. In case you are looking for an answer which suggests a particular ML model, then I would need more data for the same. However, in general, this flow-chart can be helpful in selection of the same. You can also read about Model Selection from Andrew-Ng's CS229's 5th lecture.

Now coming back to the basic methodology, some of these features like initial interview scores, entry exam scores, etc. you already know in advance. Whereas, some of them like performance in procedures are known over the semester.

So, there is no harm in saying that the model will always predict better towards the end of each semester.

However, I can make a few suggestions to make it even better:

Instead of taking the initial procedure-scores as 0, take them as a mean/median of the past performances in other procedures by the subject-apprentice.

You can even build a sub-model to analyze the relation between procedure-scores and interview-scores as they are not completely independent. (I will explain this sentence in the later part of the answer)

However, if the semester is very first semester of the subject-apprentice, then you won't have such data already present for that apprentice. In that case, you might need to consider the average performances of other apprentices with similar profiles as the subject-apprentice. If the data-set is not very large, K Nearest Neighbors approach can be quite useful here. However, for large data-sets, KNN suffers from the curse of dimensionality.

Also, plot a graph between y and different variables x[i], so as to see the independent variation of y with respect to each variable.

Most probably (although it's just a hypotheses), y will depend more the initial variables in comparison the variables achieved later. The reason being that the later variables are not completely independent of the former variables.

My point is, if a model can be created to predict the output of a semester, then, a similar model can be created to predict just the output of the 1st procedure-test.

In the end, as the model might be heavily based on demographic factors and other things, it might not be a very successful model. For the same reason, we cannot accurately predict election results, soccer match results, etc. As they are heavily dependent upon real-time dynamic data.

For dynamic predictions based on different procedure performances, Time Series Analysis can be a bit helpful. But in any case, the final result will heavily dependent on the apprentice's continuity in motivation and performance which will become more clear towards the end of each semester.

Title: Assistance regarding model choice

Body:
This definitely looks like a classification model problem:

y = f(x[0],x[1], ..., x[N-1])

where y (boolean output) = {pass, fail} and x[i] are different features.

There is a plethora of ML classification models like Naive Bayes, Neural Networks, Decision Trees, etc. which can be used depending upon the type of the data. In case you are looking for an answer which suggests a particular ML model, then I would need more data for the same. However, in general, this flow-chart can be helpful in selection of the same. You can also read about Model Selection from Andrew-Ng's CS229's 5th lecture.

Now coming back to the basic methodology, some of these features like initial interview scores, entry exam scores, etc. you already know in advance. Whereas, some of them like performance in procedures are known over the semester.

So, there is no harm in saying that the model will always predict better towards the end of each semester.

However, I can make a few suggestions to make it even better:

Instead of taking the initial procedure-scores as 0, take them as a mean/median of the past performances in other procedures by the subject-apprentice.

You can even build a sub-model to analyze the relation between procedure-scores and interview-scores as they are not completely independent. (I will explain this sentence in the later part of the answer)

However, if the semester is very first semester of the subject-apprentice, then you won't have such data already present for that apprentice. In that case, you might need to consider the average performances of other apprentices with similar profiles as the subject-apprentice. If the data-set is not very large, K Nearest Neighbors approach can be quite useful here. However, for large data-sets, KNN suffers from the curse of dimensionality.

Also, plot a graph between y and different variables x[i], so as to see the independent variation of y with respect to each variable.

Most probably (although it's just a hypotheses), y will depend more the initial variables in comparison the variables achieved later. The reason being that the later variables are not completely independent of the former variables.

My point is, if a model can be created to predict the output of a semester, then, a similar model can be created to predict just the output of the 1st procedure-test.

In the end, as the model might be heavily based on demographic factors and other things, it might not be a very successful model. For the same reason, we cannot accurately predict election results, soccer match results, etc. As they are heavily dependent upon real-time dynamic data.

For dynamic predictions based on different procedure performances, Time Series Analysis can be a bit helpful. But in any case, the final result will heavily dependent on the apprentice's continuity in motivation and performance which will become more clear towards the end of each semester.


问:
FrameLayout Shown Above AppBarLayout
I have a simple CoordinatorLayout with a AppBarLayout and FrameLayout, but the FrameLayout contents are being displayed over the AppBarLayout regardless of the layout_behavior attribute on the FrameLayout. I've tried adding that attribute elsewhere (like on my RecyclerView), but it's the same behavior.

Here's a picture to show what I mean.

Activitiy Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:layout_scrollFlags="scroll|enterAlways"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@android:id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

Fragment Layout:

```<code><android.support.v7.widget.RecyclerView
android:id="@+id/checkins_recycler_view"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</code>```

How I add my fragment in my Activity:

```<code>final UserCheckinsFragment fragment = new UserCheckinsFragment();
    final Bundle arguments = new Bundle();
    UserCheckinsFragment.getArguments(arguments, items);
    fragment.setArguments(arguments);

    getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment,
            UserCheckinsFragment.class.getName()).commit();
</code>```

答: Hi i had the same problem and i fixed it by adding"app:layout_behavior="@string/appbar_scrolling_view_behavior"" into my layout parent which is linear layout and contain the RecylerView Layout and now it works correctly but i have an other problem that the button which is in the boutmn of the page disapear</p>

Title: FrameLayout Shown Above AppBarLayout

Body:
I have a simple CoordinatorLayout with a AppBarLayout and FrameLayout, but the FrameLayout contents are being displayed over the AppBarLayout regardless of the layout_behavior attribute on the FrameLayout. I've tried adding that attribute elsewhere (like on my RecyclerView), but it's the same behavior.

Here's a picture to show what I mean.

Activitiy Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:layout_scrollFlags="scroll|enterAlways"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@android:id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

Fragment Layout:

<android.support.v7.widget.RecyclerView
android:id="@+id/checkins_recycler_view"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

How I add my fragment in my Activity:

final UserCheckinsFragment fragment = new UserCheckinsFragment();
    final Bundle arguments = new Bundle();
    UserCheckinsFragment.getArguments(arguments, items);
    fragment.setArguments(arguments);

    getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment,
            UserCheckinsFragment.class.getName()).commit();


问:
Check if image source is equal to an image
My current code exists as:

```<code><img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
    function pictureChange(){
        if(fixedScreenimg.src == "img/homeScreen.png"){
            document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg");
        }else{
            document.getElementByID("fixedScreenimg").src="img/homeScreen.png");
        }
    }
</script>
</code>```

As  you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.

I've attempted to use getAttribute and the like.

Any pointers?

Thanks.

答:
Few errors:

ID instead of Id in getElementById function.

Two, unnecessary closing brackets inside if condition.

var elem = document.getElementById('fixedScreenimg'),
    btn = document.getElementById('btn');

function pictureChange() {
  if (elem.src == "img/homeScreen.png") {
    document.getElementById("fixedScreenimg").src = "img/fixedScreen.jpg";
  } else {
    document.getElementById("fixedScreenimg").src = "img/homeScreen.png";
  }
  console.log(elem.src);
}

btn.addEventListener('click', pictureChange);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<button id='btn'>Change src</button></code>```

Body:
My current code exists as:

As  you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.

I've attempted to use getAttribute and the like.

Any pointers?

Thanks.

Body:
Few errors:

ID instead of Id in getElementById function.

Two, unnecessary closing brackets inside if condition.

var elem = document.getElementById('fixedScreenimg'),
    btn = document.getElementById('btn');

function pictureChange() {
  if (elem.src == "img/homeScreen.png") {
    document.getElementById("fixedScreenimg").src = "img/fixedScreen.jpg";
  } else {
    document.getElementById("fixedScreenimg").src = "img/homeScreen.png";
  }
  console.log(elem.src);
}

btn.addEventListener('click', pictureChange);

<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<button id='btn'>Change src</button>


问:
How to get the name of calling bat script
I need to have my 2.bat script behaviour depending on the name of calling script.

Scenario:
2.bat is invoked from many other external scripts, which I am not entitled to change. Only 2.bat is under my thumb.

1.bat:

```<code>...
call 2.bat
</code>```

2.bat:

```<code>...here place something extracting "1.bat"...
</code>```

答:
As you cant change the calling bat there will be almost impossible to get its name if it is triggered through the cmd console (may be a memory dump could help?) as then the ProcessId will hold information only for the cmd.exe. The command prompt history could give you some information but it would be unreliable (and requires a dump to a temporary file)

If the calling bat is double clicked you can use this:

```<code> setlocal enableDelayedExpansion
for /f "tokens=2* delims= " %%a in ("%cmdcmdline%") do (
    if /i "%%~a" equ "/c" (
        for %%# in (%%~b) do (
            echo calling bat : %%~#
        )
    ) else (
        doskey /history >"%tmp%\cmd.history"
        for /f "usebackq tokens=* delims=" %%# in ("%tmp%\cmd.history") do (
            set "last_command=%%#"
        )
        echo probably this is the calling bat: !last_command!
        del /q /f "%tmp%\cmd.history"
    )
)

pause
</code>```

Body:
I need to have my 2.bat script behaviour depending on the name of calling script.

Scenario:
2.bat is invoked from many other external scripts, which I am not entitled to change. Only 2.bat is under my thumb.

1.bat:

...
call 2.bat

2.bat:

...here place something extracting "1.bat"...

Body:
As you cant change the calling bat there will be almost impossible to get its name if it is triggered through the cmd console (may be a memory dump could help?) as then the ProcessId will hold information only for the cmd.exe. The command prompt history could give you some information but it would be unreliable (and requires a dump to a temporary file)

If the calling bat is double clicked you can use this:

 setlocal enableDelayedExpansion
for /f "tokens=2* delims= " %%a in ("%cmdcmdline%") do (
    if /i "%%~a" equ "/c" (
        for %%# in (%%~b) do (
            echo calling bat : %%~#
        )
    ) else (
        doskey /history >"%tmp%\cmd.history"
        for /f "usebackq tokens=* delims=" %%# in ("%tmp%\cmd.history") do (
            set "last_command=%%#"
        )
        echo probably this is the calling bat: !last_command!
        del /q /f "%tmp%\cmd.history"
    )
)

pause


问:
What is the minimum file size of a PE file (exe) on Windows? And the minimal memory allocation?
What is the minimum file size of a PE file (exe) on Windows?
And the minimum memory allocation?

I assembled (using MASM (ml.exe) and link.exe that come with VS 10) the following code:
I can not leave out kernel32.lib and ExitProcess, if I do, the program crashes.

```<code>; Assmebly options
.386
.MODEL FLAT, STDCALL
option casemap:none

; Include Libs
includelib kernel32.lib

; Imported symbols
ExitProcess PROTO :Dword
Sleep PROTO :Dword

; Code
.CODE

start:
    invoke Sleep, 10000
    invoke ExitProcess, 0
END start
</code>```

The Sleep command is included only to be able to read the memory usage before the program ends.

Now I measure the following: The .exe file is exactly 2.5 KB in size (if I include user32.lib and MessageBoxA, it becomes 3 KB in size --> blocks?) and the application uses 136 KB RAM when it's run (Vista 32bit).

Isn't that somewhat much memory for such a simple program? Why is the exe file so large, and the RAM requirement much larger than the exe file?

Are there some minimal memory sizes? What about the file? It looks like it's organized in blocks of 0.5 KB in size, but isn't it 0.5 KB then for this shortest possible program?

Where can I read about this (except http://msdn.microsoft.com/en-us/magazine/cc301805.aspx which I will check out)?

Thanks (my first question here)

答:
This is a very good page on exactly this subject, if you haven't read it already:

http://www.phreedom.org/research/tinype/

Body:
What is the minimum file size of a PE file (exe) on Windows?
And the minimum memory allocation?

I assembled (using MASM (ml.exe) and link.exe that come with VS 10) the following code:
I can not leave out kernel32.lib and ExitProcess, if I do, the program crashes.

; Assmebly options
.386
.MODEL FLAT, STDCALL
option casemap:none

; Include Libs
includelib kernel32.lib

; Imported symbols
ExitProcess PROTO :Dword
Sleep PROTO :Dword

; Code
.CODE

start:
    invoke Sleep, 10000
    invoke ExitProcess, 0
END start

The Sleep command is included only to be able to read the memory usage before the program ends.

Now I measure the following: The .exe file is exactly 2.5 KB in size (if I include user32.lib and MessageBoxA, it becomes 3 KB in size --> blocks?) and the application uses 136 KB RAM when it's run (Vista 32bit).

Isn't that somewhat much memory for such a simple program? Why is the exe file so large, and the RAM requirement much larger than the exe file?

Are there some minimal memory sizes? What about the file? It looks like it's organized in blocks of 0.5 KB in size, but isn't it 0.5 KB then for this shortest possible program?

Where can I read about this (except http://msdn.microsoft.com/en-us/magazine/cc301805.aspx which I will check out)?

Thanks (my first question here)


问:
How to change image when checkbox checked
i have this floating image called back in my service
MyService.java

```<code>    back = new ImageView(this);
    back.setBackgroundResource(R.drawable.quick_launch_pressed_pink);
    back.setImageResource(R.drawable.back);
</code>```

i want to change the ImageResource by calling MyService on another class, but my application force closed. here is my code on MainActivity.java

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

    chb = (CheckBox) findViewById(R.id.cb);
    final MyService ms = new MyService();
    chb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkIos checked?
            if (((CheckBox) v).isChecked()) {
                ms.back.setImageResource(R.drawable.home);
            }

        }
    });

}
</code>```

答:
add two different images for checked & unchecked in drawable
create xml file checkbox_selected.xml in your drawable folder

checkbox_selected.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/remember_me_selected" />
    <item android:state_selected="true" android:drawable="@drawable/remember_me_selected" />
    <item android:state_activated="true" android:drawable="@drawable/remember_me_selected" />
    <item android:drawable="@drawable/remember_me" />
</selector>
</code>```

ImageView in url xml code

```<code>       <ImageView
            android:id="@+id/remember_checkbox_img"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="0.3"
            android:clickable="true"
            android:src="@drawable/checkbox_selected" />
</code>```

Body:
i have this floating image called back in my service
MyService.java

    back = new ImageView(this);
    back.setBackgroundResource(R.drawable.quick_launch_pressed_pink);
    back.setImageResource(R.drawable.back);

i want to change the ImageResource by calling MyService on another class, but my application force closed. here is my code on MainActivity.java

    public void addListenerOnCb() {

    chb = (CheckBox) findViewById(R.id.cb);
    final MyService ms = new MyService();
    chb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkIos checked?
            if (((CheckBox) v).isChecked()) {
                ms.back.setImageResource(R.drawable.home);
            }

        }
    });

}

Body:
add two different images for checked & unchecked in drawable
create xml file checkbox_selected.xml in your drawable folder

checkbox_selected.xml

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/remember_me_selected" />
    <item android:state_selected="true" android:drawable="@drawable/remember_me_selected" />
    <item android:state_activated="true" android:drawable="@drawable/remember_me_selected" />
    <item android:drawable="@drawable/remember_me" />
</selector>

ImageView in url xml code

       <ImageView
            android:id="@+id/remember_checkbox_img"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="0.3"
            android:clickable="true"
            android:src="@drawable/checkbox_selected" />


问:
Office 2010 - Excel issue
Today having problems with the Excel file on a Windows 7 laptop. I worked with this file last night without any problems.

The file was saved on a network drive and during saving have not been received error.

When this morning I needed to open the file I got the message about error.
"excel cannot open the file because the file format or file extension is not valid" And also the file is showing up as having 0kb.

Tried an excel repair on the file and also opening up in another program like .docx or .txt. Is there any way of finding out what happened this file or fixing the issue.

File server is running windows 2012 R2 server. Shadow copies are available and I can restore the file to previous version, however the user did alot of work after that time.

答:
I think your file is corrupted and it may be repaired using an excel repair tool; I personally have not used the Excel version of this maker but I have used the Excel Repair Kit and password tool and they work well:

However, if the user was working for a long time Excel may have saved a copy in the users computer C:\Documents And Settings\UserName\Application Data\Microsoft\Excel\filename.xlsx.
Another thing, I use Undelete Server Edition and it has worked great for the last 5 years; every time a user saves a file it makes a copy and it stores it for the time you specify.

Title: Office 2010 - Excel issue


问:
Make an object orbit another in SceneKit
Say I have 2 nodes in my SceneKit scene.  I want one to rotate around or orbit (like a planet orbiting a star), the other node once in a certain time interval.  I know I can set up animations like so:

```<code>let anim = CABasicAnimation(keyPath: "rotation")
anim.fromValue = NSValue(scnVector4: SCNVector4(x: 0, y: 1, z: 0, w: 0))
anim.toValue = NSValue(scnVector4: SCNVector4(x: 0, y: 1, z: 0, w: Float(2 * Double.pi)))
anim.duration = 60
anim.repeatCount = .infinity
parentNode.addAnimation(aim, forKey: "spin around")
</code>```

Is there an animation for "orbiting", and a way to specify the target node?

答:
The way to do this is by using an additional (helper) SCNNode. You'll use the fact that it adds its own coordinate system and that all of its Child Nodes will move together with that (helper) coordinate system. The child nodes that are off-centre will effectively be orbiting if you view them from the world coordinate system.

You add the HelperNode at the centre of your FixedPlanetNode (orbited planet), perhaps as its child, but definitely at the same position

You add your OrbitingPlanetNode as a child to the HelperNode, but with an offset on one of the axes, e.g. 10 points on the X axis

You start the HelperNode rotating (together with its coordinate system) around a different axis, e.g. the Y axis

This will result in the OrbitingPlanetNode orbiting around the Y axis of HelperNode with an orbit radius of 10 points.

EXAMPLE

earthNode - fixed orbited planet

moonNode - orbiting planet

helperNode - helper node added to provide coordinate system

```<code>// assuming all planet geometry is at the centre of corresponding nodes
// also helperNode.position is set to (0, 0, 0)
[earthNode addChildNode:helperNode];
moonNode.position = SCNVector3Make(10, 0, 0);
[helperNode addChildNode:moonNode];

// set helperNode to rotate forever
SCNAction * rotation = [SCNAction rotateByX:0 y:3 z:0];
SCNAction * infiniteRotation = [SCNAction repeatActionForever:rotation];
[helperNode runAction:infiniteRotation];
</code>```

I used actions and objective-c as this is what I am familiar with, but should be perfectly doable in Swift and with animations.

Body:
Say I have 2 nodes in my SceneKit scene.  I want one to rotate around or orbit (like a planet orbiting a star), the other node once in a certain time interval.  I know I can set up animations like so:

let anim = CABasicAnimation(keyPath: "rotation")
anim.fromValue = NSValue(scnVector4: SCNVector4(x: 0, y: 1, z: 0, w: 0))
anim.toValue = NSValue(scnVector4: SCNVector4(x: 0, y: 1, z: 0, w: Float(2 * Double.pi)))
anim.duration = 60
anim.repeatCount = .infinity
parentNode.addAnimation(aim, forKey: "spin around")

Is there an animation for "orbiting", and a way to specify the target node?

Body:
The way to do this is by using an additional (helper) SCNNode. You'll use the fact that it adds its own coordinate system and that all of its Child Nodes will move together with that (helper) coordinate system. The child nodes that are off-centre will effectively be orbiting if you view them from the world coordinate system.

You add the HelperNode at the centre of your FixedPlanetNode (orbited planet), perhaps as its child, but definitely at the same position

You add your OrbitingPlanetNode as a child to the HelperNode, but with an offset on one of the axes, e.g. 10 points on the X axis

You start the HelperNode rotating (together with its coordinate system) around a different axis, e.g. the Y axis

This will result in the OrbitingPlanetNode orbiting around the Y axis of HelperNode with an orbit radius of 10 points.

EXAMPLE

earthNode - fixed orbited planet

moonNode - orbiting planet

helperNode - helper node added to provide coordinate system

// assuming all planet geometry is at the centre of corresponding nodes
// also helperNode.position is set to (0, 0, 0)
[earthNode addChildNode:helperNode];
moonNode.position = SCNVector3Make(10, 0, 0);
[helperNode addChildNode:moonNode];

// set helperNode to rotate forever
SCNAction * rotation = [SCNAction rotateByX:0 y:3 z:0];
SCNAction * infiniteRotation = [SCNAction repeatActionForever:rotation];
[helperNode runAction:infiniteRotation];

I used actions and objective-c as this is what I am familiar with, but should be perfectly doable in Swift and with animations.


问:
Cannot build Linphone android with different package name
I am trying to build Linphone android from this, with SDK api 23 and NDK r11c on Ubuntu 16.10. I already built it successfully but I cannot change its package name so as to be able to upload it to Google Play Store despite following its instruction to the letter. For Example:

To create an apk with a different package name

You need to edit the custom_rules.xml file:

look for the property named "linphone.package.name" and change it value accordingly

Already done:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="custom_rules">
    <property name="linphone.package.name" value="my.name" />
....
</code>```

Then I did this

also update the values in the AndroidManifest file where the comment appears

by replacing all instances of org.linphone in every  comment. All of them are comments though so that may be not important. I did not change this one because it will throw an error when I run make

```<code> <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="org.linphone"
        android:installLocation="auto"
        android:versionCode="3253"
        android:versionName="3.2.5">
</code>```

And the next step is

change the package name also in the files: res/xml/syncadapter.xml, res/xml/contacts.xml and res/values/non_localizable_custom where appears

which I did exactly like I was told. The last step is running make.

But the result I always get is org.linphone no matter whichever name I changed  it to. Did I botched any step? Can we even change linphone package name to something other than org.linphone? And no, I cannot change its package name by this method, it would just brick the project, render it unbuildable.

答:
Now the package name are in build.gradle and no more in custom_rules.xml

```<code>def getPackageName() {
  return "org.linphone"
}
</code>```

and its used here:

```<code>defaultConfig {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"
    applicationId getPackageName()
    multiDexEnabled true
}
</code>```

Body:
I am trying to build Linphone android from this, with SDK api 23 and NDK r11c on Ubuntu 16.10. I already built it successfully but I cannot change its package name so as to be able to upload it to Google Play Store despite following its instruction to the letter. For Example:

To create an apk with a different package name

You need to edit the custom_rules.xml file:

look for the property named "linphone.package.name" and change it value accordingly

Already done:

<?xml version="1.0" encoding="UTF-8"?>
<project name="custom_rules">
    <property name="linphone.package.name" value="my.name" />
....

Then I did this

also update the values in the AndroidManifest file where the comment appears

by replacing all instances of org.linphone in every  comment. All of them are comments though so that may be not important. I did not change this one because it will throw an error when I run make

 <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="org.linphone"
        android:installLocation="auto"
        android:versionCode="3253"
        android:versionName="3.2.5">

And the next step is

change the package name also in the files: res/xml/syncadapter.xml, res/xml/contacts.xml and res/values/non_localizable_custom where appears

which I did exactly like I was told. The last step is running make.

But the result I always get is org.linphone no matter whichever name I changed  it to. Did I botched any step? Can we even change linphone package name to something other than org.linphone? And no, I cannot change its package name by this method, it would just brick the project, render it unbuildable.

Body:
Now the package name are in build.gradle and no more in custom_rules.xml

def getPackageName() {
  return "org.linphone"
}

and its used here:

defaultConfig {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"
    applicationId getPackageName()
    multiDexEnabled true
}


问:
How do I setup DB2 Express-C Data Federation for a Sybase data source?
I wish to make fields in a remote public Sybase database outlined at http://www.informatics.jax.org/software.shtml#sql appear locally in our DB2 project's schema. To do this, I was going to use data federation, however I can't seem to be able to install the data source library (Sybase-specific file libdb2ctlib.so for Linux) because only DB2 and Infomatix work OOTB with DB2 Express-C v9.5 (which is the version we're currently running, I also tried the latest V9.7.)

From unclear IBM documentation and forum posts, the best I can gather is we need to spend $675 on http://www-01.ibm.com/software/data/infosphere/federation-server/ to get support for Sybase but budget-wise that's a bit out of the question.

So is there a free method using previous tool versions (as it seems DB2 Information Integrator was rebranded as InfoSphere Federation Server) to setup DB2 data wrappers for Sybase? Alternatively, is there another non-MySQL approach we can use, such as switching our local DBMS from DB2 to PostgreSQL? Does the latter support data integration/federation?

答:
Derek, there are several ways in which one can create a federated database. One is by using the federated database capability that is built in to DB2 Express-C. However, DB2 Express-C can only federate data from specific data sources i.e. other DB2 databases and industry standard web services. To add Sybase to this list you must purchase IBM Federation Server product.
The other way is to leverage DB2 capability to create User Defined Functions in DB2 Express-C that use OLE DB API to access other data sources. Because OLE DB is a Windows-based technology, only DB2 servers running on Windows can do that. What you do is create a table UDF that you can then use anywhere you would expect to see a table result set e.g view definition. For example, you could define a view that uses your UDF to materialize the results. These results would come from a query (via OLE DB) of your Sybase data (or any other OLE DB compliant data source).
You can find more information here http://publib.boulder.ibm.com/infocenter/idm/v2r2/index.jsp?topic=/com.ibm.datatools.routines.doc/topics/coledb_cont.html</p>


问:
Why is my answer different every time?
I've been writing a program where you give a buyer company ID and product ID to a program and it'll give you the price based on company exclusive discounts and a few other discounts.

However, every time I test it (with the same inputs), I get a completely different answer, usually hundreds of times larger than my intended answer. I'm still new to C and programming so a lot of the methods I've been using in this program I've never done before.

```<code>#include <stdio.h>

char compID[30];
double discount;
char prodID[30];
int prodAmount = 0;
double productPrice;
double tax;
double totalprice = 0;

int main() {

    char cont[2];

    printf("What is your company ID? ");
    scanf("%s", compID);

    if (strcmp(compID, "BFSC") == 0) {

        discount = 1;
        tax = 1.1;

    }

    do {

        int itemPrice;

        printf("What is the idea of the product you'd like to purchase? ");
        scanf("%s", prodID);

        if (strcmp(prodID, "FENG") == 0) {

            productPrice = 12124.50;

        }

        printf("How many? ");
        scanf("%d", &prodAmount);

        printf("Do you want to purchase another item? (y/n) ");
        scanf("%s", &cont);
    } while (cont == 'y' || cont == 'Y');

    totalprice = prodAmount*productPrice*tax*discount;
    printf("%d", &totalprice);

}
</code>```

If i put BFSC as the company ID and FENG as the product ID, the answers i'm getting are 1 million plus, rather than 13336.95.

答:
I have reviewed your code its just format specifier mistakes and there are some typecast problems you are calculating totalprice and but printing its address printf("%d", &totalprice);

and where totalprice = prodAmount(int type) * productPrice(double) * tax(double) * discount(double)

here if you will not do any type cast then it would always give some garbage data as output or integer value. please try below code this might help you

```<code>#include <stdio.h>
char compID[30];
double discount;
char prodID[30];
float prodAmount = 0;
float productPrice;
float tax;
float totalprice;
int main() {

    char cont = 0;

    printf("What is your company ID? ");
    scanf("%s",compID);

    if (strcmp(compID, "BFSC") == 0) {

            discount = 1;
            tax = 1.1;

    }

    do {

            int itemPrice;

            printf("What is the idea of the product you'd like to purchase? ");
            scanf("%s", prodID);

            if (strcmp(prodID, "FENG") == 0) {

                    productPrice = 12124.50;

            }

            printf("How many? ");
            scanf("%f",&prodAmount);

            printf("Do you want to purchase another item? (y/n) ");
            scanf(" %c", &cont);
    } while (cont == 'y' || cont == 'Y');

    totalprice = ((prodAmount * productPrice) * tax )* discount;

    printf("%0.02f\n", totalprice);

}
</code>```

Title: Why is my answer different every time?

Body:
I've been writing a program where you give a buyer company ID and product ID to a program and it'll give you the price based on company exclusive discounts and a few other discounts.

However, every time I test it (with the same inputs), I get a completely different answer, usually hundreds of times larger than my intended answer. I'm still new to C and programming so a lot of the methods I've been using in this program I've never done before.

#include <stdio.h>

char compID[30];
double discount;
char prodID[30];
int prodAmount = 0;
double productPrice;
double tax;
double totalprice = 0;

int main() {

    char cont[2];

    printf("What is your company ID? ");
    scanf("%s", compID);

    if (strcmp(compID, "BFSC") == 0) {

        discount = 1;
        tax = 1.1;

    }

    do {

        int itemPrice;

        printf("What is the idea of the product you'd like to purchase? ");
        scanf("%s", prodID);

        if (strcmp(prodID, "FENG") == 0) {

            productPrice = 12124.50;

        }

        printf("How many? ");
        scanf("%d", &prodAmount);

        printf("Do you want to purchase another item? (y/n) ");
        scanf("%s", &cont);
    } while (cont == 'y' || cont == 'Y');

    totalprice = prodAmount*productPrice*tax*discount;
    printf("%d", &totalprice);

}

If i put BFSC as the company ID and FENG as the product ID, the answers i'm getting are 1 million plus, rather than 13336.95.

Body:
I have reviewed your code its just format specifier mistakes and there are some typecast problems you are calculating totalprice and but printing its address printf("%d", &totalprice);

and where totalprice = prodAmount(int type) * productPrice(double) * tax(double) * discount(double)

here if you will not do any type cast then it would always give some garbage data as output or integer value. please try below code this might help you

#include <stdio.h>
char compID[30];
double discount;
char prodID[30];
float prodAmount = 0;
float productPrice;
float tax;
float totalprice;
int main() {

    char cont = 0;

    printf("What is your company ID? ");
    scanf("%s",compID);

    if (strcmp(compID, "BFSC") == 0) {

            discount = 1;
            tax = 1.1;

    }

    do {

            int itemPrice;

            printf("What is the idea of the product you'd like to purchase? ");
            scanf("%s", prodID);

            if (strcmp(prodID, "FENG") == 0) {

                    productPrice = 12124.50;

            }

            printf("How many? ");
            scanf("%f",&prodAmount);

            printf("Do you want to purchase another item? (y/n) ");
            scanf(" %c", &cont);
    } while (cont == 'y' || cont == 'Y');

    totalprice = ((prodAmount * productPrice) * tax )* discount;

    printf("%0.02f\n", totalprice);

}


答:
first declare what is fixedScreenimg and the brackets at the 2 statements

```<code><img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
    function pictureChange(){
        var fixedScreenimg = document.getElementById("fixedScreenimg");
        if(fixedScreenimg.src == "img/homeScreen.png"){
            fixedScreenimg.src="img/fixedScreen.jpg";
        }else{
            fixedScreenimg.src="img/homeScreen.png";
        }
    }
</script>
</code>```

Title: Check if image source is equal to an image

Body:
first declare what is fixedScreenimg and the brackets at the 2 statements

<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
    function pictureChange(){
        var fixedScreenimg = document.getElementById("fixedScreenimg");
        if(fixedScreenimg.src == "img/homeScreen.png"){
            fixedScreenimg.src="img/fixedScreen.jpg";
        }else{
            fixedScreenimg.src="img/homeScreen.png";
        }
    }
</script>


问:
.htaccess redirect to all IP's but mine
Basically, I am trying to work on the front end of a website, but I would like everyone else but myself to be redirected to a construction page if you like. I currently have:

```<code>redirect 301 /index.php http://www.domain.com/construction.php
</code>```

While this works, it works to well, I would like to be able to still see the live site myself, is it possible to exclude everyone but my IP?

Thanks again.

答:
If you have a range of IPs you want to exclude from seeing 'under construction' page you can use |

```<code>RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^127.0.0.1|212.250.141.228
RewriteRule ! construction\.html /construction.html [R]
</code>```

It is important to put the 2 last lines at the end of your .htaccess file, especially when it contains more rewriting rules.

Title: .htaccess redirect to all IP's but mine

Body:
Basically, I am trying to work on the front end of a website, but I would like everyone else but myself to be redirected to a construction page if you like. I currently have:

redirect 301 /index.php http://www.domain.com/construction.php

While this works, it works to well, I would like to be able to still see the live site myself, is it possible to exclude everyone but my IP?

Thanks again.

Body:
If you have a range of IPs you want to exclude from seeing 'under construction' page you can use |

RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^127.0.0.1|212.250.141.228
RewriteRule ! construction\.html /construction.html [R]

It is important to put the 2 last lines at the end of your .htaccess file, especially when it contains more rewriting rules.


问:
Console two line output
I have this code which output some value from array, plus - in new line under value a[i]

```<code>Console.Write(a[i] + "\n-");
</code>```

So it looks like this

```<code>a
-
</code>```

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

```<code>a
-b
-c
-d
-
</code>```

I know why this is the case but how can I return one line up after every new line \n? So I can get this

```<code>abcd
----
</code>```

答:
One liner with Linq:</p>

```<code>Console.Write(String.Concat(a) + "\n" + new String('-', a.Length));
</code>```

Title: Console two line output

Body:
I have this code which output some value from array, plus - in new line under value a[i]

Console.Write(a[i] + "\n-");

So it looks like this

a
-

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

a
-b
-c
-d
-

I know why this is the case but how can I return one line up after every new line \n? So I can get this

abcd
----

Body:
One liner with Linq:

Console.Write(String.Concat(a) + "\n" + new String('-', a.Length));


问:
Truncating all tables in a Postgres database
I regularly need to delete all the data from my PostgreSQL database before a rebuild. How would I do this directly in SQL?

At the moment I've managed to come up with a SQL statement that returns all the commands I need to execute:

```<code>SELECT 'TRUNCATE TABLE ' ||  tablename || ';' FROM pg_tables WHERE tableowner='MYUSER';
</code>```

But I can't see a way to execute them programmatically once I have them.

答:
For removing the data and preserving the table-structures in pgAdmin you can do:

Right-click database -> backup, select "Schema only"

Drop the database

Create a new database and name it like the former

Right-click the new database -> restore -> select the backup, select "Schema only"

Body:
I regularly need to delete all the data from my PostgreSQL database before a rebuild. How would I do this directly in SQL?

At the moment I've managed to come up with a SQL statement that returns all the commands I need to execute:

SELECT 'TRUNCATE TABLE ' ||  tablename || ';' FROM pg_tables WHERE tableowner='MYUSER';

But I can't see a way to execute them programmatically once I have them.


问:
How do you set PowerShell's default directory?
Is there a way to change PowerShell's default location?

How do you set PowerShell's default working directory?

答:
I had tried the above answers in Windows Server 2016 without success.

But I found this approach (it should be the same for Windows 10) working for me.

Start a PowerShell session

In the Taskbar, right-click and pin to keep a link there

Again right click the icon in taskbar and then right-click Windows PowerShell and choose Properties

Enter your preferred directory in the Start in: input field and press OK

Start from the taskbar icon

Done!

In the same Properties dialog you can also change many other settings like fonts, colors, sizes and on the Shortcut tab there via button Advanced. You can select if that PowerShell session is to be run with administrator privileges.


问:
How to get the rows of a dataframe together (selcted row bottom up)
I explain my question with an example. For example, if I am in the row number 5 (following table), how can I get the rows before 5 that have the same P_P value. The point is the row index of the selected rows should be sequential.
For example in the case of following table, I need to get only rows 3 and 4 (since between the row 1 and the rest of the rows there is row number 2 with different P_P.)
FYI, I could use for loop to do it but I want to avoid it.

Thanks

```<code>ID   Contest   P_P   Time
1      UMA      A    2015
2      DOIS     B    2016
3      DOIS     A    2016
4      UMA      A    2017
5      DOIS     A    2017
</code>```

答:
Here is a solution with rev() and rle():

```<code>tail(d, rle(rev(as.integer(d$P_P)))$lengths[1]) # with last row
head(tail(d, rle(rev(as.integer(d$P_P)))$lengths[1]), -1) # without last row
</code>```

Another solution:

We can use inverse.rle() to build a grouping variable:

```<code>r <- rle(as.character(d$P_P)) # also possible: r <- rle(as.integer(d$P_P))
r$values <- seq(r$values)
d$group <- inverse.rle(r)
i <- 5
d[d$group==d$group[i],]
</code>```

result:

```<code>#  ID Contest P_P Time group
#3  3    DOIS   A 2016     3
#4  4     UMA   A 2017     3
#5  5    DOIS   A 2017     3
</code>```

If you want a result without the row i:

```<code>subset(d[-i,], group==d$group[i])
</code>```

data:

```<code>d <- structure(list(ID = 1:5, Contest = structure(c(2L, 1L, 1L, 2L,
1L), .Label = c("DOIS", "UMA"), class = "factor"), P_P = structure(c(1L,
2L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor"), Time = c(2015L,
2016L, 2016L, 2017L, 2017L)), .Names = c("ID", "Contest", "P_P",
"Time"), class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
I explain my question with an example. For example, if I am in the row number 5 (following table), how can I get the rows before 5 that have the same P_P value. The point is the row index of the selected rows should be sequential.
For example in the case of following table, I need to get only rows 3 and 4 (since between the row 1 and the rest of the rows there is row number 2 with different P_P.)
FYI, I could use for loop to do it but I want to avoid it.

Thanks

ID   Contest   P_P   Time
1      UMA      A    2015
2      DOIS     B    2016
3      DOIS     A    2016
4      UMA      A    2017
5      DOIS     A    2017

Body:
Here is a solution with rev() and rle():

tail(d, rle(rev(as.integer(d$P_P)))$lengths[1]) # with last row
head(tail(d, rle(rev(as.integer(d$P_P)))$lengths[1]), -1) # without last row

Another solution:

We can use inverse.rle() to build a grouping variable:

r <- rle(as.character(d$P_P)) # also possible: r <- rle(as.integer(d$P_P))
r$values <- seq(r$values)
d$group <- inverse.rle(r)
i <- 5
d[d$group==d$group[i],]

result:

#  ID Contest P_P Time group
#3  3    DOIS   A 2016     3
#4  4     UMA   A 2017     3
#5  5    DOIS   A 2017     3

If you want a result without the row i:

subset(d[-i,], group==d$group[i])

data:

d <- structure(list(ID = 1:5, Contest = structure(c(2L, 1L, 1L, 2L,
1L), .Label = c("DOIS", "UMA"), class = "factor"), P_P = structure(c(1L,
2L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor"), Time = c(2015L,
2016L, 2016L, 2017L, 2017L)), .Names = c("ID", "Contest", "P_P",
"Time"), class = "data.frame", row.names = c(NA, -5L))