问:
Query with multiple EXIST
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

```<code>select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)
</code>```

Is there any way to optimize or making this shorter?

答:
```<code>select * from rooms r where
(select count(id) from equipments where eq_id='eq1' and room_id=r.id) > 0
and
...
</code>```

Title: Query with multiple EXIST

Body:
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)

Is there any way to optimize or making this shorter?


来源: stackexchange

问:
How to fix NotificationCenter in swift4
During conversion from swift3 to swift4 the convertor has changed NotificationCenter to the following view:

```<code> NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSNotification.Name.NSTextView.didChangeSelectionNotification, object: myNSTextView)
</code>```

So, because of selector in .addObserver() myFunction now has @objc in front. Now the compiler is complaining, that the type NSNotification.Name has no member NSTextView. This is what convertor made, not me. I am confused.

How to fix this ?

Update. I have found the information here How to migrate NSWorkspace notifications to Swift 4?

So I have to use

```<code>NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)
</code>```

答: you may also type @objc before method and it will work</p>

ContentLicense: CC BY-SA 3.0

Title: How to fix NotificationCenter in swift4

Body:
During conversion from swift3 to swift4 the convertor has changed NotificationCenter to the following view:

 NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSNotification.Name.NSTextView.didChangeSelectionNotification, object: myNSTextView)

So, because of selector in .addObserver() myFunction now has @objc in front. Now the compiler is complaining, that the type NSNotification.Name has no member NSTextView. This is what convertor made, not me. I am confused.

How to fix this ?

Update. I have found the information here How to migrate NSWorkspace notifications to Swift 4?

So I have to use

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)


问:
return list of words in dictionary.txt
I'm a beginner to Python. I am begging to learn about functions and files. I need to write a code that will return a list of all the words in dictionary.txt using a function, but I can't seem to figure it out.

Current code

```<code>def get_dictionary_wordlist(dic):
     dic = open("dictionary.txt", "r")
     for word in dic:
         return word
</code>```

答:
You have to make a list and add the words there, then you return it.</p>

```<code>def get_dictionary_wordlist(dic):
     words = [] # Make a list
     dic = open("dictionary.txt", "r")
     for word in dic:
         words.append() # Add words to the list
     return words
</code>```

Title: return list of words in dictionary.txt

Body:
I'm a beginner to Python. I am begging to learn about functions and files. I need to write a code that will return a list of all the words in dictionary.txt using a function, but I can't seem to figure it out.

Current code

def get_dictionary_wordlist(dic):
     dic = open("dictionary.txt", "r")
     for word in dic:
         return word

Body:
You have to make a list and add the words there, then you return it.

def get_dictionary_wordlist(dic):
     words = [] # Make a list
     dic = open("dictionary.txt", "r")
     for word in dic:
         words.append() # Add words to the list
     return words


问:
ASCII dictionary in python
Is there any way to initialize a dictionary in python with keys as all the 128 ascii characters and values as their corresponding ascii values?</p>

答:
```<code>asciiDict = {i: chr(i) for i in range(128)}
</code>```

Title: ASCII dictionary in python

ContentLicense: CC BY-SA 4.0


问:
C++ - Overwrite Multiple Lines that were Previously Output to Console
If I have a grid of characters displayed in the console, is there any practical way to re-write those multiple lines in order to output an altered grid on those same lines of the console.

e.g, I would like this code:

```<code>#include <iostream>

using namespace std;

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        for (int i=0; i<5; i++) {
                cout << '\r';
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout.flush();
        }

        return 0;
}
</code>```

to output:

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

then, upon user input, overwrite that with;

```<code>xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
</code>```

I see other examples of people displaying loading bar type displays by outputting '\r' to re-write a single line, but I'm not sure if there is any straightforward way to accomplish that for multiple lines?

I'm using MinGW.

One Solution:

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

using namespace std;

void gotoxy( int column, int line )
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
  }

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        gotoxy(0,0);

        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout << endl;
        }

        return 0;
}
</code>```

答:
You can add this block of code between your two loops to clear the screen.

```<code>    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);
</code>```

It uses ANSI escape sequences to do so. You also need to add #include <stdio.h> to support printf().

There's also no need for the \r and you should replace cout.flush(); with cout << endl;

You code should finally look like this :

```<code>#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    for (int i=0; i<5; i++) {
            for (int j=0; j<5; j++) {
                    cout << "-";
            }
            cout << endl;
    }

    getchar();
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);

    for (int i=0; i<5; i++) {
            for (int j=0; j<5; j++) {
                    cout << "x";
            }
            cout<<endl;
    }

    return 0;
}
</code>```

Body:
If I have a grid of characters displayed in the console, is there any practical way to re-write those multiple lines in order to output an altered grid on those same lines of the console.

e.g, I would like this code:

#include <iostream>

using namespace std;

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        for (int i=0; i<5; i++) {
                cout << '\r';
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout.flush();
        }

        return 0;
}

to output:

-----
-----
-----
-----
-----

then, upon user input, overwrite that with;

xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

I see other examples of people displaying loading bar type displays by outputting '\r' to re-write a single line, but I'm not sure if there is any straightforward way to accomplish that for multiple lines?

I'm using MinGW.

One Solution:

#include <iostream>
#include <stdio.h>
#include <windows.h>

using namespace std;

void gotoxy( int column, int line )
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
  }

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        gotoxy(0,0);

        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout << endl;
        }

        return 0;
}

Body:
You can add this block of code between your two loops to clear the screen.

    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);

It uses ANSI escape sequences to do so. You also need to add #include <stdio.h> to support printf().

There's also no need for the \r and you should replace cout.flush(); with cout << endl;

You code should finally look like this :

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    for (int i=0; i<5; i++) {
            for (int j=0; j<5; j++) {
                    cout << "-";
            }
            cout << endl;
    }

    getchar();
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);

    for (int i=0; i<5; i++) {
            for (int j=0; j<5; j++) {
                    cout << "x";
            }
            cout<<endl;
    }

    return 0;
}


问:
Deploying actions on google webhook on glitch
I want to deploy this example on glitch. I've added package.js and index.js to my glitch project and built successfully.

However, the code is missing a section to listen for HTTPS requests. In most node.js/express webapps, there is code to indicate which paths trigger which functions, but this is missing from the example. Can you explain to me how it should work and why that part is missing from this example?

答:
It's not clear what do you mean by "the code is missing a section to listen" as the only main feature of index.js is to listen to requests and return information.

I suggest you check index.js and make sure that you getting requests to your end point on glitch.

Also, it would be helpful if you can share your glitch project over here at SO so we could see what you are doing.
Btw, you might want to double check that you have all the packages

I also created this simple example on Glitch - It's returning the current bitcoin price. Feel free to remix it and use the code there for your own action.
Good luck!


问:
What is the proper way to create an update trigger with a variable getting value from the same table?
I'm creating a update trigger where an employee can never have a salary that is greater than the president's. However I need to subquery the president's salary for comparison and the "new" updated employee's salary.

I originally had the the subquery using from the from employees table but had to make a new table because of the mutating table problem. I don't think creating a new table is plausible solution for a real implementation.

Is there a way I can save the president's salary without creating a new table?

```<code>CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
    declare pres_sal number(8,2);
BEGIN
    select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error

    IF (:new.salary > pres_sal)
        THEN UPDATE employees
        SET salary = :old.salary
        WHERE employee_id = :old.employee_id;
    END IF;
END;
</code>```

答:
One way to do it is to save off the president's salary in a BEFORE STATEMENT trigger and then use that in the FOR EACH ROW trigger.

"Compound Triggers", which have been around at least since version 11.1, offer a nice way to do that all in one place.

Here is an example:

```<code>CREATE OR REPLACE TRIGGER prevent_salary
FOR UPDATE OF salary ON employees
COMPOUND TRIGGER

  pres_sal NUMBER;

BEFORE STATEMENT IS
BEGIN
    select salary
    into pres_sal
    from employees
    where job_id='AD_PRES';
END BEFORE STATEMENT;

BEFORE EACH ROW IS
BEGIN
    :new.salary := least(:new.salary, pres_sal);
END BEFORE EACH ROW;

