问:
How to create an animated, variable size accordion component in QtQuick / QML
I want to create an animated accordion-like element that expands on click. Here's how it should work.

When the user clicks one of the red rectangles, the green rectangle which is the actual content, should expand. I want this expansion to be animated. The height of the contents of the green rectangles could be different for each red header.

I have been able to implement the click-to-expand behavior, but there's no animation. Here is the code I currently have.

AccordionElement.qml

```<code>import QtQuick 2.5
import QtQuick.Layouts 1.1

ColumnLayout {
    id: rootElement

    property string title: ""
    property bool isOpen: false
    default property alias accordionContent: contentPlaceholder.data

    anchors.left: parent.left; anchors.right: parent.right

    // Header element
    Rectangle {
        id: accordionHeader
        color: "red"
        anchors.left: parent.left; anchors.right: parent.right
        height: 50
        MouseArea {
            anchors.fill: parent
            Text {
                text: rootElement.title
                anchors.centerIn: parent
            }
            cursorShape: Qt.PointingHandCursor
            onClicked: {
                rootElement.isOpen = !rootElement.isOpen
            }
        }
    }

    // This will get filled with the content
    ColumnLayout {
        id: contentPlaceholder
        visible: rootElement.isOpen
        anchors.left: parent.left; anchors.right: parent.right
    }
}
</code>```

And this is how it is used from the parent element:

Accordion.qml

```<code>ColumnLayout {
    Layout.margins: 5

    visible: true

    AccordionElement {
        title: "Title1"
        accordionContent: Rectangle {
            anchors.left: parent.left; anchors.right: parent.right
            height: 20
            color: "green"
        }
    }
    AccordionElement {
        title: "Title2"
        accordionContent: Rectangle {
            anchors.left: parent.left; anchors.right: parent.right
            height: 50
            color: "green"
        }
    }

    AccordionElement {
        title: "Title3"
        accordionContent: Rectangle {
            anchors.left: parent.left; anchors.right: parent.right
            height: 30
            color: "green"
        }
    }

    // Vertical spacer to keep the rectangles in upper part of column
    Item {
        Layout.fillHeight: true
    }
}
</code>```

This produces the following result (when all rectangles are expanded):

Ideally I would like the green rectangles to roll out of the red rectangles (like paper out of a printer). But I am stuck on how to do this. I have tried several approaches using the height property, and I got the green rectangle to disappear but the white space remains under the red rectangle.

Any help would be appreciated. Is there an approach I'm missing?

答:
Here is a quick and simple example:

```<code>// AccItem.qml
Column {
  default property alias item: ld.sourceComponent
  Rectangle {
    width: 200
    height: 50
    color: "red"
    MouseArea {
      anchors.fill: parent
      onClicked: info.show = !info.show
    }
  }
  Rectangle {
    id: info
    width: 200
    height: show ? ld.height : 0
    property bool show : false
    color: "green"
    clip: true
    Loader {
      id: ld
      y: info.height - height
      anchors.horizontalCenter: info.horizontalCenter
    }
    Behavior on height {
      NumberAnimation { duration: 200; easing.type: Easing.InOutQuad }
    }
  }
}

// Acc.qml
Column {
  spacing: 5
  AccItem {
    Rectangle {
      width: 50
      height: 50
      radius: 50
      color: "blue"
      anchors.centerIn: parent
    }
  }
  AccItem {
    Rectangle {
      width: 100
      height: 100
      radius: 50
      color: "yellow"
      anchors.centerIn: parent
    }
  }
  AccItem {
    Rectangle {
      width: 75
      height: 75
      radius: 50
      color: "cyan"
      anchors.centerIn: parent
    }
  }
}
</code>```

You are needlessly over-complicating it with the anchors and the layouts. It doesn't seem the problem calls for any of those.

Update: I slightly refined the implementation, compared to the initial one the content would actually slide out of the header as paper out of printer rather than simply being unveiled, and also removed the source of a false positive binding loop warning.

Body:
I want to create an animated accordion-like element that expands on click. Here's how it should work.

When the user clicks one of the red rectangles, the green rectangle which is the actual content, should expand. I want this expansion to be animated. The height of the contents of the green rectangles could be different for each red header.

I have been able to implement the click-to-expand behavior, but there's no animation. Here is the code I currently have.

AccordionElement.qml

import QtQuick 2.5
import QtQuick.Layouts 1.1

ColumnLayout {
    id: rootElement

    property string title: ""
    property bool isOpen: false
    default property alias accordionContent: contentPlaceholder.data

    anchors.left: parent.left; anchors.right: parent.right

    // Header element
    Rectangle {
        id: accordionHeader
        color: "red"
        anchors.left: parent.left; anchors.right: parent.right
        height: 50
        MouseArea {
            anchors.fill: parent
            Text {
                text: rootElement.title
                anchors.centerIn: parent
            }
            cursorShape: Qt.PointingHandCursor
            onClicked: {
                rootElement.isOpen = !rootElement.isOpen
            }
        }
    }

    // This will get filled with the content
    ColumnLayout {
        id: contentPlaceholder
        visible: rootElement.isOpen
        anchors.left: parent.left; anchors.right: parent.right
    }
}

And this is how it is used from the parent element:

Accordion.qml

ColumnLayout {
    Layout.margins: 5

    visible: true

    AccordionElement {
        title: "Title1"
        accordionContent: Rectangle {
            anchors.left: parent.left; anchors.right: parent.right
            height: 20
            color: "green"
        }
    }
    AccordionElement {
        title: "Title2"
        accordionContent: Rectangle {
            anchors.left: parent.left; anchors.right: parent.right
            height: 50
            color: "green"
        }
    }

    AccordionElement {
        title: "Title3"
        accordionContent: Rectangle {
            anchors.left: parent.left; anchors.right: parent.right
            height: 30
            color: "green"
        }
    }

    // Vertical spacer to keep the rectangles in upper part of column
    Item {
        Layout.fillHeight: true
    }
}

This produces the following result (when all rectangles are expanded):

Ideally I would like the green rectangles to roll out of the red rectangles (like paper out of a printer). But I am stuck on how to do this. I have tried several approaches using the height property, and I got the green rectangle to disappear but the white space remains under the red rectangle.

Any help would be appreciated. Is there an approach I'm missing?

Body:
Here is a quick and simple example:

// AccItem.qml
Column {
  default property alias item: ld.sourceComponent
  Rectangle {
    width: 200
    height: 50
    color: "red"
    MouseArea {
      anchors.fill: parent
      onClicked: info.show = !info.show
    }
  }
  Rectangle {
    id: info
    width: 200
    height: show ? ld.height : 0
    property bool show : false
    color: "green"
    clip: true
    Loader {
      id: ld
      y: info.height - height
      anchors.horizontalCenter: info.horizontalCenter
    }
    Behavior on height {
      NumberAnimation { duration: 200; easing.type: Easing.InOutQuad }
    }
  }
}

// Acc.qml
Column {
  spacing: 5
  AccItem {
    Rectangle {
      width: 50
      height: 50
      radius: 50
      color: "blue"
      anchors.centerIn: parent
    }
  }
  AccItem {
    Rectangle {
      width: 100
      height: 100
      radius: 50
      color: "yellow"
      anchors.centerIn: parent
    }
  }
  AccItem {
    Rectangle {
      width: 75
      height: 75
      radius: 50
      color: "cyan"
      anchors.centerIn: parent
    }
  }
}

You are needlessly over-complicating it with the anchors and the layouts. It doesn't seem the problem calls for any of those.

Update: I slightly refined the implementation, compared to the initial one the content would actually slide out of the header as paper out of printer rather than simply being unveiled, and also removed the source of a false positive binding loop warning.


来源: stackexchange

问:
How to exactly add L1 regularisation to tensorflow error function
Hey I am new to tensorflow and even after a lot of efforts could not add
L1 regularisation term to the error term

```<code>x = tf.placeholder("float", [None, n_input])
# Weights and biases to hidden layer
ae_Wh1 = tf.Variable(tf.random_uniform((n_input, n_hidden1), -1.0 / math.sqrt(n_input), 1.0 / math.sqrt(n_input)))
ae_bh1 = tf.Variable(tf.zeros([n_hidden1]))
ae_h1 = tf.nn.tanh(tf.matmul(x,ae_Wh1) + ae_bh1)

ae_Wh2 = tf.Variable(tf.random_uniform((n_hidden1, n_hidden2), -1.0 / math.sqrt(n_hidden1), 1.0 / math.sqrt(n_hidden1)))
ae_bh2 = tf.Variable(tf.zeros([n_hidden2]))
ae_h2 = tf.nn.tanh(tf.matmul(ae_h1,ae_Wh2) + ae_bh2)

ae_Wh3 = tf.transpose(ae_Wh2)
ae_bh3 = tf.Variable(tf.zeros([n_hidden1]))
ae_h1_O = tf.nn.tanh(tf.matmul(ae_h2,ae_Wh3) + ae_bh3)

ae_Wh4 = tf.transpose(ae_Wh1)
ae_bh4 = tf.Variable(tf.zeros([n_input]))
ae_y_pred = tf.nn.tanh(tf.matmul(ae_h1_O,ae_Wh4) + ae_bh4)

ae_y_actual = tf.placeholder("float", [None,n_input])
meansq = tf.reduce_mean(tf.square(ae_y_actual - ae_y_pred))
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(meansq)
</code>```

after this I run the above graph using

```<code>init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

n_rounds = 100
batch_size = min(500, n_samp)
for i in range(100):
    sample = np.random.randint(n_samp, size=batch_size)
    batch_xs = input_data[sample][:]
    batch_ys = output_data_ae[sample][:]
    sess.run(train_step, feed_dict={x: batch_xs, ae_y_actual:batch_ys})
</code>```

Above is the code for a 4 layer autoencoder, "meansq" is my squared loss function. How can I add L1 reguarisation for the weight matrix (tensors) in the network?

答: You can also use tf.slim.l1_regularizer() from the slim losses.</p>

ContentLicense: CC BY-SA 3.0

Body:
Hey I am new to tensorflow and even after a lot of efforts could not add
L1 regularisation term to the error term

x = tf.placeholder("float", [None, n_input])
# Weights and biases to hidden layer
ae_Wh1 = tf.Variable(tf.random_uniform((n_input, n_hidden1), -1.0 / math.sqrt(n_input), 1.0 / math.sqrt(n_input)))
ae_bh1 = tf.Variable(tf.zeros([n_hidden1]))
ae_h1 = tf.nn.tanh(tf.matmul(x,ae_Wh1) + ae_bh1)

