问:
Bootstrap-datepicker inline get Date on click in short format
I am a beginner and trying the Bootstrap-Datepicker. I am using it embedded/inline like in this Demo.

It works, but I want that the selected Date to be displayed in a label/textbox etc. when clicked on a Date. So far I only got the Date after I click on a Button, but more worse it is a huge line like
Thu Mar 30.2017 00:00:00 GMT +100 (Mitteleuropäische Zeit).
I want it simple like 30.03.2017 or 30. Mar.2017.

What should I do?

PS. The first 2 solutions work but gives the long line back. The other 2 give undefined back.

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Untitled Document</title>
    <!-- Bootstrap -->
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.js"></script>
    <link href="css/bootstrap.css" rel="stylesheet">
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery-1.11.3.min.js"></script>

    <!-- Bootstrap Date-Picker Plugin -->
    <script src="js/bootstrap-datepicker.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap-datepicker3.css"/>
  </head>
  <body>
    <div id="pickyDate"> </div>
    <div>
      <input  type="text" placeholder="Date shown here"  id="showDate"/
    </div>
    <!-- Testing here -->
    <div>
      <button type="button" class="btn btn-danger" onClick="showTestDate()">Danger Button</button>
      <span class="label label-danger" id="DateTest">Danger Label</span>
      <span class="label label-info" id="lbl2">Info Label</span>
      <span class="label label-info" id="lbl3">Info Label</span>
    </div>

    <script>
      $(document).ready(function(){
        $('#pickyDate').datepicker({
          format: "dd/mm/yyyy",
          todayBtn: "linked",
          language: "de",
          daysOfWeekDisabled: "0,6",
          daysOfWeekHighlighted: "4",
          todayHighlight: true,
        });
      })
      /* Need it in Format dd mm yyyy */
      function showTestDate(){
        /** works but output is too long */
        var datelist = $('#pickyDate').datepicker('getDate');
        document.getElementById("DateTest").innerText = datelist;

        var valueDate = $("#pickyDate").datepicker("getDate");
        document.getElementById("showDate").value = valueDate;

        /** works not 'undefined' */
        var ndate = $("#pickyDate").data("datepicker").date;
        document.getElementById("lbl2").innerText = ndate;

        var myDate=window.document.getElementById("pickyDate").value;
        document.getElementById("lbl3").innerText=myDate;
      }
    </script>
  </body>
</html>
</code>```

答:
You have to use datepicker('getFormattedDate') instead of datepicker('getDate'). getDate retuns a JavaScript Date object that will show in the long format mentionend in the question.

Change format option to dd.mm.yyyy to get date with numeric month or to dd-M-yyyy to get abbreviated month name.

When you selcet a date the changeDate event is fired, so you can attach a listner to it to update your input, labels etc.

Here a working sample:

$('#pickyDate').datepicker({
  format: "dd.mm.yyyy",
  todayBtn: "linked",
  language: "de",
  daysOfWeekDisabled: "0,6",
  daysOfWeekHighlighted: "4",
  todayHighlight: true,
}).on('changeDate', showTestDate);

function showTestDate(){
  var value = $('#pickyDate').datepicker('getFormattedDate');
  $("#showDate").val(value);
  $("#DateTest").html(value);
  $("#lbl2").html(value);
  $("#lbl3").html(value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/locales/bootstrap-datepicker.de.min.js"></script>

<div id="pickyDate"></div>
<div>
  <input type="text" placeholder="Date shown here"  id="showDate"/>
</div>
<!-- Testing here -->
<div>
  <button type="button" class="btn btn-danger" onClick="showTestDate()">Get date</button>
  <span class="label label-danger" id="DateTest">Danger Label</span>
  <span class="label label-info" id="lbl2">Info Label</span>
  <span class="label label-info" id="lbl3">Info Label</span>
</div></code>```

Body:
I am a beginner and trying the Bootstrap-Datepicker. I am using it embedded/inline like in this Demo.

It works, but I want that the selected Date to be displayed in a label/textbox etc. when clicked on a Date. So far I only got the Date after I click on a Button, but more worse it is a huge line like
Thu Mar 30.2017 00:00:00 GMT +100 (Mitteleuropäische Zeit).
I want it simple like 30.03.2017 or 30. Mar.2017.

What should I do?

PS. The first 2 solutions work but gives the long line back. The other 2 give undefined back.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Untitled Document</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link rel="stylesheet" href="css/bootstrap-datepicker3.css"/>

      <input  type="text" placeholder="Date shown here"  id="showDate"/

      <button type="button" class="btn btn-danger" onClick="showTestDate()">Danger Button</button>
      Danger Label
      Info Label
      Info Label

Body:
You have to use datepicker('getFormattedDate') instead of datepicker('getDate'). getDate retuns a JavaScript Date object that will show in the long format mentionend in the question.

Change format option to dd.mm.yyyy to get date with numeric month or to dd-M-yyyy to get abbreviated month name.

When you selcet a date the changeDate event is fired, so you can attach a listner to it to update your input, labels etc.

Here a working sample:

$('#pickyDate').datepicker({
  format: "dd.mm.yyyy",
  todayBtn: "linked",
  language: "de",
  daysOfWeekDisabled: "0,6",
  daysOfWeekHighlighted: "4",
  todayHighlight: true,
}).on('changeDate', showTestDate);

