问:
Hosting ReactJS with Laravel
We are in the final stages developing a web application. It has a front-end in React and a back-end in Laravel. They communicate by sending JSONs back and forth (API style), so they can be hosted on seperate servers without many problems.

During development we switched to Firebase, because this way we could host React for free, but we need some logic in the back-end and Firebase is not ideal for this.

What is the best solution to host an application that uses React for the front-end and Laravel for the back-end?

答:
This is a very generic question. There are plenty of hosting providers out there - AWS, Google Cloud, DigitalOcean to name a few.

To decide which one is the best, you need to provide more information:

What matters most to you? Pricing, support, availability, technology solutions / capabilities, ease of scaling?

What's your tech stack, starting with database, caching, CDNs, etc.(the whole works)? Laravel and ReactJS alone does not describe your tech stack unless you're using local file drivers for everything (such as sessions, cache, config) and SQLite as your DB.

Title: Hosting ReactJS with Laravel


来源: stackexchange

问:
Missing parenthesis in expression in Oracle Documentation?
Found this condition in Oracle SQL documentation:

```<code>NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)
</code>```

https://docs.oracle.com/database/122/SQLRF/About-SQL-Conditions.htm#SQLRF52101

It explains, "The following complex condition adds the salary value to the commission_pct value (substituting the value 0 for null) and determines whether the sum is greater than the number constant 25000:".
But when I tried to execute it, it throws an error,

'MISSING RIGHT PARENTHESIS'.

Is this condition valid ? or Is there some other way to execute it.

```<code>SELECT  NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000) FROM HR.Employees;
</code>```

Any help will be appreciated, Thank you.

答:
The condition is intended to be used in a WHERE clause, not a SELECT:

```<code>SELECT e.*
FROM HR.Employees
WHERE NVL(salary, 0) + NVL(salary + salary*commission_pct, 0) > 25000 ;
</code>```

(This also adjusts the parentheses.)

Adding the salary twice doesn't make sense.  Presumably the intended logic is:

```<code>WHERE NVL(salary, 0) + NVL(salary*commission_pct, 0) > 25000 ;
</code>```

However, I would write this as:

```<code>SELECT e.*
FROM HR.Employees
WHERE COALESCE(salary, 0) * (1 + COALESCE(commission_pct, 0)) > 25000 ;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Found this condition in Oracle SQL documentation:

NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)

https://docs.oracle.com/database/122/SQLRF/About-SQL-Conditions.htm#SQLRF52101

It explains, "The following complex condition adds the salary value to the commission_pct value (substituting the value 0 for null) and determines whether the sum is greater than the number constant 25000:".
But when I tried to execute it, it throws an error,

'MISSING RIGHT PARENTHESIS'.

Is this condition valid ? or Is there some other way to execute it.

SELECT  NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000) FROM HR.Employees;

Any help will be appreciated, Thank you.

Body:
The condition is intended to be used in a WHERE clause, not a SELECT:

SELECT e.*
FROM HR.Employees
WHERE NVL(salary, 0) + NVL(salary + salary*commission_pct, 0) > 25000 ;

(This also adjusts the parentheses.)

Adding the salary twice doesn't make sense.  Presumably the intended logic is:

WHERE NVL(salary, 0) + NVL(salary*commission_pct, 0) > 25000 ;

However, I would write this as:

SELECT e.*
FROM HR.Employees
WHERE COALESCE(salary, 0) * (1 + COALESCE(commission_pct, 0)) > 25000 ;


问:
React Native mixing style PropTypes
I just recently started using React Native and trying my best to be a good little developer I'm defining the propTypes for my components.  However there is one thing that irks me about this process, which is the style prop type doesn't seem to be "composable" in any way.

For example, I want to create a Divider component that essentially consists of a View with a flat backgroundColor and a width/height set to the value of a thickness property; depending upon it's orientation.

When defining the propTypes for the Divider component I use the View.propTypes as I've seen people on the internet recommend, only I would like to use color instead of backgroundColor to specify the color of the divider. View.propTypes.style doesn't have a color property, and it doesn't seem possible to extend/compose the built-in style prop type.

Has anyone run into similar problems and have a decent remedy/workaround?

Another slightly different but related example: lets say I want to develop a TextField component which wraps TextInput and provides all of it's styling options plus an icon prop which will render the specified icon "inside" and to the left of the TextField the JSX might look something like this:

```<code>render() {
    const {
        icon,
        style,   // how to efficiently spread this across View and TextInput?
        ...props
    } = this.props;

    return (
        <View style={styles.container}>
            {icon()}
            <TextInput ... />
        </View>
    );
}
</code>```

I would like the spread the style supplied across the View and TextInput components where relevant (e.g. the backgroundColor property should be applied to the View component not the TextInput, likewise the color property should be applied to the TextInput component).

答:
Because you have a custom component, I don't think it is a good idea to have things mixed. My suggestions:

(1) if you really want someone to be able to pass in "style" as written, choose one and only one component where that style prop will spread to (e.g. choose the View and make it clear it should only be style props relevant to a view). Then, you could accept another custom prop that would define the style for the TextInput:

```<code><View {...props.style} />
  <TextInput {...props.textInputStyle} />
  {/* ... */}
</code>```

(2) Define custom props one by one on your component that will modify its style. For e.g. <YourComponent color="white" backgroundColor="red" /> would mean you would use props.color to define the text component's color and props.backgroundColor would take care of the view component's background:

```<code><View style={{ backgroundColor: props.backgroundColor, ... }} />
  <Text style={{ color: props.color, ... }} />
  {/* ... */}
</code>```

Remember that it is your custom component and you can accept any props, with any name! The implementation is up to you; internally, you should follow the basic component prop names -- but from without, your own custom component can be used in any way you'd like!

Title: React Native mixing style PropTypes

Body:
I just recently started using React Native and trying my best to be a good little developer I'm defining the propTypes for my components.  However there is one thing that irks me about this process, which is the style prop type doesn't seem to be "composable" in any way.

For example, I want to create a Divider component that essentially consists of a View with a flat backgroundColor and a width/height set to the value of a thickness property; depending upon it's orientation.

When defining the propTypes for the Divider component I use the View.propTypes as I've seen people on the internet recommend, only I would like to use color instead of backgroundColor to specify the color of the divider. View.propTypes.style doesn't have a color property, and it doesn't seem possible to extend/compose the built-in style prop type.

Has anyone run into similar problems and have a decent remedy/workaround?

Another slightly different but related example: lets say I want to develop a TextField component which wraps TextInput and provides all of it's styling options plus an icon prop which will render the specified icon "inside" and to the left of the TextField the JSX might look something like this:

render() {
    const {
        icon,
        style,   // how to efficiently spread this across View and TextInput?
        ...props
    } = this.props;

    return (
        <View style={styles.container}>
            {icon()}
            <TextInput ... />
        </View>
    );
}

I would like the spread the style supplied across the View and TextInput components where relevant (e.g. the backgroundColor property should be applied to the View component not the TextInput, likewise the color property should be applied to the TextInput component).

Body:
Because you have a custom component, I don't think it is a good idea to have things mixed. My suggestions:

(1) if you really want someone to be able to pass in "style" as written, choose one and only one component where that style prop will spread to (e.g. choose the View and make it clear it should only be style props relevant to a view). Then, you could accept another custom prop that would define the style for the TextInput:

<View {...props.style} />
  <TextInput {...props.textInputStyle} />
  {/* ... */}

(2) Define custom props one by one on your component that will modify its style. For e.g. <YourComponent color="white" backgroundColor="red" /> would mean you would use props.color to define the text component's color and props.backgroundColor would take care of the view component's background:

<View style={{ backgroundColor: props.backgroundColor, ... }} />
  <Text style={{ color: props.color, ... }} />
  {/* ... */}

Remember that it is your custom component and you can accept any props, with any name! The implementation is up to you; internally, you should follow the basic component prop names -- but from without, your own custom component can be used in any way you'd like!


问:
Add two textviews side by side in a TableLayout dynamically
I'm trying to add rows dynamically in a table. I need to add two TextViews side by side in each row. This has to be done dynamically. I have written the code that creates rows dynamically. I'm unable to add a second TextView on the side.

activity.xml

```<code><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:stretchColumns="0,1"
    android:id="@+id/tableView"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</TableLayout>`
</code>```

MainActivity.java

```<code>    TableLayout ll = (TableLayout) findViewById(R.id.tableView);
    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        TextView qty = new TextView(this);
        qty.setText("10");
        row.addView(qty);
        ll.addView(row,i);
    }
</code>```

答:
You forgot to set the LayoutParams:

```<code>TableLayout ll = (TableLayout) findViewById(R.id.tableView);
for (int i = 0; i < 2; i++) {

    TableRow row = new TableRow(this);
    row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

    TextView qty = new TextView(this);
    qty.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
    qty.setText("10");
    row.addView(qty);

    ll.addView(row);
}
</code>```

Body:
I'm trying to add rows dynamically in a table. I need to add two TextViews side by side in each row. This has to be done dynamically. I have written the code that creates rows dynamically. I'm unable to add a second TextView on the side.

