问:
firstname and lastname not showing in django form
i'm trying to create a registration form with following information (firstname, lastname, email, password, password_confirm), however i do not get firstname and lastname. so far i only get username, password and password confirmation. what am i doing wrong in order to add the missing fields?

forms.py

```<code>class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, label='Fornavn', help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, label='Efternavn', help_text='Optional.')
    email = forms.EmailField(max_length=254, label='Email', help_text='Required. Inform a valid email address.')

class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email')
</code>```

register.html

```<code>{% for field in form %}
<div class="form-group">
     <label>{{ field.label }}</label>
     {% render_field field class="form-control" placeholder=field.help_text %}
</div>
{% endfor %}
</code>```

views.py

```<code>def register(request):
    if request.user.is_authenticated():
        return redirect('/account/')
    context = {}
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/account/')
    else:
        form = UserCreationForm()
    return render(request, 'register.html', {'form': form})
</code>```

urls

```<code>urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^register/$', views.register, name='register')

]
</code>```

答:
You're passing UserCreationForm instead of SignUpForm for your GET (and other) requests:

```<code>if request.method == "POST":
    ...
else:
    form = SignUpForm()
</code>```

Body:
i'm trying to create a registration form with following information (firstname, lastname, email, password, password_confirm), however i do not get firstname and lastname. so far i only get username, password and password confirmation. what am i doing wrong in order to add the missing fields?

forms.py

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, label='Fornavn', help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, label='Efternavn', help_text='Optional.')
    email = forms.EmailField(max_length=254, label='Email', help_text='Required. Inform a valid email address.')

class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email')

register.html

{% for field in form %}

     {{ field.label }}
     {% render_field field class="form-control" placeholder=field.help_text %}

{% endfor %}

views.py

def register(request):
    if request.user.is_authenticated():
        return redirect('/account/')
    context = {}
    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('/account/')
    else:
        form = UserCreationForm()
    return render(request, 'register.html', {'form': form})

urls

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^register/$', views.register, name='register')

]

Body:
You're passing UserCreationForm instead of SignUpForm for your GET (and other) requests:

if request.method == "POST":
    ...
else:
    form = SignUpForm()


来源: stackexchange

问:
Select and Join from SQL table (Select statement + Hibernate code)
I have the following two tables:

"STUDENT" and "SKILL" tables

```<code>STUDENT table
"id"         "name"
1             Peter
2              David
3             Mark

SKILL table
"id"    "id_student"    "skill"     "skill value"
1            1            height              180
2            1            weight              75
3            2            height              170
4            3            height              180
</code>```

I would like to select "every student who have 180 as height, 75 as weight and "Peter" as a name".

The main thing that I need is the SQL statement but it would be very helpful as well if someone could tell me how to do this using Java + Hibernate (I mean how to create the Criteria object)

Many thanks for your help.

答:
Without giving the whole game away, does this help?

```<code>DROP TABLE IF EXISTS student;

CREATE TABLE student
(id INT NOT NULL aUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
);

INSERT INTO student VALUES
(1,'Peter'),
(2,'David'),
(3,'Mark'),
(4,'Peter'),
(5,'Brian');

DROP TABLE IF EXISTS student_skill;

CREATE TABLE student_skill
(id_student INT NOT NULL
,skill VARCHAR(20) NOT NULL
,value INT NOT NULL
,PRIMARY KEY(id_student,skill)
);

INSERT INTO student_skill VALUES
(1,'height',180),
(1,'weight',75),
(2,'height',170),
(3,'height',180),
(4,'height',170),
(4,'weight',75),
(5,'height',180),
(5,'weight',75);
</code>```

Query 1.

```<code>SELECT x.*
     , y.height
     , y.weight
  FROM student x
  JOIN
     ( SELECT id_student
            , MAX(CASE WHEN skill = 'height' THEN value END) height
            , MAX(CASE WHEN skill = 'weight' THEN value END) weight
         FROM student_skill
        GROUP
           BY id_student
     ) y
    ON y.id_student = x.id;
+----+-------+--------+--------+
| id | name  | height | weight |
+----+-------+--------+--------+
|  1 | Peter |    180 |     75 |
|  2 | David |    170 |   NULL |
|  3 | Mark  |    180 |   NULL |
|  4 | Peter |    170 |     75 |
|  5 | Brian |    180 |     75 |
+----+-------+--------+--------+
</code>```

...or alternatively, Query 2.

```<code>SELECT s.*
     , h.value height
     , w.value weight
  FROM student s
  LEFT
  JOIN student_skill h
    ON h.id_student = s.id
   AND h.skill = 'height'
  LEFT
  JOIN student_skill w
    ON w.id_student = s.id
   AND w.skill = 'weight';

+----+-------+--------+--------+
| id | name  | height | weight |
+----+-------+--------+--------+
|  1 | Peter |    180 |     75 |
|  2 | David |    170 |   NULL |
|  3 | Mark  |    180 |   NULL |
|  4 | Peter |    170 |     75 |
|  5 | Brian |    180 |     75 |
+----+-------+--------+--------+
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following two tables:

"STUDENT" and "SKILL" tables

STUDENT table
"id"         "name"
1             Peter
2              David
3             Mark

SKILL table
"id"    "id_student"    "skill"     "skill value"
1            1            height              180
2            1            weight              75
3            2            height              170
4            3            height              180

I would like to select "every student who have 180 as height, 75 as weight and "Peter" as a name".

The main thing that I need is the SQL statement but it would be very helpful as well if someone could tell me how to do this using Java + Hibernate (I mean how to create the Criteria object)

Many thanks for your help.

Body:
Without giving the whole game away, does this help?

DROP TABLE IF EXISTS student;

CREATE TABLE student
(id INT NOT NULL aUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
);

INSERT INTO student VALUES
(1,'Peter'),
(2,'David'),
(3,'Mark'),
(4,'Peter'),
(5,'Brian');

DROP TABLE IF EXISTS student_skill;

CREATE TABLE student_skill
(id_student INT NOT NULL
,skill VARCHAR(20) NOT NULL
,value INT NOT NULL
,PRIMARY KEY(id_student,skill)
);

INSERT INTO student_skill VALUES
(1,'height',180),
(1,'weight',75),
(2,'height',170),
(3,'height',180),
(4,'height',170),
(4,'weight',75),
(5,'height',180),
(5,'weight',75);

Query 1.

SELECT x.*
     , y.height
     , y.weight
  FROM student x
  JOIN
     ( SELECT id_student
            , MAX(CASE WHEN skill = 'height' THEN value END) height
            , MAX(CASE WHEN skill = 'weight' THEN value END) weight
         FROM student_skill
        GROUP
           BY id_student
     ) y
    ON y.id_student = x.id;
+----+-------+--------+--------+
| id | name  | height | weight |
+----+-------+--------+--------+
|  1 | Peter |    180 |     75 |
|  2 | David |    170 |   NULL |
|  3 | Mark  |    180 |   NULL |
|  4 | Peter |    170 |     75 |
|  5 | Brian |    180 |     75 |
+----+-------+--------+--------+

...or alternatively, Query 2.

SELECT s.*
     , h.value height
     , w.value weight
  FROM student s
  LEFT
  JOIN student_skill h
    ON h.id_student = s.id
   AND h.skill = 'height'
  LEFT
  JOIN student_skill w
    ON w.id_student = s.id
   AND w.skill = 'weight';

+----+-------+--------+--------+
| id | name  | height | weight |
+----+-------+--------+--------+
|  1 | Peter |    180 |     75 |
|  2 | David |    170 |   NULL |
|  3 | Mark  |    180 |   NULL |
|  4 | Peter |    170 |     75 |
|  5 | Brian |    180 |     75 |
+----+-------+--------+--------+


问:
How would I implement the search function to find a file or directory
I am currently working on a script for bash that will ask the user for a starting location and a file name then search for the file. If possible I would also like to cat the file once found. Here is the script I have so far if someone would point out how I would include the function I would be very thankful. Also still a Unix beginner so please bear with me :)</p>

```<code>#!/bin/bash
function press_enter
{
    echo""
    echo -n "Press Enter to continue"
    read
    clear
}
selction=
until [ "$selection" = "3" ]; do
echo -e "Where would you like to search
1- Root
2- Home
3- Exit

Enter your choice ---> \c"
read selection
case $selection in
    1) cd / ; press_enter ;;
    2) cd /home ; press_enter ;;
    3) echo "Have a nice day!" ; exit ;;
