问:
How to use spinner items as input to get a result
I'm new to android. I'm building an app for city bus fare. I will use two spinners as 'starting' point and 'destination'. I want to match these two input and get the result as 'fare cost' in a textview. Please give me some easy idea of how to implement this.</p>

答:
Here is the working example:

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp">

    <TextView
        android:id="@+id/text_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="30dp"
        android:text="RESULT"/>

    <Spinner
        android:id="@+id/spinner_source"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">

    </Spinner>

    <Spinner
        android:id="@+id/spinner_destination"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">

    </Spinner>

</LinearLayout>
</code>```

MainActivity.java

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TextView textResult;
    Spinner spinnerSource;
    Spinner spinnerDestination;

    String source;
    String destination;
    int cost = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Views
        textResult = (TextView) findViewById(R.id.text_result);
        spinnerSource = (Spinner) findViewById(R.id.spinner_source);
        spinnerDestination = (Spinner) findViewById(R.id.spinner_destination);

        // Spinner Drop down elements
        List<String> locations = new ArrayList<String>();
        locations.add("Location 1");
        locations.add("Location 2");
        locations.add("Location 3");

        // Initialize
        source = locations.get(0);
        destination = locations.get(0);

        // Creating adapter for spinner
        ArrayAdapter<String> adapterSpinnerSource = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);
        ArrayAdapter<String> adapterSpinnerDestination = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);

        // attaching data adapter to spinners
        spinnerSource.setAdapter(adapterSpinnerSource);
        spinnerDestination.setAdapter(adapterSpinnerDestination);

        // Spinner item select listener
        spinnerSource.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                // Source location
                source = parent.getItemAtPosition(position).toString();

                calculateCost();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                // Destination location
                destination = parent.getItemAtPosition(position).toString();

                calculateCost();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void calculateCost() {

        if ((source.equals("Location 1") && destination.equals("Location 2"))
                || (source.equals("Location 2") && destination.equals("Location 1"))) {

            cost = 100;
        } else if ((source.equals("Location 1") && destination.equals("Location 3"))
                || (source.equals("Location 3") && destination.equals("Location 1"))) {

            cost = 200;
        } else if ((source.equals("Location 2") && destination.equals("Location 3"))
                || (source.equals("Location 3") && destination.equals("Location 2"))) {

            cost = 300;
        }

        // Output
        textResult.setText(String.valueOf(cost));
    }
}
</code>```

OUTPUT:

Hope this will help~

Body:
Here is the working example:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="24dp">

    <TextView
        android:id="@+id/text_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="30dp"
        android:text="RESULT"/>

    <Spinner
        android:id="@+id/spinner_source"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">

    </Spinner>

    <Spinner
        android:id="@+id/spinner_destination"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp">

    </Spinner>

</LinearLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    TextView textResult;
    Spinner spinnerSource;
    Spinner spinnerDestination;

    String source;
    String destination;
    int cost = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Views
        textResult = (TextView) findViewById(R.id.text_result);
        spinnerSource = (Spinner) findViewById(R.id.spinner_source);
        spinnerDestination = (Spinner) findViewById(R.id.spinner_destination);

        // Spinner Drop down elements
        List<String> locations = new ArrayList<String>();
        locations.add("Location 1");
        locations.add("Location 2");
        locations.add("Location 3");

        // Initialize
        source = locations.get(0);
        destination = locations.get(0);

        // Creating adapter for spinner
        ArrayAdapter<String> adapterSpinnerSource = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);
        ArrayAdapter<String> adapterSpinnerDestination = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, locations);

        // attaching data adapter to spinners
        spinnerSource.setAdapter(adapterSpinnerSource);
        spinnerDestination.setAdapter(adapterSpinnerDestination);

        // Spinner item select listener
        spinnerSource.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                // Source location
                source = parent.getItemAtPosition(position).toString();

                calculateCost();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                // Destination location
                destination = parent.getItemAtPosition(position).toString();

                calculateCost();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void calculateCost() {

        if ((source.equals("Location 1") && destination.equals("Location 2"))
                || (source.equals("Location 2") && destination.equals("Location 1"))) {

            cost = 100;
        } else if ((source.equals("Location 1") && destination.equals("Location 3"))
                || (source.equals("Location 3") && destination.equals("Location 1"))) {

            cost = 200;
        } else if ((source.equals("Location 2") && destination.equals("Location 3"))
                || (source.equals("Location 3") && destination.equals("Location 2"))) {

            cost = 300;
        }

        // Output
        textResult.setText(String.valueOf(cost));
    }
}

OUTPUT:

Hope this will help~


来源: stackexchange

问:
How to make multi level dropdown menu using select option mentod
i want to make multi level dropdown menu using select and option method</p>

```<code><select>
   <option value="" data-display-text="Select">None</option>
   <option value="oranges">SSC</option>
   <option value="oranges">GATE</option>
   <option value="bananas">BANK PO</option>
   <option value="bananas">RAILWAY</option>
 </select>
</code>```

答:
You can't make multiple levels with the select element.

Any ways, if its any help, there's

```<code><select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i want to make multi level dropdown menu using select and option method

<select>
   <option value="" data-display-text="Select">None</option>
   <option value="oranges">SSC</option>
   <option value="oranges">GATE</option>
   <option value="bananas">BANK PO</option>
   <option value="bananas">RAILWAY</option>
 </select>

Body:
You can't make multiple levels with the select element.

Any ways, if its any help, there's

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>


问:
Ionic Serve error with module.js
My app is working on my macbook air, I cloned the app and tried to run it on my iMac using ionic serve, I am getting this error.

I have tried using different versions of node and looking online for solutions.

```<code>ionic $ module.js:338
    throw err;
          ^
Error: Cannot find module 'escape-string-regexp'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/kel/Documents/Code/gogenieapp-genie-side/node_modules/chalk/index.js:2:26)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
</code>```

答:
The problem is probably about the dependencies. Check your "package.json" file on the project that is working and also the versions of the libraries/dependencies that are installed on this project.

If there is an update on some libraries and your code on the "package.json" file is like:

```<code>"dependencies": {
  ...
  "library": "^3.9.0",
  ...
}
</code>```

then in your new project the latest version of those libraries will be installed. Had the same problem.

Just go to your "package.json" file of the new project and change the code to:

```<code>"dependencies": {
  ...
  "library": "3.9.0",
  ...
}
</code>```

so that, the exact version of the library will be installed. This solved for me due to the updated API of a library.

Title: Ionic Serve error with module.js

Body:
My app is working on my macbook air, I cloned the app and tried to run it on my iMac using ionic serve, I am getting this error.

I have tried using different versions of node and looking online for solutions.

ionic $ module.js:338
    throw err;
          ^
Error: Cannot find module 'escape-string-regexp'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/kel/Documents/Code/gogenieapp-genie-side/node_modules/chalk/index.js:2:26)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)

Body:
The problem is probably about the dependencies. Check your "package.json" file on the project that is working and also the versions of the libraries/dependencies that are installed on this project.

If there is an update on some libraries and your code on the "package.json" file is like:

"dependencies": {
  ...
  "library": "^3.9.0",
  ...
}

then in your new project the latest version of those libraries will be installed. Had the same problem.

Just go to your "package.json" file of the new project and change the code to:

"dependencies": {
  ...
  "library": "3.9.0",
  ...
}

so that, the exact version of the library will be installed. This solved for me due to the updated API of a library.


问:
MySQL - ORDER BY, CASE and DESC
I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

```<code>$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";
</code>```

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

```<code>$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";
</code>```

This one throws a syntax error. How can I achieve this?

答:
Use math:</p>

```<code>ORDER BY
CASE
    WHEN $var = 1 THEN myText1
    WHEN $var = 2 THEN myText2
    WHEN $var = 3 THEN 1000000 - someNumber
END
</code>```

Title: MySQL - ORDER BY, CASE and DESC

Body:
I have a PHP variable called $var. I want to sort my result in dependence of $var. This one works:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber
    END";

But when $var is 3 I need to sort by someNumber with DESC. So I tried this:

$sql = "
SELECT
    myText1,
    myText2,
    someNumber
FROM myTable
ORDER BY
    CASE
        WHEN $var = 1 THEN myText1
        WHEN $var = 2 THEN myText2
        WHEN $var = 3 THEN someNumber DESC
    END";

This one throws a syntax error. How can I achieve this?

Body:
Use math:

ORDER BY
CASE
    WHEN $var = 1 THEN myText1
    WHEN $var = 2 THEN myText2
    WHEN $var = 3 THEN 1000000 - someNumber
END


问:
Better ruby terminal coloring library
There are plenty of coloring libraries: colored, term-ansicolor.
But is there any which can do this:

```<code>puts "#{'hello'.red} world!".bold
</code>```

And world! should be bold.

To make it clear, I want to get this:

```<code>"\e[1m\e[31mhello\e[0m\e[1m world!\e[0m"
</code>```

or better even this (just shorter):

```<code>"\e[1;31mhello\e[0;1m world!\e[0m"
</code>```

instead of this:

```<code>"\e[1m\e[31mhello\e[0m world!\e[0m"
</code>```

答:
The lib is called Highline
It has a color method: say("This should be <%= color('bold', BOLD) %>!")
Which can be easily used to implement String#bold.

ContentLicense: CC BY-SA 2.5

Title: Better ruby terminal coloring library

Body:
There are plenty of coloring libraries: colored, term-ansicolor.
But is there any which can do this:

puts "#{'hello'.red} world!".bold

And world! should be bold.

To make it clear, I want to get this:

"\e[1m\e[31mhello\e[0m\e[1m world!\e[0m"

or better even this (just shorter):

"\e[1;31mhello\e[0;1m world!\e[0m"

instead of this:

"\e[1m\e[31mhello\e[0m world!\e[0m"


问:
Show data from the server in ag-grid
I use ag-grid in my Angular 4 project.

I bring the data from the server and then try to display it in a table, but the table remains empty (although the data exists).

Just to be sure where the problem is, I have an *ngFor which generates the same data and I can see it displayed on the screen.

I also manage to display the data in the ag-grid if I write it manually (hard-coded) and it's parsed when the page is loaded, without any ajax request.

html:

```<code><div style="width: 200px;">
  <ag-grid-angular #agGrid style="width: 100%; height: 200px;" class="ag-fresh"
                   [gridOptions]="gridOptions">
  </ag-grid-angular>