END prevent_salary;
</code>```

Body:
I'm creating a update trigger where an employee can never have a salary that is greater than the president's. However I need to subquery the president's salary for comparison and the "new" updated employee's salary.

I originally had the the subquery using from the from employees table but had to make a new table because of the mutating table problem. I don't think creating a new table is plausible solution for a real implementation.

Is there a way I can save the president's salary without creating a new table?

CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
    declare pres_sal number(8,2);
BEGIN
    select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error

    IF (:new.salary > pres_sal)
        THEN UPDATE employees
        SET salary = :old.salary
        WHERE employee_id = :old.employee_id;
    END IF;
END;

Body:
One way to do it is to save off the president's salary in a BEFORE STATEMENT trigger and then use that in the FOR EACH ROW trigger.

"Compound Triggers", which have been around at least since version 11.1, offer a nice way to do that all in one place.

Here is an example:

CREATE OR REPLACE TRIGGER prevent_salary
FOR UPDATE OF salary ON employees
COMPOUND TRIGGER

  pres_sal NUMBER;

BEFORE STATEMENT IS
BEGIN
    select salary
    into pres_sal
    from employees
    where job_id='AD_PRES';
END BEFORE STATEMENT;

BEFORE EACH ROW IS
BEGIN
    :new.salary := least(:new.salary, pres_sal);
END BEFORE EACH ROW;

END prevent_salary;


问:
How long does Instagram API access tokens last?
I would like to know how long Instagram API access tokens last? It's not very clear how long they last on their documentation and every PHP package that uses the Instagram API and they all just expect a static access token (along with the client ID and secret) which indicates to me it doesn't change very much.

I am trying to display an Instagram feed on a website, and would like to know if I need to build extra code to periodically check the access token still works or if this is negligible.

答:
https://www.instagram.com/developer/authentication/

Access tokens may expire at any time in the future.

+

Even though our access tokens do not specify an expiration time, your
  app should handle the case that either the user revokes access, or
  Instagram expires the token after some period of time. If the token is
  no longer valid, API responses will contain an
  “error_type=OAuthAccessTokenException”. In this case you will need to
  re-authenticate the user to obtain a new valid token. In other words:
  do not assume your access_token is valid forever.


问:
MongoDB aggregation - how to get a percentage value of how many times an event occurred per day of week
Im a MongoDB noob so please dont judge me if my question is stupid:P
Im trying to get some results from MongoDB to create a table that would show percentage statistics of how much do i play a certain game per day of week (all games together per day = 100%). This is my JSON import for the database:

```<code>[
{"title":"GTA","date":"2017-11-13"},
{"title":"GTA","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-14"}
]
</code>```

Ive written an aggregation that grouped the results by days and counted the total amount of times a game has been played per each day…:

```<code>db.games.aggregate([
    { $project: { _id: 0, date : { $dayOfWeek: "$date" }, "title":1} },
    { $group: { _id: {title: "$title", date: "$date"}, total: {$sum: 1} } },
    { $group: { _id: "$_id.date", types: {$addToSet: {title:"$_id.title", total: "$total"} } } }
])
</code>```

…and this is what i got from MongoDB now:

```<code>/* 1 */
{
    "_id" : 3,
    "types" : [
        {
            "title" : "BattleField",
            "total" : 1.0
        }
    ]
},