function showTestDate(){
  var value = $('#pickyDate').datepicker('getFormattedDate');
  $("#showDate").val(value);
  $("#DateTest").html(value);
  $("#lbl2").html(value);
  $("#lbl3").html(value);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/locales/bootstrap-datepicker.de.min.js"></script>

<div id="pickyDate"></div>
<div>
  <input type="text" placeholder="Date shown here"  id="showDate"/>
</div>
<!-- Testing here -->
<div>
  <button type="button" class="btn btn-danger" onClick="showTestDate()">Get date</button>
  <span class="label label-danger" id="DateTest">Danger Label</span>
  <span class="label label-info" id="lbl2">Info Label</span>
  <span class="label label-info" id="lbl3">Info Label</span>
</div>


来源: stackexchange

问:
MySQL Many to Many select
I'm trying to create a MySQL Many to Many select query. I have three tables:

Profiles

Skills

Profile_skills (Profile ID and Skills ID)

I want to be able to search for a skill (PHP for example) and all profiles with that skill show up in a list, but including all their other skills. Like most freelance sites, so I can also see that they know MySQL etc.

I haven't found or figured out the correct way to get all info about a profile including all their skills. This is my best result so far:

```<code>SELECT * FROM profiles INNER JOIN profile_skills ON
profile_skills.profil_id = profiles.profil_id INNER JOIN skills ON
skills.skill_id = profile_skills.skill_id WHERE skill = 'PHP'
</code>```

But this only gives me the profile with that one skill and not the rest.

Result:
http://imgur.com/E9PEiaU

Expected:
To have the id, Skill "PHP", and the rest of skills, for example "C#" if user id 1 possesses that skill.
http://imgur.com/5bCG4qo

So like this when I search for a profile with a skill, it also shows the rest of that profiles acquired skills.

答:
You can re-join the profile_skills and skills table to get the result you want.

SELECT p.*, s2.*
FROM skills s1
INNER JOIN profile_skills ps1 ON s.skill_id = ps1.skill_id
INNER JOIN profiles p ON ps1.profil_id = p.profil_id
INNER JOIN profile_skills ps2 ON p.profil_id = ps2.profil_id
INNER JOIN skills s2 ON ps2.skill_id = s2.skill_id
WHERE s1.skill = 'PHP'
```

<p>This will get you a result like this:</p>

<pre class="lang-none prettyprint-override"><code>| p.id | p.name | s.id |       s.skill      |
---------------------------------------------
|  1   | rasmus |  1   |         PHP        |
|  1   | rasmus |  2   |        Linux       |
|  2   | thomas |  1   |         PHP        |
|  2   | thomas |  3   |  Eating Sandwiches |
</code>```

There are various different ways to get each profile in one row with a list of skills. One way is with GROUP_CONCAT in MySQL.

SELECT p.profil_id, p.profile_name, GROUP_CONCAT(s2.skill) AS skills
FROM skills s1
INNER JOIN profile_skills ps1 ON s.skill_id = ps1.skill_id
INNER JOIN profiles p ON ps1.profil_id = p.profil_id
INNER JOIN profile_skills ps2 ON p.profil_id = ps2.profil_id
INNER JOIN skills s2 ON ps2.skill_id = s2.skill_id
WHERE s1.skill = 'PHP'
GROUP BY p.profil_id
```

<p>I added the <code>profile_name</code> column for example, since I don't know what your columns actually are, and you can add other ones, or even still use <code>p.*</code>. Technically, the other columns in <code>profile</code> aren't defined with <code>GROUP BY p.profil_id</code>, and you generally shouldn't select columns that aren't either included in the grouping or some aggregate function, but MySQL will take care of that for you <em>in this case</em>, since they'll all have the same values for each row with the same <code>p.profil_id</code>.</p>

<p>Another way is to just use the first query and do the grouping in PHP:</p>

```$previous_id = null;
while ($row = some_fetch_method()) {
    if ($row['profil_id'] != $previous_id) {
        echo "
$row[profile_name]
";
    }
    echo "
$row[skill]
";
}
```

obviously the HTML won't be quite what you need, but it should be enough to show the general idea.

ContentLicense: CC BY-SA 3.0

Title: MySQL Many to Many select

Body:
I'm trying to create a MySQL Many to Many select query. I have three tables:

Profiles

Skills

Profile_skills (Profile ID and Skills ID)

I want to be able to search for a skill (PHP for example) and all profiles with that skill show up in a list, but including all their other skills. Like most freelance sites, so I can also see that they know MySQL etc.

I haven't found or figured out the correct way to get all info about a profile including all their skills. This is my best result so far:

SELECT * FROM profiles INNER JOIN profile_skills ON
profile_skills.profil_id = profiles.profil_id INNER JOIN skills ON
skills.skill_id = profile_skills.skill_id WHERE skill = 'PHP'

But this only gives me the profile with that one skill and not the rest.

Result:
http://imgur.com/E9PEiaU

Expected:
To have the id, Skill "PHP", and the rest of skills, for example "C#" if user id 1 possesses that skill.
http://imgur.com/5bCG4qo

So like this when I search for a profile with a skill, it also shows the rest of that profiles acquired skills.

Body:
You can re-join the profile_skills and skills table to get the result you want.

SELECT p.*, s2.*
FROM skills s1
INNER JOIN profile_skills ps1 ON s.skill_id = ps1.skill_id
INNER JOIN profiles p ON ps1.profil_id = p.profil_id
INNER JOIN profile_skills ps2 ON p.profil_id = ps2.profil_id
INNER JOIN skills s2 ON ps2.skill_id = s2.skill_id
WHERE s1.skill = 'PHP'

This will get you a result like this:

| p.id | p.name | s.id |       s.skill      |
---------------------------------------------
|  1   | rasmus |  1   |         PHP        |
|  1   | rasmus |  2   |        Linux       |
|  2   | thomas |  1   |         PHP        |
|  2   | thomas |  3   |  Eating Sandwiches |

There are various different ways to get each profile in one row with a list of skills. One way is with GROUP_CONCAT in MySQL.

SELECT p.profil_id, p.profile_name, GROUP_CONCAT(s2.skill) AS skills
FROM skills s1
INNER JOIN profile_skills ps1 ON s.skill_id = ps1.skill_id
INNER JOIN profiles p ON ps1.profil_id = p.profil_id
INNER JOIN profile_skills ps2 ON p.profil_id = ps2.profil_id
INNER JOIN skills s2 ON ps2.skill_id = s2.skill_id
WHERE s1.skill = 'PHP'
GROUP BY p.profil_id

I added the profile_name column for example, since I don't know what your columns actually are, and you can add other ones, or even still use p.*. Technically, the other columns in profile aren't defined with GROUP BY p.profil_id, and you generally shouldn't select columns that aren't either included in the grouping or some aggregate function, but MySQL will take care of that for you in this case, since they'll all have the same values for each row with the same p.profil_id.

Another way is to just use the first query and do the grouping in PHP:

$previous_id = null;
while ($row = some_fetch_method()) {
    if ($row['profil_id'] != $previous_id) {
        echo "<h3>$row[profile_name]</h3>";
    }
    echo "<div>$row[skill]</div>";
}

obviously the HTML won't be quite what you need, but it should be enough to show the general idea.


问:
Laravel mix compile - class not found
After moving from Laravel 5.3 to 5.4 I am working on moving over to webpack.

It compiles fine however when loading up the page it always shows

app.a711192….js:125 Uncaught ReferenceError: Layout is not defined
    at HTMLDocument. (app.a711192….js:125)
    at i (vendor.19cd2ff….js:2)
    at Object.fireWith [as resolveWith] (vendor.19cd2ff….js:2)
    at Function.ready (vendor.19cd2ff….js:2)
    at HTMLDocument.J (vendor.19cd2ff….js:2)

I have pasted binned the compiled app.js, it looks as if it is compiling as Layout is there, however I am not sure as to why it's not loading it correctly.

webpack.mix.js

```<code>const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */
let npmFolder = './node_modules/';
mix.disableNotifications()
    .js('resources/assets/js/app.js', 'public/js')
    .scripts([
        npmFolder + 'jquery/dist/jquery.min.js',
        npmFolder + 'jquery-migrate/dist/jquery-migrate.min.js',
        npmFolder + 'bootstrap-sass/assets/javascripts/bootstrap.min.js',
        npmFolder + 'axios/dist/axios.min.js'
    ], 'public/js/vendor.js')
    .sass('resources/assets/sass/app.scss', 'public/css')
    .sass('resources/assets/sass/admin/admin.scss', 'public/css')
    .version()
;
</code>```

app.js

```<code>require('./layout.js');
require('./main.js');
</code>```

main.js

```<code>$(function()
{
    let instance = axios.create({
        baseURL: 'https://some-domain.com/api/',
        timeout: 1000,
        headers: {'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
    });

    let layout = new Layout();

    $("button[data-layout-action]").click(function(e)
    {
        let action = $(this).attr('data-layout-action');

        console.log(action);

        switch(action)
        {
            case 'new-page':
                layout.newPage();
                break;
            case 'edit-page':
                layout.editPage();
                break;
            default:
                alert('Invalid layout action ' + action)
        }
    });
});
</code>```

layout.js

```<code>class Layout {
    constructor() {

    }

    newPage() {
        this.loadPage({});
    }

    editPage() {

    }

    loadPage(layout) {
        axios.post('/layout/generate', {
            layout
        })
            .catch(error => {
                alert(error);
            })
    }
}
</code>```

答:
I finally managed to figure this out by adding the following into Layout.js

```<code>module.exports = Layout;
</code>```

Then by adding into app.js

```<code>import * as _layout from './Layout';

const Layout = new _layout();
</code>```

Title: Laravel mix compile - class not found

Body:
After moving from Laravel 5.3 to 5.4 I am working on moving over to webpack.

It compiles fine however when loading up the page it always shows

app.a711192….js:125 Uncaught ReferenceError: Layout is not defined
    at HTMLDocument. (app.a711192….js:125)
    at i (vendor.19cd2ff….js:2)
    at Object.fireWith [as resolveWith] (vendor.19cd2ff….js:2)
    at Function.ready (vendor.19cd2ff….js:2)
    at HTMLDocument.J (vendor.19cd2ff….js:2)

I have pasted binned the compiled app.js, it looks as if it is compiling as Layout is there, however I am not sure as to why it's not loading it correctly.

webpack.mix.js

const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */
let npmFolder = './node_modules/';
mix.disableNotifications()
    .js('resources/assets/js/app.js', 'public/js')
    .scripts([
        npmFolder + 'jquery/dist/jquery.min.js',
        npmFolder + 'jquery-migrate/dist/jquery-migrate.min.js',
        npmFolder + 'bootstrap-sass/assets/javascripts/bootstrap.min.js',
        npmFolder + 'axios/dist/axios.min.js'
    ], 'public/js/vendor.js')
    .sass('resources/assets/sass/app.scss', 'public/css')
    .sass('resources/assets/sass/admin/admin.scss', 'public/css')
    .version()
;

app.js

require('./layout.js');
require('./main.js');

main.js

$(function()
{
    let instance = axios.create({
        baseURL: 'https://some-domain.com/api/',
        timeout: 1000,
        headers: {'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
    });

    let layout = new Layout();

    $("button[data-layout-action]").click(function(e)
    {
        let action = $(this).attr('data-layout-action');

        console.log(action);

        switch(action)
        {
            case 'new-page':
                layout.newPage();
                break;
            case 'edit-page':
                layout.editPage();
                break;
            default:
                alert('Invalid layout action ' + action)
        }
    });
});

layout.js

class Layout {
    constructor() {

    }

    newPage() {
        this.loadPage({});
    }

    editPage() {

    }

    loadPage(layout) {
        axios.post('/layout/generate', {
            layout
        })
            .catch(error => {
                alert(error);
            })
    }
}

Body:
I finally managed to figure this out by adding the following into Layout.js

module.exports = Layout;

Then by adding into app.js

import * as _layout from './Layout';

const Layout = new _layout();


问:
Workflow System with Azure Table Storage
I have a system where we need to run a simple workflow.
Example:

On Jan 1st 08:15 trigger task A for object Z

When triggered then run some code (implementation details not important)

Schedule task B for object Z to run at Jan 3rd 10:25 (and so on)

The workflow itself is simple, but I need to run 500.000+ instances and that's the tricky part.

I know Windows Workflow Foundation and for that very same reason I have chosen not to use that.

My initial design would be to use Azure Table Storage and I would really appreciate some feedback on the design.

The system will consist of two tables

```<code>Table "Jobs"
  PartitionKey: ObjectId
  Rowkey: ProcessOn (UTC Ticks in reverse so that newest are on top)
  Attributes: State (Pending, Processed, Error, Skipped), etc...

Table "Timetable"
  PartitionKey: YYYYMMDD
  Rowkey: YYYYMMDDHHMM_<GUID>
  Attributes: Job_PartitionKey, Job_RowKey
</code>```

The idea is that the runs table will have the complete history of jobs per object and the Timetable will have a list of all jobs to run in the future.

Some assumptions:

A job will never span more than one Object

There will only ever be one pending job per Object

The "job" is very lightweight e.g. posting a message to a queue

The system must be able to perform these tasks:

Execute pending jobs

Query for all records in "Timetable" with a "partition <= Today" and "RowKey <= today"

For each record (in parallel)

Lookup job in Jobs table via PartitionKey and RowKey

If "not exists" or State != Pending then skip

Execute "logic". If fails => log and maybe do some retry logic

Submit "Next run date in Timetable"

Submit "Update State = Processed" and "New Job Record (next run)" as a single transaction

When all are finished => Delete all processed Timetable records

Concern: Only two of the three records modifications are in a transaction. Could this be overcome in any way?

Stop workflow
Stop/pause workflow for Object Z

Query top 1 jobs in Jobs table by PartitionKey

If any AND State == Pending then update to "Cancelled"

(No need to bother cleaning Timetable it will clean itself up "when time comes")

Start workflow

Create Pending record in Jobs table

Create record in Timetable

In terms of "executing the thing" I would
be using a Azure Function or Scheduler-thing to execute the pending jobs every 5 minutes or so.

Any comments or suggestions would be highly appreciated.

Thanks!

答: How about using Service Bus instead? The BrokeredMessage class has a property called ScheduledEnqueueTimeUtc. You can just schedule when you want your jobs to run via the ScheduledEnqueueTimeUtc property, and then fuggedabouddit. You can then have a triggered webjob that monitors the Service Bus messaging queue, and will be triggered very near when the job message is enqueued. I'm a big fan of relying on existing services to minimize the coding needed. </p>

Body:
I have a system where we need to run a simple workflow.
Example:

On Jan 1st 08:15 trigger task A for object Z

When triggered then run some code (implementation details not important)

Schedule task B for object Z to run at Jan 3rd 10:25 (and so on)

The workflow itself is simple, but I need to run 500.000+ instances and that's the tricky part.

I know Windows Workflow Foundation and for that very same reason I have chosen not to use that.

My initial design would be to use Azure Table Storage and I would really appreciate some feedback on the design.

The system will consist of two tables

Table "Jobs"
  PartitionKey: ObjectId
  Rowkey: ProcessOn (UTC Ticks in reverse so that newest are on top)
  Attributes: State (Pending, Processed, Error, Skipped), etc...

Table "Timetable"
  PartitionKey: YYYYMMDD
  Rowkey: YYYYMMDDHHMM_<GUID>
  Attributes: Job_PartitionKey, Job_RowKey

The idea is that the runs table will have the complete history of jobs per object and the Timetable will have a list of all jobs to run in the future.

Some assumptions:

A job will never span more than one Object

There will only ever be one pending job per Object

The "job" is very lightweight e.g. posting a message to a queue

The system must be able to perform these tasks:

Execute pending jobs

Query for all records in "Timetable" with a "partition <= Today" and "RowKey <= today"

For each record (in parallel)

Lookup job in Jobs table via PartitionKey and RowKey

If "not exists" or State != Pending then skip

Execute "logic". If fails => log and maybe do some retry logic

Submit "Next run date in Timetable"

Submit "Update State = Processed" and "New Job Record (next run)" as a single transaction

When all are finished => Delete all processed Timetable records

Concern: Only two of the three records modifications are in a transaction. Could this be overcome in any way?

Stop workflow
Stop/pause workflow for Object Z

Query top 1 jobs in Jobs table by PartitionKey

If any AND State == Pending then update to "Cancelled"

(No need to bother cleaning Timetable it will clean itself up "when time comes")

Start workflow

Create Pending record in Jobs table

Create record in Timetable

In terms of "executing the thing" I would
be using a Azure Function or Scheduler-thing to execute the pending jobs every 5 minutes or so.

Any comments or suggestions would be highly appreciated.

Thanks!


问:
How to implement app indexing with library project?
I'm trying to implement app indexing for one of my apps, but I'm not quite sure what I should return as the appUri for the app indexing Action.

Let's say I have a the package name com.example.myapp and the webUri http://example.com/some/path.

As I understand it, the appUri would normally be com.example.myapp/http/example.com/some/path in this case, correct?

Now  enter the library project that my app uses, and where the indexed activity exists. Let's call the library project com.example.mylibrary and the indexed activity MyActivity.

If I want to start the activity using adb, I would use

adb shell am start -W -a android.intent.action.VIEW -d "http://example.com/some/path" com.example.myapp/com.example.mylibrary.MyActivity

So, my question is - what should the appUri for the app indexing Action be in this case? Is it affected at all by the fact that the activity is within the library project?

答:
In general you can build Action by Action.Builder provided by library. As uri you need to provide related URI. So if you want to index View Action you should provide URI of product, that was viewed.

```<code>Uri.Builder builder = new Uri.Builder();
    String uriStr = builder
        .scheme("http")
        .authority("example.com")
        .appendPath("some/path").build().toString();

    Action action = new Action.Builder(Action.Builder.VIEW_ACTION)
        .setObject("productName", uriStr)
        .build();
</code>```

For more details you can look at logging actions docs and their sample app.

To test:

```<code>adb shell am start -a android.intent.action.VIEW -d "{URL}" {package name}
</code>```

where {package name} = com.example.myapp and URL = http://example.com/some/path

At the end, your Activity placed in library should have intent filter which can handle your URI http://example.com/some/path

Body:
In general you can build Action by Action.Builder provided by library. As uri you need to provide related URI. So if you want to index View Action you should provide URI of product, that was viewed.

Uri.Builder builder = new Uri.Builder();
    String uriStr = builder
        .scheme("http")
        .authority("example.com")
        .appendPath("some/path").build().toString();

    Action action = new Action.Builder(Action.Builder.VIEW_ACTION)
        .setObject("productName", uriStr)
        .build();

For more details you can look at logging actions docs and their sample app.

To test:

adb shell am start -a android.intent.action.VIEW -d "{URL}" {package name}

where {package name} = com.example.myapp and URL = http://example.com/some/path

At the end, your Activity placed in library should have intent filter which can handle your URI http://example.com/some/path


问:
Convert a byte array into an int array in java
Is there was a way to convert a hole array of bytes (lets say 1024) into an int array of total 256 integers without using something similar to this:</p>

```<code>int result = 0;
    result = b[0] & MASK;
    result = result + ((b[1] & MASK) << 8);
    result = result + ((b[2] & MASK) << 16);
    result = result + ((b[3] & MASK) << 24);
return result;
</code>```

答: An int array?  No, there isn't.  You might be able to get other APIs that are similar to arrays, but even so they'll be doing something like that underneath.  For example, ByteBuffer.wrap(array).asIntBuffer() would do that: it'd give you an array-like API, but underneath it'd be doing exactly what you say.

Body:
Is there was a way to convert a hole array of bytes (lets say 1024) into an int array of total 256 integers without using something similar to this:

int result = 0;
    result = b[0] & MASK;
    result = result + ((b[1] & MASK) << 8);
    result = result + ((b[2] & MASK) << 16);
    result = result + ((b[3] & MASK) << 24);
return result;


问:
Adding content files to and accessing content files from a web service
I want to include an XML file in the bin directory of my web application/web service.  I've included the bin folder in my project in Visual Studio and added the file.  I set its Build Action to "Content" and Copy to Output Directory to "Copy Always".  When my code goes to find it, I use

```<code>string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!dir.EndsWith(@"\")) dir += @"\";
</code>```

to get the directory and return it as appPath, where appPath is (unescaped version):

```<code>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs\0c7655f\d4908928\assembly\dl3\5cf9fd67\fdc52284_ffa7d201\
</code>```

then I append the file name of my XML file (where string filename = "myXmlFile.xml") to read it:

```<code>StreamReader reader = new StreamReader(appPath + filename);
</code>```

But I get an exception on that line of code, that it could not find my file.  I am handling for escaping of the slashes fine, so it is not that.  When I checked the physical directory that the path points to, it was not copied to that directory, and that is the cause of the exception.  So how do I get my file to get copied there?

答:
How about using HostingEnvironment.ApplicationPhysicalPath

```<code>var dir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\filename.xml")
</code>```

See related question how to get the application path in asp.net?.

Body:
I want to include an XML file in the bin directory of my web application/web service.  I've included the bin folder in my project in Visual Studio and added the file.  I set its Build Action to "Content" and Copy to Output Directory to "Copy Always".  When my code goes to find it, I use

string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!dir.EndsWith(@"\")) dir += @"\";

to get the directory and return it as appPath, where appPath is (unescaped version):

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs\0c7655f\d4908928\assembly\dl3\5cf9fd67\fdc52284_ffa7d201\

then I append the file name of my XML file (where string filename = "myXmlFile.xml") to read it:

StreamReader reader = new StreamReader(appPath + filename);

But I get an exception on that line of code, that it could not find my file.  I am handling for escaping of the slashes fine, so it is not that.  When I checked the physical directory that the path points to, it was not copied to that directory, and that is the cause of the exception.  So how do I get my file to get copied there?

Body:
How about using HostingEnvironment.ApplicationPhysicalPath

var dir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\filename.xml")

See related question how to get the application path in asp.net?.


问:
Concatenate fields on Odoo v9
I'm trying to concatenate  3 fields to form a internal code and display it in the views:

I have 3 models:

Category (size=2)

Product  (size=4)

Serie    (size=3)

And I want to display it in the form like this

Product Code: CAT-PROD-001

I don't know if i have to use a computed field or if exist anoter way to do this, because I was doing test with computed fields but can't reach the desired output.

Edit:

Now I'm trying to use a computed field with a onchange function to generate the value on the field

MODEL

```<code># -*- coding:utf-8 -*-
from openerp import models,fields,api
class exec_modl(models.Model):
        _name           =   "exec.modl"
        _rec_name       =   "exec_desc"
        exec_code       =   fields.Char('Identificador',required=True,size=3)
        exec_desc       =   fields.Char('Descripción',required=True)
        cour_exec       =   fields.Many2one('cour.modl')
        proc_exec       =   fields.Many2one('enro.modl')
        inte_code       =   fields.Char(compute='_onchange_proc')
</code>```

FUNCTION

```<code>  @api.onchange('proc_exec')
    def _onchange_proc(self):
        cate    =   "XX"
        cour    =   "XXXX"
        exet    =   "XXX"
        output  =   cate+"-"+cour+"-"+exet
        return output
</code>```

I'm just trying with plain values just to know how to send it to the field.

EDIT 2:

Using the answer from @Charif I can print the static strings on the form, but the next milestome I'm trying to reach is getting the codes (external models fields) to crate that inte_code

ex: From the model cour.modl I want to get the value from the field cour_code(internal_id for course) corresponding to the cour_exec field on the first model (the cour_exec field have the description of the course from cour.modl model)

```<code>@api.depends('proc_exec')
        def _onchange_proc(self):
            cate    =   "XX"
            cour    =   self.env['cour.modl'].search([['cour_desc','=',self.cour_exec]])
            exet    =   "XXX"
            output  =   cate+"-"+cour+"-"+exet
            self.inte_code = output
</code>```

E        @api.depends('inte_code')
        def _onchange_proc(self):
            cate    =   "XX"
            # first domain use tuple not list
            cour_result    =   self.env['cour.modl'].search([('id','=',exec_modl.cour_exec)]).cour_code
            cour = "" # empty string because you cannot contcatenate None or False with a string value
            #if  cour_result :
            #    cour = ",".join(crse_code for crse_code in cour_result.ids)
            #else :
            #    print "result of search is empty check you domain"
            exet    =   "XXX"
            output  =   cate+"-"+cour+"-"+exet+"-"+cour_result
            self.inte_code = output

EDIT 3

I've been trying to usse the search mode calling other model values but I have the console output :

Can't adapt type 'Many2One' , seems im trying to compare 2 different type of fields, the types can be parsed on odoo ? or I'm using a wrong syntax for search method?

```<code>   @api.depends('inte_code')
    def _onchange_proc(self):
        cate    =   "XX"
        # first domain use tuple not list
        cour_result    = self.env['cour.modl'].search([('id','=',exec_modl.cour_exec)]).cour_code

        exet    =   "XXX"
        output  =   cate+"-"+cour+"-"+exet+"-"+cour_result
        self.inte_code = output
</code>```

EDIT 4 : ANSWER
Finally I've reach the desired output! using the following code:

```<code>@api.depends('inte_code')
        def _onchange_proc(self):
            cate_result    = self.cate_exec
            proc_result    =    self.env['enro.modl'].search([('id','=',str(self.proc_exec.id))]).enro_code
            cour_result    =    self.env['cour.modl'].search([('id','=',str(self.cour_exec.id))]).cour_code
            output  =   str(proc_result)+"-"+str(cate_result)+"-"+str(cour_result)+"-"+self.exec_code
            self.inte_code = output
</code>```

Additionaly I've added a related field for add the course category to the final output.

```<code>cate_exec       =   fields.Char(related='cour_exec.cour_cate.cate_code')
</code>```

Now the output have this structure:

INTERNAL_PROC_ID-CAT_COURSE-COURSE-EXECUTION_CODE

EX: xxxxxxxx-xx-xxxx-xxx

答:
First in compute field use api.depends not onchange :

Second the compute function don't return anything but it passes the record on the self variable so all you have to do is assign the value to the computed field.

@api.depends('proc_exec')
def _onchange_proc(self):
    # compute the value
    # ...
    # Than assign it to the field
    self.computed_field =   computed_value
```

<p>one of the thing that i recommand to do is to loop the self because it's recordSet so if the self contains more than one record this previous code will raise signlton error
 so you can do this : </p>

<pre class="lang-py prettyprint-override"><code># compute the value here if it's the same for every record in self
for rec in self :
     # compute the value here it depends on the value of the record
     rec.compute_field = computeValue
</code>```

or use api.one with api.depends

@api.one
@api.depends('field1', 'field2', ...)
```

<p>EDITS: </p>

<pre class="lang-py prettyprint-override"><code>    @api.depends('proc_exec')
    def _onchange_proc(self):
        cate    =   "XX"
        # first domain use tuple not list
        cour_result    =   self.env['cour.modl'].search([('cour_desc','=',self.cour_exec)])
        cour = "" # empty string because you cannot contcatenate None or False with a string value
        if cour_result :
            cour = ",".join(id for id in cour_result.ids)
        else :
            print "result of search is empty check you domain"
        exet    =   "XXX"
        output  =   cate+"-"+cour+"-"+exet
        self.inte_code = output
</code>```

try this code i think the result of search is a recordSet so you can get the list of ids by name_of_record_set.ids  than create a string from the list of ids to concatenate it try and let me know if there is an error because i'm using work PC i don't have odoo on my hand ^^

Title: Concatenate fields on Odoo v9

Body:
I'm trying to concatenate  3 fields to form a internal code and display it in the views:

I have 3 models:

Category (size=2)

Product  (size=4)

Serie    (size=3)

And I want to display it in the form like this

Product Code: CAT-PROD-001

I don't know if i have to use a computed field or if exist anoter way to do this, because I was doing test with computed fields but can't reach the desired output.

Edit:

Now I'm trying to use a computed field with a onchange function to generate the value on the field

MODEL

# -*- coding:utf-8 -*-
from openerp import models,fields,api
class exec_modl(models.Model):
        _name           =   "exec.modl"
        _rec_name       =   "exec_desc"
        exec_code       =   fields.Char('Identificador',required=True,size=3)
        exec_desc       =   fields.Char('Descripción',required=True)
        cour_exec       =   fields.Many2one('cour.modl')
        proc_exec       =   fields.Many2one('enro.modl')
        inte_code       =   fields.Char(compute='_onchange_proc')

FUNCTION

  @api.onchange('proc_exec')
    def _onchange_proc(self):
        cate    =   "XX"
        cour    =   "XXXX"
        exet    =   "XXX"
        output  =   cate+"-"+cour+"-"+exet
        return output

I'm just trying with plain values just to know how to send it to the field.

EDIT 2:

Using the answer from @Charif I can print the static strings on the form, but the next milestome I'm trying to reach is getting the codes (external models fields) to crate that inte_code

ex: From the model cour.modl I want to get the value from the field cour_code(internal_id for course) corresponding to the cour_exec field on the first model (the cour_exec field have the description of the course from cour.modl model)

@api.depends('proc_exec')
        def _onchange_proc(self):
            cate    =   "XX"
            cour    =   self.env['cour.modl'].search([['cour_desc','=',self.cour_exec]])
            exet    =   "XXX"
            output  =   cate+"-"+cour+"-"+exet
            self.inte_code = output

E        @api.depends('inte_code')
        def _onchange_proc(self):
            cate    =   "XX"
            # first domain use tuple not list
            cour_result    =   self.env['cour.modl'].search([('id','=',exec_modl.cour_exec)]).cour_code
            cour = "" # empty string because you cannot contcatenate None or False with a string value
            #if  cour_result :
            #    cour = ",".join(crse_code for crse_code in cour_result.ids)
            #else :
            #    print "result of search is empty check you domain"
            exet    =   "XXX"
            output  =   cate+"-"+cour+"-"+exet+"-"+cour_result
            self.inte_code = output

EDIT 3

I've been trying to usse the search mode calling other model values but I have the console output :

Can't adapt type 'Many2One' , seems im trying to compare 2 different type of fields, the types can be parsed on odoo ? or I'm using a wrong syntax for search method?

   @api.depends('inte_code')
    def _onchange_proc(self):
        cate    =   "XX"
        # first domain use tuple not list
        cour_result    = self.env['cour.modl'].search([('id','=',exec_modl.cour_exec)]).cour_code

        exet    =   "XXX"
        output  =   cate+"-"+cour+"-"+exet+"-"+cour_result
        self.inte_code = output

EDIT 4 : ANSWER
Finally I've reach the desired output! using the following code:

@api.depends('inte_code')
        def _onchange_proc(self):
            cate_result    = self.cate_exec
            proc_result    =    self.env['enro.modl'].search([('id','=',str(self.proc_exec.id))]).enro_code
            cour_result    =    self.env['cour.modl'].search([('id','=',str(self.cour_exec.id))]).cour_code
            output  =   str(proc_result)+"-"+str(cate_result)+"-"+str(cour_result)+"-"+self.exec_code
            self.inte_code = output

Additionaly I've added a related field for add the course category to the final output.

cate_exec       =   fields.Char(related='cour_exec.cour_cate.cate_code')

Now the output have this structure:

INTERNAL_PROC_ID-CAT_COURSE-COURSE-EXECUTION_CODE

EX: xxxxxxxx-xx-xxxx-xxx

Body:
First in compute field use api.depends not onchange :

Second the compute function don't return anything but it passes the record on the self variable so all you have to do is assign the value to the computed field.

@api.depends('proc_exec')
def _onchange_proc(self):
    # compute the value
    # ...
    # Than assign it to the field
    self.computed_field =   computed_value

one of the thing that i recommand to do is to loop the self because it's recordSet so if the self contains more than one record this previous code will raise signlton error
 so you can do this :

# compute the value here if it's the same for every record in self
for rec in self :
     # compute the value here it depends on the value of the record
     rec.compute_field = computeValue

or use api.one with api.depends

@api.one
@api.depends('field1', 'field2', ...)

EDITS:

    @api.depends('proc_exec')
    def _onchange_proc(self):
        cate    =   "XX"
        # first domain use tuple not list
        cour_result    =   self.env['cour.modl'].search([('cour_desc','=',self.cour_exec)])
        cour = "" # empty string because you cannot contcatenate None or False with a string value
        if cour_result :
            cour = ",".join(id for id in cour_result.ids)
        else :
            print "result of search is empty check you domain"
        exet    =   "XXX"
        output  =   cate+"-"+cour+"-"+exet
        self.inte_code = output

try this code i think the result of search is a recordSet so you can get the list of ids by name_of_record_set.ids  than create a string from the list of ids to concatenate it try and let me know if there is an error because i'm using work PC i don't have odoo on my hand ^^

ContentLicense: CC BY-SA 4.0


问:
Custom (width and height) to print Product Labels on Odoo - QWEB
Right now the system is printing the Product Labels and work fine but in wrong dimensions.

I need set width to 7cm and height to 4cm on QWEB report.

Where I can change the dimensions to print QWEB report?

I can't change the format to the print preferences because in a sheet can be many Products Labels.

This is my QWEB:

<?xml version="1.0"?>
<t t-name="product.report_productlabel">
<t t-call="report.html_container">

  <t t-foreach="docs" t-as="template">
    <t t-foreach="template.product_variant_ids" t-as="product">

                  <t t-esc="product.name"/>

                    <t t-esc="product.company_id.currency_id.symbol"/>

                  <t t-esc="product.barcode"/>

    </t>
  </t>

```

答:
This the solution for the width of the table using the DPI of 90;

```<code><table style="border-spacing:0;margin-bottom:0;height: 187px; width: 319px; border: 2px solid black;" class="table">
</code>```

This is the QWEB template with the dimensions you need and I also scale the fonts and padding of the table elements to match the new width and height:

<?xml version="1.0"?>
<t t-name="product.report_productlabel">
<t t-call="report.html_container">

        <t t-foreach="docs" t-as="template">
            <t t-foreach="template.product_variant_ids" t-as="product">

                                        <t t-esc="product.name"/>

                                                <t t-esc="product.company_id.currency_id.symbol"/>

                                            <t t-esc="product.barcode"/>

            </t>
        </t>

</t>
```

Body:
This the solution for the width of the table using the DPI of 90;

<table style="border-spacing:0;margin-bottom:0;height: 187px; width: 319px; border: 2px solid black;" class="table">

This is the QWEB template with the dimensions you need and I also scale the fonts and padding of the table elements to match the new width and height:

<?xml version="1.0"?>
<t t-name="product.report_productlabel">
<t t-call="report.html_container">
    <div class="page">
        <style>

        </style>

        <t t-foreach="docs" t-as="template">
            <t t-foreach="template.product_variant_ids" t-as="product">

                <div class="col-xs-6" style="padding:0;">
                    <table style="border-spacing:0;margin-bottom:0;height: 187px; width: 319px; border: 2px solid black;"
                           class="table">
                        <thead>
                            <tr style="width: 3in;">
                                <td style="width: 2.63in; font-size: 19px; text-align: left; background-color: #fff; margin-top: 10px;"
                                    colspan="2"
                                    class="col-xs-8 danger">
                                    <strong style="text-transform: uppercase;">
                                        <t t-esc="product.name"/>
                                    </strong>
                                </td>
                            </tr>
                        </thead>
                        <tbody>
                            <tr style="width: 1in;">
                                <td width="50%"
                                    style="text-align: center; border-top: 0px solid #fff; padding: 5px; position: relative;">
                                    <div style="position:absolute; bottom: 20px; left: 0; padding-left: 5px; width: 100%">
                                        <h4 style="border: 4px solid #ff4040; border-radius: 9px; background-color: #ffff00; padding: 10px 6px; font-size: 21px; margin: 0px ">
                                            <strong t-field="product.list_price"/>
                                            <strong>
                                                <t t-esc="product.company_id.currency_id.symbol"/>
                                            </strong>
                                        </h4>
                                    </div>
                                </td>
                                <td width="50%"
                                    style="text-align: center;border-top: 0px solid #fff;padding: 5px; position: relative;">
                                    <div style="position:absolute; bottom: 20px; padding-right: 5px;">
                                        <img class="img-responsive"
                                             t-att-src="'data:image/png;base64,%s' % res_company.logo"
                                             style="background-color: #fff; margin-left: auto; margin-right: auto; width: auto; height: 35px; margin-bottom: 5px;"/>
                                        <img class="img-responsive" t-if="product.barcode"
                                             t-att-src="'/report/barcode/?type=%s&amp;value=%s&amp;width=%s&amp;height=%s' % ('EAN13', product.barcode, 650, 200)"
                                             style="height: 20px; width: 100%;"/>
                                        <span style="font-size: 14px">
                                            <t t-esc="product.barcode"/>
                                        </span>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

            </t>
        </t>
    </div>
</t>


问:
Rounting in angular2 application
I am trying to route to dashboard page on clicking login button. But I'm unable to route to it. I have a login component and dashboard component. I want to route to dashboard page on successful login.
Login-routing module.ts

```<code>const routes: Routes = [
    {
                path: 'login',
                component: LoginComponent,
                data: {
                    title: 'Login Page'
                }
            },
            {
                path: 'register',
                component: RegisterComponent,
                data: {
                    title: 'Register Page'
                }
            }

];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class LoginRoutingModule {}
</code>```

This is my login html file.

```<code>    <div class="app flex-row align-items-center">
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card-group mb-0">
          <div class="card p-2">
            <div class="card-block">
              <h1>Login</h1>
              <p class="text-muted">Sign In to your account</p>
              <div class="input-group mb-1">
                                <span class="input-group-addon"><i class="icon-user"></i>
                                </span>
                <input type="text" class="form-control" placeholder="Username">
              </div>
              <div class="input-group mb-2">
                                <span class="input-group-addon"><i class="icon-lock"></i>
                                </span>
                <input type="password" class="form-control" placeholder="Password">
              </div>
              <div class="row">
                <div class="col-6">
                  <!--
                  <button type="button" class="btn btn-primary px-2">Login</button>
                  !-->
                  <button (click)="OnTestLogin()">Login</button>
                  <p>Output:{{postData}}</p>
                </div>
                <div class="col-6 text-right">
                  <button type="button" class="btn btn-link px-0">Forgot password?</button>
                </div>
              </div>
            </div>
          </div>
          <div class="card card-inverse card-primary py-3 hidden-md-down" style="width:44%">
            <div class="card-block text-center">
              <div>
                <h2>Sign up</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
                <button type="button" class="btn btn-primary active mt-1">Register Now!</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

This is my app-routing.ts file

```<code> export const routes: Routes = [
  {
    path: '',
    component: LoginComponent
  },
  {
    path: '#/dashboard',
    component: LoginComponent
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: {
      title: 'login'
    },

    children: [
      {
        path: 'login',
        loadChildren: './login/login.module#LoginModule'
      },
    ]
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

I am very new to angular and routing concepts. Please help me to route to dashboard component page on successful login. I'm getting the output success on login but unable to route to dashboard page.

答:
As of the official release of Angular 4.0.0, all of my previously working Routes stopped working with an error that says a path cannot have a leading slash.

That means that my previous Angular 2.4.10 code that looked like this:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomerComponent } from './customer/customer.component';
import {PageNotFoundComponent} from './page-not-found/page-not-found.component';

const routes: Routes = [
  {
    path: '/customer',
    component: CustomerComponent
  }
  ,
  {
    path: '',
    pathMatch: 'full',
    redirectTo: '/customer'
  }
  ,
  {
    path: '**',
    component: PageNotFoundComponent
  }
];
</code>```

had to be changed to this to avoid the error:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomerComponent } from './customer/customer.component';
import {PageNotFoundComponent} from './page-not-found/page-not-found.component';

const routes: Routes = [
  {
    path: 'customer',
    component: CustomerComponent
  }
  ,
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'customer'
  }
  ,
  {
    path: '**',
    component: PageNotFoundComponent
  }
];
</code>```

To avoid using those nasty # in your routes, I would recommend changing your app.module.ts to specify that you want "plain paths" as shown below:

```<code>import { LocationStrategy, PathLocationStrategy} from '@angular/common';
</code>```

and the providers portion of your @NgModule declaration should add this line:

```<code>  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy}
  ],