</div>

<table class="table">
  <tr>
    <th>
      Foo
    </th>
    <th>
      Bar
    </th>
  </tr>
  <tr *ngFor="let item of gridOptions.rowData; let myIndex = index">
    <td>
      {{item.foo}}
    </td>
    <td>
      {{item.bar}}
    </td>
  </tr>
</table>
</code>```

ts:

```<code>export class HomeComponent implements OnInit {
private gridOptions: GridOptions;

constructor(
  private adsService: AdsService
) {
  this.gridOptions = {};

  this.gridOptions.columnDefs = [
    {
      headerName: "Foo",
      field: "foo",
      width: 100
    },
    {
      headerName: "Bar",
      field: "bar",
      width: 100
    },
  ];

  this.gridOptions.rowData = [];
}

  ngOnInit(){
    this.myService
       .getAll()
       .subscribe(item => this.gridOptions.rowData = item);
  }
}
</code>```

So I probably need to somehow let ag-grid know that the data has changed, I just don't know how to do it.

答:
Working plunker: https://embed.plnkr.co/HJd1xI/

Instead of passing the gridOptions to the template, I ended up with passing separated columnRefs and rowData as below.

full-width-renderer.component.html

```<code><ag-grid-angular #agGrid style="width: 100%; height: 350px;" class="ag-fresh"
             [gridOptions]="gridOptions"
             [columnDefs]="columnDefs"
             [rowData]="rowData">
</ag-grid-angular>
</code>```

And on the component, I assign the value to rowData directly.

full-width-renderer.component.ts

```<code>this.createRowData().subscribe((result) => {
    this.rowData = result;
});
</code>```

Reference

Title: Show data from the server in ag-grid

Body:
I use ag-grid in my Angular 4 project.

I bring the data from the server and then try to display it in a table, but the table remains empty (although the data exists).

Just to be sure where the problem is, I have an *ngFor which generates the same data and I can see it displayed on the screen.

I also manage to display the data in the ag-grid if I write it manually (hard-coded) and it's parsed when the page is loaded, without any ajax request.

html:

  <ag-grid-angular #agGrid style="width: 100%; height: 200px;" class="ag-fresh"
                   [gridOptions]="gridOptions">
  </ag-grid-angular>

      Foo

      Bar

      {{item.foo}}

      {{item.bar}}

ts:

export class HomeComponent implements OnInit {
private gridOptions: GridOptions;

constructor(
  private adsService: AdsService
) {
  this.gridOptions = {};

  this.gridOptions.columnDefs = [
    {
      headerName: "Foo",
      field: "foo",
      width: 100
    },
    {
      headerName: "Bar",
      field: "bar",
      width: 100
    },
  ];

  this.gridOptions.rowData = [];
}

  ngOnInit(){
    this.myService
       .getAll()
       .subscribe(item => this.gridOptions.rowData = item);
  }
}

So I probably need to somehow let ag-grid know that the data has changed, I just don't know how to do it.

Body:
Working plunker: https://embed.plnkr.co/HJd1xI/

Instead of passing the gridOptions to the template, I ended up with passing separated columnRefs and rowData as below.

full-width-renderer.component.html

<ag-grid-angular #agGrid style="width: 100%; height: 350px;" class="ag-fresh"
             [gridOptions]="gridOptions"
             [columnDefs]="columnDefs"
             [rowData]="rowData">
</ag-grid-angular>

And on the component, I assign the value to rowData directly.

full-width-renderer.component.ts

this.createRowData().subscribe((result) => {
    this.rowData = result;
});

Reference


问:
Finding and Tagging Duplicates in R
I was looking for an optimize way to do a task using R
Task: Find a way to assign 1 and 0 corresponds to a column entries, if entries are repeated then assign 1 for the first time occurrence of the value and rest time assign 0.

```<code>Example
ID      assigned value
2012            1
2012            0
2012            0
2014            1
2016            1
2015            1
</code>```

Here id is a vector contain id and assign vector will hold values accordingly.
My Solution:

```<code>   for(num in 1:(nrow(Final_file)-1))
   {
     if((Final_file[num,'ID']) == (Final_file[(num+1),'ID']))
     {
       assign_value[num] <- c('0')
            }
     else
     { assign_value[num] <- c('1')
     }
    }
</code>```

Here Final_file is sorted according to ID, my Solution is working but it take around 40 min to perform this logic on a file which contains 21K Rows. I want a code that will take less time to do the same task.

答:
See ?duplicated

```<code>#set up data (you should have done this part for us)
ID <- c(2012L, 2012L, 2012L, 2014L, 2016L, 2015L)

# one way of getting what you want:
1-duplicated(ID)
</code>```

I just did this on my cheap little laptop. It did a vector of 2.1 million IDs in well under a second (though the IDs were all in a vector in memory)

```<code>data.frame(ID=ID,assigned.value=1-duplicated(ID))
    ID assigned.value
1 2012              1
2 2012              0
3 2012              0
4 2014              1
5 2016              1
6 2015              1
</code>```

Title: Finding and Tagging Duplicates in R

Body:
I was looking for an optimize way to do a task using R
Task: Find a way to assign 1 and 0 corresponds to a column entries, if entries are repeated then assign 1 for the first time occurrence of the value and rest time assign 0.

Example
ID      assigned value
2012            1
2012            0
2012            0
2014            1
2016            1
2015            1

Here id is a vector contain id and assign vector will hold values accordingly.
My Solution:

   for(num in 1:(nrow(Final_file)-1))
   {
     if((Final_file[num,'ID']) == (Final_file[(num+1),'ID']))
     {
       assign_value[num] <- c('0')
            }
     else
     { assign_value[num] <- c('1')
     }
    }

Here Final_file is sorted according to ID, my Solution is working but it take around 40 min to perform this logic on a file which contains 21K Rows. I want a code that will take less time to do the same task.

Body:
See ?duplicated

#set up data (you should have done this part for us)
ID <- c(2012L, 2012L, 2012L, 2014L, 2016L, 2015L)

# one way of getting what you want:
1-duplicated(ID)

I just did this on my cheap little laptop. It did a vector of 2.1 million IDs in well under a second (though the IDs were all in a vector in memory)

data.frame(ID=ID,assigned.value=1-duplicated(ID))
    ID assigned.value
1 2012              1
2 2012              0
3 2012              0
4 2014              1
5 2016              1
6 2015              1


问:
Oracle SQL multiple tables
I'm still pretty fresh with SQL in general so this is probably not the best worded question. I want to get columns from different tables. They don't have any common column but there's 3rd table that has information that's able to link them together.

This is how I've tried to go about it:

```<code>SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17',
    CI_SP.SP_TYPE_CD WHERE SP_TYPE_CD='G-RES'
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID
</code>```

And this is the error that I receive in return:
    ORA-00923: FROM keyword not found where expected
    00923. 00000 -  "FROM keyword not found where expected"
    *Cause:

    *Action:
    Error at Line: 3 Column: 18

Anyone would be able to point me where I've got it wrong?

答:
In addition to what the others have said, re. the where clauses being in the wrong place, you also need to join your tables correctly. I think you're after something like:</p>

```<code>SELECT CI_SA.ACCT_ID,
       CI_SA.EXPIRE_DT WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17',
       CI_SP.SP_TYPE_CD WHERE SP_TYPE_CD='G-RES'
FROM   CI_SA
       INNER JOIN CI_SA_SP ON CI_SA.SA_ID = CI_SA_SP.SA_ID
       INNER JOIN CI_SP ON CI_SP.SP_ID = CI_SA_SP.SP_ID
WHERE  CI_SA.EXPIRE_DT BETWEEN TO_DATE('01/04/2017', 'DD/MM/YYYY') AND TO_DATE('30/04/2017', 'DD/MM/YYYY')
AND    CI_SP.SP_TYPE_CD = 'G-RES';
</code>```

Title: Oracle SQL multiple tables

Body:
I'm still pretty fresh with SQL in general so this is probably not the best worded question. I want to get columns from different tables. They don't have any common column but there's 3rd table that has information that's able to link them together.

This is how I've tried to go about it:

SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17',
    CI_SP.SP_TYPE_CD WHERE SP_TYPE_CD='G-RES'
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID

And this is the error that I receive in return:
    ORA-00923: FROM keyword not found where expected
    00923. 00000 -  "FROM keyword not found where expected"
    *Cause:

    *Action:
    Error at Line: 3 Column: 18

Anyone would be able to point me where I've got it wrong?

Body:
In addition to what the others have said, re. the where clauses being in the wrong place, you also need to join your tables correctly. I think you're after something like:

SELECT CI_SA.ACCT_ID,
       CI_SA.EXPIRE_DT WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17',
       CI_SP.SP_TYPE_CD WHERE SP_TYPE_CD='G-RES'
FROM   CI_SA
       INNER JOIN CI_SA_SP ON CI_SA.SA_ID = CI_SA_SP.SA_ID
       INNER JOIN CI_SP ON CI_SP.SP_ID = CI_SA_SP.SP_ID
WHERE  CI_SA.EXPIRE_DT BETWEEN TO_DATE('01/04/2017', 'DD/MM/YYYY') AND TO_DATE('30/04/2017', 'DD/MM/YYYY')
AND    CI_SP.SP_TYPE_CD = 'G-RES';


问:
Storing and Retrieving hashmap values from ArrayList?
i have to take union of sets (if there is n number then sets will be  > n*(n-1)/2)

What i have done :

I have taken list of maps and then put the values in map

Given: n=size of list, l=length of map

```<code>List<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>();
      for(int i=0;i<n;i++){
          Map<Integer,String> myMap1 = new HashMap<Integer, String>();
           int l=in.nextInt();
           for(int j=0;j<l;j++){
               int num=in.nextInt();
               myMap1.put(num, "Val0");
           }
           //System.out.println(myMap1);
           maps.add(i,myMap1);
           //System.out.println(maps.get(i));
      }