/* 2 */
{
    "_id" : 2,
    "types" : [
        {
            "title" : "GTA",
            "total" : 2.0
        },
        {
            "title" : "BattleField",
            "total" : 2.0
        }
    ]
}
</code>```

what i need to get is a table that would look like this:

```<code>            Monday      Tuesday
GTA         50,00%      0%
BattleField 50,00%      100%
</code>```

Could you please advise me how can i get such percentage results from Mongo?

答:
Your attempt was pretty close to a solution! The following should point you in the right direction:

```<code>aggregate([
    { $project: { "_id": 0, "date" : { $dayOfWeek: "$date" }, "title": 1 } }, // get the day of the week from the "date" field
    { $group: { "_id": { "title": "$title", "date": "$date" }, "total": { $sum: 1 } } }, // group by title and date to get the total per title and date
    { $group: { "_id": "$_id.date", "types": { $push: { "title": "$_id.title", total: "$total" } }, "grandTotal": { $sum: "$total" } } }, // group by date only to get the grand total
    { $unwind: "$types" }, // flatten grouped items
    { $project: { "_id": 0, "title": "$types.title", "percentage": { $divide: [ "$types.total", "$grandTotal" ] }, "day": { $arrayElemAt: [ [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "$_id" ] } } }, // calculate percentage and beautify output for "day"
])
</code>```

Results:

```<code>{
    "title" : "BattleField",
    "percentage" : 0.5,
    "day" : "Tue"
}
{
    "title" : "GTA",
    "percentage" : 0.5,
    "day" : "Tue"
}
{
    "title" : "BattleField",
    "percentage" : 1.0,
    "day" : "Wed"
}
</code>```

Body:
Im a MongoDB noob so please dont judge me if my question is stupid:P
Im trying to get some results from MongoDB to create a table that would show percentage statistics of how much do i play a certain game per day of week (all games together per day = 100%). This is my JSON import for the database:

[
{"title":"GTA","date":"2017-11-13"},
{"title":"GTA","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-14"}
]

Ive written an aggregation that grouped the results by days and counted the total amount of times a game has been played per each day…:

db.games.aggregate([
    { $project: { _id: 0, date : { $dayOfWeek: "$date" }, "title":1} },
    { $group: { _id: {title: "$title", date: "$date"}, total: {$sum: 1} } },
    { $group: { _id: "$_id.date", types: {$addToSet: {title:"$_id.title", total: "$total"} } } }
])

…and this is what i got from MongoDB now:

/* 1 */
{
    "_id" : 3,
    "types" : [
        {
            "title" : "BattleField",
            "total" : 1.0
        }
    ]
},

/* 2 */
{
    "_id" : 2,
    "types" : [
        {
            "title" : "GTA",
            "total" : 2.0
        },
        {
            "title" : "BattleField",
            "total" : 2.0
        }
    ]
}

what i need to get is a table that would look like this:

            Monday      Tuesday
GTA         50,00%      0%
BattleField 50,00%      100%

Could you please advise me how can i get such percentage results from Mongo?

Body:
Your attempt was pretty close to a solution! The following should point you in the right direction:

aggregate([
    { $project: { "_id": 0, "date" : { $dayOfWeek: "$date" }, "title": 1 } }, // get the day of the week from the "date" field
    { $group: { "_id": { "title": "$title", "date": "$date" }, "total": { $sum: 1 } } }, // group by title and date to get the total per title and date
    { $group: { "_id": "$_id.date", "types": { $push: { "title": "$_id.title", total: "$total" } }, "grandTotal": { $sum: "$total" } } }, // group by date only to get the grand total
    { $unwind: "$types" }, // flatten grouped items
    { $project: { "_id": 0, "title": "$types.title", "percentage": { $divide: [ "$types.total", "$grandTotal" ] }, "day": { $arrayElemAt: [ [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "$_id" ] } } }, // calculate percentage and beautify output for "day"
])

Results:

{
    "title" : "BattleField",
    "percentage" : 0.5,
    "day" : "Tue"
}
{
    "title" : "GTA",
    "percentage" : 0.5,
    "day" : "Tue"
}
{
    "title" : "BattleField",
    "percentage" : 1.0,
    "day" : "Wed"
}


问:
Size of char array is bigger than number of elements passed to initialize it
for arrays of type int or double, if the size of the array is bigger than the number of elements provided when the array is initialized (like a list), the rest of the elements in the array are defaulted to 0 right?

What happens when I initialize a character array with less elements than the size I provide? Like

```<code>char ch[10] = { 'h', 'e', 'l', 'l', 'o' };
</code>```

Are the rest of the elements assigned any value? Or is it just garbage in memory?

答:
This declaration

```<code>char ch[10] = { 'h', 'e', 'l', 'l', 'o' };
</code>```

is equivalent to this declaration

```<code>char ch[10] = { "hello" };
</code>```

that in turn is equivalent to the following declaration

```<code>char ch[10] = "hello";
</code>```

and all these declarations are equivalent to the following declaration

```<code>char ch[10] = { 'h', 'e', 'l', 'l', 'o', '\0', '\0', '\0', '\0', '\0', };
</code>```

That is elements of the array that do not have explicit initializers are implicitly zero-initialized.

From the C Standard (6.7.9 Initialization)

10 If an object that has automatic storage duration is not initialized
  explicitly, its value is indeterminate. If an object that has static
  or thread storage duration is not initialized explicitly, then:

...

— if it has arithmetic type, it is initialized to (positive or
  unsigned) zero;

and

19 The initialization shall occur in initializer list order, each
  initializer provided for a particular subobject overriding any
  previously listed initializer for the same subobject;151) all
  subobjects that are not initialized explicitly shall be initialized
  implicitly the same as objects that have static storage duration.

Body:
for arrays of type int or double, if the size of the array is bigger than the number of elements provided when the array is initialized (like a list), the rest of the elements in the array are defaulted to 0 right?

What happens when I initialize a character array with less elements than the size I provide? Like

char ch[10] = { 'h', 'e', 'l', 'l', 'o' };

Are the rest of the elements assigned any value? Or is it just garbage in memory?

Body:
This declaration

char ch[10] = { 'h', 'e', 'l', 'l', 'o' };

is equivalent to this declaration

char ch[10] = { "hello" };

that in turn is equivalent to the following declaration

char ch[10] = "hello";

and all these declarations are equivalent to the following declaration

char ch[10] = { 'h', 'e', 'l', 'l', 'o', '\0', '\0', '\0', '\0', '\0', };

That is elements of the array that do not have explicit initializers are implicitly zero-initialized.

From the C Standard (6.7.9 Initialization)

10 If an object that has automatic storage duration is not initialized
  explicitly, its value is indeterminate. If an object that has static
  or thread storage duration is not initialized explicitly, then:

...

— if it has arithmetic type, it is initialized to (positive or
  unsigned) zero;

and

19 The initialization shall occur in initializer list order, each
  initializer provided for a particular subobject overriding any
  previously listed initializer for the same subobject;151) all
  subobjects that are not initialized explicitly shall be initialized
  implicitly the same as objects that have static storage duration.


问:
How to have checkbox items create a list
I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.

The checkboxes should be populating as a list field.

Here is my form

```<code><input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2
</code>```

There are about 7 checkboxes.

I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.

If I take away the array, the last one selected goes through to the layout.

Any help would be great.

答:
I worked it out. To enter checked boxes into a return separated list:

View:

At the top of the section with the checkboxes

```<code><?php $join->fieldname = explode("\n", $join->fieldname); ?>

// The actual input in the form
<input name="fieldnameXX[checkboxValue]" value="value" <?php echo (in_array('value', set_value('fieldname[value]', $join->fieldname)) ? ' checked="checked"': '')?> type="checkbox" class="form-check-input" > Value
</code>```

Factory:

```<code>$fieldnameZZ = $data['fieldnameXX'];
$data['fieldnameXX'] = FALSE;
unset($data['fieldnameXX']);
$sacraments = implode("\n", $fieldnameZZ);
$data['fieldname'] = $fieldnameZZ;
</code>```

I'm not sure if this is the best way to have done it, but it works.

Body:
I am new to PHP and the project I am working on is a codeigniter php form writing back to a FileMaker database.

The checkboxes should be populating as a list field.

Here is my form

<input name="fieldname[]" value="value1"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value1
<input name="fieldname[]" value="value2"<?php echo (set_checkbox('fieldname', $join->fieldname))?> type="checkbox" class="form-check-input"> value2

There are about 7 checkboxes.

I assume that I have to setup a foreach loop to get it to go thought to FileMaker's field, but unsure how to do that.

If I take away the array, the last one selected goes through to the layout.

Any help would be great.

Body:
I worked it out. To enter checked boxes into a return separated list:

View:

At the top of the section with the checkboxes

<?php $join->fieldname = explode("\n", $join->fieldname); ?>

// The actual input in the form
<input name="fieldnameXX[checkboxValue]" value="value" <?php echo (in_array('value', set_value('fieldname[value]', $join->fieldname)) ? ' checked="checked"': '')?> type="checkbox" class="form-check-input" > Value

Factory:

$fieldnameZZ = $data['fieldnameXX'];
$data['fieldnameXX'] = FALSE;
unset($data['fieldnameXX']);
$sacraments = implode("\n", $fieldnameZZ);
$data['fieldname'] = $fieldnameZZ;

I'm not sure if this is the best way to have done it, but it works.


问:
directly quoting %~dp0 does not ignore spaces in file path
i have a script which 3 arguments, two of which are paths. I would like to call it from a .bat file.

```<code>python myscript.py "%~dp0inputs/" "%~dp0outputs/" "foo"
</code>```

If i call a dummy script that simply prints argv using the above line, i get the expected results, even for paths containing spaces:

```<code>myscript.py
C:\path\containing spaces\inputs/
C:\path\containing spaces\outputs/
foo
</code>```

however if i use this (ie %~dp0 for argument 1 with nothing else between the quotes):

```<code>python myscript.py "%~dp0" "%~dp0outputs/" "foo"
</code>```

then it behaves oddly when the path contains spaces:

```<code>myscript.py
C:\path\containing spaces" C:\path\containing
spaces\outputs/ foo
</code>```

it seems that the quotes have not been processed properly - what have i done wrong?

答:
It is because the quotes are passed into the python script.
And %~dp0 ends with a \ character.

Python figures that \ escapes the double quote - fun.

So, "%~dp0" is passed to the script as

```<code>"C:\temp\containing spaces\"
</code>```

Python treats that trailing \ as escaping the quote, so it merges the arguments.

It shouldn't do that - but it does.

You can remove the trailing \, or add another.
Either of these works:

```<code>python myscript.py "%~dp0/" "%~dp0outputs/" "foo"
python myscript.py "%~dp0\" "%~dp0outputs/" "foo"
</code>```

Body:
i have a script which 3 arguments, two of which are paths. I would like to call it from a .bat file.

python myscript.py "%~dp0inputs/" "%~dp0outputs/" "foo"

If i call a dummy script that simply prints argv using the above line, i get the expected results, even for paths containing spaces:

myscript.py
C:\path\containing spaces\inputs/
C:\path\containing spaces\outputs/
foo

however if i use this (ie %~dp0 for argument 1 with nothing else between the quotes):

python myscript.py "%~dp0" "%~dp0outputs/" "foo"

then it behaves oddly when the path contains spaces:

myscript.py
C:\path\containing spaces" C:\path\containing
spaces\outputs/ foo

it seems that the quotes have not been processed properly - what have i done wrong?

Body:
It is because the quotes are passed into the python script.
And %~dp0 ends with a \ character.

Python figures that \ escapes the double quote - fun.

So, "%~dp0" is passed to the script as

"C:\temp\containing spaces\"

Python treats that trailing \ as escaping the quote, so it merges the arguments.

It shouldn't do that - but it does.

You can remove the trailing \, or add another.
Either of these works:

python myscript.py "%~dp0/" "%~dp0outputs/" "foo"
python myscript.py "%~dp0\" "%~dp0outputs/" "foo"


问:
grep: finding a string that starts and ends with a specific letter in directory
I am teaching myself commands and different ways to use grep. I know how to search for a string in a directory and its sub directories, but I am confused when it comes to searching for a split in the string.

for example: how could I search for all words (string size varies) that starts with a and ends with e. so that I could find ape or apple in text files?

EDIT UPDATE:
I am not sure of the grep version I am using, but I tried using:

" grep -nr "a[A-Za-z]*e" "

this produces the answer by including outputs like ape and apple but it also includes apes which is NOT wanted.

答:
Simply:

```<code>grep '\ba\w*e\b'
</code>```

or

```<code>grep --color '\ba\w*e\b'
</code>```

or

```<code>grep -rn '\ba\w*e\b'
</code>```

Some explanations

As this question is tagged linux, this answer use GNU grep:  grep (GNU grep) 2.27.

The result of command man grep | grep -3 '\\b':

```<code>The Backslash Character and Special Expressions
    The  symbols  \<  and  \>  respectively  match  the empty string at the
    beginning and end of a word.  The symbol \b matches the empty string at
    the  edge  of a word, and \B matches the empty string provided it's not
    at the edge of a word.  The symbol \w is a synonym for [_[:alnum:]] and
    \W is a synonym for [^_[:alnum:]].
</code>```

Let you show

\b mean edge of a word

\w mean [_[:alnum:]]

a and e are letters

you may already know* wich mean The preceding item will be matched zero or more times. (elsewhere in same man page: man grep | grep '^ *\*' ;)

... and finally... This could by written:

```<code>grep '\<a\w*e\>'
</code>```

where

The  symbols  \<  and  >  respectively  match  the empty string at the beginning and end of a word.

This could have near same effect, but description strictly correspond to title of this: grep: finding a string that starts and ends with a specific letter in directory

Body:
Simply:

grep '\ba\w*e\b'

or

grep --color '\ba\w*e\b'

or

grep -rn '\ba\w*e\b'

Some explanations

As this question is tagged linux, this answer use GNU grep:  grep (GNU grep) 2.27.

The result of command man grep | grep -3 '\\b':

The Backslash Character and Special Expressions
    The  symbols  \<  and  \>  respectively  match  the empty string at the
    beginning and end of a word.  The symbol \b matches the empty string at
    the  edge  of a word, and \B matches the empty string provided it's not
    at the edge of a word.  The symbol \w is a synonym for [_[:alnum:]] and
    \W is a synonym for [^_[:alnum:]].

Let you show

\b mean edge of a word

\w mean [_[:alnum:]]

a and e are letters

you may already know* wich mean The preceding item will be matched zero or more times. (elsewhere in same man page: man grep | grep '^ *\*' ;)

... and finally... This could by written:

grep '\<a\w*e\>'

where

The  symbols  \<  and  >  respectively  match  the empty string at the beginning and end of a word.

This could have near same effect, but description strictly correspond to title of this: grep: finding a string that starts and ends with a specific letter in directory


问:
JS: Return value from EventListener function
i'm trying to return an array of instances of my Class. However the return is simply returning from the window.addEventListener('load', function(){} ); function I believe. As when I type plugins into the control it is undefined.

```<code>;class Parallax {

    constructor(node) {

        // Settings and defaults
        // this.settings = {
        //     container: null,
        //     panels: [],
        //     defaultSpeed: 0.5
        // };

    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                let instances = [];

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }

                return instances;
            } else {
                // Page doesn't appear to have Parallax
                return false;
            }
        }.bind(this));
    }
}
window.plugins = { "parallax-instances": Parallax.initialize() };
</code>```

Not too sure how to go about doing this, I have tried assigning the window.addEventListener to a variable, however that doesn't return the value. I am retaining the class scope by binding this to my function call within the event listener.

Edit:
I did want to start the plugin by simply having the below code, however not too sure how to return possible multiple instances of the class as of course doing the below runs the constructor method first.

```<code>window.plugins = { "parallax-instances": new Parallax };
</code>```

Edit 2
If I return the instances outside of the EventListener I get my desired result. However this could potentially return instances before the page has loaded right?

```<code>static initialize() {

        this.instances = [];

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        this.instances.push(new this(panels[panel]));
                    }
                }
            }
        }.bind(this));

        return this.instances;
    }
</code>```

What I get in the console:

```<code>{parallax-instances: Array(2)}
    parallax-instances:Array(2)
        0:Parallax {}
        1:Parallax {}
        length:2
    __proto__:Array(0)
    __proto__:Object
