问:
How to consume Google PubSub opencensus metrics using GoLang?
I am new in Google PubSub. I am using GoLang for the client library.

How to see the opencensus metrics that recorded by the google-cloud-go library?

I already success publish a message to Google PubSub. And now I want to see this metrics, but I can not find these metrics in Google Stackdriver.

```<code>PublishLatency = stats.Float64(statsPrefix+"publish_roundtrip_latency", "The latency in milliseconds per publish batch", stats.UnitMilliseconds)
</code>```

https://github.com/googleapis/google-cloud-go/blob/25803d86c6f5d3a315388d369bf6ddecfadfbfb5/pubsub/trace.go#L59

答:
This is curious; I'm surprised to see these (machine-generated) APIs sprinkled with OpenCensus (Stats) integration.

I've not tried this but I'm familiar with OpenCensus.

One of OpenCensus' benefits is that it loosely-couples the generation of e.g. metrics from the consumption. So, while the code defines the metrics (and views), I expect (!?) the API leaves it to you to choose which Exporter(s) you'd like to use and to configure these.

In your code, you'll need to import the Stackdriver (and any other exporters you wish to use) and then follow these instructions:

https://opencensus.io/exporters/supported-exporters/go/stackdriver/#creating-the-exporter

NOTE I encourage you to look at the OpenCensus Agent too as this further decouples your code; you reference the generic Opencensus Agent in your code and configure the agent to route e.g. metrics to e.g. Stackdriver.

For Stackdriver, you will need to configure the exporter with a GCP Project ID and that project will need to have Stackdriver Monitor enabled (and configured). I've not used Stackdriver in some months but this used to require a manual step too. Easiest way to check is to visit:

https://console.cloud.google.com/monitoring/?project=[[YOUR-PROJECT]]

If I understand the intent (!) correctly, I expect API calls will then record stats at the metrics in the views defined in the code that you referenced.

Once you're confident that metrics are being shipped to Stackdriver, the easiest way to confirm this is to query a metric using Stackdriver's metrics explorer:

https://console.cloud.google.com/monitoring/metrics-explorer?project=[[YOUR-PROJECT]]

You may wish to test this approach using the Prometheus Exporter because it's simpler. After configuring the Prometheus Exporter, when you run your code, it will be create an HTTP server and you can curl the metrics that are being generated on:

http://localhost:8888/metrics

NOTE Opencensus is being (!?) deprecated in favor of a replacement solution called OpenTelemetry.

Body:
I am new in Google PubSub. I am using GoLang for the client library.

How to see the opencensus metrics that recorded by the google-cloud-go library?

I already success publish a message to Google PubSub. And now I want to see this metrics, but I can not find these metrics in Google Stackdriver.

PublishLatency = stats.Float64(statsPrefix+"publish_roundtrip_latency", "The latency in milliseconds per publish batch", stats.UnitMilliseconds)

https://github.com/googleapis/google-cloud-go/blob/25803d86c6f5d3a315388d369bf6ddecfadfbfb5/pubsub/trace.go#L59


来源: stackexchange

问:
CSS not displaying properly after transferred to IIS 7 in IE 9
When running on dev server through VS 2010 all CSS displays properly.  I publish to win server 2008 r2 with IIS 7, and when I open in IE 9 the inline-block doesnt work, the gradients dont work, and the box-shadow doesnt work.  It strips out most of the CSS formatting, I load the same page in firefox and it looks the same as it does in IE 9 under the dev server.  Code below:
CSS file:

```<code>body {
}
#opsChartContainer
{
    background: #FFFFFF;
margin: auto;
width: 600px;
padding-top: 15px;
font-family: helvetica, arial, sans-serif;
display: inline-table;
}
#oldestActiveCon
{
    background: #FFFFFF;
    margin: auto;
    width: 300px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#incVolumeCon
{
    background: #FFFFFF;
    margin: auto;
    width: 700px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#reqSLACon
{
    background: #FFFFFF;
    margin: auto;
    width: 400px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}

h1
{
    background: #e3e3e3;
    background: -moz-linear-gradient(top, #fcfdfe, #8bb7e3);
    background: -webkit-gradient(linear, left top, left bottom, from(#fcfdfe), to(#8bb7e3));
    padding: 10px 20px;
    margin-left: -20px;
    margin-top: 0;
    position: relative;
    width: 70%;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #292929;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfdfe,     endColorstr=#8bb7e3)";
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-weight: bold;
}
h2
{
    background: #dde3d5;
    padding: 10px 20px;
    margin-left: 5px;
    margin-top: 10px;
    position: relative;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #b5baae;
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-style: normal;
}
.mGrid {
    width: 100%;
    margin: 5px 0 10px 0;
    border: solid 1px #525252;
    border-collapse:collapse;
}
.mGrid td {
    padding: 2px;

}
.header
{
    padding: 4px 2px;
    color: #ffffff;
    background: #4289c6 url('../grd_head.png') repeat-x top;
}
.alt
{
    background: #FFFFFF url('../grd_alt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}
.rst
{
    background: #FFFFFF url('../grd_firstt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}

ul#testy li
{
    list-style-type: none;
    display: inline-block;
    vertical-align: top;
    padding-left: 50px;
}
</code>```

ASPX front end:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"     CodeBehind="test.aspx.cs" Inherits="test.test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="opsChartContainer"><h1>TEXT</h1><h2>FLASHFILE</h2></div>
<div id="oldestActiveCon"><h1>TEXT</h1>
<h2>
    <asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333"
        GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="200px">
        <AlternatingRowStyle CssClass="alt" />
        <Columns>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" />
            <asp:BoundField DataField="Time" HeaderText="Time" ReadOnly="True"
                SortExpression="Time" />
            <asp:TemplateField HeaderText="Request ID">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"     NavigateUrl='<%    # "link"+ Eval("Request") + "&"%>'><%#Eval("Request")%></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <HeaderStyle CssClass="header" />

<RowStyle CssClass="rst"></RowStyle>

    </asp:GridView>
</h2>
</div>

<div id="incVolumeCon">
    <h1>text</h1>
    <h2>
        flashfile
    </h2>
</div>
<div id="reqSLACon">
    <h1> text</h1>
        <h2>
        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
        DataSourceID="blahblah" CellPadding="4" ForeColor="#333333"
        GridLines="None" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" RowStyle-CssClass="rst" Width = "400">
        <Columns>
            <asp:BoundField DataField="text" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="Dueby Time" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="Expr1" HeaderText="text" ReadOnly="True"
                SortExpression="Expr1" />
            <asp:TemplateField HeaderText="Request ID" >
            <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# "link"+ Eval("Request ID") + "&"%>'><%#Eval("Request ID")%></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

test
    </h2>