</code>```

What i Want:

Now i want to add every map with other so that i can find union

Please Help ! and dont Downvote it , it is not duplicate Q i have serched for answer and i didnt get, as i am getting opposite result as link description here

答:
Are you looking for something like this:

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MapUnion {

    /**
     * This method adds all entries in all maps and return it as single map. It
     * takes Collection of elements of type Map<K, V>
     *
     * @param maps - the Collection of maps, to sum all the entries
     * @return map containig "union" of all entries from all of the supplied maps
     */
    public <K, V> Map<K, V> unionAllMaps(Collection<Map<K, V>> maps) {
        return unionAllMaps(maps.toArray(new Map[maps.size()]));
    }

    /**
     * This method adds all entries in all maps and return it as single map. It
     * takes any numner of elements of type Map<K, V>. You can invoke it using
     * eg unionAllMaps(map1, map2, map3); the ... denotes, that all parameters
     * will be automatically converted to an array
     *
     * @param maps - the Array of maps, to sum all the entries
     * @return map containig "union" of all entries from all of the supplied maps
     */
    public <K, V> Map<K, V> unionAllMaps(Map<K, V>... maps) {
        HashMap<K, V> union = new HashMap<K, V>();
        for (Map<K, V> map : maps) {
            union.putAll(map);
        }
        return union;
    }

    public static void main(String[] args) {
        new MapUnion().test();
    }

    public void test() {
        HashMap<Integer, String> map1 = new HashMap<Integer, String>();
        map1.put(1, "1");
        map1.put(2, "2");
        HashMap<Integer, String> map2 = new HashMap<Integer, String>();
        map1.put(2, "2");
        map1.put(3, "3");

        ArrayList<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>();
        maps.add(map1);
        maps.add(map2);

        Map<Integer, String> union = unionAllMaps(maps);

        System.out.println(union);
    }
}
</code>```

will print:

{1=1, 2=2, 3=3}

But what should happen if there are same keys with different values in these maps? In this approach, the last value will overwrite previous one, but is this correct?

Body:
i have to take union of sets (if there is n number then sets will be  > n*(n-1)/2)

What i have done :

I have taken list of maps and then put the values in map

Given: n=size of list, l=length of map

List<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>();
      for(int i=0;i<n;i++){
          Map<Integer,String> myMap1 = new HashMap<Integer, String>();
           int l=in.nextInt();
           for(int j=0;j<l;j++){
               int num=in.nextInt();
               myMap1.put(num, "Val0");
           }
           //System.out.println(myMap1);
           maps.add(i,myMap1);
           //System.out.println(maps.get(i));
      }

What i Want:

Now i want to add every map with other so that i can find union

Please Help ! and dont Downvote it , it is not duplicate Q i have serched for answer and i didnt get, as i am getting opposite result as link description here

Body:
Are you looking for something like this:

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MapUnion {

    /**
     * This method adds all entries in all maps and return it as single map. It
     * takes Collection of elements of type Map<K, V>
     *
     * @param maps - the Collection of maps, to sum all the entries
     * @return map containig "union" of all entries from all of the supplied maps
     */
    public <K, V> Map<K, V> unionAllMaps(Collection<Map<K, V>> maps) {
        return unionAllMaps(maps.toArray(new Map[maps.size()]));
    }

    /**
     * This method adds all entries in all maps and return it as single map. It
     * takes any numner of elements of type Map<K, V>. You can invoke it using
     * eg unionAllMaps(map1, map2, map3); the ... denotes, that all parameters
     * will be automatically converted to an array
     *
     * @param maps - the Array of maps, to sum all the entries
     * @return map containig "union" of all entries from all of the supplied maps
     */
    public <K, V> Map<K, V> unionAllMaps(Map<K, V>... maps) {
        HashMap<K, V> union = new HashMap<K, V>();
        for (Map<K, V> map : maps) {
            union.putAll(map);
        }
        return union;
    }

    public static void main(String[] args) {
        new MapUnion().test();
    }

    public void test() {
        HashMap<Integer, String> map1 = new HashMap<Integer, String>();
        map1.put(1, "1");
        map1.put(2, "2");
        HashMap<Integer, String> map2 = new HashMap<Integer, String>();
        map1.put(2, "2");
        map1.put(3, "3");

        ArrayList<Map<Integer, String>> maps = new ArrayList<Map<Integer, String>>();
        maps.add(map1);
        maps.add(map2);

        Map<Integer, String> union = unionAllMaps(maps);

        System.out.println(union);
    }
}

will print:

{1=1, 2=2, 3=3}

But what should happen if there are same keys with different values in these maps? In this approach, the last value will overwrite previous one, but is this correct?


答:
The issue is that if you pass the value as an argument, you will get an array where each value refers to that same object. You do exactly that with:

```<code>Array.new(5, Array.new(6, 0))
</code>```

You can use Array#*, i.e array multiplication instead:

```<code>[[[0] * 6] * 5] * 4
</code>```

Title: How to initialise a three dimensional ruby array

Body:
I want to initialise a three dimensional ruby array. For a two-dimensional array, I can do

a = Array.new(4){ Array.new(5, 0) }

so I have tried

a = Array.new(4) { Array.new(5, Array.new(6, 0)) }

but if I do a[1][2][3] = 5, it not only sets that element to 5, it sets the corresponding element to 5 in other sub arrays i.e.

[[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]]

Body:
The issue is that if you pass the value as an argument, you will get an array where each value refers to that same object. You do exactly that with:

Array.new(5, Array.new(6, 0))

You can use Array#*, i.e array multiplication instead:

[[[0] * 6] * 5] * 4


问:
Trouble getting location on device with Ionic 2 application
I am having trouble using Ionic 2 Geolocation on real Android device. I have my location switched on on my Android device and I also tried reinstalling Ionic 2 and Cordova plugin for Geolocation, but I still cannot get location on my device. The code works fine when I test it on browser tho'. There is no error neither is the callback for success. I also tried testing it on different devices, but none worked properly. My code is the following:

```<code>loadMap(){
   this.error = "";
   let element: HTMLElement = document.getElementById('map');

   let mapOptions = {
     center: new google.maps.LatLng(38.50, -90.50),
     zoom: 15,
     mapTypeId: google.maps.MapTypeId.ROADMAP
   }

   this.map = new google.maps.Map(element, mapOptions);

   this.geolocation.getCurrentPosition(mapOptions).then((position) => {
     alert("Ready.");
   }, error => alert("Not ready."));
};
</code>```

I tried to do simple thing at first, so to load a map (which loads with no problems) and to get a location ready. this.geolocation is of type Geolocation. I also tried to get the location using navigator.geolocation.getCurrentPosition(...), but it also didn't do anything.
I hope someone can help.
Thank you in beforehand.

答: Seems it was an Android version compatibility issue in my case... I tried running it on device that had Android 6.0 Marshmallow installed and everything worked fine... Later I updated Android on my own device and tried running the application. Fortunately it ran nicely also on my device after the update. Hope this helps to solve someone else's issues too. Cheers</p>

Body:
I am having trouble using Ionic 2 Geolocation on real Android device. I have my location switched on on my Android device and I also tried reinstalling Ionic 2 and Cordova plugin for Geolocation, but I still cannot get location on my device. The code works fine when I test it on browser tho'. There is no error neither is the callback for success. I also tried testing it on different devices, but none worked properly. My code is the following:

loadMap(){
   this.error = "";
   let element: HTMLElement = document.getElementById('map');

   let mapOptions = {
     center: new google.maps.LatLng(38.50, -90.50),
     zoom: 15,
     mapTypeId: google.maps.MapTypeId.ROADMAP
   }

   this.map = new google.maps.Map(element, mapOptions);

   this.geolocation.getCurrentPosition(mapOptions).then((position) => {
     alert("Ready.");
   }, error => alert("Not ready."));
};

I tried to do simple thing at first, so to load a map (which loads with no problems) and to get a location ready. this.geolocation is of type Geolocation. I also tried to get the location using navigator.geolocation.getCurrentPosition(...), but it also didn't do anything.
I hope someone can help.
Thank you in beforehand.


答:
As far as I understand from your "multi level dropdown" concept, you can make a simple dropdown and just move some elements with CSS. Category name is stored in optgroup.

```<code><select name="select_projects" id="select_projects">
        <option value="">project.xml</option>
        <optgroup label="client1">
            <option value="">project2.xml</option>
        </optgroup>
        <optgroup label="client2">
            <option value="">project5.xml</option>
            <option value="">project6.xml</option>
            <optgroup label="client2_a">
                <option value="" style="margin-left:23px;">project7.xml</option>
                <option value="" style="margin-left:23px;">project8.xml</option>
            </optgroup>
            <option value="">project3.xml</option>
            <option value="">project4.xml</option>
       </optgroup>
       <option value="">project0.xml</option>
       <option value="">project1.xml</option>
    </select>
</code>```

