问:
How to wrap array into string in laravel
How can i wrap my return array into string in laravel?
Some thing like this

Laravel:

```<code>    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = "No";
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';
    //end add custom css
    $columnDefinitions["index_number"] = $columnDefinition;
    return $columnDefinitions;
</code>```

Expected result

```<code>'[{
   apple: {
             label: "No"
             sortable: true
             tdClass: "text-center"
          }
}]'
</code>```

答:
As per the Laravel Documentation you can directly send the json response from your method

The json method will automatically set the Content-Type header to
  application/json, as well as convert the given array to JSON using the
  json_encode PHP function:

```<code>return response()->json([
    // You can pass your array values here
]);
</code>```

Laravel -> Http Responses -> Json Responses

Body:
How can i wrap my return array into string in laravel?
Some thing like this

Laravel:

    $columnDefinitions = array();

    $columnDefinition = new \stdClass();
    $columnDefinition->label = "No";
    $columnDefinition->sortable = true;
    $columnDefinition->thClass = 'width-50';
    $columnDefinition->tdClass = 'text-center';
    //end add custom css
    $columnDefinitions["index_number"] = $columnDefinition;
    return $columnDefinitions;

Expected result

'[{
   apple: {
             label: "No"
             sortable: true
             tdClass: "text-center"
          }
}]'

Body:
As per the Laravel Documentation you can directly send the json response from your method

The json method will automatically set the Content-Type header to
  application/json, as well as convert the given array to JSON using the
  json_encode PHP function:

return response()->json([
    // You can pass your array values here
]);

Laravel -> Http Responses -> Json Responses


来源: stackexchange

问:
How to update ag-grid versions?
Previously I used:

"ag-grid": "^18.1.2",

"ag-grid-angular": "^18.1.1"

"ag-grid-enterprise": "^18.1.1" version.

Since the licence was expired I got the new version licences.

And then I added:

"@ag-grid-community/angular": "^22.1.1",

"@ag-grid-community/core": "^22.1.1",

"@ag-grid-enterprise/all-modules": "^22.1.1",

"@ag-grid-enterprise/core": "^22.1.1",

"@ag-grid-community/client-side-row-model": "^22.1.1",

And also I added

```<code>@import "./node_modules/@ag-grid-enterprise/all-modules/dist/styles/ag-grid.scss";
@import "./node_modules/@ag-grid-enterprise/all-modules/dist/styles/ag-theme-balham/sass/ag-theme-balham.scss";
@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";
</code>```

to styles.css file.

But row lines are missed in ag-grid for an updated version.

If you can give me suggestions it will be a great help for me.

This is another image of ag-grid.

答:
I think you also need to upgrade "ag-grid": "^18.1.2", to "ag-grid-angular": "^20.1.0", to do so you need to follow changes

Step1: go to package.json and modify "ag-grid": "^18.1.2", to "ag-grid-angular": "20.1.0",

Step2: change your typescript version "typescript": "~2.7.2" to "typescript": "~3.2.4"

Step3: Run npm update in your project.

Step4: now run ng serve

ContentLicense: CC BY-SA 4.0

Title: How to update ag-grid versions?

Body:
Previously I used:

"ag-grid": "^18.1.2",

"ag-grid-angular": "^18.1.1"

"ag-grid-enterprise": "^18.1.1" version.

Since the licence was expired I got the new version licences.

And then I added:

"@ag-grid-community/angular": "^22.1.1",

"@ag-grid-community/core": "^22.1.1",

"@ag-grid-enterprise/all-modules": "^22.1.1",

"@ag-grid-enterprise/core": "^22.1.1",

"@ag-grid-community/client-side-row-model": "^22.1.1",

And also I added

@import "./node_modules/@ag-grid-enterprise/all-modules/dist/styles/ag-grid.scss";
@import "./node_modules/@ag-grid-enterprise/all-modules/dist/styles/ag-theme-balham/sass/ag-theme-balham.scss";
@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";

to styles.css file.

But row lines are missed in ag-grid for an updated version.

If you can give me suggestions it will be a great help for me.

This is another image of ag-grid.


问:
Evaluate string expression and convert to bool?
I want to evaluate the string expression and convert the result to bool.

For example

string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;

the above expression has to evaluate and return true.

Can anyone suggest how to evaluate the expression and return bool value?

答:
If your requirement is to get expressoin output as string "true" then use this,

```<code>string expression = Convert.ToString(!((71 > 70) && (80 > 71)) || 72 < 71);
</code>```

And if requirement is to get bool "true" then use this,

```<code>bool expression = !((71 > 70) && (80 > 71)) || 72 < 71;
</code>```

But your expression is like it will return false, to make it true remove "!" as below,

```<code>string expression = Convert.ToString(((71 > 70) && (80 > 71)) || 72 < 71);
bool bool_expression = ((71 > 70) && (80 > 71)) || 72 < 71;
</code>```

Body:
If your requirement is to get expressoin output as string "true" then use this,

string expression = Convert.ToString(!((71 > 70) && (80 > 71)) || 72 < 71);

And if requirement is to get bool "true" then use this,

bool expression = !((71 > 70) && (80 > 71)) || 72 < 71;

But your expression is like it will return false, to make it true remove "!" as below,

string expression = Convert.ToString(((71 > 70) && (80 > 71)) || 72 < 71);
bool bool_expression = ((71 > 70) && (80 > 71)) || 72 < 71;


问:
Is it possible to print out something in the browser debug console, so that when clicked on, will invoke a function?
While debugging, I might have an element el, and I can print it out using console.log(el).

There can be 50 or even 100 of them, while debugging.  Can I print out something in the debug console in Google Chrome, so that when I click on it, will make the element come into focus in the webpage?

I tried:

```<code>    let tmpLink = document.createElement("a");
    tmpLink.href = "#";   // now it is a link instead of anchor
    tmpLink.innerHTML = "Click Me";
    tmpLink.addEventListener("click", function() {
      el.focus();
    });
    console.log(tmpLink);
</code>```

and the link is printed out in the debug console, except when I click on it, doesn't bring me to the element on page. Is there a way to do it?

One less desirable way is to do

```<code>window.focusArr = window.focusArr || [];
window.focusArr.push(el);
console.log(`Element ${window.focusArr.length - 1}`);
</code>```

so I can just do in the console:

```<code>focusArr[21].focus()
</code>```

But is there a way to make clicking on something work in the debug console?

答:
Just log the element itself.

let e = document.getElementById('main');
console.log(e)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
Hello
</div></code>```

You can then right click on the element in the log message and choose "Scroll into view"

Body:
While debugging, I might have an element el, and I can print it out using console.log(el).

There can be 50 or even 100 of them, while debugging.  Can I print out something in the debug console in Google Chrome, so that when I click on it, will make the element come into focus in the webpage?

I tried:

    let tmpLink = document.createElement("a");
    tmpLink.href = "#";   // now it is a link instead of anchor
    tmpLink.innerHTML = "Click Me";
    tmpLink.addEventListener("click", function() {
      el.focus();
    });
    console.log(tmpLink);

and the link is printed out in the debug console, except when I click on it, doesn't bring me to the element on page. Is there a way to do it?

One less desirable way is to do

window.focusArr = window.focusArr || [];
window.focusArr.push(el);
console.log(`Element ${window.focusArr.length - 1}`);

so I can just do in the console:

focusArr[21].focus()

But is there a way to make clicking on something work in the debug console?

Body:
Just log the element itself.

let e = document.getElementById('main');
console.log(e)

<div id="main">
Hello
</div>

You can then right click on the element in the log message and choose "Scroll into view"


问:
Rownum for a column with lag
I have this query

```<code>SELECT CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee
ORDER   BY emp_id;
</code>```

And it shows me result like this: Resultset

I want to add row number (first column SN) for Employee ID for in between rows I want to set it as null, for e.g. For Employee ID -> S/N 2-> F904 (SN should be null). How can I do that?

答:
You can use the outer query to create the SN column as follows:

```<code>SELECT CASE WHEN "S/N" = 1 THEN '<1>' END AS SN, T.* FROM -- added this
(SELECT
       CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee ) T
ORDER BY "Employee ID", "S/N"; -- Added this
</code>```

Note that I have also changed the ORDER BY clause (which is moved to the outer query).

Cheers!!

Title: Rownum for a column with lag

Body:
I have this query

SELECT CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee
ORDER   BY emp_id;

And it shows me result like this: Resultset

I want to add row number (first column SN) for Employee ID for in between rows I want to set it as null, for e.g. For Employee ID -> S/N 2-> F904 (SN should be null). How can I do that?

Body:
You can use the outer query to create the SN column as follows:

SELECT CASE WHEN "S/N" = 1 THEN '<1>' END AS SN, T.* FROM -- added this
(SELECT
       CASE WHEN LAG(emp_id) OVER( ORDER BY NULL ) = emp_id THEN '-'
            ELSE  emp_id END "Employee ID",
       row_number() over (partition by emp_id order by emp_id) as "S/N",
       family_mem_id   "MemID",
       CASE WHEN LAG(emp_id) OVER(ORDER BY NULL ) = emp_id THEN 0
            ELSE (SUM(amount_paid) OVER(PARTITION BY emp_id)) END "Total amount"
FROM    Employee ) T
ORDER BY "Employee ID", "S/N"; -- Added this

Note that I have also changed the ORDER BY clause (which is moved to the outer query).

Cheers!!


问:
VueJS Send component props with space
I want to send component props from my view but there is a space and it make vue return me vendor.js:695 [Vue warn]: Error compiling template: - invalid expression: :user-name="Awesome Me"
- invalid expression: :user-name="Awesome Me"

my view:

```<code><ActionButton :id="1"
          :user-name="Awesome Me"
          :main="1" />