</code>```

答:
Your initialize is not returning anything. If you elevate instances to outside your event listener and return that, you can remove the other return statements. Note that the returned array will be empty until the callback is actually called (after load).

```<code>static initialize() {

    const instances = [];

    window.addEventListener( "load", () => {

        const panels = document.querySelectorAll( "[data-parallax]" );
        for ( let i = 0; i < panels.length; i++ )
            instances.push( new this( panels[ i ] ) );

    });

    return instances;

}
</code>```

Since you would be returning an array right away, your false syntax would disappear and you'd test .length === 0 instead. You can get the behavior you specified using a getter instead.

Body:
i'm trying to return an array of instances of my Class. However the return is simply returning from the window.addEventListener('load', function(){} ); function I believe. As when I type plugins into the control it is undefined.

;class Parallax {

    constructor(node) {

        // Settings and defaults
        // this.settings = {
        //     container: null,
        //     panels: [],
        //     defaultSpeed: 0.5
        // };

    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                let instances = [];

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }

                return instances;
            } else {
                // Page doesn't appear to have Parallax
                return false;
            }
        }.bind(this));
    }
}
window.plugins = { "parallax-instances": Parallax.initialize() };

Not too sure how to go about doing this, I have tried assigning the window.addEventListener to a variable, however that doesn't return the value. I am retaining the class scope by binding this to my function call within the event listener.

Edit:
I did want to start the plugin by simply having the below code, however not too sure how to return possible multiple instances of the class as of course doing the below runs the constructor method first.

window.plugins = { "parallax-instances": new Parallax };

Edit 2
If I return the instances outside of the EventListener I get my desired result. However this could potentially return instances before the page has loaded right?

static initialize() {

        this.instances = [];

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        this.instances.push(new this(panels[panel]));
                    }
                }
            }
        }.bind(this));

        return this.instances;
    }

What I get in the console:

{parallax-instances: Array(2)}
    parallax-instances:Array(2)
        0:Parallax {}
        1:Parallax {}
        length:2
    __proto__:Array(0)
    __proto__:Object

Body:
Your initialize is not returning anything. If you elevate instances to outside your event listener and return that, you can remove the other return statements. Note that the returned array will be empty until the callback is actually called (after load).

static initialize() {

    const instances = [];

    window.addEventListener( "load", () => {

        const panels = document.querySelectorAll( "[data-parallax]" );
        for ( let i = 0; i < panels.length; i++ )
            instances.push( new this( panels[ i ] ) );

    });

    return instances;

}

Since you would be returning an array right away, your false syntax would disappear and you'd test .length === 0 instead. You can get the behavior you specified using a getter instead.


问:
Install Twilio onto EC2 RHEL instance
I was wondering how I install Twilio onto my RHEL EC2 instance. I have already tried, and this is what happened:

Naturally, I decided to search for the package instead. This time, I realized that I could not find anything named Twilio:

How should I go about installing Twilio onto my EC2 instance? Thanks in advance for all the help.

Jack

答:
Twilio is a communications service. You do not install it.

If you are developing applications that use Twilio, then you would install the application and the Twilio SDK for the language that you are using.

Here is a link to the Twilio Libraries (SDKs):

Server-Side SDKs

If you are looking to install the Twilio Client for VOIP:

THE TWILIO.JS LIBRARY: TWILIO IN THE BROWSER

Title: Install Twilio onto EC2 RHEL instance


问:
Hide other field on field change - Suite Script 2.0
I would like to hide the ID 'custrecord_hrx_vendor_status_list'
once item has selected in select box ( options ).

Here is my code.
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
*/

define(['N/ui/serverWidget', 'N/error'],

```<code>function (error) {

    function fieldChanged(context) {
        var currentRecord = context.currentRecord;
        var fieldId = context.fieldId;
        if( fieldId === 'custrecord_hrx_negotiation_type' ){
            var selectedType = currentRecord.getText(fieldId);
            console.log(currentRecord.getField('custrecord_hrx_vendor_status_list'));

            currentRecord.updateDisplayType({
                id: 'custrecord_hrx_vendor_status_list',
                displayType: serverWidget.FieldDisplayType.HIDDEN
            });
        }
    }

    return {
        fieldChanged: fieldChanged
    }

}
</code>```

);

----HERE IS THE ERROR

答:
As the error message says, you are trying to load a module that is not available. You are writing a client script, and trying to load a module that is only for server-side scripts.

Additionally, N/currentRecord#CurrentRecord does not have a updateDisplayType() method.

The way to hide a field in a SS2.0 client script is:

```<code>currentRecord.getField({
  fieldId: 'custrecord_hrx_vendor_status_list'
}).isDisplay = false;
</code>```

Body:
I would like to hide the ID 'custrecord_hrx_vendor_status_list'
once item has selected in select box ( options ).

Here is my code.
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
*/

define(['N/ui/serverWidget', 'N/error'],

function (error) {

    function fieldChanged(context) {
        var currentRecord = context.currentRecord;
        var fieldId = context.fieldId;
        if( fieldId === 'custrecord_hrx_negotiation_type' ){
            var selectedType = currentRecord.getText(fieldId);
            console.log(currentRecord.getField('custrecord_hrx_vendor_status_list'));

            currentRecord.updateDisplayType({
                id: 'custrecord_hrx_vendor_status_list',
                displayType: serverWidget.FieldDisplayType.HIDDEN
            });
        }
    }

    return {
        fieldChanged: fieldChanged
    }

}

);

----HERE IS THE ERROR

Body:
As the error message says, you are trying to load a module that is not available. You are writing a client script, and trying to load a module that is only for server-side scripts.

Additionally, N/currentRecord#CurrentRecord does not have a updateDisplayType() method.

The way to hide a field in a SS2.0 client script is:

currentRecord.getField({
  fieldId: 'custrecord_hrx_vendor_status_list'
}).isDisplay = false;


问:
Converting an IEnumerable<string> to IEnumerable<ListItem>
I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable'
  to
  'System.Web.UI.WebControls.ListItem'

```<code>public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}
</code>```

答:
You don't need to yield return from ... but simply return from ... or you could:

```<code>private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
{
    return results.Select(s => new ListItem(s));
}
</code>```

or even get rid of this function and:

```<code>dropDown.Items.AddRange(items.Select(s => new ListItem(s)).ToArray());
</code>```

Body:
I'm getting this error which while trying to use the yield return feature in C#. The error appears on the select inside visual studio and I don't really understand it. In my mind I'm converting a string to a ListItem and then returning the lot as an IEnumerable. My understanding of yield return and IEnumerable might very well be off the mark so any help would be appreciated. The commented code is the old school way of doing it which does work properly.

Cannot implicitly convert type
  'System.Collections.Generic.IEnumerable'
  to
  'System.Web.UI.WebControls.ListItem'

public partial class CloseIncident : System.Web.UI.Page
{
    private ClevelandIncidentRepository repo = new ClevelandIncidentRepository();

    protected void Page_Load(object sender, EventArgs e)
    {
        SetDropDown(InitialType, repo.GetMainTypes());
    }

    private void SetDropDown(DropDownList dropDown, IEnumerable<string> items)
    {
        dropDown.Items.Clear();
        dropDown.Text = string.Empty;
        dropDown.Enabled = items.Count() > 0;

        dropDown.Items.AddRange(ToListItem(items).ToArray());
    }

    private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
    {
        yield return from result in results
                     select new ListItem(result);

        //List<ListItem> items = new List<ListItem>();

        //items.AddRange(from result in results
        //               select new ListItem(result));

        //return items;
    }
}

Body:
You don't need to yield return from ... but simply return from ... or you could:

private IEnumerable<ListItem> ToListItem(IEnumerable<string> results)
{
    return results.Select(s => new ListItem(s));
}

or even get rid of this function and:

dropDown.Items.AddRange(items.Select(s => new ListItem(s)).ToArray());

ContentLicense: CC BY-SA 2.5


问:
last entry per group with additional conditions
I have the following code for MYSQL.

```<code>SELECT p1.*
  FROM `tags` p1
  LEFT
  JOIN `tags` p2
    ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp)
 WHERE p2.timestamp IS NULL
</code>```

I want to add the conditional "WHERE unitid = 5".  I'm having a brain fart moment and cannot figure out where to put that.

the source table looks like this:

```<code>Let me clarify what I want this to do.  I have one table.
</code>```

The structure looks like this :

```<code>unitid - cabinetid - timestamp
5        -      6          - timestamp
5        -       7        - timestamp
6        -       6        -   timestamp
7       -        8        - timestamp
</code>```

I want to get all entries for unitid 5, and get the latest entry for each cabinetid

答:
```<code>SELECT p1.*
  FROM tags p1
  LEFT
  JOIN tags p2
   ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp)
 WHERE p2.timestamp IS NULL
   and unitid = 5
</code>```

<p>sorry if not right </p>

Body:
I have the following code for MYSQL.

SELECT p1.*
  FROM `tags` p1
  LEFT
  JOIN `tags` p2
    ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp)
 WHERE p2.timestamp IS NULL

I want to add the conditional "WHERE unitid = 5".  I'm having a brain fart moment and cannot figure out where to put that.

the source table looks like this:

Let me clarify what I want this to do.  I have one table.

The structure looks like this :

unitid - cabinetid - timestamp
5        -      6          - timestamp
5        -       7        - timestamp
6        -       6        -   timestamp
7       -        8        - timestamp

I want to get all entries for unitid 5, and get the latest entry for each cabinetid

Body:
SELECT p1.*
  FROM tags p1
  LEFT
  JOIN tags p2
   ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp)
 WHERE p2.timestamp IS NULL
   and unitid = 5

sorry if not right


问:
PHP Extracting MYSQL Value Issue
I have 2 tables: users and transactions

In users I have: userid, name, email

And in transactions I have: id, idsender, idreceiver

I want to make a log-table showing all the transactions and I want them to be displayed like: Transaction ID - SENDER'S NAME - RECEIVER'S NAME

I tried like this but it doesn't seem to work, at "Receiver" it doesn't show anything .. :

```<code>echo "<table>";
echo "<tr>";
echo "<th>Transaction ID</th>";
echo "<th>Sender</th>";
echo "<th>Receiver</th>";
echo "</tr>";

    $resultuser = mysqli_query($conn, "SELECT * FROM users");
    $rowuser=mysqli_fetch_array($resultuser);

    $resulttrans = mysqli_query($conn, "SELECT * FROM transactions");
    $rowtrans=mysqli_fetch_array($resulttrans);

    $ress=mysqli_query($conn, "SELECT * FROM transactions");

            while($row=mysqli_fetch_array($ress)){
                echo "<tr>";
                echo "<td>".$row['id']."</td>";
                echo "<td>"." same as receiver"."</td>";
            $receiver=mysqli_query($conn, "SELECT name FROM users WHERE userid='" . $rowtrans['idreceiver'] . "'");
            $receivername = mysqli_fetch_array($receiver);

                echo "<td>". $receivername ."</td>";
                echo "</tr>";
            }