ae_Wh2 = tf.Variable(tf.random_uniform((n_hidden1, n_hidden2), -1.0 / math.sqrt(n_hidden1), 1.0 / math.sqrt(n_hidden1)))
ae_bh2 = tf.Variable(tf.zeros([n_hidden2]))
ae_h2 = tf.nn.tanh(tf.matmul(ae_h1,ae_Wh2) + ae_bh2)

ae_Wh3 = tf.transpose(ae_Wh2)
ae_bh3 = tf.Variable(tf.zeros([n_hidden1]))
ae_h1_O = tf.nn.tanh(tf.matmul(ae_h2,ae_Wh3) + ae_bh3)

ae_Wh4 = tf.transpose(ae_Wh1)
ae_bh4 = tf.Variable(tf.zeros([n_input]))
ae_y_pred = tf.nn.tanh(tf.matmul(ae_h1_O,ae_Wh4) + ae_bh4)

ae_y_actual = tf.placeholder("float", [None,n_input])
meansq = tf.reduce_mean(tf.square(ae_y_actual - ae_y_pred))
train_step = tf.train.GradientDescentOptimizer(0.05).minimize(meansq)

after this I run the above graph using

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

n_rounds = 100
batch_size = min(500, n_samp)
for i in range(100):
    sample = np.random.randint(n_samp, size=batch_size)
    batch_xs = input_data[sample][:]
    batch_ys = output_data_ae[sample][:]
    sess.run(train_step, feed_dict={x: batch_xs, ae_y_actual:batch_ys})

Above is the code for a 4 layer autoencoder, "meansq" is my squared loss function. How can I add L1 reguarisation for the weight matrix (tensors) in the network?


问:
How can I programatically select a drop down option using Ember?
This is my sample drop down

```<code><select name="newType" class="parts-select full-width-combo" onchange={{action "loadFilter" value="target.value" }}>
            <option value="" selected  hidden >Select </option>
            {{#each model as |item|}}
                <option value="{{item.id}}">{{item.description}}</option>
            {{/each}}
 </select>
</code>```

from the relevant template action I wanted to set this selected item dynamically.

As an example it default selected by "Select" and then based on some button click on that page and need to set my selected option to other selected option to be selected.
I am not using any plugin and I can't do it here.

答:
I used mut helper to set directly to selectedItemId property. so onchange it will update it automaticaly. also used ember-truth-helper for eq helper to decide particular item is selected or not.

```<code><select name="newType" class="parts-select full-width-combo" onchange={{action (mut selectedItemId) value="target.value" }}>
            <option value="" selected  hidden >Select </option>
            {{#each model as |item|}}
                <option value="{{item.id}}" selected={{if (eq item.id selectedItemId) 'true'}}>{{item.description}}</option>
            {{/each}}
 </select>
</code>```

Body:
This is my sample drop down