</code>```

my components:

```<code><script>
    export default{
        props: {
            id: {
                type: String
            },
            userName:{
                type: String
            },
            main: {
                type: Boolean
            }
        },
        methods: {
            setAsMain(id){
                // some stuff
            },

        },
        computed: {
            mainMessage(){
                return this.main == 1 ? 'Main character' : '';
            }
        }
    }
</script>
</code>```

How can I send the user-name value consist of space?

答:
I encontered the same issue and solved with:

<ActionButton :user-name="'Awesome Me'" />
```

<p>Notice that we must use another sigle quote,
I think vue would parse whatever in v-bind double quote as <strong>code</strong> rather that text.
For example, if I use:</p>

<pre class="lang-html prettyprint-override"><code><ActionButton :buttonText="()=>'Awesome Me'" />

</code>```

the text on button would be:

```<code>function() {return 'Awesome Me'}
</code>```

ContentLicense: CC BY-SA 3.0

Title: VueJS Send component props with space

Body:
I want to send component props from my view but there is a space and it make vue return me vendor.js:695 [Vue warn]: Error compiling template: - invalid expression: :user-name="Awesome Me"
- invalid expression: :user-name="Awesome Me"

my view:

<ActionButton :id="1"
          :user-name="Awesome Me"
          :main="1" />

my components:

How can I send the user-name value consist of space?

Body:
I encontered the same issue and solved with:

<ActionButton :user-name="'Awesome Me'" />

Notice that we must use another sigle quote,
I think vue would parse whatever in v-bind double quote as code rather that text.
For example, if I use:

<ActionButton :buttonText="()=>'Awesome Me'" />

the text on button would be:

function() {return 'Awesome Me'}


问:
Android - Fragments or custom views? Which should I be using?
I am trying to create a layout in an activity that will look different in landscape and portrait, however it will contain the same sections, just in different places on the screen.

Most examples I find on fragments is always the list and detail, which is not what I'm looking at.

In my example I have, amongst others,

a scrolling image section (carousel)

a page title with some brief details

a carousel of thumbnails

two buttons

full details of the page

Now in the landscape layout, the image section will always be on the left side with down the right side, the page title, carousel of thumbs, two buttons and full details.
In the Portrait the title will appear at top, with image carousel beneath, then thumbs, then buttons etc.

The way it works in my head, is that each section should be a fragment, and then depending on the layout file in the respective res/layout folder corresponding to land/port, the fragments are arranged accordingly. But I'm also thinking is each section a whole fragment? Or could it be a separate view that get's loaded in, but just in a different order depending on the screen orientation.

I hope that made sense?

Does anyone have any good tutorials that explain exactly when you should and shouldn't use fragments. All the usual suspects just list the list/detail example, which is not applicable in my case.

tl;dr Can I use fragments as modules/blocks in various layouts or should I just create other layouts and display them inside the main layouts.

答:
If you just want to change how the screen is laid out, the answer is neither. You can define orientation-specific resources (either a separate layout file for each orientation or different dimensions/constraints for each orientation) and the system will just provide you with the correct resource set for the current orientation.

That said, it sounds like you may be describing a modified version of master/detail flow. If this is the case, fragments are a good way to go since the landscape view is actually several separate screens in the portrait version of the app, so each section needs it's own state and lifecycle, which fragments provide.

Now, I know you said you wanted an example beyond a list and detail view, so here's some more details on when to use fragments:

Fragment, like activities, have state and lifecycle. Custom views do not have lifecycle and are completely dependent on the activity or fragment containing them.

You might use a custom view when you have a widget on screen that is used in multiple places and is just like any other view – bound to the activity when the layout is inflated and controlled from there. It's a way to either reduce duplicating combinations of views in your layout or to draw a custom view that doesn't exist yet.

Fragments are good when you need some state or lifecycle for a section of the app that might get used in multiple places or shouldn't be logically connected to the activity it is contained in. If you use the new Navigation Component, you actually just define one activity and then each screen in the navigation tree is a fragment that gets swapped out as the user navigates around the app. Here each child component on the screen (each "screen" that the user navigates to) has it's own lifecycle, business logic, etc, so mixing the code for all of that in the activity wouldn't make sense.

So the question comes down to what you are trying to build, and this may be a case where the best way to learn the difference is to try each option out as bit. The differences become more clear with practice using them. As a general rule of thumb, personally, I only really use custom views when I am trying to make a new view that doesn't exist elsewhere. If what I'm trying to do is simply a matter of laying out existing views in a new way, the answer is probably some trick in the layout file or layout code inside the activity. If I'm trying to make a stand-alone piece of the app that does stuff, especially if it also appears in multiple places in the app, I'll probably be building a fragment.


问:
Apache Maven Download using CURL is timed out
```<code>curl -O "https://www.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz"
</code>```

This is the command I am using from terminal to download maven but it's either timed out or curl: (7) Failed to connect to www.apache.org port 443: Operation timed out.

If I use browser to download, no issue.

My assumption is the ssl connection or certificate issue. Any idea how can I resolve the curl issue.

Please take note, I am using this in a Dockerfile to create docker image and here is that:

```<code>FROM ******/mule-42x:v2.2.1

ENV MAVEN_VERSION 3.6.3

RUN mkdir -p /opt/maven \
  && cd /opt/maven \
  && curl -O "https://www.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz" \
  && tar xzvf "apache-maven-$MAVEN_VERSION-bin.tar.gz" \
  && rm "apache-maven-$MAVEN_VERSION-bin.tar.gz"

ENV MAVEN_HOME "/opt/maven/apache-maven-$MAVEN_VERSION"

ENV PATH=$MAVEN_HOME/bin:$PATH
</code>```

答:
I've tried to run the command presented in the question and encountered the following errors:

```<code>curl -O "https://www.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz"
</code>```

curl tries to verify the SSL certificate but fails with the following message:

```<code>curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.
</code>```

So I've added -k flag as the message suggests.

Now this works, however the http call returns and HTML page with 302 (redirect) to https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz

So the command that has worked for me is:

```<code>curl -O -k https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz
</code>```

An Important side note:

I'm assuming that you've configured the network right and it has all the proper proxy definitions if you're running behind the proxy in your organization, otherwise you should define proxy first.

All in all I suggest you running this command 'manually' first (from the command line not as a part of the build I mean) outside the docker on the machine where you run the docker build and only when you make sure it works run it in a docker file.

Body:
curl -O "https://www.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz"

This is the command I am using from terminal to download maven but it's either timed out or curl: (7) Failed to connect to www.apache.org port 443: Operation timed out.

If I use browser to download, no issue.

My assumption is the ssl connection or certificate issue. Any idea how can I resolve the curl issue.

Please take note, I am using this in a Dockerfile to create docker image and here is that:

FROM ******/mule-42x:v2.2.1

ENV MAVEN_VERSION 3.6.3

RUN mkdir -p /opt/maven \
  && cd /opt/maven \
  && curl -O "https://www.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz" \
  && tar xzvf "apache-maven-$MAVEN_VERSION-bin.tar.gz" \
  && rm "apache-maven-$MAVEN_VERSION-bin.tar.gz"

ENV MAVEN_HOME "/opt/maven/apache-maven-$MAVEN_VERSION"

ENV PATH=$MAVEN_HOME/bin:$PATH

Body:
I've tried to run the command presented in the question and encountered the following errors:

curl -O "https://www.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz"

curl tries to verify the SSL certificate but fails with the following message:

curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

So I've added -k flag as the message suggests.

Now this works, however the http call returns and HTML page with 302 (redirect) to https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz

So the command that has worked for me is:

curl -O -k https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz

An Important side note:

I'm assuming that you've configured the network right and it has all the proper proxy definitions if you're running behind the proxy in your organization, otherwise you should define proxy first.

All in all I suggest you running this command 'manually' first (from the command line not as a part of the build I mean) outside the docker on the machine where you run the docker build and only when you make sure it works run it in a docker file.


问:
Cannot call stored procedure from code which works on direct call to database
I connected to the Informix server using RazorSQL, created a stored procedure and tested it, getting the expected answer, so the procedure exists in the database in some form.

I then run the following code:

```<code>If ConnectToInformix() Then
    Dim cmd As New IfxCommand("dc_routeHasOutstandingQuantity", conn)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.Add(New IfxParameter("WorksOrder", wo_num))
    cmd.Parameters.Add(New IfxParameter("CompNo", IBM.Data.Informix.IfxType.SmallInt)).Value = CType(compNo, Int16)
    rdr = cmd.ExecuteReader
</code>```

For completeness' sake, here is the ConnectToInformix function.

```<code>Private Function ConnectToInformix() As Boolean
    Try
        If conn Is Nothing Then
            conn = New IfxConnection
            conn.ConnectionString = ConnectionString
        End If
        If conn.State = System.Data.ConnectionState.Closed Then
            conn.Open()
        End If
        Return True
    Catch ex As System.Exception
        conn.Dispose()
        conn = Nothing
        Return False
    End Try