</div>
</code>```

ANY ideas?  What is causing the disparity between when I view it in IE 9 through dev server from vs 2010 and when I view it in IE 9 on production server?

答: Did you manually go to the URL of the CSS file on the server and see what it displays? I expect it will be a 500 Internal Server Error or similar response instead of actual CSS code.</p>

ContentLicense: CC BY-SA 3.0

Body:
When running on dev server through VS 2010 all CSS displays properly.  I publish to win server 2008 r2 with IIS 7, and when I open in IE 9 the inline-block doesnt work, the gradients dont work, and the box-shadow doesnt work.  It strips out most of the CSS formatting, I load the same page in firefox and it looks the same as it does in IE 9 under the dev server.  Code below:
CSS file:

body {
}
#opsChartContainer
{
    background: #FFFFFF;
margin: auto;
width: 600px;
padding-top: 15px;
font-family: helvetica, arial, sans-serif;
display: inline-table;
}
#oldestActiveCon
{
    background: #FFFFFF;
    margin: auto;
    width: 300px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#incVolumeCon
{
    background: #FFFFFF;
    margin: auto;
    width: 700px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}
#reqSLACon
{
    background: #FFFFFF;
    margin: auto;
    width: 400px;
    padding-top: 15px;
    font-family: helvetica, arial, sans-serif;
    display: inline-table;
}

h1
{
    background: #e3e3e3;
    background: -moz-linear-gradient(top, #fcfdfe, #8bb7e3);
    background: -webkit-gradient(linear, left top, left bottom, from(#fcfdfe), to(#8bb7e3));
    padding: 10px 20px;
    margin-left: -20px;
    margin-top: 0;
    position: relative;
    width: 70%;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #292929;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfdfe,     endColorstr=#8bb7e3)";
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-weight: bold;
}
h2
{
    background: #dde3d5;
    padding: 10px 20px;
    margin-left: 5px;
    margin-top: 10px;
    position: relative;
    -moz-box-shadow: 1px 1px 3px #292929;
    -webkit-box-shadow: 1px 1px 3px #292929;
    box-shadow: 3px 3px 3px #b5baae;
    color: #454545;
    text-shadow: 0 1px 0 white;
    font-size: small;
    font-style: normal;
}
.mGrid {
    width: 100%;
    margin: 5px 0 10px 0;
    border: solid 1px #525252;
    border-collapse:collapse;
}
.mGrid td {
    padding: 2px;

}
.header
{
    padding: 4px 2px;
    color: #ffffff;
    background: #4289c6 url('../grd_head.png') repeat-x top;
}
.alt
{
    background: #FFFFFF url('../grd_alt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}
.rst
{
    background: #FFFFFF url('../grd_firstt.png') repeat-x top;
    font-size: smaller;
    font-family: Arial;
    font-style: normal;
}

ul#testy li
{
    list-style-type: none;
    display: inline-block;
    vertical-align: top;
    padding-left: 50px;
}

ASPX front end:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"     CodeBehind="test.aspx.cs" Inherits="test.test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

TEXT

FLASHFILE

TEXT

    <asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333"
        GridLines="None" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" Width="200px">
        <AlternatingRowStyle CssClass="alt" />
        <Columns>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" />
            <asp:BoundField DataField="Time" HeaderText="Time" ReadOnly="True"
                SortExpression="Time" />
            <asp:TemplateField HeaderText="Request ID">
                <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"     NavigateUrl='<%    # "link"+ Eval("Request") + "&"%>'><%#Eval("Request")%></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>

        <HeaderStyle CssClass="header" />

<RowStyle CssClass="rst"></RowStyle>

    </asp:GridView>

text

        flashfile

 text

        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
        DataSourceID="blahblah" CellPadding="4" ForeColor="#333333"
        GridLines="None" CssClass="mGrid" AlternatingRowStyle-CssClass="alt" RowStyle-CssClass="rst" Width = "400">
        <Columns>
            <asp:BoundField DataField="text" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="Dueby Time" HeaderText="text" ReadOnly="True"
                SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="text" HeaderText="text"
                ReadOnly="True" SortExpression="text" />
            <asp:BoundField DataField="Expr1" HeaderText="text" ReadOnly="True"
                SortExpression="Expr1" />
            <asp:TemplateField HeaderText="Request ID" >
            <ItemTemplate>
                    <asp:HyperLink ID="HyperLink1" runat="server" Target="_blank" NavigateUrl='<%# "link"+ Eval("Request ID") + "&"%>'><%#Eval("Request ID")%></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>

test

ANY ideas?  What is causing the disparity between when I view it in IE 9 through dev server from vs 2010 and when I view it in IE 9 on production server?


问:
Rescheduling cron jobs in nodejs on server restart
I have node js application where a user can schedule 4-5 different cron jobs. A user selects a start_date, end_date, start_time, and end_time, and accordingly, the cron functions are scheduled and some campaigns are generated to connect with leads (or other users). I am using npm package node-schedule to achieve the desired cron-job execution but the issue arises if my web application crashes in between.

As per the official documentation of node-schedule,

Note that Node Schedule is designed for in-process scheduling, i.e. scheduled jobs will only fire as long as your script is running, and the schedule will disappear when execution completes.

The solution I can come up to resolve this is to call the cron functions using server.js file which restarts every time the server script is executed. But I am unable to resolve some of the following issues:

A scheduler is an individual function, not campaign-specific, so how will the application know which cron-function to start if it has not been completed?

A scheduler is a single function, that will be called every time as soon as the server is restarted. If 6 instances of a server are created, it will be called 6 times.

Suppose, my scheduler is due to execute between 28th May 11:00 AM to 31st May 12:00 AM. The scheduler starts its job and some of the campaigns are executed in between. If my server goes down on 30th May, how can I pick up from the remaining date-time and campaigns and complete it from there?

So I am concerned about how to schedule or handle the cron job functions for the campaigns? If any of the campaign cron jobs is crashed in between if the server is stopped, how should I be able to re-schedule or execute that cron function from the time or date that has been left of it?

I am not much experienced with cron jobs, hoping for some handy solutions.

答:
Here some advice, that you could review or implement depending of your hardware capabilities:

Decoupling

Decouple your current application in two separated artifacts: web and campaign. This allows each service to be deployed, rebuilt, re-deployed and managed independently. And also to have autonomous or cross-functional Teams.

source: https://skelia.com/articles/5-major-benefits-microservice-architecture/

Fault tolerance

If you need an app that doesn't affect a failure , crash or any event who needs a restart, you must use something outside to your app.

Commonly this outside is a database. You could use a json file if a database is not an option for you.

Campaign

We have two entities here:

campaign_configurations

| identifier        | desc           | cron_expression |
|-------------------|----------------|-----------------|
| month_discounts   | discounts ...  | 0 0 1 * *       |
| reminder_shop_car | a reminder ... | */10 * * * *    |
|                   |                |                 |

Also you can add a column to control the period validity of the cron with a start and end date.

campaign_executions

| execution_date      | execution_status | execution_log |
|---------------------|------------------|---------------|
| 10-10-2020 01:00:00 | finished         | ...           |
| 10-10-2020 14:30:00 | error            | ...           |
| 10-10-2020 14:35:00 | executing        | ...           |

App startup

When your nodejs campaign starts/restarts due to failure or scheduled maintance, this must be the flow:

read campaign_configurations table and get all of cron expressions in a valid period.

use an algorithm to detect if today your cron expressions must be executed. Example:

a cron only in December (Christmas) should not run today: June 03

a cron for every 5 minutes, should execute in the next 5 minutes

Every execution at the start must create an entry in campaign_executions table with a status: pending

Every execution could use node-schedule to execute it logic.

New executions should not execute if there is a previous execution in pending or error. According to your internal business logic.

App is healthy

When app is healthy, its must query to the campaign_configurations table in order to execute new or modified cron expressions (previous explained flow)

This could be at every 30 minutes, more and less, according to your internal business logic.

You could use node-schedule for this task.

ContentLicense: CC BY-SA 4.0


问:
Pomodoro timer in Python
I have recently started learning Python and tried writing a pomodoro timer program. I have written the tasks() function and it works fine but i don't know how to write break function that works together with tasks() function.

Things I have tried:

I tried writing the break function separate from tasks() function and called break function inside the tasks() function.

I have written the break code inside the tasks() function.

Define main function and written break function in it but nothing is working. I have tried to google
but could not find the answer.

I would be really thankful if someone can teach me how to integrate break function with tasks function.

```<code>import time

checkmark=0
def tasks():
    global checkmark
    carry_on='y'
    while carry_on=='y'or carry_on=='Y':
        min=0
        task=input('What task do you want to work on?')
        print('timer for ',task,' is 25 mins')
        start=input('Press Enter to start the timer.')
        while min!=1:
            time.sleep(60)
            min=min+1
        print('End of task')
        checkmark=checkmark+1
        print('Total check mark is ',checkmark)

def main():
    tasks()
    mins=0
    if checkmark <4:
        print('take a short break')
        while mins!=3:
            time.sleep(60)
            mins=mins+1
            print('break over')
    elif checkmark >=4:
        print('Take a long break')
        while mins !=10:
            time.sleep(60)
            mins=mins+1
        print('Break over')
    else:
        tasks()

if __name__ == '__main__':
    main()
</code>```

答:
You can define the tasks() and breaks() functions as foolows. ALso note that you had not taken any input from the user to carry on with the task or not. You can check the code below. Also I have defined a total_mins variable which keep tracks of total time worked on the task.

```<code>import time

checkmark = 0
total_mins = 0

def tasks(task):
    global checkmark
    global total_mins
    mins=0
    print('Timer for ',task,' is 25 mins.')
    start=input('Press Enter to start the timer.')
    while mins <= 25:
        time.sleep(60)
        mins = mins + 1
        total_mins += 1
        print(mins, " minutes work completed.")
    print('End of Pomodoro')
    checkmark += 1
    print('Total check mark is ',checkmark)

def breaks():
    global checkmark
    mins = 0
    if checkmark <4:
        print('Take a short break.')
        while mins!=3:
            time.sleep(60)
            mins = mins + 1
            print(mins, " minutes break completed.")
        print('Break over')

    elif checkmark >=4:
        print('Take a long break.')
        while mins !=10:
            time.sleep(60)
            mins = mins + 1
            print(mins, " minutes break completed.")
        checkmark = 0
        print('Break over.')

def main():
    carry_on = 'y'
    task=input('Welcome to Pomodoro Timer\n What task do you want to work on? ')
    while carry_on=='y'or carry_on=='Y':
        tasks(task)
        breaks()
        carry_on = input("Do you want ot carry on?(y/n)")

    print("End of task ",task,". \nTotal time worked was minutes ", total_mins, " minutes.")

if __name__ == '__main__':
    main()