Update:

Or if you are trying to make a "chain" of dropdowns like you have in start menu in Windows, that is the easiest way to do it:

https://jqueryui.com/menu/

Title: How to make multi level dropdown menu using select option mentod

Body:
i want to make multi level dropdown menu using select and option method

<select>
   <option value="" data-display-text="Select">None</option>
   <option value="oranges">SSC</option>
   <option value="oranges">GATE</option>
   <option value="bananas">BANK PO</option>
   <option value="bananas">RAILWAY</option>
 </select>

Body:
As far as I understand from your "multi level dropdown" concept, you can make a simple dropdown and just move some elements with CSS. Category name is stored in optgroup.

<select name="select_projects" id="select_projects">
        <option value="">project.xml</option>
        <optgroup label="client1">
            <option value="">project2.xml</option>
        </optgroup>
        <optgroup label="client2">
            <option value="">project5.xml</option>
            <option value="">project6.xml</option>
            <optgroup label="client2_a">
                <option value="" style="margin-left:23px;">project7.xml</option>
                <option value="" style="margin-left:23px;">project8.xml</option>
            </optgroup>
            <option value="">project3.xml</option>
            <option value="">project4.xml</option>
       </optgroup>
       <option value="">project0.xml</option>
       <option value="">project1.xml</option>
    </select>

Update:

Or if you are trying to make a "chain" of dropdowns like you have in start menu in Windows, that is the easiest way to do it:

https://jqueryui.com/menu/

ContentLicense: CC BY-SA 4.0


问:
Connecting Eclipse JSP Page with MySQL DataSource
I need to connect MySQL datasource to a jsp page through eclipse. I need to add, delete and read data from tables. I am using Eclipse Helios, Tomcat Apache 7 and Struts 2. I found some related page How should I connect to JDBC database / datasource in a servlet based application? but i dont know how to use public Database().What do i import. Also pls tell me some simple procedure to add and access data from tables.</p>

答:
You need to learn JDBC first - http://download.oracle.com/javase/tutorial/jdbc/index.html - and then you need to add the appropriate Java MySQL driver to your application so that the JDBC connection creation string can locate it.

Start with the tutorial.

Edit:  A very good JDBC-based database exploration program is the DBVisualizer - http://www.dbvis.com/ - where the free version can help you getting started as well as help you investigate database contents and an easy SQL editor for getting the selects right.


问:
How can I remove "/url?q=" from text data in R
I want to remove "/url?q=" from text data in R Studio.
This is my code for google search:

```<code>## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  links
</code>```

And my result is:

[1] "/url?q=https://www.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQFggUMAA&usg=AFQjCNEqtiOAIA7OOTa3meWC8zaTjjTy8A"

  [2] "/url?q=http://www.cran.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQjBAIGzAB&usg=AFQjCNF8QmYbLzG0c66QZM2wsXF1n1-9tQ"

What can I do to remove "/url?q=" from the links above?

答:
I solved it this way as they were limited number of characters</p>

```<code>links <- substring(links,8)
</code>```

Body:
I want to remove "/url?q=" from text data in R Studio.
This is my code for google search:

## Code for Google Search
# Enter Search Term Here
 search.term <- "r-project"
# Creating Function
 getGoogleURL <- function(search.term, domain = '.co.in', quotes=TRUE)
{
   # Getting Search Term
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='')
   # Putting Search Term in Google Search
    getGoogleURL <- paste('http://www.google', domain, '/search?q=', search.term, sep='') }

## Get Links from Google Search
# Creating Function to Get URLs From Search Results
 getGoogleLinks <- function(google.url) {
  # Creating a File to Save URLs
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R(3.4.0)"))
  # Removing HTML code and Setting Nodes
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]])) }

## Remove quoted text, Create URL List
  quotes <- "FALSE"
  search.url <- getGoogleURL(search.term=search.term, quotes=quotes)
  links <- getGoogleLinks(search.url)

## Print URL List
  links

And my result is:

[1] "/url?q=https://www.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQFggUMAA&usg=AFQjCNEqtiOAIA7OOTa3meWC8zaTjjTy8A"

  [2] "/url?q=http://www.cran.r-project.org/&sa=U&ved=0ahUKEwj78ZWXoabUAhUcTI8KHaTEDTIQjBAIGzAB&usg=AFQjCNF8QmYbLzG0c66QZM2wsXF1n1-9tQ"

What can I do to remove "/url?q=" from the links above?

Body:
I solved it this way as they were limited number of characters

links <- substring(links,8)


问:
How to solve below Scenario, using SQL server?
I am having lot of data like this,here I've given sample data only,So Case when clause not suitable for this,

```<code>  DECLARE @T TABLE (EID INT, VALUE VARCHAR(50),CATEGORY VARCHAR(50),CATEGORY1 VARCHAR(50))

INSERT INTO @T
SELECT 1,'JHON','NAME',NULL
UNION
SELECT 2,'MARY','NAME',NULL
UNION
SELECT 1,'IT','DEPT',NULL
UNION
SELECT 1,'85204-00065',NULL,'PHONE'
UNION
SELECT 1,'MALE',NULL,'GENDER'
UNION
SELECT 2,'85285-00525',NULL,'PHONE'
UNION
SELECT 2,'FEMALE',NULL,'GENDER'
UNION
SELECT 2,'BPO','DEPT',NULL

SELECT * FROM @T
</code>```

Expected Output:

```<code>EId  Name   Dept    Gender  Phone
1    Jhon   IT      Male    85204-00065
2    Mary   Bpo     Female  85285-00525
</code>```

Any one Provide better solution for this scenario.

答:
You can do pivot, coalesce and dynamic query as below:</p>

```<code>declare @cols1 varchar(max)
declare @cols2 varchar(max)
declare @query nvarchar(max)

Select @cols1 = stuff((select Distinct ','+QuoteName(Coalesce(Category,Category1)) from YourEmpData for xml path('')),1,1,'')
Select @Cols2 = 'Coalesce(' +stuff((Select ','+ QUOTENAME(Column_Name) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YourEmpData' and COLUMN_NAME not in ('EID', 'VALUE') for xml path('')),1,1,'') + ')'

Select @query = '   Select * from (
        Select EID, [Value], ' + @cols2 + ' as Categories FROM YourEmpData ) a
        pivot (max([Value]) for [Categories] in (' + @cols1 + ')) p '

select @query --uncomment and execute if your query generated correct
--exec sp_executesql @query
</code>```

Body:
I am having lot of data like this,here I've given sample data only,So Case when clause not suitable for this,

  DECLARE @T TABLE (EID INT, VALUE VARCHAR(50),CATEGORY VARCHAR(50),CATEGORY1 VARCHAR(50))

INSERT INTO @T
SELECT 1,'JHON','NAME',NULL
UNION
SELECT 2,'MARY','NAME',NULL
UNION
SELECT 1,'IT','DEPT',NULL
UNION
SELECT 1,'85204-00065',NULL,'PHONE'
UNION
SELECT 1,'MALE',NULL,'GENDER'
UNION
SELECT 2,'85285-00525',NULL,'PHONE'
UNION
SELECT 2,'FEMALE',NULL,'GENDER'
UNION
SELECT 2,'BPO','DEPT',NULL

SELECT * FROM @T

Expected Output:

EId  Name   Dept    Gender  Phone
1    Jhon   IT      Male    85204-00065
2    Mary   Bpo     Female  85285-00525

Any one Provide better solution for this scenario.

Body:
You can do pivot, coalesce and dynamic query as below:

declare @cols1 varchar(max)
declare @cols2 varchar(max)
declare @query nvarchar(max)

Select @cols1 = stuff((select Distinct ','+QuoteName(Coalesce(Category,Category1)) from YourEmpData for xml path('')),1,1,'')
Select @Cols2 = 'Coalesce(' +stuff((Select ','+ QUOTENAME(Column_Name) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YourEmpData' and COLUMN_NAME not in ('EID', 'VALUE') for xml path('')),1,1,'') + ')'

Select @query = '   Select * from (
        Select EID, [Value], ' + @cols2 + ' as Categories FROM YourEmpData ) a
        pivot (max([Value]) for [Categories] in (' + @cols1 + ')) p '

select @query --uncomment and execute if your query generated correct
--exec sp_executesql @query


问:
How to make PDF file downloadable in HTML link?
I am giving link of a pdf file on my web page for download, like below

```<code><a href="myfile.pdf">Download Brochure</a>
</code>```

The problem is when user clicks on this link then

If the user have installed Adobe Acrobat, then it opens the file in the same browser window in Adobe Reader.

If the Adobe Acrobat is not installed then it pop-up to the user for Downloading the file.

But I want it always pop-up to the user for download, irrespective of "Adobe acrobat" is installed or not.

Please tell me how i can do this?

答:
I solved mine using the whole url of the PDF file (Instead of just putting the file name or location to href):
    a href="domain . com/pdf/filename.pdf" </p>

OwnerDisplayName: Prashant

Body:
I am giving link of a pdf file on my web page for download, like below

Download Brochure

The problem is when user clicks on this link then

If the user have installed Adobe Acrobat, then it opens the file in the same browser window in Adobe Reader.

If the Adobe Acrobat is not installed then it pop-up to the user for Downloading the file.

But I want it always pop-up to the user for download, irrespective of "Adobe acrobat" is installed or not.

Please tell me how i can do this?


问:
copy mysql db from previous xampp to new one
I reinstalled my computer, before I did that, I copy my Xampp folder for backup.