<select name="newType" class="parts-select full-width-combo" onchange={{action "loadFilter" value="target.value" }}>
            <option value="" selected  hidden >Select </option>
            {{#each model as |item|}}
                <option value="{{item.id}}">{{item.description}}</option>
            {{/each}}
 </select>

from the relevant template action I wanted to set this selected item dynamically.

As an example it default selected by "Select" and then based on some button click on that page and need to set my selected option to other selected option to be selected.
I am not using any plugin and I can't do it here.

Body:
I used mut helper to set directly to selectedItemId property. so onchange it will update it automaticaly. also used ember-truth-helper for eq helper to decide particular item is selected or not.

<select name="newType" class="parts-select full-width-combo" onchange={{action (mut selectedItemId) value="target.value" }}>
            <option value="" selected  hidden >Select </option>
            {{#each model as |item|}}
                <option value="{{item.id}}" selected={{if (eq item.id selectedItemId) 'true'}}>{{item.description}}</option>
            {{/each}}
 </select>


问:
Get variables that have been created inside a function
I have created a function (which is quite long) that I have saved in a .txt file.
It works well (I use source(<  >) to access it).
My problem is that I have created a few variables in that function
ie:

```<code>myfun<-function(a,b) {
Var1=....
Var2=Var1 + ..
}
</code>```

Now I want to get those variables.
When I include return() inside the function, its fine: the value comes up on the screen, but when I type Var1 outside the function, I have an error message "the object cannot be found".
I am new to R, but I was thinking it might be because "myfun" operates in a different envrionment than the global one, but when I did

```<code>environment()
environment: R_GlobalEnv>
environment(myfun1)
environment: R_GlobalEnv>
</code>```

It seems to me the problem is elsewhere...

Any idea?

Thanks

答:
I realize this answer is more than 3 years old but I believe the option you are looking for is as follows:

```<code>myfun <- function(a,b) {
  Var1 = (a + b) / 2   # do whatever logic you have to do here...
  Var2 <<- Var1 + a    # then output result to Global Environment with the "<<-" object.
}
</code>```

The double "<<-" assignment operator will output "Var2" to the global environment and you can then use or reference it however you like without having to use "return()" inside your function.

Body:
I have created a function (which is quite long) that I have saved in a .txt file.
It works well (I use source(<  >) to access it).
My problem is that I have created a few variables in that function
ie:

myfun<-function(a,b) {
Var1=....
Var2=Var1 + ..
}

Now I want to get those variables.
When I include return() inside the function, its fine: the value comes up on the screen, but when I type Var1 outside the function, I have an error message "the object cannot be found".
I am new to R, but I was thinking it might be because "myfun" operates in a different envrionment than the global one, but when I did

environment()
environment: R_GlobalEnv>
environment(myfun1)
environment: R_GlobalEnv>

It seems to me the problem is elsewhere...

Any idea?

Thanks

Body:
I realize this answer is more than 3 years old but I believe the option you are looking for is as follows:

myfun <- function(a,b) {
  Var1 = (a + b) / 2   # do whatever logic you have to do here...
  Var2 <<- Var1 + a    # then output result to Global Environment with the "<<-" object.
}

The double "<<-" assignment operator will output "Var2" to the global environment and you can then use or reference it however you like without having to use "return()" inside your function.

ContentLicense: CC BY-SA 4.0


问:
How can I create arrays of suitable candidates based on certain criteria?
So to brief you on the question:

I have a number of employees field in a form.

Employees have a salary and the day rate is calculated using (salary / 260)

Assuming employees work a fixed standard day

A task has a certain budget and a date range (start to end - e.g. 29/03/2017 to 31/03/2017)

A task also requires a fixed amount of employees (i.e. 3)

Now with those details in mind, I want to get a list of x employees (the fixed amount, i.e. 3) for which those employee's salaries match the date range of the project, and also slot into the budget.

I started doing this as follows, but have no idea how to continue further:

```<code>$employees = array(
    0 => array(
        'id' => 1,
        'salary' => 22000
    );
);
$startDate = some_date_here;
$endDate = some_date_here;

foreach($employees as &$user) {
    $dayRate = round($user['salary'] / 260, 2);
}
</code>```

EDIT:

Using http://php.net/manual/en/function.date-diff.php#117691, I managed to find the days between the dates of a project as follows (code update):

```<code>function days_diff($d1, $d2) {
    $x1 = days($d1);
    $x2 = days($d2);
        if ($x1 && $x2) {
        return abs($x1 - $x2);
    }
}

function days($x) {
    if (get_class($x) != 'DateTime') {
        return false;
    }
        $y = $x->format('Y') - 1;
    $days = $y * 365;
    $z = (int)($y / 4);
    $days += $z;
    $z = (int)($y / 100);
    $days -= $z;
    $z = (int)($y / 400);
    $days += $z;
    $days += $x->format('z');
        return $days;
}

$startDate = DateTime::createFromFormat('Y-m-d', $startDate);
$endDate = DateTime::createFromFormat('Y-m-d', $endDate);
$projectDays = days_diff($startDate, $endDate);
</code>```

答:
I think you can do this by the following code.

```<code>            $startDate = some_date_here;
            $endDate = some_date_here;
            $noOfDays = calculate_using_end-start;

            $employeeRate = [];
            $noOfEmployeesRequired = 3;

            foreach($employees as $index=>$user) {
                $dayRate = round($user['salary'] / 260, 2);
                $totalRate = $dayRate*$noOfDays;
                $employeeRate[$user['id']] = $totalRate;
            }
</code>```

Now I have all employees Cost hence i sort it and find the cheapest solution

```<code>            sort($employeeRate);
            $output = array();
            $counter = 0;

            foreach($employeeRate as $id=>$emp) {
                array_push($output, $id);
                $counter++;
                if($counter == $noOfEmployeesRequired) {
                    break;
                }
            }
</code>```

Body:
So to brief you on the question:

I have a number of employees field in a form.

Employees have a salary and the day rate is calculated using (salary / 260)

Assuming employees work a fixed standard day

A task has a certain budget and a date range (start to end - e.g. 29/03/2017 to 31/03/2017)

A task also requires a fixed amount of employees (i.e. 3)

Now with those details in mind, I want to get a list of x employees (the fixed amount, i.e. 3) for which those employee's salaries match the date range of the project, and also slot into the budget.

I started doing this as follows, but have no idea how to continue further:

$employees = array(
    0 => array(
        'id' => 1,
        'salary' => 22000
    );
);
$startDate = some_date_here;
$endDate = some_date_here;

foreach($employees as &$user) {
    $dayRate = round($user['salary'] / 260, 2);
}

EDIT:

Using http://php.net/manual/en/function.date-diff.php#117691, I managed to find the days between the dates of a project as follows (code update):

function days_diff($d1, $d2) {
    $x1 = days($d1);
    $x2 = days($d2);
        if ($x1 && $x2) {
        return abs($x1 - $x2);
    }
}

function days($x) {
    if (get_class($x) != 'DateTime') {
        return false;
    }
        $y = $x->format('Y') - 1;
    $days = $y * 365;
    $z = (int)($y / 4);
    $days += $z;
    $z = (int)($y / 100);
    $days -= $z;
    $z = (int)($y / 400);
    $days += $z;
    $days += $x->format('z');
        return $days;
}

$startDate = DateTime::createFromFormat('Y-m-d', $startDate);
$endDate = DateTime::createFromFormat('Y-m-d', $endDate);
$projectDays = days_diff($startDate, $endDate);

Body:
I think you can do this by the following code.

            $startDate = some_date_here;
            $endDate = some_date_here;
            $noOfDays = calculate_using_end-start;

            $employeeRate = [];
            $noOfEmployeesRequired = 3;

            foreach($employees as $index=>$user) {
                $dayRate = round($user['salary'] / 260, 2);
                $totalRate = $dayRate*$noOfDays;
                $employeeRate[$user['id']] = $totalRate;
            }

Now I have all employees Cost hence i sort it and find the cheapest solution

            sort($employeeRate);
            $output = array();
            $counter = 0;

            foreach($employeeRate as $id=>$emp) {
                array_push($output, $id);
                $counter++;
                if($counter == $noOfEmployeesRequired) {
                    break;
                }
            }


问:
Object oriented design in javascript and 'this' pointer
I am creating a object in javascript like this

```<code>function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()
</code>```

What is the proper way to pass the this pointer to an anonymous function?

答:
Adding the following code to the end of your snippet and running it correctly alerts '1':

```<code>mything.b();
alert(mything.myvar1);
</code>```

What were you expecting? Perhaps you're incorrectly invoking mything.b() ?

ContentLicense: CC BY-SA 2.5

Body:
I am creating a object in javascript like this

function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()

What is the proper way to pass the this pointer to an anonymous function?

Body:
Adding the following code to the end of your snippet and running it correctly alerts '1':

mything.b();
alert(mything.myvar1);

What were you expecting? Perhaps you're incorrectly invoking mything.b() ?


问:
Getting HttpServletRequest using CDI
Is this right way to get HttpServletRequest using CDI in a non Bean

HttpServletRequest request = CDI.current().select(HttpServletRequest.class).get();

Edit :

I want to access the HttpServletRequest for logging session session information like username etc.

答:
To acquire a properly managed instance of the request, do this instead:

```<code>@Context
private HttpServletRequest httpRequest;
</code>```

Source: Injection of HttpServletRequest

Title: Getting HttpServletRequest using CDI

Body:
To acquire a properly managed instance of the request, do this instead:

@Context
private HttpServletRequest httpRequest;

Source: Injection of HttpServletRequest


问:
Store WSDL file in Android Project and Parse this to create Retrofit API
i only have a .wsdl file locally and i only find examples for android to create a soap service with retrofit2 with an url. Now my question is what is best practice to store the .wsdl file in the project (is this a raw file?) and parse this for example with ksoap to create my api with retrofit? Any body some ideas?</p>

答: The WSDL file is a webservice file, therefore it should seat on your server, you can deploy such webservices using Tomcat or JBoss applications. So you  don't want to 'store' the wsdl file in your application, it should seat on your server. And you shouldn't 'parse' a wsdl file, its function is moving data from your client to server and viceversa. If doing what you are suggesting was possible(parsing with ksoap to create my api with retrofit), then it would be a bad programming practise due to redudancy. Retrofit works similarly to soap difference being retrofit makes use of JSON while SOAP makes use of XML. Try looking at my answer here Call a soap webservice in android to understand how android interacts with soap webservice</p>


问:
Powershell how to add new line after certain string
I am very new to scripting. I am trying to solve one problem and I was looking at windows batch and powershell. I have found this but I dont know, why it is not working:

I have input.txt file with this content:

```<code><a> TEXT </a>
<c> text asdrtlj </c>
<a> another text </a>
</code>```

I want to add new line before every , so I tried this:

```<code>powershell -Command "(gc input.txt) -replace '<a>', '`r`n<a>' | Out-File output.txt"
</code>```

That adding of newline doesnt work. Can you help me please?

PS: I've found a lot of complicated codes while searching the solution and I haven't understood them yet so if you recommend me some good tutorials where to start with this languages I will appreciate it.

答:
We need more quotation marks.

```<code>powershell.exe -command "(gc 1_105.jpg) -replace '<a>', """"`r`n<a>""""|Out-File output.txt"
</code>```

Or how is about a small refactoring?

```<code>powershell.exe -Command "gc input.txt|%{$_.replace('<a>',[environment]::newline+'<a>')}|Out-File output.txt"
</code>```

Body:
I am very new to scripting. I am trying to solve one problem and I was looking at windows batch and powershell. I have found this but I dont know, why it is not working:

I have input.txt file with this content:

 TEXT
<c> text asdrtlj </c>
 another text

I want to add new line before every , so I tried this:

powershell -Command "(gc input.txt) -replace '', '`r`n' | Out-File output.txt"

That adding of newline doesnt work. Can you help me please?

PS: I've found a lot of complicated codes while searching the solution and I haven't understood them yet so if you recommend me some good tutorials where to start with this languages I will appreciate it.

Body:
We need more quotation marks.

powershell.exe -command "(gc 1_105.jpg) -replace '<a>', """"`r`n<a>""""|Out-File output.txt"

Or how is about a small refactoring?

powershell.exe -Command "gc input.txt|%{$_.replace('<a>',[environment]::newline+'<a>')}|Out-File output.txt"


问:
Why i cant see this image button on IE8 with this CSS?
So, this is the html code for the button

```<code><input type="submit" name="logueo" value="log" id="sendbu"/>
</code>```

And this is the css style

```<code>#sendbu     { width: 50px; height: 34px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 12px; background: transparent url(lock.png) no-repeat center top; border: 0;   text-indent: -1000em; cursor: pointer; cursor: hand; }
</code>```

All this works on Chrome and Firefox, but in IE the button seams to dont exist. Thanks for the help.

答: Try: background: transparent url(lock.png) center top no-repeat;, and also the 'name' and 'id' properties should match, different flavours of Browser use 'name' differently.

Body:
So, this is the html code for the button

<input type="submit" name="logueo" value="log" id="sendbu"/>

And this is the css style

#sendbu     { width: 50px; height: 34px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 12px; background: transparent url(lock.png) no-repeat center top; border: 0;   text-indent: -1000em; cursor: pointer; cursor: hand; }

All this works on Chrome and Firefox, but in IE the button seams to dont exist. Thanks for the help.


问:
Segmentation Fault in linkedlist and debugging options for Linux
full code: ( https://github.com/martin-varbanov96/fmi_summer_2017/tree/master/daa/bfs )

So I have to do a graph BFS, but first I have to make a fully working linkedList and I have a problem with the segmentation fault.

The real problem here is that I am using Linux and trying to learn vim and so I have no good way of debugging and I have to use gdb.

The general problem is that I have a node struct and I want to assign it a value but it gives a Segmentation fault. Here is the node:

```<code>struct node{
        int value;
        node* next;
};
</code>```

and than in the main function, program crashes in the assigment:

```<code>int main(){
        node* b;
        b->value=1;
        linkedList a;
         ...
</code>```

this is the gdb result:

```<code>Wed Mar 29; 15:59:29; marton;~/documents/github/fmi_summer_2017/daa/bfs ;  $  gdb a.out
GNU gdb (GDB; openSUSE Leap 42.1) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://bugs.opensuse.org/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x4008f5: file main.cpp, line 5.
Starting program: /home/marton/documents/github/fmi_summer_2017/daa/bfs/a.out
step
Temporary breakpoint 1, main () at main.cpp:5
5               b->value=1;
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00000000004008f9 in main () at main.cpp:5
5               b->value=1;
(gdb)

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)
</code>```

So my question is what is the problem with my code and what do I need to do to fix it and is there a better way to debug my things in the future?

EDIT:

changes main, as said:

```<code>int main(){
        node* b=new node();
        b->value=1;
</code>```

gdb:

```<code>Temporary breakpoint 1, main () at main.cpp:4
4               node* b=new node();
(gdb) step
operator new (sz=16) at ../../../../libstdc++-v3/libsupc++/new_op.cc:43
43      ../../../../libstdc++-v3/libsupc++/new_op.cc: No such file or directory.
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
43      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
50      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)

__GI___libc_malloc (bytes=16) at malloc.c:2897
2897    malloc.c: No such file or directory.
(gdb)
2902    in malloc.c
(gdb)
2903    in malloc.c
(gdb)
2906    in malloc.c
(gdb)
2908    in malloc.c
(gdb)
_int_malloc (av=av@entry=0x7ffff753a620 <main_arena>, bytes=bytes@entry=16) at malloc.c:3325
3325    in malloc.c
(gdb)
3355    in malloc.c
(gdb)
3359    in malloc.c
(gdb)
3373    in malloc.c
(gdb)
3375    in malloc.c
</code>```

Real problem is how to debug properly with vim and linux

答:
You are using a non allocated structure. malloc (C) or new (C++) your structure before using it</p>

```<code>int main(){
    node* b;
    b = malloc(sizeof(node));
    b->value=1;
    linkedList a;
}

int main(){
    node* b = new node();
    b = malloc(sizeof(node));
    b->value=1;
    linkedList a;
}
</code>```

Body:
full code: ( https://github.com/martin-varbanov96/fmi_summer_2017/tree/master/daa/bfs )

So I have to do a graph BFS, but first I have to make a fully working linkedList and I have a problem with the segmentation fault.

The real problem here is that I am using Linux and trying to learn vim and so I have no good way of debugging and I have to use gdb.

The general problem is that I have a node struct and I want to assign it a value but it gives a Segmentation fault. Here is the node:

struct node{
        int value;
        node* next;
};

and than in the main function, program crashes in the assigment:

int main(){
        node* b;
        b->value=1;
        linkedList a;
         ...

this is the gdb result:

Wed Mar 29; 15:59:29; marton;~/documents/github/fmi_summer_2017/daa/bfs ;  $  gdb a.out
GNU gdb (GDB; openSUSE Leap 42.1) 7.11.1
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://bugs.opensuse.org/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...done.
(gdb) start
Temporary breakpoint 1 at 0x4008f5: file main.cpp, line 5.
Starting program: /home/marton/documents/github/fmi_summer_2017/daa/bfs/a.out
step
Temporary breakpoint 1, main () at main.cpp:5
5               b->value=1;
(gdb) step

Program received signal SIGSEGV, Segmentation fault.
0x00000000004008f9 in main () at main.cpp:5
5               b->value=1;
(gdb)

Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb)

So my question is what is the problem with my code and what do I need to do to fix it and is there a better way to debug my things in the future?

EDIT:

changes main, as said:

int main(){
        node* b=new node();
        b->value=1;

gdb:

Temporary breakpoint 1, main () at main.cpp:4
4               node* b=new node();
(gdb) step
operator new (sz=16) at ../../../../libstdc++-v3/libsupc++/new_op.cc:43
43      ../../../../libstdc++-v3/libsupc++/new_op.cc: No such file or directory.
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
43      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
48      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)
50      in ../../../../libstdc++-v3/libsupc++/new_op.cc
(gdb)

__GI___libc_malloc (bytes=16) at malloc.c:2897
2897    malloc.c: No such file or directory.
(gdb)
2902    in malloc.c
(gdb)
2903    in malloc.c
(gdb)
2906    in malloc.c
(gdb)
2908    in malloc.c
(gdb)
_int_malloc (av=av@entry=0x7ffff753a620 <main_arena>, bytes=bytes@entry=16) at malloc.c:3325
3325    in malloc.c
(gdb)
3355    in malloc.c
(gdb)
3359    in malloc.c
(gdb)
3373    in malloc.c
(gdb)
3375    in malloc.c

Real problem is how to debug properly with vim and linux

Body:
You are using a non allocated structure. malloc (C) or new (C++) your structure before using it

int main(){
    node* b;
    b = malloc(sizeof(node));
    b->value=1;
    linkedList a;
}

int main(){
    node* b = new node();
    b = malloc(sizeof(node));
    b->value=1;
    linkedList a;
}


问:
Print sum of numbers in Python Script
I've been searching for a while and haven't been able to figure this out.

I'm running Kali Linux and I'm trying to run a very simple script and I'm not getting the output I would expect. I used to programing python on windows and the switch to Kali and I can't get this basic script to give me my desired output.

```<code>a = 1
b = 2
a + b
</code>```

This should give me the output of 3, however I don't get any output.

When I run:

```<code>a = 1
b = 2
a + b

print "test %s" %a
</code>```

I get the output:

```<code>test 1
</code>```

Any help is greatly appreciated

答:
in your code you have two variable a and b assigned with some value and then u are adding a and b, but it has to be stored somewhere; a+b doesn't mean the sum of a and b  goes into a!

```<code>a=10;
b=20;
c=a+b;

print c
</code>```

or

```<code>a=10;
b=20;
c=a+b;
print "test %d" %c
</code>```

or

```<code>    a=10;
    b=20;
    c=a+b;
    print "test %d" %(a+b)
</code>```

Title: Print sum of numbers in Python Script

Body:
I've been searching for a while and haven't been able to figure this out.

I'm running Kali Linux and I'm trying to run a very simple script and I'm not getting the output I would expect. I used to programing python on windows and the switch to Kali and I can't get this basic script to give me my desired output.

a = 1
b = 2
a + b

This should give me the output of 3, however I don't get any output.

When I run:

a = 1
b = 2
a + b

print "test %s" %a

I get the output:

test 1

Any help is greatly appreciated

Body:
in your code you have two variable a and b assigned with some value and then u are adding a and b, but it has to be stored somewhere; a+b doesn't mean the sum of a and b  goes into a!

a=10;
b=20;
c=a+b;

print c

or

a=10;
b=20;
c=a+b;
print "test %d" %c

or

    a=10;
    b=20;
    c=a+b;
    print "test %d" %(a+b)


问:
How to add a generic dependency injection
Working on a read-only api service and making use of generics to package the operation into convention based process.

Repository interface:

```<code>public interface IRepository<TIdType,TEntityType> where TEntityType:class {
   Task<EntityMetadata<TIdType>> GetMetaAsync();
}
</code>```

Repository implementation:

```<code>public class Repository<TIdType,TEntityType> : IRepository<TIdType,TEntityType> where TEntityType:class {
   public Repository(string connectionString) { // initialization }
   public async Tas<EntityMetadata<TIdType>> GetMetaAsync() { // implementation   }
}
</code>```

In Startup.cs -> ConfigureServices :

```<code>services.AddSingleton<IRepository<int, Employee>> ( p=> new Repository<int, Employee>(connectionString));
services.AddSingleton<IRepository<int, Department>> ( p=> new Repository<int, Department>(connectionString));
// and so on
</code>```

Controller:

```<code>public class EmployeeController : Controller {
   public EmployeeController(IRepository<int,Employee> repo) {//stuff}
}
</code>```

I am currently repeating the repository implmentation for all types of entity types in the ConfigureServices. Is there a way to make this generic too?

```<code>services.AddSingleton<IRepository<TIdType, TEntityType>> ( p=> new Repository<TIdType, TEntityType>(connectionString));
</code>```

so in the controller constructor call can automatically get the relevant repository?

Update 1: Not a duplicate:

The repository implementation does not have default constructor

Because it does not have default constructor, I cannot provide the solution given in the linked question.

When trying services.AddScoped(typeof(IRepository<>), ...) I am getting error Using the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments

答:
Since this question is still not properly marked as duplicate: The way to register a Generic class:

```<code>services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>));
</code>```

now you can resolve it in the following way:

```<code>serviceProvider.GetService(typeof(IRepository<A,B>));
// or: with extensionmethod
serviceProvider.GetService<IRepository<A,B>>();
</code>```

Body:
Working on a read-only api service and making use of generics to package the operation into convention based process.

Repository interface:

public interface IRepository<TIdType,TEntityType> where TEntityType:class {
   Task<EntityMetadata<TIdType>> GetMetaAsync();
}

Repository implementation:

public class Repository<TIdType,TEntityType> : IRepository<TIdType,TEntityType> where TEntityType:class {
   public Repository(string connectionString) { // initialization }
   public async Tas<EntityMetadata<TIdType>> GetMetaAsync() { // implementation   }
}

In Startup.cs -> ConfigureServices :

services.AddSingleton<IRepository<int, Employee>> ( p=> new Repository<int, Employee>(connectionString));
services.AddSingleton<IRepository<int, Department>> ( p=> new Repository<int, Department>(connectionString));
// and so on

Controller:

public class EmployeeController : Controller {
   public EmployeeController(IRepository<int,Employee> repo) {//stuff}
}

I am currently repeating the repository implmentation for all types of entity types in the ConfigureServices. Is there a way to make this generic too?

services.AddSingleton<IRepository<TIdType, TEntityType>> ( p=> new Repository<TIdType, TEntityType>(connectionString));

so in the controller constructor call can automatically get the relevant repository?

Update 1: Not a duplicate:

The repository implementation does not have default constructor

Because it does not have default constructor, I cannot provide the solution given in the linked question.

When trying services.AddScoped(typeof(IRepository<>), ...) I am getting error Using the generic type 'IRepostiory<TIdType,TEntityType>' requires 2 type arguments

Body:
Since this question is still not properly marked as duplicate: The way to register a Generic class:

services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>));

now you can resolve it in the following way:

serviceProvider.GetService(typeof(IRepository<A,B>));
// or: with extensionmethod
serviceProvider.GetService<IRepository<A,B>>();


问:
laravel 5.3 returning notfoundexception when trying to load a woff / ttf file from public directory
trying to access

http://dev.myapp.org/caup_api/css/font-awesome/fonts/fontawesome-webfont.woff?v=4.7.0

return

```<code>NotFoundHttpException in RouteCollection.php line 161:
</code>```

accessing

http://dev.myapp.org/caup_api/css/font-awesome/fonts/fontawesome-webfont.css?v=4.7.0

returns 404. 404 is expected, as the file is not a CSS file. but notfoundhttpexception is not

why is that and why cannot I load fonts via public folder?

lets make it clear:

the font file is there

not found http exception is only expected for proper routes, not for files in the public folder. It seems that .woff is not trying to reach a file in the public folder. Is it an nginx config problem?

答:
actually have a subfolder installation of laravel

had to fix the following lines marked with ##, where caup_api is my subfolder

```<code>    location ~ /caup_api {
##      try_files /caup_api/$uri /caup_api/$uri/ /caup_api/index.php?q=$uri&$args;
try_files $uri $uri/ /caup_api/index.php?$query_string;

    }
</code>```

Body:
trying to access

http://dev.myapp.org/caup_api/css/font-awesome/fonts/fontawesome-webfont.woff?v=4.7.0

return

NotFoundHttpException in RouteCollection.php line 161:

accessing

http://dev.myapp.org/caup_api/css/font-awesome/fonts/fontawesome-webfont.css?v=4.7.0

returns 404. 404 is expected, as the file is not a CSS file. but notfoundhttpexception is not

why is that and why cannot I load fonts via public folder?

lets make it clear:

the font file is there

not found http exception is only expected for proper routes, not for files in the public folder. It seems that .woff is not trying to reach a file in the public folder. Is it an nginx config problem?

Body:
actually have a subfolder installation of laravel

had to fix the following lines marked with ##, where caup_api is my subfolder

    location ~ /caup_api {
##      try_files /caup_api/$uri /caup_api/$uri/ /caup_api/index.php?q=$uri&$args;
try_files $uri $uri/ /caup_api/index.php?$query_string;

    }


问:
ASP.NET MVC - redirect after form submit
I have a ASP.NET MVC website and a "Configuration" view with a form.

When I submit the form, I would like to do some stuff and then Redirect to my "Initialization" ViewResult... How to do it ?

My form :

```<code>@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "Config" }))
{
     // Some fields

     <input type="submit" value="Save" />

}
</code>```

then, the "Save" action :

```<code>[HttpPost]
[ValidateAntiForgeryToken()]
public async Task<RedirectToRouteResult> Save(Config websiteConfiguration)
    {
        // Do some stuff

        bool ok = await myMethod();

        if(ok)
        {
            return RedirectToAction("Initialization");
        }

    }
</code>```

I tried other possibilities but I don't manage to get it work...

Up, I still have the problem...

答:
Not sure if this issue was with an earlier version of MVC, but I have often forgotten that the [HttpPost] label may be placed above an ActionResult in the controller and not just above a JsonResult.

So the simplest MVC-style answer would be just use Html.BeginForm and post to the ActionResult (with the [HttpPost] attribute), wherein you execute your logic, then call RedirectToAction at end after you have handled the post controller side.

This seems far easier than all the client-side fiddles, e.g. window.location.href = '' etc...

Body:
I have a ASP.NET MVC website and a "Configuration" view with a form.

When I submit the form, I would like to do some stuff and then Redirect to my "Initialization" ViewResult... How to do it ?

My form :

@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "Config" }))
{
     // Some fields

     <input type="submit" value="Save" />

}

then, the "Save" action :

[HttpPost]
[ValidateAntiForgeryToken()]
public async Task<RedirectToRouteResult> Save(Config websiteConfiguration)
    {
        // Do some stuff

        bool ok = await myMethod();

        if(ok)
        {
            return RedirectToAction("Initialization");
        }

    }

I tried other possibilities but I don't manage to get it work...

Up, I still have the problem...


问:
Queuing theory for programmers?
After being burnt several times on things that seemed "obviously fast enough" but sucked performance-wise under load, I'm starting to think that my "gut feeling" might be not enough when doing capacity planning, and some theoretical background is necessary.

So - community, can you point me to good resources on applications of queuing theory to programming?

Whatever - articles, case studies, books.

I found a couple of books that seem to be relevant so far; I'd be happy to hear your opinions on them, if you're familiar:

Software Performance and Scalability: A Quantitative Approach

The Art of Computer Systems Performance Analysis: Techniques for Experimental Design, Measurement, Simulation, and Modeling

Performance by Design: Computer Capacity Planning By Example

答:
Jain is classic, but there's some good modern stuff too.
Assuming you're a mathie, anything by Neil Gunther is
good: Guerrilla Capacity Planning is his most recent,
preceded by Analyzing Computer System Performance with Perl::PDQ

Bob Sneed and I are working on a more engineering-oriented
one, but I'm moving a little slow (;-))

--dave

Title: Queuing theory for programmers?


问:
How to parse only one option of XML in PHP?
Hi I want to parse in php

and read only one option of each line. How can I do this?

I tried:

```<code><?php
$xml = file_get_contents("file.xml");
echo $xml;
?>
</code>```

But this read the full xml. I need only one option of the xml

答:
Try this

<? php $xml = simplexml_load_file("path/to/your/file/file.xml"); ?>

Convert your object into array like this

```<code>$array= (array) $xml;
</code>```

after that you can do this

```<code>$option = $array['OptionName'];
</code>```

Body:
Hi I want to parse in php

and read only one option of each line. How can I do this?

I tried:

<?php
$xml = file_get_contents("file.xml");
echo $xml;
?>

But this read the full xml. I need only one option of the xml

Body:
Try this

<? php $xml = simplexml_load_file("path/to/your/file/file.xml"); ?>

Convert your object into array like this

$array= (array) $xml;

after that you can do this

$option = $array['OptionName'];


问:
Change of property with numbered name in Java
I have a huge field of graphic elements in my GUI, and I need to change their property according to value I have.

I want to avoid writing out switch, although it will work, it seems stupid.
I have graphic properties in HBox named r0 - r200, and I want to change opacity of element corresponding with returned value from other functions.

Is there some clever way, better than:

```<code>switch(note.offGraphic()){

    case 0:
        flat6.setOpacity(1);
        break;
    case 1:
        flat5.setOpacity(1);
        break;
    case 2:
        flat4.setOpacity(1);
        break;
    case 3:
        flat3.setOpacity(1);
        break;
    case 4:
        flat2.setOpacity(1);
        break;
    case 5:
        flat1.setOpacity(1);
    case 6:
        ok.setOpacity(1);
        break;
` and on and on
</code>```

答:
That depends on what flat1 etc. are but if they are instance of some class or interface you could use a map.

(Edit: it seems you're using javafx.scene.Node you probably don't need any additional interface.)

Assuming your flats etc. are instances of javafx.scene.Node you could just use them in a map:

```<code>Map<Integer, Node> map = ...;
map.put( 0, flat6 );
map.put( 1, flat5 );
...
map.put( 6, ok );
...
</code>```

Then use it like this:

```<code>Node n = map.get( note.offGraphic() );
if( n != null) {
  n.setOpacity(1);
}
</code>```

Alternatively, your box could display a representation of those elements, i.e. you just provide a list of elements, select one and call setOpacity(1) on it.

Body:
I have a huge field of graphic elements in my GUI, and I need to change their property according to value I have.

I want to avoid writing out switch, although it will work, it seems stupid.
I have graphic properties in HBox named r0 - r200, and I want to change opacity of element corresponding with returned value from other functions.

Is there some clever way, better than:

switch(note.offGraphic()){

    case 0:
        flat6.setOpacity(1);
        break;
    case 1:
        flat5.setOpacity(1);
        break;
    case 2:
        flat4.setOpacity(1);
        break;
    case 3:
        flat3.setOpacity(1);
        break;
    case 4:
        flat2.setOpacity(1);
        break;
    case 5:
        flat1.setOpacity(1);
    case 6:
        ok.setOpacity(1);
        break;
` and on and on

Body:
That depends on what flat1 etc. are but if they are instance of some class or interface you could use a map.

(Edit: it seems you're using javafx.scene.Node you probably don't need any additional interface.)

Assuming your flats etc. are instances of javafx.scene.Node you could just use them in a map:

Map<Integer, Node> map = ...;
map.put( 0, flat6 );
map.put( 1, flat5 );
...
map.put( 6, ok );
...

Then use it like this:

Node n = map.get( note.offGraphic() );
if( n != null) {
  n.setOpacity(1);
}

Alternatively, your box could display a representation of those elements, i.e. you just provide a list of elements, select one and call setOpacity(1) on it.


问:
UIImage Aspect Fill when using drawInRect?
I tried to draw scaleAspectFill like contents mode.

I found how to make sacelAspectFit using AVFoundation But I can't find scaleAspectFill.

if I draw horizontal image, I don't know x value

```<code>image.draw(in: CGRect(origin: CGPoint.init(x: ?, y: 0), size: CGSize(width: displayWidth*(image.size.width/image.size.height), height: displayWidth)))
</code>```

答:
Assuming you have an image called image, and you want to draw it inside a rectangle targetRect so that it fills the rect without being distorted, you can use the following code:

```<code>let aspect = image.size.width / image.size.height
let rect: CGRect
if targetRect.size.width / aspect > targetRect.size.height {
    let height = targetRect.size.width / aspect
    rect = CGRect(x: 0, y: (targetRect.size.height - height) / 2,
                  width: targetRect.size.width, height: height)
} else {
    let width = targetRect.size.height * aspect
    rect = CGRect(x: (targetRect.size.width - width) / 2, y: 0,
                  width: width, height: targetRect.size.height)
}
image.draw(in: rect)
</code>```

Note: this doesn't clip the image, so it will draw outside the edges of the target rect. if you want to clip the image, call CGContextClipToRect(context, rect) before drawing.

Note also that the core graphics vertical axis is flipped, with zero starting in the bottom-left instead of top-left compared to UIGraphics, so you may need to flip the rect and clipping rect accordingly.

Body:
I tried to draw scaleAspectFill like contents mode.

I found how to make sacelAspectFit using AVFoundation But I can't find scaleAspectFill.

if I draw horizontal image, I don't know x value

image.draw(in: CGRect(origin: CGPoint.init(x: ?, y: 0), size: CGSize(width: displayWidth*(image.size.width/image.size.height), height: displayWidth)))

Body:
Assuming you have an image called image, and you want to draw it inside a rectangle targetRect so that it fills the rect without being distorted, you can use the following code:

let aspect = image.size.width / image.size.height
let rect: CGRect
if targetRect.size.width / aspect > targetRect.size.height {
    let height = targetRect.size.width / aspect
    rect = CGRect(x: 0, y: (targetRect.size.height - height) / 2,
                  width: targetRect.size.width, height: height)
} else {
    let width = targetRect.size.height * aspect
    rect = CGRect(x: (targetRect.size.width - width) / 2, y: 0,
                  width: width, height: targetRect.size.height)
}
image.draw(in: rect)

Note: this doesn't clip the image, so it will draw outside the edges of the target rect. if you want to clip the image, call CGContextClipToRect(context, rect) before drawing.

Note also that the core graphics vertical axis is flipped, with zero starting in the bottom-left instead of top-left compared to UIGraphics, so you may need to flip the rect and clipping rect accordingly.


问:
C++ Standard and Global Symbol Removal
Anyone have a link to what the C++ standard says regarding a compiler removing global and static symbols?  I thought you weren't guaranteed that the compiler will remove global symbols if they're not referenced. A colleague of mine asserts that if your global symbols are included in the main translation unit, those symbols will not be removed even if they're not referenced.  </p>

答:
It's this way i believe (we had a lengthy discussion on this earlier on stack overflow in a comment-thread):

If the initialization or destructor of an object with namespace scope (that are objects with static storage duration) has no side-effects, the objet can be optimized out if there is no use of a function or object in its translation unit.

For objects whose initialization or destruction cause side effects, then the compiler may not optimize that variable out, even if there is no use of objects or functions of its translation units.

In any case, the compiler has to initialize the objects before that use is done, but not necessarily before main. I did tests because someone at stackoverflow said that gcc effectively optimizes out initializations of objects having side effects if there is no such use. I tested that now, and I've seen gcc does not do that. Additionally, as i understand the Standard, it is not allowed to do so anyway.

It suffices if you just take the address of an object or function of the translation unit of the object you want to have initialized. To be on the safe side, better always do that, even for objects having initializations with side effects. Assuming your friend is right, i think for the translation unit of main, main is always seen as being used, so that condition immediately is satisfied. Rules can be found in 3.6.2p3, 3.7.1p2 and 3.2p2 (definition of use), 1.9p7 (definition of side-effect).

OwnerDisplayName: Michael Kelley

Title: C++ Standard and Global Symbol Removal

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
Product Delete Observer
I want to create an observer for Product deletion. Means when admin deletes a product, during deletion I want to add some custom functionality in this process. Currently I'm using

```<code>catalog_controller_product_delete
</code>```

for this purpose. But it is doing nothing for me. Please help me. How can I do something extra during product deletion?

I want to send deleted product id to my API where I have copy of this product so that I can delete it from there too, but it is not triggering the event. I know this because I am triggering sendProductDelReq() method by <method>sendProductDelReq</method> and for verification I've put a die in this method.

答:
You can also use

model_delete_after

without modifying any core file.

Here's a brief of the after delete function dispatching the model_delete_after event.

```<code>protected function _afterDelete()
{
    Mage::dispatchEvent('model_delete_after', array('object'=>$this));

    Mage::dispatchEvent($this->_eventPrefix.'_delete_after', $this->_getEventData());
    return $this;
}
</code>```

Title: Product Delete Observer

Body:
I want to create an observer for Product deletion. Means when admin deletes a product, during deletion I want to add some custom functionality in this process. Currently I'm using

catalog_controller_product_delete

for this purpose. But it is doing nothing for me. Please help me. How can I do something extra during product deletion?

I want to send deleted product id to my API where I have copy of this product so that I can delete it from there too, but it is not triggering the event. I know this because I am triggering sendProductDelReq() method by <method>sendProductDelReq</method> and for verification I've put a die in this method.

Body:
You can also use

model_delete_after

without modifying any core file.

Here's a brief of the after delete function dispatching the model_delete_after event.

protected function _afterDelete()
{
    Mage::dispatchEvent('model_delete_after', array('object'=>$this));

    Mage::dispatchEvent($this->_eventPrefix.'_delete_after', $this->_getEventData());
    return $this;
}


问:
TCPDF cache problems when using https
We have been using TCPDF to create PDFs on the fly for a while now and everything has been working fine.

However, we changed to https today using the following htaccess code:

```<code>RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.berau.at/$1 [R,L]
</code>```

Now we are getting the following TCPDF error:

```<code>TCPDF ERROR: [Image] Unable to get image: /home/.sites/64/site1783/web/pdf2/cache/img_UgqqR0
</code>```

If we remove the htaccess redirect for https, everything works fine again.

We've searched the TCPDF website, but no references to https problems there.

The TCPDF cache folder already has 755 permissions!

Here's the code we're using to call the image:

```<code>$img_file = $rs_produkt[20];
$pdf->Image($img_file, 0, 0, 0, 0, '', '', '', false, 300, '', false, false, 0);
</code>```

Thanks in advance for any help!

答:
Here's the solution to our problem:

Line 23847 in tcpdf.php contains a direct reference to http. Change this line from

```<code>if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
                        $tag['attribute']['src'] = 'http:'.$tag['attribute']['src'];
                    }
</code>```

to

```<code>if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
                        $tag['attribute']['src'] = 'https:'.$tag['attribute']['src'];
                    }
</code>```

and everything works fine.

Title: TCPDF cache problems when using https

Body:
We have been using TCPDF to create PDFs on the fly for a while now and everything has been working fine.

However, we changed to https today using the following htaccess code:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.berau.at/$1 [R,L]

Now we are getting the following TCPDF error:

TCPDF ERROR: [Image] Unable to get image: /home/.sites/64/site1783/web/pdf2/cache/img_UgqqR0

If we remove the htaccess redirect for https, everything works fine again.

We've searched the TCPDF website, but no references to https problems there.

The TCPDF cache folder already has 755 permissions!

Here's the code we're using to call the image:

$img_file = $rs_produkt[20];
$pdf->Image($img_file, 0, 0, 0, 0, '', '', '', false, 300, '', false, false, 0);

Thanks in advance for any help!

Body:
Here's the solution to our problem:

Line 23847 in tcpdf.php contains a direct reference to http. Change this line from

if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
                        $tag['attribute']['src'] = 'http:'.$tag['attribute']['src'];
                    }

to

if (preg_match('%^/{2}%', $tag['attribute']['src'])) {
                        $tag['attribute']['src'] = 'https:'.$tag['attribute']['src'];
                    }

and everything works fine.


问:
Using oob to change value to a another color in ggplot2
I am checking this post: R ggplot2 - How do I specify out of bounds values' colour on how to "Specify out of bounds values to color".

The answer given was using obs=squish, but that doesn't let you specify a color that is out of range. In my example, it just uses the closest color in my range of values. What if I want to highlight those with another one?

Example:

Here all the values out of range as well as NA are treated as NA and are coloured as grey.

```<code>dat <- matrix(rnorm(100, 3, 1), ncol=10)
dat.m <- melt(dat)
dat.m[c(1,5,10),3] <- NA

ggplot(dat.m, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = round(value, 1))) +
  scale_fill_continuous("",limits=c(1,2), low = "#d73027",
                        high = "#4575b4", na.value = "grey")
</code>```

But now I want all the values that are out of range to have another color, say white, but NA still with grey. If I use oob=squish, it just colors them to the closest value, but where can I specify a color?

```<code>ggplot(dat.m, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = round(value, 1))) +
  scale_fill_continuous("",limits=c(1,2), low = "#d73027",
                        high = "#4575b4", na.value = "grey",oob=squish)
</code>```

答:
It's probably easiest to just use two geom_tiles and rely on overplotting for the true NA values:

```<code>ggplot(dat.m, aes(factor(Var1), factor(Var2))) +
  geom_tile(aes(fill = value)) +
  geom_tile(fill = 'grey', data = subset(dat.m, is.na(value))) +
  geom_text(aes(label = round(value, 1))) +
  scale_fill_continuous("",limits=c(1,2), low = "#d73027",
                        high = "#4575b4", na.value = "lightgreen") +
  coord_fixed()
</code>```

Body:
I am checking this post: R ggplot2 - How do I specify out of bounds values' colour on how to "Specify out of bounds values to color".

The answer given was using obs=squish, but that doesn't let you specify a color that is out of range. In my example, it just uses the closest color in my range of values. What if I want to highlight those with another one?

Example:

Here all the values out of range as well as NA are treated as NA and are coloured as grey.

dat <- matrix(rnorm(100, 3, 1), ncol=10)
dat.m <- melt(dat)
dat.m[c(1,5,10),3] <- NA

ggplot(dat.m, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = round(value, 1))) +
  scale_fill_continuous("",limits=c(1,2), low = "#d73027",
                        high = "#4575b4", na.value = "grey")

But now I want all the values that are out of range to have another color, say white, but NA still with grey. If I use oob=squish, it just colors them to the closest value, but where can I specify a color?

ggplot(dat.m, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = round(value, 1))) +
  scale_fill_continuous("",limits=c(1,2), low = "#d73027",
                        high = "#4575b4", na.value = "grey",oob=squish)

Body:
It's probably easiest to just use two geom_tiles and rely on overplotting for the true NA values:

ggplot(dat.m, aes(factor(Var1), factor(Var2))) +
  geom_tile(aes(fill = value)) +
  geom_tile(fill = 'grey', data = subset(dat.m, is.na(value))) +
  geom_text(aes(label = round(value, 1))) +
  scale_fill_continuous("",limits=c(1,2), low = "#d73027",
                        high = "#4575b4", na.value = "lightgreen") +
  coord_fixed()


问:
Manage relation using Eloquemt ORM
I am working with Laravel5.4. I have a user table that have column like id,introducer_id,company_id,user_role.

If login user has company_id as 1 than fetch all users who has company_id as 1 and also fetch whose company is not same as login user but user_role is 3.

I need to fetch users as per the above requirement using Eloquent ORM. So how can I write query?

答:
Do this:</p>

```<code>User::where('company_id', auth()->user()->company_id)
    ->orWhere(function($q) {
        $q->where('company_id', '<>', auth()->user()->company_id)
          ->where('user_role', 3);
    })
    ->get();
</code>```

Title: Manage relation using Eloquemt ORM

Body:
Do this:

User::where('company_id', auth()->user()->company_id)
    ->orWhere(function($q) {
        $q->where('company_id', '<>', auth()->user()->company_id)
          ->where('user_role', 3);
    })
    ->get();


问:
Gulp.task unexpected token
I created a package.json and ran npm install followed by gulp but it throws an error on the first gulp.task()

SyntaxError: Unexpected token .

```<code>{
  "name": "theme",
  "version": "1.0.0",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "browser-sync": "^2.12.5",
    "gulp": "^3.9.1",
    "gulp-compass": "^2.1.0",
    "gulp-concat": "^2.6.0",
    "gulp-html": "^0.4.4",
    "gulp-htmlmin": "^2.0.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-rename": "^1.2.2",
    "gulp-uglify": "^1.5.3"
  }
}
</code>```

gulp.js

```<code>   var gulp = require('gulp'),
    path = require('path'),

    // CSS
    compass = require('gulp-compass'),
    minifyCSS = require('gulp-minify-css'),

    // JS BUILD
    concat = require('gulp-concat'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),

    // HTML
    htmlmin = require('gulp-htmlmin'),

    // Browser sync
    browserSync = require('browser-sync'),

    // Import files
    pkg = require('./package.json'),

gulp.task('js', function () {
        gulp.src(['scripts/*.js'])
            .pipe(concat(pkg.name + '.js'))
            .pipe(gulp.dest('/'))
            .pipe(rename(pkg.name + '.min.js'))
            .pipe(uglify())
            .pipe(gulp.dest('/'));
});

gulp.task('compass', function(){
    gulp.src('_sass/**/*.scss')
        .pipe(compass({
            css: 'css/',
            sass: 'sass/',
            image: 'images/',
            logging: true,
            style: 'compressed'
        }))
        .on('error', function(error){
            console.log('Compass Error')
            console.log(error)
        })
        .pipe(minifyCSS({
            keepBreaks: false,
            keepSpecialComments:true
        }))
        .pipe(gulp.dest('css/'));
});

gulp.task('default', ['compass', 'js'], function (event) {
    gulp.watch('sass/**/*.scss', ['compass']);
    gulp.watch('scripts/**/*.js', ['js']);
});
</code>```

Edit: Gulp is locally and globally installed

答:
Just saw that my last import had a comma , which caused that error

```<code>pkg = require('./package.json'),
</code>```

needs to be

```<code>pkg = require('./package.json')
</code>```

Title: Gulp.task unexpected token

Body:
I created a package.json and ran npm install followed by gulp but it throws an error on the first gulp.task()

SyntaxError: Unexpected token .

{
  "name": "theme",
  "version": "1.0.0",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "browser-sync": "^2.12.5",
    "gulp": "^3.9.1",
    "gulp-compass": "^2.1.0",
    "gulp-concat": "^2.6.0",
    "gulp-html": "^0.4.4",
    "gulp-htmlmin": "^2.0.0",
    "gulp-minify-css": "^1.2.4",
    "gulp-rename": "^1.2.2",
    "gulp-uglify": "^1.5.3"
  }
}