</code>```

Title: Pomodoro timer in Python

Body:
I have recently started learning Python and tried writing a pomodoro timer program. I have written the tasks() function and it works fine but i don't know how to write break function that works together with tasks() function.

Things I have tried:

I tried writing the break function separate from tasks() function and called break function inside the tasks() function.

I have written the break code inside the tasks() function.

Define main function and written break function in it but nothing is working. I have tried to google
but could not find the answer.

I would be really thankful if someone can teach me how to integrate break function with tasks function.

import time

checkmark=0
def tasks():
    global checkmark
    carry_on='y'
    while carry_on=='y'or carry_on=='Y':
        min=0
        task=input('What task do you want to work on?')
        print('timer for ',task,' is 25 mins')
        start=input('Press Enter to start the timer.')
        while min!=1:
            time.sleep(60)
            min=min+1
        print('End of task')
        checkmark=checkmark+1
        print('Total check mark is ',checkmark)

def main():
    tasks()
    mins=0
    if checkmark <4:
        print('take a short break')
        while mins!=3:
            time.sleep(60)
            mins=mins+1
            print('break over')
    elif checkmark >=4:
        print('Take a long break')
        while mins !=10:
            time.sleep(60)
            mins=mins+1
        print('Break over')
    else:
        tasks()

if __name__ == '__main__':
    main()

Body:
You can define the tasks() and breaks() functions as foolows. ALso note that you had not taken any input from the user to carry on with the task or not. You can check the code below. Also I have defined a total_mins variable which keep tracks of total time worked on the task.

import time

checkmark = 0
total_mins = 0

def tasks(task):
    global checkmark
    global total_mins
    mins=0
    print('Timer for ',task,' is 25 mins.')
    start=input('Press Enter to start the timer.')
    while mins <= 25:
        time.sleep(60)
        mins = mins + 1
        total_mins += 1
        print(mins, " minutes work completed.")
    print('End of Pomodoro')
    checkmark += 1
    print('Total check mark is ',checkmark)

def breaks():
    global checkmark
    mins = 0
    if checkmark <4:
        print('Take a short break.')
        while mins!=3:
            time.sleep(60)
            mins = mins + 1
            print(mins, " minutes break completed.")
        print('Break over')

    elif checkmark >=4:
        print('Take a long break.')
        while mins !=10:
            time.sleep(60)
            mins = mins + 1
            print(mins, " minutes break completed.")
        checkmark = 0
        print('Break over.')

def main():
    carry_on = 'y'
    task=input('Welcome to Pomodoro Timer\n What task do you want to work on? ')
    while carry_on=='y'or carry_on=='Y':
        tasks(task)
        breaks()
        carry_on = input("Do you want ot carry on?(y/n)")

    print("End of task ",task,". \nTotal time worked was minutes ", total_mins, " minutes.")

if __name__ == '__main__':
    main()


问:
How can I check if vars are equal 0?
On php documentation we can see:

```<code>"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
</code>```

If I have for example $var1 = 0; and $var2 = 0; on php I can do:

```<code>if (empty($var1)){
echo "empty";
}
</code>```

But I cant do this:

```<code>if (empty($var1 && $var2)){
echo "empty";
}
</code>```

How can I do for check if the two vars are equal to 0 on the same if?

答:
You can run

```<code>if( $var1 === 0 && $var2 === 0 ) {
   // both empty
}
</code>```

to see if those two variable are both holding the integer zero.

If you want a more loose type check (see if the variables are zero, or false, or null, for example), you can do:

```<code>if( empty($var1) && empty($var2) ) {
   // both empty
}
</code>```

If (based on your question) you wanted to see if the variable holds the string "0", you would do it like this:

```<code>if( $var1 === "0" && $var2 === "0" ) {
   // both are the string "0"
}
</code>```

Title: How can I check if vars are equal 0?

Body:
On php documentation we can see:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)

If I have for example $var1 = 0; and $var2 = 0; on php I can do:

if (empty($var1)){
echo "empty";
}

But I cant do this:

if (empty($var1 && $var2)){
echo "empty";
}

How can I do for check if the two vars are equal to 0 on the same if?

Body:
You can run

if( $var1 === 0 && $var2 === 0 ) {
   // both empty
}

to see if those two variable are both holding the integer zero.

If you want a more loose type check (see if the variables are zero, or false, or null, for example), you can do:

if( empty($var1) && empty($var2) ) {
   // both empty
}

If (based on your question) you wanted to see if the variable holds the string "0", you would do it like this:

if( $var1 === "0" && $var2 === "0" ) {
   // both are the string "0"
}


问:
Multirow multicolumn table
I need to create the following table in LaTeX and I just cannot seem to get it right.

The text inside the cells is not centered correctly and the same goes for the "Eye movements" cell. Could any of you see what I doing wrong?

```<code>\begin{tabular}{ccc|c}
& & \multicolumn{2}{c}{\textbf{Response}} \\
& & unnatural & natural \\ \cline{3-4}
\multicolumn{1}{c}{\multirow{2}{*}{\begin{sideways}\textbf{Eye movement}\end{sideways}}} &
\multicolumn{1}{c|}{\begin{sideways}unnatural\end{sideways}} & 1 & \multicolumn{1}{c|}{2} \\ \cline{2-4}
\multicolumn{1}{c}{}                        &
\multicolumn{1}{c|}{\begin{sideways}natural\end{sideways}} & 3 & \multicolumn{1}{c|}{4}   \\ \cline{3-4}
\end{tabular}
</code>```

答:
Thanks for the pointer. I finally made it work with the following code:</p>

```<code>\begin{table}[h]\centering
\def \BoxWidth {3.5cm}
\def \BoxHeight {2cm}
\def \SWidth {0.2cm}
\newcolumntype{M}{>{\centering\arraybackslash}m{\BoxWidth}}
\newcolumntype{S}{>{\centering\arraybackslash}m{\SWidth}}
\newcolumntype{R}{>{\raggedright\arraybackslash}m{\BoxWidth}}
\begin{tabular}{SSM|M}
~ & ~ & \multicolumn{2}{c}{\textbf{Response}} \\
~ & ~ & unnatural & natural  \\  \cline{3-4}
\multirow{2}{*}{\begin{sideways}{\textbf{Eye Movements}}\end{sideways}}
~ & \begin{sideways}\parbox{\BoxHeight}{\centering unnatural}\end{sideways}
&  \multicolumn{1}{|R|}{Command-based interfaces} &  \multicolumn{1}{R|}{Not Possible} \\ \cline{2-4}
~ & \begin{sideways}\parbox{\BoxHeight}{\centering natural}\end{sideways}
& \multicolumn{1}{|R|}{Non-command interfaces} &  \multicolumn{1}{R|}{Virtual environments} \\  \cline{3-4}
\end{tabular}
\end{table}
</code>```

Title: Multirow multicolumn table

Body:
I need to create the following table in LaTeX and I just cannot seem to get it right.

The text inside the cells is not centered correctly and the same goes for the "Eye movements" cell. Could any of you see what I doing wrong?

\begin{tabular}{ccc|c}
& & \multicolumn{2}{c}{\textbf{Response}} \\
& & unnatural & natural \\ \cline{3-4}
\multicolumn{1}{c}{\multirow{2}{*}{\begin{sideways}\textbf{Eye movement}\end{sideways}}} &
\multicolumn{1}{c|}{\begin{sideways}unnatural\end{sideways}} & 1 & \multicolumn{1}{c|}{2} \\ \cline{2-4}
\multicolumn{1}{c}{}                        &
\multicolumn{1}{c|}{\begin{sideways}natural\end{sideways}} & 3 & \multicolumn{1}{c|}{4}   \\ \cline{3-4}
\end{tabular}

Body:
Thanks for the pointer. I finally made it work with the following code:

\begin{table}[h]\centering
\def \BoxWidth {3.5cm}
\def \BoxHeight {2cm}
\def \SWidth {0.2cm}
\newcolumntype{M}{>{\centering\arraybackslash}m{\BoxWidth}}
\newcolumntype{S}{>{\centering\arraybackslash}m{\SWidth}}
\newcolumntype{R}{>{\raggedright\arraybackslash}m{\BoxWidth}}
\begin{tabular}{SSM|M}
~ & ~ & \multicolumn{2}{c}{\textbf{Response}} \\
~ & ~ & unnatural & natural  \\  \cline{3-4}
\multirow{2}{*}{\begin{sideways}{\textbf{Eye Movements}}\end{sideways}}
~ & \begin{sideways}\parbox{\BoxHeight}{\centering unnatural}\end{sideways}
&  \multicolumn{1}{|R|}{Command-based interfaces} &  \multicolumn{1}{R|}{Not Possible} \\ \cline{2-4}
~ & \begin{sideways}\parbox{\BoxHeight}{\centering natural}\end{sideways}
& \multicolumn{1}{|R|}{Non-command interfaces} &  \multicolumn{1}{R|}{Virtual environments} \\  \cline{3-4}
\end{tabular}
\end{table}


问:
Laravel Lighthouse Error: Response not successful: Received status code 500
I'm using laravel lighthouse for graphql and I'm encountering this error when writing graphql queries in lighthouse playground:

ServerError: Response not successful: Received status code 500

bundle.esm.js:69 POST http://127.0.1.4/api 500 (Internal Server Error)

I get this error when I open lighthouse playground page and I don't even get a chance to write queries.

Here is my lighthouse config file, I just changed the route part to api and also this part 'enable' => env('LIGHTHOUSE_CACHE_ENABLE', false):

```<code><?php

return [
    'route' => [
        'uri' => '/api',
        'name' => 'api',
        'middleware' => [
            \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class,
            \Nuwave\Lighthouse\Support\Http\Middleware\AttemptAuthentication::class,
        ],
    ],
    'guard' => null,
    'schema' => [
        'register' => base_path('graphql/schema.graphql'),
    ],
    'cache' => [
        'enable' => env('LIGHTHOUSE_CACHE_ENABLE', false),
        'key' => env('LIGHTHOUSE_CACHE_KEY', 'lighthouse-schema'),
        'ttl' => env('LIGHTHOUSE_CACHE_TTL', null),
    ],
    'namespaces' => [
        'models' => 'App\\Models',
        'queries' => 'App\\GraphQL\\Queries',
        'mutations' => 'App\\GraphQL\\Mutations',
        'subscriptions' => 'App\\GraphQL\\Subscriptions',
        'interfaces' => 'App\\GraphQL\\Interfaces',
        'unions' => 'App\\GraphQL\\Unions',
        'scalars' => 'App\\GraphQL\\Scalars',
        'directives' => ['App\\GraphQL\\Directives'],
    ],
    'security' => [
        'max_query_complexity' => \GraphQL\Validator\Rules\QueryComplexity::DISABLED,
        'max_query_depth' => \GraphQL\Validator\Rules\QueryDepth::DISABLED,
        'disable_introspection' => \GraphQL\Validator\Rules\DisableIntrospection::DISABLED,
    ],
    'pagination' => [
        'default_count' => 10,
        'max_count' => null,
    ],
    'pagination_amount_argument' => 'first',
    'orderBy' => 'field',
    'debug' => \GraphQL\Error\Debug::INCLUDE_DEBUG_MESSAGE | \GraphQL\Error\Debug::INCLUDE_TRACE,
    'error_handlers' => [
        \Nuwave\Lighthouse\Execution\ExtensionErrorHandler::class,
        \Nuwave\Lighthouse\Execution\ReportingErrorHandler::class,
    ],
    'global_id_field' => 'id',
    'batched_queries' => true,
    'transactional_mutations' => true,
    'batchload_relations' => true,
    'subscriptions' => [
        'queue_broadcasts' => env('LIGHTHOUSE_QUEUE_BROADCASTS', true),
        'broadcasts_queue_name' => env('LIGHTHOUSE_BROADCASTS_QUEUE_NAME', null),
        'storage' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE', 'redis'),
        'storage_ttl' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE_TTL', null),
        'broadcaster' => env('LIGHTHOUSE_BROADCASTER', 'pusher'),
        'broadcasters' => [
            'log' => [
                'driver' => 'log',
            ],
            'pusher' => [
                'driver' => 'pusher',
                'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@pusher',
                'connection' => 'pusher',
            ],
        ],
    ],
    'defer' => [
        'max_nested_fields' => 0,
        'max_execution_ms' => 0,
    ],
];
</code>```

And here is my CORS config file, I just changed the paths part to api:

```<code><?php

return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];
</code>```

Here's graphql's schema file:

```<code>"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")

"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")

"A datetime and timezone string in ISO 8601 format `Y-m-dTH:i:sO`, e.g. `2020-04-20T13:53:12+02:00`."
scalar DateTimeTz @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTimeTz")

type Query {
    fields(input: ListInput @spread): [Field]
    field(id: ID! @eq): Field @find(model: "App\\Field")
}