End Function
</code>```

The ConnectToInformix function works fine for every other Informix connection made by this program, but this is the first Informix stored procedure being used, so maybe there's some special magic I have to work on the connection...

Anyway, when I try to call the stored procedure on the rdr = cmd.ExecuteReader line I get the following error:

```<code>ERROR [HY000] [Informix .NET provider][Informix]Cannot read system catalog (sysprocedures).
</code>```

This error does not occur when calling the stored procedure from a live SQL connection.

What am I doing wrong?

答: First thing I'd check is you’re user has permissions to the database, and to that stored procedure.  </p>

Body:
I connected to the Informix server using RazorSQL, created a stored procedure and tested it, getting the expected answer, so the procedure exists in the database in some form.

I then run the following code:

If ConnectToInformix() Then
    Dim cmd As New IfxCommand("dc_routeHasOutstandingQuantity", conn)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.Add(New IfxParameter("WorksOrder", wo_num))
    cmd.Parameters.Add(New IfxParameter("CompNo", IBM.Data.Informix.IfxType.SmallInt)).Value = CType(compNo, Int16)
    rdr = cmd.ExecuteReader

For completeness' sake, here is the ConnectToInformix function.

Private Function ConnectToInformix() As Boolean
    Try
        If conn Is Nothing Then
            conn = New IfxConnection
            conn.ConnectionString = ConnectionString
        End If
        If conn.State = System.Data.ConnectionState.Closed Then
            conn.Open()
        End If
        Return True
    Catch ex As System.Exception
        conn.Dispose()
        conn = Nothing
        Return False
    End Try
End Function

The ConnectToInformix function works fine for every other Informix connection made by this program, but this is the first Informix stored procedure being used, so maybe there's some special magic I have to work on the connection...

Anyway, when I try to call the stored procedure on the rdr = cmd.ExecuteReader line I get the following error:

ERROR [HY000] [Informix .NET provider][Informix]Cannot read system catalog (sysprocedures).

This error does not occur when calling the stored procedure from a live SQL connection.

What am I doing wrong?


问:
Getting all my public posts using Facebook Graph API
How can i get all my facebook posts using python code and facebook graph api.
i have tried using this code:

```<code>import json
import facebook

def get_basic_info(token):

    graph = facebook.GraphAPI(token)

    profile = graph.get_object('me',fields='first_name,last_name,location,link,email')

    print(json.dumps(profile, indent=5))

def get_all_posts(token):
    graph = facebook.GraphAPI(token)
    events = graph.request('type=event&limit=10000')
    print(events)

def main():

    token = "my_token"
    #get_basic_info(token)
    get_all_posts(token)

if __name__ == '__main__':

    main()
</code>```

I am getting a error that says,
"GraphAPIError: (#33) This object does not exist or does not support this action".

Seems like all the other stackoverflow questions are very old and does not apply for the newest version of facebook graph API. I am not entirely sure whether u can do this using facebook graph api or not.
if this is not possible using this technique, is there any other way i can get my posts using python?
please note that function get_basic_info() is working perfectly.

答:
I have solved this problem with the help of the first answer by @luschn
I was making one more mistake, that is using events for getting all my posts.instead i should have used me/posts in my code.
Here is the function that works perfectly in version 6.

```<code>def get_all_posts(graph):

    posts = graph.request('/me/posts')
    count=1
    while "paging" in posts:
        print("length of the dictionary",len(posts))
        print("length of the data part",len(posts['data']))
        for post in posts["data"]:
            print(count,"\n")
            if "message" in post:   #because some posts may not have a caption
                print(post["message"])
            print("time :  ",post["created_time"])
            print("id   :",post["id"],"\n\n")
            count=count+1

        posts=requests.get(posts["paging"]["next"]).json()

    print("end of posts")
</code>```

Here, the post["data"] only gives first 25 posts, so I have used posts["paging"]["next"] link to get the next page as long as there is the next page.

Body:
How can i get all my facebook posts using python code and facebook graph api.
i have tried using this code:

import json
import facebook

def get_basic_info(token):

    graph = facebook.GraphAPI(token)

    profile = graph.get_object('me',fields='first_name,last_name,location,link,email')

    print(json.dumps(profile, indent=5))

def get_all_posts(token):
    graph = facebook.GraphAPI(token)
    events = graph.request('type=event&limit=10000')
    print(events)

def main():

    token = "my_token"
    #get_basic_info(token)
    get_all_posts(token)

if __name__ == '__main__':

    main()

I am getting a error that says,
"GraphAPIError: (#33) This object does not exist or does not support this action".

Seems like all the other stackoverflow questions are very old and does not apply for the newest version of facebook graph API. I am not entirely sure whether u can do this using facebook graph api or not.
if this is not possible using this technique, is there any other way i can get my posts using python?
please note that function get_basic_info() is working perfectly.

Body:
I have solved this problem with the help of the first answer by @luschn
I was making one more mistake, that is using events for getting all my posts.instead i should have used me/posts in my code.
Here is the function that works perfectly in version 6.

def get_all_posts(graph):

    posts = graph.request('/me/posts')
    count=1
    while "paging" in posts:
        print("length of the dictionary",len(posts))
        print("length of the data part",len(posts['data']))
        for post in posts["data"]:
            print(count,"\n")
            if "message" in post:   #because some posts may not have a caption
                print(post["message"])
            print("time :  ",post["created_time"])
            print("id   :",post["id"],"\n\n")
            count=count+1

        posts=requests.get(posts["paging"]["next"]).json()

    print("end of posts")

Here, the post["data"] only gives first 25 posts, so I have used posts["paging"]["next"] link to get the next page as long as there is the next page.


问:
How do I mock a REST template exchange?
I have a service in which I need to ask an outside server via rest for some information:

```<code>public class SomeService {

    public List<ObjectA> getListofObjectsA() {
        List<ObjectA> objectAList = new ArrayList<ObjectA>();
        ParameterizedTypeReference<List<ObjectA>> typeRef = new ParameterizedTypeReference<List<ObjectA>>() {};
        ResponseEntity<List<ObjectA>> responseEntity = restTemplate.exchange("/objects/get-objectA", HttpMethod.POST, new HttpEntity<>(ObjectAList), typeRef);
        return responseEntity.getBody();
    }
}
</code>```

How can I write a JUnit test for getListofObjectsA()?

I have tried with the below:

```<code>@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
    private MockRestServiceServer mockServer;

    @Mock
    private RestTemplate restTemplate;

    @Inject
   private SomeService underTest;

@Before
public void setup() {
    mockServer = MockRestServiceServer.createServer(restTemplate);
    underTest = new SomeService(restTemplate);
    mockServer.expect(requestTo("/objects/get-objectA")).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess("{json list response}", MediaType.APPLICATION_JSON));
}

    @Test
    public void testGetObjectAList() {
    List<ObjectA> res = underTest.getListofObjectsA();
    Assert.assertEquals(myobjectA, res.get(0));
}
</code>```

However the above code does not work, it shows that responseEntitty is null.  How can I correct my test to properly mock restTemplate.exchange?

答:
Let say you have an exchange call like below:

```<code>String url = "/zzz/{accountNumber}";

Optional<AccountResponse> accResponse = Optional.ofNullable(accountNumber)
        .map(account -> {

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "bearer 121212");

            HttpEntity<Object> entity = new HttpEntity<>(headers);
            ResponseEntity<AccountResponse> response = template.exchange(
                    url,
                    GET,
                    entity,
                    AccountResponse.class,
                    accountNumber
            );

            return response.getBody();
        });

</code>```

To mock this in your test case you can use mocitko as below:

```<code>when(restTemplate.exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class),
        ArgumentMatchers.any(),
        ArgumentMatchers.<Class<AccountResponse>>any(),
        ArgumentMatchers.<ParameterizedTypeReference<List<Object>>>any())
)

</code>```

Title: How do I mock a REST template exchange?

Body:
I have a service in which I need to ask an outside server via rest for some information:

public class SomeService {

    public List<ObjectA> getListofObjectsA() {
        List<ObjectA> objectAList = new ArrayList<ObjectA>();
        ParameterizedTypeReference<List<ObjectA>> typeRef = new ParameterizedTypeReference<List<ObjectA>>() {};
        ResponseEntity<List<ObjectA>> responseEntity = restTemplate.exchange("/objects/get-objectA", HttpMethod.POST, new HttpEntity<>(ObjectAList), typeRef);
        return responseEntity.getBody();
    }
}

How can I write a JUnit test for getListofObjectsA()?

I have tried with the below:

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
    private MockRestServiceServer mockServer;

    @Mock
    private RestTemplate restTemplate;

    @Inject
   private SomeService underTest;

@Before
public void setup() {
    mockServer = MockRestServiceServer.createServer(restTemplate);
    underTest = new SomeService(restTemplate);
    mockServer.expect(requestTo("/objects/get-objectA")).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess("{json list response}", MediaType.APPLICATION_JSON));
}

    @Test
    public void testGetObjectAList() {
    List<ObjectA> res = underTest.getListofObjectsA();
    Assert.assertEquals(myobjectA, res.get(0));
}

However the above code does not work, it shows that responseEntitty is null.  How can I correct my test to properly mock restTemplate.exchange?

Body:
Let say you have an exchange call like below:

String url = "/zzz/{accountNumber}";

Optional<AccountResponse> accResponse = Optional.ofNullable(accountNumber)
        .map(account -> {

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "bearer 121212");

            HttpEntity<Object> entity = new HttpEntity<>(headers);
            ResponseEntity<AccountResponse> response = template.exchange(
                    url,
                    GET,
                    entity,
                    AccountResponse.class,
                    accountNumber
            );

            return response.getBody();
        });

To mock this in your test case you can use mocitko as below:

when(restTemplate.exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class),
        ArgumentMatchers.any(),
        ArgumentMatchers.<Class<AccountResponse>>any(),
        ArgumentMatchers.<ParameterizedTypeReference<List<Object>>>any())
)


问:
How to perform Gaussian pooling on a 2d array using numpy
Given a 2D(M x N) matrix, and a 2D Gaussian Mask(K x K), how do i return a matrix that is the result of Gaussian pooling using the given kernel over the image?

I'd like to use numpy if possible(Not Using "for", only use numpy)
eg of 2x2 Gaussian pooling:(It could be wrong answer)

```<code>matrix:
array([[  20,  200,   -5,   23,  10, -50],
       [ -13,  134,  119,  100,  45, -79],
       [ 120,   32,   49,   25,  13,   0],
       [  40,   12,   59,   23,  32,  -1],
       [  75,  121,   69,   67,  64,  -7],
       [  39,   12,   79,   -8,  16,  -9]])