</code>```

Title: Rounting in angular2 application

Body:
I am trying to route to dashboard page on clicking login button. But I'm unable to route to it. I have a login component and dashboard component. I want to route to dashboard page on successful login.
Login-routing module.ts

const routes: Routes = [
    {
                path: 'login',
                component: LoginComponent,
                data: {
                    title: 'Login Page'
                }
            },
            {
                path: 'register',
                component: RegisterComponent,
                data: {
                    title: 'Register Page'
                }
            }

];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class LoginRoutingModule {}

This is my login html file.

Login

Sign In to your account

                <input type="text" class="form-control" placeholder="Username">

                <input type="password" class="form-control" placeholder="Password">

                  <button (click)="OnTestLogin()">Login</button>

Output:{{postData}}

                  <button type="button" class="btn btn-link px-0">Forgot password?</button>

Sign up

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

                <button type="button" class="btn btn-primary active mt-1">Register Now!</button>

This is my app-routing.ts file

 export const routes: Routes = [
  {
    path: '',
    component: LoginComponent
  },
  {
    path: '#/dashboard',
    component: LoginComponent
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: {
      title: 'login'
    },

    children: [
      {
        path: 'login',
        loadChildren: './login/login.module#LoginModule'
      },
    ]
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

I am very new to angular and routing concepts. Please help me to route to dashboard component page on successful login. I'm getting the output success on login but unable to route to dashboard page.

Body:
As of the official release of Angular 4.0.0, all of my previously working Routes stopped working with an error that says a path cannot have a leading slash.

That means that my previous Angular 2.4.10 code that looked like this:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomerComponent } from './customer/customer.component';
import {PageNotFoundComponent} from './page-not-found/page-not-found.component';

const routes: Routes = [
  {
    path: '/customer',
    component: CustomerComponent
  }
  ,
  {
    path: '',
    pathMatch: 'full',
    redirectTo: '/customer'
  }
  ,
  {
    path: '**',
    component: PageNotFoundComponent
  }
];

had to be changed to this to avoid the error:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomerComponent } from './customer/customer.component';
import {PageNotFoundComponent} from './page-not-found/page-not-found.component';

const routes: Routes = [
  {
    path: 'customer',
    component: CustomerComponent
  }
  ,
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'customer'
  }
  ,
  {
    path: '**',
    component: PageNotFoundComponent
  }
];

To avoid using those nasty # in your routes, I would recommend changing your app.module.ts to specify that you want "plain paths" as shown below:

import { LocationStrategy, PathLocationStrategy} from '@angular/common';

and the providers portion of your @NgModule declaration should add this line:

  providers: [
    {provide: LocationStrategy, useClass: PathLocationStrategy}
  ],


问:
Passing PHP variable via AJAX to PHP variable in another DIV
I've been working on this for a whole day but think I'm getting confused on the various methods available while I learn AJAX.   I want my website to display the results of Python script. I can do that.

The problem is the script's results change randomly (it's the status of my garage door) and my site is clunky if the garage door's status changes.  Usually the user has to keep reloading the page to get a current status.  I'm trying to have the DIV that shows the status to update every 5 seconds thus showing the new status.

The Python script takes about 4 seconds to run, so I want to keep calling it as a function and pass it as a DIV on my site where I want to display the results.

If possible, one PHP file (index.php).  Here is the skeleton of what I'm looking to do.  My get_status function works, but I'm at a loss on the rest of it.

Thank you.

EDIT:   Code updated with minor tweaks spotted by the commenters.

```<code><html>
<body>