type Mutation {
    createField(
        name_en: String! @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @create(model: "App\\Field")

    updateField(
        id: ID! @rules(apply: ["required", "int"])
        name_en: String @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @update(model: "App\\Field")

    deleteField(
        id: ID! @rules(apply: ["required", "int"])
    ): Field @delete(model: "App\\Field")
}

type Field {
    id: ID!
    name_en: String!
    name_fa: String!
    description: String!
    img_url: String!
    created_at: DateTime!
    updated_at: DateTime!

    subFields: [SubField] @hasMany
}

input ListInput {
    page: Int @rules(apply: ["int"])
    limit: Int @rules(apply: ["int"])
    q: String @rules(apply: ["string", "max:191"])
}
</code>```

I really have no idea what the problem is. Hope you can help me with this.

答:
Replace the below code in  CORS config file:</p>

```<code>'paths' => ['api/*', 'graphql'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
</code>```

Body:
I'm using laravel lighthouse for graphql and I'm encountering this error when writing graphql queries in lighthouse playground:

ServerError: Response not successful: Received status code 500

bundle.esm.js:69 POST http://127.0.1.4/api 500 (Internal Server Error)

I get this error when I open lighthouse playground page and I don't even get a chance to write queries.

Here is my lighthouse config file, I just changed the route part to api and also this part 'enable' => env('LIGHTHOUSE_CACHE_ENABLE', false):

<?php

return [
    'route' => [
        'uri' => '/api',
        'name' => 'api',
        'middleware' => [
            \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class,
            \Nuwave\Lighthouse\Support\Http\Middleware\AttemptAuthentication::class,
        ],
    ],
    'guard' => null,
    'schema' => [
        'register' => base_path('graphql/schema.graphql'),
    ],
    'cache' => [
        'enable' => env('LIGHTHOUSE_CACHE_ENABLE', false),
        'key' => env('LIGHTHOUSE_CACHE_KEY', 'lighthouse-schema'),
        'ttl' => env('LIGHTHOUSE_CACHE_TTL', null),
    ],
    'namespaces' => [
        'models' => 'App\\Models',
        'queries' => 'App\\GraphQL\\Queries',
        'mutations' => 'App\\GraphQL\\Mutations',
        'subscriptions' => 'App\\GraphQL\\Subscriptions',
        'interfaces' => 'App\\GraphQL\\Interfaces',
        'unions' => 'App\\GraphQL\\Unions',
        'scalars' => 'App\\GraphQL\\Scalars',
        'directives' => ['App\\GraphQL\\Directives'],
    ],
    'security' => [
        'max_query_complexity' => \GraphQL\Validator\Rules\QueryComplexity::DISABLED,
        'max_query_depth' => \GraphQL\Validator\Rules\QueryDepth::DISABLED,
        'disable_introspection' => \GraphQL\Validator\Rules\DisableIntrospection::DISABLED,
    ],
    'pagination' => [
        'default_count' => 10,
        'max_count' => null,
    ],
    'pagination_amount_argument' => 'first',
    'orderBy' => 'field',
    'debug' => \GraphQL\Error\Debug::INCLUDE_DEBUG_MESSAGE | \GraphQL\Error\Debug::INCLUDE_TRACE,
    'error_handlers' => [
        \Nuwave\Lighthouse\Execution\ExtensionErrorHandler::class,
        \Nuwave\Lighthouse\Execution\ReportingErrorHandler::class,
    ],
    'global_id_field' => 'id',
    'batched_queries' => true,
    'transactional_mutations' => true,
    'batchload_relations' => true,
    'subscriptions' => [
        'queue_broadcasts' => env('LIGHTHOUSE_QUEUE_BROADCASTS', true),
        'broadcasts_queue_name' => env('LIGHTHOUSE_BROADCASTS_QUEUE_NAME', null),
        'storage' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE', 'redis'),
        'storage_ttl' => env('LIGHTHOUSE_SUBSCRIPTION_STORAGE_TTL', null),
        'broadcaster' => env('LIGHTHOUSE_BROADCASTER', 'pusher'),
        'broadcasters' => [
            'log' => [
                'driver' => 'log',
            ],
            'pusher' => [
                'driver' => 'pusher',
                'routes' => \Nuwave\Lighthouse\Subscriptions\SubscriptionRouter::class.'@pusher',
                'connection' => 'pusher',
            ],
        ],
    ],
    'defer' => [
        'max_nested_fields' => 0,
        'max_execution_ms' => 0,
    ],
];

And here is my CORS config file, I just changed the paths part to api:

<?php

return [
    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,
];

Here's graphql's schema file:

"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")

"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")

"A datetime and timezone string in ISO 8601 format `Y-m-dTH:i:sO`, e.g. `2020-04-20T13:53:12+02:00`."
scalar DateTimeTz @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTimeTz")

type Query {
    fields(input: ListInput @spread): [Field]
    field(id: ID! @eq): Field @find(model: "App\\Field")
}

type Mutation {
    createField(
        name_en: String! @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @create(model: "App\\Field")

    updateField(
        id: ID! @rules(apply: ["required", "int"])
        name_en: String @rules(apply: ["required"])
        name_fa: String
        description: String
        img_url: String
    ): Field @update(model: "App\\Field")

    deleteField(
        id: ID! @rules(apply: ["required", "int"])
    ): Field @delete(model: "App\\Field")
}

type Field {
    id: ID!
    name_en: String!
    name_fa: String!
    description: String!
    img_url: String!
    created_at: DateTime!
    updated_at: DateTime!

    subFields: [SubField] @hasMany
}

input ListInput {
    page: Int @rules(apply: ["int"])
    limit: Int @rules(apply: ["int"])
    q: String @rules(apply: ["string", "max:191"])
}

I really have no idea what the problem is. Hope you can help me with this.

Body:
Replace the below code in  CORS config file:

'paths' => ['api/*', 'graphql'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,


问:
Microsoft Outlook O365 "Add-In Error" With Automatic Restart
Recently I have been seeing my Microsoft O365 add-in load with this error:

Error Image ADD-IN ERROR Sorry, we had to restart because this add-in wasn't responding.

The console/dev tools shows no error logged at all and then the add-in procedes to restart and run just fine. Is there any reason why add-ins fail to load on occasion without specific errors?

答: By default, web add-ins are restarted if any action takes more than 330 ms (5s). You can use a WebWorker to launch long-running tasks. For example, see Long operations crash Office addin (JS).</p>


问:
Can I limit the width of text inside of a
?
In Markdown images are wrapped inside of paragraphs. I'd like images to be wider than text and fill the container's larger width. How can I solve this? Here is an example: https://sidey.now.sh/2019/08/31/difference-between-font-formats/

Ideally the text would only have a width of 40rem.

答:
You can solve this using CSS grid:

.container {
  margin:0 50px;
  border:1px solid;
}
.container >p {
  display:grid;
  grid-template-columns:1fr minmax(0,20rem) 1fr;
}

/* this pseudo element will take the first column and force the text to be on the middle one */
p::before {
  content:"";
}
/**/

p > img {
  grid-column:1/span 3; /* the image should take all the 3 columns (full width) */
}

img {
 max-width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<p>Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</p>
<p><img src="https://images.unsplash.com/photo-1580792214064-6102bf1948d5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2167&q=80" alt="image"></p>
<p>Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</p>
</div></code>```

Title: Can I limit the width of text inside of a <p>?

Body:
You can solve this using CSS grid:

.container {
  margin:0 50px;
  border:1px solid;
}
.container >p {
  display:grid;
  grid-template-columns:1fr minmax(0,20rem) 1fr;
}

/* this pseudo element will take the first column and force the text to be on the middle one */
p::before {
  content:"";
}
/**/

p > img {
  grid-column:1/span 3; /* the image should take all the 3 columns (full width) */
}

img {
 max-width:100%;
}

<div class="container">
<p>Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</p>
<p><img src="https://images.unsplash.com/photo-1580792214064-6102bf1948d5?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=2167&amp;q=80" alt="image"></p>
<p>Lorem ipsum dolor amet tousled viral art party blue bottle single-origin coffee cardigan, selvage man braid helvetica. Banh mi taxidermy meditation microdosing. Selvage cornhole YOLO, small batch vexillologist raclette VHS prism sustainable 8-bit ugh semiotics letterpress disrupt pop-up. Celiac shabby chic ugh, jianbing whatever kitsch tattooed edison bulb kogi irony etsy.</p>
</div>


问:
Why is the value of alpha different between psych::omega and psych::alpha in R?
I have data from a five-item measure completed by about 260 participants and estimated internal consistency with the psych library in R. I got a value of -0.36 (I triple-checked for reverse-coded questions). My data doesn't cover a broad range of the possible scores -- due to the nature of the group I am sampling from -- so this is a plausible number. But the scale I'm using is well validated, admittedly with low typical values of alpha ranging from 0.5--0.7.

When looking for alternative methods to assess my data I used psych::omega. This returns an alpha value of 0.57 alongwith the omega statistic I was looking for. This alpha value is much more in keeping with other literature which uses the scale in question. I have also looked at other validated measures from my study and the alpha values from psych::alpha and psych::omega are equal. It is only on this particular measure which is known to have low internal consistency where the difference appears.

My question: why are the alpha values different between psych::alpha and psych::omega?

The code below includes the actual data and will spit a warning about negatively correlated items. I've checked and rechecked my score-coding and it's correct so I am confident we can ignore this warning.

```<code>library("psych")

data <- structure(list(rMEQQ01 = c(2, 3, 3, 3, 3, 3, 3, 1, 5, 3, 3, 3,
3, 3, 3, 3, 3, 5, 3, 2, 5, 2, 3, 3, 3, 3, 3, 2, 3, 2, 2, 1, 3,
5, 3, 4, 3, 4, 5, 4, 3, 3, 2, 5, 4, 2, 3, 3, 5, 3, 3, 5, 5, 4,
2, 2, 4, 1, 4, 1, 2, 1, 5, 2, 4, 3, 3, 1, 3, 3, 4, 2, 4, 2, 2,
3, 5, 4, 3, 3, 2, 5, 3, 5, 1, 5, 3, 5, 1, 3, 3, 3, 3, 3, 5, 3,
5, 5, 2, 5, 2, 5, 3, 5, 3, 3, 5, 4, 3, 3, 4, 3, 3, 4, 3, 2, 3,
4, 3, 2, 3, 5, 5, 3, 4, 4, 3, 5, 3, 2, 3, 2, 5, 3, 3, 5, 3, 3,
3, 2, 5, 5, 4, 4, 5, 4, 1, 3, 3, 3, 4, 3, 3, 3, 3, 3, 2, 4, 3,
3, 3, 4, 4, 3, 3, 3, 4, 3, 1, 2, 3, 3, 5, 4, 3, 4, 2, 2, 3, 4,
2, 2, 1, 4, 3, 5, 3, 3, 3, 3, 3, 3, 3, 5, 3, 3, 4, 5, 2, 3, 5,
4, 3, 4, 4, 4, 3, 3, 3, 5, 2, 3, 3, 5, 5, 4, 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, 0, 4, 4, 4, 4, 4, 2, 6, 4, 0, 4, 0,
    2, 0, 0, 0, 6, 2, 0, 6, 4, 2, 2, 0, 2, 0, 2, 6, 2, 2, 0,
    6, 2, 2, 0, 0, 0, 4, 0, 4, 2, 6, 2, 4, 2, 4, 2, 4, 6, 6,
    6, 4, 0, 0, 0, 4, 6, 2, 6, 6, 2, 2, 0, 0, 2, 2, 6, 2, 2,
    6, 6, 0, 0, 4, 2, 4, 4, 4, 0, 2, 0)), row.names = c(NA, -260L
), class = "data.frame")

alpha <- psych::alpha(data) # alpha$total$raw_alpha = -0.3665156
omega <- psych::omega(data) # omega$alpha = 0.5710576
```

```

答:
Alpha compares the total test variance to the sum of the item variances (* the number of items/number of items -1) .  Total test variance is just the sum of the item variances and covariances.  As you can see from your correlation matrix, you have some negatively correlated items.  This will reduce the total variance to be less than the sum of the item variances.  In your case, the total test variance is 6.197 and the sum of the item variances is 8.015 with k =5 and thus

```<code>alpha = (6.198 - 8.015)/6.198  * 5/4 =  -.366

lowerCor(data)
        rMEQQ01 rMEQQ02 rMEQQ03 rMEQQ04 rMEQQ05
rMEQQ01  1.00
rMEQQ02 -0.26    1.00
rMEQQ03  0.29   -0.02    1.00
rMEQQ04 -0.15    0.09   -0.02    1.00
rMEQQ05 -0.45    0.30   -0.32    0.20    1.00
</code>```

For a better understanding of alpha and the omega statistics, I recommend you read our paper in press at Psychological Assessment: Revelle and Condon, From alpha to Omega, a tutorial (2020) preprint at https://psyarxiv.com/2y3w9/.

Body:
I have data from a five-item measure completed by about 260 participants and estimated internal consistency with the psych library in R. I got a value of -0.36 (I triple-checked for reverse-coded questions). My data doesn't cover a broad range of the possible scores -- due to the nature of the group I am sampling from -- so this is a plausible number. But the scale I'm using is well validated, admittedly with low typical values of alpha ranging from 0.5--0.7.

When looking for alternative methods to assess my data I used psych::omega. This returns an alpha value of 0.57 alongwith the omega statistic I was looking for. This alpha value is much more in keeping with other literature which uses the scale in question. I have also looked at other validated measures from my study and the alpha values from psych::alpha and psych::omega are equal. It is only on this particular measure which is known to have low internal consistency where the difference appears.

My question: why are the alpha values different between psych::alpha and psych::omega?

The code below includes the actual data and will spit a warning about negatively correlated items. I've checked and rechecked my score-coding and it's correct so I am confident we can ignore this warning.

library("psych")

data <- structure(list(rMEQQ01 = c(2, 3, 3, 3, 3, 3, 3, 1, 5, 3, 3, 3,
3, 3, 3, 3, 3, 5, 3, 2, 5, 2, 3, 3, 3, 3, 3, 2, 3, 2, 2, 1, 3,
5, 3, 4, 3, 4, 5, 4, 3, 3, 2, 5, 4, 2, 3, 3, 5, 3, 3, 5, 5, 4,
2, 2, 4, 1, 4, 1, 2, 1, 5, 2, 4, 3, 3, 1, 3, 3, 4, 2, 4, 2, 2,
3, 5, 4, 3, 3, 2, 5, 3, 5, 1, 5, 3, 5, 1, 3, 3, 3, 3, 3, 5, 3,
5, 5, 2, 5, 2, 5, 3, 5, 3, 3, 5, 4, 3, 3, 4, 3, 3, 4, 3, 2, 3,
4, 3, 2, 3, 5, 5, 3, 4, 4, 3, 5, 3, 2, 3, 2, 5, 3, 3, 5, 3, 3,
3, 2, 5, 5, 4, 4, 5, 4, 1, 3, 3, 3, 4, 3, 3, 3, 3, 3, 2, 4, 3,
3, 3, 4, 4, 3, 3, 3, 4, 3, 1, 2, 3, 3, 5, 4, 3, 4, 2, 2, 3, 4,
2, 2, 1, 4, 3, 5, 3, 3, 3, 3, 3, 3, 3, 5, 3, 3, 4, 5, 2, 3, 5,
4, 3, 4, 4, 4, 3, 3, 3, 5, 2, 3, 3, 5, 5, 4, 2, 3, 3, 3, 3, 3,
3, 3, 2, 3, 1, 3, 2, 1, 2, 5, 3, 5, 1, 3, 3, 2, 3, 4, 5, 3, 3,
3, 4, 3, 1, 3, 3, 3, 3, 5, 1, 3, 4, 5, 3, 4, 3, 3), rMEQQ02 = c(2,
2, 2, 1, 2, 1, 2, 3, 2, 2, 3, 2, 1, 1, 2, 1, 2, 1, 2, 3, 4, 2,
1, 1, 3, 2, 3, 2, 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, 2, 4, 4, 4, 0, 2, 0)), row.names = c(NA, -260L
), class = "data.frame")

alpha <- psych::alpha(data) # alpha$total$raw_alpha = -0.3665156
omega <- psych::omega(data) # omega$alpha = 0.5710576
```

Body:
Alpha compares the total test variance to the sum of the item variances (* the number of items/number of items -1) .  Total test variance is just the sum of the item variances and covariances.  As you can see from your correlation matrix, you have some negatively correlated items.  This will reduce the total variance to be less than the sum of the item variances.  In your case, the total test variance is 6.197 and the sum of the item variances is 8.015 with k =5 and thus

alpha = (6.198 - 8.015)/6.198  * 5/4 =  -.366

lowerCor(data)
        rMEQQ01 rMEQQ02 rMEQQ03 rMEQQ04 rMEQQ05
rMEQQ01  1.00
rMEQQ02 -0.26    1.00
rMEQQ03  0.29   -0.02    1.00
rMEQQ04 -0.15    0.09   -0.02    1.00
rMEQQ05 -0.45    0.30   -0.32    0.20    1.00

For a better understanding of alpha and the omega statistics, I recommend you read our paper in press at Psychological Assessment: Revelle and Condon, From alpha to Omega, a tutorial (2020) preprint at https://psyarxiv.com/2y3w9/.


问:
Random Number Generator from input
I'm new to Xcode development, and i would like to know how can i generate random numbers from 2 inputs.

In IB i have 2 textfields (with Number pad) that indicate the interval of the numbers to generate (i.e. from 3 to 7). I would like to know how i get the inputs from the 2 textfields and do a method that generate random numbers from these inputs.

答:
```<code>int low_bound = 3;
int high_bound = 7;
int width = high_bound - low_bound; // 4
int value = low_bound + arc4random() % (width + 1); // 3 + 0..4
</code>```

Plus read the bounds from the fields, something like bound = [[field text] intValue].

If you have trouble connecting the input fields to the code, you should read some Cocoa tutorial. There are several ways to do it, one of the most straightforward is declaring properties for the text fields in the controller class:

```<code>@interface Controller : UIViewController {}
@property(retain) IBOutlet UITextField *lowerBoundField;
@property(retain) IBOutlet UITextField *upperBoundField;
@end
</code>```

Then you can connect the text fields in the Interface Builder to these outlets and work with them in code like this:

```<code>- (void) generateNumber {
    int lowerBound = [[lowerBoundField text] intValue];
    …
}
</code>```

This is assuming we are talking about Cocoa Touch. In desktop Cocoa the situation is similar, just the details would be different.

Title: Random Number Generator from input

Body:
int low_bound = 3;
int high_bound = 7;
int width = high_bound - low_bound; // 4
int value = low_bound + arc4random() % (width + 1); // 3 + 0..4

Plus read the bounds from the fields, something like bound = [[field text] intValue].

If you have trouble connecting the input fields to the code, you should read some Cocoa tutorial. There are several ways to do it, one of the most straightforward is declaring properties for the text fields in the controller class:

@interface Controller : UIViewController {}
@property(retain) IBOutlet UITextField *lowerBoundField;
@property(retain) IBOutlet UITextField *upperBoundField;
@end

Then you can connect the text fields in the Interface Builder to these outlets and work with them in code like this:

- (void) generateNumber {
    int lowerBound = [[lowerBoundField text] intValue];
    …
}

This is assuming we are talking about Cocoa Touch. In desktop Cocoa the situation is similar, just the details would be different.


问:
Using Big Cartel E-commerce / Shop: Require 1 item from specific product category to checkout
I'm creating a Big Cartel shop.

I need customers to add a product from a specific category to there cart to be able to checkout.
In my case this is a delivery time as a product. I have these set up as products in a category called 'time' (there are other categories).
I want something like the following but this doesn't work. It just always shows the button even if there is not time product item in the cart.

The BigCartel syntax and variables can be found here: https://developers.bigcartel.com/api/themes#cart

```<code>{% if cart.items_category.name == time %}
   <button type="submit" name="checkout" class="button checkout-btn">Checkout</button>
{% else %}
    Please add a product from Time to continue
{% endif %}
</code>```

答: Looking at the big cartel API, the reference to cart.items_category is nonexistent.  From what I see you can get the cart items using cart.items which will return all items in the cart. Then you can loop through the returned items using item.product which will return all products associated with the items in your cart, then you can do the product categories using product.categories returning all product categories used in the scope, finally that list of product categories can be compared to see if any match the name time.

Body:
I'm creating a Big Cartel shop.

I need customers to add a product from a specific category to there cart to be able to checkout.
In my case this is a delivery time as a product. I have these set up as products in a category called 'time' (there are other categories).
I want something like the following but this doesn't work. It just always shows the button even if there is not time product item in the cart.

The BigCartel syntax and variables can be found here: https://developers.bigcartel.com/api/themes#cart

{% if cart.items_category.name == time %}
   <button type="submit" name="checkout" class="button checkout-btn">Checkout</button>
{% else %}
    Please add a product from Time to continue
{% endif %}


问:
pandas unique values with condition
I am working with a pandas DataFrame and I need to loop trough the unique values of a column.
Such columns might contain values that i dont want to loop through, for instance ''

normally I do:

```<code>edges = [edge for edge in estados['EDGE'].unique() if edge != '']
for edge in edges:
    pass
</code>```

my question is if there is a more pandonic way to build up the list different than the conprehension list.

like:

```<code>estados['EDGE'].unique().exclude('')
</code>```

THANKS

Note:
I looked for solutions like in:
nunique excluding some values in pandas
Python pandas unique value ignoring NaN
but these solutions are even less concise as mine.

答:
You can use NOT operator ~:

```<code>estados[~estados['EDGE'] == '']['EDGE'].dropna().unique()
</code>```

OR Use .ne:

```<code>estados[estados['EDGE'].ne('')]['EDGE'].dropna().unique()
</code>```

Title: pandas unique values with condition

Body:
I am working with a pandas DataFrame and I need to loop trough the unique values of a column.
Such columns might contain values that i dont want to loop through, for instance ''

normally I do:

edges = [edge for edge in estados['EDGE'].unique() if edge != '']
for edge in edges:
    pass

my question is if there is a more pandonic way to build up the list different than the conprehension list.

like:

estados['EDGE'].unique().exclude('')

THANKS

Note:
I looked for solutions like in:
nunique excluding some values in pandas
Python pandas unique value ignoring NaN
but these solutions are even less concise as mine.

Body:
You can use NOT operator ~:

estados[~estados['EDGE'] == '']['EDGE'].dropna().unique()

OR Use .ne:

estados[estados['EDGE'].ne('')]['EDGE'].dropna().unique()


问:
I need to pass a JSON file to MongoDB using Mongoose
I tried this, but it does not work:
The readFile works well, and it finishes before the connection to the DB had started.
My problem is when trying to use the parsed JSON obj (listingData) into MongoDB using Mongoose.

```<code> let listingData;
 fs.readFile('listings.json', 'utf8', (err, data) => {
   try {
     listingData = JSON.parse(data);
   } catch (err) {
     console.log('Error reading JSON file');
     throw err;
   }
   //console.log(listingData); // PRINTS DATA CORRECTLY!
 });

 async function loadListings() {
   try {
     await Listing.insertMany(listingData); // imported.insertMany(JSON Parsed)
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.log("Error importing listings to DB");
     process.exit();
   }
 }
</code>```

SOLVED, thanks

答:
If you checked fs.readfile, you'd notice that it's an async function.

So loadlistings will NOT wait for readfile to finish.

There are two ways to fix this, a bad way, and a good way.

The bad way is for you to remove async from loadlistings, and turn readfile into readfilesync. This is BAD because it is NOT the node.js way... async as much as possible.

Instead, you should learn how to leverage async properly by incorporating readfile INTO loadlistings as a promise. Which is the solution @Shivam Sood gave you.

Body:
I tried this, but it does not work:
The readFile works well, and it finishes before the connection to the DB had started.
My problem is when trying to use the parsed JSON obj (listingData) into MongoDB using Mongoose.

 let listingData;
 fs.readFile('listings.json', 'utf8', (err, data) => {
   try {
     listingData = JSON.parse(data);
   } catch (err) {
     console.log('Error reading JSON file');
     throw err;
   }
   //console.log(listingData); // PRINTS DATA CORRECTLY!
 });

 async function loadListings() {
   try {
     await Listing.insertMany(listingData); // imported.insertMany(JSON Parsed)
     console.log("Listings inserted in the DB");
     //process.exit();
   } catch (error) {
     console.log("Error importing listings to DB");
     process.exit();
   }
 }

SOLVED, thanks


问:
react-testing-library why is toBeInTheDocument() not a function
Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.

```<code> it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {
    const { queryByTestId, queryByText } = render(
      <Tooltip id="test" message="test" />,
    )
    fireEvent.mouseOver(queryByTestId('tooltip'))
    expect(queryByText('test')).toBeInTheDocument()
    fireEvent.mouseOut(queryByTestId('tooltip'))
    expect(queryByText('test')).not.toBeInTheDocument()
    cleanup()
  })
</code>```

I keep getting the error  TypeError: expect(...).toBeInTheDocument is not a function

Has anyone got any ideas why this is happening? My other tests to render and snapshot the component all work as expected. As do the queryByText and queryByTestId.

答:
Instead of doing:

```<code>    expect(queryByText('test')).toBeInTheDocument()
</code>```

you can find and test that it is in the document with just one line by using

```<code>    let element = getByText('test');
</code>```

The test will fail if the element isn't found with the getBy call.

Body:
Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.

 it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {
    const { queryByTestId, queryByText } = render(
      <Tooltip id="test" message="test" />,
    )
    fireEvent.mouseOver(queryByTestId('tooltip'))
    expect(queryByText('test')).toBeInTheDocument()
    fireEvent.mouseOut(queryByTestId('tooltip'))
    expect(queryByText('test')).not.toBeInTheDocument()
    cleanup()
  })

I keep getting the error  TypeError: expect(...).toBeInTheDocument is not a function

Has anyone got any ideas why this is happening? My other tests to render and snapshot the component all work as expected. As do the queryByText and queryByTestId.

Body:
Instead of doing:

    expect(queryByText('test')).toBeInTheDocument()

you can find and test that it is in the document with just one line by using

    let element = getByText('test');

The test will fail if the element isn't found with the getBy call.


问:
Odd behaviour in PARSEC x264 benchmark
I am running the PARSEC x264 benchmark and it runs fine until the close down when it crashes. Unfortunately the suite seems to be unmaintained or on low maintenance - this problem (the crash, not the specifics) was posted on the mailing list nearly a year ago but no replies.

I have isolated the problem to part of a particular function (see below) using good old fashioned debugging by printf:

```<code>void x264_cqm_delete( x264_t *h )
{
     int i, j;
     printf("IN BAD CODE\n");
     for( i = 0; i < 6; i++ )
     {
         for( j = 0; j < i; j++ )
             if( h->quant4_mf[i] == h->quant4_mf[j] )
                 break;
         if( j == i )
         {
            printf("DELETE CODE with i = %i and j = %i\n", i, j);
            x264_free( h->  quant4_mf[i] );
            x264_free( h->dequant4_mf[i] );
            x264_free( h->unquant4_mf[i] );
        }
        for( j = 0; j < i; j++ )
            if( h->quant4_bias[i] == h->quant4_bias[j] )
                break;
        if( j == i )
            x264_free( h->quant4_bias[i] );
}
</code>```

}

This generates the output...

```<code>IN BAD CODE
DELETE CODE with i = 0 and j = 0
DELETE CODE with i = 4 and j = 4
DELETE CODE with i = 5 and j = 4
</code>```

What is going on?

答:
From examining the canonical code in the x264 library itself it seems clear that the code is broken and the reason I am seeing these issues is that the code is trashing the heap.

In fact the outer loop's limit should be 4 - it should match the number used in the name of the various arrays - that is the pattern used in the x264 library itself - and the quant4_mf array has only 4 elements in the first dimension. Patching the code in this way sees the compiled binary run without issue.

Title: Odd behaviour in PARSEC x264 benchmark

Body:
I am running the PARSEC x264 benchmark and it runs fine until the close down when it crashes. Unfortunately the suite seems to be unmaintained or on low maintenance - this problem (the crash, not the specifics) was posted on the mailing list nearly a year ago but no replies.

I have isolated the problem to part of a particular function (see below) using good old fashioned debugging by printf:

void x264_cqm_delete( x264_t *h )
{
     int i, j;
     printf("IN BAD CODE\n");
     for( i = 0; i < 6; i++ )
     {
         for( j = 0; j quant4_mf[i] == h->quant4_mf[j] )
                 break;
         if( j == i )
         {
            printf("DELETE CODE with i = %i and j = %i\n", i, j);
            x264_free( h->  quant4_mf[i] );
            x264_free( h->dequant4_mf[i] );
            x264_free( h->unquant4_mf[i] );
        }
        for( j = 0; j quant4_bias[i] == h->quant4_bias[j] )
                break;
        if( j == i )
            x264_free( h->quant4_bias[i] );
}

}

This generates the output...

IN BAD CODE
DELETE CODE with i = 0 and j = 0
DELETE CODE with i = 4 and j = 4
DELETE CODE with i = 5 and j = 4

What is going on?


问:
Naming keys in resource files best practice
Does anyone have any recommendations on naming keys in resource files? For instance, do you base the name of your key on the text that needs to be localized or on the control that uses the text?

Say you have an edit button in several screens (one to edit a user, one to edit a group). You could use the following keys:

editUserButton.label=Edit User...

editGroupButton.label=Edit Group...

or

editUser=Edit User...

editGroup=Edit Group...

or

user.edit=Edit User...

group.edit=Edit Group...

What scheme do you prefer and why?

答:
I prefix my literals by usecase or action classname. eg:

```PlaceOrder.invalidId=Invalid id for order {0}
PlaceOrder.success=Your order {0} was successful
PlaceOrder.fail.visa=Your visa was ...
PlaceOrder.fail.communications=We could not...
PlaceOrder.submit=Buy now

Login=Login
Login.fail=Your credentials did not...
Login.alread=You are already logged in```

This way you avoid collisions:

```EditStudent=Edit
EditClass=Edit
EditCourse=Edit Course```

...and can also find what you need easier.

Another way I group is by entity:

```Person.id=#
Person.name=First name
Person.surname=Surname```

These can appear as headers on tables with the entities. It saves you in cases such as this:

```Person.id=#
Class.id=#
Course.id=Course Id```

Lastly by providing context in the property keys you can save yourself from false translations. For example I once had:

```no=no```

which was being used as an id (#) table header on the top left cell, but our french translator did this for French:

```no=non```

... he thought it was the word "no" (negative of yes). :)

Last (but not least) prefixing with classname will help you when you want to refactor/rename classes and quickly update these property keys without having to look at the templates.

OwnerDisplayName: Christophe Herreman

ContentLicense: CC BY-SA 2.5

Body:
I prefix my literals by usecase or action classname. eg:

PlaceOrder.invalidId=Invalid id for order {0}
PlaceOrder.success=Your order {0} was successful
PlaceOrder.fail.visa=Your visa was ...
PlaceOrder.fail.communications=We could not...
PlaceOrder.submit=Buy now

Login=Login
Login.fail=Your credentials did not...
Login.alread=You are already logged in

This way you avoid collisions:

EditStudent=Edit
EditClass=Edit
EditCourse=Edit Course

...and can also find what you need easier.

Another way I group is by entity:

Person.id=#
Person.name=First name
Person.surname=Surname

These can appear as headers on tables with the entities. It saves you in cases such as this:

Person.id=#
Class.id=#
Course.id=Course Id

Lastly by providing context in the property keys you can save yourself from false translations. For example I once had:

no=no

which was being used as an id (#) table header on the top left cell, but our french translator did this for French:

no=non

... he thought it was the word "no" (negative of yes). :)

Last (but not least) prefixing with classname will help you when you want to refactor/rename classes and quickly update these property keys without having to look at the templates.

OwnerDisplayName: cherouvim

LastEditorDisplayName: cherouvim


问:
Limiting PHP's file access according to logged-in user's access permissions
I have a PHP web application (running on Apache/Linux) that, among other things, allows some browsing of local files on the web server. Since Apache is running as a special "www" user, PHP has access to everything that "www" can access, whichever user is logged into the application. </p>

<p>What is the best way to limit the access to files according to the Unix filesystem privileges for the logged-in user? Ideally, I could spawn off a new process with user ID being the logged in user, but I'm not sure if that's possible. Alternatively, is there a standard PHP library somewhere that will do the permission checking and access the files? </p>

答:
You may take a look over http://httpd.apache.org/docs/2.0/suexec.html it should do what you need, without the need to keep a separate lsit of users and permissions in your aplications.

As far as i know, this extension is implemented on some(if not all) shared hosting services to control how resources are divided between users.

This will lead to scripts not getting executed by www-data(but by the system user), and PHP not running as a module(by CGI/fastCGI mechanisms).

Body:
I have a PHP web application (running on Apache/Linux) that, among other things, allows some browsing of local files on the web server. Since Apache is running as a special "www" user, PHP has access to everything that "www" can access, whichever user is logged into the application.

What is the best way to limit the access to files according to the Unix filesystem privileges for the logged-in user? Ideally, I could spawn off a new process with user ID being the logged in user, but I'm not sure if that's possible. Alternatively, is there a standard PHP library somewhere that will do the permission checking and access the files?


问:
"make all -j"$(nproc)" command works within Docker container but not in Dockerfile
I wrote the following Dockerfile to build an image with OpenPose (https://github.com/CMU-Perceptual-Computing-Lab/openpose)

```<code># Download base image
FROM nvidia/cuda:9.0-cudnn7-devel

# Set keyboard configuration in advance of installing CUDA
#RUN apt-get update && apt-get install -yq keyboard-configuration

#==========Caffe dependencies=================
RUN apt-get --assume-yes update && \
    apt-get --assume-yes install build-essential \
                                 libatlas-base-dev \
                                 libprotobuf-dev \
                                 libleveldb-dev \
                                 libsnappy-dev \
                                 libhdf5-serial-dev \
                                 protobuf-compiler

RUN apt-get --assume-yes install --no-install-recommends libboost-all-dev

# Remaining dependencies
RUN apt-get --assume-yes install libgflags-dev \
                                 libgoogle-glog-dev \
                                 liblmdb-dev

#=========OpenCV============
RUN apt-get update && apt-get --assume-yes install libopencv-dev \
                                                   python-opencv \
                                                   python-pip \
                                                   python-dev \
                                                   cmake \
                                                   libeigen3-dev \
                                                   doxygen

#=========Python Libs=======
RUN pip install --upgrade numpy \
                          protobuf \
                          opencv-python

#=========OpenPose==========
RUN apt-get -y install git
RUN git clone --depth 10 https://github.com/CMU-Perceptual-Computing-Lab/openpose.git /opt/openpose
RUN apt-get install -y cmake

# Set environment variables
ENV PATH "/usr/local/cuda-9.0/bin:$PATH"
ENV LD_LIBRARY_PATH "/usr/local/cuda-9.0/lib64:$LD_LIBRARY_PATH"
ENV OPENPOSE_ROOT /opt/openpose

RUN cd /opt/openpose && \
    mkdir -p build && cd build && \
    cmake \
      -DCMAKE_BUILD_TYPE="Release" \
      -DBUILD_EXAMPLES=ON \
      -DBUILD_DOCS=ON \
      -DBUILD_SHARED_LIBS=ON \
      -DDOWNLOAD_BODY_25_MODEL=ON \
      -DDOWNLOAD_BODY_COCO_MODEL=ON \
      -DDOWNLOAD_BODY_MPI_MODEL=ON \
      -DDOWNLOAD_HAND_MODEL=ON \
      -DWITH_3D_RENDERER:BOOL=OFF \
      -DBUILD_PYTHON=ON ../

RUN printenv && cd opt/openpose/build && make all -n -j"$(nproc)"
</code>```

When building the Dockerfile with nvidia-docker build -t openpose_image . I get the following error in the last step:

```<code>Step 14/14 : RUN printenv && cd opt/openpose/build && make all -n -j"$(nproc)"
 ---> Running in 8cbc7a731e6d
LIBRARY_PATH=/usr/local/cuda/lib64/stubs
HOSTNAME=8cbc7a731e6d
LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64
HOME=/root
CUDA_VERSION=9.0.176
NVIDIA_REQUIRE_CUDA=cuda>=9.0
NVIDIA_DRIVER_CAPABILITIES=compute,utility
PATH=/usr/local/cuda-9.0/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
CUDA_PKG_VERSION=9-0=9.0.176-1
CUDNN_VERSION=7.4.1.5
PWD=/
NVIDIA_VISIBLE_DEVICES=all
NCCL_VERSION=2.3.7
OPENPOSE_ROOT=/opt/openpose
/usr/bin/cmake -H/opt/openpose -B/opt/openpose/build --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /opt/openpose/build/CMakeFiles /opt/openpose/build/CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make -f CMakeFiles/doc_doxygen.dir/build.make CMakeFiles/doc_doxygen.dir/depend
make -f CMakeFiles/openpose_caffe.dir/build.make CMakeFiles/openpose_caffe.dir/depend
cd /opt/openpose/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /opt/openpose /opt/openpose /opt/openpose/build /opt/openpose/build /opt/openpose/build/CMakeFiles/doc_doxygen.dir/DependInfo.cmake --color=
make -f CMakeFiles/doc_doxygen.dir/build.make CMakeFiles/doc_doxygen.dir/build
cd /opt/openpose/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /opt/openpose /opt/openpose /opt/openpose/build /opt/openpose/build /opt/openpose/build/CMakeFiles/openpose_caffe.dir/DependInfo.cmake --color=
make -f CMakeFiles/openpose_caffe.dir/build.make CMakeFiles/openpose_caffe.dir/build
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=1 "Generating API documentation with Doxygen"
cd /opt/openpose/doc && /usr/bin/doxygen /opt/openpose/doc/doc_autogeneration.doxygen
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=4 "Creating directories for 'openpose_caffe'"
/usr/bin/cmake -E make_directory /opt/openpose/3rdparty/caffe
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/src/openpose_caffe-build
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/tmp
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/src/openpose_caffe-stamp
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/src
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-mkdir
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=5 "No download step for 'openpose_caffe'"
/usr/bin/cmake -E echo_append
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-download
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=7 "No patch step for 'openpose_caffe'"
/usr/bin/cmake -E echo_append
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-patch
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=6 "No update step for 'openpose_caffe'"
/usr/bin/cmake -E echo_append
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-update
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=8 "Performing configure step for 'openpose_caffe'"
cd /opt/openpose/build/caffe/src/openpose_caffe-build && /usr/bin/cmake -DCMAKE_INSTALL_PREFIX:PATH=/opt/openpose/build/caffe -DUSE_CUDNN=ON -DCUDA_ARCH_NAME=Auto -DCPU_ONLY=OFF -DCMAKE_BUILD_TYPE=Release -DBUILD_docs=OFF -DBUILD_python=OFF -DBUILD_python_layer=OFF -DUSE_LEVELDB=OFF -DUSE_LMDB=OFF -DUSE_OPENCV=OFF "-GUnix Makefiles" /opt/openpose/3rdparty/caffe
cd /opt/openpose/build/caffe/src/openpose_caffe-build && /usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-configure
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=9 "Performing build step for 'openpose_caffe'"
cd /opt/openpose/build/caffe/src/openpose_caffe-build && make
/usr/bin/cmake -E cmake_echo_color --switch= --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=1 "Built target doc_doxygen"
make[3]: *** No targets specified and no makefile found.  Stop.
CMakeFiles/openpose_caffe.dir/build.make:110: recipe for target 'caffe/src/openpose_caffe-stamp/openpose_caffe-build' failed
make[2]: *** [caffe/src/openpose_caffe-stamp/openpose_caffe-build] Error 2
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/openpose_caffe.dir/all' failed
make[1]: *** [CMakeFiles/openpose_caffe.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
The command '/bin/sh -c printenv && cd opt/openpose/build && make all -n -j"$(nproc)"' returned a non-zero code: 2
</code>```

Two weird things also happen here. 1) If I run the image built so far with docker run -it openpose_image and then cd opt/openpose/build && make all -j"$(nproc)" I get the same exact error. 2) If I do instead nvidia-docker run -it openpose_image and then cd opt/openpose/build && make all -j"$(nproc)" the building runs smoothly, ending successfully without raising errors. Can somebody help me to figure out what is going on? Thanks