gulp.js

   var gulp = require('gulp'),
    path = require('path'),

    // CSS
    compass = require('gulp-compass'),
    minifyCSS = require('gulp-minify-css'),

    // JS BUILD
    concat = require('gulp-concat'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),

    // HTML
    htmlmin = require('gulp-htmlmin'),

    // Browser sync
    browserSync = require('browser-sync'),

    // Import files
    pkg = require('./package.json'),

gulp.task('js', function () {
        gulp.src(['scripts/*.js'])
            .pipe(concat(pkg.name + '.js'))
            .pipe(gulp.dest('/'))
            .pipe(rename(pkg.name + '.min.js'))
            .pipe(uglify())
            .pipe(gulp.dest('/'));
});

gulp.task('compass', function(){
    gulp.src('_sass/**/*.scss')
        .pipe(compass({
            css: 'css/',
            sass: 'sass/',
            image: 'images/',
            logging: true,
            style: 'compressed'
        }))
        .on('error', function(error){
            console.log('Compass Error')
            console.log(error)
        })
        .pipe(minifyCSS({
            keepBreaks: false,
            keepSpecialComments:true
        }))
        .pipe(gulp.dest('css/'));
});

gulp.task('default', ['compass', 'js'], function (event) {
    gulp.watch('sass/**/*.scss', ['compass']);
    gulp.watch('scripts/**/*.js', ['js']);
});

