问:
long double (GCC specific) and __float128
I'm looking for detailed information on long double and __float128 in GCC/x86 (more out of curiosity than because of an actual problem).

Few people will probably ever need these (I've just, for the first time ever, truly needed a double), but I guess it is still worthwile (and interesting) to know what you have in your toolbox and what it's about.

In that light, please excuse my somewhat open questions:

Could someone explain the implementation rationale and intended usage of these types, also in comparison of each other? For example, are they "embarrassment implementations" because the standard allows for the type, and someone might complain if they're only just the same precision as double, or are they intended as first-class types?

Alternatively, does someone have a good, usable web reference to share? A Google search on "long double" site:gcc.gnu.org/onlinedocs didn't give me much that's truly useful.

Assuming that the common mantra "if you believe that you need double, you probably don't understand floating point" does not apply, i.e. you really need more precision than just float, and one doesn't care whether 8 or 16 bytes of memory are burnt... is it reasonable to expect that one can as well just jump to long double or __float128 instead of double without a significant performance impact?

The "extended precision" feature of Intel CPUs has historically been source of nasty surprises when values were moved between memory and registers. If actually 96 bits are stored, the long double type should eliminate this issue. On the other hand, I understand that the long double type is mutually exclusive with -mfpmath=sse, as there is no such thing as "extended precision" in SSE. __float128, on the other hand, should work just perfectly fine with SSE math (though in absence of quad precision instructions certainly not on a 1:1 instruction base). Am I right in these assumptions?

(3. and 4. can probably be figured out with some work spent on profiling and disassembling, but maybe someone else had the same thought previously and has already done that work.)

Background (this is the TL;DR part):

I initially stumbled over long double because I was looking up DBL_MAX in <float.h>, and incidentially LDBL_MAX is on the next line. "Oh look, GCC actually has 128 bit doubles, not that I need them, but... cool" was my first thought. Surprise, surprise: sizeof(long double) returns 12... wait, you mean 16?

The C and C++ standards unsurprisingly do not give a very concrete definition of the type. C99 (6.2.5 10) says that the numbers of double are a subset of long double whereas C++03 states (3.9.1 8) that long double has at least as much precision as double (which is the same thing, only worded differently). Basically, the standards leave everything to the implementation, in the same manner as with long, int, and short.

Wikipedia says that GCC uses "80-bit extended precision on x86 processors regardless of the physical storage used".

The GCC documentation states, all on the same page, that the size of the type is 96 bits because of the i386 ABI, but no more than 80 bits of precision are enabled by any option (huh? what?), also Pentium and newer processors want them being aligned as 128 bit numbers. This is the default under 64 bits and can be manually enabled under 32 bits, resulting in 32 bits of zero padding.

Time to run a test:

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

int main()
{
#ifdef  USE_FLOAT128
    typedef __float128  long_double_t;
#else
    typedef long double long_double_t;
#endif

long_double_t ld;

int* i = (int*) &ld;
i[0] = i[1] = i[2] = i[3] = 0xdeadbeef;

for(ld = 0.0000000000000001; ld < LDBL_MAX; ld *= 1.0000001)
    printf("%08x-%08x-%08x-%08x\r", i[0], i[1], i[2], i[3]);

return 0;
}
</code>```

The output, when using long double, looks somewhat like this, with the marked digits being constant, and all others eventually changing as the numbers get bigger and bigger:

```<code>5636666b-c03ef3e0-00223fd8-deadbeef
                  ^^       ^^^^^^^^
</code>```

This suggests that it is not an 80 bit number. An 80-bit number has 18 hex digits. I see 22 hex digits changing, which looks much more like a 96 bits number (24 hex digits). It also isn't a 128 bit number since 0xdeadbeef isn't touched, which is consistent with sizeof returning 12.

The output for __int128 looks like it's really just a 128 bit number. All bits eventually flip.

Compiling with -m128bit-long-double does not align long double to 128 bits with a 32-bit zero padding, as indicated by the documentation. It doesn't use __int128 either, but indeed seems to align to 128 bits, padding with the value 0x7ffdd000(?!).

Further, LDBL_MAX, seems to work as +inf for both long double and __float128. Adding or subtracting a number like 1.0E100 or 1.0E2000 to/from LDBL_MAX results in the same bit pattern.

Up to now, it was my belief that the foo_MAX constants were to hold the largest representable number that is not +inf (apparently that isn't the case?). I'm also not quite sure how an 80-bit number could conceivably act as +inf for a 128 bit value... maybe I'm just too tired at the end of the day and have done something wrong.

答:
It boils down to the difference between 4.9999999999999999999 and 5.0.

Although the range is the main difference, it is precision that is important.

These type of data will be needed in great circle calculations or coordinate mathematics that is likely to be used with GPS systems.

As the precision is much better than normal double, it means you can retain typically 18 significant digits without loosing accuracy in calculations.

Extended precision I believe uses 80 bits (used mostly in maths processors), so 128 bits will be much more accurate.

Body:
I'm looking for detailed information on long double and __float128 in GCC/x86 (more out of curiosity than because of an actual problem).

Few people will probably ever need these (I've just, for the first time ever, truly needed a double), but I guess it is still worthwile (and interesting) to know what you have in your toolbox and what it's about.

In that light, please excuse my somewhat open questions:

Could someone explain the implementation rationale and intended usage of these types, also in comparison of each other? For example, are they "embarrassment implementations" because the standard allows for the type, and someone might complain if they're only just the same precision as double, or are they intended as first-class types?

Alternatively, does someone have a good, usable web reference to share? A Google search on "long double" site:gcc.gnu.org/onlinedocs didn't give me much that's truly useful.

Assuming that the common mantra "if you believe that you need double, you probably don't understand floating point" does not apply, i.e. you really need more precision than just float, and one doesn't care whether 8 or 16 bytes of memory are burnt... is it reasonable to expect that one can as well just jump to long double or __float128 instead of double without a significant performance impact?

The "extended precision" feature of Intel CPUs has historically been source of nasty surprises when values were moved between memory and registers. If actually 96 bits are stored, the long double type should eliminate this issue. On the other hand, I understand that the long double type is mutually exclusive with -mfpmath=sse, as there is no such thing as "extended precision" in SSE. __float128, on the other hand, should work just perfectly fine with SSE math (though in absence of quad precision instructions certainly not on a 1:1 instruction base). Am I right in these assumptions?

(3. and 4. can probably be figured out with some work spent on profiling and disassembling, but maybe someone else had the same thought previously and has already done that work.)

Background (this is the TL;DR part):

I initially stumbled over long double because I was looking up DBL_MAX in <float.h>, and incidentially LDBL_MAX is on the next line. "Oh look, GCC actually has 128 bit doubles, not that I need them, but... cool" was my first thought. Surprise, surprise: sizeof(long double) returns 12... wait, you mean 16?

The C and C++ standards unsurprisingly do not give a very concrete definition of the type. C99 (6.2.5 10) says that the numbers of double are a subset of long double whereas C++03 states (3.9.1 8) that long double has at least as much precision as double (which is the same thing, only worded differently). Basically, the standards leave everything to the implementation, in the same manner as with long, int, and short.

Wikipedia says that GCC uses "80-bit extended precision on x86 processors regardless of the physical storage used".

The GCC documentation states, all on the same page, that the size of the type is 96 bits because of the i386 ABI, but no more than 80 bits of precision are enabled by any option (huh? what?), also Pentium and newer processors want them being aligned as 128 bit numbers. This is the default under 64 bits and can be manually enabled under 32 bits, resulting in 32 bits of zero padding.

Time to run a test:

#include <stdio.h>
#include <cfloat>

int main()
{
#ifdef  USE_FLOAT128
    typedef __float128  long_double_t;
#else
    typedef long double long_double_t;
#endif

long_double_t ld;

int* i = (int*) &ld;
i[0] = i[1] = i[2] = i[3] = 0xdeadbeef;

for(ld = 0.0000000000000001; ld < LDBL_MAX; ld *= 1.0000001)
    printf("%08x-%08x-%08x-%08x\r", i[0], i[1], i[2], i[3]);

return 0;
}

The output, when using long double, looks somewhat like this, with the marked digits being constant, and all others eventually changing as the numbers get bigger and bigger:

5636666b-c03ef3e0-00223fd8-deadbeef
                  ^^       ^^^^^^^^

This suggests that it is not an 80 bit number. An 80-bit number has 18 hex digits. I see 22 hex digits changing, which looks much more like a 96 bits number (24 hex digits). It also isn't a 128 bit number since 0xdeadbeef isn't touched, which is consistent with sizeof returning 12.

The output for __int128 looks like it's really just a 128 bit number. All bits eventually flip.

Compiling with -m128bit-long-double does not align long double to 128 bits with a 32-bit zero padding, as indicated by the documentation. It doesn't use __int128 either, but indeed seems to align to 128 bits, padding with the value 0x7ffdd000(?!).

Further, LDBL_MAX, seems to work as +inf for both long double and __float128. Adding or subtracting a number like 1.0E100 or 1.0E2000 to/from LDBL_MAX results in the same bit pattern.

Up to now, it was my belief that the foo_MAX constants were to hold the largest representable number that is not +inf (apparently that isn't the case?). I'm also not quite sure how an 80-bit number could conceivably act as +inf for a 128 bit value... maybe I'm just too tired at the end of the day and have done something wrong.


来源: stackexchange

问:
Send ArrayList<Float> between Activities
I have to draw a graph from the values stored in an ArrayList named "subZ" (It has 252 elements). In my main activity I store the values and then in the next activity I have to draw.

So I send it like this:

```<code>Intent change_screen = new Intent(MeasureScreenActivity.this, ResultScreenActivity.class);
//Send variables to another activity
change_screen.putExtra("standard_measurement",standard_measurement);
change_screen.putExtra("current_measurement",current_measurement);
change_screen.putExtra("subZ", subZ);
startActivity(change_screen);
//Effect of transition
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
finish();
</code>```

And in the other activity I recieve it like this:

```<code>//Store the data passed from MeasureScreenActivity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();

//Make sure that bundle is not null
if(bundle != null) {
    standard_measurement = (String) bundle.get("standard_measurement");
    current_measurement = (int) bundle.get("current_measurement");
    subZ = (ArrayList<Float>) bundle.get("subZ");
}
</code>```

My question is: Is well done in this way? Because the metod putExtra(String, ArrayList) does not exist really.

I know about other way that is cast the ArrayList to array:

```<code>Float aux[] = subZ.toArray();
</code>```

And use the method putExtra(String, Float[]) to send in the same way than before.

I do not know which on in the best way to do this because I do not want to saturate the main thread.

Other way that I am thinking is to draw in the main activity and then send the draw to the next activity to show it. But I do not know if it is possible.

Which one of this three options will saturate less the main thread?

答:
You can send the ArrayList with
change_screen.putStringArrayListExtra("subZ", subZ); instead of
change_screen.putExtra("subZ", subZ);

ContentLicense: CC BY-SA 3.0

Body:
I have to draw a graph from the values stored in an ArrayList named "subZ" (It has 252 elements). In my main activity I store the values and then in the next activity I have to draw.

So I send it like this:

Intent change_screen = new Intent(MeasureScreenActivity.this, ResultScreenActivity.class);
//Send variables to another activity
change_screen.putExtra("standard_measurement",standard_measurement);
change_screen.putExtra("current_measurement",current_measurement);
change_screen.putExtra("subZ", subZ);
startActivity(change_screen);
//Effect of transition
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
finish();

And in the other activity I recieve it like this:

//Store the data passed from MeasureScreenActivity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();

//Make sure that bundle is not null
if(bundle != null) {
    standard_measurement = (String) bundle.get("standard_measurement");
    current_measurement = (int) bundle.get("current_measurement");
    subZ = (ArrayList<Float>) bundle.get("subZ");
}

My question is: Is well done in this way? Because the metod putExtra(String, ArrayList) does not exist really.

I know about other way that is cast the ArrayList to array:

Float aux[] = subZ.toArray();

And use the method putExtra(String, Float[]) to send in the same way than before.

I do not know which on in the best way to do this because I do not want to saturate the main thread.

Other way that I am thinking is to draw in the main activity and then send the draw to the next activity to show it. But I do not know if it is possible.

Which one of this three options will saturate less the main thread?


问:
How to update a progress bar in a loop inside a loop inside an ajax async call inside a loop
I have an application using kendoGrid where i update selected rows after saving them to our db.

Sometimes we have 1000+ rows so i have to partition the rows in order not to bog down the application. This takes quite a long time so i wanted to display a progress bar to help users see the progress on the updates.

The problem is that the progress bar doesn't update in each iteration. As i step through using chrome debugger i can see the progress bar update. but when i run the script in real time nothing happens.

HTML

```<code><div id="progressbar-wrapper">
    <div id="progressbar-outer" style="display: table;margin: 0 auto;background-color: #FFFFFF;border: 5px solid #000000;width: 50%;height: 30px;opacity: 1;z-index: 9998">
        <div id="progressbar" style="float:left;width: 0;height: 30px;background-color:#000000;border: 0;opacity: 1;z-index: 99999">
        </div>
    </div>
    <div id="loading-animation" style="position: fixed;top: 150px;left: 0;height: 120px;width: 100%;font-size: 100px;line-height: 120px;text-align: center;color: #000000;z-index: 9999;">
        ...SAVING...<br /><small>Saving Lines</small>
    </div>
</div>
</code>```

JAVASCRIPT

```<code>var progressbar = {};
$(function () {

    progressbar = {

        /** initial progress */
        progress: 0,

        /** maximum width of progressbar */
        progress_max: 0,

        /** The inner element of the progressbar (filled box). */
        $progress_bar: $('#progressbar'),

        /** Method to set the progressbar.
         */
        set: function (num) {
            if (this.progress_max && num) {
                this.progress = num / this.progress_max * 100;
                console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);
                this.$progress_bar.width(String(this.progress) + '%');
            }
        },

        fn_wrap: function (num) {
            setTimeout(function () {
                this.set(num);
            }, 0);
        }

    };

});