答: I assume that's because shell expansion doesn't happen with the RUN statements.  I just tried using backticks instead (i.e. make -j`nproc`) and it appeared to work

Body:
I wrote the following Dockerfile to build an image with OpenPose (https://github.com/CMU-Perceptual-Computing-Lab/openpose)

# Download base image
FROM nvidia/cuda:9.0-cudnn7-devel

# Set keyboard configuration in advance of installing CUDA
#RUN apt-get update && apt-get install -yq keyboard-configuration

#==========Caffe dependencies=================
RUN apt-get --assume-yes update && \
    apt-get --assume-yes install build-essential \
                                 libatlas-base-dev \
                                 libprotobuf-dev \
                                 libleveldb-dev \
                                 libsnappy-dev \
                                 libhdf5-serial-dev \
                                 protobuf-compiler

RUN apt-get --assume-yes install --no-install-recommends libboost-all-dev

# Remaining dependencies
RUN apt-get --assume-yes install libgflags-dev \
                                 libgoogle-glog-dev \
                                 liblmdb-dev

#=========OpenCV============
RUN apt-get update && apt-get --assume-yes install libopencv-dev \
                                                   python-opencv \
                                                   python-pip \
                                                   python-dev \
                                                   cmake \
                                                   libeigen3-dev \
                                                   doxygen

#=========Python Libs=======
RUN pip install --upgrade numpy \
                          protobuf \
                          opencv-python

#=========OpenPose==========
RUN apt-get -y install git
RUN git clone --depth 10 https://github.com/CMU-Perceptual-Computing-Lab/openpose.git /opt/openpose
RUN apt-get install -y cmake

# Set environment variables
ENV PATH "/usr/local/cuda-9.0/bin:$PATH"
ENV LD_LIBRARY_PATH "/usr/local/cuda-9.0/lib64:$LD_LIBRARY_PATH"
ENV OPENPOSE_ROOT /opt/openpose

RUN cd /opt/openpose && \
    mkdir -p build && cd build && \
    cmake \
      -DCMAKE_BUILD_TYPE="Release" \
      -DBUILD_EXAMPLES=ON \
      -DBUILD_DOCS=ON \
      -DBUILD_SHARED_LIBS=ON \
      -DDOWNLOAD_BODY_25_MODEL=ON \
      -DDOWNLOAD_BODY_COCO_MODEL=ON \
      -DDOWNLOAD_BODY_MPI_MODEL=ON \
      -DDOWNLOAD_HAND_MODEL=ON \
      -DWITH_3D_RENDERER:BOOL=OFF \
      -DBUILD_PYTHON=ON ../

RUN printenv && cd opt/openpose/build && make all -n -j"$(nproc)"

When building the Dockerfile with nvidia-docker build -t openpose_image . I get the following error in the last step:

Step 14/14 : RUN printenv && cd opt/openpose/build && make all -n -j"$(nproc)"
 ---> Running in 8cbc7a731e6d
LIBRARY_PATH=/usr/local/cuda/lib64/stubs
HOSTNAME=8cbc7a731e6d
LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64:/usr/local/nvidia/lib:/usr/local/nvidia/lib64
HOME=/root
CUDA_VERSION=9.0.176
NVIDIA_REQUIRE_CUDA=cuda>=9.0
NVIDIA_DRIVER_CAPABILITIES=compute,utility
PATH=/usr/local/cuda-9.0/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
CUDA_PKG_VERSION=9-0=9.0.176-1
CUDNN_VERSION=7.4.1.5
PWD=/
NVIDIA_VISIBLE_DEVICES=all
NCCL_VERSION=2.3.7
OPENPOSE_ROOT=/opt/openpose
/usr/bin/cmake -H/opt/openpose -B/opt/openpose/build --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /opt/openpose/build/CMakeFiles /opt/openpose/build/CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make -f CMakeFiles/doc_doxygen.dir/build.make CMakeFiles/doc_doxygen.dir/depend
make -f CMakeFiles/openpose_caffe.dir/build.make CMakeFiles/openpose_caffe.dir/depend
cd /opt/openpose/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /opt/openpose /opt/openpose /opt/openpose/build /opt/openpose/build /opt/openpose/build/CMakeFiles/doc_doxygen.dir/DependInfo.cmake --color=
make -f CMakeFiles/doc_doxygen.dir/build.make CMakeFiles/doc_doxygen.dir/build
cd /opt/openpose/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /opt/openpose /opt/openpose /opt/openpose/build /opt/openpose/build /opt/openpose/build/CMakeFiles/openpose_caffe.dir/DependInfo.cmake --color=
make -f CMakeFiles/openpose_caffe.dir/build.make CMakeFiles/openpose_caffe.dir/build
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=1 "Generating API documentation with Doxygen"
cd /opt/openpose/doc && /usr/bin/doxygen /opt/openpose/doc/doc_autogeneration.doxygen
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=4 "Creating directories for 'openpose_caffe'"
/usr/bin/cmake -E make_directory /opt/openpose/3rdparty/caffe
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/src/openpose_caffe-build
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/tmp
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/src/openpose_caffe-stamp
/usr/bin/cmake -E make_directory /opt/openpose/build/caffe/src
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-mkdir
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=5 "No download step for 'openpose_caffe'"
/usr/bin/cmake -E echo_append
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-download
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=7 "No patch step for 'openpose_caffe'"
/usr/bin/cmake -E echo_append
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-patch
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=6 "No update step for 'openpose_caffe'"
/usr/bin/cmake -E echo_append
/usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-update
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=8 "Performing configure step for 'openpose_caffe'"
cd /opt/openpose/build/caffe/src/openpose_caffe-build && /usr/bin/cmake -DCMAKE_INSTALL_PREFIX:PATH=/opt/openpose/build/caffe -DUSE_CUDNN=ON -DCUDA_ARCH_NAME=Auto -DCPU_ONLY=OFF -DCMAKE_BUILD_TYPE=Release -DBUILD_docs=OFF -DBUILD_python=OFF -DBUILD_python_layer=OFF -DUSE_LEVELDB=OFF -DUSE_LMDB=OFF -DUSE_OPENCV=OFF "-GUnix Makefiles" /opt/openpose/3rdparty/caffe
cd /opt/openpose/build/caffe/src/openpose_caffe-build && /usr/bin/cmake -E touch /opt/openpose/build/caffe/src/openpose_caffe-stamp/openpose_caffe-configure
/usr/bin/cmake -E cmake_echo_color --switch= --blue --bold --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=9 "Performing build step for 'openpose_caffe'"
cd /opt/openpose/build/caffe/src/openpose_caffe-build && make
/usr/bin/cmake -E cmake_echo_color --switch= --progress-dir=/opt/openpose/build/CMakeFiles --progress-num=1 "Built target doc_doxygen"
make[3]: *** No targets specified and no makefile found.  Stop.
CMakeFiles/openpose_caffe.dir/build.make:110: recipe for target 'caffe/src/openpose_caffe-stamp/openpose_caffe-build' failed
make[2]: *** [caffe/src/openpose_caffe-stamp/openpose_caffe-build] Error 2
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/openpose_caffe.dir/all' failed
make[1]: *** [CMakeFiles/openpose_caffe.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
The command '/bin/sh -c printenv && cd opt/openpose/build && make all -n -j"$(nproc)"' returned a non-zero code: 2

Two weird things also happen here. 1) If I run the image built so far with docker run -it openpose_image and then cd opt/openpose/build && make all -j"$(nproc)" I get the same exact error. 2) If I do instead nvidia-docker run -it openpose_image and then cd opt/openpose/build && make all -j"$(nproc)" the building runs smoothly, ending successfully without raising errors. Can somebody help me to figure out what is going on? Thanks