Edit: Gulp is locally and globally installed

Body:
Just saw that my last import had a comma , which caused that error

pkg = require('./package.json'),

needs to be

pkg = require('./package.json')


问:
JS - Dropdown element dependent
I'm trying to have the user pick "YES" and the other dropdown automatically goes to "NO" and vice versa. I have a code below, I'm not sure why it is not working.

*I'm trying to get it onload so it automatically runs without the user having to press a button.

Code:

<!DOCTYPE html>

Currently:
        <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
          <option value="">Select Option</option>
          <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
          <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
        </select>

Microphone:
        <select id="microphone" class="microphone select2" name = "microphone">
          <option value=" "  selected="selected"> </option>
          <option value="ON. Thank you.">ON</option>
          <option value="OFF. Thank you.">OFF</option>
        </select>

        <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>

```

答:
id is unique  so try with class name .you should apply the class name in two select boxes.And

s1 is yes s2 is on

s1 is No s2 is OFF

<!DOCTYPE html>

Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
     </select>

Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected"> </option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>

    <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>

   </form>

```
</div>
</div>
</p>

<p>for more simplified of function use this</p>

```function inputHandler(thisSelect, otherSelect) {
otherSelect.selectedIndex = thisSelect.selectedIndex;
        }
```

<p><strong><em>updated answer with single page html</em></strong></p>