<?php
    function get_status(){
        $status = shell_exec('python /path/to/garage_door/myq-garage.py status');  //Equals either 'Open' or 'Closed'
        echo $status;
    }
?>

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
    var java_status = <?php echo json_encode(get_status) ?>;

    // I have no idea how to pass a variable from PHP thru javascript to PHP on the
    // same page.  Trying to pass on results of get_status function every 5 seconds.

    setInterval(function(){

        $.ajax({
            url: "index.php"
            type: "POST"
            dataType: "json"
            data: ({status: java_status}),
            success: function(data){
                $("#status_div").html(data);
            }
        })

    }, 5000);
</script>

<div id="status_div">
    <?php
        $new_status = json_decode(data);
    ?>

    // I have no idea how to get that status variable here.
    The Garage Door Status is:  <?php
        echo $new_status;
    ?>

</div>
</body>
</html>
</code>```

答:
To do this properly you have to have valid HTML and you don't need to send the PHP script any parameters. In addition, you need to separate your PHP from the rest of the code, else you will get back all of the markup in your AJAX response:

PHP Script - php_python.php

```<code><?php
    function get_status(){
        $status = shell_exec('python /path/to/garage_door/myq-garage.py status');  //Equals either 'Open' or 'Closed'
        echo $status;
    }
    get_status(); // execute the function