kernel:
array([[ 1/16, 1/8, 1/16],
       [  1/8, 1/4,  1/8],
       [ 1/16, 1/8, 1/16]])
soln:
array([[   87.25,   16.625],
       [ 64.8125,  29.8125]])
</code>```

答:
First transform you M x N matrix into a (M//K) x K x (N//K) x K array,
then pointwise multiply with the kernel at the second and fourth dimensions,
then sum at the second and fourth dimensions.

np.sum(
    matrix.reshape((
        matrix.shape[-2] // kernel.shape[-2], kernel.shape[-2],
        matrix.shape[-1] // kernel.shape[-1], kernel.shape[-1],
    ))
    * kernel[np.newaxis, :, np.newaxis, :],
    axis=(-3, -1),
)
```

<p>You can also replace the pointwise-multiply-then-sum by a <code>np.tensordot</code> call.</p>

<pre class="lang-py prettyprint-override"><code>np.tensordot(
    matrix.reshape((
        matrix.shape[-2] // kernel.shape[-2], kernel.shape[-2],
        matrix.shape[-1] // kernel.shape[-1], kernel.shape[-1],
    )),
    kernel,
    axes=(
        (-3, -1),
        (-2, -1),
    )
)
</code>```

Body:
Given a 2D(M x N) matrix, and a 2D Gaussian Mask(K x K), how do i return a matrix that is the result of Gaussian pooling using the given kernel over the image?

I'd like to use numpy if possible(Not Using "for", only use numpy)
eg of 2x2 Gaussian pooling:(It could be wrong answer)

matrix:
array([[  20,  200,   -5,   23,  10, -50],
       [ -13,  134,  119,  100,  45, -79],
       [ 120,   32,   49,   25,  13,   0],
       [  40,   12,   59,   23,  32,  -1],
       [  75,  121,   69,   67,  64,  -7],
       [  39,   12,   79,   -8,  16,  -9]])
kernel:
array([[ 1/16, 1/8, 1/16],
       [  1/8, 1/4,  1/8],
       [ 1/16, 1/8, 1/16]])
soln:
array([[   87.25,   16.625],
       [ 64.8125,  29.8125]])

Body:
First transform you M x N matrix into a (M//K) x K x (N//K) x K array,
then pointwise multiply with the kernel at the second and fourth dimensions,
then sum at the second and fourth dimensions.

np.sum(
    matrix.reshape((
        matrix.shape[-2] // kernel.shape[-2], kernel.shape[-2],
        matrix.shape[-1] // kernel.shape[-1], kernel.shape[-1],
    ))
    * kernel[np.newaxis, :, np.newaxis, :],
    axis=(-3, -1),
)

You can also replace the pointwise-multiply-then-sum by a np.tensordot call.

np.tensordot(
    matrix.reshape((
        matrix.shape[-2] // kernel.shape[-2], kernel.shape[-2],
        matrix.shape[-1] // kernel.shape[-1], kernel.shape[-1],
    )),
    kernel,
    axes=(
        (-3, -1),
        (-2, -1),
    )
)


问:
jQuery bind event listener before another
Using the prettyPhoto plugin to open modal-style content containers, and trying to integrate with Google Analytics' Event Tracking to track when videos get opened.

Trouble is, when I

```<code>$('a.videoClickListener').click(function(event){
    console.log('here');
    _gaq.push(['_trackEvent', 'Product Page', 'Video Open', '<?php echo $product->getNameWithManufacturer(); ?>']);
});
</code>```

the event is never fired, as prettyPhoto stops the event from continuing (quite rightly, as otherwise the page would change if a hyperlink was clicked).

prettyPhoto does not seem to provide an 'open' callback function, but if it did I couldn't use it anyway, as the prettyPhoto listeners are set up somewhere in the layout (we use rel="prettyPhoto" every time we want to use prettyPhoto, and pass params through the URL, which is the prettyPhoto-recommended way of doing things).  I would also like to pass the product details to Analytics, ruling out a global video-opening listener across all prettyPhoto opening events.

How can I bind my listener before the prettyPhoto listener?  If it turns out I have to use .unbind(), then bind my listener, and then rebind prettyPhoto, how can I unbind a handler specified in a plugin?

答: if you use unbind() then even the bindings made by plugins will be unbinded.</p>

Body:
Using the prettyPhoto plugin to open modal-style content containers, and trying to integrate with Google Analytics' Event Tracking to track when videos get opened.

Trouble is, when I

$('a.videoClickListener').click(function(event){
    console.log('here');
    _gaq.push(['_trackEvent', 'Product Page', 'Video Open', '<?php echo $product->getNameWithManufacturer(); ?>']);
});

the event is never fired, as prettyPhoto stops the event from continuing (quite rightly, as otherwise the page would change if a hyperlink was clicked).

prettyPhoto does not seem to provide an 'open' callback function, but if it did I couldn't use it anyway, as the prettyPhoto listeners are set up somewhere in the layout (we use rel="prettyPhoto" every time we want to use prettyPhoto, and pass params through the URL, which is the prettyPhoto-recommended way of doing things).  I would also like to pass the product details to Analytics, ruling out a global video-opening listener across all prettyPhoto opening events.

How can I bind my listener before the prettyPhoto listener?  If it turns out I have to use .unbind(), then bind my listener, and then rebind prettyPhoto, how can I unbind a handler specified in a plugin?


问:
Python Shell Scripting. Chain Unix OpenSSL Commands
I am trying to write a simple Python shell script that will take user input of server name and port number and route it into an OpenSSL command that shows SSL certificate expiration info.

I am using the subprocess module, however I am unclear of the proper method of chaining the command with user entered information.

The full command is:

```<code>echo | openssl s_client -servername www.google.com -connect www.google.com:443 2>/dev/null | openssl x509 -noout -dates
</code>```

Output of command (which is what I want the script to output):

```<code>notBefore=May 31 16:57:23 2017 GMT
notAfter=Aug 23 16:32:00 2017 GMT
</code>```

My code:

```<code>#!/usr/bin/env python
import subprocess

server_name = raw_input("Enter server name: ")
port_number = raw_input("Enter port number: ")

def display_cert_info(servername, portnum):
    pn = str(server_name + ":" + port_number)
    cmd = ["echo", "|", "openssl", "s_client", "-servername", str(servername), "-connect", pn, "2>/dev/null", "|", "openssl", "x509", "-noout", "-dates"]

    info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = info.communicate()[0]
    print(output)

display_cert_info(server_name, port_number)
</code>```

Any help is appreciated!

答:
@Han I realize I might be a little too late to the party to help you, so sorry for that, but this is for the other folks looking for this solution. I had to string together Popen() and check_output() functions, like so:

```<code>#!/usr/bin/python3
from subprocess import Popen, PIPE, check_output
from os import open, O_WRONLY

servers = [
    "server1.domain.com",
    "server2.domain.com",
    "server3.domain.com"
    ]

for s in servers:
    print("querying {}".format(s))
    dn = open("/dev/null", O_WRONLY)
    q = Popen(["/usr/bin/openssl", "s_client", "-servername", s, "-connect","{}:443".format(s)], stdout=PIPE, stdin=PIPE, stderr=dn, shell=False)
    y = check_output(["/usr/bin/openssl", "x509", "-noout", "-dates"], stdin=q.stdout)
    print(y.decode("utf-8"))