<blockquote>
  <p>They error are placing wrong place of <code>js script</code></p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

    <div class="cmicrophone" id="cmicrophone">Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
     </select>
    </div>
    <div class="microphone" id="microphone">Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected"> </option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>
    </div>

<div class="button updatebutton">
    <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>
   </div>
   </form>
  </div>
    <script>
const cmicrophone = document.querySelectorAll('.select1')[0];
const microphone = document.querySelectorAll('.select2')[0];
function inputHandler(thisSelect, otherSelect) {
 otherSelect.selectedIndex =thisSelect.selectedIndex
        }
        cmicrophone.addEventListener('change', event => {
    inputHandler(cmicrophone, microphone);
  });

  microphone.addEventListener('change', event => {
    inputHandler(microphone, cmicrophone);
  });
</script>
</body>
</html></code>```

Title: JS - Dropdown element dependent

Body:
id is unique  so try with class name .you should apply the class name in two select boxes.And

s1 is yes s2 is on

s1 is No s2 is OFF

<!DOCTYPE html>
<html>
<body onload="start()">
<script>
function start(){
const cmicrophone = document.querySelector('.select1');
  const microphone = document.querySelector('.select2');

  function inputHandler(thisSelect, otherSelect) {
    // console.log(thisSelect.selectedIndex)
    if (thisSelect.selectedIndex == 1) {
   otherSelect.selectedIndex = 1;
    } else if (thisSelect.selectedIndex == 2) {
   otherSelect.selectedIndex = 2;
    } else {
   thisSelect.selectedIndex = 0;
   otherSelect.selectedIndex = 0;
    }
  }

  cmicrophone.addEventListener('input', event => {
    inputHandler(cmicrophone, microphone);
  });

  microphone.addEventListener('input', event => {
    inputHandler(microphone, cmicrophone);
  });
    }

</script>
    <div class="cmicrophone" id="cmicrophone">Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
     </select>
    </div>
    <div class="microphone" id="microphone">Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected"> </option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>
    </div>

<div class="button updatebutton">
    <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>
   </div>
   </form>
  </div>
</body>
</html>

for more simplified of function use this

function inputHandler(thisSelect, otherSelect) {
otherSelect.selectedIndex = thisSelect.selectedIndex;
        }

updated answer with single page html

They error are placing wrong place of js script

<!DOCTYPE html>
<html>
<body>

    <div class="cmicrophone" id="cmicrophone">Currently:
     <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
      <option value="">Select Option</option>
      <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
      <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
     </select>
    </div>
    <div class="microphone" id="microphone">Microphone:
     <select id="microphone" class="microphone select2" name = "microphone">
      <option value=" "  selected="selected"> </option>
      <option value="ON. Thank you.">ON</option>
      <option value="OFF. Thank you.">OFF</option>
     </select>
    </div>

<div class="button updatebutton">
    <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>
   </div>
   </form>
  </div>
    <script>
const cmicrophone = document.querySelectorAll('.select1')[0];
const microphone = document.querySelectorAll('.select2')[0];
function inputHandler(thisSelect, otherSelect) {
 otherSelect.selectedIndex =thisSelect.selectedIndex
        }
        cmicrophone.addEventListener('change', event => {
    inputHandler(cmicrophone, microphone);
  });

  microphone.addEventListener('change', event => {
    inputHandler(microphone, cmicrophone);
  });
</script>
</body>
</html>


问:
Avoiding Collisions With Self in Unity
I'm firing lasers from a cannon in a 2d space game in unity using the following method:

```<code>[Command]
private void CmdFire()
{
    GameObject laser = (GameObject)Instantiate(LaserPrefab, leftShot ? leftCannon.position : rightCannon.position, leftShot ? leftCannon.rotation * Quaternion.Euler(0, 0, 90) : rightCannon.rotation * Quaternion.Euler(0, 0, 90));
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").GetComponent<Collider2D>());
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").FindChild(leftShot?"LeftCannon":"RightCannon").GetComponent<Collider2D>());
    laser.GetComponent<SpriteRenderer>().sortingOrder = 0;
    laser.GetComponent<Rigidbody2D>().velocity = laser.transform.right * 10;
    NetworkServer.Spawn(laser);
    leftShot = !leftShot;
    Destroy(laser, 2f);
}
</code>```

The important bit being the Physics2D.IgnoreCollision() sections that are designed to stop them shooting themselves. This works exactly as expected on the host (you can shoot the other ships but not yourself) but the lasers constantly hit their own ship on the client machines.

As you can see here:

This is my first attempt at making a multiplayer game in Unity so any help would be appreciated.

答:
Alternatively, you could add a tag to your player, like "Player" and check in OnCollisionEnter2D whether or not the bullet is colliding with the player that way:

```<code>void OnCollisionEnter2D (Collision2D coll) {
    // If the tag of the thing we collide with is "Player"...
    if (coll.gameObject.tag == "Player")
        Debug.Log("Player hit!");

    // Ignore the collision with the player.
    Physics2D.IgnoreCollision(player.collider, collider);
}
</code>```

Another way is to give the player a different layer to the bullets and ignore collisions between the player and bullet layers:

```<code>Physics2D.IgnoreLayerCollision(PlayerLayer, BulletLayer, true);
</code>```

Or go to Edit > Project Settings > Physics 2D and choose which layers collide with each other there:

You would probably want to add your own custom layers for Player and Bullets.

Title: Avoiding Collisions With Self in Unity

Body:
I'm firing lasers from a cannon in a 2d space game in unity using the following method:

[Command]
private void CmdFire()
{
    GameObject laser = (GameObject)Instantiate(LaserPrefab, leftShot ? leftCannon.position : rightCannon.position, leftShot ? leftCannon.rotation * Quaternion.Euler(0, 0, 90) : rightCannon.rotation * Quaternion.Euler(0, 0, 90));
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").GetComponent<Collider2D>());
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").FindChild(leftShot?"LeftCannon":"RightCannon").GetComponent<Collider2D>());
    laser.GetComponent<SpriteRenderer>().sortingOrder = 0;
    laser.GetComponent<Rigidbody2D>().velocity = laser.transform.right * 10;
    NetworkServer.Spawn(laser);
    leftShot = !leftShot;
    Destroy(laser, 2f);
}

The important bit being the Physics2D.IgnoreCollision() sections that are designed to stop them shooting themselves. This works exactly as expected on the host (you can shoot the other ships but not yourself) but the lasers constantly hit their own ship on the client machines.

As you can see here:

This is my first attempt at making a multiplayer game in Unity so any help would be appreciated.

Body:
Alternatively, you could add a tag to your player, like "Player" and check in OnCollisionEnter2D whether or not the bullet is colliding with the player that way:

void OnCollisionEnter2D (Collision2D coll) {
    // If the tag of the thing we collide with is "Player"...
    if (coll.gameObject.tag == "Player")
        Debug.Log("Player hit!");

    // Ignore the collision with the player.
    Physics2D.IgnoreCollision(player.collider, collider);
}

Another way is to give the player a different layer to the bullets and ignore collisions between the player and bullet layers:

Physics2D.IgnoreLayerCollision(PlayerLayer, BulletLayer, true);

Or go to Edit > Project Settings > Physics 2D and choose which layers collide with each other there:

You would probably want to add your own custom layers for Player and Bullets.


问:
Tray Selection in Google Cloud Printer
The requirement is to print different documents from different tray like the invoices from Tray 1, Envelops from Tray 2.

Is it possible to do with Google Cloud Print?

答: Google Cloud Print does not include any CJT item to set the tray. It is not possible.</p>

Title: Tray Selection in Google Cloud Printer


问:
expose Zeppelin interpreter UI with more options
ON AWS, I use Zeppelin interpreter UI to set some spark configs.
Only the gree ones (pictured) are there by default while the red ones were added by me at a later stage.
How can I set those argument to appear by default, so I can play only with the values and not the names of the properties?

I know about the spark defaults, but the UI is important to me as I'm testing different configs.

答: You can do it by directly editing conf/interpreter.json. There are default Spark configurations which appear in Zeppelin UI. You can add whatever you want to that file. Then restart Zeppelin.


问:
How should I store salts and passwords in MongoDB
I am trying to store passwords and salts in MongoDB and I'm not sure which datatype should be used.  When I use strings, the encrypted password appears to be stored correctly, but the generated salt, which is created with new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');, seems to have characters that weren't recognized.  For example, I have a salt stored as �y_�6j(�l~Z}0ۡ\" and I don't think this is correct.

Is the problem that it's stored as a string?

答:
While registering a user, you can generate a hashed password using bcrypt. Let's call this password as P#1. Save this hashed password (P#1) in your database only, and not the salt.

While logging in a user, generate hashed version of the password which the user sends, let's call it P#2. Now you just have to match P# and P#2. If they match, the user is authenticated. This way you can perform authentication without actually saving the salt in your database.

I will try to put it in simple way with the help of an example.

// My user schema

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var userSchema = new Schema({
  username: String,
  password: String
});

// hash the password
userSchema.methods.generateHash = function(password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
  return bcrypt.compareSync(password, this.password);
};
var User = mongoose.model('user', userSchema);
module.exports = User;
```
<br>
<pre class="lang-js prettyprint-override"><code>// My APIs for registering and authenticating a user