?>
</code>```

HTML Page - index.php (note the use of a document ready handler because the script is at the top of the page)

You also need to separate
        <script type="text/javascript">
        $(function(){ // you need a document ready handler if you put the script at the top of the page
            setInterval(function(){
                $.ajax({
                    url: "php_python.php",
                    type: "POST",
                    dataType: "text",
                    success: function(data){
                        $("#status_div").html('The Garage Door Status is: ' + data);
                    }
                })

            }, 5000);
        });
        </script>

```

If you're just learning jQuery's AJAX here are some basic tips for setting it up and trouble-shooting problems.

Body:
I've been working on this for a whole day but think I'm getting confused on the various methods available while I learn AJAX.   I want my website to display the results of Python script. I can do that.

The problem is the script's results change randomly (it's the status of my garage door) and my site is clunky if the garage door's status changes.  Usually the user has to keep reloading the page to get a current status.  I'm trying to have the DIV that shows the status to update every 5 seconds thus showing the new status.

The Python script takes about 4 seconds to run, so I want to keep calling it as a function and pass it as a DIV on my site where I want to display the results.

If possible, one PHP file (index.php).  Here is the skeleton of what I'm looking to do.  My get_status function works, but I'm at a loss on the rest of it.

Thank you.

EDIT:   Code updated with minor tweaks spotted by the commenters.