</code>```

This allowed me a quick and dirty audit of all of the servers I added to the list. My next iteration was to add monitoring/alerting to the output and never be surprised by an expired cert again.

Body:
I am trying to write a simple Python shell script that will take user input of server name and port number and route it into an OpenSSL command that shows SSL certificate expiration info.

I am using the subprocess module, however I am unclear of the proper method of chaining the command with user entered information.

The full command is:

echo | openssl s_client -servername www.google.com -connect www.google.com:443 2>/dev/null | openssl x509 -noout -dates

Output of command (which is what I want the script to output):

notBefore=May 31 16:57:23 2017 GMT
notAfter=Aug 23 16:32:00 2017 GMT

My code:

#!/usr/bin/env python
import subprocess

server_name = raw_input("Enter server name: ")
port_number = raw_input("Enter port number: ")

def display_cert_info(servername, portnum):
    pn = str(server_name + ":" + port_number)
    cmd = ["echo", "|", "openssl", "s_client", "-servername", str(servername), "-connect", pn, "2>/dev/null", "|", "openssl", "x509", "-noout", "-dates"]

    info = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = info.communicate()[0]
    print(output)

display_cert_info(server_name, port_number)

Any help is appreciated!

Body:
@Han I realize I might be a little too late to the party to help you, so sorry for that, but this is for the other folks looking for this solution. I had to string together Popen() and check_output() functions, like so:

#!/usr/bin/python3
from subprocess import Popen, PIPE, check_output
from os import open, O_WRONLY

servers = [
    "server1.domain.com",
    "server2.domain.com",
    "server3.domain.com"
    ]

for s in servers:
    print("querying {}".format(s))
    dn = open("/dev/null", O_WRONLY)
    q = Popen(["/usr/bin/openssl", "s_client", "-servername", s, "-connect","{}:443".format(s)], stdout=PIPE, stdin=PIPE, stderr=dn, shell=False)
    y = check_output(["/usr/bin/openssl", "x509", "-noout", "-dates"], stdin=q.stdout)
    print(y.decode("utf-8"))

This allowed me a quick and dirty audit of all of the servers I added to the list. My next iteration was to add monitoring/alerting to the output and never be surprised by an expired cert again.


问:
sticky session with apache web server and tomcat servers
I am using apache web server as a  load balancer for two tomcat instances behind apache. When the first request goes to node A and second request from the same client goes to node B, i cant access session variables within node A. It's obvious. I surfed in the internet and found that enabling sticky sessions would help. But all the tutorials for enabling the sticky sessions in apache look confusing. Is there any simple step-by-step tutorial for this? Please help.

Code fragment from comment:

```<code>ProxyPass /balancer-manager !
ProxyPass /balancer://mycluster/ stickysession=JSESSIONID
ProxyPassReverse /balancer://mycluster/
<Proxy balancer://mycluster>;
  BalancerMember ajp://localhost:9001/ route=NodeA1000 retry=10
  BalancerMember ajp://localhost:9002/ route=NodeB1000 retry=10
</Proxy>
</code>```

答:
None of the above solutions worked for me, but I found it in MOTECH project documentation here: http://docs.motechproject.org/en/latest/deployment/sticky_session_apache.html

This config works for me (on Apache 2.4.41):

```<code><VirtualHost *:80>
    (...)
    Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
    (...)
    <Proxy balancer://mycluster>
        (...)
        BalancerMember http://10.20.30.40:8080 route=backend-1 enablereuse=On
        BalancerMember http://10.20.30.41:8080 route=backend-2 enablereuse=On

        ProxySet lbmethod=bytraffic
        ProxySet stickysession=ROUTEID
        (...)
    </Proxy>

    ProxyPass / balancer://mycluster/
    ProxyPassReverse / balancer://mycluster/
    (...)
</VirtualHost>
</code>```

Body:
I am using apache web server as a  load balancer for two tomcat instances behind apache. When the first request goes to node A and second request from the same client goes to node B, i cant access session variables within node A. It's obvious. I surfed in the internet and found that enabling sticky sessions would help. But all the tutorials for enabling the sticky sessions in apache look confusing. Is there any simple step-by-step tutorial for this? Please help.

Code fragment from comment:

ProxyPass /balancer-manager !
ProxyPass /balancer://mycluster/ stickysession=JSESSIONID
ProxyPassReverse /balancer://mycluster/
<Proxy balancer://mycluster>;
  BalancerMember ajp://localhost:9001/ route=NodeA1000 retry=10
  BalancerMember ajp://localhost:9002/ route=NodeB1000 retry=10
</Proxy>

Body:
None of the above solutions worked for me, but I found it in MOTECH project documentation here: http://docs.motechproject.org/en/latest/deployment/sticky_session_apache.html

This config works for me (on Apache 2.4.41):

<VirtualHost *:80>
    (...)
    Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
    (...)
    <Proxy balancer://mycluster>
        (...)
        BalancerMember http://10.20.30.40:8080 route=backend-1 enablereuse=On
        BalancerMember http://10.20.30.41:8080 route=backend-2 enablereuse=On

        ProxySet lbmethod=bytraffic
        ProxySet stickysession=ROUTEID
        (...)
    </Proxy>

    ProxyPass / balancer://mycluster/
    ProxyPassReverse / balancer://mycluster/
    (...)
</VirtualHost>


问:
MongoDB scripting
Essentially, I am trying to create a large number of users to test my app with.

I have tried a variety of different versions of this script but none are working.

Adding one user works as expected:
  db.users.insertOne({<test-user-json>})

BUT

when I try adding bulk users like this, it doesn't work:

```<code>db = connect('localhost:27017/_testDB');

const numArr = new Array(100);

const usersToAdd = numArr.map((e, i) => ({
    name: 'foo bar',
    email: `foo${i}@bar.com`,
    avatar: 'https://picsum.photos/seed/849/200?blur=3',
    password: 'asdfasdf',
    date: Date.now(),
  }))

db.users.insertMany(usersToAdd);
</code>```

I've also tried looping through a forEach and using insertOne to individually add them, since it does work on it's own, but this doesn't work either.

Is there a reason? What is the difference between MongoDB JavaScript and regular JavaScript? e.i. console.log is printjson() What else is different? Should I be using the mongDB NodeJs driver? The mongoDB documentation page on scripting seems pretty sparse..

And or, what is the best way to create a large number of arbitrary users and other administrative tasks?

I was about to write a bash script to get this working, but I figured I'd ask here first.

答:
Got it!

```<code>var bulk = db.users.initializeUnorderedBulkOp();

for (let i = 0; i < 100; i++) {
  bulk.insert({
    name: 'foo bar',
    email: `foo${i}@bar.com`,
    avatar: 'https://picsum.photos/seed/849/200?blur=3',
    password: 'asdfasdf',
    date: Date.now(),
  });
}
bulk.execute();
</code>```

Title: MongoDB scripting

Body:
Essentially, I am trying to create a large number of users to test my app with.

I have tried a variety of different versions of this script but none are working.

Adding one user works as expected:
  db.users.insertOne({<test-user-json>})

BUT

when I try adding bulk users like this, it doesn't work:

db = connect('localhost:27017/_testDB');

const numArr = new Array(100);

const usersToAdd = numArr.map((e, i) => ({
    name: 'foo bar',
    email: `foo${i}@bar.com`,
    avatar: 'https://picsum.photos/seed/849/200?blur=3',
    password: 'asdfasdf',
    date: Date.now(),
  }))

db.users.insertMany(usersToAdd);

I've also tried looping through a forEach and using insertOne to individually add them, since it does work on it's own, but this doesn't work either.

Is there a reason? What is the difference between MongoDB JavaScript and regular JavaScript? e.i. console.log is printjson() What else is different? Should I be using the mongDB NodeJs driver? The mongoDB documentation page on scripting seems pretty sparse..

And or, what is the best way to create a large number of arbitrary users and other administrative tasks?

I was about to write a bash script to get this working, but I figured I'd ask here first.

Body:
Got it!

var bulk = db.users.initializeUnorderedBulkOp();

for (let i = 0; i < 100; i++) {
  bulk.insert({
    name: 'foo bar',
    email: `foo${i}@bar.com`,
    avatar: 'https://picsum.photos/seed/849/200?blur=3',
    password: 'asdfasdf',
    date: Date.now(),
  });
}
bulk.execute();


问:
Making an outbound connection
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)

```<code>import socket

#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
    clientsocket, address = s.accept()
    print(f"connection from client has been established")
    clientsocket.send(bytes("welcome to the server!", "utf-8"))

</code>```

My server side script runs fine, however when i run the client script

```<code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))
</code>```

i get the following:

```<code>File "client.py", line 3
    s.connect((socket.gethostname(127.0.0.1), 0))
                                       ^
SyntaxError: invalid syntax
</code>```

I've tried changing the IP to my computer host name  and gives the following:

```<code>raceback (most recent call last):
  File "client.py", line 3, in <module>
    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined
</code>```

答: Put the 127.0.0.1 as string in gethostname</p>

Title: Making an outbound connection

Body:
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)

import socket

#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
    clientsocket, address = s.accept()
    print(f"connection from client has been established")
    clientsocket.send(bytes("welcome to the server!", "utf-8"))

My server side script runs fine, however when i run the client script

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))

i get the following:

File "client.py", line 3
    s.connect((socket.gethostname(127.0.0.1), 0))
                                       ^
SyntaxError: invalid syntax

I've tried changing the IP to my computer host name  and gives the following:

raceback (most recent call last):
  File "client.py", line 3, in <module>
    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined


问:
Determining size of a control before rendering process
I've got a composite control consisting of a rectangle and a few dynamically created labels (dynamically, because during design time I don't know how many labels shall be displayed). The labels' positions (margins) are evaluated during run time by combining whole control size, additional collection passed through dependency property and by heights of labels themselves.

Unfortunately, I didn't came into deterministic way of determining label height before one was rendered. ActualWidth and ActualHeight are 0 before the labels are displayed, Width/Height is not set, because I wish the labels to size themselves basing on their contents, DesiredSize returns either 0, correct size or size exceeding the real label size (like 2 or 3 times), RenderSize returns either valid size or 0 and it is like first label returns valid size and second one - 0.0, without any noticeable reason.

I've tried calling Measure() on the labels with double.PositiveInfinity passed by only to reach situation, when DesiredSize was way bigger than expected (all labels have the same font and consist only of numbers, so they all shall have more less similar size, but first had ~16 pixels, second - ~36, though after the rendering, RenderSize was valid for both of them).

Is there a deterministic way to check desired control size, based only on its contents (not on alignment/margins) before it is rendered on screen?

答: You can use UpdateLayout to force a measure / layout pass. After invoking this method ActualWidth and ActualHeight will have the correct values.


问:
Convert argb to string
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

```<code>$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8
</code>```

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

```<code> ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200
</code>```

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

答:
There are some nice and initiative answers for this question, but it looks like all have overlooked the correct way, using type converters. There is a ColorConverter responsible for ConvertTo and ConvertFrom String/Color:

```<code>$Color = [System.Drawing.Color]'0, 100, 200'
[System.Drawing.ColorConverter]::new().ConvertToString($Color)
# Result: 0, 100, 200
</code>```

This is the same class which is used by PropertyGrid to convert the string to Color or Color and vice versa.

It will take care of A element of the color as well, for example if you create the color like 100, 0, 100, 200. This solution automatically include or ignore  A portion whenever is required:

```<code>$Color = [System.Drawing.Color]'100, 0, 100, 200'
[System.Drawing.ColorConverter]::new().ConvertToString($Color)
# Result: 100, 0, 100, 200
</code>```

Title: Convert argb to string

Body:
Which method allows convert ARGB to string as 'int, int, int'? Example. The $Main background color is set as a string '0, 100, 200'. Return $Main.BackColor gives ARGB but not string '0, 100, 200':

$Main  = [System.Windows.Forms.Form] @{
    BackColor = '0, 100, 200'
}

$Main.BackColor
--------------
R             : 0
G             : 100
B             : 200
A             : 255
IsKnownColor  : False
IsEmpty       : False
IsNamedColor  : False
IsSystemColor : False
Name          : ff0064c8

The To.String() method returns the result Color [A=255, R=0, G=100, B=200]
. This is not what is expected.

At the moment I am doing this:

 ('R', 'G', 'B').ForEach({ $Main.BackColor.$_ }) -join ', '

--------------
0, 100, 200

However, I hope that there are special methods for converting as ARGB to string, as string to ARGB. What are these methods? Thanks

Body:
There are some nice and initiative answers for this question, but it looks like all have overlooked the correct way, using type converters. There is a ColorConverter responsible for ConvertTo and ConvertFrom String/Color:

$Color = [System.Drawing.Color]'0, 100, 200'
[System.Drawing.ColorConverter]::new().ConvertToString($Color)
# Result: 0, 100, 200

This is the same class which is used by PropertyGrid to convert the string to Color or Color and vice versa.

It will take care of A element of the color as well, for example if you create the color like 100, 0, 100, 200. This solution automatically include or ignore  A portion whenever is required:

$Color = [System.Drawing.Color]'100, 0, 100, 200'
[System.Drawing.ColorConverter]::new().ConvertToString($Color)
# Result: 100, 0, 100, 200


问:
Replace strings in LaTeX
I want LaTeX to automatically replace strings like " a ", " s ", " z " with " a~", " s~", " z~", because they can't be at line end. Any suggestions?</p>

答:
You can use \StrSubstitute from xstring package.

e.g.

```<code>\StrSubstitute{change ME}{ ME}{d}
</code>```

will convert change ME into changed.
Although, nesting is not possible, so to make another substitution you must use an intermediate variable in this way

```<code>\StrSubstitute{change ME}{ ME}{d}[\mystring]
\StrSubstitute{\mystring}{ed}{ing}
</code>```

Finally, your solution would be

```<code>\usepackage{xstring}
\def\mystring{...source string here...}
\begin{document}
\StrSubstitute{\mystring}{ a }{a~{}}[\mystring]
\StrSubstitute{\mystring}{ s }{s~{}}[\mystring]
\StrSubstitute{\mystring}{ z }{z~{}}[\mystring]
\mystring
\end{document}
</code>```

Note the use of the empty string {} to avoid the sequence ~}.

ContentLicense: CC BY-SA 2.5

Title: Replace strings in LaTeX

Body:
You can use \StrSubstitute from xstring package.

e.g.

\StrSubstitute{change ME}{ ME}{d}

will convert change ME into changed.
Although, nesting is not possible, so to make another substitution you must use an intermediate variable in this way

\StrSubstitute{change ME}{ ME}{d}[\mystring]
\StrSubstitute{\mystring}{ed}{ing}

Finally, your solution would be

\usepackage{xstring}
\def\mystring{...source string here...}
\begin{document}
\StrSubstitute{\mystring}{ a }{a~{}}[\mystring]
\StrSubstitute{\mystring}{ s }{s~{}}[\mystring]
\StrSubstitute{\mystring}{ z }{z~{}}[\mystring]
\mystring
\end{document}

Note the use of the empty string {} to avoid the sequence ~}.


问:
Why is `close` and `open` not matching the price on chart?
FOREX, 1H Chart, //version=3 pinescript

I'm still new to Pinescript but I noticed that using close or open returns data that is not the current close or open price. Even using close[1] returns an amount completely different than the closing of that previous candle.

Why is this? Am I interpreting this data incorrectly?

In the research I've done, I came across this article: https://www.tradingcode.net/tradingview/operators/history-referencing-operator/:

Technically, the history referencing operator doesn’t return a single
  value but returns a series of values with a certain offset, even
  though we generally think that the history referencing operator
  accesses the nth element.

This means that, for example, close[5] doesn’t return a single
  closing price but a series of closing prices that are equal to the
  closing price of 5 bars ago.

That bold statement above - "A series of closing prices"; does this mean that close[5] itself is not the 5th candle's closing price?

If that's the case, then how would I go about displaying the current close price for that candle with something like:

strategy.entry("SHORT", strategy.short, comment=tostring(close[1]) )

答: This issue has been fixed in both Pine v3 and v4. The posted code now shows this on the chart. The date is that of the bar preceding the order's execution, which corresponds to when the order was issued:


问:
MySQL; the function value doesn't appear in resulted table
I created a table with three fields and applied a created function to automatic concat two fields of the same record and the result appears in the third field of the table at the same record.
While the problem is whenever I do insert statement the result of the function appears as error but not on the table!!! the following is the code:

```<code>create table Tab (
  stuId varchar (1),
  stuName varchar (10)
  recordCon varchar (20),
  primary key (stuId));
</code>```

Auto concat function for one record by input id:

```<code>DELIMITER //
CREATE FUNCTION AutoCon (id varchar (1)) RETURNS int DETERMINISTIC
BEGIN
 DECLARE name varchar(10);
 DECLARE Con varchar(20);

 select stuName from Tab where stuId = id into name;
 Select concat(id, name) into con;
 RETURN con;
END
//
DELIMITER ;
</code>```

```<code>insert into Tab values ('1a', 'Rami', AutoCon('1a'))
</code>```

the result

```<code>a1  Rami    null
</code>```

答:
FUNCTION AutoCon (id varchar (1)), but you pass 2 chars as the parameter - AutoCon('1a')

Something wrong there ...

Body:
I created a table with three fields and applied a created function to automatic concat two fields of the same record and the result appears in the third field of the table at the same record.
While the problem is whenever I do insert statement the result of the function appears as error but not on the table!!! the following is the code:

create table Tab (
  stuId varchar (1),
  stuName varchar (10)
  recordCon varchar (20),
  primary key (stuId));

Auto concat function for one record by input id:

DELIMITER //
CREATE FUNCTION AutoCon (id varchar (1)) RETURNS int DETERMINISTIC
BEGIN
 DECLARE name varchar(10);
 DECLARE Con varchar(20);

 select stuName from Tab where stuId = id into name;
 Select concat(id, name) into con;
 RETURN con;
END
//
DELIMITER ;

insert into Tab values ('1a', 'Rami', AutoCon('1a'))

the result

a1  Rami    null


问:
could someone explain that C++ code for me?
In the following code what is the meaning of colon? and where callback function came from?

using void_callback_f = void (*)();
std::vector<void_callback_f> _reload_callbacks;

void Reload() {
    for (const auto& callback : _reload_callbacks) {
        callback();
    }
}
```

答:
The colon in the for loop is an example of Range-based for loop

range_expression is evaluated to determine the sequence or range to
  iterate. Each element of the sequence, in turn, is dereferenced and
  assigned to the variable with the type and name given in
  range_declaration.

Please check here for more information


问:
Putting Custom CSS into Laravel 6
I put my css in the public folder and linked to it in my template, but the css won't work. When I run the file out of Laravel using HTML index, it works fine. But, when I put it in Laravel it won't see the css.

This is my code in the template:

```<code><link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/media.css">
</code>```

Do I need to add anything to make it blade/laravel specific?

答: Turns out, it was a browser issue. All of my css and links were correct and the files were in the correct location. It worked in Safari, but not in Firefox. I had to correct a few things on my preferences in Firefox.</p>

Title: Putting Custom CSS into Laravel 6

Body:
I put my css in the public folder and linked to it in my template, but the css won't work. When I run the file out of Laravel using HTML index, it works fine. But, when I put it in Laravel it won't see the css.

This is my code in the template:

<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/media.css">

Do I need to add anything to make it blade/laravel specific?


问:
How to access last element in a web page when everything has the same class?
I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

```<code>message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")
</code>```

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

答:
You can use find_elements_by_xpath to get a list of all the elements matching the locator and take the last item on that list

```<code>all_messages = self.driver.find_elements_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")
message = all_messages[-1]
</code>```

By the way you can simplify the xpath to

```<code>find_elements_by_xpath("//div[@class='markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN']")
</code>```

Or use css_selector instead

```<code>find_elements_by_css_selector('.markup-2BOw-j.containerCozy-336-Cz.markupRtl-3M0hmN')
</code>```

Body:
I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

Body:
You can use find_elements_by_xpath to get a list of all the elements matching the locator and take the last item on that list

all_messages = self.driver.find_elements_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")
message = all_messages[-1]

By the way you can simplify the xpath to

find_elements_by_xpath("//div[@class='markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN']")