esac
done
</code>```

答:
You can use find as one command, or use your selection inputs to drive find in your script.

```<code>find $where_selection -name $what_selection
# with cat:
find $where_selection -name $what_selection -exec cat {} \;
</code>```

-exec cat {} replaces the {} with the current found file path from find.

Body:
I am currently working on a script for bash that will ask the user for a starting location and a file name then search for the file. If possible I would also like to cat the file once found. Here is the script I have so far if someone would point out how I would include the function I would be very thankful. Also still a Unix beginner so please bear with me :)

#!/bin/bash
function press_enter
{
    echo""
    echo -n "Press Enter to continue"
    read
    clear
}
selction=
until [ "$selection" = "3" ]; do
echo -e "Where would you like to search
1- Root
2- Home
3- Exit

Enter your choice ---> \c"
read selection
case $selection in
    1) cd / ; press_enter ;;
    2) cd /home ; press_enter ;;
    3) echo "Have a nice day!" ; exit ;;
esac
done

Body:
You can use find as one command, or use your selection inputs to drive find in your script.

find $where_selection -name $what_selection
# with cat:
find $where_selection -name $what_selection -exec cat {} \;

-exec cat {} replaces the {} with the current found file path from find.


问:
unable to see sqlite file on the SD card
my problem is the following:
I have correctly moved the SQlite database on the local SD, but the file is not visible both from the device and the PC via USB connection.
The app does not raise any error.
Here is the method that performs the copy:
private void exportDB(){</p>

```<code>    DBHelper db = DBHelper.getInstance(this);
    String DBName = db.getDBName();
    File dbPath = this.getDatabasePath(DBName);
    String DBPath = dbPath.getAbsolutePath();
    //Toast.makeText(this, "DB Path : " + DBPath , Toast.LENGTH_LONG).show();

    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = DBPath;
    String backupDBPath = "Download/"+DBName;
    File currentDB = new File(currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();

        destination.close();
        Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
    } catch(FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e) {
        e.printStackTrace();
    }

}
</code>```

答: for transferting DB, I think it may achievable in rooted device.</p>

Body:
my problem is the following:
I have correctly moved the SQlite database on the local SD, but the file is not visible both from the device and the PC via USB connection.
The app does not raise any error.
Here is the method that performs the copy:
private void exportDB(){

    DBHelper db = DBHelper.getInstance(this);
    String DBName = db.getDBName();
    File dbPath = this.getDatabasePath(DBName);
    String DBPath = dbPath.getAbsolutePath();
    //Toast.makeText(this, "DB Path : " + DBPath , Toast.LENGTH_LONG).show();

    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = DBPath;
    String backupDBPath = "Download/"+DBName;
    File currentDB = new File(currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();

        destination.close();
        Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
    } catch(FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e) {
        e.printStackTrace();
    }

}


问:
Merge two XSLT into one to process the same nodes for two different reasons
I want to remove all namespaces (including all xmlns & xsi from attributes) and then want to sort the output.

Sample XML

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="https://www.w3schools.com/furniture" xmlns='http://ns.xyz.org/2004-08-02'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:ns1='http://ns.xyz.org/2004-08-02'
xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:type='ns1:table'>

    <h:table>
        <h:tr>
            <!-- <TestComment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/> -->
            <h:td att2="2" att1="1">Bananas</h:td>
            <h:td xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">Apples</h:td>
        </h:tr>
    </h:table>

    <f:table>
        <f:name class="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">African Coffee Table</f:name>
        <f:width>80</f:width>
        <f:length>120</f:length>
    </f:table>
</root>
</code>```

Right now I am transforming the xml in two different xsls.

XSL to remove namespaces (including xmlns & xsi) is

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@xsi:*" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<xsl:template match="comment()|processing-instruction()"/>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>
</code>```

This gives me the following output

```<code><root>
    <table>
        <tr>
            <td att2="2" att1="1">Bananas</td>
            <td>Apples</td>
        </tr>
    </table>
    <table>
        <name class="1">African Coffee Table</name>
        <width>80</width>
        <length>120</length>
    </table>
</root>
</code>```

And then I use the below xsl to sort the xml

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*">
                <xsl:sort select="local-name()"/>
            </xsl:apply-templates>
            <xsl:apply-templates select="node()">
                <xsl:sort select="local-name()"/>
                <xsl:sort select="."/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

This gives me the final output as

```<code><root>
    <table>
        <length>120</length>
        <name class="1">African Coffee Table</name>
        <width>80</width>
    </table>
    <table>
        <tr>
            <td>Apples</td>
            <td att1="1" att2="2">Bananas</td>
        </tr>
    </table>
</root>
</code>```

Now, how do I merge these two processing into one xsl file so that I don't have to transform twice?

答:
Move the two xsl:sort into the namespace removing templates:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@xsi:*" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<xsl:template match="comment()|processing-instruction()"/>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*">
            <xsl:sort select="local-name()"/>
        </xsl:apply-templates>
        <xsl:apply-templates>
          <xsl:sort select="local-name()"/>
          <xsl:sort select="."/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>
</code>```

http://xsltransform.hikmatu.com/jyyiVhg

Or use two modes to separate processing steps and perform the first step in a variable, then use exsl:node-set to process it with the second step/mode.

Body:
I want to remove all namespaces (including all xmlns & xsi from attributes) and then want to sort the output.

Sample XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="https://www.w3schools.com/furniture" xmlns='http://ns.xyz.org/2004-08-02'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:ns1='http://ns.xyz.org/2004-08-02'
xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:type='ns1:table'>

    <h:table>
        <h:tr>

            <h:td att2="2" att1="1">Bananas</h:td>
            <h:td xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">Apples</h:td>
        </h:tr>
    </h:table>

    <f:table>
        <f:name class="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true">African Coffee Table</f:name>
        <f:width>80</f:width>
        <f:length>120</f:length>
    </f:table>
</root>

Right now I am transforming the xml in two different xsls.

XSL to remove namespaces (including xmlns & xsi) is

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@xsi:*" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<xsl:template match="comment()|processing-instruction()"/>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

This gives me the following output

<root>

            Bananas
            Apples

        <name class="1">African Coffee Table</name>
        <width>80</width>
        <length>120</length>

</root>

And then I use the below xsl to sort the xml

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*">
                <xsl:sort select="local-name()"/>
            </xsl:apply-templates>
            <xsl:apply-templates select="node()">
                <xsl:sort select="local-name()"/>
                <xsl:sort select="."/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

This gives me the final output as

<root>

        <length>120</length>
        <name class="1">African Coffee Table</name>
        <width>80</width>

            Apples
            Bananas

</root>

Now, how do I merge these two processing into one xsl file so that I don't have to transform twice?

Body:
Move the two xsl:sort into the namespace removing templates:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="utf-8" method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@xsi:*" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<xsl:template match="comment()|processing-instruction()"/>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*">
            <xsl:sort select="local-name()"/>
        </xsl:apply-templates>
        <xsl:apply-templates>
          <xsl:sort select="local-name()"/>
          <xsl:sort select="."/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
        <xsl:value-of select="."/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

http://xsltransform.hikmatu.com/jyyiVhg

Or use two modes to separate processing steps and perform the first step in a variable, then use exsl:node-set to process it with the second step/mode.


问:
Apply a vector-valued function to a vector. Result not as expected
In Matloff's The Art of R programming, he uses the function below (z12) to demonstrate the use of a vector-valued function.

My question is: When applying the function to 1:8, why does it return 1 2 3 4 ... 1 4 9 16 ... and not 1, 1, 2, 4, 3, 9 ...? After all, isn't z^2 right next to z in the return statement?

Body:
We can change the function to

z12 <- function(z) c(rbind(z, z^2))
z12(x)
#[1]  1  1  2  4  3  9  4 16  5 25  6 36  7 49  8 64


问:
Cox Hazard in function R
I have problem with reference to the variable in R.

Look for my easy function:

```<code> CoxStep <- function(dataset,a,b){
 m1 = coxph(Surv(b,a)~.-dataset[,b]-dataset[,a] ,data=dataset)
  summary(m1)
  }
</code>```

I call the function as follow:

CoxStep(data, Alive1, FU_3M)

where FU_3M is a column of time
Alive1 is a column of event
and data is my dataset which contain variables below and other variables.

Function does not see this Alive1 and FU_3M.

Could you help me? Any proposition?

答:
The easy fix is to have your function take a formula as argument:

```<code>CoxStep <- function(dataset, form){
 m1 = coxph(form, data=dataset)
  summary(m1)
  }
</code>```

and then call it with CoxStep(dataset, Surv(a, b) ~ . - a - b).

You could build a helper function if you want for that formula:

```<code>my_form = function(a, b) {
    as.formula(sprintf('Surv(%1$s, %2$s) ~ . - %1$s - %2$s', a, b)
}
</code>```

my_form can be called with strings, e.g., my_form('a', 'b'), so you could put it all together with CoxStep(dataset, my_form('a', 'b')).

Title: Cox Hazard in function R

Body:
I have problem with reference to the variable in R.

Look for my easy function:

 CoxStep <- function(dataset,a,b){
 m1 = coxph(Surv(b,a)~.-dataset[,b]-dataset[,a] ,data=dataset)
  summary(m1)
  }

I call the function as follow:

CoxStep(data, Alive1, FU_3M)

where FU_3M is a column of time
Alive1 is a column of event
and data is my dataset which contain variables below and other variables.

Function does not see this Alive1 and FU_3M.

Could you help me? Any proposition?

Body:
The easy fix is to have your function take a formula as argument:

CoxStep <- function(dataset, form){
 m1 = coxph(form, data=dataset)
  summary(m1)
  }

and then call it with CoxStep(dataset, Surv(a, b) ~ . - a - b).

You could build a helper function if you want for that formula:

my_form = function(a, b) {
    as.formula(sprintf('Surv(%1$s, %2$s) ~ . - %1$s - %2$s', a, b)
}

my_form can be called with strings, e.g., my_form('a', 'b'), so you could put it all together with CoxStep(dataset, my_form('a', 'b')).


问:
Polymer 2: Handle clicks on PaperCard header
I have a custom element that contains a <paper-card> element. I want to listen for clicks on the header of that element, i.e. the
 element.

My current solution looks like this

```<code><paper-card heading="[[title]]" on-tap="onCardClick">
    ...
</paper-card>

onCardClick(e){
    if( e.path[0].classList.contains('header') || e.path[0].classList.contains('title-text') ){
        // Header was clicked
    }
}
</code>```

but it feels hacky.

Is there a better way of doing this?

答:
I would suggest separating the header element like

```<code><paper-card>
  <div class="header" on-click="onCardClick">
    <div class="title-text">[[title]]</div>
  </div>
</paper-card>
</code>```

with the original CSS:

```<code>.header {
  position: relative;
  border-top-left-radius: inherit;
  border-top-right-radius: inherit;
  overflow: hidden;
}

.title-text {
  padding: 16px;
  font-size: 24px;
  font-weight: 400;
  color: var(--paper-card-header-color, #000);
}
</code>```

It has exactly the same effect as you use the heading attribute but is more flexible.

Body:
I have a custom element that contains a <paper-card> element. I want to listen for clicks on the header of that element, i.e. the
 element.

My current solution looks like this

<paper-card heading="[[title]]" on-tap="onCardClick">
    ...
</paper-card>

onCardClick(e){
    if( e.path[0].classList.contains('header') || e.path[0].classList.contains('title-text') ){
        // Header was clicked
    }
}

but it feels hacky.

Is there a better way of doing this?

Body:
I would suggest separating the header element like

<paper-card>
  <div class="header" on-click="onCardClick">
    <div class="title-text">[[title]]</div>
  </div>
</paper-card>

with the original CSS:

.header {
  position: relative;
  border-top-left-radius: inherit;
  border-top-right-radius: inherit;
  overflow: hidden;
}

.title-text {
  padding: 16px;
  font-size: 24px;
  font-weight: 400;
  color: var(--paper-card-header-color, #000);
}

It has exactly the same effect as you use the heading attribute but is more flexible.


问:
Get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City in swift 3 xcode
Here, I want to get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City using swift 3 xcode. I tried to get current Time-hrs/min/sec/millisec of Mexico city like,

```<code>    let date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(identifier: "America/Mexico_City")! /* Something wrong here */

    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = Int(Int64(Date().timeIntervalSince1970 * 1000)) /* this should be fetched using calendar object */
    print("hours = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")
</code>```

But I'm unable to get current time of some specific city like MexicoCity. So, Please help me out.

答:
SOLVED FINALLY

Step 1:
Using this LINK find the city/country abbreviation abbr.

Step 2:
Using the link mentioned in step 1, you will get JsonObject as response like example for mexico city:

```<code>{
"value": "Central Standard Time (Mexico)",
"abbr": "CDT",
"offset": -5,
"isdst": true,
"text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey",
"utc": [
  "America/Bahia_Banderas",
  "America/Cancun",
  "America/Merida",
  "America/Mexico_City",
  "America/Monterrey"
]
}
</code>```

Step 3: So use this abbr key value like TimeZone.init(abbreviation: "CDT") which is clearly mentioned below.

```<code>func initVars(){

    var date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(abbreviation: "CDT")!
    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = calendar.component(.nanosecond, from: date) // may need to convert NANOSECOND to Millisecond // this should be fetchhed using calendat obj
    print("TESTING Current Time = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")

}
</code>```

So Finally, as result you will get like:

```<code>TESTING Current Time = 10:39:17:812892973
</code>```

Current Mexico time: 10:39 AM Thursday, November 16, 2017 (CST) Time in Mexico City, CDMX, Mexico

Body:
Here, I want to get current Hour/Minute/Secong/Millisecond using timezone of some specific city like America/Mexico_City using swift 3 xcode. I tried to get current Time-hrs/min/sec/millisec of Mexico city like,

    let date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(identifier: "America/Mexico_City")! /* Something wrong here */

    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = Int(Int64(Date().timeIntervalSince1970 * 1000)) /* this should be fetched using calendar object */
    print("hours = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")

But I'm unable to get current time of some specific city like MexicoCity. So, Please help me out.

Body:
SOLVED FINALLY

Step 1:
Using this LINK find the city/country abbreviation abbr.

Step 2:
Using the link mentioned in step 1, you will get JsonObject as response like example for mexico city:

{
"value": "Central Standard Time (Mexico)",
"abbr": "CDT",
"offset": -5,
"isdst": true,
"text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey",
"utc": [
  "America/Bahia_Banderas",
  "America/Cancun",
  "America/Merida",
  "America/Mexico_City",
  "America/Monterrey"
]
}

Step 3: So use this abbr key value like TimeZone.init(abbreviation: "CDT") which is clearly mentioned below.

func initVars(){

    var date = Date()
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.init(abbreviation: "CDT")!
    hrOfDay = calendar.component(.hour, from: date)
    curMin = calendar.component(.minute, from: date)
    curSec = calendar.component(.second, from: date)
    curMillSec = calendar.component(.nanosecond, from: date) // may need to convert NANOSECOND to Millisecond // this should be fetchhed using calendat obj
    print("TESTING Current Time = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")

}

So Finally, as result you will get like:

TESTING Current Time = 10:39:17:812892973

Current Mexico time: 10:39 AM Thursday, November 16, 2017 (CST) Time in Mexico City, CDMX, Mexico


问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答:
In my opinion each derived class is "a class of it's own", and the clients of this class, including subclasses) should in general not bother, or be interested in, how many classes there are between this class and the Object class.

Thus, my answer would be: No, let the hierarchy be as deep as it needs to be, as long as it makes sense / seems logical. Don't let the hierarchy depth influence the decision of whether or not to collapse two classes.  Since each subclass is a refinement of it's base class, my experience says that it seldom makes sense to have depths of more than 5 or 6 classes.

Just to be clear: As others have pointed out, you should favour composition over inheritance. To me however, that seems to answer a slightly different question though.

According to this article, the maximum depth in the standard Java API is 9.

ContentLicense: CC BY-SA 2.5

Title: How many levels of inheritance


问:
Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration
https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf

EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)

I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **

tarzan.txt - https://pastebin.com/XDxnXYsM

output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt

simple.txt https://pastebin.com/Djc2R0Vz

clothes.txt https://pastebin.com/SQB8Q7Y8

this code should print to an output file you name.

Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.

Welcome to the game of Mad Libs.
I will ask you to provide various words

and phrases to fill in a story.

The result will be written to an output file.

(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c

Input file name: tarzan.txt

Output file name: test.txt

Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this

Please type a noun: DDDD

Please type an adjective: DD

Please type a place:

========================================================================

```<code>package MadLibs;
import java.util.*;
import java.io.*;

public class MadLibs2 {
   public static void main(String[] args) throws FileNotFoundException {
      Scanner console = new Scanner(System.in);
      intro();
      boolean isTrue = true;
      while(isTrue) {
          System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
          String choice = console.next();
         if (choice.equalsIgnoreCase("c")) {
            create(console);
         }
         else if (choice.equalsIgnoreCase("v")) {
            view(console);
         }
         else if (choice.equalsIgnoreCase("q")) {
            System.exit(0);
         }
      }
   }

   public static void view(Scanner console) throws FileNotFoundException {
       System.out.print("Input file name: ");
       String viewFile = console.next();
       File existingMadLib = new File(viewFile);
       Scanner printText = new Scanner(existingMadLib);
       while(printText.hasNextLine()) {
           System.out.println(printText.nextLine());
       }
   }

   public static void create(Scanner console) throws FileNotFoundException {
      System.out.print("Input file name: ");
      String inputFile = console.next();
      File newMadLib = new File(inputFile);
      while(!newMadLib.exists()) {
         System.out.print("File not found. Try again: ");
         inputFile = console.next();
         newMadLib = new File(inputFile);
      }
      System.out.print("Output file name: ");
      String outputFile = console.next();
      System.out.println();
      PrintStream output = new PrintStream(new File(outputFile));
      Scanner input = new Scanner(newMadLib);
      while(input.hasNextLine()) {
         String line = input.nextLine();
         outputLines(line, output, console);
      }
   }

   public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
      String s = "";
      Scanner lineScan = new Scanner(line);
      while(lineScan.hasNext()){
         s = lineScan.next();
         if(s.startsWith("<") || s.endsWith(">")) {
            s = rePlaceholder(console, lineScan, s);
         }
         output.print(s + " ");
      }
      output.println();
   }

   public static String rePlaceholder(Scanner console, Scanner input, String token) {
      String placeholder = token;
      placeholder = placeholder.replace("<", "").replace(">", "").replace("-",  " ");
      if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
       || placeholder.startsWith("o") || placeholder.startsWith("u")) {
         System.out.print("Please type an " + placeholder + ": ");
      }  else {
          System.out.print("Please type a " + placeholder + ": ");
       }
      String change = console.nextLine();
      return change;
   }

   public static void intro() {
      System.out.println("Welcome to the game of Mad Libs.");
      System.out.println("I will ask you to provide various words");
      System.out.println("and phrases to fill in a story.");
      System.out.println("The result will be written to an output file.");
   }
}
</code>```

答:
in your rePlaceholder, change this line:

```<code>String change = console.nextLine();
</code>```

Into this

```<code>String change = console.next();
</code>```

Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.

This is from the documentation to be a bit more precise on the explanation:

Since this method continues to search through the input looking for a
  line separator, it may buffer all of the input searching for the line
  to skip if no line separators are present.

UPDATE

After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.

```<code> System.out.print("Output file name: ");
 String outputFile = console.next();
 console.nextLine(); // dummy call
 System.out.println();
</code>```

Body:
https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf

EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)

I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **

tarzan.txt - https://pastebin.com/XDxnXYsM

output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt

simple.txt https://pastebin.com/Djc2R0Vz

clothes.txt https://pastebin.com/SQB8Q7Y8

this code should print to an output file you name.

Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.

Welcome to the game of Mad Libs.
I will ask you to provide various words

and phrases to fill in a story.

The result will be written to an output file.