<?php
    function get_status(){
        $status = shell_exec('python /path/to/garage_door/myq-garage.py status');  //Equals either 'Open' or 'Closed'
        echo $status;
    }
?>

    <?php
        $new_status = json_decode(data);
    ?>

    // I have no idea how to get that status variable here.
    The Garage Door Status is:  <?php
        echo $new_status;
    ?>

Body:
To do this properly you have to have valid HTML and you don't need to send the PHP script any parameters. In addition, you need to separate your PHP from the rest of the code, else you will get back all of the markup in your AJAX response:

PHP Script - php_python.php

<?php
    function get_status(){
        $status = shell_exec('python /path/to/garage_door/myq-garage.py status');  //Equals either 'Open' or 'Closed'
        echo $status;
    }
    get_status(); // execute the function
?>

HTML Page - index.php (note the use of a document ready handler because the script is at the top of the page)

You also need to separate <script> tags, using one to load the jQuery library and another to describe your JavaScript functions.

<html>
    <head>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(function(){ // you need a document ready handler if you put the script at the top of the page
            setInterval(function(){
                $.ajax({
                    url: "php_python.php",
                    type: "POST",
                    dataType: "text",
                    success: function(data){
                        $("#status_div").html('The Garage Door Status is: ' + data);
                    }
                })

            }, 5000);
        });
        </script>
    </head>
    <body>
        <div id="status_div"></div>
    </body>
</html>

If you're just learning jQuery's AJAX here are some basic tips for setting it up and trouble-shooting problems.


问:
How to optimize algorithm to be able to determine 10 digit long prime numbers in java
I am currently new to java and programming in general, I'm working on an algorithm that determines the prime numbers in specific given ranges. Currently it works with six ranges which are numbers under 1 billion, when I tried to determine a 10 digit long number it failed. I am aware it needs to be changed to long since the digit is out of range but I am not sure how.

this is the part of the code where it determines if the umber is prime:

```<code>public ArrayList<Integer> getPrimes(int StartPos, int n) {
    ArrayList<Integer> primeList = new ArrayList<>();

    boolean[] primes = new boolean[n + 1];
    for (int i = StartPos; i < primes.length; i++) {
        primes[i] = true;
    }
    int num = 2;
    while (true) {
         for (int i = 2;; i++) {
              int m = num * i;
              if (m > n) {
                    break;
              } else {
                    primes[m] = false;
              }
         }
         boolean nextNum = false;
         for (int i = num + 1; i < n + 1; i++) {
              if (primes[i]) {
                    num = i;
                    nextNum = true;
                    break;
              }
         }
         if (!nextNum) {
              break;
         }
    }
    for (int i = 0; i < primes.length; i++) {
         if (primes[i]) {
            primeList.add(i);
         }
    }
    return primeList;
}
</code>```

I was checking online and found that perhaps I could do it with vectors but I have no experience with them and Also they are relatively slower than an Array.

答:
You might try BigInteger#isProbablePrime: https://www.tutorialspoint.com/java/math/biginteger_isprobableprime.htm</p>

```<code>import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

// Java 8
public class FindPrimes {
    public static void main(String[] args) {
        System.out.println("1 - 100 primes: " + findPrimes(1L, 99L));
        System.out.println("some 10-digit primes: " + findPrimes(99_999_999_999L, 20000L));
    }

    private static List<Long> findPrimes(long start, long quant) {
        return LongStream.rangeClosed(start, start + quant).filter(v ->
                BigInteger.valueOf(v).isProbablePrime(1)).boxed().collect(Collectors.toList());
    }
}
</code>```

Body:
I am currently new to java and programming in general, I'm working on an algorithm that determines the prime numbers in specific given ranges. Currently it works with six ranges which are numbers under 1 billion, when I tried to determine a 10 digit long number it failed. I am aware it needs to be changed to long since the digit is out of range but I am not sure how.

this is the part of the code where it determines if the umber is prime:

public ArrayList<Integer> getPrimes(int StartPos, int n) {
    ArrayList<Integer> primeList = new ArrayList<>();

    boolean[] primes = new boolean[n + 1];
    for (int i = StartPos; i < primes.length; i++) {
        primes[i] = true;
    }
    int num = 2;
    while (true) {
         for (int i = 2;; i++) {
              int m = num * i;
              if (m > n) {
                    break;
              } else {
                    primes[m] = false;
              }
         }
         boolean nextNum = false;
         for (int i = num + 1; i < n + 1; i++) {
              if (primes[i]) {
                    num = i;
                    nextNum = true;
                    break;
              }
         }
         if (!nextNum) {
              break;
         }
    }
    for (int i = 0; i < primes.length; i++) {
         if (primes[i]) {
            primeList.add(i);
         }
    }
    return primeList;
}

I was checking online and found that perhaps I could do it with vectors but I have no experience with them and Also they are relatively slower than an Array.

Body:
You might try BigInteger#isProbablePrime: https://www.tutorialspoint.com/java/math/biginteger_isprobableprime.htm

import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

// Java 8
public class FindPrimes {
    public static void main(String[] args) {
        System.out.println("1 - 100 primes: " + findPrimes(1L, 99L));
        System.out.println("some 10-digit primes: " + findPrimes(99_999_999_999L, 20000L));
    }

    private static List<Long> findPrimes(long start, long quant) {
        return LongStream.rangeClosed(start, start + quant).filter(v ->
                BigInteger.valueOf(v).isProbablePrime(1)).boxed().collect(Collectors.toList());
    }
}


问:
To assign var to name attribute of input tag using javascript
Here I am trying to store medicines given by doctor via html form.
By taking an input as text in cells of a dynamic table, I want to append some counter to the name tag of the input cell by using javascript but unable to do so.I want to create new input tag with attr name as prsc+counter-value
so can u please help me

```<code><table id="myTable">
  <tr>
    <td><input type="text" name="prsc0"></td>
  </tr>
  <tr>
    <td><input type="text" name="prsc1"></td>
  </tr>
  <tr>
    <td><input type="text" name="prsc2"></td>
  </tr>
</code>```

```<code><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>

<script>
 var counter=3;
 function myCreateFunction() {
     var table = document.getElementById("myTable");
     var row = table.insertRow(0);
     var cell1 = row.insertCell(0);
     counter=counter+1;
     var presc="prsc"+""+counter;
     cell1.innerHTML = '<input type="text" name=presc>';

 }

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow(0);
}
</script>
</code>```

答:
Your presc is a variable:

```<code>cell1.innerHTML = '<input type="text" name="' + presc + '">';
</code>```

or without creating it:

```<code>cell1.innerHTML = '<input type="text" name="presc' + counter + '">';
</code>```

JSBin

Body:
Here I am trying to store medicines given by doctor via html form.
By taking an input as text in cells of a dynamic table, I want to append some counter to the name tag of the input cell by using javascript but unable to do so.I want to create new input tag with attr name as prsc+counter-value
so can u please help me

    <input type="text" name="prsc0">

    <input type="text" name="prsc1">

    <input type="text" name="prsc2">

<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>

Body:
Your presc is a variable:

cell1.innerHTML = '<input type="text" name="' + presc + '">';

or without creating it:

cell1.innerHTML = '<input type="text" name="presc' + counter + '">';

JSBin


问:
void is not assignable to type value User Angular 2
I am calling a JSON file using rx/js Observable.

Service

```<code>constructor(private http: Http){

}

 getUserById():Observable<User[]> {

let url = this.mockData;
let header = new Headers({'Content-Type': 'application/json'});

return this.http.get(url)
    .map((res:Response) =><User[]>res.json())
    .do(data => console.log("User Data: "+JSON.stringify(data)))
    .catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};
</code>```

component:

```<code>    @Input() users: User[] = [];

        userTemp: User[] = [];

getUserById(userId){

        this._searchService.getUserById()
            .filter(users => {
                for(let user of users){
                    if(user.userName === userId){
                        this.userTemp.push(user);
                    }}});

        return this.userTemp;

    }
</code>```

under users => { says when I hover over it (Users: Users[]) => void is not assignable) => boolean.

I know there is a small detail I am missing but I am not sure where it is. Any advice would be greatly appreciated.

------------------------------update 1--------------------------
Trying this now but and it compiles but doesn't work.

```<code>this._searchService.getUserById()
            ._do(users => {
                for(let user of this.users){
                    if(user.id == userId){
                        this.userTemp.push(user);
                    }
                }
            });
</code>```

---------------------Update 2--------------------------
I got some advice from the posts below and now I am trying to do it like this, but it is rendering nothing and giving no errors.