var processedPartitions = 0;
var partitions = saveData.partition(30); //saveData is the selected saved rows

//Iterate through partitions
for (var i = 0; i < partitions.length; i++) {

    var urlForWindow = "/Data/Save/";
    $.ajax({
        url: urlForWindow,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(partitions[i]),
        async: true,
        complete: function () {
            processedPartitions++;
            if (processedPartitions === partitions.length) {

                //PROGRESS BAR (DOESNT WORK, Doesnt show or update the progressbar in real time) ==========================================

                //Get the full number of rows getting updated.
                var iterations = 0;
                for (var i = 0; i < partitions.length; i++) {
                    iterations = iterations + partitions[i].length;
                }

                //add total number of records to update as the iterations
                progressbar.progress_max = iterations;

                //make the progress bar visable before updating //does not show
                $("#progressbar-wrapper").css("display", "block");

                //start counter of rows updated
                var recordsUpdated = 0;

                //begin update loop
                var mainGrid = $("#mainGrid").data("kendoGrid");
                $.each(mainGrid.dataSource.data(), function () {

                    if (this.RowSelected === true) {

                        for (var i = 0; i < partitions.length; i++) {
                            for (var j = 0; j < partitions[i].length; j++) {

                                    var row = mainGrid.dataSource.getByUid(this.uid);
                                    row.set("RowSelected", "false");
                                    row.set("dirty", "false");

                                    //after update iterate recordsupdated
                                    recordsUpdated++;

                                //update the progress bar if not complete //doesnt update in realtime
                                if (iterations >= recordsUpdated) {
                                    progressbar.set(recordsUpdated);
                                }
                            }
                        }
                    }
                });

                //turn off progressbar after complete // never shows in realtime, never shown closing
                $("#progressbar-wrapper").css("display", "none");

                //Success message
                alert("Saved");
            }

        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.resonseText);
        }
    });
}
</code>```

So stepping through the code line by line, I can see that everything works. But when running in real-time. The progress bar never shows. Its like the entire page freezes.

答:
You cannot perform multiple tasks at the same time as javascript is single threaded. However HTML5 introduced web workers and i believe you can achieve your requirements with web worker so that background thread will be used for server interaction an the main thread will be spare for UI updates.

Web workers

Body:
I have an application using kendoGrid where i update selected rows after saving them to our db.

Sometimes we have 1000+ rows so i have to partition the rows in order not to bog down the application. This takes quite a long time so i wanted to display a progress bar to help users see the progress on the updates.

The problem is that the progress bar doesn't update in each iteration. As i step through using chrome debugger i can see the progress bar update. but when i run the script in real time nothing happens.

HTML

        ...SAVING...
Saving Lines

JAVASCRIPT

var progressbar = {};
$(function () {

    progressbar = {

        /** initial progress */
        progress: 0,

        /** maximum width of progressbar */
        progress_max: 0,

        /** The inner element of the progressbar (filled box). */
        $progress_bar: $('#progressbar'),

        /** Method to set the progressbar.
         */
        set: function (num) {
            if (this.progress_max && num) {
                this.progress = num / this.progress_max * 100;
                console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);
                this.$progress_bar.width(String(this.progress) + '%');
            }
        },

        fn_wrap: function (num) {
            setTimeout(function () {
                this.set(num);
            }, 0);
        }

    };

});

var processedPartitions = 0;
var partitions = saveData.partition(30); //saveData is the selected saved rows

//Iterate through partitions
for (var i = 0; i < partitions.length; i++) {

    var urlForWindow = "/Data/Save/";
    $.ajax({
        url: urlForWindow,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(partitions[i]),
        async: true,
        complete: function () {
            processedPartitions++;
            if (processedPartitions === partitions.length) {

                //PROGRESS BAR (DOESNT WORK, Doesnt show or update the progressbar in real time) ==========================================

                //Get the full number of rows getting updated.
                var iterations = 0;
                for (var i = 0; i < partitions.length; i++) {
                    iterations = iterations + partitions[i].length;
                }

                //add total number of records to update as the iterations
                progressbar.progress_max = iterations;

                //make the progress bar visable before updating //does not show
                $("#progressbar-wrapper").css("display", "block");

                //start counter of rows updated
                var recordsUpdated = 0;

                //begin update loop
                var mainGrid = $("#mainGrid").data("kendoGrid");
                $.each(mainGrid.dataSource.data(), function () {

                    if (this.RowSelected === true) {

                        for (var i = 0; i < partitions.length; i++) {
                            for (var j = 0; j < partitions[i].length; j++) {

                                    var row = mainGrid.dataSource.getByUid(this.uid);
                                    row.set("RowSelected", "false");
                                    row.set("dirty", "false");

                                    //after update iterate recordsupdated
                                    recordsUpdated++;

                                //update the progress bar if not complete //doesnt update in realtime
                                if (iterations >= recordsUpdated) {
                                    progressbar.set(recordsUpdated);
                                }
                            }
                        }
                    }
                });

                //turn off progressbar after complete // never shows in realtime, never shown closing
                $("#progressbar-wrapper").css("display", "none");

                //Success message
                alert("Saved");
            }

        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.resonseText);
        }
    });
}

So stepping through the code line by line, I can see that everything works. But when running in real-time. The progress bar never shows. Its like the entire page freezes.


问:
Get exchange rate on a specific date from GoogleFinance
I'm having trouble stopping the googlefinance function on a specific date to use "that" specific exchange rate to convert currency from GBP to EUR.

Here is my formulae: =Finance!B4*GOOGLEFINANCE("CURRENCY:GBPEUR","price",date(2017,15,11))

Here is the error: When evaluating GOOGLEFINANCE, the query for the symbol: 'CURRENCY:GBPEUR' returned no data.

I've looked at other solutions on SO but none to avail. I've actually added "date" and "price" to my formulae from other solutions. Like so:- Solution 1

答:
First of all, date(2017,15,11) means the 11th day of 15th month of the year, so you'll need to swap the month and day.

Secondly, historical data queries, such as

```<code>=GOOGLEFINANCE("CURRENCY:GBPEUR", "price", date(2017,11,15))
</code>```

return a table with columns and headers.

```<code>Date                Close
11/15/2017 23:58:00 1.1163
</code>```

From the way you use this formula, I see you just want the exchange rate. Wrap the function in index(..., 2, 2) to get the second cell in second row.

```<code>=index(GOOGLEFINANCE("CURRENCY:GBPEUR", "price", date(2017,11,15)), 2, 2)
</code>```

Body:
First of all, date(2017,15,11) means the 11th day of 15th month of the year, so you'll need to swap the month and day.

Secondly, historical data queries, such as

=GOOGLEFINANCE("CURRENCY:GBPEUR", "price", date(2017,11,15))

return a table with columns and headers.

Date                Close
11/15/2017 23:58:00 1.1163

From the way you use this formula, I see you just want the exchange rate. Wrap the function in index(..., 2, 2) to get the second cell in second row.

=index(GOOGLEFINANCE("CURRENCY:GBPEUR", "price", date(2017,11,15)), 2, 2)


问:
Is it possible to automatically open Google Chrome devtools?
Given that Selenium 2 closes the devtools window which contains my emulator profile saved under my user profile for chrome. Is there a way to trigger devtools to open using a selenium script?

Here is the info on the devtools window closing issue
https://sites.google.com/a/chromium.org/chromedriver/help/devtools-window-keeps-closing

I feel a little exhausted trying some of these Chromium override parameters only one of which seems to work
http://peter.sh/experiments/chromium-command-line-switches/

The one that had any affect is the following

```<code>options.addArguments("user-data-dir=/Path/to/chrome/profile");
</code>```

If there is no way to open the dev tools window or panel, is there a way to initialize the emulator?

答:
at the terminal, type the following -</p>

```<code>/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --auto-open-devtools-for-tabs
</code>```

Body:
Given that Selenium 2 closes the devtools window which contains my emulator profile saved under my user profile for chrome. Is there a way to trigger devtools to open using a selenium script?

Here is the info on the devtools window closing issue
https://sites.google.com/a/chromium.org/chromedriver/help/devtools-window-keeps-closing

I feel a little exhausted trying some of these Chromium override parameters only one of which seems to work
http://peter.sh/experiments/chromium-command-line-switches/

The one that had any affect is the following

options.addArguments("user-data-dir=/Path/to/chrome/profile");

If there is no way to open the dev tools window or panel, is there a way to initialize the emulator?

Body:
at the terminal, type the following -

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --auto-open-devtools-for-tabs


问:
Category and Subcategories MySQL
i have 3 tables:

```<code>CREATE TABLE student
(ID INT PRIMARYKEY NOT NULL)