activity.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:stretchColumns="0,1"
    android:id="@+id/tableView"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</TableLayout>`

MainActivity.java

    TableLayout ll = (TableLayout) findViewById(R.id.tableView);
    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        TextView qty = new TextView(this);
        qty.setText("10");
        row.addView(qty);
        ll.addView(row,i);
    }

Body:
You forgot to set the LayoutParams:

TableLayout ll = (TableLayout) findViewById(R.id.tableView);
for (int i = 0; i < 2; i++) {

    TableRow row = new TableRow(this);
    row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));

    TextView qty = new TextView(this);
    qty.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
    qty.setText("10");
    row.addView(qty);

    ll.addView(row);
}


问:
Load all tiles for area in mapView
I have found a way to cache tiles with MapKit, but I haven't found any solution for loading all tiles inside an area to from the top level tiles to the bottom level tiles. </p>

<p>I want to cache all tiles for a rectangle area in my mapview. Is there any way to do this in Mapkit? </p>

答:
In order to load custom tiles in MKMapView you need to subclass MKTileOverlay and override method
url(forTilePath path: MKTileOverlayPath) -> URL

MKTitleOverlay contains x, y and z properties for the tile.
So the implementation may look like this:

```<code>override func url(forTilePath path: MKTileOverlayPath) -> URL {
  let tilePath = Bundle.main.url(
  forResource: "\(path.y)",
  withExtension: "png",
  subdirectory: "tiles/\(path.z)/\(path.x)",
  localization: nil)!
  return tile
}
</code>```

In your mapView setting function add the following:

```<code>let overlay = CustomTileOverlay()
overlay.canReplaceMapContent = true
mapView.add(overlay, level: .aboveLabels)
</code>```

Also don't forget to return renderer in

```<code>func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
  return MKTileOverlayRenderer(tileOverlay: overlay)
}
</code>```

P.S. There is a great tutorial on raywenderlich.com on that subject:

Title: Load all tiles for area in mapView

Body:
I have found a way to cache tiles with MapKit, but I haven't found any solution for loading all tiles inside an area to from the top level tiles to the bottom level tiles.

I want to cache all tiles for a rectangle area in my mapview. Is there any way to do this in Mapkit?

Body:
In order to load custom tiles in MKMapView you need to subclass MKTileOverlay and override method
url(forTilePath path: MKTileOverlayPath) -> URL

MKTitleOverlay contains x, y and z properties for the tile.
So the implementation may look like this:

override func url(forTilePath path: MKTileOverlayPath) -> URL {
  let tilePath = Bundle.main.url(
  forResource: "\(path.y)",
  withExtension: "png",
  subdirectory: "tiles/\(path.z)/\(path.x)",
  localization: nil)!
  return tile
}

In your mapView setting function add the following:

let overlay = CustomTileOverlay()
overlay.canReplaceMapContent = true
mapView.add(overlay, level: .aboveLabels)

Also don't forget to return renderer in

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
  return MKTileOverlayRenderer(tileOverlay: overlay)
}

P.S. There is a great tutorial on raywenderlich.com on that subject:


问:
Make div and table header fixed on scroll
I have a div where I have a dropdown and then on the bottom there's a table.
I am using ngx-infinite-scrolling, and when I scroll i want the div and the header of the table to remain fixed as more data is added and scrolled down.

This is a jsfiddle JSFiddle

Html code:

```<code> <div class="topTable row ">

  <div class="col-md-4 col-lg-3 col-sm-4 col-6">
  <form class="form-inline">
      <div class="form-group" style="width:100%;max-width:200px;">
        <div class="input-group" style="width:100%">
            <select class="form-control"  >
                <option >All</option>
                <option >Option1</option>
                 <option >Option1</option>
                  <option >Option1</option>
              </select>

        </div>
   </div>

 <div class="container-fluid">
   <div class="col-md-12">
  <div class="col-md-12 tableDiv"  >
  <div class="constrained"  >
  <table class="table table-striped col-md-12 table-condensed cf" >
  <thead class="table-bordered cf">
    <tr>
      <th>Column1</th>
      <th>Column2</th>
      <th>Column3</th>
      <th>Column4</th>
      <th>Column5</th>
      <th>Column6</th>

    </tr>
  </thead>
  <tbody >
    <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>
        <tr>
      <td > asdf</td>
      <td >asdfa</td>
      <td >fsdf</td>
      <td>sdfsfd</td>
      <td>sdfs</td>
      <td>fsdfsdf</td>
    </tr>

   </tbody>
  </table>
 </div>
  <div>
  </div>
 </div>
</div>
</div>
</code>```

CSS:

```<code>.topTable{
 height:70px;
background:red;
margin-top:-20px;
margin-bottom:20px;
display: flex;
padding-left: 32px;
border:1px solid rgba(0,0,0,.1)
}

.tableDiv{
margin-top:50px
}
</code>```

I tried putting position:static on the div, but then on scroll down, table would go on top of it.
How to also make table static and its header fixed ?
Any help is appreciated

答:
You have to separate the top-block from the content-block, otherwise you make everything fixed.

Now you can make the first block fixed, the block has to get 100% width and z-index more than the content block (default is 0 -> so we need 1 or higher).

```<code>position:fixed;
width:100%;
z-index: 1;
</code>```

I have forked your fiddle: http://jsfiddle.net/n958b7q3/1/
changes are marked.

Some tips:

html

You got to many divs, only make new div's if really needed

Your form has no closing tag </form>

css:

You forgot ; after border:1px solid rgba(0,0,0,.1)

Body:
I have a div where I have a dropdown and then on the bottom there's a table.
I am using ngx-infinite-scrolling, and when I scroll i want the div and the header of the table to remain fixed as more data is added and scrolled down.

This is a jsfiddle JSFiddle

Html code:

  <form class="form-inline">

            <select class="form-control"  >
                <option >All</option>
                <option >Option1</option>
                 <option >Option1</option>
                  <option >Option1</option>
              </select>

      Column1
      Column2
      Column3
      Column4
      Column5
      Column6

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

       asdf
      asdfa
      fsdf
      sdfsfd
      sdfs
      fsdfsdf

CSS:

.topTable{
 height:70px;
background:red;
margin-top:-20px;
margin-bottom:20px;
display: flex;
padding-left: 32px;
border:1px solid rgba(0,0,0,.1)
}

.tableDiv{
margin-top:50px
}

I tried putting position:static on the div, but then on scroll down, table would go on top of it.
How to also make table static and its header fixed ?
Any help is appreciated

Body:
You have to separate the top-block from the content-block, otherwise you make everything fixed.

Now you can make the first block fixed, the block has to get 100% width and z-index more than the content block (default is 0 -> so we need 1 or higher).

position:fixed;
width:100%;
z-index: 1;

I have forked your fiddle: http://jsfiddle.net/n958b7q3/1/
changes are marked.

Some tips:

html

You got to many divs, only make new div's if really needed

Your form has no closing tag </form>

css:

You forgot ; after border:1px solid rgba(0,0,0,.1)


问:
Result from PHP markdown parser is string, not valid html

Goal

I am trying to display links that a user has entered as either markdown or html into a description. The description is saved in a database, and then when its read, I'm trying to parse it to display as a link (rather than the literal markup/markdown).

Problem

I'm using HTML Purifier to parse markdown that is stored in the database. When I run the string through the parser, the result on the page is not valid HTML, but instead the correct HTML simply inside a string.

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'a[href]');
$config->set('AutoFormat.Linkify', true);
$config->set('HTML.TargetBlank', true);
$config->set('HTML.TargetNoreferrer', true);

//My database result
$subrow['description'];

$purifier = new HTMLPurifier($config);
printf("
%s
", $purifier->purify($subrow['description'));
```

Currently the output is literally: "A link my link"

Screenshot from the chrome dev tools

答:
I think the encoding is changed inside of purifier... only a guess as I have never used it. I was able to mimic your results with the following:

```<code>$test = htmlentities("A link <a href=\"https://url.com/my link\">mylink</a>");
printf('<br />%s<br />', $test);
</code>```

To get the valid markup back, I used html_entity_decode():

```<code>printf('<br />%s<br />', html_entity_decode($test));
</code>```

Try

```<code>printf("<br />%s<br />", html_entity_decode($purifier->purify($subrow['description'])));
</code>```

Does that help?

Body:
Goal

I am trying to display links that a user has entered as either markdown or html into a description. The description is saved in a database, and then when its read, I'm trying to parse it to display as a link (rather than the literal markup/markdown).

Problem

I'm using HTML Purifier to parse markdown that is stored in the database. When I run the string through the parser, the result on the page is not valid HTML, but instead the correct HTML simply inside a string.

$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'a[href]');
$config->set('AutoFormat.Linkify', true);
$config->set('HTML.TargetBlank', true);
$config->set('HTML.TargetNoreferrer', true);

//My database result
$subrow['description'];