问:
New lines in Jasper Reports?
I've just started using Jasper Reports to generate reports from data retrieved using Hibernate. Everything is working, except JR doesn't seem to respect newline characters (\n) in text fields. Is there a way to force line breaks at newline characters?</p>

答: Set the markup as html then add a

Title: New lines in Jasper Reports?

Body: Set the markup as html then add a <br/>


问:
Collection of Types rather than Instances
I have a list of viewmodels that currently instantiates all the viewmodels at the start:

private ObservableCollection<ViewModelWithTemplate> StepViewModels
{
    get
    {
        if (_stepViewModels == null)
            _stepViewModels = new ObservableCollection<ViewModelWithTemplate>
        {
            new AddRemoveCellsViewModel(TemplateRows),
            new ActivateDeactivateCellsViewModel(TemplateRows),
            new RotateCellsViewModel(TemplateRows),
            new SetAcquisitionOrderViewModel(TemplateRows),
            new NameTemplateViewModel(TemplateRows)
        };
        return _stepViewModels;
    }
}

public ViewModelWithTemplate CurrentStepViewModel => StepViewModels[StepIndex];
```

<p>The problem is that the VMs are created all at once, but I want them to be only created when needed, mainly so that they have the most recent edition of <code>TemplateRows</code>. </p>

<p>How can I do this? My first thought is to have the collection be a list of <em>types</em> so that I can instantiate each viewmodel when I arrive at it, like this:</p>

<pre class="lang-cs prettyprint-override"><code>public ViewModelWithTemplate CurrentStepViewModel => new StepViewModels[StepIndex](TemplateRows);
</code>```