CREATE TABLE classA
(ID INT PRIMARYKEY NOT NULL)

CREATE TABLE classB
(ID INT PRIMARYKEY NOT NULL)
</code>```

my main category is "student". my subcategories are students from either "classA" or "classB".

now my question is how do I implement this model in mysql? I've thought about creating an one to many relationship between student and classA and one between student and classB. Not sure if that's the best way and really realizes what i want.

i'm an major beginner and my english is pretty bad, so sorry in advance

答:
It's all about your specification :)

If a student should have many corespondents in a class table then yes you have to make one to many relationship.

A primary key in student and foreign key on the ClassA and ClassB.

Let's take a super simple example:

If a student from student table will borrow some books (an you will keep those books in ClassA table) than this is one to many relationship between student table which have one row with the student id (primary key) and classA which will have many rows with same student id (foreign key here) and the books that he borrowed :)

Hope it helps!

Title: Category and Subcategories MySQL

Body:
i have 3 tables:

CREATE TABLE student
(ID INT PRIMARYKEY NOT NULL)

CREATE TABLE classA
(ID INT PRIMARYKEY NOT NULL)

CREATE TABLE classB
(ID INT PRIMARYKEY NOT NULL)

my main category is "student". my subcategories are students from either "classA" or "classB".

now my question is how do I implement this model in mysql? I've thought about creating an one to many relationship between student and classA and one between student and classB. Not sure if that's the best way and really realizes what i want.

i'm an major beginner and my english is pretty bad, so sorry in advance


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答:
Output buffering in some circumstances is almost mandatory. With PHP as soon as you output something back to the user, headers are sent. Therefore if you get partway through processing a page and something happens that requires a header being sent you cant unless buffering is turned on. Otherwise you get the dreaded "Cannot modify header information – headers already sent".

Some will tell you you shouldn't code that way. humbug I say!

With buffers turned on your code can be more flexible.


问:
You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react
I'm trying to build my first portfolio website and got stuck in routing using react-router-dom 4.2.2 and styled-components 2.2.3.

error message: You should not use Route or withRouter() outside a Router

I also try using Link instead of NavLink but got error too(You should not use Link outside a Router)

Someone help me please.

navigationBar.js

```<code>import React, { Component } from 'react';
import { NavigationContainer, NavItem } from './navigationBar.style';

class NavigationBar extends Component {
  render() {
    return (
      <NavigationContainer>
        <NavItem to="/">Home</NavItem>
        <NavItem to="/projects">Project</NavItem>
      </NavigationContainer>
    );
  }
}

export default NavigationBar;
</code>```

navigationBar.style.js

```<code>import styled from 'styled-components';
import { Flex, Div } from 'theme/grid';
import { NavLink } from 'react-router-dom';

export const NavigationContainer = styled(Flex)`
  position: fixed;
  right: 20px;
  top: 0.5em;
  font-size: 1em;
`;
export const NavItem = styled(NavLink)`
  position: relative;
  padding-left: 10px;
  cursor: pointer;
`;
</code>```

答:
Well you're using a NavLink outside of the BrowserRouter/HashRouter (whatever you're using)

You said it yourself

You should not use Link outside a Router

Make sure that you have the structure like this

```<code>// App render or whatever
render() {
  return (
    <BrowserRouter>
       <NavigationBar />
       {`whatever else you doin'`}
    </BrowserRouter>
  );
}
</code>```

You must always render them inside a Router

Body:
I'm trying to build my first portfolio website and got stuck in routing using react-router-dom 4.2.2 and styled-components 2.2.3.

error message: You should not use Route or withRouter() outside a Router

I also try using Link instead of NavLink but got error too(You should not use Link outside a Router)

Someone help me please.

navigationBar.js

import React, { Component } from 'react';
import { NavigationContainer, NavItem } from './navigationBar.style';

class NavigationBar extends Component {
  render() {
    return (
      <NavigationContainer>
        <NavItem to="/">Home</NavItem>
        <NavItem to="/projects">Project</NavItem>
      </NavigationContainer>
    );
  }
}

export default NavigationBar;

navigationBar.style.js

import styled from 'styled-components';
import { Flex, Div } from 'theme/grid';
import { NavLink } from 'react-router-dom';

export const NavigationContainer = styled(Flex)`
  position: fixed;
  right: 20px;
  top: 0.5em;
  font-size: 1em;
`;
export const NavItem = styled(NavLink)`
  position: relative;
  padding-left: 10px;
  cursor: pointer;
`;

Body:
Well you're using a NavLink outside of the BrowserRouter/HashRouter (whatever you're using)

You said it yourself

You should not use Link outside a Router

Make sure that you have the structure like this

// App render or whatever
render() {
  return (
    <BrowserRouter>
       <NavigationBar />
       {`whatever else you doin'`}
    </BrowserRouter>
  );
}

You must always render them inside a Router


问:
React componentWillReceiveProps check not working if API responds too quick
I have a React container component which on page load dispatches an action (using the componentDidMount lifecycle method). The action calls an API, a successful API call results in the data being added to my Redux store via a reducer.

I have some other API's which require data from the response of the initial  API call. I have these in the componentWillReceiveProps lifecycle method and I'm comparing this.props against nextProps to work out whether I have the data ready to call the API's.

90% of the time this code works and the API calls inside of componentWillReceiveProps are successfully called, but the other 10% of the API's don't get called because the code inside of the if statement which compares this.props to nextProps doesn't execute.

From testing I think I've found the issue... If the initial API call returns fast enough, the very first time componentWillReceiveProps is called this.props is already populated with data from the API call rather than returning my initial state, at which point the if statement doesn't execute.

What is the best way of bulletproofing this?

```<code><Route
  path={'Content/:id'}
  component={DrillPage}
/>

class DrillPage extends Component {
  componentDidMount() {
    this.props.actions.getLoggedInUser();
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props);
    console.log(nextProps);

    // Don't fire if user isn't logged in
    if (this.props.loggedInUser.id !== nextProps.loggedInUser.id) {
      this.props.actions.isFavourite(this.props.content.id, this.props.content.type);
      this.props.actions.doIFollow([this.props.content.author.id]);
    }
  }
}

function mapStateToProps(state, ownProps) {
  return {
    contentId: ownProps.params.id,
    loggedInUser: state.loggedInUser,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Object.assign({}, contentActions, userActions), dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(DrillPage);
</code>```

答: You could make a custom middleware for Redux that calls the API on an action dispatch from your component. Then it would directly modify the state and have no dependence on the component other than the initial dispatch.</p>

Body:
I have a React container component which on page load dispatches an action (using the componentDidMount lifecycle method). The action calls an API, a successful API call results in the data being added to my Redux store via a reducer.

I have some other API's which require data from the response of the initial  API call. I have these in the componentWillReceiveProps lifecycle method and I'm comparing this.props against nextProps to work out whether I have the data ready to call the API's.

90% of the time this code works and the API calls inside of componentWillReceiveProps are successfully called, but the other 10% of the API's don't get called because the code inside of the if statement which compares this.props to nextProps doesn't execute.

From testing I think I've found the issue... If the initial API call returns fast enough, the very first time componentWillReceiveProps is called this.props is already populated with data from the API call rather than returning my initial state, at which point the if statement doesn't execute.

What is the best way of bulletproofing this?

<Route
  path={'Content/:id'}
  component={DrillPage}
/>

class DrillPage extends Component {
  componentDidMount() {
    this.props.actions.getLoggedInUser();
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props);
    console.log(nextProps);