var User = require('/path/to/user/model');

app.post('/register', function(req, res) {
  var new_user = new User({
    username: req.body.username
  });

  new_user.password = new_user.generateHash(req.body.password);
  new_user.save();
});

app.post('/login', function(req, res) {
  User.findOne({username: req.body.username}, function(err, user) {

    if (!user.validPassword(req.body.password)) {
      //password did not match
    } else {
      // password matched. proceed forward
    }
  });
});
</code>```

Hope it helps you!

Body:
While registering a user, you can generate a hashed password using bcrypt. Let's call this password as P#1. Save this hashed password (P#1) in your database only, and not the salt.

While logging in a user, generate hashed version of the password which the user sends, let's call it P#2. Now you just have to match P# and P#2. If they match, the user is authenticated. This way you can perform authentication without actually saving the salt in your database.

I will try to put it in simple way with the help of an example.

// My user schema

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var userSchema = new Schema({
  username: String,
  password: String
});

// hash the password
userSchema.methods.generateHash = function(password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
  return bcrypt.compareSync(password, this.password);
};
var User = mongoose.model('user', userSchema);
module.exports = User;

// My APIs for registering and authenticating a user

var User = require('/path/to/user/model');

app.post('/register', function(req, res) {
  var new_user = new User({
    username: req.body.username
  });

  new_user.password = new_user.generateHash(req.body.password);
  new_user.save();
});

app.post('/login', function(req, res) {
  User.findOne({username: req.body.username}, function(err, user) {

    if (!user.validPassword(req.body.password)) {
      //password did not match
    } else {
      // password matched. proceed forward
    }
  });
});

Hope it helps you!


问:
MS SQL Server : Full text search Not working when using Wild Card in Contains
I am trying to search from table using keywords and it works fine when I do not use wildcards.

```<code>CONTAINS(CP.Course, '"B.A" OR "B.E/B.Tech"')
</code>```

But it does not shows any records when I use this:

```<code>CONTAINS(CP.Course, '"*B.A*" OR "*B.E/B.Tech*"')
</code>```

Is there any reason for it? Since wild card is used as both prefix and suffix so any matching record should be shown. But it shows none.

答:
SQL Server full-text search does not support search by prefix asterisk.

So, while "B.A*" is a valid term, "*B.A*" and "*B.A" are not.

https://learn.microsoft.com/en-us/sql/t-sql/queries/contains-transact-sql

Body:
I am trying to search from table using keywords and it works fine when I do not use wildcards.

CONTAINS(CP.Course, '"B.A" OR "B.E/B.Tech"')

But it does not shows any records when I use this:

CONTAINS(CP.Course, '"*B.A*" OR "*B.E/B.Tech*"')

Is there any reason for it? Since wild card is used as both prefix and suffix so any matching record should be shown. But it shows none.


问:
Overriding the legend title using user specified string instead of variable name
I have a  below code using ggplot2() package. I am trying to plot between the variables - 'Company Advertising' and 'Brand Revenue' of my data frame 'htmltable' , when the another variable 'Industry' is 'Luxury'; using ggplot() function. I am using another variable of my data frame 'Brand Value' as colour variable.

```<code>p<- ggplot(htmltable[htmltable$Industry='Luxury',],aes(x='CompanyAdvertising',y='BrandRevenue')

q <- p+geom_point(aes(color='BrandValue',size='BrandValue') + geom_text(label='Brand')

r <- q+xlab("Company Advertisiment in Billions")+ylab("Brand Revenue in Billions") +ggtitle("Luxury")

r+theme(plot.title=element_text(size=10,face='bold'),legend.key=element_rect(fill='light blue'))
</code>```

Here, I want to change my legend title from "BrandValue" to "BrandValue in Billions". Please suggest.

I tried using labs parameter in the below statement. But it is resulting in 2 legends.

```<code>r <- q+xlab("Company Advertisiment in Billions")+ylab("Brand Revenue in Billions") +ggtitle("Luxury")+labs(colour="BrandValue in Billions")
</code>```

答:
Have you tried this ?</p>

```<code>   +labs(colour="BrandValue in Billions",
          size="BrandValue in Billions")
</code>```

Body:
I have a  below code using ggplot2() package. I am trying to plot between the variables - 'Company Advertising' and 'Brand Revenue' of my data frame 'htmltable' , when the another variable 'Industry' is 'Luxury'; using ggplot() function. I am using another variable of my data frame 'Brand Value' as colour variable.

p<- ggplot(htmltable[htmltable$Industry='Luxury',],aes(x='CompanyAdvertising',y='BrandRevenue')

q <- p+geom_point(aes(color='BrandValue',size='BrandValue') + geom_text(label='Brand')

r <- q+xlab("Company Advertisiment in Billions")+ylab("Brand Revenue in Billions") +ggtitle("Luxury")

r+theme(plot.title=element_text(size=10,face='bold'),legend.key=element_rect(fill='light blue'))

Here, I want to change my legend title from "BrandValue" to "BrandValue in Billions". Please suggest.

I tried using labs parameter in the below statement. But it is resulting in 2 legends.

r <- q+xlab("Company Advertisiment in Billions")+ylab("Brand Revenue in Billions") +ggtitle("Luxury")+labs(colour="BrandValue in Billions")

Body:
Have you tried this ?

   +labs(colour="BrandValue in Billions",
          size="BrandValue in Billions")


问:
JUnit assertions within in Java 8 stream
Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb. But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:

```<code>List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
  .forEach(it -> myObjects.stream()
    .filter(it2 -> it2.getId().equals(it))
    .????
</code>```

But I'm not sure where my assertEquals() would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

答:
Just a little supplement for your additional question:

Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

Yes you can use IntStream to create  a stream based on the size of your objects like:

```<code>IntStream.rangeClosed(1, objects.size()) // both start and end inclusive
</code>```

and there's also a method IntStream.range(int start, int end) which end is exclusive.

Body:
Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb. But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:

List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
  .forEach(it -> myObjects.stream()
    .filter(it2 -> it2.getId().equals(it))
    .????

But I'm not sure where my assertEquals() would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

Body:
Just a little supplement for your additional question:

Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?

Yes you can use IntStream to create  a stream based on the size of your objects like:

IntStream.rangeClosed(1, objects.size()) // both start and end inclusive

and there's also a method IntStream.range(int start, int end) which end is exclusive.


答:
You should remove ids from divs and change a little bit your start logic like:</p>

```<code><!DOCTYPE html>
<html>
<body>
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", ready);

        function ready() {
            const cmicrophone = document.querySelector('#cmicrophone');
            const microphone = document.querySelector('#microphone');

            function inputHandler(thisSelect, otherSelect) {
                console.log(thisSelect.options[thisSelect.selectedIndex].value);
              if (thisSelect.selectedIndex == 1) {
                otherSelect.selectedIndex = 2;
              } else if (thisSelect.selectedIndex == 2) {
                otherSelect.selectedIndex = 1;
              } else {
                thisSelect.selectedIndex = 0;
                otherSelect.selectedIndex = 0;
              }
            }

            cmicrophone.addEventListener('input', event => {
              inputHandler(cmicrophone, microphone);
            });

            microphone.addEventListener('input', event => {
              inputHandler(microphone, cmicrophone);
            });

        }
    </script>
    <div class="cmicrophone">Currently:
        <select id="cmicrophone" class="cmicrophone" name="cmicrophone">
            <option value="">Select Option</option>
            <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
            <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
        </select>
    </div>
    <div class="microphone">Microphone:
        <select id="microphone" class="microphone" name = "microphone">
            <option value=" "  selected="selected"> </option>
            <option value="ON. Thank you.">ON</option>
            <option value="OFF. Thank you.">OFF</option>
        </select>
    </div>
</div>
</body>
</html>
</code>```

Title: JS - Dropdown element dependent

Body:
I'm trying to have the user pick "YES" and the other dropdown automatically goes to "NO" and vice versa. I have a code below, I'm not sure why it is not working.

*I'm trying to get it onload so it automatically runs without the user having to press a button.

Code:

<!DOCTYPE html>

Currently:
        <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
          <option value="">Select Option</option>
          <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
          <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
        </select>

Microphone:
        <select id="microphone" class="microphone select2" name = "microphone">
          <option value=" "  selected="selected"> </option>
          <option value="ON. Thank you.">ON</option>
          <option value="OFF. Thank you.">OFF</option>
        </select>

        <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>

Body:
You should remove ids from divs and change a little bit your start logic like:

<!DOCTYPE html>
<html>
<body>
    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", ready);

        function ready() {
            const cmicrophone = document.querySelector('#cmicrophone');
            const microphone = document.querySelector('#microphone');

            function inputHandler(thisSelect, otherSelect) {
                console.log(thisSelect.options[thisSelect.selectedIndex].value);
              if (thisSelect.selectedIndex == 1) {
                otherSelect.selectedIndex = 2;
              } else if (thisSelect.selectedIndex == 2) {
                otherSelect.selectedIndex = 1;
              } else {
                thisSelect.selectedIndex = 0;
                otherSelect.selectedIndex = 0;
              }
            }

            cmicrophone.addEventListener('input', event => {
              inputHandler(cmicrophone, microphone);
            });

            microphone.addEventListener('input', event => {
              inputHandler(microphone, cmicrophone);
            });

        }
    </script>
    <div class="cmicrophone">Currently:
        <select id="cmicrophone" class="cmicrophone" name="cmicrophone">
            <option value="">Select Option</option>
            <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
            <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
        </select>
    </div>
    <div class="microphone">Microphone:
        <select id="microphone" class="microphone" name = "microphone">
            <option value=" "  selected="selected"> </option>
            <option value="ON. Thank you.">ON</option>
            <option value="OFF. Thank you.">OFF</option>
        </select>
    </div>
</div>
</body>
</html>