But a little Googling around makes me think the answer is more toward inversion of control, and/or a VM factory. I'm having trouble finding actual helpful information that's not tied to some framework. (Prism, etc)

答:
You can use Func delegates (assuming StepIndex is of type int and TemplateRows is of type TemplateRowsType):

```<code>// this can be moved to static prop:
var stepViewModelsCtorDict = new Dictionary<int, Func<TemplateRowsType, ViewModelWithTemplate>>
{
   {0, trows => new AddRemoveCellsViewModel(trows) },
   {1, trows => new ActivateDeactivateCellsViewModel(trows) },
....
};

var result = stepViewModelsCtorDict[StepIndex](TemplateRows);
</code>```

Body:
I have a list of viewmodels that currently instantiates all the viewmodels at the start:

private ObservableCollection<ViewModelWithTemplate> StepViewModels
{
    get
    {
        if (_stepViewModels == null)
            _stepViewModels = new ObservableCollection<ViewModelWithTemplate>
        {
            new AddRemoveCellsViewModel(TemplateRows),
            new ActivateDeactivateCellsViewModel(TemplateRows),
            new RotateCellsViewModel(TemplateRows),
            new SetAcquisitionOrderViewModel(TemplateRows),
            new NameTemplateViewModel(TemplateRows)
        };
        return _stepViewModels;
    }
}