the problem is i forget to backup my database from Phpmyadmin.

I tried to copy /xampp/mysql/data/ to new one but i got error

```<code>#1932 - Table 'phpmyadmin.pma__tracking' doesn't exist in engine
</code>```

anyone how to fix this?

*browser is ok to access those data, but i have trouble to open it inside of phpmyadmin

答: If you are using windows, run a linux live cd and copy the xampp folder into your external drive then go to the target computer, run again live cd on the target computer or just boot it in safe mode(for windows) then copy the xampp folder into your target computers drive.</p>

Body:
I reinstalled my computer, before I did that, I copy my Xampp folder for backup.

the problem is i forget to backup my database from Phpmyadmin.

I tried to copy /xampp/mysql/data/ to new one but i got error

#1932 - Table 'phpmyadmin.pma__tracking' doesn't exist in engine

anyone how to fix this?

*browser is ok to access those data, but i have trouble to open it inside of phpmyadmin


问:
How to Access model from Form template in Django
I have a form that edits a model.  In the template though I would like to access the model.  Is this possible and how can I accomplish this?</p>

答: {{ model_form._meta.model }}</p>

Body: {{ model_form._meta.model }}


问:
Why does assert np.nan == np.nan cause an error?
If

```<code>assert 1 == 1
</code>```

is fine, then why does:

```<code>assert np.nan == np.nan
</code>```

cause an assertion error?

What's even more confusing, this is OK:

```<code>assert np.nan != np.nan
</code>```

What's the best way to test for nan?

答:
NaN has the property that it doesn't equal itself, you should use np.isnan to test NaN values, here np.isnan(np.nan) will yield True:

```<code>In[5]:
np.nan == np.nan

Out[5]: False

In[6]:
np.nan != np.nan

Out[6]: True

In[7]:
np.isnan(np.nan)

Out[7]: True
</code>```

Body:
If

assert 1 == 1

is fine, then why does:

assert np.nan == np.nan

cause an assertion error?

What's even more confusing, this is OK:

assert np.nan != np.nan

What's the best way to test for nan?

Body:
NaN has the property that it doesn't equal itself, you should use np.isnan to test NaN values, here np.isnan(np.nan) will yield True:

In[5]:
np.nan == np.nan

Out[5]: False

In[6]:
np.nan != np.nan

Out[6]: True

In[7]:
np.isnan(np.nan)

Out[7]: True


问:
how to check if array of file input fields have files uploaded?
I have an array of files and I want to be able to submit the form even if the file input fields are empty, but if they are not empty then check if its bigger than 5Mb. I could check if the file is bigger than 5Mb and if it is then it prevents form submit. but if the input file fields are empty the form will not allow me to submit. please help</p>

```<code>  if (window.File && window.FileReader && window.FileList && window.Blob){
        //get the file size and file type from file input field
        var fsize = $('.upload_files')[0].files[0].size;

        if(fsize>5242880) //do something if file size more than 1 mb (1048576)
        {
            error_alert("file size is too big! please choose a smaller file");return false;
        }

        }
</code>```

答:
Here is the function which can be helpful to satisfy your needs. This function can work with n number of file objects and you can set it as a callback or can be called on any event as well. Please go through it.

```<code>function checkFileSize() {
    $total_file_size = $file_size = 0 ;
    $file_selected = false ;
    $('input:file').each(function() {
        $file_size = 0 ;
        $obj = this.files[0] ;

        if (typeof($obj) == 'undefined'){
            $file_size = 0 ;
        }
        else {
            $file_selected = true ;
            $file_size = $obj.size ;
        }
        $total_file_size += $file_size ;
    }) ;

    if($file_selected) {
        if($total_file_size <= 5242880) {
            return true ;
        }
        alert('File size is greater than 5MB') ;
        return false ;
    }
    else {
        return false ;
    }
}
</code>```

You can tweak it as per your requirement. I wish it will work for you.
Thanks, Have a great time ahead.

Body:
I have an array of files and I want to be able to submit the form even if the file input fields are empty, but if they are not empty then check if its bigger than 5Mb. I could check if the file is bigger than 5Mb and if it is then it prevents form submit. but if the input file fields are empty the form will not allow me to submit. please help

  if (window.File && window.FileReader && window.FileList && window.Blob){
        //get the file size and file type from file input field
        var fsize = $('.upload_files')[0].files[0].size;

        if(fsize>5242880) //do something if file size more than 1 mb (1048576)
        {
            error_alert("file size is too big! please choose a smaller file");return false;
        }

        }

Body:
Here is the function which can be helpful to satisfy your needs. This function can work with n number of file objects and you can set it as a callback or can be called on any event as well. Please go through it.

function checkFileSize() {
    $total_file_size = $file_size = 0 ;
    $file_selected = false ;
    $('input:file').each(function() {
        $file_size = 0 ;
        $obj = this.files[0] ;

        if (typeof($obj) == 'undefined'){
            $file_size = 0 ;
        }
        else {
            $file_selected = true ;
            $file_size = $obj.size ;
        }
        $total_file_size += $file_size ;
    }) ;

    if($file_selected) {
        if($total_file_size <= 5242880) {
            return true ;
        }
        alert('File size is greater than 5MB') ;
        return false ;
    }
    else {
        return false ;
    }
}

You can tweak it as per your requirement. I wish it will work for you.
Thanks, Have a great time ahead.


问:
Error displayed after Default.srprofile is modified
I have modified .srprofile to configure my own report template.

But when executed thrown with below error message and html file is not generated -

System.InvalidOperationException: render template resource not found
   at TechTalk.SpecRun.Framework.Reporting.ReportTemplateLoader.LoadTemplate(Report report)....

Changes done to .srprofile:

```<code>  <Report copyAlsoToBaseFolder="true">
<Template name="ReportTemplate.cshtml" outputName="AutomationReport.html" />
 </Report>"
</code>```

Did i do anything wrong here?

答:
SpecFlow+Runner is searching for the ReportTemplate.cshtml in the output directory (normally bin\debug). If you add the file to the project, in default it is not copied to the output directory.

Change "copy to output" in the properties of the file to "always"

Body:
I have modified .srprofile to configure my own report template.

But when executed thrown with below error message and html file is not generated -

System.InvalidOperationException: render template resource not found
   at TechTalk.SpecRun.Framework.Reporting.ReportTemplateLoader.LoadTemplate(Report report)....

Changes done to .srprofile:

  <Report copyAlsoToBaseFolder="true">
<Template name="ReportTemplate.cshtml" outputName="AutomationReport.html" />
 </Report>"

Did i do anything wrong here?


问:
How to get content of ScrolledText?
I'm trying to get content of a ScrolledText but so far success is not with me :)
I don't understand where i'm wrong.
Here a very simple example of not working code...</p>

```<code>from Tkinter import Tk
from ScrolledText import ScrolledText

def returnPressed(value):
    print "CONTENT: " + value

root = Tk()
st = ScrolledText(root)
st.bind("<Return>", lambda event, i=st.get("1.0", "end-1c"): returnPressed(i))
st.insert("insert", "TEST")
st.pack()
root.mainloop()
</code>```

答:
You are getting the value at the time you create the button, which means the value will always be empty.  You need to get the value at the time that the event is processed.

You should avoid using lambda, it is a somewhat advanced concept that in this case adds complexity without adding any value. Simply get the value from within the function:

```<code>def returnPressed(event):
    value = event.widget.get("1.0", "end-1c")
    print "CONTENT: " + value
...
st.bind("<Return>", returnPressed)
</code>```

Title: How to get content of ScrolledText?

Body:
I'm trying to get content of a ScrolledText but so far success is not with me :)
I don't understand where i'm wrong.
Here a very simple example of not working code...

from Tkinter import Tk
from ScrolledText import ScrolledText

def returnPressed(value):
    print "CONTENT: " + value

root = Tk()
st = ScrolledText(root)
st.bind("<Return>", lambda event, i=st.get("1.0", "end-1c"): returnPressed(i))
st.insert("insert", "TEST")
st.pack()
root.mainloop()

Body:
You are getting the value at the time you create the button, which means the value will always be empty.  You need to get the value at the time that the event is processed.

You should avoid using lambda, it is a somewhat advanced concept that in this case adds complexity without adding any value. Simply get the value from within the function:

def returnPressed(event):
    value = event.widget.get("1.0", "end-1c")
    print "CONTENT: " + value
...
st.bind("<Return>", returnPressed)


问:
How to PROVE the precedence of '&&' and '||' by coding in Java?
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

```<code>boolExp1 || boolExp2 && boolExp3 || boolExp4
</code>```

The code above produces the same results no matter the precedence of && and ||, that is,

```<code>false || false && true || false
</code>```

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

答:
I was looking at the java specification to see if they defined operator precedence for && and ||

Both are defined as left-associative and no operator precedence is defined.

See s. 15.7.3 a bit down from s. 17.7,
&& s. 15.23,
|| s. 15.24

i.e. Java defines:

```<code>boolExp1 || boolExp2 && boolExp3 || boolExp4
</code>```

As:

```<code>((((boolExp1) || boolExp2) && boolExp3) || boolExp4)
</code>```

Body:
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

boolExp1 || boolExp2 && boolExp3 || boolExp4

The code above produces the same results no matter the precedence of && and ||, that is,

false || false && true || false

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

Body:
I was looking at the java specification to see if they defined operator precedence for && and ||

Both are defined as left-associative and no operator precedence is defined.

See s. 15.7.3 a bit down from s. 17.7,
&& s. 15.23,
|| s. 15.24

i.e. Java defines:

boolExp1 || boolExp2 && boolExp3 || boolExp4

As:

((((boolExp1) || boolExp2) && boolExp3) || boolExp4)


问:
Applying MVC With JavaFx
I'm new to the GUI world/OO design pattern and I want to use MVC pattern for my GUI application, I have read a little tutorial about MVC pattern, the Model will contain the data, the View will contain the visual element and the Controller will tie between the View and the Model.

I have a View that contains a ListView node, and the ListView will be filled with names, from a Person Class (Model). But I'm a little confused about one thing.

What I want to know is if loading the data from a file is the responsibility of the Controller or the Model?? And the ObservableList of the names: should it be stored in the Controller or the Model?

答:
What i want to know is that if loading the data from a file is the responsibility of the Controller Or the model?

For me the model is only responsible of bringing the required data structures that represent the business logic of the application.

The action of loading that data from any source should be done by the Controller Layer. You could also use the repository pattern, which can help you in abstracting from the type of source when you are acessing the data from the view. With this implemented you should not care if the Repository implementation is loading the data from file, SQL, NoSQL, Web service ...

And the ObservableList of the names will be stored in the controller or the model?

For me the ObservableList is part of the View. It is the kind of data structure you can bind to JavaFX controls. So for example a ObservableList<String> could be populated with Strings from the model but the ObservableList reference should be an attribute of some View´s class.
In JavaFX it's very pleasant to bind JavaFX controls with Observable Properties backed by domain objects from the model.

You could also have a look to viewmodel concept. For me a JavaFX bean backed by a POJO could be considered as a view-model, you could see it as a model object ready to be presented in the view. So for example if your view needs to show some total value calculated from 2 model attributes, this total value could be an attribute of the view-model. This attribute would not be persisted and it would be calculated any time you show the view.

Title: Applying MVC With JavaFx


问:
Text to Morse Code
I recently found out that you can play sounds in python. I instantly wanted to make a text to morse code program but when I try to assign winsound.Beep(600,300) to "a" and launch, it just beeps once and when i type a it does nothing.

```<code>import winsound
def dot():
    winsound.Beep(600,100)
def line():
    winsound.Beep(600,100)
a = dot(), line()    #it doesn't work when i just do
                     #a = winsound.Beep(600,100) either
                     #and it beeps at the beginning which i don't want
</code>```

can you tell me how i can assign winsound.Beep() to a varible?

答:
Adding a layer of indirection is often helpful. Define the character values separately from the playing, then you can loop over any text:

```<code>import winsound
import time

# define the values for the alphabet (using easy to verify strings)
alphabet = dict(
    a='.-',
    b='-...',
    c='-.-.',
    d='-..',
    e='.',
    h='....',
    l='.-..',
    o='---',
    w='.--',
    r='.-.',
    # etc.
)
</code>```

How to play (single) dots and dashes (the lines are referred to as dashes):

```<code>def play_dot():
    winsound.Beep(600, 100)

def play_dash():
    winsound.Beep(500, 200)  # a bit lower frequency, double length
</code>```

Play one character by looking up the morse value for the character in the alphabet and then iterate over the dots/dashes:

```<code>def play_char(ch):
    if ch == ' ':             # space is a special case
        time.sleep(0.9)       # wait for 0.9 seconds before returning
        return '<space>'

    morseval = alphabet[ch]   # morseval is now a series of dots/dashes
    for d in morseval:        # loop over them
        if d == '.':          # if it's a dot, play a dot
            play_dot()
        else:
            play_dash()
        time.sleep(0.1)       # a small break (0.1 secs) makes it easier on the ears

    return morseval           # return the morse value so we can see what was played..
</code>```

to play a text, assuming it's ascii, just iterate through the characters and play each of them in turn:

```<code>def txt2morse(txt):
    for ch in txt.lower():    # convert the text to lower case, just in case..
        print play_char(ch),  # Python 2.7'ism to keep printing on the same line
    print
</code>```

then:

```<code>>>> txt2morse('hello world')
.... . .-.. .-.. --- <space> .-- --- .-. .-.. -..
</code>```

Title: Text to Morse Code

Body:
I recently found out that you can play sounds in python. I instantly wanted to make a text to morse code program but when I try to assign winsound.Beep(600,300) to "a" and launch, it just beeps once and when i type a it does nothing.

import winsound
def dot():
    winsound.Beep(600,100)
def line():
    winsound.Beep(600,100)
a = dot(), line()    #it doesn't work when i just do
                     #a = winsound.Beep(600,100) either
                     #and it beeps at the beginning which i don't want

can you tell me how i can assign winsound.Beep() to a varible?

Body:
Adding a layer of indirection is often helpful. Define the character values separately from the playing, then you can loop over any text:

import winsound
import time

# define the values for the alphabet (using easy to verify strings)
alphabet = dict(
    a='.-',
    b='-...',
    c='-.-.',
    d='-..',
    e='.',
    h='....',
    l='.-..',
    o='---',
    w='.--',
    r='.-.',
    # etc.
)

How to play (single) dots and dashes (the lines are referred to as dashes):

def play_dot():
    winsound.Beep(600, 100)

def play_dash():
    winsound.Beep(500, 200)  # a bit lower frequency, double length

Play one character by looking up the morse value for the character in the alphabet and then iterate over the dots/dashes:

def play_char(ch):
    if ch == ' ':             # space is a special case
        time.sleep(0.9)       # wait for 0.9 seconds before returning
        return '<space>'

    morseval = alphabet[ch]   # morseval is now a series of dots/dashes
    for d in morseval:        # loop over them
        if d == '.':          # if it's a dot, play a dot
            play_dot()
        else:
            play_dash()
        time.sleep(0.1)       # a small break (0.1 secs) makes it easier on the ears

    return morseval           # return the morse value so we can see what was played..

to play a text, assuming it's ascii, just iterate through the characters and play each of them in turn:

def txt2morse(txt):
    for ch in txt.lower():    # convert the text to lower case, just in case..
        print play_char(ch),  # Python 2.7'ism to keep printing on the same line
    print

then:

>>> txt2morse('hello world')
.... . .-.. .-.. --- <space> .-- --- .-. .-.. -..


问:
UICollectionView insetForSectionAtIndex not being called
I have a class with the following declaration and constructor:

```<code>class GameView: UIView, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
    var collectionView: UICollectionView?
    var flowLayout =  UICollectionViewFlowLayout()

    init (frame : CGRect, navigationController:UINavigationController, parentViewController: ScrambleViewController)
{
    super.init(frame : frame)
    cvFrame = CGRect(x: cvLeftBorder, y: cvY, width: Int(UIScreen.main.bounds.width) -  (2 * cvLeftBorder), height: cvHeight)
    collectionView = UICollectionView(frame: cvFrame!, collectionViewLayout: flowLayout);
    collectionView!.dataSource = self
    collectionView!.delegate = self;
    .....
}
</code>```

This is a game where there is a different number of cells each round.   I want to center the cells, so I inserted:

```<code>func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

 // calculate the insets and return a UIEdgeInsets
}
</code>```

For some reason, the function is never called.   Otherwise, the program is working fine.   Or is there a better way to center the cells in each round?

Thanks in advance.

答:
sobremesa answer is correct, so to implement this method you have to use something like this:</p>

```<code>public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return yourInsets
}
</code>```

Body:
I have a class with the following declaration and constructor:

class GameView: UIView, UICollectionViewDelegate,  UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
    var collectionView: UICollectionView?
    var flowLayout =  UICollectionViewFlowLayout()

    init (frame : CGRect, navigationController:UINavigationController, parentViewController: ScrambleViewController)
{
    super.init(frame : frame)
    cvFrame = CGRect(x: cvLeftBorder, y: cvY, width: Int(UIScreen.main.bounds.width) -  (2 * cvLeftBorder), height: cvHeight)
    collectionView = UICollectionView(frame: cvFrame!, collectionViewLayout: flowLayout);
    collectionView!.dataSource = self
    collectionView!.delegate = self;
    .....
}

This is a game where there is a different number of cells each round.   I want to center the cells, so I inserted:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

 // calculate the insets and return a UIEdgeInsets
}

For some reason, the function is never called.   Otherwise, the program is working fine.   Or is there a better way to center the cells in each round?

Thanks in advance.

Body:
sobremesa answer is correct, so to implement this method you have to use something like this:

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return yourInsets
}


问:
Protractor Unable to click on the button even though it finds it
I have been struggling to click on a button using Protractor.The problem is that even that the driver finds the element but it still doesn't click it.Any Help is appreciated.Thanks in advance.

Below is the HTML for the Sign in Button:

div class="row mod-form-button">
                <button id="sign_in" class="mod-main" tabindex="4">Sign in</button>

                    Not a member yet?

                        Get an Test ID

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

<p>Protractor Code:
This is the specs file:
// spec.js</p>

```    describe(' Demo', function() {

  it('Should Login to Demo Site', function() {
    browser.waitForAngularEnabled(false);
    browser.get('https://stage.com');

   // var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
//browser.wait(EC.elementToBeClickable($('password')), 5000);
    element(by.id('password')).sendKeys('123456');
    element(by.id('username')).sendKeys('Tester@test.com');
    //browser.sleep(35000);

     var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
 element(by.id('sign_in')).click();
 browser.sleep(5000);
 var el = element(by.id('sign_in'));
browser.executeScript('arguments[0].scrollIntoView()', el.getWebElement());

el.click();
// browser.wait(EC.elementToBeClickable($('sign_in')), 5000);
//browser.wait(EC.elementToBeClickable($('.btn.coral-btn.coral-btn-primary')), 5000);
//element(by.css('.btn.coral-btn.coral-btn-primary')).click();
  //  expect(element(by.binding('latest')).getText()).
      //  toEqual('5'); // This is wrong!
  });
});
```