$purifier = new HTMLPurifier($config);
printf("
%s
", $purifier->purify($subrow['description'));

Currently the output is literally: "A link my link"

Screenshot from the chrome dev tools

Body:
I think the encoding is changed inside of purifier... only a guess as I have never used it. I was able to mimic your results with the following:

$test = htmlentities("A link <a href=\"https://url.com/my link\">mylink</a>");
printf('<br />%s<br />', $test);

To get the valid markup back, I used html_entity_decode():

printf('<br />%s<br />', html_entity_decode($test));

Try

printf("<br />%s<br />", html_entity_decode($purifier->purify($subrow['description'])));

Does that help?


问:
How to automatically input in the WebBrowser control
I'm quite very amateur in vb.net. When I type a text on textbox, it should be able to automatically input on the webbrowsercontrol and also how to click the button signin, wherein no getelementbyid.

Also I manage to get the 1st part correct, but when I click sign in button from inside browser, there seems to be a minor error. I've made a project like this one before long long time ago and can't find the source code of it anymore, so I'm starting from scratch again.

Website: https://app.coins.ph/welcome/login

Heres my code so far:

```<code>Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    WebBrowser1.Document.GetElementById("username").InnerText = TextBox1.Text
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("class") 'Depending on how the source code is formatted on the tag, you may also try Element.OuterHTML, Element.InnerText and Element.OuterText in the line below
        If Element.OuterText.Contains("SIGN IN") Then
            Element.InvokeMember("click")
            Exit For
        End If
    Next Element
End Sub

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    WebBrowser1.Document.GetElementById("password").InnerText = TextBox2.Text
End Sub
</code>```

答:
You've got a couple of issues here. Let's start with the textbox inputs. If you look at the html source for that website's sign-in page, the inputs for username and password do not have an ID property, they only use Name. Moreover, GetElementsByTagName is searching for a html element of "username", not an "input" as it should. Given both of those issues, you should be using Document.All("[elementName]") to access those inputs. As for the sign-in part, as stated before, GetElementsByTagName is looking for html elements, so searching for the value "class" is not going to return anything you want. Instead, you should be looking for a "button" where the OuterText contains "SIGN IN". With all those changes applied, the code becomes:

```<code>Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WebBrowser1.Navigate("https://app.coins.ph/welcome/login")
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        WebBrowser1.Document.All("username").InnerText = TextBox1.Text
    End Sub

    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
        WebBrowser1.Document.All("password").InnerText = TextBox2.Text
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
            If Element.OuterText.Contains("SIGN IN") Then
                Element.InvokeMember("click")
                Exit For
            End If
        Next Element
    End Sub

End Class
</code>```

There is another problem once you run this code though

If you run the above example, you will see that the form-fields are properly filled in and the sign-in button is clicked successfully, however an error appears indicating that the form fields are still blank. Even if you use WebBrowser1.Document.All("username").SetAttribute("value", TextBox1.Text) to set the input's value as well, the same error occurs. This is likely because the website's developers are using some sort of javascript that is detecting keypresses for one reason or another...it's impossible to know why, but that's how it is. So you're left with actually simulating key presses yourself. If you do that, the website will successfully log in with the username and password. You have two ways of doing this. The cleaner way is to just send all the keys at once and log in like so:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    WebBrowser1.Focus()
    WebBrowser1.Document.All("username").Focus()
    For Each c As Char In TextBox1.Text.ToCharArray
        SendKeys.SendWait(c)
    Next
    WebBrowser1.Document.All("password").Focus()
    For Each c As Char In TextBox2.Text.ToCharArray
        SendKeys.SendWait(c)
    Next
    For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
        If Element.OuterText.Contains("SIGN IN") Then
            Element.InvokeMember("click")
            Exit For
        End If
    Next Element
End Sub
</code>```

However, if you still want each character to appear as you type, to mirror the functionality of the TextChanged event logic you are currently using you would have to use the KeyPress event and basically forward the keystrokes like this:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
        If Element.OuterText.Contains("SIGN IN") Then
            Element.InvokeMember("click")
            Exit For
        End If
    Next Element
End Sub

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    WebBrowser1.Focus()
    WebBrowser1.Document.All("username").Focus()
    SendKeys.SendWait(e.KeyChar)
    TextBox1.Focus()
End Sub

Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
    WebBrowser1.Focus()
    WebBrowser1.Document.All("password").Focus()
    SendKeys.SendWait(e.KeyChar)
    TextBox2.Focus()
End Sub
</code>```

Body:
I'm quite very amateur in vb.net. When I type a text on textbox, it should be able to automatically input on the webbrowsercontrol and also how to click the button signin, wherein no getelementbyid.

Also I manage to get the 1st part correct, but when I click sign in button from inside browser, there seems to be a minor error. I've made a project like this one before long long time ago and can't find the source code of it anymore, so I'm starting from scratch again.

Website: https://app.coins.ph/welcome/login

Heres my code so far:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    WebBrowser1.Document.GetElementById("username").InnerText = TextBox1.Text
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("class") 'Depending on how the source code is formatted on the tag, you may also try Element.OuterHTML, Element.InnerText and Element.OuterText in the line below
        If Element.OuterText.Contains("SIGN IN") Then
            Element.InvokeMember("click")
            Exit For
        End If
    Next Element
End Sub

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    WebBrowser1.Document.GetElementById("password").InnerText = TextBox2.Text
End Sub

Body:
You've got a couple of issues here. Let's start with the textbox inputs. If you look at the html source for that website's sign-in page, the inputs for username and password do not have an ID property, they only use Name. Moreover, GetElementsByTagName is searching for a html element of "username", not an "input" as it should. Given both of those issues, you should be using Document.All("[elementName]") to access those inputs. As for the sign-in part, as stated before, GetElementsByTagName is looking for html elements, so searching for the value "class" is not going to return anything you want. Instead, you should be looking for a "button" where the OuterText contains "SIGN IN". With all those changes applied, the code becomes:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WebBrowser1.Navigate("https://app.coins.ph/welcome/login")
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        WebBrowser1.Document.All("username").InnerText = TextBox1.Text
    End Sub

    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
        WebBrowser1.Document.All("password").InnerText = TextBox2.Text
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
            If Element.OuterText.Contains("SIGN IN") Then
                Element.InvokeMember("click")
                Exit For
            End If
        Next Element
    End Sub

End Class

There is another problem once you run this code though

If you run the above example, you will see that the form-fields are properly filled in and the sign-in button is clicked successfully, however an error appears indicating that the form fields are still blank. Even if you use WebBrowser1.Document.All("username").SetAttribute("value", TextBox1.Text) to set the input's value as well, the same error occurs. This is likely because the website's developers are using some sort of javascript that is detecting keypresses for one reason or another...it's impossible to know why, but that's how it is. So you're left with actually simulating key presses yourself. If you do that, the website will successfully log in with the username and password. You have two ways of doing this. The cleaner way is to just send all the keys at once and log in like so:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    WebBrowser1.Focus()
    WebBrowser1.Document.All("username").Focus()
    For Each c As Char In TextBox1.Text.ToCharArray
        SendKeys.SendWait(c)
    Next
    WebBrowser1.Document.All("password").Focus()
    For Each c As Char In TextBox2.Text.ToCharArray
        SendKeys.SendWait(c)
    Next
    For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
        If Element.OuterText.Contains("SIGN IN") Then
            Element.InvokeMember("click")
            Exit For
        End If
    Next Element
End Sub

However, if you still want each character to appear as you type, to mirror the functionality of the TextChanged event logic you are currently using you would have to use the KeyPress event and basically forward the keystrokes like this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
        If Element.OuterText.Contains("SIGN IN") Then
            Element.InvokeMember("click")
            Exit For
        End If
    Next Element
End Sub

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
    WebBrowser1.Focus()
    WebBrowser1.Document.All("username").Focus()
    SendKeys.SendWait(e.KeyChar)
    TextBox1.Focus()
End Sub

Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
    WebBrowser1.Focus()
    WebBrowser1.Document.All("password").Focus()
    SendKeys.SendWait(e.KeyChar)
    TextBox2.Focus()
End Sub


问:
Powershell Zip Directory exclude some Subdirectories
I'm writing a powershell script in which I would like to .zip a directory with 2 subdirectories. In one of the subdirectories I would like to exclude another directory.

```<code>myDirectory
-- sub 1
--- sub 1.1
--- sub 1.2
-- sub 2
--- sub 2.1
--- sub 2.2
</code>```

I wrote this script but it isn't working. Can anyone give me a hint or tell me what I'm doing wrong?

```<code>$ChildItemPath = "myDirectory"

$Date = [DateTime]::Now.ToString("yyyyMMdd-HHmmss")
$Exclude = @("myDirectory/sub 2/sub 2.1")

$DestinationPath = "Archive-v" + $Date

$CompressPath = Get-ChildItem -Path $ChildItemPath -Exclude $Exclude

Compress-Archive -Path $CompressPath -DestinationPath $DestinationPath -update
</code>```

the .bat/.ps1 file is in the same directory as 'myDirectory'

-------------------------- EDIT 19:55 --------------------------
Solution of suggested by Reza works fine when subfolder is pretty 'small'. I'm trying to exclude 'node_modules' from a AngularClient-dir.

So the final .zip file contains a 'serverside'-dir: vs217 asp.net core project
and a 'clientside'-dir: angular4 project without the node_modules

答:
To exclude some subfolders of a folder when creating a zip file, as an option you can copy the folder excluding those subfolders to a temp folder in temp directory of windows. Then zip the temp folder:</p>

```<code>$inputFolder = "C:\MyDirectory"
$excludeFolders = @("\Sub1\Sub1-2", "\Sub2\Sub2-2")
$ouputFileName="C:\MyFile.zip"

$tempFolder = [System.IO.Path]::GetTempFileName()
Remove-Item $tempFolder -Force
New-Item -Type  Directory -Path $tempFolder -Force
$exclude =@()
$excludeFolders | ForEach-Object {
 $exclude+=(Join-Path $inputFolder $_)
 Get-ChildItem (Join-Path $inputFolder $_) -Recurse |
  ForEach-Object{$exclude+=$_.FullName}}
Get-ChildItem $inputFolder -Recurse | Where-Object { $_.FullName -notin $exclude} |
 Copy-Item -Destination {Join-Path $tempFolder $_.FullName.Substring($inputFolder.length)}

Get-ChildItem $tempFolder |
Compress-Archive -DestinationPath $ouputFileName -Update
# Remove-Item $tempFolder -Force -Recurse
</code>```

Body:
I'm writing a powershell script in which I would like to .zip a directory with 2 subdirectories. In one of the subdirectories I would like to exclude another directory.

myDirectory
-- sub 1
--- sub 1.1
--- sub 1.2
-- sub 2
--- sub 2.1
--- sub 2.2

I wrote this script but it isn't working. Can anyone give me a hint or tell me what I'm doing wrong?

$ChildItemPath = "myDirectory"

$Date = [DateTime]::Now.ToString("yyyyMMdd-HHmmss")
$Exclude = @("myDirectory/sub 2/sub 2.1")

$DestinationPath = "Archive-v" + $Date

$CompressPath = Get-ChildItem -Path $ChildItemPath -Exclude $Exclude

Compress-Archive -Path $CompressPath -DestinationPath $DestinationPath -update

the .bat/.ps1 file is in the same directory as 'myDirectory'

-------------------------- EDIT 19:55 --------------------------
Solution of suggested by Reza works fine when subfolder is pretty 'small'. I'm trying to exclude 'node_modules' from a AngularClient-dir.

So the final .zip file contains a 'serverside'-dir: vs217 asp.net core project
and a 'clientside'-dir: angular4 project without the node_modules

Body:
To exclude some subfolders of a folder when creating a zip file, as an option you can copy the folder excluding those subfolders to a temp folder in temp directory of windows. Then zip the temp folder:

$inputFolder = "C:\MyDirectory"
$excludeFolders = @("\Sub1\Sub1-2", "\Sub2\Sub2-2")
$ouputFileName="C:\MyFile.zip"

$tempFolder = [System.IO.Path]::GetTempFileName()
Remove-Item $tempFolder -Force
New-Item -Type  Directory -Path $tempFolder -Force
$exclude =@()
$excludeFolders | ForEach-Object {
 $exclude+=(Join-Path $inputFolder $_)
 Get-ChildItem (Join-Path $inputFolder $_) -Recurse |
  ForEach-Object{$exclude+=$_.FullName}}
Get-ChildItem $inputFolder -Recurse | Where-Object { $_.FullName -notin $exclude} |
 Copy-Item -Destination {Join-Path $tempFolder $_.FullName.Substring($inputFolder.length)}

Get-ChildItem $tempFolder |
Compress-Archive -DestinationPath $ouputFileName -Update
# Remove-Item $tempFolder -Force -Recurse


问:
Lexical this context in fat arrows
An example will better illustrate my question.

```<code>let obj = {
    columns: [
        { column: name },
        { column: name },
        { column: name },
        { column: name },
        { column: name }
    ],
    someFunc: () => {
        this.somePublicFunc(this.columns[0])
    }
}
</code>```

With a regular function() the this.columns would point to obj.columns. Is there a way at access the function this scope within a fat arrow function?

Alternatively can I call a public function in a non-fat arrow function?

```<code>    someFunc: function() {
        this.somePublicFunc(this.columns[0])
    }
</code>```

Edit: I know I can access obj.columns, but was looking for other options as this is not the most elegant option for the actual code.

Edit: This was all the result of quickly changing all the public methods over to arrow functions. The thought never even occurred to me to just change the problem method in question to a traditional non fat arrow function. Problem solved, ego bruised.

答:
Remember that arrow functions determine their this base upon the current this at the time the function is declared and not base upon its placement within an object.

In your code above, assume it is running globally, the this pointer will be window in a browser and global in node when the function someFunc was declared so that will be the this pointer inside of the arrow function.

In general, using a traditional function declaration will resolve your problem, unless this gets changed by something else.

Title: Lexical this context in fat arrows

Body:
An example will better illustrate my question.

let obj = {
    columns: [
        { column: name },
        { column: name },
        { column: name },
        { column: name },
        { column: name }
    ],
    someFunc: () => {
        this.somePublicFunc(this.columns[0])
    }
}

With a regular function() the this.columns would point to obj.columns. Is there a way at access the function this scope within a fat arrow function?

Alternatively can I call a public function in a non-fat arrow function?

    someFunc: function() {
        this.somePublicFunc(this.columns[0])
    }

Edit: I know I can access obj.columns, but was looking for other options as this is not the most elegant option for the actual code.

Edit: This was all the result of quickly changing all the public methods over to arrow functions. The thought never even occurred to me to just change the problem method in question to a traditional non fat arrow function. Problem solved, ego bruised.


问:
Verify that a given string can be converted into a positive integer
I wrote method that checks if a given String input can be parsed as positive integer or not.

Is there a cleaner way to write this so I'm not repeating the code that rejects the value?

```<code>try {
  int num = Integer.parseInt(value);

  if (num <= 0) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
  }
} catch (NumberFormatException e) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}
</code>```

答:
I belive this is the cleaner you can get.
Even if it passes on the try if it is not in the range of results that you expect you force it into the catch.</p>

```<code>try {
  int num = Integer.parseInt(value);

  if (num <= 0) {
    throw new NumberFormatException();
  }
} catch (NumberFormatException e) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}
</code>```

Body:
I wrote method that checks if a given String input can be parsed as positive integer or not.

Is there a cleaner way to write this so I'm not repeating the code that rejects the value?

try {
  int num = Integer.parseInt(value);

  if (num <= 0) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
  }
} catch (NumberFormatException e) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}