In component:

```<code>@Input() users: IUser[] = [];
</code>```

Method being called in component:

```<code>case 'role':
          this.users = this.getUserByRole(this.role);
          console.log(this.role);
          break;
</code>```

method in component:

```<code> getUserByRole(role){

        this._searchService.getUsers()
            .subscribe(users => {
                for(let user of users) {
                    if(user.role == role){
                        this.users.push(user);
                    }}});

        return this.users;
    }
</code>```

Service method:

```<code>getUsers(): Observable<IUser[]> {
        let users = this.http
            .get(this.url)
            .map(res => res.json());
        return users;
    }
</code>```

In the console it will print whatever I put in the input box and I confirmed the url for the http call is valid.

I am trying to do it like this so all I need to do is change the http url to have headers and a real url later without have to change to much.

--------------Update 3----------------------

In the HTML I have:

```<code> <td>{{data.role | async}}</td>
</code>```

method in component:

```<code>getUserByRole(role){

        return this._searchService.getUsers()
            .map(data => {
                return data.filter((x:any) => x.role == role)
            });
    }
</code>```

Field:

```<code> @Input() users: Observable<IUser[]>;
</code>```

Calling the method:

```<code>case 'role':
         console.log(this.getUserByRole(this.role));
         this.users = this.getUserByRole(this.role);
         console.log(this.users);
         break;
</code>```

error:

```<code>Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
</code>```

In my searchService I am now looking at doing it this way but still not working:

```<code> findUserByRole(user: IUser) {
        return this.http.get(this.url)
            .map(res => res.json())
            .subscribe(
                data => {

                }
            );
    }
</code>```

答:
EDIT based on updates:

Not entirely sure, what you are trying to achieve with: {{data.role | async}}	, but if you want to filter users based on a specific role using async pipe would be to declare users as an Observable like you have. When you want to filter, have your switch statement (like you have):

case 'role':
      this.users = this.getUserByRole(this.role);
      break;
```

<p>and in this method you return an observable of the filtered array</p>

<pre class="lang-ts prettyprint-override"><code>getUserByRole(role){
    return this._searchService.getUsers()
        .map(data => {
            return data.filter((x:any) => x.role == role)
        });
}
</code>```

which you then can use together with async pipe, which displays the users which have the filtered values from your switch-case, whatever that filter value might be. In this case we have filtered above based on a role value.

```

<h2>DEMO</h2>

<p><strong>Update 2:</strong></p>

<p>Now seeing your JSON, the problem should be that your array is in an object named <code>data</code>. You want the array from the response, so you need to extract that array from the object, so change your mapping a bit:</p>

<pre class="lang-ts prettyprint-override"><code>return this.http.get(url)
    .map((res:Response) =><User[]>res.json().data) // here! Extract the array from the object "data"
    .do(data => console.log("User Data: "+JSON.stringify(data)))
    .catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};
</code>```

Original post:

filter actually does the filtering for you, you do not need to iterate the response. Unfortunately I do not see that you are able to return userTemp other than as an observable in your filtering. You actually have to subscribe to it and assign the values from the filter to your userTemp, the following will always return undefined as you are returning the array outside the callback:

getUserById(userId){
   this._searchService.getUserById()
     .map(users => {
        ......
     });
     return this.userTemp; // data has not been assigned yet, when you return it.
}
```

<p>This is just how it works. You need to do manipulate your data inside the callback! Here is some more info: How do I return the response from an Observable/http/async call in angular2?</p>

<p>But back to your code, You can map several times, so here you would use <code>map</code> together with <code>filter</code> to get the data you want:</p>

<pre class="lang-ts prettyprint-override"><code>getUserById(userId) {
 return this.service.getUsers()
   .map(data => {
     return data.filter((x:any) => x.userName == userId)
   });
}
</code>```

So this returnes an observable to where you need it.

But as said, AFAIK you cannot return the userTemp as a plain JS array.

Body:
I am calling a JSON file using rx/js Observable.

Service

constructor(private http: Http){

}

 getUserById():Observable<User[]> {

let url = this.mockData;
let header = new Headers({'Content-Type': 'application/json'});

return this.http.get(url)
    .map((res:Response) =><User[]>res.json())
    .do(data => console.log("User Data: "+JSON.stringify(data)))
    .catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};

component:

    @Input() users: User[] = [];

        userTemp: User[] = [];

getUserById(userId){

        this._searchService.getUserById()
            .filter(users => {
                for(let user of users){
                    if(user.userName === userId){
                        this.userTemp.push(user);
                    }}});

        return this.userTemp;

    }

under users => { says when I hover over it (Users: Users[]) => void is not assignable) => boolean.

I know there is a small detail I am missing but I am not sure where it is. Any advice would be greatly appreciated.

------------------------------update 1--------------------------
Trying this now but and it compiles but doesn't work.

this._searchService.getUserById()
            ._do(users => {
                for(let user of this.users){
                    if(user.id == userId){
                        this.userTemp.push(user);
                    }
                }
            });

---------------------Update 2--------------------------
I got some advice from the posts below and now I am trying to do it like this, but it is rendering nothing and giving no errors.

In component:

@Input() users: IUser[] = [];

Method being called in component:

case 'role':
          this.users = this.getUserByRole(this.role);
          console.log(this.role);
          break;

method in component:

 getUserByRole(role){

        this._searchService.getUsers()
            .subscribe(users => {
                for(let user of users) {
                    if(user.role == role){
                        this.users.push(user);
                    }}});

        return this.users;
    }

Service method:

getUsers(): Observable<IUser[]> {
        let users = this.http
            .get(this.url)
            .map(res => res.json());
        return users;
    }

In the console it will print whatever I put in the input box and I confirmed the url for the http call is valid.

I am trying to do it like this so all I need to do is change the http url to have headers and a real url later without have to change to much.

--------------Update 3----------------------

In the HTML I have:

 {{data.role | async}}

method in component:

getUserByRole(role){

        return this._searchService.getUsers()
            .map(data => {
                return data.filter((x:any) => x.role == role)
            });
    }

Field:

 @Input() users: Observable<IUser[]>;

Calling the method:

case 'role':
         console.log(this.getUserByRole(this.role));
         this.users = this.getUserByRole(this.role);
         console.log(this.users);
         break;

error:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

In my searchService I am now looking at doing it this way but still not working:

 findUserByRole(user: IUser) {
        return this.http.get(this.url)
            .map(res => res.json())
            .subscribe(
                data => {

                }
            );
    }

Body:
EDIT based on updates:

Not entirely sure, what you are trying to achieve with: <td>{{data.role | async}}</td>, but if you want to filter users based on a specific role using async pipe would be to declare users as an Observable like you have. When you want to filter, have your switch statement (like you have):

case 'role':
      this.users = this.getUserByRole(this.role);
      break;

and in this method you return an observable of the filtered array

getUserByRole(role){
    return this._searchService.getUsers()
        .map(data => {
            return data.filter((x:any) => x.role == role)
        });
}

which you then can use together with async pipe, which displays the users which have the filtered values from your switch-case, whatever that filter value might be. In this case we have filtered above based on a role value.

<div *ngFor="let user of users | async">

DEMO

Update 2:

Now seeing your JSON, the problem should be that your array is in an object named data. You want the array from the response, so you need to extract that array from the object, so change your mapping a bit:

return this.http.get(url)
    .map((res:Response) =><User[]>res.json().data) // here! Extract the array from the object "data"
    .do(data => console.log("User Data: "+JSON.stringify(data)))
    .catch((error:any) => Observable.throw(error) || "Mock Data Error get by role")
};

Original post:

filter actually does the filtering for you, you do not need to iterate the response. Unfortunately I do not see that you are able to return userTemp other than as an observable in your filtering. You actually have to subscribe to it and assign the values from the filter to your userTemp, the following will always return undefined as you are returning the array outside the callback:

getUserById(userId){
   this._searchService.getUserById()
     .map(users => {
        ......
     });
     return this.userTemp; // data has not been assigned yet, when you return it.
}

This is just how it works. You need to do manipulate your data inside the callback! Here is some more info: How do I return the response from an Observable/http/async call in angular2?

But back to your code, You can map several times, so here you would use map together with filter to get the data you want:

getUserById(userId) {
 return this.service.getUsers()
   .map(data => {
     return data.filter((x:any) => x.userName == userId)
   });
}

So this returnes an observable to where you need it.

But as said, AFAIK you cannot return the userTemp as a plain JS array.


问:
How do I paint Swing Components to a PDF file with iText?
I would like to print my Swing JComponent via iText to pdf.

```<code>JComponent com = new JPanel();
com.add( new JLabel("hello") );

PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream( dFile ) );
document.open( );

PdfContentByte cb = writer.getDirectContent( );
PdfTemplate tp = cb.createTemplate( pageImageableWidth, pageImageableHeight );
Graphics2D g2d = tp.createGraphics( pageImageableWidth, pageImageableHeight, new DefaultFontMapper( ) );
g2d.translate( pf.getImageableX( ), pf.getImageableY( ) );
g2d.scale( 0.4d, 0.4d );
com.paint( g2d );
cb.addTemplate( tp, 25, 200 );
g2d.dispose( );
</code>```

Unfortunately nothing is shown in the PDF file.
Do you know how to solve this problem?

答:
I have figured it out adding addNotify and validate helps.</p>

```
    com.addNotify( );
    com.validate( );
```

ContentLicense: CC BY-SA 2.5

Body:
I would like to print my Swing JComponent via iText to pdf.

JComponent com = new JPanel();
com.add( new JLabel("hello") );

PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream( dFile ) );
document.open( );

PdfContentByte cb = writer.getDirectContent( );
PdfTemplate tp = cb.createTemplate( pageImageableWidth, pageImageableHeight );
Graphics2D g2d = tp.createGraphics( pageImageableWidth, pageImageableHeight, new DefaultFontMapper( ) );
g2d.translate( pf.getImageableX( ), pf.getImageableY( ) );
g2d.scale( 0.4d, 0.4d );
com.paint( g2d );
cb.addTemplate( tp, 25, 200 );
g2d.dispose( );