<p>This is the config file:
//Config.js</p>

```exports.config = {

  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
   allScriptsTimeout: 5000000,
  specs: ['specs.js']

}
```

答:
i had exp only with Selenium-java, and test front-end with it.
The steps i used to test thinks like yours.

Use click button, after check that exist. (sometimes click evt() works early than check).So when it try to click on button, button doesn't exist yet.

In your case i will do this steps:

Use ExpectedCondition to check that page has been already loaded.
ExpectedConditions.until(visibilityOf(WebElement)). push element
like input (log or pass).

SendKeys for inputs. Than you can check input.value

Button click check, that is exist and clickable.

by.id(btnID).click().

I hope it will helps.

Body:
I have been struggling to click on a button using Protractor.The problem is that even that the driver finds the element but it still doesn't click it.Any Help is appreciated.Thanks in advance.

Below is the HTML for the Sign in Button:

div class="row mod-form-button">
                <button id="sign_in" class="mod-main" tabindex="4">Sign in</button>

                    Not a member yet?

                        Get an Test ID

Protractor Code:
This is the specs file:
// spec.js

    describe(' Demo', function() {

  it('Should Login to Demo Site', function() {
    browser.waitForAngularEnabled(false);
    browser.get('https://stage.com');

   // var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
//browser.wait(EC.elementToBeClickable($('password')), 5000);
    element(by.id('password')).sendKeys('123456');
    element(by.id('username')).sendKeys('Tester@test.com');
    //browser.sleep(35000);

     var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be clickable.
 element(by.id('sign_in')).click();
 browser.sleep(5000);
 var el = element(by.id('sign_in'));
browser.executeScript('arguments[0].scrollIntoView()', el.getWebElement());

el.click();
// browser.wait(EC.elementToBeClickable($('sign_in')), 5000);
//browser.wait(EC.elementToBeClickable($('.btn.coral-btn.coral-btn-primary')), 5000);
//element(by.css('.btn.coral-btn.coral-btn-primary')).click();
  //  expect(element(by.binding('latest')).getText()).
      //  toEqual('5'); // This is wrong!
  });
});

This is the config file:
//Config.js

exports.config = {

  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
   allScriptsTimeout: 5000000,
  specs: ['specs.js']

}


问:
unexpected token : using map to form array of object
I want to produce this

```<code>[
        {name: "james", age: 10},
        {name: "john", age: 12},
        {name: "johnny", age: 56}
    ]
</code>```

My below code failed, got expected token?

```<code>let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => {name:obj.name, age:obj.age})

console.log(y)
</code>```

答:
Just as a reference, this would also work, and be the same:

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
];

let y = x.map(obj => {
  return { name:obj.name, age:obj.age };
});

console.log(y);```

Body:
I want to produce this

[
        {name: "james", age: 10},
        {name: "john", age: 12},
        {name: "johnny", age: 56}
    ]

My below code failed, got expected token?

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => {name:obj.name, age:obj.age})

console.log(y)


问:
Android dotted underline is staying in middle of textview
I want to show a dotted underline below the textview, following are my codes

```<code><TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />
</code>```

dashed_line.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>
</code>```

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

```<code>android:drawableBottom="@drawable/dashed_line"
</code>```

答:
You can also use like this(Under Line)</p>

```<code>    TextView contacttv = (TextView) findViewById(R.id.contactTextView);

    contacttv.setPaintFlags(contacttv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
</code>```

Body:
I want to show a dotted underline below the textview, following are my codes

<TextView
  android:id="@+id/contact_num"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="4dp"
  android:text="1234567890"
  android:background="@drawable/dashed_line"
  android:layerType="software"
  android:textSize="20dp" />

dashed_line.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">

    <stroke
        android:color="@color/oceanBlue"
        android:dashWidth="2dp"
        android:dashGap="3dp"
        android:width="1dp"/>
</shape>

and the textview looks as above

can anyone help me to get the dotted line below to the textview?

tried with drawableBottom also but no use

android:drawableBottom="@drawable/dashed_line"

Body:
You can also use like this(Under Line)

    TextView contacttv = (TextView) findViewById(R.id.contactTextView);

    contacttv.setPaintFlags(contacttv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);


问:
Regular expression for decimals
Hi Experts,
                   I have a requirement where I think regular expressions might help reducing a lot of if statements and conditions in my code.