public ViewModelWithTemplate CurrentStepViewModel => StepViewModels[StepIndex];

The problem is that the VMs are created all at once, but I want them to be only created when needed, mainly so that they have the most recent edition of TemplateRows.

How can I do this? My first thought is to have the collection be a list of types so that I can instantiate each viewmodel when I arrive at it, like this:

public ViewModelWithTemplate CurrentStepViewModel => new StepViewModels[StepIndex](TemplateRows);

But a little Googling around makes me think the answer is more toward inversion of control, and/or a VM factory. I'm having trouble finding actual helpful information that's not tied to some framework. (Prism, etc)

Body:
You can use Func delegates (assuming StepIndex is of type int and TemplateRows is of type TemplateRowsType):

// this can be moved to static prop:
var stepViewModelsCtorDict = new Dictionary<int, Func<TemplateRowsType, ViewModelWithTemplate>>
{
   {0, trows => new AddRemoveCellsViewModel(trows) },
   {1, trows => new ActivateDeactivateCellsViewModel(trows) },
....
};

var result = stepViewModelsCtorDict[StepIndex](TemplateRows);


问:
executing a none php file from a php file showing error: word unexpected
I am trying to use php exec() function to execute a python file. When i try something like this:

echo exec("python app.py");

It works but if i omit the python string and keep it like this:

echo exec("app.py"),

it gives this error: Syntax error: word unexpected (expecting ")")" which also shows up even if i change from python to another language other than php like JavaScript

app.py only contains one code line: print("Hello World").

What am i doing wrong please as this is my first time using the exec() function.

答:
app.py should include a Shebang so it will look like this:

#!/usr/bin/python
print("Hello World")
```

echo exec("./app.py")

Hope this works and helps!

~ PanTrakX

Body:
app.py should include a Shebang so it will look like this:

#!/usr/bin/python
print("Hello World")

echo exec("./app.py")

Hope this works and helps!

~ PanTrakX