Or use css_selector instead

find_elements_by_css_selector('.markup-2BOw-j.containerCozy-336-Cz.markupRtl-3M0hmN')


问:
Why the loop becomes infinite?
How to get out of an infinite loop?

```<code>unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}
</code>```

Help, please.

Thank you!

答:
How to get out of an infinite loop?

Paradoxically, you cannot. Because if you get out of a loop, then the loop was finite.

Title: Why the loop becomes infinite?

Body:
How to get out of an infinite loop?

unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}

Help, please.

Thank you!


问:
Replacing values with dictionary key in python
So I created a dictionary with every state abbreviation and the keys are "East", "Central", and "West"

```<code>states_dict = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}
</code>```

I'm trying to figure out a way to apply this to a column of code and return the dictionary keys instead in the column. For example if it is ["CA", "FL"] I want the column to be ["West","East]. I created a for loop where i appended the keys into a new list and it wasnt the correct length so I started using .replace and that is just continually running. Here is my code.

```<code>for x in df['X20']:
    for i,j in states_dict.items():
        for v in j:
            if x==v:
                x20=df['X20'].replace(x,i)

            else:
                pass
x20
</code>```

答:
Not sure if you need columns, but it's easy enough to inverse your keys/values to easily extract the data you're looking for:

keyed_by_region = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}

keyed_by_states = {}
for region, states in keyed_by_region.items():
    for state in states:
        keyed_by_states[state] = region

print('FL', keyed_by_states['FL'])
print('CA', keyed_by_states['CA'])
```

FL East

CA West

Body:
So I created a dictionary with every state abbreviation and the keys are "East", "Central", and "West"

states_dict = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}

I'm trying to figure out a way to apply this to a column of code and return the dictionary keys instead in the column. For example if it is ["CA", "FL"] I want the column to be ["West","East]. I created a for loop where i appended the keys into a new list and it wasnt the correct length so I started using .replace and that is just continually running. Here is my code.

for x in df['X20']:
    for i,j in states_dict.items():
        for v in j:
            if x==v:
                x20=df['X20'].replace(x,i)

            else:
                pass
x20

Body:
Not sure if you need columns, but it's easy enough to inverse your keys/values to easily extract the data you're looking for:

keyed_by_region = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}

keyed_by_states = {}
for region, states in keyed_by_region.items():
    for state in states:
        keyed_by_states[state] = region

print('FL', keyed_by_states['FL'])
print('CA', keyed_by_states['CA'])

FL East

CA West


问:
Rails doesn't allow to create new enum - instance method already defined by another enum
Trying to add enum to User class:

```<code>enum vehicle: { car: 1, bus: 2, other: 3 }, _prefix: true
</code>```

and rails throws an error

You tried to define an enum named "vehicle" on the model "Spree::User", but this will generate an instance method "vehicle_car?", which is already defined by another enum.

I had tried with another name, suffix and prefix options, and made ack in gems folder. I suppose that can be Zeitwerk problem but I don't have idea how to fix that.

Working on Rails version: 6

答:
You could give a custom prefix/suffix to make it differ from vehicle_car?

```<code>enum vehicle: { car: 1, bus: 2, other: 3 }, _prefix: :vehicle_type

model_instance.vehicle_type_car!
model_instance.vehicle_type_car? # => false
</code>```

For reference

https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html

Body:
Trying to add enum to User class:

enum vehicle: { car: 1, bus: 2, other: 3 }, _prefix: true

and rails throws an error

You tried to define an enum named "vehicle" on the model "Spree::User", but this will generate an instance method "vehicle_car?", which is already defined by another enum.

I had tried with another name, suffix and prefix options, and made ack in gems folder. I suppose that can be Zeitwerk problem but I don't have idea how to fix that.

Working on Rails version: 6

Body:
You could give a custom prefix/suffix to make it differ from vehicle_car?

enum vehicle: { car: 1, bus: 2, other: 3 }, _prefix: :vehicle_type

model_instance.vehicle_type_car!
model_instance.vehicle_type_car? # => false

For reference

https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html


问:
Python - loop through same query with different variables, merge data frames
I have a query in SAS where I use a Macro variable to repeat a query to Teradata with a different variable. We have 5 databases, one for each state, where I run the same query, but use the variable to update the state, then mend all data sets. I'm looking for help in how I can do this in python.

loop through {state1, state2, state3, state4, state5} and save each query as {stateX}_df then merge all

```<code>import teradata as td
import pandas as pd
from teradata import tdodbc

udaExec = td.UdaExec(appConfigFile="udaexec.ini")

with udaExec.connect("${dataSourceName}", LoginTimeout=120) as session:

query1 = """database my_db_{state1};"""

     query2 = """
                select  distinct
                {state1}, item_a, item_b
                from table

              """
    session.execute(query1)
    session.execute(query2)

    {stateX}_df = pd.read_sql(query2), session)
</code>```

答:
Not sure if you are using python 2 or python 3. If you can use python 3.6 or later, maybe something like the following could work?

```<code>import teradata as td
import pandas as pd

udaExec = td.UdaExec(appName="test", version="1.0", logConsole=False)
with udaExec.connect(
    method="odbc",
    system="host",
    username="username",
    password="password",
    driver="drivername"
    ) as conn:

state_dataframes = []
STATES = ["state1", "state2", "state3", "state4", "state5"]

for state in STATES:
    sql = f"select distinct {state}, item_a, item_b from my_db_{state}.table;"
    state_dataframes.append(pd.read_sql(sql, conn))

combined_data = pd.concat(state_dataframes)
</code>```

This isn't tested, but hopefully it gets you going in the right direction.

Body:
I have a query in SAS where I use a Macro variable to repeat a query to Teradata with a different variable. We have 5 databases, one for each state, where I run the same query, but use the variable to update the state, then mend all data sets. I'm looking for help in how I can do this in python.

loop through {state1, state2, state3, state4, state5} and save each query as {stateX}_df then merge all

import teradata as td
import pandas as pd
from teradata import tdodbc

udaExec = td.UdaExec(appConfigFile="udaexec.ini")

with udaExec.connect("${dataSourceName}", LoginTimeout=120) as session:

query1 = """database my_db_{state1};"""

     query2 = """
                select  distinct
                {state1}, item_a, item_b
                from table

              """
    session.execute(query1)
    session.execute(query2)

    {stateX}_df = pd.read_sql(query2), session)

Body:
Not sure if you are using python 2 or python 3. If you can use python 3.6 or later, maybe something like the following could work?

import teradata as td
import pandas as pd

udaExec = td.UdaExec(appName="test", version="1.0", logConsole=False)
with udaExec.connect(
    method="odbc",
    system="host",
    username="username",
    password="password",
    driver="drivername"
    ) as conn:

state_dataframes = []
STATES = ["state1", "state2", "state3", "state4", "state5"]

for state in STATES:
    sql = f"select distinct {state}, item_a, item_b from my_db_{state}.table;"
    state_dataframes.append(pd.read_sql(sql, conn))

combined_data = pd.concat(state_dataframes)

This isn't tested, but hopefully it gets you going in the right direction.


问:
How can I separate the horizontal rule from the table. They are mixed together. I want the horizontal rule below my table
My horizontal rule is mixed up with part of the information on a table

So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

```

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.

Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

答:
Just an educated guess at this stage you have two

 have you tried

 for your second table? instead of left? Hope this helps!!

Body:
My horizontal rule is mixed up with part of the information on a table

So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.

Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

Body:
Just an educated guess at this stage you have two
 <table style="float: left"> have you tried
 <table style="float: right"> for your second table? instead of left? Hope this helps!!


问:
Find and replace a sublist in Python
I'm fairly new to Python and programming in general and have run into a situation that I can't figure out.

I'm building an Employee Management System in which a user can add a new employee, view all employees, search for an employee by SSN and replace an employee's previous info by searching for the SSN and re-entering the required input.  The last part is where I am failing.  I believe that I am able to search appropriately by SSN but I can't figure out how to get the user to replace the previous info from that sublist.  Can anyone help me figure this out? I also included the error message that I receive below the script.

```<code>employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL EMPLOYEES." To find an employee, type: "SEARCH EMPLOYEE BY SSN." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "SEARCH":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        found = False
        for employee in employee_info:
            if employee[1] == find_emp:
                print('            -----------------', employee[0], '-----------------\n')
                print('SSN:', employee[1], '\n')
                print('Phone:', '(' + employee[2][0] + employee[2][1] + employee[2][2] + ')' + employee[2][3] + employee[2][4] + employee[2][
                5] + '-' + employee[2][6] + employee[2][7] + employee[2][8] + employee[2][9], '\n')
                print('Email:', employee[3], '\n')
                print('Salary:', '$' + str(employee[4]), '\n')
                print('            ----------------------------------------------------')
                found = True

        if found == False:
            print("Employee not found!")
    elif add_new == "CHANGE":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        found = False
        for employee in employee_info:
            if employee[1] == find_emp:
                changeName = input(employee.replace(employee[0], 'Please enter new name.\n'))
                changeSSN = input(employee.replace(employee[1], 'Please enter new SSN.\n'))
                changePhone = input(employee.replace(employee[2], 'Please enter new phone number.\n'))
                changeEmail = input(employee.replace(employee[3], 'Please enter new email.\n'))
                changeSalary = input(employee.replace(employee[4], 'Please enter new salary.\n'))

                found = True

        if found == False:
            print("Employee not found!")

Traceback (most recent call last):
  File "C:\Users\jmcra\Desktop\CPT200\Employment Management System - Functionality (4).py", line 54, in <module>
    changeName = input(employee.replace(employee[0], 'Please enter new name.\n'))
AttributeError: 'list' object has no attribute 'replace'
</code>```