</code>```

答:
Don't use two queries. Join the two tables in one query:</p>

```<code>$ress = mysqli_query("SELECT t.id, u1.name AS sendername, u2.name AS receivername
    FROM transactions AS t
    JOIN users AS u1 ON u1.userid = t.idsender
    JOIN users AS u2 ON u2.userid = t.idreceiver");
while ($row = mysqli_fetch_assoc($ress)) {
    echo "<tr>";
    echo "<td>".$row['id']."</td>";
    echo "<td>" . $row['sendername'] ."</td>";
    echo "<td>" . $row['receivername'] . "</td>";
    echo "</tr>";
}
</code>```

Title: PHP Extracting MYSQL Value Issue

Body:
I have 2 tables: users and transactions

In users I have: userid, name, email

And in transactions I have: id, idsender, idreceiver

I want to make a log-table showing all the transactions and I want them to be displayed like: Transaction ID - SENDER'S NAME - RECEIVER'S NAME

I tried like this but it doesn't seem to work, at "Receiver" it doesn't show anything .. :

echo "
";
echo "
";
echo "Transaction ID	";
echo "Sender	";
echo "Receiver	";
echo "
";

    $resultuser = mysqli_query($conn, "SELECT * FROM users");
    $rowuser=mysqli_fetch_array($resultuser);

    $resulttrans = mysqli_query($conn, "SELECT * FROM transactions");
    $rowtrans=mysqli_fetch_array($resulttrans);

    $ress=mysqli_query($conn, "SELECT * FROM transactions");

            while($row=mysqli_fetch_array($ress)){
                echo "
";
                echo "".$row['id']."	";
                echo ""." same as receiver"."	";
            $receiver=mysqli_query($conn, "SELECT name FROM users WHERE userid='" . $rowtrans['idreceiver'] . "'");
            $receivername = mysqli_fetch_array($receiver);

                echo "". $receivername ."	";
                echo "
";
            }

Body:
Don't use two queries. Join the two tables in one query:

$ress = mysqli_query("SELECT t.id, u1.name AS sendername, u2.name AS receivername
    FROM transactions AS t
    JOIN users AS u1 ON u1.userid = t.idsender
    JOIN users AS u2 ON u2.userid = t.idreceiver");
while ($row = mysqli_fetch_assoc($ress)) {
    echo "<tr>";
    echo "<td>".$row['id']."</td>";
    echo "<td>" . $row['sendername'] ."</td>";
    echo "<td>" . $row['receivername'] . "</td>";
    echo "</tr>";
}


问:
Check for changes in specifics files with batch not working as expected
I have differents files, and I want to check for any changes in any of them, using batch. This is what I have:

```<code>@echo off
setlocal enableDelayedExpansion
set "list=test.txt test1.txt"

:loop
timeout -t 1 >nul
for %%j in (%list%) do (
    REM Here only prints test.txt
    echo %%j
    for %%i in (%%j) do echo %%~ai|find "a">nul || goto :loop
    echo file was changed %%j
    attrib -a %%j
)
goto :loop
</code>```

If I use only one file, works, but not with two or more. The idea is, that echo file was changed %%j only outputs the correct file, and not both.

Any ideas?

EDIT:

If I do some changes:

```<code>@echo off
title LAN chat reader
setlocal enableDelayedExpansion
set "list=test.txt test1.txt"

:loop
timeout -t 1 >nul
for %%j in (%list%) do (
    echo %%j
    echo %%~aj|find "a">nul || goto :loop
    echo file was changed %%j
    attrib -a %%j
)
goto :loop
</code>```

works, but only alerts me the changes in the second file, after I make changes in the first. I can understand that the problem is in the loop, so there is where I'm confused.

答:
I'd suggest a couple of things.

1: Use

```<code>call :CheckFile "%%j"
</code>```

instead of a nested for loop - makes things easier to read.

2: you can use DIR to check the attribute a bit more directly:

```<code>dir /aa %%j > nul 2>&1 && attrib -a %%j
</code>```

Both together looks something like:

```<code>:loop
    timeout -t 1 >nul
    for %%j in (%list%) do call :CheckFile "%%j"
    goto :loop

:CheckFile
    echo %1
    dir /aa %1 > nul 2>&1 || goto :EOF
    echo file was changed %1
    attrib -a %1
    goto :EOF
</code>```

Body:
I have differents files, and I want to check for any changes in any of them, using batch. This is what I have:

@echo off
setlocal enableDelayedExpansion
set "list=test.txt test1.txt"

:loop
timeout -t 1 >nul
for %%j in (%list%) do (
    REM Here only prints test.txt
    echo %%j
    for %%i in (%%j) do echo %%~ai|find "a">nul || goto :loop
    echo file was changed %%j
    attrib -a %%j
)
goto :loop

If I use only one file, works, but not with two or more. The idea is, that echo file was changed %%j only outputs the correct file, and not both.

Any ideas?

EDIT:

If I do some changes:

@echo off
title LAN chat reader
setlocal enableDelayedExpansion
set "list=test.txt test1.txt"

:loop
timeout -t 1 >nul
for %%j in (%list%) do (
    echo %%j
    echo %%~aj|find "a">nul || goto :loop
    echo file was changed %%j
    attrib -a %%j
)
goto :loop

works, but only alerts me the changes in the second file, after I make changes in the first. I can understand that the problem is in the loop, so there is where I'm confused.

Body:
I'd suggest a couple of things.

1: Use

call :CheckFile "%%j"

instead of a nested for loop - makes things easier to read.

2: you can use DIR to check the attribute a bit more directly:

dir /aa %%j > nul 2>&1 && attrib -a %%j

Both together looks something like:

:loop
    timeout -t 1 >nul
    for %%j in (%list%) do call :CheckFile "%%j"
    goto :loop

:CheckFile
    echo %1
    dir /aa %1 > nul 2>&1 || goto :EOF
    echo file was changed %1
    attrib -a %1
    goto :EOF


问:
How to debug a stackoverflowexception in .NET
Scenario:

I've just been on a roll and implemented a bunch of code, but when I execute it I get thrown a StackOverflowException? The StackOverflowException doesn't have a stacktrace so I'm stuck. I know why a stack overflow might occur, but to fix it I need to know where it's root is.

All I'm getting is: An unhandled exception of type 'System.StackOverflowException' occurred in tag-you're-it.dll

Options:

Scan through all the changes and try to pin point the problem. (could be slow)

Use a debugger and step through till you find the problem. (probably better than 1.)

Use a profile and look for the most called methods.

?

PS:

This is a hypothetical situation (although not too uncommon) and therefore no code is available.

答: You can execute the program on debug mode and pause it. On the current callstack you can see that there are a method or a group of method that appears several times, these are the problematic methods. Put a break point on this method and look what its calling itself all the time.</p>


问:
Gradle 3.3 Error Need Java 7 or Later Unsolved
i just imported some project that i bought from my friend.
Once i import it to Android Studio 2.1.2 i just get this messages
"Error:Gradle 3.3 requires Java 7 or later to run. You are currently using Java 6."

I have install Java 7 and 8 in my mac. I have change the directory in Default Project Structure, but still that messages always appear and i can't do anything with the code.

Please master, help me.

答:
Ran into the same issue, but I needed to keep java 6 for macOS legacy reasons (as I commented on Shubhendu's post).  So I ended up downloading java 8 jdk found here

and on android studio 3.3 at least here is the rough path I took:

I right clicked project -> open module settings -> sdk location -> uncheck use embedded jdk -> added path to new 1.8 jdk which for me it was

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home


问:
GROUP BY not NULL values
I have a Hive table (no primary key) that looks similar to:

```<code>X      Y
-------------
1      a
2      a
2      a
1      b
1      b
2      c
2      NULL
1      NULL
2      d
</code>```

Note the X column can be values other than just 1 and 2.

The query if I don't want to do GROUP BY would be:

```<code>SELECT X, Y
FROM my_table
</code>```

I want to do a GROUP BY operation on column Y where the value isn't NULL. Moreover, I want to keep the NULL value for Y. So the resulting table would look like:

```<code>X      Y
-------------
1      a
1      b
2      c
2      NULL
1      NULL
2      d
</code>```

Note, I don't care which X gets selected.

Based on this question, my query would be:

```<code>SELECT
    IFNULL(Y, UUID()) AS unq_Y,
    any(X) AS X
FROM my_table
GROUP BY unq_Y
</code>```

However, unq_Y would be whatever UUID() returns if Y is NULL, the query result would be:

```<code>X      unq_Y
-------------
1      a
1      b
2      c
2      UUID()_result
1      UUID()_result
2      d
</code>```

How can I avoid this?

答:
It's quite simple if the order of result set is not important. Just use union all as follows:

```<code>SELECT
    X AS X,
    Y AS unq_Y
FROM my_table
where y is not null
GROUP BY unq_Y
    union all
SELECT
    X AS X,
    Y AS unq_Y
FROM my_table
where y is null
;
</code>```

DEMO

Hope it helps!

Title: GROUP BY not NULL values

Body:
I have a Hive table (no primary key) that looks similar to:

X      Y
-------------
1      a
2      a
2      a
1      b
1      b
2      c
2      NULL
1      NULL
2      d

Note the X column can be values other than just 1 and 2.

The query if I don't want to do GROUP BY would be:

SELECT X, Y
FROM my_table

I want to do a GROUP BY operation on column Y where the value isn't NULL. Moreover, I want to keep the NULL value for Y. So the resulting table would look like:

X      Y
-------------
1      a
1      b
2      c
2      NULL
1      NULL
2      d

Note, I don't care which X gets selected.

Based on this question, my query would be:

SELECT
    IFNULL(Y, UUID()) AS unq_Y,
    any(X) AS X
FROM my_table
GROUP BY unq_Y

However, unq_Y would be whatever UUID() returns if Y is NULL, the query result would be:

X      unq_Y
-------------
1      a
1      b
2      c
2      UUID()_result
1      UUID()_result
2      d

How can I avoid this?

Body:
It's quite simple if the order of result set is not important. Just use union all as follows:

SELECT
    X AS X,
    Y AS unq_Y
FROM my_table
where y is not null
GROUP BY unq_Y
    union all
SELECT
    X AS X,
    Y AS unq_Y
FROM my_table
where y is null
;

DEMO

Hope it helps!


问:
How to Assign screen results from a function to variables in R
I'm new in R. I am using a Library called "CircStat". Functions in that library print the results on the screen, for example

```<code>rao.spacing(angles)
</code>```

gives

```<code>Rao's Spacing Test of Uniformity

Test Statistic = 155.9671

0.001 < P-value < 0.01
</code>```

where "rao.spacing is the function, and "angles" is a list of several angles in rad.

I need to pass the output, specifically, "155.9671" to a variable to use it in other parts of my code, How can I do that?

I prefer to do NOT write to a file and read from that, because I need to use the function for more that 50,000. And printing would be very time consuming.

Thanks,
Moe

答:
Apparently, the author of CircStats didn't think functions needed to return a value--rao.spacing() is designed to return NULL (note in the help for rao.spacing(), the VALUE section is simpley "NULL").

However, if you examine the function itself (hit F2 in Rstudio, or type in the function without any parenthesis or arguments), it's pretty simple to hack in a return value by creating your own version:

```<code>rao2  <- function (x, alpha = 0, rad = TRUE)
{
  rao.table <- NULL
  data(rao.table, package = "CircStats", envir = sys.frame(which = sys.nframe()))
  if (rad == TRUE)
    x <- deg(x)
  x <- sort(x%%360)
  n <- length(x)
  spacings <- c(diff(x), x[1] - x[n] + 360)
  U <- 1/2 * sum(abs(spacings - 360/n))
  if (n < 4)
    stop("Sample size too small")
  if (n <= 30)
    table.row <- n - 3
  else if (n <= 32)
    table.row <- 27
  else if (n <= 37)
    table.row <- 28
  else if (n <= 42)
    table.row <- 29
  else if (n <= 47)
    table.row <- 30
  else if (n <= 62)
    table.row <- 31
  else if (n <= 87)
    table.row <- 32
  else if (n <= 125)
    table.row <- 33
  else if (n <= 175)
    table.row <- 34
  else if (n <= 250)
    table.row <- 35
  else if (n <= 350)
    table.row <- 36
  else if (n <= 450)
    table.row <- 37
  else if (n <= 550)
    table.row <- 38
  else if (n <= 650)
    table.row <- 39
  else if (n <= 750)
    table.row <- 40
  else if (n <= 850)
    table.row <- 41
  else if (n <= 950)
    table.row <- 42
  else table.row <- 43
  if (alpha == 0) {
    cat("\n")
    cat("       Rao's Spacing Test of Uniformity", "\n",
        "\n")
    cat("Test Statistic =", round(U, 5), "\n")
    if (U > rao.table[table.row, 1])
      cat("P-value < 0.001", "\n", "\n")
    else if (U > rao.table[table.row, 2])
      cat("0.001 < P-value < 0.01", "\n", "\n")
    else if (U > rao.table[table.row, 3])
      cat("0.01 < P-value < 0.05", "\n", "\n")
    else if (U > rao.table[table.row, 4])
      cat("0.05 < P-value < 0.10", "\n", "\n")
    else cat("P-value > 0.10", "\n", "\n")
  }
  else {
    cat("\n")
    cat("       Rao's Spacing Test of Uniformity", "\n",
        "\n")
    cat("Test Statistic =", round(U, 5), "\n")
    if (sum(alpha == c(0.001, 0.01, 0.05, 0.1)) == 0)
      stop("Invalid significance level")
    table.col <- (1:4)[alpha == c(0.001, 0.01, 0.05, 0.1)]
    critical <- rao.table[table.row, table.col]
    cat("Level", alpha, "critical value =", critical, "\n")
    if (U > critical)
      cat("Reject null hypothesis of uniformity", "\n",
          "\n")
    else cat("Do not reject null hypothesis of uniformity",
             "\n", "\n")
  }

  return(U)
}

myvalue  <- rao2(angles)
</code>```

Note the return(U) at the end, which kicks out the value you're looking for (though, without performing the sort of significance testing that the function is designed to do--you'll need to perform those sort of sanity checks yourself).

Body:
I'm new in R. I am using a Library called "CircStat". Functions in that library print the results on the screen, for example

rao.spacing(angles)

gives

Rao's Spacing Test of Uniformity

Test Statistic = 155.9671

0.001 < P-value < 0.01

where "rao.spacing is the function, and "angles" is a list of several angles in rad.

I need to pass the output, specifically, "155.9671" to a variable to use it in other parts of my code, How can I do that?

I prefer to do NOT write to a file and read from that, because I need to use the function for more that 50,000. And printing would be very time consuming.

Thanks,
Moe

Body:
Apparently, the author of CircStats didn't think functions needed to return a value--rao.spacing() is designed to return NULL (note in the help for rao.spacing(), the VALUE section is simpley "NULL").

However, if you examine the function itself (hit F2 in Rstudio, or type in the function without any parenthesis or arguments), it's pretty simple to hack in a return value by creating your own version:

rao2  <- function (x, alpha = 0, rad = TRUE)
{
  rao.table <- NULL
  data(rao.table, package = "CircStats", envir = sys.frame(which = sys.nframe()))
  if (rad == TRUE)
    x <- deg(x)
  x <- sort(x%%360)
  n <- length(x)
  spacings <- c(diff(x), x[1] - x[n] + 360)
  U <- 1/2 * sum(abs(spacings - 360/n))
  if (n < 4)
    stop("Sample size too small")
  if (n <= 30)
    table.row <- n - 3
  else if (n <= 32)
    table.row <- 27
  else if (n <= 37)
    table.row <- 28
  else if (n <= 42)
    table.row <- 29
  else if (n <= 47)
    table.row <- 30
  else if (n <= 62)
    table.row <- 31
  else if (n <= 87)
    table.row <- 32
  else if (n <= 125)
    table.row <- 33
  else if (n <= 175)
    table.row <- 34
  else if (n <= 250)
    table.row <- 35
  else if (n <= 350)
    table.row <- 36
  else if (n <= 450)
    table.row <- 37
  else if (n <= 550)
    table.row <- 38
  else if (n <= 650)
    table.row <- 39
  else if (n <= 750)
    table.row <- 40
  else if (n <= 850)
    table.row <- 41
  else if (n <= 950)
    table.row <- 42
  else table.row <- 43
  if (alpha == 0) {
    cat("\n")
    cat("       Rao's Spacing Test of Uniformity", "\n",
        "\n")
    cat("Test Statistic =", round(U, 5), "\n")
    if (U > rao.table[table.row, 1])
      cat("P-value < 0.001", "\n", "\n")
    else if (U > rao.table[table.row, 2])
      cat("0.001 < P-value < 0.01", "\n", "\n")
    else if (U > rao.table[table.row, 3])
      cat("0.01 < P-value < 0.05", "\n", "\n")
    else if (U > rao.table[table.row, 4])
      cat("0.05 < P-value < 0.10", "\n", "\n")
    else cat("P-value > 0.10", "\n", "\n")
  }
  else {
    cat("\n")
    cat("       Rao's Spacing Test of Uniformity", "\n",
        "\n")
    cat("Test Statistic =", round(U, 5), "\n")
    if (sum(alpha == c(0.001, 0.01, 0.05, 0.1)) == 0)
      stop("Invalid significance level")
    table.col <- (1:4)[alpha == c(0.001, 0.01, 0.05, 0.1)]
    critical <- rao.table[table.row, table.col]
    cat("Level", alpha, "critical value =", critical, "\n")
    if (U > critical)
      cat("Reject null hypothesis of uniformity", "\n",
          "\n")
    else cat("Do not reject null hypothesis of uniformity",
             "\n", "\n")
  }

  return(U)
}

myvalue  <- rao2(angles)

Note the return(U) at the end, which kicks out the value you're looking for (though, without performing the sort of significance testing that the function is designed to do--you'll need to perform those sort of sanity checks yourself).


问:
core-image-minimal has bluetooth
I am trying to build core-image-minimal receipe for iMx7 (Yocto project), the image gets successfully built but it has bluetooth, caam and lot of other stuff. How can I remove these from including in the minimal-image?

core-image-minimal should only have things required for just booting nothing else, somehow other packages are getting added. I didnt add anything in my local.config file.

MACHINE = "imx7dsabresd"

答:
bluetooth and wifi are enabled here:
imx7dsabresd.conf

You can add the following to your local.conf to remove bluetooth:

```<code>MACHINE_FEATURES_remove = "bluetooth"
</code>```

CAAM is enabled in the kernel config here:
defconfig

To change the kernel configuration you can either provide a new defconfig or use a configuration fragment. The following steps describe how to create a config fragment.

Run the following command and deselect the bluetooth related config options:

```<code>bitbake -c menuconfig virtual/kernel
</code>```

Run the following command to generate fragment.cfg in ${WORKDIR}

```<code>bitbake -c diffconfig virtual/kernel
</code>```

At this point if you do not have your own layer, create one by following this guide:
Creating Your Own Layer

Create the directory for the .bbappend and the configuration fragment:

```<code>mkdir -p ${PATH_TO_YOUR_LAYER}/recipes-kernel/linux/linux-fslc-imx/linux-fslc-imx/
</code>```

Move fragment.cfg from ${WORKDIR} to ${PATH_TO_YOUR_LAYER}/recipes-kernel/linux/linux-fslc-imx/linux-fslc-imx/

Create a ${PATH_TO_YOUR_LAYER}/recipes-kernel/linux/linux-fslc-imx_%.bbappend (assuming linux-fslc-imx is the correct kernel recipe for this board) and place the following in it:

```<code>FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRC_URI += "file://fragment.cfg"
</code>```

Additionally, you may find the Creating Configuration Fragments section of the manual helpful.

For more information about bbappends see:
mega-manual

Title: core-image-minimal has bluetooth

Body:
bluetooth and wifi are enabled here:
imx7dsabresd.conf

You can add the following to your local.conf to remove bluetooth:

MACHINE_FEATURES_remove = "bluetooth"

CAAM is enabled in the kernel config here:
defconfig

To change the kernel configuration you can either provide a new defconfig or use a configuration fragment. The following steps describe how to create a config fragment.

Run the following command and deselect the bluetooth related config options:

bitbake -c menuconfig virtual/kernel

Run the following command to generate fragment.cfg in ${WORKDIR}

bitbake -c diffconfig virtual/kernel

At this point if you do not have your own layer, create one by following this guide:
Creating Your Own Layer

Create the directory for the .bbappend and the configuration fragment:

mkdir -p ${PATH_TO_YOUR_LAYER}/recipes-kernel/linux/linux-fslc-imx/linux-fslc-imx/

Move fragment.cfg from ${WORKDIR} to ${PATH_TO_YOUR_LAYER}/recipes-kernel/linux/linux-fslc-imx/linux-fslc-imx/

Create a ${PATH_TO_YOUR_LAYER}/recipes-kernel/linux/linux-fslc-imx_%.bbappend (assuming linux-fslc-imx is the correct kernel recipe for this board) and place the following in it:

FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"
SRC_URI += "file://fragment.cfg"

Additionally, you may find the Creating Configuration Fragments section of the manual helpful.

For more information about bbappends see:
mega-manual


问:
NtQueryInformationFile(FileStreamInformation) fails with STATUS_END_OF_FILE
I deal with application that scans files at a location (identified by UNC path) and gathers various bits of information about them. One of such bits is a list of alternate files streams -- which gets retrieved via NtQueryInformationFile(..., FileStreamInformation) call.

This works for untold number of files with exception of very few -- for those few (mostly jpg originated from some camera, but also docx and zip) that function call fails with STATUS_END_OF_FILE. I can't find any explanation of why. There are other files in same directory(ies) that have no such problem, dir /r shows no alternate streams, copy works fine. Data corruption is very unlikely.

I would appreciate any ideas that may explain this. Thank you.

More info:

target is located on VNX 7500 (maybe a bug in their SMB server implementation?)

NTFS

答:
Something went wrong with alternate streams. Listing them fails, but if you copy file -- it arrives to destination without any alternate streams (and application works with copied file without problems). I suspect OS copy operation silently ignores alt stream-related failures and (if they happen) doesn't copy them.

So, basically, copying files elsewhere and copying them back (overwriting originals) fixes the problem.


答:
Turns out, I can just put the NULL check in the GROUP BY clause:

```<code>SELECT
    any(Y) AS Y,
    any(X) AS X
FROM my_table
GROUP BY COALESCE(Y, CAST(reflect("java.util.UUID", "randomUUID") AS STRING));
</code>```

My version of Hive doesn't support IFNULL() so COALESCE() is a good alternative. My version Hive also doesn't support UUID() so I called reflect() to get unique id.

Title: GROUP BY not NULL values

Body:
Turns out, I can just put the NULL check in the GROUP BY clause:

SELECT
    any(Y) AS Y,
    any(X) AS X
FROM my_table
GROUP BY COALESCE(Y, CAST(reflect("java.util.UUID", "randomUUID") AS STRING));

My version of Hive doesn't support IFNULL() so COALESCE() is a good alternative. My version Hive also doesn't support UUID() so I called reflect() to get unique id.


问:
How to call python script file under PHP?
I have two files in the same directory:

```<code>index.php
excel.py
</code>```

I tried to call excel.py in file index.php like:

```<code>$buff = system('python excel.py ' . $handle->file_dst_pathname, $retval);
</code>```

I use Windows 10

答:
Try it like this,

```<code>exec("C:\Python27\python.exe C:\dir...\file.py");
</code>```

The problem is you must call C:\Python27\python.exe Python exe file
 before python file.

Body:
I have two files in the same directory:

index.php
excel.py

I tried to call excel.py in file index.php like:

$buff = system('python excel.py ' . $handle->file_dst_pathname, $retval);

I use Windows 10

Body:
Try it like this,

exec("C:\Python27\python.exe C:\dir...\file.py");

The problem is you must call C:\Python27\python.exe Python exe file
 before python file.


问:
Django - new style middleware process_response
I'm using the new style middleware in Django, and for some reason, it never gets to the 'process_response' part. If I understand correctly, it should occur after the

```<code>response = self.get_response(request)
</code>```

in __call__ function. But it never gets to the code beyond that line. What could be the reason?

This is how my middleware is defined:

```<code>class GlobalThreadVarMiddleware(object):
_threadmap = {}

def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    self._threadmap[_thread.get_ident()] = {}
    self._threadmap[_thread.get_ident()]['data_manager'] = DataManager()

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.
    current_data_manager = self.get_current_data_manager()
    current_data_manager.trigger_events()
    del self._threadmap[_thread.get_ident()]['data_manager']

    return response

@classmethod
def get_current_data_manager(cls):
    return cls._threadmap[_thread.get_ident()]['data_manager']
</code>```

I'm using Django 1.10. This is the MIDDLEWARE parameter in settings.py:

```<code>MIDDLEWARE = [

'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'workflows.api.middleware.ApiCsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

'workflows.api.middleware.ExceptionMiddleware',
'workflows.api.global_thread_variables_middleware.GlobalThreadVarMiddleware'
]
</code>```

It's the last one in the list.

This is the ExceptionMiddleware code:

```<code>class ExceptionMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
    guid, code, error, data, error_status = ExceptionMiddleware.log_exception(request, exception)

    return JsonResponse(
        {
            "error_id": guid,
            "code": code,
            "message": error,
            "data": data
        },
        status=error_status
    )

@staticmethod
def log_exception(request, exception):
    guid = str(uuid.uuid4())
    error = code = data = error_status = None

    if isinstance(exception, FlowException):
        error = str(exception.message)
        code = exception.code
        data = str(exception.data)
        error_status = exception.code
    elif isinstance(exception, Exception):
        error = str(exception.args)
        code = 10001
        data = {'exception_type': str(type(exception))}
        error_status = status.HTTP_500_INTERNAL_SERVER_ERROR

    logging.getLogger(__name__).exception('error_id: ' + guid,
                                          {'request': request, 'error_data': data, 'error_code': code,
                                           'error_message': error})
    kwargs = {} #"exc": exception, "tb": exception.__traceback__, "value": error}
    if newrelic.agent.current_transaction() is None:
        app = newrelic.agent.application()
        if app.active is False:
            app.activate()
            newrelic.agent.register_application()
        kwargs["application"] = app
    newrelic.agent.record_exception(**kwargs)

    return guid, code, error, data, error_status
</code>```

答:
I can't comment, because of my bad reputation.

I've seen your question before you edited it and it included ImportError that was directly related to your problem. Did you fix that ImportError?

New middleware style in Django works as advertised. I have implemented this new style many times and just to be sure, I even tested your code with certain modification to get it working and there is nothing wrong with it in general.

Body:
I'm using the new style middleware in Django, and for some reason, it never gets to the 'process_response' part. If I understand correctly, it should occur after the

response = self.get_response(request)

in __call__ function. But it never gets to the code beyond that line. What could be the reason?

This is how my middleware is defined:

class GlobalThreadVarMiddleware(object):
_threadmap = {}

def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    self._threadmap[_thread.get_ident()] = {}
    self._threadmap[_thread.get_ident()]['data_manager'] = DataManager()

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.
    current_data_manager = self.get_current_data_manager()
    current_data_manager.trigger_events()
    del self._threadmap[_thread.get_ident()]['data_manager']

    return response

@classmethod
def get_current_data_manager(cls):
    return cls._threadmap[_thread.get_ident()]['data_manager']

I'm using Django 1.10. This is the MIDDLEWARE parameter in settings.py:

MIDDLEWARE = [

'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'workflows.api.middleware.ApiCsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

'workflows.api.middleware.ExceptionMiddleware',
'workflows.api.global_thread_variables_middleware.GlobalThreadVarMiddleware'
]

It's the last one in the list.

This is the ExceptionMiddleware code:

class ExceptionMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
    guid, code, error, data, error_status = ExceptionMiddleware.log_exception(request, exception)

    return JsonResponse(
        {
            "error_id": guid,
            "code": code,
            "message": error,
            "data": data
        },
        status=error_status
    )

@staticmethod
def log_exception(request, exception):
    guid = str(uuid.uuid4())
    error = code = data = error_status = None

    if isinstance(exception, FlowException):
        error = str(exception.message)
        code = exception.code
        data = str(exception.data)
        error_status = exception.code
    elif isinstance(exception, Exception):
        error = str(exception.args)
        code = 10001
        data = {'exception_type': str(type(exception))}
        error_status = status.HTTP_500_INTERNAL_SERVER_ERROR

    logging.getLogger(__name__).exception('error_id: ' + guid,
                                          {'request': request, 'error_data': data, 'error_code': code,
                                           'error_message': error})
    kwargs = {} #"exc": exception, "tb": exception.__traceback__, "value": error}
    if newrelic.agent.current_transaction() is None:
        app = newrelic.agent.application()
        if app.active is False:
            app.activate()
            newrelic.agent.register_application()
        kwargs["application"] = app
    newrelic.agent.record_exception(**kwargs)

    return guid, code, error, data, error_status


问:
Requirements for Keyword Argument Unpacking
What is required to support keyword argument unpacking for a custom class in Python? In both the Python 2.7 and Python 3.6 interpreters the following error message is given when trying to unpack an incompatible type:

```<code>>>> dict(**None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type object argument after ** must be a mapping, not NoneType
</code>```

Does mapping mean the object has to specifically subclass collections.Mapping? Or is mapping in this case one of those pseudo types such as iterable where you don't have to explicitly subclass collections.Iterable to support iter()? Does this behavior differ between Python 2 and 3?

答:
Here is the Python glossary entry for mapping:

A container object that supports arbitrary key lookups and implements the methods specified in the Mapping or MutableMapping abstract base classes. Examples include dict, collections.defaultdict, collections.OrderedDict and collections.Counter.

Body:
What is required to support keyword argument unpacking for a custom class in Python? In both the Python 2.7 and Python 3.6 interpreters the following error message is given when trying to unpack an incompatible type:

>>> dict(**None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type object argument after ** must be a mapping, not NoneType

Does mapping mean the object has to specifically subclass collections.Mapping? Or is mapping in this case one of those pseudo types such as iterable where you don't have to explicitly subclass collections.Iterable to support iter()? Does this behavior differ between Python 2 and 3?


问:
(C#) OpenXML import xlsx into DataTable with correct column data type
I am using OpenXML library to import excelsheet(.xslx) into a DataTable using C#.

The first row of the xlsx contains the column name, so i start adding the column in the DataTable:

```<code>foreach (Cell cell in row.Descendants<Cell>())
{
    dt.Columns.Add(GetXlsxCellValue(sharedStringTableList, cell));
}
</code>```

Then i loop all the other rows and i fill the DataTable by adding any single row to my DataTable in a similar way with any cell in the current row.

Now, imagine that my excel has two columns like this

excelExample

The first row contain the column name, so the first cell has a DataType = string (the text is stored in sharedStringTableList).

All the other rows contains ONLY Number in the first column (and, in excel, the entire column it's also format as "number").

At the end, in my DataTable, the first column has the correct name ("Number") but the column DataType is STRING.

The question: how can i create my DataTable with the correct column DataType set in the xlsx at the beginning?
The method "Columns.Add()" allow you to specify the column dataType, but in the first row all the cell have DataType = string, so i need to check the column DataType in other way.

Thanks in advance,

Andrea

...

答:
There is a library called ClosedXML that is a friendly wrapper for OpenXML I found much easier to use than straight OpenXML. There is an Enum (XLCellValues) that tells you what the excel data type is. This can be used to help you build the correct data column type.

Here is an example of how to navigate and parse the rows and columns into a simple class using closed xml, pretty similar to your example (but for a class instead of data table). There is also a method in that link/example that maps C# sharp types to excel column types that you could use in reverse (XLCellValues enum). It gets more complicated if you don't trust the given excel data type.

If you have a simple target class you are trying to extract out of the excel this nuget could work out of the box, but I think you want a DataTable output.

Hope this helps.

Body:
I am using OpenXML library to import excelsheet(.xslx) into a DataTable using C#.

The first row of the xlsx contains the column name, so i start adding the column in the DataTable:

foreach (Cell cell in row.Descendants<Cell>())
{
    dt.Columns.Add(GetXlsxCellValue(sharedStringTableList, cell));
}

Then i loop all the other rows and i fill the DataTable by adding any single row to my DataTable in a similar way with any cell in the current row.

Now, imagine that my excel has two columns like this

excelExample

The first row contain the column name, so the first cell has a DataType = string (the text is stored in sharedStringTableList).

All the other rows contains ONLY Number in the first column (and, in excel, the entire column it's also format as "number").

At the end, in my DataTable, the first column has the correct name ("Number") but the column DataType is STRING.

The question: how can i create my DataTable with the correct column DataType set in the xlsx at the beginning?
The method "Columns.Add()" allow you to specify the column dataType, but in the first row all the cell have DataType = string, so i need to check the column DataType in other way.

Thanks in advance,

Andrea

...


问:
JavaScript: set dropdown selected item based on option text
Say I have a dropdown list like this:

```<code><select id="MyDropDown">
    <option value="0">Google</option>
    <option value="1">Bing</option>
    <option value="2">Yahoo</option>
</select>
</code>```

and I want to set the selected value based on the option text, not the value with javascript. How can I go about doing this? For example, with c# I can do something like the example below and the the option with "Google" would be selected.

```<code>ListItem mt = MyDropDown.Items.FindByText("Google");
if (mt != null)
{
   mt.Selected = true;
}
</code>```

答:
A modern alternative:</p>

```<code>const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
</code>```

Body:
Say I have a dropdown list like this:

<select id="MyDropDown">
    <option value="0">Google</option>
    <option value="1">Bing</option>
    <option value="2">Yahoo</option>
</select>

and I want to set the selected value based on the option text, not the value with javascript. How can I go about doing this? For example, with c# I can do something like the example below and the the option with "Google" would be selected.

ListItem mt = MyDropDown.Items.FindByText("Google");
if (mt != null)
{
   mt.Selected = true;
}

Body:
A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);


问:
Webservice works on Android but not on IOS
I have written the below service in Angular 4. When I try to consume it
on Android it works, but on IOS I get error status: 0  for URL: null
Need to know if something is wrong in web-service code? </p>

```<code>getConversationData(userText : string){

    let userName = 'XYZ'
    let meetingType = 'ABC'
    let url = 'serverURL' + '/Conversation'

    return this.http.post(
      url,
      {
        headers : {'Content-Type': 'application/json charset=UTF-8',
                        'Accept': 'application/json'},
        "message" : userText,
        "username" : userName,
        "MeetingType" : meetingType
      },

    ).map(response => response.json())
  }
</code>```

答:
Another area I've had to adjust in these types of scenarios is whitelisting resources so that the app allows access.

https://cordova.apache.org/docs/en/latest/guide/appdev/whitelist/

See the <allow-intent> and <allow-navigation> areas.  I believe the ionic/cordova build process will inspect these and update the iOS plist.info file with this info too.

Body:
I have written the below service in Angular 4. When I try to consume it
on Android it works, but on IOS I get error status: 0  for URL: null
Need to know if something is wrong in web-service code?

getConversationData(userText : string){

    let userName = 'XYZ'
    let meetingType = 'ABC'
    let url = 'serverURL' + '/Conversation'

    return this.http.post(
      url,
      {
        headers : {'Content-Type': 'application/json charset=UTF-8',
                        'Accept': 'application/json'},
        "message" : userText,
        "username" : userName,
        "MeetingType" : meetingType
      },

    ).map(response => response.json())
  }


问:
Adding three dots at the bottom of
 tag when text overflows
This is my HTML code

```<code> <section class="mammaliaSection">
            <p>ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXT</p>
    </section>
</code>```

and this is my CSS code

```<code>#main section{
height:610px;
width:100%;
background-repeat:no-repeat;
background-size:cover;
position:relative;

}
 section p{
   position:absolute;
   display:block;
   width:325px;
   height:150px;
   font-size:36px;
   display:block;
   color:white;
   margin-left:15px;
   white-space:nowrap;
   overflow:hidden;
   text-overflow:ellipsis;
 }
</code>```

I want to add "..." at the bottom of p tag

Like so

My code shows three dots at the first line because of white-space:nowrap. Tried white-space:pre-line, but did not work.

答:
You can't do that with only CSS. You must use some JS for that. Please take a look at a simple JQuery code for adding three dots at end of an paragraph.

while ($('p').outerHeight() > $('.text-box').height()) {
    $('p').text(function (index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text-box{
height: 100px;
}</code>```

ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL

```

Hope this helps

Title: Adding three dots at the bottom of <p> tag when text overflows

Body:
This is my HTML code

ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXT

and this is my CSS code

#main section{
height:610px;
width:100%;
background-repeat:no-repeat;
background-size:cover;
position:relative;

}
 section p{
   position:absolute;
   display:block;
   width:325px;
   height:150px;
   font-size:36px;
   display:block;
   color:white;
   margin-left:15px;
   white-space:nowrap;
   overflow:hidden;
   text-overflow:ellipsis;
 }

I want to add "..." at the bottom of p tag

Like so

My code shows three dots at the first line because of white-space:nowrap. Tried white-space:pre-line, but did not work.

Body:
You can't do that with only CSS. You must use some JS for that. Please take a look at a simple JQuery code for adding three dots at end of an paragraph.

while ($('p').outerHeight() > $('.text-box').height()) {
    $('p').text(function (index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}

.text-box{
height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-box">
<p>ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL ANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL TEXTANIMAL </p>
</div>

Hope this helps


问:
Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
I would like to display the column B in my below SQL, but when I add it to the query it gives me the following error:

Column T2.B'
  is invalid in the select list because it is not contained in either an
  aggregate function or the GROUP BY clause.

My code:

```<code>SELECT A, COUNT(B) as T1, B
FROM T2
WHERE ID=1
GROUP BY A
</code>```

答:
The consequence of this is that you may need a rather insane-looking query, e. g.,

```<code>SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]
</code>```

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

Body:
I would like to display the column B in my below SQL, but when I add it to the query it gives me the following error:

Column T2.B'
  is invalid in the select list because it is not contained in either an
  aggregate function or the GROUP BY clause.

My code:

SELECT A, COUNT(B) as T1, B
FROM T2
WHERE ID=1
GROUP BY A

Body:
The consequence of this is that you may need a rather insane-looking query, e. g.,

SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.