(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c

Input file name: tarzan.txt

Output file name: test.txt

Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this

Please type a noun: DDDD

Please type an adjective: DD

Please type a place:

========================================================================

package MadLibs;
import java.util.*;
import java.io.*;

public class MadLibs2 {
   public static void main(String[] args) throws FileNotFoundException {
      Scanner console = new Scanner(System.in);
      intro();
      boolean isTrue = true;
      while(isTrue) {
          System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
          String choice = console.next();
         if (choice.equalsIgnoreCase("c")) {
            create(console);
         }
         else if (choice.equalsIgnoreCase("v")) {
            view(console);
         }
         else if (choice.equalsIgnoreCase("q")) {
            System.exit(0);
         }
      }
   }

   public static void view(Scanner console) throws FileNotFoundException {
       System.out.print("Input file name: ");
       String viewFile = console.next();
       File existingMadLib = new File(viewFile);
       Scanner printText = new Scanner(existingMadLib);
       while(printText.hasNextLine()) {
           System.out.println(printText.nextLine());
       }
   }

   public static void create(Scanner console) throws FileNotFoundException {
      System.out.print("Input file name: ");
      String inputFile = console.next();
      File newMadLib = new File(inputFile);
      while(!newMadLib.exists()) {
         System.out.print("File not found. Try again: ");
         inputFile = console.next();
         newMadLib = new File(inputFile);
      }
      System.out.print("Output file name: ");
      String outputFile = console.next();
      System.out.println();
      PrintStream output = new PrintStream(new File(outputFile));
      Scanner input = new Scanner(newMadLib);
      while(input.hasNextLine()) {
         String line = input.nextLine();
         outputLines(line, output, console);
      }
   }

   public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
      String s = "";
      Scanner lineScan = new Scanner(line);
      while(lineScan.hasNext()){
         s = lineScan.next();
         if(s.startsWith("<") || s.endsWith(">")) {
            s = rePlaceholder(console, lineScan, s);
         }
         output.print(s + " ");
      }
      output.println();
   }

   public static String rePlaceholder(Scanner console, Scanner input, String token) {
      String placeholder = token;
      placeholder = placeholder.replace("<", "").replace(">", "").replace("-",  " ");
      if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
       || placeholder.startsWith("o") || placeholder.startsWith("u")) {
         System.out.print("Please type an " + placeholder + ": ");
      }  else {
          System.out.print("Please type a " + placeholder + ": ");
       }
      String change = console.nextLine();
      return change;
   }

   public static void intro() {
      System.out.println("Welcome to the game of Mad Libs.");
      System.out.println("I will ask you to provide various words");
      System.out.println("and phrases to fill in a story.");
      System.out.println("The result will be written to an output file.");
   }
}

Body:
in your rePlaceholder, change this line:

String change = console.nextLine();

Into this

String change = console.next();

Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.

This is from the documentation to be a bit more precise on the explanation:

Since this method continues to search through the input looking for a
  line separator, it may buffer all of the input searching for the line
  to skip if no line separators are present.

UPDATE

After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.

 System.out.print("Output file name: ");
 String outputFile = console.next();
 console.nextLine(); // dummy call
 System.out.println();


问:
syntaxerror: 'return' outside function in python code
There is something wrong with my python code. I am a beginner in python.

```<code>def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

if len(acc_id) == 15:
    pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
    pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
    pp_acc_id = "01130066" + acc_id.substring(1)
else:
    return "null"

if not amount:
    pp_amount = format("54%02d%s", amount.length(), amount)

    pp_str = "00020101021129370016A000000677010111"
    + pp_acc_id
    + "5303764"
    + pp_amount
    + "5802TH"
    + "6304"
    pp_chksum = crc16.checksum(pp_str);
    pp_str += pp_chksum;
    return pp_str
</code>```

Error says it's SyntaxError: 'return' outside function. What's the problem with this code. By the way i convert the code from java to python. Is that everything okey in my code? I edit my code here but still there are some error

答:
You need to properly indent your code. From your question I'm guessing this would resolve your issue:</p>

```<code>    import crc16

    def gen_qr_text(acc_id,amount):
        pp_acc_id = ""
        pp_amount = ""
        pp_chksum = ""

        if len(acc_id) == 15:
          pp_acc_id = "0315" + acc_id
        elif acc_id.length() == 13:
          pp_acc_id = "0213" + acc_id
        elif acc_id.length() == 10:
          pp_acc_id = "01130066" + acc_id.substring(1)
        else:
          return "null"

        if not amount:
          pp_amount = format("54%02d%s", amount.length(), amount)

        pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304"
        pp_chksum = crc16.checksum(pp_str);
        pp_str += pp_chksum;
        return pp_str
</code>```

Body:
There is something wrong with my python code. I am a beginner in python.

def gen_qr_text(acc_id,amount):
    pp_acc_id = ""
    pp_amount = ""
    pp_chksum = ""

if len(acc_id) == 15:
    pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
    pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
    pp_acc_id = "01130066" + acc_id.substring(1)
else:
    return "null"

if not amount:
    pp_amount = format("54%02d%s", amount.length(), amount)

    pp_str = "00020101021129370016A000000677010111"
    + pp_acc_id
    + "5303764"
    + pp_amount
    + "5802TH"
    + "6304"
    pp_chksum = crc16.checksum(pp_str);
    pp_str += pp_chksum;
    return pp_str

Error says it's SyntaxError: 'return' outside function. What's the problem with this code. By the way i convert the code from java to python. Is that everything okey in my code? I edit my code here but still there are some error

Body:
You need to properly indent your code. From your question I'm guessing this would resolve your issue:

    import crc16

    def gen_qr_text(acc_id,amount):
        pp_acc_id = ""
        pp_amount = ""
        pp_chksum = ""

        if len(acc_id) == 15:
          pp_acc_id = "0315" + acc_id
        elif acc_id.length() == 13:
          pp_acc_id = "0213" + acc_id
        elif acc_id.length() == 10:
          pp_acc_id = "01130066" + acc_id.substring(1)
        else:
          return "null"

        if not amount:
          pp_amount = format("54%02d%s", amount.length(), amount)

        pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304"
        pp_chksum = crc16.checksum(pp_str);
        pp_str += pp_chksum;
        return pp_str


问:
Uncaught SyntaxError: Unexpected end of input error
Not sure why I'm getting an Uncaught SyntaxError: Unexpected end of input error on this, to be honest I have used this snippet in many places before and never had this issue? I obviously am just code blind this afternoon!</p>

```<code><!-- jquery and bootstrap -->
<script src="js/libs.min.js?t=1494075642"></script>
<script src="js/template.js?t=1494075642"></script>
<script>
    // =======================
    // SUBMIT TO MAILCHIMP
    // =======================
    $(document).ready( function () {
    var action = "https://<<client_name>>.us13.list-manage.com/subscribe/post-json?u=207e8e8eebc7ed702d92e7928";
    var form = $('.mailchimp');

    if ( form.length > 0 ) {
        $('.mailchimp button[type="submit"]').on('click', function(e) {
            e.preventDefault();
            form = $(this).closest(".mailchimp");
            register(form);
        });
    }

    function register(form) {
        $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: form.serialize(),
            cache       : false,
            dataType    : 'json',
            contentType: "application/json; charset=utf-8",
            error       : function(err) {
                alert("Could not connect to the registration server. Please try again later.");
            },
            success     : function(data) {
                if (data.result != "success") {
                    $('#success').addClass("alert-danger").toggle().find("p").text(data.msg);
                    $('#mailchimpModal').modal('show');
                    $form.reset();
                } else {
                    $('#success').addClass("alert-success").toggle().find("p").text(data.msg);
                    $('#mailchimpModal').modal('show');
                    $form.reset();
                }
            }
        })
    }

</script>
</code>```

答: You are missing ' }); ' at the bottom. Just add it right above the /script tag. You need to close out your $(document).ready( function() { </p>


问:
Call a function after completing the *ngFor
I'm trying to create a application with angular 2; I want when last element rendered in *ngFor,execute a function, something like this, tag is :

```<code><img *ngFor="let image of template.previewImages; let i = index" [src]="image" [class.hs_visible]="i==0" />
</code>```

Function name is

```<code>animation(){console.log('enter');}
</code>```

答: Pankay Parkar answer works, but you need to change the writing of lastElement in setTimeout function (now is lastElem, so the plunker doesn't work to check if is last element of *ngFor)

Body:
I'm trying to create a application with angular 2; I want when last element rendered in *ngFor,execute a function, something like this, tag is :

Function name is

animation(){console.log('enter');}


问:
How to change InfiniteScrollView from horizontal to vertical in android?
I am building an android app. I am using this plugin

https://github.com/satansly/InfiniteScrollView

to make a circular scrollview. When I try it, it makes a horizontal scrollview. But I want a vertical one.

It says on the readme Infinite or Circular scroll view for Android. Allows infinite scrolling in either directions..

But there is no documentation on how to change it.

Does anyone know how?

Thanks

答:
Change all getX() method to getY(). Change all getXVelocity() to getYVelocity(). Change params.leftMargin to params.topMargin. Also change MATCH_PARENT to WRAP_CONTENT in constructors of PSInfiniteScrollView.java file.

Hope it may work. :)


问:
How to access services in a different Kubernetes cluster
For improved performance and availability we'd like to distribute certain services from out stack across different Kubernetes clusters in different parts of the world (GCP regions).

The majority of our stack will continue to run in one cluster / region but some user facing services will be deployed all over the world.

Some of these services need to access other services in our main cluster.

Q: How can we reliably access services in a different Kubernetes cluster?

Using internal load balancers seems to be out of the question as those are per region only.

We'd like to keep the communication between our services inside the private GCP network and avoid going over the public internet. So an public ingress also wouldn't work.

答: VPC networks are global resources, not restricted by regional boundaries, and so with the correct firewall rules set up, you should be able to access any internal resource from any other resource "right out of the box", assuming they are in the same VPC network and same project.</p>


问:
randomizing a sequence in a 1d array in c
**This is not generating a number, it is rearranging the number in 1d array
Need help in randomizing the sequence of 0,1,2,3 number in rbox array. however when random, it shows 1,1,1,1 or 2,2,2,2 etc. anyone have idea how to randomize the sequence into 0,3,2,1 or 2,0,1,3 etc?</p>

```<code>srand(time(NULL));
int randomm = rand()%4;
int rbox[4];
int x;

for(x=0;x<4;x++)
{
    rbox[x] = 0;
}
for(x=0;x<4;x++)
{
    rbox[x] = randomm;
}
for(x=0;x<4;x++)
{
    printf("%i", rbox[x]);
}
</code>```

答:
This is prime example of bad coding.

randomm variable gets the value once and you are assigning the same value four times to your array in the loop.

Do this,

```<code>for(x=0;x<4;x++)
{
    rbox[x] = rand()%4;
}
</code>```

But this will have a chance of repeating random values.
You will need to verify that the value has previously occurred or not in the array on every iteration.

Body:
**This is not generating a number, it is rearranging the number in 1d array
Need help in randomizing the sequence of 0,1,2,3 number in rbox array. however when random, it shows 1,1,1,1 or 2,2,2,2 etc. anyone have idea how to randomize the sequence into 0,3,2,1 or 2,0,1,3 etc?

srand(time(NULL));
int randomm = rand()%4;
int rbox[4];
int x;

for(x=0;x<4;x++)
{
    rbox[x] = 0;
}
for(x=0;x<4;x++)
{
    rbox[x] = randomm;
}
for(x=0;x<4;x++)
{
    printf("%i", rbox[x]);
}

Body:
This is prime example of bad coding.

randomm variable gets the value once and you are assigning the same value four times to your array in the loop.

Do this,

for(x=0;x<4;x++)
{
    rbox[x] = rand()%4;
}

But this will have a chance of repeating random values.
You will need to verify that the value has previously occurred or not in the array on every iteration.


问:
configuration for msysgit bash inside emacs on windows
What do you add to your .emacs file to use msysgit bash inside emacs ?

I just modified the cygwin instructions for msysgit replace cygwin with msysgit everywhere in these .

The only thing i can't do is run ssh or vim inside the bash...

directory completions work with windows style drive names prepended at the beginning.

答:
Update May 2018: Git 2.18 (Q2 2018) has now removed the contrib/emacs/ content.

Users of the git.el mode are now much better off using either Magit or the Git backend for Emacs's own VC mode.

See "Emacs Lisp error at init" for more.

Original answer 2011:

Not tested, but the idea was (2008) to copy in your Git installation directory at least:

```<code>contrib\emacs\git.el
contrib\emacs\git-mswin.el
</code>```

With git-mswin.el being "Windows/msysgit specific modifications for git.el".

Body:
Update May 2018: Git 2.18 (Q2 2018) has now removed the contrib/emacs/ content.

Users of the git.el mode are now much better off using either Magit or the Git backend for Emacs's own VC mode.

See "Emacs Lisp error at init" for more.

Original answer 2011:

Not tested, but the idea was (2008) to copy in your Git installation directory at least:

contrib\emacs\git.el
contrib\emacs\git-mswin.el

With git-mswin.el being "Windows/msysgit specific modifications for git.el".

ContentLicense: CC BY-SA 4.0


问:
client (fetch) and server (nodejs http) don't understand each other?
I try to wrap my mind around nodejs at the moment.

So I've created a client:

```<code>let myHeaders = {
 'Content-Type': 'application/json',
 'Accept': 'application/json'
};

let myBody = {
  aString: "Test"
};

fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors',
  headers: myHeaders,
  body: JSON.stringify(myBody)
})
.then(result => {
  return result.text();
})
.then(text => {
  // do stuff with text from server
});
</code>```

And I have created a server:

```<code>// request needed modules
const http = require('http');

// init server
let server = http.createServer(logic);
server.listen(8099);

// server logic
function logic (req, res) {
  var body = req.body;
  res.end("Hello");
}
</code>```

Two problems:

1) The sever does not get the body (req.body is undefined).

UPDATE

See my answer below.

--

2) The client does not receive "Hello" (result.text() returns "").