Body:
I belive this is the cleaner you can get.
Even if it passes on the try if it is not in the range of results that you expect you force it into the catch.

try {
  int num = Integer.parseInt(value);

  if (num <= 0) {
    throw new NumberFormatException();
  }
} catch (NumberFormatException e) {
    errors.rejectValue(FIELD_FILE, INVALID_MESSAGE_KEY, new Object[]{lineNumber, fieldName}, "Line {0}: {1} must be a positive integer");
}


问:
Dividing bootstrap column under col-1
I would like to be able to divide a bootstrap gid even more. Without to much hassle or workarounds. What is the best way of creating column 1/24 of a grid.

Fiddle to understand better what I mean: https://jsfiddle.net/Lmm1ra7d/

```<code><div class='row'>
    <div class="col-xs-8">8/12</div>
    <div class="col-xs-4">4/12</div>
</div>

<br/>
Now I need to transform this to  a 0.5/12 => 1/24 What would be the best approach without a hacky fix. Also not to break the responsiveness.
This is the smallest column bootstrap can make 8.3333%
<br/>
<br/>

<div class='row'>
    <div class="col-xs-1">1/12</div>
    <div class="col-xs-11">11/12</div>
</div>

<br/>
What I really want would be 4%
<br/>
<br/>

<div class='row'>
    <div style="width:3%; display: inline-block;">1/24</div><div style="width:96%;display: inline-block;">23/24</div>
</div>
</code>```

答:
you can nest a row in a column, so basically you divide your main row in other rows. For example

```<code>    <div class="row">
     <div class="col-sm-3">
      <!-- now you have 1/4 -->
       <div class="row">
        <div class="col-sm-3">
         <!-- now you have 1/4 of 1/4 -->
        </div>
       </div>
     </div>
    </div>
</code>```

Title: Dividing bootstrap column under col-1

Body:
I would like to be able to divide a bootstrap gid even more. Without to much hassle or workarounds. What is the best way of creating column 1/24 of a grid.

Fiddle to understand better what I mean: https://jsfiddle.net/Lmm1ra7d/

8/12

4/12

Now I need to transform this to  a 0.5/12 => 1/24 What would be the best approach without a hacky fix. Also not to break the responsiveness.
This is the smallest column bootstrap can make 8.3333%

1/12

11/12

What I really want would be 4%

1/24

23/24

Body:
you can nest a row in a column, so basically you divide your main row in other rows. For example

    <div class="row">
     <div class="col-sm-3">
      <!-- now you have 1/4 -->
       <div class="row">
        <div class="col-sm-3">
         <!-- now you have 1/4 of 1/4 -->
        </div>
       </div>
     </div>
    </div>


问:
Angular erasing all query parameters
Related to but not a duplicate of: How to keep query string parameters in URL when accessing a route of an Angular 2 app?

I have a very basic Angular app, and when I add a query parameter, it's erased (from the browser's url and everywhere else it would seem) before the code hits the app.component constructor.

Note: it is on the initial load (and subsequent reloads) that query parameters appear to be stripped

Example: navigating to localhost:8081/calculator?a=1 is changed to localhost:8081/calculator

I've tried this in Angular 4.3.1, 4.4.6 and 5.0.4, with the same result.

Here's my route config:

```<code>const appRoutes: Routes = [
    {
        path: 'calculator',
        component: CalculatorComponent
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
</code>```

Here's the main app component's constructor:

```<code>public constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered app constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('app', params);
    });
}
</code>```

Here's the calculator component's constructor:

```<code>constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered calc constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('calc', params);
    });
}
</code>```

Here's the log I see in chrome:

Why is my query parameter erased?

UPDATE
I do have navigation configured in the app component like so:

```<code>let navigationExtras: NavigationExtras = {
    queryParamsHandling: 'preserve',
    preserveFragment: true
};
this.router.navigate(['/calculator'], navigationExtras);
</code>```

Note that the query parameters are already gone before it gets here though...

答:
The issue you are having is because you are calling
this.router.navigate(['/calculator'], navigationExtras);
inside your app component constructor or OnInit. Remember that queryParamMap is an observable, and so when you call navigate, the call will happen before your subscriber gets called. To fix your problem, just remove the navigate call. If you want your app component to autoredirect to calculator, the simplest safe method is to just change your paths to include:

routes: Routes = [
 {path: '', redirectTo: 'calculator', pathMatch: 'full'},
...
]

There is a plunker that should illustrate this. To get routing in plunker working I used HashLocation strategy though, so make sure you use /#/... when playing.

Title: Angular erasing all query parameters

Body:
Related to but not a duplicate of: How to keep query string parameters in URL when accessing a route of an Angular 2 app?

I have a very basic Angular app, and when I add a query parameter, it's erased (from the browser's url and everywhere else it would seem) before the code hits the app.component constructor.

Note: it is on the initial load (and subsequent reloads) that query parameters appear to be stripped

Example: navigating to localhost:8081/calculator?a=1 is changed to localhost:8081/calculator

I've tried this in Angular 4.3.1, 4.4.6 and 5.0.4, with the same result.

Here's my route config:

const appRoutes: Routes = [
    {
        path: 'calculator',
        component: CalculatorComponent
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Here's the main app component's constructor:

public constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered app constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('app', params);
    });
}

Here's the calculator component's constructor:

constructor(private router: Router, private route: ActivatedRoute) {
    console.log('entered calc constructor');
    this.route.queryParamMap.subscribe(params => {
        console.log('calc', params);
    });
}

Here's the log I see in chrome:

Why is my query parameter erased?

UPDATE
I do have navigation configured in the app component like so:

let navigationExtras: NavigationExtras = {
    queryParamsHandling: 'preserve',
    preserveFragment: true
};
this.router.navigate(['/calculator'], navigationExtras);

Note that the query parameters are already gone before it gets here though...


问:
R: created a names vector containing the means of multiple numeric vectors
I have over 20 numeric vectors which consist of a series of values. each vector is distinguished by a letter, e.g. val_a, val_b, val_c etc...

I would like to put the means from each of these vectors into a single named vector. I could of course do this in a laborious manner like so:

```<code>obs <- c("val_a" = round(mean(val_a),3),
         "val_b" = round(mean(val_b),3),
         "val_c" = round(mean(val_c),3))
</code>```

But with 20 vectors this then becomes tedious to write out, and not to mention an inelegant solution. How can I create the named vector in a more succinct way? I have made an attempt using a for loop, as so:

```<code>obs <- c(for (j in 1:20) {
  assign(paste("val",letters[j], sep = "_"),
  mean(as.name(paste('val',letters[j], sep = '_'))),)
})
</code>```

In the right hand argument passed to assign, "as.name" is used in order to remove the quotation marks from output of "paste". So the second argument passed to assign returns a character which has the exact same name as the numeric vector that I want get the mean of, e.g. val_a. But I get the error messsage:

Warning messages:
1: In mean.default(as.name(paste("val", letters[j], sep = "_"))) :
  argument is not numeric or logical: returning NA

Does anyone know how to accomplish this?

答:
Solution

To build on bouncyball's comment so you have a full answer, you can do this:

```<code>sapply(paste('val', letters[1:20], sep='_'), function(x) round(mean(get(x)), 3))
</code>```