My requirement is something like this
I have a quantity field that is displayed in the UI( JavaScript) which has a control factor (based on the quantity field's Unit of Measurement) send from the backend .

Example my Quantity = "126.768"
The control factor D = "2" (which means the number of display positions after the decimal point is 2) .

Now I need a regex to find the following

Regex1 should check whether the quantity is having any decimal points at all. If so then it should check whether the value after decimal points are not just zeros (ex sometimes quantity comes without getting formatted with the full length of decimal points 145.000, which in our case should be displayed as 145 in the UI and the control factor D doesn't need to be considered). Also RegEx should consider quantity values like ".590" ".001" etc.

Since I am new to RegEx I am struggling to come up with an expression

I managed to make a very basic RegEx that just check for the "." within the quantity and all the values after the "."
RegEx = /[.]\d*/g

If RegEx1 returns a positive result . Then Regex2 should now check for the value  D. It should adjust the decimal points based on D. For example if D = 3 and quantity = 345.26 then the output of regex2 should give 345.260 and similarly is D = 1 then quantity should be 345.3 ( donno whether rounding is possible using RegEx, a solution without rounding is also fine).

Regards,
Bince

答:
The first regex is

```<code>"\d*\.\d*[1-9]\d*"
</code>```

It searches for at least 1 non-zero digit after the dot.

For the second point, you can round with regex only if the digits overcomes the control factor, while for the 0-padding you can't use regex:

function round(num, control) {
  var intPart = num.split(".")[0];
  var decPart = num.split(".")[1];
  decPart = decPart.substring(0, control);  //this does the truncation
  var padding = "0".repeat(control - decPart.length); //this does the 0-padding
  return intPart + "." + decPart + padding;
}

var num1 = "210.012";
var num2 = "210.1";
var control = 2;
console.log(round(num1, control));
console.log(round(num2, control));```

Title: Regular expression for decimals

Body:
The first regex is

"\d*\.\d*[1-9]\d*"

It searches for at least 1 non-zero digit after the dot.

For the second point, you can round with regex only if the digits overcomes the control factor, while for the 0-padding you can't use regex:

function round(num, control) {
  var intPart = num.split(".")[0];
  var decPart = num.split(".")[1];
  decPart = decPart.substring(0, control);  //this does the truncation
  var padding = "0".repeat(control - decPart.length); //this does the 0-padding
  return intPart + "." + decPart + padding;
}

var num1 = "210.012";
var num2 = "210.1";
var control = 2;
console.log(round(num1, control));
console.log(round(num2, control));


问:
rails validation messages
My Rails app began returning funky validation error messages of this form upon create/save of a model.

{{count}} errors prohibited this {{model}} from being saved
There were problems with the following fields:
{{attribute}} {{message}}
{{attribute}} {{message}}
{{attribute}} {{message}}
{{attribute}} {{message}}

Has anyone else experienced anything like this?

Thanks

答:
You probably upgraded Ruby to a version that does not work well with your version of Rails. I think that if you use Ruby 1.9 you have to at least use Rails 2.3.9 if I'm not mistaken.

Here is a changelog for Rails 2.3.9: ruby-on-rails-2-3-9-released

Title: rails validation messages


答: Use np.isnan(value). NaN doesn't compare equal to itself because it indicates a failure, and might not have been produced the same way. I'm not sure why isnan is missing in the CPython documentation, but it's present in math for both CPython 3.4 and 2.7, and as a ufunc in numpy.

Title: Why does assert np.nan == np.nan cause an error?

Body:
If

assert 1 == 1

is fine, then why does:

assert np.nan == np.nan

cause an assertion error?

What's even more confusing, this is OK:

assert np.nan != np.nan

What's the best way to test for nan?


答:
In python everything is an object. If you run this:

```<code>a = dot()
</code>```

Execute dot() and assign the returned value to a - in your case it's None.

However, if you want to "assign" the function dot() to a and then call a you do this:

```<code>a = dot
a()
</code>```

In this case the names a and dot refer to the same object. a is now a function which you call with parentheses only.

Title: Text to Morse Code

Body:
In python everything is an object. If you run this:

a = dot()

Execute dot() and assign the returned value to a - in your case it's None.

However, if you want to "assign" the function dot() to a and then call a you do this:

a = dot
a()

In this case the names a and dot refer to the same object. a is now a function which you call with parentheses only.


问:
Swift Filter and Map over array of structs
I may have this really wrong. Noob. I've recreated what I'm doing in a playground type environment here. Basically the sender is a slider within a UITableView of other sliders. The myData is the underlying data. I want to perform a calculation to all the items of the underlying data EXCEPT the one which corresponds to the sender item. I have no idea if my closure syntax is correct. This is the first time I'm creating one.

```<code>// sender comes over as a struct
struct myStruct {
    var tag: Int = 0
    var value: Float = 0
}
let sender = myStruct(tag: 1, value: 199)

// some vars for the calculation
let globalTotal: Float = 597
let globalAnotherTotal: Float = 0

// an array of data structs
struct myDataStruct {
    var name: String = ""
    var value: Float = 0
}
var myData: [myDataStruct] = []
myData.append(myDataStruct(name: "Tom", value: 45.0))
myData.append(myDataStruct(name: "Dick", value: 16.4))
myData.append(myDataStruct(name: "Harry", value: 12.3))

// a closure to do the calculation
var calcOtherVals: (Float, Float) -> (Float) = { (startVal, senderStartVal) in

    let remainingStartVals = globalTotal - senderStartVal
    let remainingNewVal = globalTotal - sender.value - globalAnotherTotal

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVal

    return endVal
}

// now need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag hopefully using filter and map
</code>```

So basically I'm trying to use filter and map and the calcOtherVals closure to edit the array of structs in place. I can do this with conditionals and loops and calcOtherVals as a function no problem. Just hoping to do it more elegantly.

QUESTION: As in the code comment, I need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag. How?

答:
This Question is Already have an answer,

for better understanding you can review this very good tutorial about map, filter and reduce

Link:- https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/

Body:
I may have this really wrong. Noob. I've recreated what I'm doing in a playground type environment here. Basically the sender is a slider within a UITableView of other sliders. The myData is the underlying data. I want to perform a calculation to all the items of the underlying data EXCEPT the one which corresponds to the sender item. I have no idea if my closure syntax is correct. This is the first time I'm creating one.

// sender comes over as a struct
struct myStruct {
    var tag: Int = 0
    var value: Float = 0
}
let sender = myStruct(tag: 1, value: 199)

// some vars for the calculation
let globalTotal: Float = 597
let globalAnotherTotal: Float = 0

// an array of data structs
struct myDataStruct {
    var name: String = ""
    var value: Float = 0
}
var myData: [myDataStruct] = []
myData.append(myDataStruct(name: "Tom", value: 45.0))
myData.append(myDataStruct(name: "Dick", value: 16.4))
myData.append(myDataStruct(name: "Harry", value: 12.3))

// a closure to do the calculation
var calcOtherVals: (Float, Float) -> (Float) = { (startVal, senderStartVal) in

    let remainingStartVals = globalTotal - senderStartVal
    let remainingNewVal = globalTotal - sender.value - globalAnotherTotal

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVal

    return endVal
}

// now need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag hopefully using filter and map

So basically I'm trying to use filter and map and the calcOtherVals closure to edit the array of structs in place. I can do this with conditionals and loops and calcOtherVals as a function no problem. Just hoping to do it more elegantly.

QUESTION: As in the code comment, I need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag. How?


问:
How do you search MS SQL database for a particular string?
The Situation

I come from PHP + MySQL background and I'm migrating an ASP website.

I've migrated them a few times before, but in this case I'm encountering a couple of issues that disorient me and are preventing me from importing a database.

The Obstacles

I downloaded, through Plesk (current version as of writing of this post), a backup of the MS SQL database. But upon opening it I find strings of numbers, not SQL. Thus I cannot do a find and replace of the website URL.

Ex.

5441 5045 0000 0300 8c00 0e01 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000

When I connect to MS SQL via myLittleAdmin and navigate to Tools > New Query and attempt to use a FIND or SEARCH command, as I would in MySQL, it simply doesn't work.

I search the MS SQL documention for similar commands but couldn't locate any. And all of the Questions here on Stack Overflow that come up related to my question have huge queries that have a lot of syntax / code that is irrelevant to the simplicity of my question.

The Question

Can someone help me understand what I'm missing here?

Ultimately I am just seeking the MS SQL code I write to search the entire database for an instance of a particular string of text.

答:
Please see the following SO post on obtaining a dump: How can I get a SQL dump of a SQL Server 2008 database?

From there, locate the text in question then update the actual DB accordingly once you've identified the requisite tables and columns.


问:
PHP - Displaying html from mysql text field in a div
I've some problem with displaying html tags after I retrieve them from a text field in my mysql DB.

my code looks something like this:

```<code><div class='textDiv'><? echo htmlspecialchars_decode(str_replace("\r\n", "<br>", $row["textField"]), ENT_NOQUOTES);?></div>
</code>```

So when the text field in mysql has only plain text, everything is fine, but when I add a link inside the text, I get a line break before and after the link tag, and the displayed text becomes line this:

```<code>Some text justified over the div, then a sudden break
text with link to source
then the text continues justified as normal
</code>```

However, HTML code generated by the script is like this:

```<code><div class="textDiv">Senior Advisor said in a <a href="test.html">media interview</a> that the overall monetary policy tone is shifting towards...</div>
</code>```

Do you guys have any idea why this happens and how to fix it? So that the text is displayed smoothly without line breaks?

答:
When you are using htmlspecialchars_decode all of the text's html is being decoded , so if you want to keep the decode function

1)Change the link in to how a normal link will look like , eg : yourwebsite.com/test.html don't add the  tag

2) Don't echo string directly  do this

```<code>$text = htmlspecialchars_decode(str_replace("\r\n", "<br>", $row["textField"]);
</code>```

3) Then pass the variable $text to code to detect links , here is one :-

```<code>        $reg_exUrl = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.\,]*(\?\S+)?)?)*)@';
    if(preg_match($reg_exUrl, $text, $url)) {
    echo preg_replace($reg_exUrl, '<a href="https://'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
    }
    else
    {
    echo $text;
    }
</code>```

You can change the code to adjust to your needs

Body:
I've some problem with displaying html tags after I retrieve them from a text field in my mysql DB.

my code looks something like this:

<? echo htmlspecialchars_decode(str_replace("\r\n", "
", $row["textField"]), ENT_NOQUOTES);?>

So when the text field in mysql has only plain text, everything is fine, but when I add a link inside the text, I get a line break before and after the link tag, and the displayed text becomes line this:

Some text justified over the div, then a sudden break
text with link to source
then the text continues justified as normal

However, HTML code generated by the script is like this:

Senior Advisor said in a media interview that the overall monetary policy tone is shifting towards...

Do you guys have any idea why this happens and how to fix it? So that the text is displayed smoothly without line breaks?

Body:
When you are using htmlspecialchars_decode all of the text's html is being decoded , so if you want to keep the decode function

1)Change the link in to how a normal link will look like , eg : yourwebsite.com/test.html don't add the  tag

2) Don't echo string directly  do this

$text = htmlspecialchars_decode(str_replace("\r\n", "<br>", $row["textField"]);

3) Then pass the variable $text to code to detect links , here is one :-

        $reg_exUrl = '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.\,]*(\?\S+)?)?)*)@';
    if(preg_match($reg_exUrl, $text, $url)) {
    echo preg_replace($reg_exUrl, '<a href="https://'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
    }
    else
    {
    echo $text;
    }

You can change the code to adjust to your needs


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答:
In some cases it makes sense. But, in the majority of cases use of it it considered poor practice because it can make the execution path of code tricky to read compared to using structured code such as for loops and while loops.

When you look at a goto or a label, you don't really know where is goes to or comes from without reading or searching through the code for the label name. This is tricky especially if the goto doesn't fit on the same screen as the label. Compare this to a for loop or a while loop or an if.. you can tell from the structure (i.e. indenting of the code) what the execution path is.

Having said this, it sometimes is useful, especially for example when jumping out of some nested for loops that are digging for a particular value inside a multi-dimensional array. You could use a goto here to jump out of the for loops when the correct value is found.

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

OwnerDisplayName: Scott Langham


问:
ASP.NET app with Sharepoint integration
We have ASP.NET business Application which we would like to integrate with Sharepoint. ASP.NET Application have lot of document and search as part of the system. I am putting togeather a Design document. If any one have any tech design template with the topics we need to cover for Sharepoint and ASP.NET integration in prespective of upload documents and search for documents? </p>

答: For uploading document is same like a file upload in the asp.net only you have to upload in the library in the sharepoint. For search you have to give specific files or restrictions top the users.</p>

Title: ASP.NET app with Sharepoint integration


问:
Mock an object created in the middle of a method
I know that creating an instance of a Class in the middle of a method it's a bad practice since it makes code hard to test.
But I can't refactor the code, so I need to find a way to mock an Object created with new in the middle of a method under test.

Used Frameworks: PHPUnit, Mockery, WP_Mock

Example: Here I need to mock the get_second_string() method from the instance of the class ExternalClass

```<code>Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}
</code>```

答: IMHO there is no way to do such a thing. You should pass the object as parameter to the method.</p>

Body:
I know that creating an instance of a Class in the middle of a method it's a bad practice since it makes code hard to test.
But I can't refactor the code, so I need to find a way to mock an Object created with new in the middle of a method under test.

Used Frameworks: PHPUnit, Mockery, WP_Mock

Example: Here I need to mock the get_second_string() method from the instance of the class ExternalClass

Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}


问:
UI Testing with Xcode: How to find a button that has no title?
I have some buttons in my user interface that only display an image and no title. How can I access them during a UI Test?  window.buttons["delete"].click() doesn't find the button due to lack of title. And I cannot set the title because the image has some transparency.

答:
You should set an accessibilityIdentifier. This is a non-user-facing property which was designed to allow you to identify elements in your UI tests. It was introduced to stop people from abusing accessibilityLabel, which people would previously use for identifying things in their tests, but which had an effect on the experience of Voiceover users, who hear the contents of accessibilityLabel when they select an element.

```<code>// app code
let myButton: UIButton!
myButton.accessibilityIdentifier = "deleteButton"

// test code
let app = XCUIApplication()
let deleteButton = app.buttons["deleteButton"]
</code>```

Body:
You should set an accessibilityIdentifier. This is a non-user-facing property which was designed to allow you to identify elements in your UI tests. It was introduced to stop people from abusing accessibilityLabel, which people would previously use for identifying things in their tests, but which had an effect on the experience of Voiceover users, who hear the contents of accessibilityLabel when they select an element.

// app code
let myButton: UIButton!
myButton.accessibilityIdentifier = "deleteButton"

// test code
let app = XCUIApplication()
let deleteButton = app.buttons["deleteButton"]