Unfortunately nothing is shown in the PDF file.
Do you know how to solve this problem?

LastEditorDisplayName: mmyers

Body:
I have figured it out adding addNotify and validate helps.

    com.addNotify( );
    com.validate( );


问:
Destructure a map in another map?
I have the following data structure:

```<code>{:file #<File /foo.bar>, :resolution {:width 1280, :height 1024}}
</code>```

I would like to write a function that destructures the :resolution key into width and height symbols.  Something like

```<code>(defn to-directory-name [{{:keys [width height]}} wallpaper]
  (str width "x" height))
</code>```

Is something like that possible with destructuring?

Thanks.

答:
```<code>(defn to-directory-name [{{width :width height :height} :resolution}]
  (str width "x" height))
</code>```

Works for me.

Title: Destructure a map in another map?

Body:
I have the following data structure:

{:file #<File /foo.bar>, :resolution {:width 1280, :height 1024}}

I would like to write a function that destructures the :resolution key into width and height symbols.  Something like

(defn to-directory-name [{{:keys [width height]}} wallpaper]
  (str width "x" height))

Is something like that possible with destructuring?

Thanks.

Body:
(defn to-directory-name [{{width :width height :height} :resolution}]
  (str width "x" height))

Works for me.


问:
Rails click event not working
What I am trying to accomplish is that the user can select one of the items in the list group and ill be able to get returned which one it is along with making the item active in the group. I can't seem to get it working with jquery, or I am not doing this correctly.

Any feedback/help is appreciated.

Here is the HAML Code

```<code>= form_for @editor do |f|
  %body
   .container
    .list-group
      %a.list-group-item.active Hello
      %a.list-group-item Hey
      %a.list-group-item Greetings
</code>```

I made a js file called editors.js

```<code>$(document).ready(function() {
 $(".list-group-item").live('click', function(){
  $('.active').removeClass('active');
  $(this).addClass('active');
 });
});
</code>```

答:
$(document).on("click", ".list-group-item", function(){
  $(this).addClass('active')
    .siblings('.active')
    .removeClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  color: red;
}</code>```

  Hello
  Hey
  Greetings

  Bye
  Adios
  Auf Wiedersehen

```

This also makes it idempotent and turbolinks compatible by delegating from the document instead of attaching the handler to a DOM node.

Title: Rails click event not working

Body:
What I am trying to accomplish is that the user can select one of the items in the list group and ill be able to get returned which one it is along with making the item active in the group. I can't seem to get it working with jquery, or I am not doing this correctly.

Any feedback/help is appreciated.

Here is the HAML Code

= form_for @editor do |f|
  %body
   .container
    .list-group
      %a.list-group-item.active Hello
      %a.list-group-item Hey
      %a.list-group-item Greetings

I made a js file called editors.js

$(document).ready(function() {
 $(".list-group-item").live('click', function(){
  $('.active').removeClass('active');
  $(this).addClass('active');
 });
});

Body:
$(document).on("click", ".list-group-item", function(){
  $(this).addClass('active')
    .siblings('.active')
    .removeClass('active');
});

.active {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group">
  <a class="list-group-item active">Hello</a>
  <a class="list-group-item">Hey</a>
  <a class="list-group-item">Greetings</a>
</div>
<div class="list-group">
  <a class="list-group-item active">Bye</a>
  <a class="list-group-item">Adios</a>
  <a class="list-group-item">Auf Wiedersehen</a>
</div>

This also makes it idempotent and turbolinks compatible by delegating from the document instead of attaching the handler to a DOM node.


答:
Use the DOM API to create the input element instead of building an HTML string:</p>

```<code>var input = document.createElement('input');
input.name = 'prsc' + counter;
cell1.appendChild(input);
</code>```

Title: To assign var to name attribute of input tag using javascript

Body:
Use the DOM API to create the input element instead of building an HTML string:

var input = document.createElement('input');
input.name = 'prsc' + counter;
cell1.appendChild(input);


问:
Bit packing results in wrong value in Java
I have the following method in Java combine a set of four integer representation of bytes into a long.

```<code>public static long addBytesToInt(int x1, int x2, int x3, int x4) {
    return ((x4 << 24) | (x3 << 16) | (x2 << 8) | (x1 & 0xFF));
}
</code>```

But the problem is that if i would call this with for example the following values:

```<code>//1111 1111 0000 1111 0011 1100 0000 0011 = 4279188483
addBytesToInt(3, 60, 15, 255);
</code>```

It would return the wrong value.
I had to change to the following code for it to work as intended and I cannot figure out why:

```<code>public static long addBytesToInt(int x1, int x2, int x3, int x4) {
    long l = 0;

    l = (l << 8) + x4;
    l = (l << 8) + x3;
    l = (l << 8) + x2;
    l = (l << 8) + x1;

    return l;
}
</code>```

答:
The problem with ((x4 << 24) | (x3 << 16) | (x2 << 8) | (x1 & 0xFF)) has to do with the types of the operands.  Since x1 - x4 all have type int, the result of each shift operation also has type int.  Therefore, the result of each arithmetic or operation has type int, too.  When x4 has a value greater than 127, that final int result has its sign bit set, and therefore represents a negative number.  When that number is converted to long for return, the (negative) value is preserved.

Since the resulting long value has all its lower 32 bits set correctly, the easiest way to fix the problem is by masking off the 32 high-order bits.  I.e., apply an & 0xffffffffL operation to the current result.

The same does not apply to your working alternative.  Since variable l has type long, every operation produces a result of type long.  No overflow occurs, and the sign bit is never set.

Body:
I have the following method in Java combine a set of four integer representation of bytes into a long.

public static long addBytesToInt(int x1, int x2, int x3, int x4) {
    return ((x4 << 24) | (x3 << 16) | (x2 << 8) | (x1 & 0xFF));
}

But the problem is that if i would call this with for example the following values:

//1111 1111 0000 1111 0011 1100 0000 0011 = 4279188483
addBytesToInt(3, 60, 15, 255);

It would return the wrong value.
I had to change to the following code for it to work as intended and I cannot figure out why:

public static long addBytesToInt(int x1, int x2, int x3, int x4) {
    long l = 0;

    l = (l << 8) + x4;
    l = (l << 8) + x3;
    l = (l << 8) + x2;
    l = (l << 8) + x1;

    return l;
}


问:
Manipulating a dataset by separating variables
I have a data set that looks similar to the image shown below. Total, it is over a 1000 observations long. I want to create a new data frame that separates the single variable into 3 variables. Each variable is separated by a "+" in each observation, so it will need to be separated by using that as a factor.

答:
Here is a solution using data.table:

```<code>library(data.table)

# Data frame
df <- data.frame(MovieId.Title.Genres = c("yyyy+xxxx+wwww", "zzzz+aaaa+aaaa"))

# Data frame to data table.
df <- data.table(df)

# Split column into parts.
df[, c("MovieId", "Title", "Genres") := tstrsplit(MovieId.Title.Genres, "\\+")]

# Print data table
df
</code>```

Body:
Here is a solution using data.table:

library(data.table)

# Data frame
df <- data.frame(MovieId.Title.Genres = c("yyyy+xxxx+wwww", "zzzz+aaaa+aaaa"))

# Data frame to data table.
df <- data.table(df)

# Split column into parts.
df[, c("MovieId", "Title", "Genres") := tstrsplit(MovieId.Title.Genres, "\\+")]

# Print data table
df


问:
ImportError: Could not import the Python Imaging Library (PIL) required to load image files on tensorflow
I am doing a deep learning course on udacity. For the first assignment whenI tried to run the script which is below the problem 1 , I got this error. So I tried to uninstall PIL and pillow and then installed these individually but I didnot succeeded.
I need help guy. I am using tensorflow docker image with python notebook.

```<code># These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import scipy
import tarfile
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlretrieve
from six.moves import cPickle as pickle
# Config the matplotlib backend as plotting inline in IPython
%matplotlib inline

url = 'http://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None

def download_progress_hook(count, blockSize, totalSize):
    percent = int(count * blockSize * 100 / totalSize)

   if last_percent_reported != percent:
     if percent % 5 == 0:
  sys.stdout.write("%s%%" % percent)
  sys.stdout.flush()
else:
  sys.stdout.write(".")
  sys.stdout.flush()

last_percent_reported = percent
</code>```

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb

You can see the code here. I got error in the code block after problem 1
Error Image

I tried each and everything describe here in these two links or solutions:

Solution 1 on stackoverflow

Solution 2 on stackoverflow

Operating System:

using docker and tensorflow is installed in a container with IPython notebook.

The output from python -c "import tensorflow; print(tensorflow.version)".

0.11.0

答:
pip install pillow

Then replace
from IPython.display import display, Image
with
from IPython.display import display
from PIL import Image

Body:
I am doing a deep learning course on udacity. For the first assignment whenI tried to run the script which is below the problem 1 , I got this error. So I tried to uninstall PIL and pillow and then installed these individually but I didnot succeeded.
I need help guy. I am using tensorflow docker image with python notebook.

# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import scipy
import tarfile
from IPython.display import display, Image
from scipy import ndimage
from sklearn.linear_model import LogisticRegression
from six.moves.urllib.request import urlretrieve
from six.moves import cPickle as pickle
# Config the matplotlib backend as plotting inline in IPython
%matplotlib inline

url = 'http://commondatastorage.googleapis.com/books1000/'
last_percent_reported = None

def download_progress_hook(count, blockSize, totalSize):
    percent = int(count * blockSize * 100 / totalSize)

   if last_percent_reported != percent:
     if percent % 5 == 0:
  sys.stdout.write("%s%%" % percent)
  sys.stdout.flush()
else:
  sys.stdout.write(".")
  sys.stdout.flush()

last_percent_reported = percent

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/1_notmnist.ipynb

You can see the code here. I got error in the code block after problem 1
Error Image

I tried each and everything describe here in these two links or solutions:

Solution 1 on stackoverflow

Solution 2 on stackoverflow

Operating System:

using docker and tensorflow is installed in a container with IPython notebook.

The output from python -c "import tensorflow; print(tensorflow.version)".

0.11.0