Explanation

For an object in your environment called x, get("x") will return x. See help("get"). Then we can do this for every element of paste('val', letters[1:20], sep='_') using sapply(), or if you like, a loop.

Example

```<code>val_a <- rnorm(100)
val_b <- rnorm(100)
val_c <- rnorm(100)

sapply(paste('val', letters[1:3], sep='_'), function(x) round(mean(get(x)), 3))

      val_a       val_b       val_c
-0.09328504 -0.15632654 -0.09759111
</code>```

Body:
I have over 20 numeric vectors which consist of a series of values. each vector is distinguished by a letter, e.g. val_a, val_b, val_c etc...

I would like to put the means from each of these vectors into a single named vector. I could of course do this in a laborious manner like so:

obs <- c("val_a" = round(mean(val_a),3),
         "val_b" = round(mean(val_b),3),
         "val_c" = round(mean(val_c),3))

But with 20 vectors this then becomes tedious to write out, and not to mention an inelegant solution. How can I create the named vector in a more succinct way? I have made an attempt using a for loop, as so:

obs <- c(for (j in 1:20) {
  assign(paste("val",letters[j], sep = "_"),
  mean(as.name(paste('val',letters[j], sep = '_'))),)
})

In the right hand argument passed to assign, "as.name" is used in order to remove the quotation marks from output of "paste". So the second argument passed to assign returns a character which has the exact same name as the numeric vector that I want get the mean of, e.g. val_a. But I get the error messsage:

Warning messages:
1: In mean.default(as.name(paste("val", letters[j], sep = "_"))) :
  argument is not numeric or logical: returning NA

Does anyone know how to accomplish this?

Body:
Solution

To build on bouncyball's comment so you have a full answer, you can do this:

sapply(paste('val', letters[1:20], sep='_'), function(x) round(mean(get(x)), 3))

Explanation

For an object in your environment called x, get("x") will return x. See help("get"). Then we can do this for every element of paste('val', letters[1:20], sep='_') using sapply(), or if you like, a loop.

Example

val_a <- rnorm(100)
val_b <- rnorm(100)
val_c <- rnorm(100)

sapply(paste('val', letters[1:3], sep='_'), function(x) round(mean(get(x)), 3))

      val_a       val_b       val_c
-0.09328504 -0.15632654 -0.09759111


问:
Java library for calling exteral programs
I am looking for a JAVA library that facilitates running external programs. Now I run them "manually" in a separate thread and capture I/O.

I have several different external tools to run and what I need is a uniform approach to do that. The tasks I have to handle includes:
- preparing input files according to predefined templates
- running the commands
- waiting for the results and parsing output files
- maintaining the pipeline

The whole pipeline can be considered as a graph with external tools as nodes and data flow as edges. It would be great if the software could run some of the commands in parallel threads, if the data flow permits.

Is there an existing solution of such problems?

Based on the answers I got I feel I have to clarify: I don't need pipes. Data flow can be solved with files, which I need anyway. Moreover, pipes have to be linear (1 output -> 1 input) but I need a graph

I already have a kind of a prototype in python - a bunch of scripts. It is good but as for me - not scalable. Moreover some of the programs I call are in java, so making the whole thing in java would be handy.
Best,
Tim

答: I would think  ant should be perfect for this. It also has fairly good java library to do file processing. Between that and maybe velocity templates, i would think you should be able to do what you want. </p>

ContentLicense: CC BY-SA 2.5


答:
It seems to be a documentation bug; even in the 12cR2 documentation it still says:

```<code>NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)
</code>```

instead of

```<code>NVL(salary, 0) + NVL(salary*commission_pct, 0) > 25000
</code>```

or

```<code>NVL(salary + salary*commission_pct, 0) > 25000
</code>```

or (closer to the original, though this looks like an odd thing to want to find)

```<code>NVL(salary, 0) + NVL(salary + salary*commission_pct, 0) > 25000
</code>```

or some other valid variant depending on what it's supposed to be checking...

And as others have already pointed out it's a condition, so it goes in a where clause, not in the select list.

Title: Missing parenthesis in expression in Oracle Documentation?

Body:
Found this condition in Oracle SQL documentation:

NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)

https://docs.oracle.com/database/122/SQLRF/About-SQL-Conditions.htm#SQLRF52101

It explains, "The following complex condition adds the salary value to the commission_pct value (substituting the value 0 for null) and determines whether the sum is greater than the number constant 25000:".
But when I tried to execute it, it throws an error,

'MISSING RIGHT PARENTHESIS'.

Is this condition valid ? or Is there some other way to execute it.

SELECT  NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000) FROM HR.Employees;

Any help will be appreciated, Thank you.

Body:
It seems to be a documentation bug; even in the 12cR2 documentation it still says:

NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)

instead of

NVL(salary, 0) + NVL(salary*commission_pct, 0) > 25000

or

NVL(salary + salary*commission_pct, 0) > 25000

or (closer to the original, though this looks like an odd thing to want to find)

NVL(salary, 0) + NVL(salary + salary*commission_pct, 0) > 25000

or some other valid variant depending on what it's supposed to be checking...

And as others have already pointed out it's a condition, so it goes in a where clause, not in the select list.


问:
convert orderdate of format m/d/yy to YYYY-MM-DD in R
My orderdate is in factor and i want to convert it into from mm/dd/yy format to YYYY-MM-DD format.

```<code> orderdate : Factor w/ 155932 levels "1/1/2017 1:05:00 AM",..: 41 1 1 89 100 102 106 107 119 122 ...
</code>```

I tried couple of things:

```<code>orders2017$newdate <- (factor(orders2017$orderdate))
orders2017$newdate1 <- as.Date(orders2017$newdate,format="%Y-%m-%d")
</code>```

but nothing is working out and giving me new columns as empty. Any help is appreciated

答:
If you really have values like "1/1/2017 1:05:00 AM" then those aren't dates, they are date times, and as such you have to specify formatting characters for both the date and time parts.

So, first you need to get your date times into a form R understands as such (e.g. POSIXct) by specifying all the parts of the date time:

```<code>test <- as.POSIXct("1/1/2017 1:05:00 AM", format = '%m/%d/%Y %I:%M:%S %p')
test

> test
[1] "2017-01-01 01:05:00 CST"
</code>```

See ?strftime if you are not familiar with all the formatting placeholders used above, and note the conditions for use of %I and %p.

Then you can convert the POSIXct vector into the date format you desire

```<code>format(test, format = '%Y-%m-%d')

> format(test, format = '%Y-%m-%d')
[1] "2017-01-01"
</code>```