UPDATE
2 is solved by:

Changing this on the client

```<code>fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors', <-- CHANGE to: mode: 'cors'
...
</code>```

Adding this on server

```<code>res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
</code>```

--

I don't get what I do wrong here...

答:
Your Node.js code has nothing which would generate the HTML document containing the JS that calls fetch.

This means you must be making a cross-origin request (this is supported by the absolute URL you pass to fetch).

You also set mode: 'no-cors' which means "Don't throw a security exception for trying to access a cross-origin resource, and don't make the response available to JS".

Consequently, when you try to read the response: You can't.

Set the mode to "cors" and change the Node.js code to follow the CORS specification to grant permission to the page trying to read the data.

I try to wrap my mind around nodejs at the moment.

There is nothing particular to Node.js here. The problems are related to security restrictions on what JavaScript running in the browser can do unless granted permission by the HTTP server.

Body:
I try to wrap my mind around nodejs at the moment.

So I've created a client:

let myHeaders = {
 'Content-Type': 'application/json',
 'Accept': 'application/json'
};

let myBody = {
  aString: "Test"
};

fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors',
  headers: myHeaders,
  body: JSON.stringify(myBody)
})
.then(result => {
  return result.text();
})
.then(text => {
  // do stuff with text from server
});

And I have created a server:

// request needed modules
const http = require('http');

// init server
let server = http.createServer(logic);
server.listen(8099);

// server logic
function logic (req, res) {
  var body = req.body;
  res.end("Hello");
}

Two problems:

1) The sever does not get the body (req.body is undefined).

UPDATE

See my answer below.

--

2) The client does not receive "Hello" (result.text() returns "").

UPDATE
2 is solved by:

Changing this on the client