答:
List has no method "replace"
to replace your list use this instead

```<code>employee[0] = input('New name')
</code>```

here's your code

```<code>elif add_new == "CHANGE":
    find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
    found = False
    for employee in employee_info:
        if employee[1] == find_emp:
            changeName = input('Please enter new name.\n')
            changeSSN = input('Please enter new SSN.\n')
            changePhone = input('Please enter new phone number.\n')
            changeEmail = input('Please enter new email.\n')
            changeSalary = input('Please enter new salary.\n')

            employee[0] = changeName;
            employee[1] = changeSSN;
            employee[2] = changePhone;
            employee[3] = changeEmail;
            employee[4] = changeSalary;

            found = True
</code>```

You can view all the list methods here :
https://www.programiz.com/python-programming/methods/list

Title: Find and replace a sublist in Python

Body:
I'm fairly new to Python and programming in general and have run into a situation that I can't figure out.

I'm building an Employee Management System in which a user can add a new employee, view all employees, search for an employee by SSN and replace an employee's previous info by searching for the SSN and re-entering the required input.  The last part is where I am failing.  I believe that I am able to search appropriately by SSN but I can't figure out how to get the user to replace the previous info from that sublist.  Can anyone help me figure this out? I also included the error message that I receive below the script.

employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL EMPLOYEES." To find an employee, type: "SEARCH EMPLOYEE BY SSN." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "SEARCH":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        found = False
        for employee in employee_info:
            if employee[1] == find_emp:
                print('            -----------------', employee[0], '-----------------\n')
                print('SSN:', employee[1], '\n')
                print('Phone:', '(' + employee[2][0] + employee[2][1] + employee[2][2] + ')' + employee[2][3] + employee[2][4] + employee[2][
                5] + '-' + employee[2][6] + employee[2][7] + employee[2][8] + employee[2][9], '\n')
                print('Email:', employee[3], '\n')
                print('Salary:', '$' + str(employee[4]), '\n')
                print('            ----------------------------------------------------')
                found = True

        if found == False:
            print("Employee not found!")
    elif add_new == "CHANGE":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        found = False
        for employee in employee_info:
            if employee[1] == find_emp:
                changeName = input(employee.replace(employee[0], 'Please enter new name.\n'))
                changeSSN = input(employee.replace(employee[1], 'Please enter new SSN.\n'))
                changePhone = input(employee.replace(employee[2], 'Please enter new phone number.\n'))
                changeEmail = input(employee.replace(employee[3], 'Please enter new email.\n'))
                changeSalary = input(employee.replace(employee[4], 'Please enter new salary.\n'))

                found = True

        if found == False:
            print("Employee not found!")

Traceback (most recent call last):
  File "C:\Users\jmcra\Desktop\CPT200\Employment Management System - Functionality (4).py", line 54, in <module>
    changeName = input(employee.replace(employee[0], 'Please enter new name.\n'))
AttributeError: 'list' object has no attribute 'replace'

Body:
List has no method "replace"
to replace your list use this instead

employee[0] = input('New name')

here's your code

elif add_new == "CHANGE":
    find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
    found = False
    for employee in employee_info:
        if employee[1] == find_emp:
            changeName = input('Please enter new name.\n')
            changeSSN = input('Please enter new SSN.\n')
            changePhone = input('Please enter new phone number.\n')
            changeEmail = input('Please enter new email.\n')
            changeSalary = input('Please enter new salary.\n')

            employee[0] = changeName;
            employee[1] = changeSSN;
            employee[2] = changePhone;
            employee[3] = changeEmail;
            employee[4] = changeSalary;

            found = True

You can view all the list methods here :
https://www.programiz.com/python-programming/methods/list


问:
Is it possible to train data on 4 features and test on only using features?
I have done training on four features including Month, day, Hour and Temperature which is predicting some value , what i wan to do is to predict value on basis of month ,hour and day of next day only because i don't know the temp of next day(which is going to be unseen data not used in training) so this makes the testing of data using only 3 features.
Classifier used is SVR.
I am a beginner in machine learning.

Your response will be appreciated

答:
If you are predicting temperature, then month, day and hour are your features(x_train) and temperature is your target(y_train). You should train your model with features and targets in supervised learning.  [regressor.fit(x_train, y_train)]

For testing, you should use your features (x_test) and the model will predict the target (y_predict) i.e Temperature the next day. [y_predict = regressor.predict(x_test)].
So you are using same number of features for training and testing.


问:
How to store file paths from a tab separated text file in a bash array
I have a tab separated text file with one column of file paths, e.g. table.txt

```<code>> SampleID  Factor  Condition   Replicate   Treatment   Type    Dataset isPE    ReadLength  isREF   PathFASTQ
> DG13  fd3 c1  1   cc  0   0102    0   50  1   "/path/to/fastq"
> DG14  fd3 c1 1    cc  1   0102    0   50  1   "/path/to/fastq"
</code>```

I would like to store the paths in a bash array so I can use these in a downstream parallel computation (SGE Task Arrays). For simplicity, the leading and trailing " can easily be not included in table.txt.

Excluding the header line, I tried the following:

```<code>files=($(awk '{ if(($8 == 0)) { print $1} }' table.txt ))
paths=($(awk '{ if(($8 == 0)) { print $11} }' table.txt ))
infile="${paths[$SGE_TASK_ID]}"/"${files[$SGE_TASK_ID]}".fastq.gz
</code>```

$SGE_TASK_ID takes a user-defined integer value between (1-N) in case someone does not know.

Unfortunately $infile does not show the expected value for $SGE_TASK_ID=1:

```<code>/path/to/fastq/DG13.fastq.gz
</code>```

Thanks for your help.

答:
Could you please try following, this code will remove Control M characters during run of the code.

```<code>myarr=($(awk '{gsub(/\r/,"")} match($NF,/\/[^"]*/){\
         val=substr($NF,RSTART,RLENGTH);\
         num=split(val,array,"/");\
         print val"/"$1"."array[num]".gz"}'  Input_file))
for i in "${myarr[@]}"
do
  echo $i
done
</code>```

In case you want to remove control M characters from your Input_file itself then try running following too:

```<code>tr -d '\r' < Input_file > temp && mv temp Input_file
</code>```

When we print array with loop as above shown, output will be as follows.

```<code>/path/to/fastq/DG13.fastq.gz
/path/to/fastq/DG14.fastq.gz
</code>```

Explanation of awk code:

```<code>awk '                                 ##Starting awk program from here.
match($NF,/\/[^"]*/){                 ##Using match function of awk program here, match everything till " in last field.
  val=substr($NF,RSTART,RLENGTH)      ##Creating variable val which is sub-string where starting point is RSTART till value of RLENGTH.
  num=split(val,array,"/")            ##Creating variable num whose value is number of elements plitted by split, splitting val into array with / is delimiter.
  print val"/"$1"."array[num]".gz"    ##Printing val / first field DOT array last element then .gz here.
}
'  Input_file                         ##Mentioning Input_file name here.
</code>```

Body:
I have a tab separated text file with one column of file paths, e.g. table.txt

> SampleID  Factor  Condition   Replicate   Treatment   Type    Dataset isPE    ReadLength  isREF   PathFASTQ
> DG13  fd3 c1  1   cc  0   0102    0   50  1   "/path/to/fastq"
> DG14  fd3 c1 1    cc  1   0102    0   50  1   "/path/to/fastq"

I would like to store the paths in a bash array so I can use these in a downstream parallel computation (SGE Task Arrays). For simplicity, the leading and trailing " can easily be not included in table.txt.

Excluding the header line, I tried the following:

files=($(awk '{ if(($8 == 0)) { print $1} }' table.txt ))
paths=($(awk '{ if(($8 == 0)) { print $11} }' table.txt ))
infile="${paths[$SGE_TASK_ID]}"/"${files[$SGE_TASK_ID]}".fastq.gz

$SGE_TASK_ID takes a user-defined integer value between (1-N) in case someone does not know.

Unfortunately $infile does not show the expected value for $SGE_TASK_ID=1:

/path/to/fastq/DG13.fastq.gz

Thanks for your help.

Body:
Could you please try following, this code will remove Control M characters during run of the code.

myarr=($(awk '{gsub(/\r/,"")} match($NF,/\/[^"]*/){\
         val=substr($NF,RSTART,RLENGTH);\
         num=split(val,array,"/");\
         print val"/"$1"."array[num]".gz"}'  Input_file))
for i in "${myarr[@]}"
do
  echo $i
done

In case you want to remove control M characters from your Input_file itself then try running following too:

tr -d '\r' < Input_file > temp && mv temp Input_file

When we print array with loop as above shown, output will be as follows.

/path/to/fastq/DG13.fastq.gz
/path/to/fastq/DG14.fastq.gz

Explanation of awk code:

awk '                                 ##Starting awk program from here.
match($NF,/\/[^"]*/){                 ##Using match function of awk program here, match everything till " in last field.
  val=substr($NF,RSTART,RLENGTH)      ##Creating variable val which is sub-string where starting point is RSTART till value of RLENGTH.
  num=split(val,array,"/")            ##Creating variable num whose value is number of elements plitted by split, splitting val into array with / is delimiter.
  print val"/"$1"."array[num]".gz"    ##Printing val / first field DOT array last element then .gz here.
}
'  Input_file                         ##Mentioning Input_file name here.