A complication for you is that R has converted your character date times into a factor, so you need to convert them back to a character vector before converting to date times. For example (not tested as you didn't supply example data)

```<code>orders2017 <- transform(orders2017,
                        orderdate = as.POSIXct(as.character(orderdate),
                                               format = '%m/%d/%Y %I:%M:%S %p'))
orders2017 <- transform(orders2017,
                        newdate = format(orderdate, format = '%Y-%m-%d'))
</code>```

Body:
My orderdate is in factor and i want to convert it into from mm/dd/yy format to YYYY-MM-DD format.

 orderdate : Factor w/ 155932 levels "1/1/2017 1:05:00 AM",..: 41 1 1 89 100 102 106 107 119 122 ...

I tried couple of things:

orders2017$newdate <- (factor(orders2017$orderdate))
orders2017$newdate1 <- as.Date(orders2017$newdate,format="%Y-%m-%d")

but nothing is working out and giving me new columns as empty. Any help is appreciated

Body:
If you really have values like "1/1/2017 1:05:00 AM" then those aren't dates, they are date times, and as such you have to specify formatting characters for both the date and time parts.

So, first you need to get your date times into a form R understands as such (e.g. POSIXct) by specifying all the parts of the date time:

test <- as.POSIXct("1/1/2017 1:05:00 AM", format = '%m/%d/%Y %I:%M:%S %p')
test

> test
[1] "2017-01-01 01:05:00 CST"

See ?strftime if you are not familiar with all the formatting placeholders used above, and note the conditions for use of %I and %p.

Then you can convert the POSIXct vector into the date format you desire

format(test, format = '%Y-%m-%d')

> format(test, format = '%Y-%m-%d')
[1] "2017-01-01"

A complication for you is that R has converted your character date times into a factor, so you need to convert them back to a character vector before converting to date times. For example (not tested as you didn't supply example data)

orders2017 <- transform(orders2017,
                        orderdate = as.POSIXct(as.character(orderdate),
                                               format = '%m/%d/%Y %I:%M:%S %p'))
orders2017 <- transform(orders2017,
                        newdate = format(orderdate, format = '%Y-%m-%d'))


问:
sort and join file in bash (script)
How do I get each field of the join command output to be separated by tabs?</p>

答:
This is a job for a process substitution:

```<code>join <(sort annotation) <(sort output2.txt) >outputtest.txt
</code>```

In this usage, <(sort annotation) will be replaced with a file-like object (either /dev/fd/10-form or a named pipe) which, when read from, contains the output of the command sort annotation. Thus, join will see sorted input without needing to modify either file in-place (which the original code didn't actually do).

Title: sort and join file in bash (script)

Body:
This is a job for a process substitution:

join <(sort annotation) <(sort output2.txt) >outputtest.txt

In this usage, <(sort annotation) will be replaced with a file-like object (either /dev/fd/10-form or a named pipe) which, when read from, contains the output of the command sort annotation. Thus, join will see sorted input without needing to modify either file in-place (which the original code didn't actually do).


问:
CSS using z-index doesn't place child element behind its parent
I am trying to make a drop down menu that slides from header.
I have a header and inside it I have some div with border-bottom 1px line and background-color. Inside this div I would like to place logo, searchbox some links and a user profile button. When this button is clicked I would like to drop down menu below this button. Unfortunately this dropdown menu appears in front of header and not slides from behind of header (obscuring the header background and bottom-border line). I have tried solution like below (it is simplified version).

header {
  position: relative;
  z-index: 5;
}

.dropdown {
  background-color: yellow;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
}

.background {
  position: absolute;
  background-color: #ccca;
  border-bottom: 1px solid black;
  width: 100%;
  height: 50px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="background">
    <div class="dropdown">
    </div>
  </div>
</header></code>```

I have tried many z-index configurations and none of them seems to work.
1. div.background with z-index 2, div.dropdown with z-index 1 or even -1
2. div.background without z-index and position, div.dropdown with z-index -1 (here dropdown was behind header but menu links stopped working and menu was also behind main content of webpage)

How can I make my div.dropdown to slide from behind the header bar with background and border bottom line? Isn't it possible to have this div.dropdown inside header div tree as the descendant element.

答:
This is possible with a negative z-index; however, it doesn't work with a parent element that has a non-auto z-index.  Set the .background element to have a z-index:auto (or just take it off.  auto is the default).  It's OK (and recommended imo) to have an ancestor element with a positive z-index to avoid your negative z-indexed element dropping below the  or  elements.  In this case, you do (header has a z-index of 5), so it's fine.

```

Body:
I am trying to make a drop down menu that slides from header.
I have a header and inside it I have some div with border-bottom 1px line and background-color. Inside this div I would like to place logo, searchbox some links and a user profile button. When this button is clicked I would like to drop down menu below this button. Unfortunately this dropdown menu appears in front of header and not slides from behind of header (obscuring the header background and bottom-border line). I have tried solution like below (it is simplified version).

header {
  position: relative;
  z-index: 5;
}

.dropdown {
  background-color: yellow;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
}

.background {
  position: absolute;
  background-color: #ccca;
  border-bottom: 1px solid black;
  width: 100%;
  height: 50px;
  z-index: 2;
}

I have tried many z-index configurations and none of them seems to work.
1. div.background with z-index 2, div.dropdown with z-index 1 or even -1
2. div.background without z-index and position, div.dropdown with z-index -1 (here dropdown was behind header but menu links stopped working and menu was also behind main content of webpage)

How can I make my div.dropdown to slide from behind the header bar with background and border bottom line? Isn't it possible to have this div.dropdown inside header div tree as the descendant element.

Body:
This is possible with a negative z-index; however, it doesn't work with a parent element that has a non-auto z-index.  Set the .background element to have a z-index:auto (or just take it off.  auto is the default).  It's OK (and recommended imo) to have an ancestor element with a positive z-index to avoid your negative z-indexed element dropping below the <html> or <body> elements.  In this case, you do (header has a z-index of 5), so it's fine.

<html>
<head>
<style type="text/css">
header {
 position:relative;
 z-index:5;

}
.dropdown {
 background-color: yellow;
 width: 100px;
 height: 100px;
 position: absolute;
 z-index: -1;
}
.background {
 position: absolute;
 background-color:#ccca;
 border-bottom: 1px solid black;
 width: 100%;
 height: 50px;
 z-index: auto;
}
</style>
</head>
<body>
<header>
 <div class="background">
  <div class="dropdown">
  </div>
 </div>
</header>
</body>
</html>


问:
Missing parenthesis in expression in Oracle Documentation?
Found this condition in Oracle SQL documentation:

```<code>NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000)
</code>```

https://docs.oracle.com/database/122/SQLRF/About-SQL-Conditions.htm#SQLRF52101

It explains, "The following complex condition adds the salary value to the commission_pct value (substituting the value 0 for null) and determines whether the sum is greater than the number constant 25000:".
But when I tried to execute it, it throws an error,

'MISSING RIGHT PARENTHESIS'.

Is this condition valid ? or Is there some other way to execute it.

```<code>SELECT  NVL(salary, 0) + NVL(salary + (salary*commission_pct, 0) > 25000) FROM HR.Employees;
</code>```

Any help will be appreciated, Thank you.

答:
Yes. It is a documentation  bug as at the time of writing this answer.

You should use this condition in where clause rather than select, removing some of the braces.

```<code>SELECT
    *
FROM
    hr.employees
WHERE
    nvl(salary,0) + nvl(salary + salary * commission_pct,0) > 25000;
</code>```

However, this is a more appropriate logic to compare.

```<code>NVL(salary, 0) + NVL(salary*commission_pct, 0) > 25000
</code>```

Body:
Yes. It is a documentation  bug as at the time of writing this answer.

You should use this condition in where clause rather than select, removing some of the braces.

SELECT
    *
FROM
    hr.employees
WHERE
    nvl(salary,0) + nvl(salary + salary * commission_pct,0) > 25000;

However, this is a more appropriate logic to compare.

NVL(salary, 0) + NVL(salary*commission_pct, 0) > 25000


问:
NSIS - Adding other type of files
I have a NSIS generated-installer, however, I would like to add other files to the installer at compile time. For example, I want to add a batch file to the installer, so when the .exe file is ran, I can call that batch file within the .exe without needing to copy the actual batch file to the output location. This means the batch file will actually exist within the installer.

I hope this makes sense and thanks.

答:
A batch file has to be extracted somewhere before it can be executed. $PluginsDir is a good choice because it is deleted when the installer ends.</p>

```<code>Section
SetOutPath $Instdir
File myfiles\*

InitPluginsDir
SetOutPath $PluginsDir
File file.bat
nsExec::Exec '"cmd.exe" /c if 1==1 "$PluginsDir\file.bat"'
Pop $0 ; Exit code
SetOutPath $Temp ; Don't hold lock on pluginsdir
SectionEnd
</code>```

Title: NSIS - Adding other type of files

Body:
A batch file has to be extracted somewhere before it can be executed. $PluginsDir is a good choice because it is deleted when the installer ends.

Section
SetOutPath $Instdir
File myfiles\*

InitPluginsDir
SetOutPath $PluginsDir
File file.bat
nsExec::Exec '"cmd.exe" /c if 1==1 "$PluginsDir\file.bat"'
Pop $0 ; Exit code
SetOutPath $Temp ; Don't hold lock on pluginsdir
SectionEnd


问:
Do.. While.. with Exists predicates. Access to modified closure?
```<code>string reference;
do {
  reference = GenerateNewReference();
} while (currentItems.Exists(i=>i.Reference.Equals(reference));
</code>```

ReSharper is warning me about this, something called Access to Modified Closure. I've tried my best to read and understand it, but my code still seems fine to me.

Is there a problem with my code?

答:
It's fine in your case because the value of reference doesn't change over the lifetime of your lambda. But resharper doesn't know that. As far as resharper can see the lambda might survive for a longer time during which reference changes its value.

The rule is intended to warn you when you write code like this:

```<code>int myInt=1;
Func<int,bool> IsOne = i=>i==myInt;
myInt=2;
IsOne(1);//=> false
IsOne(2);//=> true
</code>```

because the IsOne lambda binds to myInt by reference, and not by value.

Body:
string reference;
do {
  reference = GenerateNewReference();
} while (currentItems.Exists(i=>i.Reference.Equals(reference));

ReSharper is warning me about this, something called Access to Modified Closure. I've tried my best to read and understand it, but my code still seems fine to me.

Is there a problem with my code?

Body:
It's fine in your case because the value of reference doesn't change over the lifetime of your lambda. But resharper doesn't know that. As far as resharper can see the lambda might survive for a longer time during which reference changes its value.

The rule is intended to warn you when you write code like this:

int myInt=1;
Func<int,bool> IsOne = i=>i==myInt;
myInt=2;
IsOne(1);//=> false
IsOne(2);//=> true

because the IsOne lambda binds to myInt by reference, and not by value.


问:
Use Swift URLSession example code on command line tool
I am trying to figure out the simplest way to make an HTTP request in Swift 4 from the command line. I have copied this code from the URLSession programming guide, and added a couple print statements. I can't figure out why the .dataTask is not executing.

```<code>print("Testing URLSession")
let sessionWithoutADelegate = URLSession(configuration: URLSessionConfiguration.default)
if let url = URL(string: "https://www.example.com/") {
    print("Encoded url \(url)")
    (sessionWithoutADelegate.dataTask(with: url) { (data, response, error) in
        print("Executing dataTask")
        if let error = error {
            print("Error: \(error)")
        } else if let response = response,
            let data = data,
            let string = String(data: data, encoding: .utf8) {
            print("Response: \(response)")
            print("DATA:\n\(string)\nEND DATA\n")
        }
    }).resume()
}
</code>```

The objective is to retrieve data from a REST api, but I can't even make a simple GET request to work properly...

答:
I finally figured out how to make it work using CFRunLoop:

```<code>let runLoop = CFRunLoopGetCurrent()
let task = session.dataTask(with: request) { (data, response, error) in
    print("Retrieved data")
    CFRunLoopStop(runLoop)
}
task.resume()
CFRunLoopRun()
print("done")
</code>```

Body:
I am trying to figure out the simplest way to make an HTTP request in Swift 4 from the command line. I have copied this code from the URLSession programming guide, and added a couple print statements. I can't figure out why the .dataTask is not executing.

print("Testing URLSession")
let sessionWithoutADelegate = URLSession(configuration: URLSessionConfiguration.default)
if let url = URL(string: "https://www.example.com/") {
    print("Encoded url \(url)")
    (sessionWithoutADelegate.dataTask(with: url) { (data, response, error) in
        print("Executing dataTask")
        if let error = error {
            print("Error: \(error)")
        } else if let response = response,
            let data = data,
            let string = String(data: data, encoding: .utf8) {
            print("Response: \(response)")
            print("DATA:\n\(string)\nEND DATA\n")
        }
    }).resume()
}

The objective is to retrieve data from a REST api, but I can't even make a simple GET request to work properly...

Body:
I finally figured out how to make it work using CFRunLoop:

let runLoop = CFRunLoopGetCurrent()
let task = session.dataTask(with: request) { (data, response, error) in
    print("Retrieved data")
    CFRunLoopStop(runLoop)
}
task.resume()
CFRunLoopRun()
print("done")


问:
Wordpress blog : Import content
I am running a website using PHP/MySQL. Now I want to allow Blogs using wordpress in my website so I can use Google Adsense along with blog content. I have installed Wordpress on my site, using tools provided by host service provider.

Now is there anyway I can import selective-content from MySQL database to these wordpress blogs? If so, how?

Thanks.

答:
Yes you can import/export your contents from/to other site respectively using following ways

Using Plugins like duplicator etc

Using the existing WordPress tools availabe in the Dashboard/Admin section like Import & Export

There may be other different methods also available on the internet.

Title: Wordpress blog : Import content


问:
How to apply jquery only to the element selected with if statement?
I am trying to select a certain element on a page. All the elements have the same class same everything, with the only exception that the background image is different on some of them.

What I need to do is to ONLY apply the jquery code to only the element chosen via the if statement.

Please note I cannot edit the HTML, I need to use jquery for this.

Here is my code:

```<code>$('.repeated-element').each( function(){
   if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});
</code>```

I have selected the element just fine and jquery is running. I know this because I get the alert popup which shows that part (if ( $(this).css('background-image').indexOf('mystringzzz') ) {) works.

However, the problem is that I can only get it to apply to either the first element (which is not the one that is selected) or to all of the elements.

If I use:

```<code>$(this).closest('div.someclass').addClass('aclassilike');
</code>```

the result is it applies to only the very first recurrence on the page, NOT the selected one.

Alternatively if I use:

```<code>$('.repeated-element').closest('div.someclass').addClass('aclassilike');
</code>```

Then the result is it applies every recurrence on the page, not only the selected ones. It is supposed to be only the selected one.

How can I ONLY apply the jquery code to only the element chosen via the if statement?

For example,

a) inside the .repeated-element,

  b) ONLY which contains a background-image css in the external stylesheet which has part of the image name as mystringzzz,

  c) then apply the new jquery (in this example adding another class).

  d) But do not apply it to elements which do not contain the mystringzzz string in background-image.

答:
It seems you also need to remove the url from the background-image property

$('.repeated-element').each(function() {
  // removing url and only getting the image
  var getURL = $(this).css('background-image').replace('url(', '').replace(')', '').replace(/\"/gi, "");
  if (getURL.indexOf('mystringzzz') !== -1) {
    $(this).closest('div.someclass').addClass('aclassilike');
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.repeated-element {
  color: red
}

.aclassilike {
  background: green;
}</code>```

1

1

1

1

```

Body:
I am trying to select a certain element on a page. All the elements have the same class same everything, with the only exception that the background image is different on some of them.

What I need to do is to ONLY apply the jquery code to only the element chosen via the if statement.

Please note I cannot edit the HTML, I need to use jquery for this.

Here is my code:

$('.repeated-element').each( function(){
   if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});

I have selected the element just fine and jquery is running. I know this because I get the alert popup which shows that part (if ( $(this).css('background-image').indexOf('mystringzzz') ) {) works.

However, the problem is that I can only get it to apply to either the first element (which is not the one that is selected) or to all of the elements.

If I use:

$(this).closest('div.someclass').addClass('aclassilike');

the result is it applies to only the very first recurrence on the page, NOT the selected one.

Alternatively if I use:

$('.repeated-element').closest('div.someclass').addClass('aclassilike');

Then the result is it applies every recurrence on the page, not only the selected ones. It is supposed to be only the selected one.

How can I ONLY apply the jquery code to only the element chosen via the if statement?

For example,

a) inside the .repeated-element,

  b) ONLY which contains a background-image css in the external stylesheet which has part of the image name as mystringzzz,

  c) then apply the new jquery (in this example adding another class).

  d) But do not apply it to elements which do not contain the mystringzzz string in background-image.

Body:
It seems you also need to remove the url from the background-image property

$('.repeated-element').each(function() {
  // removing url and only getting the image
  var getURL = $(this).css('background-image').replace('url(', '').replace(')', '').replace(/\"/gi, "");
  if (getURL.indexOf('mystringzzz') !== -1) {
    $(this).closest('div.someclass').addClass('aclassilike');
  }

});

.repeated-element {
  color: red
}

.aclassilike {
  background: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='someclass'>
  <div style='background-image:url("mystringzzz")' class='repeated-element'>1</div>
</div>

<div class='someclass'>
  <div class='repeated-element'>1</div>
</div>
<div class='someclass'>
  <div class='repeated-element'>1</div>
</div>
<div class='someclass'>
  <div style='background-image:url("mystringzzz")' class='repeated-element'>1</div>
</div>


问:
Best way to avoid deadlock for several objects transaction?
I was looking for deadlock example and stumbled across this code:

```<code>package com.example.thread.deadlock._synchronized;

public class BankAccount {
    double balance;
    int id;

    BankAccount(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    void withdraw(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance -= amount;
    }

    void deposit(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance += amount;
    }

    static void transfer(BankAccount from, BankAccount to, double amount) {
        synchronized(from) {
            from.withdraw(amount);
            synchronized(to) {
                to.deposit(amount);
            }
        }
    }

    public static void main(String[] args) {
        final BankAccount fooAccount = new BankAccount(1, 100d);
        final BankAccount barAccount = new BankAccount(2, 100d);

        new Thread() {
            public void run() {
                BankAccount.transfer(fooAccount, barAccount, 10d);
            }
        }.start();

        new Thread() {
            public void run() {
                BankAccount.transfer(barAccount, fooAccount, 10d);
            }
        }.start();

    }
}
</code>```

How would you change transfer method so that it doesn't cause deadlock? First thought is to create a shared lock for all accounts, but that of course would just kill all concurrency. So is there a good way to lock just two accounts involved into a transaction and not affect other accounts?

答:
Use two synchronized blocks separately instead of nested.

```<code>synchronized(from){
    from.withdraw(amount);
}
synchronized(to){
    to.deposit(amount);
}
</code>```

So after from.withdraw(amount) is called, the lock on from is released before it tries to lock on to

Body:
I was looking for deadlock example and stumbled across this code:

package com.example.thread.deadlock._synchronized;

public class BankAccount {
    double balance;
    int id;

    BankAccount(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    void withdraw(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance -= amount;
    }

    void deposit(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance += amount;
    }

    static void transfer(BankAccount from, BankAccount to, double amount) {
        synchronized(from) {
            from.withdraw(amount);
            synchronized(to) {
                to.deposit(amount);
            }
        }
    }

    public static void main(String[] args) {
        final BankAccount fooAccount = new BankAccount(1, 100d);
        final BankAccount barAccount = new BankAccount(2, 100d);

        new Thread() {
            public void run() {
                BankAccount.transfer(fooAccount, barAccount, 10d);
            }
        }.start();

        new Thread() {
            public void run() {
                BankAccount.transfer(barAccount, fooAccount, 10d);
            }
        }.start();

    }
}

How would you change transfer method so that it doesn't cause deadlock? First thought is to create a shared lock for all accounts, but that of course would just kill all concurrency. So is there a good way to lock just two accounts involved into a transaction and not affect other accounts?

Body:
Use two synchronized blocks separately instead of nested.

synchronized(from){
    from.withdraw(amount);
}
synchronized(to){
    to.deposit(amount);
}

So after from.withdraw(amount) is called, the lock on from is released before it tries to lock on to


问:
PyCharm doesn't detect interpreter
I'm new to programming and just started a course on Python. I want to use PyCharm, so I downloaded and intalled it (v. 4.5, community edition). I had previously installed Python 3.5 64-bit from python.org (I'm using Windows 10).

To start using PyCharm, I need a project interpreter, which I can select in the settings. As far as I'm concerned, the interpreter is "py.exe", but when I select it, I get this error message: "The selected file is not a valid home for Python SDK". I also tried to use every file whose name contained "python" or "py", and failed.

On every website and video I see, they select a file called "python.exe", but they're using Python 3.4 or a previous version. I checked that PyCharm supports 3.5 ("Initial support for Python 3.5").

Is there anything I'm doing wrong? What should I do to be able to use PyCharm?

All replies are appreciated. Thanks in advance.

答:
PyCharm  project interpreter problem Resolved

 I installed anaconda python distribution (Anaconda3-5.0.1-Windows-x86_64.exe) from the anaconda website.  https://anaconda.org/anaconda/python

What it actually did was it re-installed my Python3.6.3 (pertinent to mention I have windows10, with pyCharm community & python 3.5 already but with the interpreter problem and while installing anaconda I chose the following settings and disabled my antivirus before my anaconda installation):

selecting allow for all users

installation path was set correctly and (stored safely for future)

restart my Computer after installation.(not essential-but I did)

opened Anaconda & Jet brian pycharm

selected new project in PyCharm  screen shot of my New project default Python interpreter    location = C:\Users\Skboy\PycharmProjects\dani     Interpreter = C:\Users\Skboy\AppData\Local\Programs\Python\Python36-32\python.exe

Wow!  my pyCharm started working for me,

Resolution : Python6.3 re-installation with proper custom setting

make a python test test1.py program file to print "hello python test world"

Run

now my Python Interpreter(automatically -by default select) Python 3.6.3

edit configuration   & check for interpreter

(C:\Users\user1\AppData\Local\Programs\Python\Python36-32\python.exe)

Run

success test Run

worth to mention Anaconda Jupyter is  a web based can also be used in case novice user are still having problems

Title: PyCharm doesn't detect interpreter


问:
org/glassfish/jersey/jackson/JacksonFeature is not defined in my rest API
I have created a small REST API which seems to work just fine. I wanted to use the Twitter API and display some tweets. But when I try to do that my server throws an error.

Reaching one of my old resources works just fine when trying this URL: http://localhost:8080/api-mashup-api/api/v1/foo/bar:

```<code>    @GET
    @Path("/bar")
    @Produces(MediaType.TEXT_HTML)
    public String print2() {
        return "This should be printed if in foo/bar";
    }
</code>```

But If I try my "twitter method" at http://localhost:8080/api-mashup-api/api/v1/foo/twitter:

```<code>    @GET
    @Path("/twitter")
    @Produces(MediaType.TEXT_HTML)
    public String print5() {
        //I have my real tokens here of course.
        ClientIdentifier ci = new ClientIdentifier("clientID",
                "ClientSecret");

        OAuth2CodeGrantFlow flow = OAuth2ClientSupport
                .authorizationCodeGrantFlowBuilder(ci,
                "https://api.twitter.com/oauth2/token", "https://api.twitter.com/oauth2/token")
                .scope("contact")
                .build();

        String finalAuthorizationUri = flow.start();

        return "This is the bearer: " + finalAuthorizationUri.toString();
    }
</code>```

It throws the following error:

```<code> HTTP Status 500 - org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/glassfish/jersey/jackson/JacksonFeature
</code>```

In reality it should just print my bearer token. I have tried importing various jackson jar files but not managed to get it working. I might add that I use Tomcat v8 and not Glassfish server.

答:
You are missing a jar, specifically jersey-media-json-jackson-2.XX.jar (where XX is the version of jersey that you are using)

you can add the maven dependency like:

```<code><!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.26</version>
</dependency>
</code>```

Body:
I have created a small REST API which seems to work just fine. I wanted to use the Twitter API and display some tweets. But when I try to do that my server throws an error.

Reaching one of my old resources works just fine when trying this URL: http://localhost:8080/api-mashup-api/api/v1/foo/bar:

    @GET
    @Path("/bar")
    @Produces(MediaType.TEXT_HTML)
    public String print2() {
        return "This should be printed if in foo/bar";
    }

But If I try my "twitter method" at http://localhost:8080/api-mashup-api/api/v1/foo/twitter:

    @GET
    @Path("/twitter")
    @Produces(MediaType.TEXT_HTML)
    public String print5() {
        //I have my real tokens here of course.
        ClientIdentifier ci = new ClientIdentifier("clientID",
                "ClientSecret");

        OAuth2CodeGrantFlow flow = OAuth2ClientSupport
                .authorizationCodeGrantFlowBuilder(ci,
                "https://api.twitter.com/oauth2/token", "https://api.twitter.com/oauth2/token")
                .scope("contact")
                .build();

        String finalAuthorizationUri = flow.start();

        return "This is the bearer: " + finalAuthorizationUri.toString();
    }

It throws the following error:

 HTTP Status 500 - org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/glassfish/jersey/jackson/JacksonFeature

In reality it should just print my bearer token. I have tried importing various jackson jar files but not managed to get it working. I might add that I use Tomcat v8 and not Glassfish server.

Body:
You are missing a jar, specifically jersey-media-json-jackson-2.XX.jar (where XX is the version of jersey that you are using)

you can add the maven dependency like:

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.26</version>
</dependency>


问:
perform MINUS operation in MySQL not working
```<code>SELECT m.inv_id,m.cus_id,CONCAT(c.customer_name ,', ', c.address) AS address,d.item_id,p.prod_name,d.quantity
FROM invoice_m m INNER JOIN customers c INNER JOIN invoice_d d INNER JOIN products p
WHERE m.cus_id = c.customer_id
AND m.inv_id = d.inv_id
AND d.item_id = p.prod_id
AND m.inv_id = 3
minus
SELECT m.inv_id,m.cus_id,m.cus_addr AS address,d.item_id,d.item_name AS prod_name,d.out_qty AS quantity
FROM delivery_m m INNER JOIN delivery_d d
WHERE m.inv_id = 3
</code>```

i am trying to perform MySQL minus query not working.I need to minus (qty - out_qty ) so that i can get actual qty.

答:
MySQL doesn’t support  MINUS set operators.

so a query like

```<code>  SELECT x, y FROM table_a
  MINUS
  SELECT x, y FROM table_b;
</code>```

In MySQL became:

```<code>SELECT a.x, a.y
FROM table_a a LEFT JOIN table_b b
ON a.x = b.x AND a.y = b.y
WHERE b.x IS NULL;
</code>```

Body:
SELECT m.inv_id,m.cus_id,CONCAT(c.customer_name ,', ', c.address) AS address,d.item_id,p.prod_name,d.quantity
FROM invoice_m m INNER JOIN customers c INNER JOIN invoice_d d INNER JOIN products p
WHERE m.cus_id = c.customer_id
AND m.inv_id = d.inv_id
AND d.item_id = p.prod_id
AND m.inv_id = 3
minus
SELECT m.inv_id,m.cus_id,m.cus_addr AS address,d.item_id,d.item_name AS prod_name,d.out_qty AS quantity
FROM delivery_m m INNER JOIN delivery_d d
WHERE m.inv_id = 3

i am trying to perform MySQL minus query not working.I need to minus (qty - out_qty ) so that i can get actual qty.

Body:
MySQL doesn’t support  MINUS set operators.

so a query like

  SELECT x, y FROM table_a
  MINUS
  SELECT x, y FROM table_b;

In MySQL became:

SELECT a.x, a.y
FROM table_a a LEFT JOIN table_b b
ON a.x = b.x AND a.y = b.y
WHERE b.x IS NULL;


问:
Database Normalization mistake
I'm preparing an exam and on my texts I found an example I don't understand.

On the Relation R(A,B,C,D,E,F) I got the following functional dependencies:

```<code>FD1 A,B -> C
FD2 C -> B
FD3 C,D -> E
FD4 D -> F
</code>```

Now I think all The FD are in 3NF (none is in BCNF), but the text says FD1 and FD2 to be in 2NF and FD3 and FD4 to be in 1NF. Where am I making mistakes (or is it the text wrong).

I found alternative keys to be ABD and ACD

答:
Terminology

It is highly improper to say that: “a Functional Dependency in is in a certain Normal Form”, since only a relation schema can be (or not) in a Normal Form. What can be said is that a Functional Dependency violates a certain Normal Form (so that the schema that contains it is not in that Normal Form).

Normal forms

It can be shown that a relation schema is in BCNF if every FD given has as determinant a superkey. Since, has you have correctly noted, the only candidate keys here are ABD and ACD, every dependency violates that Normal Form. So, the schema is not in BCNF.

To be in 3NF, a relation schema must have all the given functional dependencies such that either the determinant is a superkey, or every attribute of the determinate is a prime attribute, that is it is an attribute of some candidate key. In your example this is true for B and C, but not for E and F, so FD3 and FD4 violates the 3NF. So, the schema is neither in 3NF.

The 2NF, which is only of historical interest and not particularly useful in the normalization theory, is a normal form for which the relation schema does not have functional dependencies in which non-prime attributes depend on part of keys. This is not true again for FD3 and FD4, so that the relation is neither in 2NF.

Title: Database Normalization mistake

Body:
I'm preparing an exam and on my texts I found an example I don't understand.

On the Relation R(A,B,C,D,E,F) I got the following functional dependencies:

FD1 A,B -> C
FD2 C -> B
FD3 C,D -> E
FD4 D -> F

Now I think all The FD are in 3NF (none is in BCNF), but the text says FD1 and FD2 to be in 2NF and FD3 and FD4 to be in 1NF. Where am I making mistakes (or is it the text wrong).

I found alternative keys to be ABD and ACD


问:
how to prepend/append addtional values with default values of groupText of jqgrid grouping?
I am using Non-Commercial version of Guriddo JS jqgrid. [Also I tried the same using "free jqgrid" as well,  it didn't work,and I don't know how to do it.] I am using grouping method.

on the grouped row, I am seeing a number value like 276 , 155 like that. But what I want to see is, Group:#276 or Group:#155 - someTextToappend like this.

I order to achieve this, I am using a custom formatter in the colModel like,
{name:"ticket_id",index:"ticket_id",align:"right",formatter:taskTextFormat

I have a function as follows,

```<code>function taskTextFormat(cellvalue,options,rowObject){
     // I am returning a string concatenated value something like
    return "Group:#"+rowObect["task_ID"];
    }
</code>```

and I have set groupingField to that column ticket_id so this function is triggered and values are returned but I am seeing same text over all the grouped rows. like,

```<code>Group:#276 // row one
Group:#276 // row two , I think the last groupText value is reflected on all other grouped rows as well.
</code>```

Instead, what I wanted is,

```<code>Group:#276 // row one
Group:#277 // row two
Group:#278 // row three and so on.
</code>```

Please help me on this, I am not sure this is the right way to do this, if there is a better way I would be happy to use that.

答:
The problem: you use custom formatter in the demo https://jsfiddle.net/4aojr87w/ to format the first column. The formatter will be used not only for formatting of data, but for formatting of the group header too. You can test the type of rowData or options.rowData to detect, whether the row of data or the group header heed be formatted. The rowData parameter (or options.rowData) will be object with amount property only in case of formatting the data. Thus you have to change the code of clientFormatter to, for example, the following

```<code>function clientFormatter(cellvalue,options,rowData)
{
    if (typeof rowData === "object") {
        console.log(rowData.amount);
        return cellvalue + " " + rowData.amount;
    } else {
        // formatting for the group header
        return "Group: " + cellvalue + "!!!"
    }
}
</code>```

See https://jsfiddle.net/OlegKi/4aojr87w/1/

Body:
I am using Non-Commercial version of Guriddo JS jqgrid. [Also I tried the same using "free jqgrid" as well,  it didn't work,and I don't know how to do it.] I am using grouping method.

on the grouped row, I am seeing a number value like 276 , 155 like that. But what I want to see is, Group:#276 or Group:#155 - someTextToappend like this.

I order to achieve this, I am using a custom formatter in the colModel like,
{name:"ticket_id",index:"ticket_id",align:"right",formatter:taskTextFormat

I have a function as follows,

function taskTextFormat(cellvalue,options,rowObject){
     // I am returning a string concatenated value something like
    return "Group:#"+rowObect["task_ID"];
    }

and I have set groupingField to that column ticket_id so this function is triggered and values are returned but I am seeing same text over all the grouped rows. like,

Group:#276 // row one
Group:#276 // row two , I think the last groupText value is reflected on all other grouped rows as well.

Instead, what I wanted is,

Group:#276 // row one
Group:#277 // row two
Group:#278 // row three and so on.

Please help me on this, I am not sure this is the right way to do this, if there is a better way I would be happy to use that.

Body:
The problem: you use custom formatter in the demo https://jsfiddle.net/4aojr87w/ to format the first column. The formatter will be used not only for formatting of data, but for formatting of the group header too. You can test the type of rowData or options.rowData to detect, whether the row of data or the group header heed be formatted. The rowData parameter (or options.rowData) will be object with amount property only in case of formatting the data. Thus you have to change the code of clientFormatter to, for example, the following

function clientFormatter(cellvalue,options,rowData)
{
    if (typeof rowData === "object") {
        console.log(rowData.amount);
        return cellvalue + " " + rowData.amount;
    } else {
        // formatting for the group header
        return "Group: " + cellvalue + "!!!"
    }
}

See https://jsfiddle.net/OlegKi/4aojr87w/1/