fetch("http://localhost:8099/", {
  method: 'post',
  mode: 'no-cors', <-- CHANGE to: mode: 'cors'
...

Adding this on server

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

--

I don't get what I do wrong here...


问:
Windows SDK UWP App Error - DEP3321
I have been battling DEP3321: To deploy this application, your deployment target should be running Windows Universal Runtime version 10.0.14393.0 or higher. You currently are running version 10.0.10586.839. Please update your OS, or change your deployment target to a device with the appropriate version. for the past few days.

I have a UWP app which I cannot run on my machine. However, if I select one of the emulators, it runs fine. I have also set the minimum target value which ensures that the app runs, however, the app throws an error as it cannot find some methods in the lower version on the SDK.

I have tried repairing and uninstalling/re-installing both visual studio 2015 and 2017. I have tried the same with the various windows SDK as well. At one point i had three different versions of the SDK installed and visual studio was still complaining even though i had the updated version installed. Currently, I have installed win sdk 10.0.15063.17.

Any ideas what I can do next to resolve this issue. I have trawled various SO pages as well social.msdn pages with no luck.

Many thanks

答: I just started a new app and selected the highest Target levels and got this error. I was able to get rid of this error by selecting the default minimum Min Target Version as shown below.

Title: Windows SDK UWP App Error - DEP3321


问:
How to cross-reference tibbles in R?
```<code>library(nycflights13)
library(tidyverse)
</code>```

My task is

Look at each destination. Can you find flights that are suspiciously fast? (i.e. flights that represent a potential data entry error).

I have generated a tibble with the average flight times between every two airports:

```<code># A tibble: 224 x 3
# Groups:   origin [?]
   origin  dest mean_time
    <chr> <chr>     <dbl>
 1    EWR   ALB  31.78708
 2    EWR   ANC 413.12500
 3    EWR   ATL 111.99385
 4    EWR   AUS 211.24765
 5    EWR   AVL  89.79681
 6    EWR   BDL  25.46602
 7    EWR   BNA 114.50915
 8    EWR   BOS  40.31275
 9    EWR   BQN 196.17288
10    EWR   BTV  46.25734
# ... with 214 more rows
</code>```

Now I need to sweep through flights and extract all rows, whose air_time is outside say (mean_time/2, mean_time*2). How do I do that?

答:
You would first join that average flight time data frame onto your original flights data and then apply the filter. Something like this should work.

```<code>library(nycflights13)
library(tidyverse)

data("flights")

#get mean time
mean_time <- flights %>%
    group_by(origin, dest) %>%
    summarise(mean_time = mean(air_time, na.rm = TRUE))

#join mean time to original data
df <- left_join(flights, mean_time)

flag_flights <- df %>%
    filter(air_time <= (mean_time / 2) | air_time >= (mean_time * 2))
> flag_flights
# A tibble: 29 x 20
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin  dest air_time distance  hour minute
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl>   <chr>  <int>   <chr>  <chr> <chr>    <dbl>    <dbl> <dbl>  <dbl>
 1  2013     1    16      635            608        27      916            725       111      UA    541  N837UA    EWR   BOS       81      200     6      8
 2  2013     1    21     1851           1900        -9     2034           2012        22      US   2140  N956UW    LGA   BOS       76      184    19      0
 3  2013     1    28     1917           1825        52     2118           1935       103      US   1860  N755US    LGA   PHL       75       96    18     25
 4  2013    10     7     1059           1105        -6     1306           1215        51      MQ   3230  N524MQ    JFK   DCA       96      213    11      5
 5  2013    10    10      950            959        -9     1155           1115        40      EV   5711  N829AS    JFK   IAD       97      228     9     59
 6  2013     2    17      841            840         1     1044           1003        41      9E   3422  N913XJ    JFK   BOS       86      187     8     40
 7  2013     3     8     1136           1001        95     1409           1116       173      UA   1240  N17730    EWR   BOS       82      200    10      1
 8  2013     3     8     1246           1245         1     1552           1350       122      AA   1850  N3FEAA    JFK   BOS       80      187    12     45
 9  2013     3    12     1607           1500        67     1803           1608       115      US   2132  N946UW    LGA   BOS       77      184    15      0
10  2013     3    12     1612           1557        15     1808           1720        48      UA   1116  N37252    EWR   BOS       81      200    15     57
# ... with 19 more rows, and 2 more variables: time_hour <dttm>, mean_time <dbl>
</code>```

Title: How to cross-reference tibbles in R?

Body:
library(nycflights13)
library(tidyverse)

My task is

Look at each destination. Can you find flights that are suspiciously fast? (i.e. flights that represent a potential data entry error).

I have generated a tibble with the average flight times between every two airports:

# A tibble: 224 x 3
# Groups:   origin [?]
   origin  dest mean_time
    <chr> <chr>     <dbl>
 1    EWR   ALB  31.78708
 2    EWR   ANC 413.12500
 3    EWR   ATL 111.99385
 4    EWR   AUS 211.24765
 5    EWR   AVL  89.79681
 6    EWR   BDL  25.46602
 7    EWR   BNA 114.50915
 8    EWR   BOS  40.31275
 9    EWR   BQN 196.17288
10    EWR   BTV  46.25734
# ... with 214 more rows

Now I need to sweep through flights and extract all rows, whose air_time is outside say (mean_time/2, mean_time*2). How do I do that?

Body:
You would first join that average flight time data frame onto your original flights data and then apply the filter. Something like this should work.

library(nycflights13)
library(tidyverse)

data("flights")

#get mean time
mean_time <- flights %>%
    group_by(origin, dest) %>%
    summarise(mean_time = mean(air_time, na.rm = TRUE))

#join mean time to original data
df <- left_join(flights, mean_time)

flag_flights <- df %>%
    filter(air_time <= (mean_time / 2) | air_time >= (mean_time * 2))
> flag_flights
# A tibble: 29 x 20
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin  dest air_time distance  hour minute
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>     <dbl>   <chr>  <int>   <chr>  <chr> <chr>    <dbl>    <dbl> <dbl>  <dbl>
 1  2013     1    16      635            608        27      916            725       111      UA    541  N837UA    EWR   BOS       81      200     6      8
 2  2013     1    21     1851           1900        -9     2034           2012        22      US   2140  N956UW    LGA   BOS       76      184    19      0
 3  2013     1    28     1917           1825        52     2118           1935       103      US   1860  N755US    LGA   PHL       75       96    18     25
 4  2013    10     7     1059           1105        -6     1306           1215        51      MQ   3230  N524MQ    JFK   DCA       96      213    11      5
 5  2013    10    10      950            959        -9     1155           1115        40      EV   5711  N829AS    JFK   IAD       97      228     9     59
 6  2013     2    17      841            840         1     1044           1003        41      9E   3422  N913XJ    JFK   BOS       86      187     8     40
 7  2013     3     8     1136           1001        95     1409           1116       173      UA   1240  N17730    EWR   BOS       82      200    10      1
 8  2013     3     8     1246           1245         1     1552           1350       122      AA   1850  N3FEAA    JFK   BOS       80      187    12     45
 9  2013     3    12     1607           1500        67     1803           1608       115      US   2132  N946UW    LGA   BOS       77      184    15      0
10  2013     3    12     1612           1557        15     1808           1720        48      UA   1116  N37252    EWR   BOS       81      200    15     57
# ... with 19 more rows, and 2 more variables: time_hour <dttm>, mean_time <dbl>


问:
Why does my if statments goto else after results show?
I need to add for the decimal placement, which I know how to write that. I've tinkered with this code and tried different thing, which is why my else statement isn't the same as the if. </p>

<p>Plus I Will either go scanner over GUI. Anyways, when I chose the if statement then it shows the results in the console, but then goes to the else statement. I've tried several things, but can't figure out why. </p>

```<code>import java.text.DecimalFormat;

import javax.swing.*;

public class MathFormula {

    public static void main(String args[]) {

        //Declarations
        double getNumDouble;
        double volumeSphere;
        String getNum;
        double area;
        double volume;
        String getUserDecision; //Declared getUserDecision for outer loop decision
        DecimalFormat df = new DecimalFormat("####0.000");
        java.util.Scanner input = new java.util.Scanner(System.in);
        //End Declarations

        // Greeting
        greeting();

        System.out.println("  "); //Left blank for clarity

        // Ask user to start the program (the outer loop)

        getUserDecision = decisionOuter();
        while (getUserDecision.equalsIgnoreCase("Y")) {

            getUserDecision = decisionInner();

            if (getUserDecision.equalsIgnoreCase("S")) {

                System.out.print("Enter you number for volume of sphere: ");
                getNum = input.next();
                getNumDouble = Double.parseDouble(getNum);
                volSphere(getNumDouble);

            } else if (getUserDecision.equalsIgnoreCase("C"))
                System.out.println(" ");
            area = arCircle();
            System.out.println("you have worked: " + df.format(area));

            getUserDecision = decisionOuter();
        }

        goodbye();
    }

    public static String decisionOuter() //Outerloop decision
    {
        String userDecisionString;

        userDecisionString = JOptionPane.showInputDialog("Would you like to use the program Y/N: ");

        return userDecisionString;
    }

    public static String decisionInner() //Inner loop decision
    {
        String userDecisionString2;

        userDecisionString2 = JOptionPane.showInputDialog("C or S: ");

        return userDecisionString2;
    }

    public static void volSphere(double getNumDouble) //Vol formula
    {
        double volumeSphere;

        volumeSphere = (4 * Math.PI * getNumDouble * getNumDouble * getNumDouble) / 3;

        System.out.println("entered " + getNumDouble + "returned" + volumeSphere);
    }

    public static double arCircle() //area formula
    {
        double getNum;
        double areaCircle;
        String getNumString;

        getNumString = JOptionPane.showInputDialog("Enter you number for radius of circle: ");
        getNum = Double.parseDouble(getNumString);
        areaCircle = (getNum * getNum * Math.PI);
        return areaCircle;
    }

    public static void greeting() //greeting
    {
        final String msgGreet = "Welcome.";
        System.out.println(msgGreet);
    }

    public static void goodbye() //goodbye
    {
        final String msgBye = "goodbye.";
        System.out.println(msgBye);
    }
}
</code>```

答:
because you havent included the curley braces around the else inclusion. its only considering the 'System.out.println(" ");' as your else statement, everything else below it is executed, if you want exclusion then include curley braces around the code you want in the else condition</p>

```<code>//...
}
else if (getUserDecision.equalsIgnoreCase("C"))
{
    System.out.println(" ");
    area = arCircle();
    System.out.println("you have worked: " + df.format(area));
}

getUserDecision = decisionOuter();
//...
</code>```

Body:
I need to add for the decimal placement, which I know how to write that. I've tinkered with this code and tried different thing, which is why my else statement isn't the same as the if.

Plus I Will either go scanner over GUI. Anyways, when I chose the if statement then it shows the results in the console, but then goes to the else statement. I've tried several things, but can't figure out why.

import java.text.DecimalFormat;

import javax.swing.*;

public class MathFormula {

    public static void main(String args[]) {

        //Declarations
        double getNumDouble;
        double volumeSphere;
        String getNum;
        double area;
        double volume;
        String getUserDecision; //Declared getUserDecision for outer loop decision
        DecimalFormat df = new DecimalFormat("####0.000");
        java.util.Scanner input = new java.util.Scanner(System.in);
        //End Declarations

        // Greeting
        greeting();

        System.out.println("  "); //Left blank for clarity

        // Ask user to start the program (the outer loop)

        getUserDecision = decisionOuter();
        while (getUserDecision.equalsIgnoreCase("Y")) {

            getUserDecision = decisionInner();

            if (getUserDecision.equalsIgnoreCase("S")) {

                System.out.print("Enter you number for volume of sphere: ");
                getNum = input.next();
                getNumDouble = Double.parseDouble(getNum);
                volSphere(getNumDouble);

            } else if (getUserDecision.equalsIgnoreCase("C"))
                System.out.println(" ");
            area = arCircle();
            System.out.println("you have worked: " + df.format(area));

            getUserDecision = decisionOuter();
        }

        goodbye();
    }

    public static String decisionOuter() //Outerloop decision
    {
        String userDecisionString;

        userDecisionString = JOptionPane.showInputDialog("Would you like to use the program Y/N: ");

        return userDecisionString;
    }

    public static String decisionInner() //Inner loop decision
    {
        String userDecisionString2;

        userDecisionString2 = JOptionPane.showInputDialog("C or S: ");

        return userDecisionString2;
    }

    public static void volSphere(double getNumDouble) //Vol formula
    {
        double volumeSphere;

        volumeSphere = (4 * Math.PI * getNumDouble * getNumDouble * getNumDouble) / 3;

        System.out.println("entered " + getNumDouble + "returned" + volumeSphere);
    }

    public static double arCircle() //area formula
    {
        double getNum;
        double areaCircle;
        String getNumString;

        getNumString = JOptionPane.showInputDialog("Enter you number for radius of circle: ");
        getNum = Double.parseDouble(getNumString);
        areaCircle = (getNum * getNum * Math.PI);
        return areaCircle;
    }

    public static void greeting() //greeting
    {
        final String msgGreet = "Welcome.";
        System.out.println(msgGreet);
    }

    public static void goodbye() //goodbye
    {
        final String msgBye = "goodbye.";
        System.out.println(msgBye);
    }
}

Body:
because you havent included the curley braces around the else inclusion. its only considering the 'System.out.println(" ");' as your else statement, everything else below it is executed, if you want exclusion then include curley braces around the code you want in the else condition

//...
}
else if (getUserDecision.equalsIgnoreCase("C"))
{
    System.out.println(" ");
    area = arCircle();
    System.out.println("you have worked: " + df.format(area));
}

getUserDecision = decisionOuter();
//...


问:
How to properly escape recipe newlines in multi-line variable?

The Question

Example 1

Consider the following user-defined function:

```<code>define func =
    if [ -f $(1) ]; then \
        printf "'%s' is a file\n" '$(1)'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
    fi
endef

all:
    $(call func,foo)
</code>```

This will output the following:

```<code>$ make
if [ -f foo ]; then printf "'%s' is a file\n" 'foo'; printf "This is a rel
atively long command that"; printf " won't fit on one line\n"; fi
</code>```

For readability, I would like make to print the command on multiple lines,
as written in the Makefile.  How do I accomplish this?

What I've Tried

Example 2

The following works the way I want, but does not allow the parameterized
function:

```<code>filename := foo

.PHONY: foo
foo:
    if [ -f $(filename) ]; then \
        printf "'%s' is a file\n" '$(filename)'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
    fi
</code>```

Output:

```<code>$ make foo
if [ -f foo ]; then \
        printf "'%s' is a file\n" 'foo'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
fi
</code>```

Example 3

My obvious first instinct was to escape the backslashes:

```<code>define func =
    if [ -f $(1) ]; then \\
        printf "'%s' is a file\n" '$(1)'; \\
        printf "This is a relatively long command that"; \\
        printf " won't fit on one line\n"; \\
    fi
endef
</code>```

Output:

```<code>$ make
if [ -f foo ]; then \\
        printf "'%s' is a file\n" 'foo'; \\
        printf "This is a relatively long command that"; \\
        printf " won't fit on one line\n"; \\
fi
/bin/sh: \: command not found
'foo' is a file
/bin/sh: line 1: \: command not found
This is a relatively long command that/bin/sh: line 2: \: command not found
 won't fit on one line
/bin/sh: line 3: \: command not found
make: *** [Makefile:11: all] Error 127
</code>```

Example 4

Okay, so why not try \\\?

```<code>$ make
if [ -f foo ]; then \ printf "'%s' is a file\n" 'foo'; \ printf "This is a
relatively long command that"; \ printf " won't fit on one line\n"; \ fi
/bin/sh: -c: line 1: syntax error: unexpected end of file
make: *** [Makefile:11: all] Error 1
</code>```

Example 5

Interesting.  Let's go for four...

```<code>$ make
if [ -f foo ]; then \\\\
        printf "'%s' is a file\n" 'foo'; \\\\
        printf "This is a relatively long command that"; \\\\
        printf " won't fit on one line\n"; \\\\
fi
/bin/sh: \\: command not found
'foo' is a file
/bin/sh: line 1: \\: command not found
This is a relatively long command that/bin/sh: line 2: \\: command not found
 won't fit on one line
/bin/sh: line 3: \\: command not found
make: *** [Makefile:11: all] Error 127
</code>```

Now we're back to where we were last time.

What Works

Example 6

This is the only thing that seems to work:

```<code>define func =
    if [ -f $(1) ]; then #\\
        printf "'%s' is a file\n" '$(1)'; #\\
        printf "This is a relatively long command that"; #\\
        printf " won't fit on one line\n"; #\\
    fi
endef
</code>```

Output:

```<code>$ make
if [ -f foo ]; then #\\
        printf "'%s' is a file\n" 'foo'; #\\
        printf "This is a relatively long command that"; #\\
        printf " won't fit on one line\n"; #\\
fi
</code>```

But man, that looks ugly, and it feels hackish.  There's got to be a better
way to do this.  Or am I just going about this the wrong way in the first
place?

It seems to me that make is just confused by the magic that happens when
escaping newlines within a recipe.  The lines printed to the terminal during
execution do not match what the shell sees.  Should this be considered a bug?

I am using GNU Make 4.2.1 on Cygwin.

Edit

To clarify: make normally gives special treatment to trailing backslashes within a recipe.  They do not indicate line continuation, as they do elsewhere.  Instead, they indicate that multiple recipe lines are to be treated as a single command, and they are passed to the shell intact.

When not in a recipe, but defining a variable, this special treatment does not apply.  The lines are simply joined, as in Example 1.  This is expected.

I would expect that a double backslash would be translated to a single literal backslash in the variable, but instead both backslashes are retained.  When the variable is expanded in the recipe, I would expect make to behave as if the recipe had \\ at the end of every line.  If this were the case, each line would be executed separately.  But as you can see from Examples 3 and 6, the lines are executed together.

The point is, it is possible to get magic backslash parsing from the expansion of a variable.  The problem is the mechanics of this behavior are inconsistent and confusing.

答:
Urk! This is due to make's noddy parser.

Recipes are stored as-is.
They are expanded as-and-when make is about to call the shell.
Once the entire recipe has been expanded,
the first line is passed to a shell.
If that command succeeds, then the second is run.
Wash, rinse, repeat.
Backslashes at the end of line are preserved,
with the effect that the following line is passed at the same time as the first.

In recursive variable definition however,
backslashes at the end of line are removed as the definition is read

```<code>define oneline =
  aa \
  bb \
  cc
endef

$(error [$(value oneline)])
</code>```

which gives

$ make
Makefile:9: *** [  aa bb cc].  Stop.

What we are aiming for

We need to massage make's syntax so that a variable expands to exactly this text:

```<code>target:
    if [ -f foo ]; then \
        printf "'%s' is a file\n" 'foo'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
    fi
</code>```

which we then simply feed to make via something like

```<code>$(eval ${var})
</code>```

Backslashes

Just replace each newline with a space-backslash-newline-tab quad using $(subst).

A function to do that:

```<code>empty :=
tab := ${empty}   # Trailing tab
define \n :=

endef

stanza = $(subst ${\n}, \${\n}${tab})
</code>```

To check it works:

```<code>define func =
  if [ -f $1 ]; then
    printf "'%s' is a file\n" '$1';
    printf "This is a relatively long command that";
    printf " won't fit on one line\n";
  fi
endef

$(error [$(call stanza,$(call func,foo))])
</code>```

giving:

Makefile:23: *** [  if [ -f foo ]; then \
            printf "'%s' is a file\n" 'foo'; \
            printf "This is a relatively long command that"; \
            printf " won't fit on one line\n"; \
          fi].  Stop.

Note that the definition of func now has no annotation at the end of its lines.

Putting it all together

```<code>define \n :=

endef
empty :=
tab := ${empty}        # Trailing tab

stanza = $(subst ${\n}, \${\n}${tab},$1)

define func =
  if [ -f $1 ]; then
    printf "'%s' is a file\n" '$1';
    printf "This is a relatively long command that";
    printf " won't fit on one line\n";
  fi
endef

define rule =
  target:
        echo vvv
        $(call stanza,$(call func,foo))
        echo ^^^
endef

$(eval ${rule})
</code>```

Leading to

$ touch foo; make -R --warn
echo vvv
vvv
if [ -f foo ]; then \
    printf "'%s' is a file\n" 'foo'; \
    printf "This is a relatively long command that"; \
    printf " won't fit on one line\n"; \
  fi
'foo' is a file
This is a relatively long command that won't fit on one line
echo ^^^
^^^

An interesting academic exercise.
Still can't put literal backslashes in either :)

Body:
The Question

Example 1

Consider the following user-defined function:

define func =
    if [ -f $(1) ]; then \
        printf "'%s' is a file\n" '$(1)'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
    fi
endef

all:
    $(call func,foo)

This will output the following:

$ make
if [ -f foo ]; then printf "'%s' is a file\n" 'foo'; printf "This is a rel
atively long command that"; printf " won't fit on one line\n"; fi

For readability, I would like make to print the command on multiple lines,
as written in the Makefile.  How do I accomplish this?

What I've Tried

Example 2

The following works the way I want, but does not allow the parameterized
function:

filename := foo

.PHONY: foo
foo:
    if [ -f $(filename) ]; then \
        printf "'%s' is a file\n" '$(filename)'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
    fi

Output:

$ make foo
if [ -f foo ]; then \
        printf "'%s' is a file\n" 'foo'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
fi

Example 3

My obvious first instinct was to escape the backslashes:

define func =
    if [ -f $(1) ]; then \\
        printf "'%s' is a file\n" '$(1)'; \\
        printf "This is a relatively long command that"; \\
        printf " won't fit on one line\n"; \\
    fi
endef

Output:

$ make
if [ -f foo ]; then \\
        printf "'%s' is a file\n" 'foo'; \\
        printf "This is a relatively long command that"; \\
        printf " won't fit on one line\n"; \\
fi
/bin/sh: \: command not found
'foo' is a file
/bin/sh: line 1: \: command not found
This is a relatively long command that/bin/sh: line 2: \: command not found
 won't fit on one line
/bin/sh: line 3: \: command not found
make: *** [Makefile:11: all] Error 127

Example 4

Okay, so why not try \\\?

$ make
if [ -f foo ]; then \ printf "'%s' is a file\n" 'foo'; \ printf "This is a
relatively long command that"; \ printf " won't fit on one line\n"; \ fi
/bin/sh: -c: line 1: syntax error: unexpected end of file
make: *** [Makefile:11: all] Error 1

Example 5

Interesting.  Let's go for four...

$ make
if [ -f foo ]; then \\\\
        printf "'%s' is a file\n" 'foo'; \\\\
        printf "This is a relatively long command that"; \\\\
        printf " won't fit on one line\n"; \\\\
fi
/bin/sh: \\: command not found
'foo' is a file
/bin/sh: line 1: \\: command not found
This is a relatively long command that/bin/sh: line 2: \\: command not found
 won't fit on one line
/bin/sh: line 3: \\: command not found
make: *** [Makefile:11: all] Error 127

Now we're back to where we were last time.

What Works

Example 6

This is the only thing that seems to work:

define func =
    if [ -f $(1) ]; then #\\
        printf "'%s' is a file\n" '$(1)'; #\\
        printf "This is a relatively long command that"; #\\
        printf " won't fit on one line\n"; #\\
    fi
endef

Output:

$ make
if [ -f foo ]; then #\\
        printf "'%s' is a file\n" 'foo'; #\\
        printf "This is a relatively long command that"; #\\
        printf " won't fit on one line\n"; #\\
fi

But man, that looks ugly, and it feels hackish.  There's got to be a better
way to do this.  Or am I just going about this the wrong way in the first
place?

It seems to me that make is just confused by the magic that happens when
escaping newlines within a recipe.  The lines printed to the terminal during
execution do not match what the shell sees.  Should this be considered a bug?

I am using GNU Make 4.2.1 on Cygwin.

Edit

To clarify: make normally gives special treatment to trailing backslashes within a recipe.  They do not indicate line continuation, as they do elsewhere.  Instead, they indicate that multiple recipe lines are to be treated as a single command, and they are passed to the shell intact.

When not in a recipe, but defining a variable, this special treatment does not apply.  The lines are simply joined, as in Example 1.  This is expected.

I would expect that a double backslash would be translated to a single literal backslash in the variable, but instead both backslashes are retained.  When the variable is expanded in the recipe, I would expect make to behave as if the recipe had \\ at the end of every line.  If this were the case, each line would be executed separately.  But as you can see from Examples 3 and 6, the lines are executed together.

The point is, it is possible to get magic backslash parsing from the expansion of a variable.  The problem is the mechanics of this behavior are inconsistent and confusing.

Body:
Urk! This is due to make's noddy parser.

Recipes are stored as-is.
They are expanded as-and-when make is about to call the shell.
Once the entire recipe has been expanded,
the first line is passed to a shell.
If that command succeeds, then the second is run.
Wash, rinse, repeat.
Backslashes at the end of line are preserved,
with the effect that the following line is passed at the same time as the first.

In recursive variable definition however,
backslashes at the end of line are removed as the definition is read

define oneline =
  aa \
  bb \
  cc
endef

$(error [$(value oneline)])

which gives

$ make
Makefile:9: *** [  aa bb cc].  Stop.

What we are aiming for

We need to massage make's syntax so that a variable expands to exactly this text:

target:
    if [ -f foo ]; then \
        printf "'%s' is a file\n" 'foo'; \
        printf "This is a relatively long command that"; \
        printf " won't fit on one line\n"; \
    fi

which we then simply feed to make via something like

$(eval ${var})

Backslashes

Just replace each newline with a space-backslash-newline-tab quad using $(subst).

A function to do that:

empty :=
tab := ${empty}   # Trailing tab
define \n :=

endef

stanza = $(subst ${\n}, \${\n}${tab})

To check it works:

define func =
  if [ -f $1 ]; then
    printf "'%s' is a file\n" '$1';
    printf "This is a relatively long command that";
    printf " won't fit on one line\n";
  fi
endef

$(error [$(call stanza,$(call func,foo))])

giving:

Makefile:23: *** [  if [ -f foo ]; then \
            printf "'%s' is a file\n" 'foo'; \
            printf "This is a relatively long command that"; \
            printf " won't fit on one line\n"; \
          fi].  Stop.

Note that the definition of func now has no annotation at the end of its lines.

Putting it all together

define \n :=

endef
empty :=
tab := ${empty}        # Trailing tab

stanza = $(subst ${\n}, \${\n}${tab},$1)

define func =
  if [ -f $1 ]; then
    printf "'%s' is a file\n" '$1';
    printf "This is a relatively long command that";
    printf " won't fit on one line\n";
  fi
endef

define rule =
  target:
        echo vvv
        $(call stanza,$(call func,foo))
        echo ^^^
endef

$(eval ${rule})

Leading to

$ touch foo; make -R --warn
echo vvv
vvv
if [ -f foo ]; then \
    printf "'%s' is a file\n" 'foo'; \
    printf "This is a relatively long command that"; \
    printf " won't fit on one line\n"; \
  fi
'foo' is a file
This is a relatively long command that won't fit on one line
echo ^^^
^^^

An interesting academic exercise.
Still can't put literal backslashes in either :)


问:
Why JAVA has a solution for Diamond situation encountered in default interfaces but not for classes?
I was reading about the diamond problem in case of default interfaces, and the documentation says that if there is an interface A with default method m(), which is extended by two other interfaces B & C both having there own default method m(), and now suppose we have a class D that implements both B and C, then class D needs to have it's own implementation of the method m(), otherwise compiler will through exception.

```<code>interface A {
  default void m() {
    System.out.println("Interface A");
  }
}

interface B extends A {
  default void m() {
    System.out.println("Interface B");
  }
}

interface C extends A {
  default void m() {
    System.out.println("Interface C");
  }
}

//allowed multiple inheritance when D gives
//it's own implementation of method m()
//else compilation error
class D implements  B, C {
  public void m() {
    System.out.println("Class D");
  }
}
</code>```

If we go by the same logic, then why JAVA hasn't resolved the diamond problem in case of classes as well, and may be then we could have extended more than one classes.

```<code>interface A {
  default void m() {
    System.out.println("Interface A");
  }
}

class B implements A {
  public void m() {
    System.out.println("Interface B");
  }
}

class C implements A {
  public void m() {
    System.out.println("Interface C");
  }
}

//multiple inheritance not allowed even when D gives
//it's own implementation of method m()
//still getting compilation error
class D extends  B, C {
  public void m() {
    System.out.println("Class D");
  }
}
</code>```

答:
What do you expect to be the default behaviour when calling D.m().

Do you want that it invokes B.m() or C.m()? You just don't know.

You'd have to add a new logic which decides what method needs to be called which would exactly be the same as the current need to override.

Because of this uncertainty and not consistent behavior which clearly clashes with javas principles, you're not allowed to do that.

Body:
I was reading about the diamond problem in case of default interfaces, and the documentation says that if there is an interface A with default method m(), which is extended by two other interfaces B & C both having there own default method m(), and now suppose we have a class D that implements both B and C, then class D needs to have it's own implementation of the method m(), otherwise compiler will through exception.

interface A {
  default void m() {
    System.out.println("Interface A");
  }
}

interface B extends A {
  default void m() {
    System.out.println("Interface B");
  }
}

interface C extends A {
  default void m() {
    System.out.println("Interface C");
  }
}

//allowed multiple inheritance when D gives
//it's own implementation of method m()
//else compilation error
class D implements  B, C {
  public void m() {
    System.out.println("Class D");
  }
}

If we go by the same logic, then why JAVA hasn't resolved the diamond problem in case of classes as well, and may be then we could have extended more than one classes.

interface A {
  default void m() {
    System.out.println("Interface A");
  }
}

class B implements A {
  public void m() {
    System.out.println("Interface B");
  }
}

class C implements A {
  public void m() {
    System.out.println("Interface C");
  }
}

//multiple inheritance not allowed even when D gives
//it's own implementation of method m()
//still getting compilation error
class D extends  B, C {
  public void m() {
    System.out.println("Class D");
  }
}


问:
Python: call and run a process with input files
I am looking for a solution to run a process with input files in python:
in my script I call a process using sub-process:

```<code>import subprocess as sp
sp.call(['C:\EnergyPlusV8-8-0\EP-Launch.exe'])
</code>```

So the program I would like to launch is open, but then I need to choose 2 input files and then press the button "Simulate.." to execute the program(Energy Plus).

***comment:
I mean, after those code lines, the interface of the program(Energy Plus) is open, then I choose in that window which input files the program has to use. After that in the same interface of the program I start the simulation. I want to do these steps just in the python code, without interacte with the EnergyPlus interface. I hope I clearify the ambiguities
I would like to do the last steps automatically(knowing the input files location) in the python code.
How can I do this?

答: You won't be able to do this unless EnergyPlus is providing some kind of API, or you are prepared to write UI manipulation code, which would really depend on the type of application it is. Without more information I'm going to have to say what you want to do is not possible.</p>

Body:
I am looking for a solution to run a process with input files in python:
in my script I call a process using sub-process:

import subprocess as sp
sp.call(['C:\EnergyPlusV8-8-0\EP-Launch.exe'])

So the program I would like to launch is open, but then I need to choose 2 input files and then press the button "Simulate.." to execute the program(Energy Plus).

***comment:
I mean, after those code lines, the interface of the program(Energy Plus) is open, then I choose in that window which input files the program has to use. After that in the same interface of the program I start the simulation. I want to do these steps just in the python code, without interacte with the EnergyPlus interface. I hope I clearify the ambiguities
I would like to do the last steps automatically(knowing the input files location) in the python code.
How can I do this?


问:
php custom exception handling
I am wanting to handle exceptions in my PHP application myself.

When I throw an exception I am wanting to pass along a title to be used in the error page.

Can someone please link me to a good tutorial, or write a clear explanation of how the exception handling actually works (eg how to know what sort of exception you are dealing with, etc.

答:
First, I'd recommend to take a look at corresponding PHP manual page, it's great place to start. Also, you can take a look at Extending Exceptions page - there are some more info about standard exception class, and example of custom exception implementation.

If the question is, how to do some specific action if exception of particular type was thrown, then you just have to specify exception type in catch statement:

```<code>    try {
        //do some actions, which may throw exception
    } catch (MyException $e) {
        // Specific exception - do something with it
        // (access specific fields, if necessary)
    } catch (Exception $e) {
        // General exception - log exception details
        // and show user some general error message
    }
</code>```

Title: php custom exception handling

Body:
First, I'd recommend to take a look at corresponding PHP manual page, it's great place to start. Also, you can take a look at Extending Exceptions page - there are some more info about standard exception class, and example of custom exception implementation.

If the question is, how to do some specific action if exception of particular type was thrown, then you just have to specify exception type in catch statement:

    try {
        //do some actions, which may throw exception
    } catch (MyException $e) {
        // Specific exception - do something with it
        // (access specific fields, if necessary)
    } catch (Exception $e) {
        // General exception - log exception details
        // and show user some general error message
    }


问:
Intellij / Websphere run config says "address localhost:8880 is already in use"
This is my first attempt at creating a Websphere Local run configuration in Intellij and obviously I need some help.

First question: is Websphere supposed to be running when I run the configuration?

Second question: when I run the configuration and Webshpere is not running Intellij will say 'cannot ping localhost:8880', so probably Websphere should be running. When I start Websphere and then start the Intellij run config it says "address localhost:8880 is already in use" and then "Unable to open debugger port (127.0.0.1:62019): java.net.SocketException: 'socket closed'".

Here is my setup:

Third question: from the Websphere admin console I got that port 8880 is configured as the SOAP_CONNECTOR_ADDRESS. Is Intellij supposed to use that?

Thanks!

答:
To answer your question: no, if you want to start the server from IntelliJ, you should first check the server is stopped.

For solving the problem: Have you checked if WebSphere is running as a service automatically?

For doing it on Windows:

Open a "File Explorer" window

Right click on "My Computer"

Click on "Manage"

Click on "Services and Applications"

Click on "Services"

Look for "IBM WebSphere Application Server"

Check if it's running and stop it, change it to manual if you want to start server from IntelliJ without repeating this whole process everytime you log in Windows.