    // Don't fire if user isn't logged in
    if (this.props.loggedInUser.id !== nextProps.loggedInUser.id) {
      this.props.actions.isFavourite(this.props.content.id, this.props.content.type);
      this.props.actions.doIFollow([this.props.content.author.id]);
    }
  }
}

function mapStateToProps(state, ownProps) {
  return {
    contentId: ownProps.params.id,
    loggedInUser: state.loggedInUser,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Object.assign({}, contentActions, userActions), dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(DrillPage);


问:
JAVA not in path although JAVA_HOME set
I have set all the requirement variables in the /etc/profile but when launching elasticsearch, it is still not find Java. How i can set the environment variable. That's my /etc/profile

```<code>PATH=$PATH:$HOME/bin
APPLICATIONS=$HOME/Applications
JAVA_HOME=$APPLICATIONS/jdk1.7.0_79
PATH=$JAVA_HOME/bin:$PATH

export APPLICATIONS
export JAVA_HOME
export PATH
</code>```

Output of commands

```<code>[root@87500e63467f Applications]# echo $PATH
/root/Applications/jdk1.7.0_79/bin:/root/Applications/jdk1.7.0_79/bin:/root/Applications/jdk1.7.0_79/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/bin:/root/bin
[root@87500e63467f Applications]# echo $JAVA_HOME
/root/Applications/jdk1.7.0_79
[root@87500e63467f Applications]# java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
error: "Read-only file system" setting key "vm.max_map_count"
Starting elasticsearch: which: no java in (/sbin:/usr/sbin:/bin:/usr/bin)
Could not find any executable java binary. Please install java in your PATH or set JAVA_HOME
                                                           [FAILED]
</code>```

in the error, it says that ""Starting elasticsearch: which: no java in (/sbin:/usr/sbin:/bin:/usr/bin)"", it means really java isn't in that path, but how come when I echo $PATH, it shows that the java is in the path ?

答:
Encountered the same issue while installing Elasticsearch 5 on a debian machine. That's how I installed Java 9:</p>

```<code>su -
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java9-installer
</code>```

Title: JAVA not in path although JAVA_HOME set

Body:
I have set all the requirement variables in the /etc/profile but when launching elasticsearch, it is still not find Java. How i can set the environment variable. That's my /etc/profile

PATH=$PATH:$HOME/bin
APPLICATIONS=$HOME/Applications
JAVA_HOME=$APPLICATIONS/jdk1.7.0_79
PATH=$JAVA_HOME/bin:$PATH

export APPLICATIONS
export JAVA_HOME
export PATH

Output of commands

[root@87500e63467f Applications]# echo $PATH
/root/Applications/jdk1.7.0_79/bin:/root/Applications/jdk1.7.0_79/bin:/root/Applications/jdk1.7.0_79/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/bin:/root/bin
[root@87500e63467f Applications]# echo $JAVA_HOME
/root/Applications/jdk1.7.0_79
[root@87500e63467f Applications]# java -version
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
error: "Read-only file system" setting key "vm.max_map_count"
Starting elasticsearch: which: no java in (/sbin:/usr/sbin:/bin:/usr/bin)
Could not find any executable java binary. Please install java in your PATH or set JAVA_HOME
                                                           [FAILED]

in the error, it says that ""Starting elasticsearch: which: no java in (/sbin:/usr/sbin:/bin:/usr/bin)"", it means really java isn't in that path, but how come when I echo $PATH, it shows that the java is in the path ?

Body:
Encountered the same issue while installing Elasticsearch 5 on a debian machine. That's how I installed Java 9:

su -
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee /etc/apt/sources.list.d/webupd8team-java.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu xenial main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
apt-get install oracle-java9-installer


问:
How to change ChartJS font size with javascript?
I have an array of charts on the page called charts. This is the code I tried to run to make the font change:

```<code>for(var x in charts){
    charts[x].options.scales.yAxes[0].ticks.fontSize = 20;
    charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
    charts[x].update();
}
</code>```

I know that I am correctly reaching the fontSize attribute because in the console it returns the right font size to me. After I change the fontSize, it returns the correct one. For some reason, however, the actual charts aren't updating. Is the chart.update command only made for updating data?

Note: This question is not a duplicate of the other question that exists about dynamically updating charts with JS because the ChartJS version I am using is 2.7.

答:
In ChartJS version 2.7.0 or later, changing (dynamically) the font-size of chart axis' ticks by just setting the fontSize property of ticks won't actually apply to the chart. It will only add empty spaces for newly set font-size to the axis'.

In order to change the font-size of chart axis' ticks properly (which would apply to the chart), you will need to set fontSize property for the minor object (under ticks) , like so :

```<code>for (var x in charts) {
   // set/change the actual font-size
   charts[x].options.scales.xAxes[0].ticks.minor.fontSize = 20;
   charts[x].options.scales.yAxes[0].ticks.minor.fontSize = 20;

   // set proper spacing for resized font
   charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
   charts[x].options.scales.yAxes[0].ticks.fontSize = 20;

   // update chart to apply new font-size
   charts[x].update();
}
</code>```

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var myChart1 = new Chart(ctx1, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'Profit',
         data: [30, 10, 40, 20, 50],
         backgroundColor: 'rgba(61, 208, 239, 0.2)',
         borderColor: 'rgba(61, 208, 239, 0.6)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

var myChart2 = new Chart(ctx2, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'Loss',
         data: [50, 20, 40, 10, 30],
         backgroundColor: 'rgba(239, 92, 61, 0.2)',
         borderColor: 'rgba(239, 92, 61, 0.6)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

var charts = [myChart1, myChart2];

function changeFontSize() {
   for (var x in charts) {
      // set/change the font-size
      charts[x].options.scales.xAxes[0].ticks.minor.fontSize = 20;
      charts[x].options.scales.yAxes[0].ticks.minor.fontSize = 20;

      // set proper spacing for resized font
      charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
      charts[x].options.scales.yAxes[0].ticks.fontSize = 20;

      // update chart to apply new font-size
      charts[x].update();
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>

<button onclick="changeFontSize();">Change Font Size</button>
<canvas id="ctx1"></canvas>
<canvas id="ctx2"></canvas></code>```

Body:
I have an array of charts on the page called charts. This is the code I tried to run to make the font change:

for(var x in charts){
    charts[x].options.scales.yAxes[0].ticks.fontSize = 20;
    charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
    charts[x].update();
}

I know that I am correctly reaching the fontSize attribute because in the console it returns the right font size to me. After I change the fontSize, it returns the correct one. For some reason, however, the actual charts aren't updating. Is the chart.update command only made for updating data?

Note: This question is not a duplicate of the other question that exists about dynamically updating charts with JS because the ChartJS version I am using is 2.7.

Body:
In ChartJS version 2.7.0 or later, changing (dynamically) the font-size of chart axis' ticks by just setting the fontSize property of ticks won't actually apply to the chart. It will only add empty spaces for newly set font-size to the axis'.

In order to change the font-size of chart axis' ticks properly (which would apply to the chart), you will need to set fontSize property for the minor object (under ticks) , like so :

for (var x in charts) {
   // set/change the actual font-size
   charts[x].options.scales.xAxes[0].ticks.minor.fontSize = 20;
   charts[x].options.scales.yAxes[0].ticks.minor.fontSize = 20;

   // set proper spacing for resized font
   charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
   charts[x].options.scales.yAxes[0].ticks.fontSize = 20;

   // update chart to apply new font-size
   charts[x].update();
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var myChart1 = new Chart(ctx1, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'Profit',
         data: [30, 10, 40, 20, 50],
         backgroundColor: 'rgba(61, 208, 239, 0.2)',
         borderColor: 'rgba(61, 208, 239, 0.6)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

var myChart2 = new Chart(ctx2, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'Loss',
         data: [50, 20, 40, 10, 30],
         backgroundColor: 'rgba(239, 92, 61, 0.2)',
         borderColor: 'rgba(239, 92, 61, 0.6)'
      }]
   },
   options: {
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   }
});

var charts = [myChart1, myChart2];

function changeFontSize() {
   for (var x in charts) {
      // set/change the font-size
      charts[x].options.scales.xAxes[0].ticks.minor.fontSize = 20;
      charts[x].options.scales.yAxes[0].ticks.minor.fontSize = 20;

      // set proper spacing for resized font
      charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
      charts[x].options.scales.yAxes[0].ticks.fontSize = 20;

      // update chart to apply new font-size
      charts[x].update();
   }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>

<button onclick="changeFontSize();">Change Font Size</button>
<canvas id="ctx1"></canvas>
<canvas id="ctx2"></canvas>


问:
Do you have any good examples of "architecture for architecture's sake"?
Just listening to this week's podcast and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.

Java often gets a bad press in this respect, and an increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.

My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views).

答:
Oh yes !

In my last job, working on a quite large project, we had an architecture team which put in place the whole framework we used. They designed a custom ORM (circa 2000, Hibernate wasnt as ubiquitous as today) and a custom RCP framework based on Swing.

The ORM wasnt all that bad. They were just overly concerned about circular dependencies so in some cases we had a pretty bad time to express our domain model, as the business did require circular dependencies (business objects could flow both ways between different administrative units).

The Swing framework was hell. They tried to implement a component model, with something looking a bit like a hierarchical controller. It looked really good on paper : you can have component that can be reused. Model, views and controller were clearly separated. But in reality, the framework didnt provide enough flexibility, so we had to keep references to JComboBox to get the data through the abstraction layers. We had to write 4-5 classes for every little piece of UI. In some cases it took days to add a checkbox on a form. Debugging was awful as the process flow was going through 15-20 classes for every simple operation. Amazingly, performances were OK.

Worst thing, every Swing component was wrapped in an abstraction layer "in case we want to change the UI toolkit" !

OwnerDisplayName: Nick Pierpoint

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Nick Pierpoint

OwnerDisplayName: Guillaume

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Guillaume


问:
SQL select statement not printing properly
I have a MYSQL database with a select statement class that isn't working. It isn't giving me errors but it doesn't print anything but the top labels. Here is my select statement code</p>

```<code>public String selectStatement() {
    try {

        PreparedStatement select = con.prepareStatement("SELECT ? FROM nickdimfans WHERE FirstName = ?");

        select.setString(1, "*");
        select.setString(2, "'Nick'");

        ResultSet rs = select.executeQuery();

        StringBuilder selectStatement = new StringBuilder();
        selectStatement.append("ID\tFirst Name\tLast Name\tEmail\n");
        while (rs.next()) {
            selectStatement.append(rs.getInt("ID"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("FirstName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("LastName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("Email"));
            selectStatement.append("\n");
        }
        System.out.println(selectStatement);

        return selectStatement.toString();

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return "error check selectStatement";
}
</code>```

答:
You might want to check if RS is empty before printing the headers.'</p>

```<code>ResultSet rs = statement.execute();
if (rs.next()){

StringBuilder selectStatement = new StringBuilder();
        selectStatement.append("ID\tFirst Name\tLast Name\tEmail\n");
        while (rs.next()) {
            selectStatement.append(rs.getInt("ID"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("FirstName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("LastName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("Email"));
            selectStatement.append("\n");
        }
        System.out.println(selectStatement);
}
</code>```

Body:
I have a MYSQL database with a select statement class that isn't working. It isn't giving me errors but it doesn't print anything but the top labels. Here is my select statement code

public String selectStatement() {
    try {

        PreparedStatement select = con.prepareStatement("SELECT ? FROM nickdimfans WHERE FirstName = ?");

        select.setString(1, "*");
        select.setString(2, "'Nick'");

        ResultSet rs = select.executeQuery();

        StringBuilder selectStatement = new StringBuilder();
        selectStatement.append("ID\tFirst Name\tLast Name\tEmail\n");
        while (rs.next()) {
            selectStatement.append(rs.getInt("ID"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("FirstName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("LastName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("Email"));
            selectStatement.append("\n");
        }
        System.out.println(selectStatement);

        return selectStatement.toString();

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return "error check selectStatement";
}

Body:
You might want to check if RS is empty before printing the headers.'

ResultSet rs = statement.execute();
if (rs.next()){

StringBuilder selectStatement = new StringBuilder();
        selectStatement.append("ID\tFirst Name\tLast Name\tEmail\n");
        while (rs.next()) {
            selectStatement.append(rs.getInt("ID"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("FirstName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("LastName"));
            selectStatement.append("\t");
            selectStatement.append(rs.getString("Email"));
            selectStatement.append("\n");
        }
        System.out.println(selectStatement);
}


问:
getpid(), WIFSHSTOPPED(state) to check child process sleeping
Hello Im making program using 3 process P0,P1,P2
I wanna make a CYCLE like below

```<code>init: P0 P1,P2 paused, signal to P0
P0 : wake up by signal -> finish job -> signal to P3 -> pause
P1 : wake up by signal -> finish job -> signal to P2 -> pause
P2 : wake up by signal -> finish job -> signal to P3 -> pause
repeat 0~2
</code>```

Unfortunatly, SOMETIMES signal comes before target process sleep

So I wanna check target process is paused or not.
I insert [checking code] like this

```<code>//end job here here
//
int status = 0;
do {
    waitpid(target_pid, &status, WNOHANG); // WNOHANG : check child status without waiting
} while ( ! WIFSTOPPED(status));           // linux man said that WIFSTOPPED
                                           // return true if process stopped
//signal to target_pid and pause() here
</code>```

but it's not working.

if i use

```<code> while( ! WIFSTOPPED(status))
</code>```

program 100% can't get out of loop.

if I use

```<code> while(   WIFSTOPPED(status))
</code>```

It work as same as before I put [checking code]

I know that waitpid function is for checking process ends.

but CAN'T waitpid() JUST USED FOR CHECK PAUSED OR NOT?

答:
if child is completed normally( after delay got over) then you can use WIFEXITED(status), it will be true if child has exited normally.

if child got killed(using kill command from other terminal) or suspended by any signal from other process or same process then you can use WIFSIGNALED(status).

according to your requirement I modify your code as

```<code>int main()
{

        if(fork()==0) // p1
        {
                int t;
                srand(getpid());
                t = rand()%10 +1;//generating delay b/w 1 to 10 seconds
                printf("child1 delay : [%d] pid : [%d] ppid : [%d] \n",t,getpid(),getppid());
                sleep(t);
                printf("child1 pid : [%d] and its ppid : [%d] exiting \n",getpid(),getppid());
                exit(0);
        }
        else
        {
                if(fork()==0) // p2
                {
                        int t;
                        srand(getpid());
                        t = rand()%10 +1;//generating delay b/w 1 to 10 seconds
                        printf("child2 delay : [%d] pid : [%d] ppid : [%d] \n",t,getpid(),getppid());
                        sleep(t);
                        printf("child2 pid : [%d] and its ppid : [%d] exiting \n",getpid(),getppid());
                        exit(1);
                }
                else // p3
                {
                        int status;
                        printf("In parent...[%d]\n",getpid());
                        int ret;
                        while((ret = waitpid(-1,&status,0))!=-1)//when there is no child left it returns -1
                        {
                                if(WIFEXITED(&status))//if child is completed normally after sleep is over
                                {
                                        printf("child [%d] terminates normally : %d\n",ret,WEXITSTATUS(status));
                                }
                                if(WIFSIGNALED(&status))//true if child was killed by any signal from other process or same process
                                {
                                        printf("child [%d] terminates normally : %d\n",ret,WTERMSIG(status));//it will print the signal no by which it was killed
                                }
                        }
                }
        }
        return 0;
}
</code>```

there is no need to pause() because you should use pause() when one process should blocked until it is not received signal from other process.

Kindly go through man page of waitpid().

Body:
Hello Im making program using 3 process P0,P1,P2
I wanna make a CYCLE like below

init: P0 P1,P2 paused, signal to P0
P0 : wake up by signal -> finish job -> signal to P3 -> pause
P1 : wake up by signal -> finish job -> signal to P2 -> pause
P2 : wake up by signal -> finish job -> signal to P3 -> pause
repeat 0~2

Unfortunatly, SOMETIMES signal comes before target process sleep

So I wanna check target process is paused or not.
I insert [checking code] like this

//end job here here
//
int status = 0;
do {
    waitpid(target_pid, &status, WNOHANG); // WNOHANG : check child status without waiting
} while ( ! WIFSTOPPED(status));           // linux man said that WIFSTOPPED
                                           // return true if process stopped
//signal to target_pid and pause() here

but it's not working.

if i use

 while( ! WIFSTOPPED(status))

program 100% can't get out of loop.

if I use

 while(   WIFSTOPPED(status))

It work as same as before I put [checking code]

I know that waitpid function is for checking process ends.

but CAN'T waitpid() JUST USED FOR CHECK PAUSED OR NOT?

Body:
if child is completed normally( after delay got over) then you can use WIFEXITED(status), it will be true if child has exited normally.

if child got killed(using kill command from other terminal) or suspended by any signal from other process or same process then you can use WIFSIGNALED(status).

according to your requirement I modify your code as

int main()
{

        if(fork()==0) // p1
        {
                int t;
                srand(getpid());
                t = rand()%10 +1;//generating delay b/w 1 to 10 seconds
                printf("child1 delay : [%d] pid : [%d] ppid : [%d] \n",t,getpid(),getppid());
                sleep(t);
                printf("child1 pid : [%d] and its ppid : [%d] exiting \n",getpid(),getppid());
                exit(0);
        }
        else
        {
                if(fork()==0) // p2
                {
                        int t;
                        srand(getpid());
                        t = rand()%10 +1;//generating delay b/w 1 to 10 seconds
                        printf("child2 delay : [%d] pid : [%d] ppid : [%d] \n",t,getpid(),getppid());
                        sleep(t);
                        printf("child2 pid : [%d] and its ppid : [%d] exiting \n",getpid(),getppid());
                        exit(1);
                }
                else // p3
                {
                        int status;
                        printf("In parent...[%d]\n",getpid());
                        int ret;
                        while((ret = waitpid(-1,&status,0))!=-1)//when there is no child left it returns -1
                        {
                                if(WIFEXITED(&status))//if child is completed normally after sleep is over
                                {
                                        printf("child [%d] terminates normally : %d\n",ret,WEXITSTATUS(status));
                                }
                                if(WIFSIGNALED(&status))//true if child was killed by any signal from other process or same process
                                {
                                        printf("child [%d] terminates normally : %d\n",ret,WTERMSIG(status));//it will print the signal no by which it was killed
                                }
                        }
                }
        }
        return 0;
}

there is no need to pause() because you should use pause() when one process should blocked until it is not received signal from other process.

Kindly go through man page of waitpid().


问:
How to unload select2 script/styles loaded by new WooCommerce 2.3.x?
we are theme developers and we already use select2 (http://select2.github.io/) script for SELECT boxes in HTML in our wordpress theme.
New WooCommerce 2.3.x that just relased now use select2 scripts too. But they override its styles with its own (most of all with !important tags) in many different ways.

We can't redeclare all of their CSS changes with !important rules, this will be a lot of CSS mess that we don't like. Also now our JS script loaded 2 times and conflicts sometimes too (because woocommerce loads its own select2 js).

My question is what is a best way to deactivate woocommerce select2 CSS and JS files in our theme functions? We want to use our script version and our styles file (for woocommerce select elements too).

I tryed to use wp_dequeue_script, wp_deregister_script and the same functions available for styles, but this does not help. As I see woocommerce add scripts/css AFTER our theme already initialized and we can't deactivate it.

Thanks.

This is code that loaded in /includes/class-wc-frontend-scripts.php that I need to disable from theme functions:

```<code>self::register_script( 'select2', $assets_path . 'js/select2/select2' . $suffix . '.js', array( 'jquery' ), '3.5.2' );
self::enqueue_script( 'select2' );
wp_enqueue_style( 'select2', $assets_path . 'css/select2.css' );
</code>```

How to unload this CSS/JS files in theme functions, without changing original WooCommerce files?

答:
There's been some recent changes to WooCommerce (v 3.2.1) in which they forked the select2 script and so the code above by @Dmitry is no longer functional.  The new code which worked for me is below.. </p>

```<code>add_action( 'wp_enqueue_scripts', 'agentwp_dequeue_stylesandscripts', 100 );

function agentwp_dequeue_stylesandscripts() {
    if ( class_exists( 'woocommerce' ) ) {
    wp_dequeue_style( 'selectWoo' );
    wp_deregister_style( 'selectWoo' );

    wp_dequeue_script( 'selectWoo');
    wp_deregister_script('selectWoo');

   }
}
</code>```

Body:
we are theme developers and we already use select2 (http://select2.github.io/) script for SELECT boxes in HTML in our wordpress theme.
New WooCommerce 2.3.x that just relased now use select2 scripts too. But they override its styles with its own (most of all with !important tags) in many different ways.

We can't redeclare all of their CSS changes with !important rules, this will be a lot of CSS mess that we don't like. Also now our JS script loaded 2 times and conflicts sometimes too (because woocommerce loads its own select2 js).

My question is what is a best way to deactivate woocommerce select2 CSS and JS files in our theme functions? We want to use our script version and our styles file (for woocommerce select elements too).

I tryed to use wp_dequeue_script, wp_deregister_script and the same functions available for styles, but this does not help. As I see woocommerce add scripts/css AFTER our theme already initialized and we can't deactivate it.

Thanks.

This is code that loaded in /includes/class-wc-frontend-scripts.php that I need to disable from theme functions:

self::register_script( 'select2', $assets_path . 'js/select2/select2' . $suffix . '.js', array( 'jquery' ), '3.5.2' );
self::enqueue_script( 'select2' );
wp_enqueue_style( 'select2', $assets_path . 'css/select2.css' );

How to unload this CSS/JS files in theme functions, without changing original WooCommerce files?

Body:
There's been some recent changes to WooCommerce (v 3.2.1) in which they forked the select2 script and so the code above by @Dmitry is no longer functional.  The new code which worked for me is below..

add_action( 'wp_enqueue_scripts', 'agentwp_dequeue_stylesandscripts', 100 );

function agentwp_dequeue_stylesandscripts() {
    if ( class_exists( 'woocommerce' ) ) {
    wp_dequeue_style( 'selectWoo' );
    wp_deregister_style( 'selectWoo' );

    wp_dequeue_script( 'selectWoo');
    wp_deregister_script('selectWoo');

   }
}


问:
Identifying whether an integer over a certain value appears before a non-numerical char does C++
I'm wanting to read through a file and identify if a letter character appears before an integer value which is above 10. The items in the file are separated by a space and at the end of the list is an "endl;".

So far, I tried getting an array of the integers in the file (just by reading in the arrays and checking if any are above 10) and equally, I've been reading characters in through the file and checking if any are not a digit, but I can't work out how to compare the positions of a non-digit character and too-large integer that I find? Any advice would be greatly appreciated!

```<code>// i.e. sample file may contain:
1 2 3 A 6 12 90 //(in which case the letter appears first).
// example two:
34A 20 4 5 6 7 //(large number here appears first).
</code>```

答:
You don't need an array, you just need keep track of which one you encounter first.

Something like this:

Define a variable letter_first

As long a there is input:

Read one thing

If it's a letter, then it occurs before an integer > 10; set letter_first to true and break out of the loop

If it's a number greater than 10, then it occurs before a letter; set letter_first to false and break out of the loop

Otherwise, continue with the next item

Use the result

Body:
I'm wanting to read through a file and identify if a letter character appears before an integer value which is above 10. The items in the file are separated by a space and at the end of the list is an "endl;".

So far, I tried getting an array of the integers in the file (just by reading in the arrays and checking if any are above 10) and equally, I've been reading characters in through the file and checking if any are not a digit, but I can't work out how to compare the positions of a non-digit character and too-large integer that I find? Any advice would be greatly appreciated!

// i.e. sample file may contain:
1 2 3 A 6 12 90 //(in which case the letter appears first).
// example two:
34A 20 4 5 6 7 //(large number here appears first).


问:
How to escape a null character in T-SQL?
I'm using a library that doesn't support parametrized queries, so I'm trying to write a function to emulate them like this:

```<code>let params = [ String "\x00'blah" ] in
Mssql.execute ~params "SELECT $1"
</code>```

To test this, I'm sending it a string of every ASCII character, and the only two that seem to need escaping are:

' - Needs to be escaped as ''

\0' - Seems like it has to be changed to CHAR(0)

The null character part makes my escaping function ridiculously complicated because it has to keep track of whether a string is open and if it needs to add +. I could write a much simpler version that converts it to something like CODE(0)+''''+'a'+'s'+'d' but I suspect that's going to be very inefficient when sending megabytes of data to the server. My version is also going to be crazy inefficient if I send a megabyte of null characters (not that I plan to do that, but I don't like leaving time-bombs in code).

What I'm wondering is -- Is there any other way to escape these null chars?

(Also, am I missing anything? I can't find any documentation for this since everyone seems to assume you have access to a decent T-SQL library).

EDIT: It looks like null-characters should work in T-SQL, but I'm running into a limitation of the library I'm using, where it calls FreeTDS's dbcmd, which assumes the string is null-terminated, and I can't seem to find any alternative function. It looks like rewriting the library I'm using to support real parameterized queries might be the only option :\

答:
I don't know your library, but I know good library for that simple sql operations. This library is have simple methods to insert, update or delete records without write SQL command. Also support Merge command. Its mean if you don't know the record is exists or not but you want to save this.
If you want to encrypt sensitive data, also have a methods for this.

Here is example;

```<code>crypto.SetCryptoKey("DB-TEST-CUST");
dRec cust = new dRec("dbo.customer");
cust.fields["email"] = "john.lennon@gmail.com";
cust.fields["name"] = "John Lennon";
cust.fields["description"] = "John's secret world";
cust.fields["password"] = "abc123xyz".dEncryption();  //encryption text include some special characters, but methods support this.
if (cust.Insert() >= 0)
    return "record inserted";
else
    return "record error:" + db.LastException_Message;
</code>```

for more information library's web site : https://www.dbdll.com/Documentation

Body:
I'm using a library that doesn't support parametrized queries, so I'm trying to write a function to emulate them like this:

let params = [ String "\x00'blah" ] in
Mssql.execute ~params "SELECT $1"

To test this, I'm sending it a string of every ASCII character, and the only two that seem to need escaping are:

' - Needs to be escaped as ''

\0' - Seems like it has to be changed to CHAR(0)

The null character part makes my escaping function ridiculously complicated because it has to keep track of whether a string is open and if it needs to add +. I could write a much simpler version that converts it to something like CODE(0)+''''+'a'+'s'+'d' but I suspect that's going to be very inefficient when sending megabytes of data to the server. My version is also going to be crazy inefficient if I send a megabyte of null characters (not that I plan to do that, but I don't like leaving time-bombs in code).

What I'm wondering is -- Is there any other way to escape these null chars?

(Also, am I missing anything? I can't find any documentation for this since everyone seems to assume you have access to a decent T-SQL library).

EDIT: It looks like null-characters should work in T-SQL, but I'm running into a limitation of the library I'm using, where it calls FreeTDS's dbcmd, which assumes the string is null-terminated, and I can't seem to find any alternative function. It looks like rewriting the library I'm using to support real parameterized queries might be the only option :\

Body:
I don't know your library, but I know good library for that simple sql operations. This library is have simple methods to insert, update or delete records without write SQL command. Also support Merge command. Its mean if you don't know the record is exists or not but you want to save this.
If you want to encrypt sensitive data, also have a methods for this.

Here is example;

crypto.SetCryptoKey("DB-TEST-CUST");
dRec cust = new dRec("dbo.customer");
cust.fields["email"] = "john.lennon@gmail.com";
cust.fields["name"] = "John Lennon";
cust.fields["description"] = "John's secret world";
cust.fields["password"] = "abc123xyz".dEncryption();  //encryption text include some special characters, but methods support this.
if (cust.Insert() >= 0)
    return "record inserted";
else
    return "record error:" + db.LastException_Message;

for more information library's web site : https://www.dbdll.com/Documentation


问:
VBA string split in Text File
So here's the problem, I have a text file with all the information I need to input into my program (through VBA). But, there's one section I need to split, then use the second half of the split string for my program. BUT every time I run this code, I get an error stating the "subscript is out of range".

Here's the code:

```<code>Const modelList As String = "C:\modelList.txt"

Dim inFileNum As Integer
Dim strData As String
Dim strLine As Variant
Dim strSplit As Variant
Dim intCount As Integer

intFileNum = FreeFile
intCount = 0
Open modelList For Input As #intFileNum
Do Until EOF(intFileNum)
Input #intFileNum, strData
    Do Until strData = "[SPECS]"
    Input #intFileNum, strData
        Do Until strData = " "
        Input #intFileNum, strData
            strSplit = Split(strData, " ")
                For Each strLine In strSplit
                    SPECS.Value = strSplit(1)
                Next
        Loop
    Loop
Loop
Close #intFileNum
</code>```

Please help.

答:
Another approach would be checking for the upper bound of the split array.</p>

```<code>strSplit = Split(strData, " ")
For Each strLine In strSplit
    '~~~Assuming that you always want the second element, if available
    If (UBound(strSplit)) > 0 Then
        SPECS.Value = strSplit(1)
    Else
        SPECS.Value = strSplit(0)
    End If
Next
</code>```

Title: VBA string split in Text File

Body:
So here's the problem, I have a text file with all the information I need to input into my program (through VBA). But, there's one section I need to split, then use the second half of the split string for my program. BUT every time I run this code, I get an error stating the "subscript is out of range".

Here's the code:

Const modelList As String = "C:\modelList.txt"

Dim inFileNum As Integer
Dim strData As String
Dim strLine As Variant
Dim strSplit As Variant
Dim intCount As Integer

intFileNum = FreeFile
intCount = 0
Open modelList For Input As #intFileNum
Do Until EOF(intFileNum)
Input #intFileNum, strData
    Do Until strData = "[SPECS]"
    Input #intFileNum, strData
        Do Until strData = " "
        Input #intFileNum, strData
            strSplit = Split(strData, " ")
                For Each strLine In strSplit
                    SPECS.Value = strSplit(1)
                Next
        Loop
    Loop
Loop
Close #intFileNum

Please help.

Body:
Another approach would be checking for the upper bound of the split array.

strSplit = Split(strData, " ")
For Each strLine In strSplit
    '~~~Assuming that you always want the second element, if available
    If (UBound(strSplit)) > 0 Then
        SPECS.Value = strSplit(1)
    Else
        SPECS.Value = strSplit(0)
    End If
Next


问:
didUpdateToLocation not called
I  have a very complicated problem with geolocation : the didupdatetolocation delegate method is not called which I'm not understand.

this the code of the method:

```<code> - (void) locationManager:(CLLocationManager *)pLocationManager didUpdateToLocation:(CLLocation *)pNewLocation fromLocation:(CLLocation *)pOldLocation {

        lGPSAccuracy = 0;

        // Stop trace record when the GPS Signal is poor or null
        if (pNewLocation.horizontalAccuracy > GPS_POOR_SIGNAL || pNewLocation.horizontalAccuracy < 0){ return;}

        if (pNewLocation.horizontalAccuracy > pNewLocation.verticalAccuracy) {
            lGPSAccuracy = pNewLocation.horizontalAccuracy;
        } else {
            lGPSAccuracy = pNewLocation.verticalAccuracy;
        }

        if (self.delegate && [self.delegate respondsToSelector:@selector(traceRecorder:didUpdateToLocation:fromLocation:)]) {
            [self.delegate traceRecorder:self didUpdateToLocation:pNewLocation fromLocation:pOldLocation];
        }

        CLLocationCoordinate2D lUserLocation =  pNewLocation.coordinate;

        Boolean lLatitudeOK = (self.mMapSouthWest.latitude < lUserLocation.latitude) && (lUserLocation.latitude < self.mMapNorthEast.latitude);
        Boolean lLongitudeOK = (self.mMapSouthWest.longitude < lUserLocation.longitude) && (lUserLocation.longitude < self.mMapNorthEast.longitude);

        //IF USER IS OUT OF THE MAP

        if (self.delegate && [self.delegate respondsToSelector:@selector(userPositionOnMap:)]) {
            if ( (!lLatitudeOK || !lLongitudeOK) ) {
                [self.delegate userPositionOnMap:NO];
            } else {
                [self.delegate userPositionOnMap:YES];
            }
        }

        if (![self isNewLocation:pNewLocation acceptableComparedToOldLocation:pOldLocation]) {
            return;
        }

        [self treatLocation:pNewLocation];
    }
</code>```

when I read about this problem i found that this method is deprecated but it's still working on a old version of my project which is very abnormal.
Any help please.

答:
thank you @truncdug. I resolved the problem by changing the deprecated didtoupdatelocations method </p>

```<code>- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    if ([locations count]>0) {
        CLLocation *pNewLocation = [locations firstObject];
        CLLocation *pOldLocation = _currentLocation;

         _currentLocation = pNewLocation;

        lGPSAccuracy = 0;

        // Stop trace record when the GPS Signal is poor or null
        if (pNewLocation.horizontalAccuracy > GPS_POOR_SIGNAL || pNewLocation.horizontalAccuracy < 0){ return;}

        if (pNewLocation.horizontalAccuracy > pNewLocation.verticalAccuracy) {
            lGPSAccuracy = pNewLocation.horizontalAccuracy;
        } else {
            lGPSAccuracy = pNewLocation.verticalAccuracy;
        }

        if (self.delegate && [self.delegate respondsToSelector:@selector(traceRecorder:didUpdateToLocation:fromLocation:)]) {
            [self.delegate traceRecorder:self didUpdateToLocation:pNewLocation fromLocation:pOldLocation];
        }

        CLLocationCoordinate2D lUserLocation =  pNewLocation.coordinate;

        Boolean lLatitudeOK = (self.mMapSouthWest.latitude < lUserLocation.latitude) && (lUserLocation.latitude < self.mMapNorthEast.latitude);
        Boolean lLongitudeOK = (self.mMapSouthWest.longitude < lUserLocation.longitude) && (lUserLocation.longitude < self.mMapNorthEast.longitude);

        //IF USER IS OUT OF THE MAP

        if (self.delegate && [self.delegate respondsToSelector:@selector(userPositionOnMap:)]) {
            if ( (!lLatitudeOK || !lLongitudeOK) ) {
                [self.delegate userPositionOnMap:NO];
            } else {
                [self.delegate userPositionOnMap:YES];
            }
        }

        if (![self isNewLocation:pNewLocation acceptableComparedToOldLocation:pOldLocation]) {
            return;
        }

        [self treatLocation:pNewLocation];

    }
}
</code>```

Title: didUpdateToLocation not called

Body:
I  have a very complicated problem with geolocation : the didupdatetolocation delegate method is not called which I'm not understand.

this the code of the method:

 - (void) locationManager:(CLLocationManager *)pLocationManager didUpdateToLocation:(CLLocation *)pNewLocation fromLocation:(CLLocation *)pOldLocation {

        lGPSAccuracy = 0;

        // Stop trace record when the GPS Signal is poor or null
        if (pNewLocation.horizontalAccuracy > GPS_POOR_SIGNAL || pNewLocation.horizontalAccuracy < 0){ return;}

        if (pNewLocation.horizontalAccuracy > pNewLocation.verticalAccuracy) {
            lGPSAccuracy = pNewLocation.horizontalAccuracy;
        } else {
            lGPSAccuracy = pNewLocation.verticalAccuracy;
        }

        if (self.delegate && [self.delegate respondsToSelector:@selector(traceRecorder:didUpdateToLocation:fromLocation:)]) {
            [self.delegate traceRecorder:self didUpdateToLocation:pNewLocation fromLocation:pOldLocation];
        }

        CLLocationCoordinate2D lUserLocation =  pNewLocation.coordinate;

        Boolean lLatitudeOK = (self.mMapSouthWest.latitude < lUserLocation.latitude) && (lUserLocation.latitude < self.mMapNorthEast.latitude);
        Boolean lLongitudeOK = (self.mMapSouthWest.longitude < lUserLocation.longitude) && (lUserLocation.longitude < self.mMapNorthEast.longitude);

        //IF USER IS OUT OF THE MAP

        if (self.delegate && [self.delegate respondsToSelector:@selector(userPositionOnMap:)]) {
            if ( (!lLatitudeOK || !lLongitudeOK) ) {
                [self.delegate userPositionOnMap:NO];
            } else {
                [self.delegate userPositionOnMap:YES];
            }
        }

        if (![self isNewLocation:pNewLocation acceptableComparedToOldLocation:pOldLocation]) {
            return;
        }

        [self treatLocation:pNewLocation];
    }

when I read about this problem i found that this method is deprecated but it's still working on a old version of my project which is very abnormal.
Any help please.

Body:
thank you @truncdug. I resolved the problem by changing the deprecated didtoupdatelocations method

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    if ([locations count]>0) {
        CLLocation *pNewLocation = [locations firstObject];
        CLLocation *pOldLocation = _currentLocation;

         _currentLocation = pNewLocation;

        lGPSAccuracy = 0;

        // Stop trace record when the GPS Signal is poor or null
        if (pNewLocation.horizontalAccuracy > GPS_POOR_SIGNAL || pNewLocation.horizontalAccuracy < 0){ return;}

        if (pNewLocation.horizontalAccuracy > pNewLocation.verticalAccuracy) {
            lGPSAccuracy = pNewLocation.horizontalAccuracy;
        } else {
            lGPSAccuracy = pNewLocation.verticalAccuracy;
        }

        if (self.delegate && [self.delegate respondsToSelector:@selector(traceRecorder:didUpdateToLocation:fromLocation:)]) {
            [self.delegate traceRecorder:self didUpdateToLocation:pNewLocation fromLocation:pOldLocation];
        }

        CLLocationCoordinate2D lUserLocation =  pNewLocation.coordinate;

        Boolean lLatitudeOK = (self.mMapSouthWest.latitude < lUserLocation.latitude) && (lUserLocation.latitude < self.mMapNorthEast.latitude);
        Boolean lLongitudeOK = (self.mMapSouthWest.longitude < lUserLocation.longitude) && (lUserLocation.longitude < self.mMapNorthEast.longitude);

        //IF USER IS OUT OF THE MAP

        if (self.delegate && [self.delegate respondsToSelector:@selector(userPositionOnMap:)]) {
            if ( (!lLatitudeOK || !lLongitudeOK) ) {
                [self.delegate userPositionOnMap:NO];
            } else {
                [self.delegate userPositionOnMap:YES];
            }
        }

        if (![self isNewLocation:pNewLocation acceptableComparedToOldLocation:pOldLocation]) {
            return;
        }

        [self treatLocation:pNewLocation];

    }
}


问:
How to find all the tweet ids that a user has liked on twitter using PYTHON TWEEPY?
```<code>auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
tweet_list=api.favorites.list(screen_name="your_username", count=10)
</code>```

Error :
Traceback (most recent call last):
File "C:/Python34/fav.py", line 19, in
tweet_list=api.favorites.list(screen_name="your_username", count=10)
AttributeError: 'function' object has no attribute 'list'

答:
From Tweepy docs:

API.favorites([id][, page])

Returns the favorite statuses for the authenticating user or user specified by the ID parameter.

Parameters:

id – The ID or screen name of the user to request favorites

page – Specifies the page of results to retrieve. Note: there are pagination limits.

Return type:

list of Status objects

So you had it almost right, I'm not sure where you got the list method from but remove it and you'll get the list of tweets you want:

```<code>tweet_list = api.favorites(screen_name="your_username", count=10)
</code>```

Body:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
tweet_list=api.favorites.list(screen_name="your_username", count=10)

Error :
Traceback (most recent call last):
File "C:/Python34/fav.py", line 19, in
tweet_list=api.favorites.list(screen_name="your_username", count=10)
AttributeError: 'function' object has no attribute 'list'

Body:
From Tweepy docs:

API.favorites([id][, page])

Returns the favorite statuses for the authenticating user or user specified by the ID parameter.

Parameters:

id – The ID or screen name of the user to request favorites

page – Specifies the page of results to retrieve. Note: there are pagination limits.

Return type:

list of Status objects

So you had it almost right, I'm not sure where you got the list method from but remove it and you'll get the list of tweets you want:

tweet_list = api.favorites(screen_name="your_username", count=10)


问:
How to replace nested arrow functions in javascript for Safari compatibility?
I am customizing a JavaScript visualization library and have written a small piece of code to fill an array for the hover info:

```<code>var text = zValues.map((zValues, i) => zValues.map((value, j) => {
  return ` ID: ${yValues[i]}<br> Tissue: ${xValues[j]}<br> Expression: ${value.toFixed(2)} `
 }))
</code>```

It works for all browsers except Safari. I read that Safari does not support the arrow function, so I tried to replace this function as follows:

```<code>var text = zValues.map (function(zValues, i) { zValues.map (function (value, j) {
  return ` ID: ${yValues[i]}<br> Tissue: ${xValues[j]}<br> Expression: ${value.toFixed(2)} `
 });});
</code>```

This does not give any error, but leads to an empty 'text' array. How can I fix the problem?

答:
Arrow functions with just a single expression statement in the body have an implicit return. Functions created with function never have an implicit return (unless you count undefined I guess), so you need to explicitly return your arrow function expressions:

```<code>var text = zValues.map (function(zValues, i) { return zValues.map (function (value, j) {
  return ` ID: ${yValues[i]}<br> Tissue: ${xValues[j]}<br> Expression: ${value.toFixed(2)} `
 });});
</code>```

(You already had the return on the innermost result expression.)

Body:
I am customizing a JavaScript visualization library and have written a small piece of code to fill an array for the hover info:

var text = zValues.map((zValues, i) => zValues.map((value, j) => {
  return ` ID: ${yValues[i]}<br> Tissue: ${xValues[j]}<br> Expression: ${value.toFixed(2)} `
 }))

It works for all browsers except Safari. I read that Safari does not support the arrow function, so I tried to replace this function as follows:

var text = zValues.map (function(zValues, i) { zValues.map (function (value, j) {
  return ` ID: ${yValues[i]}<br> Tissue: ${xValues[j]}<br> Expression: ${value.toFixed(2)} `
 });});

This does not give any error, but leads to an empty 'text' array. How can I fix the problem?

Body:
Arrow functions with just a single expression statement in the body have an implicit return. Functions created with function never have an implicit return (unless you count undefined I guess), so you need to explicitly return your arrow function expressions:

var text = zValues.map (function(zValues, i) { return zValues.map (function (value, j) {
  return ` ID: ${yValues[i]}<br> Tissue: ${xValues[j]}<br> Expression: ${value.toFixed(2)} `
 });});

(You already had the return on the innermost result expression.)


问:
Using sed to replace character
I am leaning how to use awk and sed this week. I know this question might have been asked before but I am not sure what is wrong with my script. I have three files and I am using grep to search for the pattern gge0001x gge0001y gge0001z. x is in file1, y is in file 2, and z is in file3.   If anyone wants to see L2E[1-3].iva they are here: https://gist.github.com/anonymous/1112988408874c730cd4f3d313226ba4

```<code>#!/bin/bash
echo "Performance Data"
sed -n '1,19p' L2E1.iva|cat > file1 #take lines 1-19 in L2E1 and take the
# output into file1. The next two commands do the same thing
sed -n '1,19p' L2E2.iva|cat > file2
sed -n '1,19p' L2E3.iva|cat > file3
curveName=`grep "F" file1|sed "s/F/ /"`
# This will search for F in file 1, and then substitute F with a space
curveName2=`grep "F" file2|sed "s/F/ /"`
curveName3=`grep "F" file3|sed "s/F/ /"`
echo "Curve Name" "$curveName $curveName2 $curveName3"
</code>```

I want my output to be Curve Name gge0001x gge0001y gge0001z. But the output is this instead:
Performance Data gge0006ze gge0006x

If I echo them out by themselves then it is fine, but once I echo all three on the same line the output gets skewed. Why does x show up last when it is first when I echo it and where did my y go to?

答:
You can perhaps compress your script into one line

```<code>$ echo Curve name $(grep -Pohm1 '(?<=F ).*' L2E{1..3})

Curve name gge0006x gge0006y gge0006z
</code>```

exercise is to search the options used in grep

Title: Using sed to replace character

Body:
I am leaning how to use awk and sed this week. I know this question might have been asked before but I am not sure what is wrong with my script. I have three files and I am using grep to search for the pattern gge0001x gge0001y gge0001z. x is in file1, y is in file 2, and z is in file3.   If anyone wants to see L2E[1-3].iva they are here: https://gist.github.com/anonymous/1112988408874c730cd4f3d313226ba4

#!/bin/bash
echo "Performance Data"
sed -n '1,19p' L2E1.iva|cat > file1 #take lines 1-19 in L2E1 and take the
# output into file1. The next two commands do the same thing
sed -n '1,19p' L2E2.iva|cat > file2
sed -n '1,19p' L2E3.iva|cat > file3
curveName=`grep "F" file1|sed "s/F/ /"`
# This will search for F in file 1, and then substitute F with a space
curveName2=`grep "F" file2|sed "s/F/ /"`
curveName3=`grep "F" file3|sed "s/F/ /"`
echo "Curve Name" "$curveName $curveName2 $curveName3"

I want my output to be Curve Name gge0001x gge0001y gge0001z. But the output is this instead:
Performance Data gge0006ze gge0006x

If I echo them out by themselves then it is fine, but once I echo all three on the same line the output gets skewed. Why does x show up last when it is first when I echo it and where did my y go to?

Body:
You can perhaps compress your script into one line

$ echo Curve name $(grep -Pohm1 '(?<=F ).*' L2E{1..3})

Curve name gge0006x gge0006y gge0006z

exercise is to search the options used in grep


问:
ld: warning: -no_pie ignored for arm64
I  used "-no_pie" for LDFLAGS , but prompt: "ld: warning: -no_pie ignored for arm64".

then I use otool to check the binary ,there is no PIE flag with V7 and V7S cpusubtype,but still in ARM64,is the ld  don't support -no_pie for ARM64?

答: This came up for me on an older ObjC project when I upped the Deployment Target from 9.0 to 10.0.  It only occurred when I archived the project or when I ran it on a physical device.  To removed the warning, I set the Build Setting 'Generate Position-Dependent Executable' to 'No'.  It was previously set to 'Yes'.</p>

Title: ld: warning: -no_pie ignored for arm64


问:
Strange SAM rules with functions
What are exact rules for a function to be considered for Single Abstract Method conversion? In the following code there are two very similar cases, one is compiled, second is not, when compiled with Scala 2.12.4:

```<code>trait SAM {
  def apply(a: Int, b: Int): Unit
}

def callSAM(sam: SAM): Unit = {
  sam(0, 1)
}

def iAmSam(f: (Int, Int) => Unit) = {

  def lf(a: Int, b: Int) = f(a, b)

  callSAM(f) // does not work - error:
  //                          type mismatch:
  //                          found (Int, Int) => Unit,
  //                          required SAM

  callSAM(lf) // works. What is the difference?

  callSAM(f(_, _)) // works (lambda)

  callSAM((a, b) => f(a, b)) // works (lambda)
}
</code>```

What is the reason callSAM(lf) works and callSAM(f) does not? I have found a mention in Scala 2.12 release notes, which says:

Note that only lambda expressions are converted to SAM type instances, not arbitrary expressions of FunctionN type

The lf does not look like lambda expression to me. Were the rules relaxed after 2.12.0? When lf is accepted, why f is not?

答:
f is just an object, and falls exactly under

arbitrary expressions of FunctionN type

lf is the name of a method and when used as expression it's a shorthand for lf _ which in turn expands to (x, y) => lf(x, y), which is a lambda expression.

Title: Strange SAM rules with functions

Body:
What are exact rules for a function to be considered for Single Abstract Method conversion? In the following code there are two very similar cases, one is compiled, second is not, when compiled with Scala 2.12.4:

trait SAM {
  def apply(a: Int, b: Int): Unit
}

def callSAM(sam: SAM): Unit = {
  sam(0, 1)
}

def iAmSam(f: (Int, Int) => Unit) = {

  def lf(a: Int, b: Int) = f(a, b)

  callSAM(f) // does not work - error:
  //                          type mismatch:
  //                          found (Int, Int) => Unit,
  //                          required SAM

  callSAM(lf) // works. What is the difference?

  callSAM(f(_, _)) // works (lambda)

  callSAM((a, b) => f(a, b)) // works (lambda)
}

What is the reason callSAM(lf) works and callSAM(f) does not? I have found a mention in Scala 2.12 release notes, which says:

Note that only lambda expressions are converted to SAM type instances, not arbitrary expressions of FunctionN type

The lf does not look like lambda expression to me. Were the rules relaxed after 2.12.0? When lf is accepted, why f is not?


问:
Python send label to Zebra IP printer
What I have

Printer internal IP

ZPL code on printer

parameters to plug into ZPL code

Is there a way to define a label and send it to the printer via Python? I would need to specify which label type to use on the printer since it can have multiple .zpl label codes stored on it.

are there dedicated libraries? Otehrwise what are some basic socket functions to get me started

答:
OK I am not a python expert here but the general process is:

Open a TCP connection to port 9100

Write ZPL to your connection

Close your connection

You will want to look at the ^DF and ^XF commands in the ZPL programming guide to make sure you are using the templates right, but it is a pretty simple process.

If you are concerned about whether or not the printer is ready to print you could look at the ~hs command to get the current status.

In the end there is a C# and Java SDK available for the printer which has helper functions to push variables store in Maps to a template, but the JNI calls are probably more involved than just opening a TCP connection...

Title: Python send label to Zebra IP printer