问:
I am trying to implement a simple grid overlay Jquery Plugin
UPDATE: I decided to just download the demo off the website and build the site from it as a template and that works, I am not sure what I have done wrong but I still can't seem to fix it thanks for the help anyways.

I have got to the point where the button shows up that I need to click to show my overlay. However nothing happens when I click the button, it may be a path issue but I am certain that it is not. You can view the site live @ http://www.mrskitson.ca/revised there is a username(stack) and password(stack). I have been following a tutorial from http://www.badlydrawntoy.com/2009/04/21/960gs-grid-overlay-a-jquery-plugin/

Any help would be great!

Anders.

The button is located in the top left hand corner.

CODE BELOW

```<code><!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mr's Kitson.ca | KINDERGARTEN | A child's garden.</title>

<!-- 960 -->
    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/text.css" />
    <link rel="stylesheet" href="css/960.css" />
<!-- 960 ENDS -->

<!-- CSS -->
    <link rel="stylesheet" type="text/css" href="css/body.css" />
<!-- CSS ENDS -->

</head>
<body>
    <div class="container_12" >
        <h1 class="title">Mr's Kitson.ca | KINDERGARTEN | a child's garden.</h1>

            <img src="images/Mr's-Kitson.ca-(logo).png" alt="Mr's Kitson.ca | KINDERGARTEN | a child's garden." class="grid_4" />

    </div>
<!-- CONTAINER 12 ENDS-->

<!-- javascript 960 OVERLAY courtesy of www.badlydrawntoy.com -->
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.960grid-1.0.min.js"></script>
    <script type="text/javascript">
        /*<![CDATA[*/
    // onload
    $(function() {
        $("body").addGrid(12, {img_path: 'images/'});
    });
/*]]>*/
    </script>
<!-- OVERLAY ENDS-->
</body>
</html>
</code>```

答: I decided to just download the demo off the website and build the site from it as a template and that works, I am not sure what I have done wrong but I still can't seem to fix it thanks for the help anyways. The link is http://www.badlydrawntoy.com/2009/04/21/960gs-grid-overlay-a-jquery-plugin/</p>

Body:
UPDATE: I decided to just download the demo off the website and build the site from it as a template and that works, I am not sure what I have done wrong but I still can't seem to fix it thanks for the help anyways.

I have got to the point where the button shows up that I need to click to show my overlay. However nothing happens when I click the button, it may be a path issue but I am certain that it is not. You can view the site live @ http://www.mrskitson.ca/revised there is a username(stack) and password(stack). I have been following a tutorial from http://www.badlydrawntoy.com/2009/04/21/960gs-grid-overlay-a-jquery-plugin/

Any help would be great!

Anders.

The button is located in the top left hand corner.

CODE BELOW

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mr's Kitson.ca | KINDERGARTEN | A child's garden.</title>

    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/text.css" />
    <link rel="stylesheet" href="css/960.css" />

    <link rel="stylesheet" type="text/css" href="css/body.css" />

Mr's Kitson.ca | KINDERGARTEN | a child's garden.


来源: stackexchange

问:
If isset ID inside array, get values from defined ID in same array?
If user access my page using an ID: mysite.com/page.php?id=3, I want the PHP to check if ID is defined in an array, if true, it returns in page multiple user information from same array according to their defined IDs.

My code:

```<code>$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];

if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
     $name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
     $phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
    }

echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.
</code>```

It's only a base, I know it don't works, any help with the code? thanks in advance.

答:
You can use this function for any depth of the associated array. Just constraint to this function is that the key value would not be repeat any where in array.</p>

```<code><?php
function assoc_in_array($array, $key, $key_value){
      $within_array = false;
      foreach( $array as $k=>$v ){
          if( is_array($v) ){
              $within_array = assoc_in_array($v, $key, $key_value);
              if( $within_array == true ){
                    break;
              }
          } else {
                if( $v == $key_value && $k == $key ){
                    $within_array = true;
                    break;
                }
          }
      }
      return $within_array;
}
$test = [
            ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
            ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ];
var_dump(assoc_in_array($test, 'id', '3'));
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If user access my page using an ID: mysite.com/page.php?id=3, I want the PHP to check if ID is defined in an array, if true, it returns in page multiple user information from same array according to their defined IDs.

My code:

$userinfo = [
        ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
        ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ['id' => 1, 'name' => 'username1', 'phone' => '1111']
    ];

if (isset($_GET['id']) && isset($userinfo[$_GET['id']])) {
     $name = $userinfo[$_GET['name']]; // If I access PHP with '?id=3' wanna 'username3'.
     $phone = $userinfo[$_GET['phone']]; // It stores id 3 user phone: '3333'
    }

echo $name; // It returns 'name' from array.
echo $phone; // It returns 'phone' from array.

It's only a base, I know it don't works, any help with the code? thanks in advance.

Body:
You can use this function for any depth of the associated array. Just constraint to this function is that the key value would not be repeat any where in array.

<?php
function assoc_in_array($array, $key, $key_value){
      $within_array = false;
      foreach( $array as $k=>$v ){
          if( is_array($v) ){
              $within_array = assoc_in_array($v, $key, $key_value);
              if( $within_array == true ){
                    break;
              }
          } else {
                if( $v == $key_value && $k == $key ){
                    $within_array = true;
                    break;
                }
          }
      }
      return $within_array;
}
$test = [
            ['id' => 3, 'name' => 'username3', 'phone' => '3333'],
            ['id' => 2, 'name' => 'username2', 'phone' => '2222'],
        ];
var_dump(assoc_in_array($test, 'id', '3'));
?>


问:
How to save Outlook mails as .msg file with categories and other details?
It is easy to save emails in Outlook VBA with MailItem.SaveAs

But I don't see any option to save additional details like i.e. the Author and Categories.

The 3rd party program MessageSave allows to save mails with Categories and Author in .msg format. In Windows Explorer the columns Author and Categories show the same information like in Outlook.

Does anybody know how to save messages using Outlook VBA including these additional information?

I bought MessageSave and it's a good program but they don't allow their save function to be used in VBA. The only workaround is to let MessageSave save messages when they "arrive" in a specific folder. If necessary I can use this function but this is just a workaround.

Here is a sample how the emails saved with MessageSave are shown in Windows Explorer:

答:
here is a more usable script

it has no error checking

no check for duplicate message names

no check for illegal filenames (except for ":" character)

just select a bunch of emails in any outlook folder and run this

```<code>' make sure you have a reference to "DSO OLE Document Properties Reader"

Sub extendedProperties()

    Dim msg As mailItem
    Dim objFile As OleDocumentProperties

'   Set objFile = CreateObject("DSOFile.OleDocumentProperties")
    Set objFile = New OleDocumentProperties

    Dim fileName As String
    Dim subjectText As String

    ' !!!!!!!! select a bunch of messages before running this !!!!!!!!

    For Each msg In ActiveExplorer.Selection

        subjectText = Replace(msg.Subject, ":", "_")   ' get rid of illegal file name character (there are others)

        ' adjust the destination folder for your liking
        fileName = "C:\Users\js\Desktop\testFiles\" & subjectText & ".msg"

        Debug.Print fileName

        msg.SaveAs fileName

        objFile.Open fileName
        objFile.SummaryProperties.Subject = "My Subject"
        'objFile.Save
        objFile.Close True     ' save and close   !!!!! duplicate filenames get overwritten !!!!!

'   stop                       ' uncomment this line and the code will stop. press F5 to run, F8 to single-step

    Next msg

    Set msg = Nothing
    Set objFile = Nothing

End Sub
</code>```

Body:
here is a more usable script

it has no error checking

no check for duplicate message names

no check for illegal filenames (except for ":" character)

just select a bunch of emails in any outlook folder and run this

' make sure you have a reference to "DSO OLE Document Properties Reader"

Sub extendedProperties()

    Dim msg As mailItem
    Dim objFile As OleDocumentProperties

'   Set objFile = CreateObject("DSOFile.OleDocumentProperties")
    Set objFile = New OleDocumentProperties

    Dim fileName As String
    Dim subjectText As String

    ' !!!!!!!! select a bunch of messages before running this !!!!!!!!

    For Each msg In ActiveExplorer.Selection

        subjectText = Replace(msg.Subject, ":", "_")   ' get rid of illegal file name character (there are others)

        ' adjust the destination folder for your liking
        fileName = "C:\Users\js\Desktop\testFiles\" & subjectText & ".msg"

        Debug.Print fileName

        msg.SaveAs fileName

        objFile.Open fileName
        objFile.SummaryProperties.Subject = "My Subject"
        'objFile.Save
        objFile.Close True     ' save and close   !!!!! duplicate filenames get overwritten !!!!!

'   stop                       ' uncomment this line and the code will stop. press F5 to run, F8 to single-step

    Next msg

    Set msg = Nothing
    Set objFile = Nothing

End Sub


问:
Angular4: jQuery and angular2-materialize not working after route navigation
Have created an angular 4 project with angular-cli. imported css and js in angular-cli.json file.

```<code>"styles": [
    "../node_modules/materialize-css/dist/css/materialize.css",
    "styles.css"
],
"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/hammerjs/hammer.js",
    "../node_modules/materialize-css/dist/js/materialize.js",
    "../src/assets/js/init.js"
],
</code>```

init.js has below functions

```<code>(function($) {
    $(function() {
        $('.slider').slider();
        $('.button-collapse').sideNav();
        $('.carousel').carousel();
        // $('.carousel.carousel-slider').carousel({fullWidth: true});
        $('.carousel').carousel({
            dist: 0,
            shift: 0,
            padding: 20,
        });

    }); // end of document ready
})(jQuery);
</code>```

imported MaterializeModule  in app.module.ts
import { MaterializeModule } from 'angular2-materialize';

Slider works as expected when we land page first time or when we refresh.

Problem: when we navigate using router-link then page navigates correctly but javascript functions are not getting called.

routing from home page Blog

I tried: `    blog.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { MaterializeModule } from 'angular2-materialize';

import * as $ from 'jquery';

import * as Materialize from 'materialize-css';

declare let Materialize : any;

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.css']
})
export class BlogComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    Materialize('.slider').slider();
  }

}
</code>```

`
Error:
getting error :
ERROR TypeError: a.addEventListener is not a function

```<code>at http://localhost:4200/vendor.bundle.js:15611:765
at Array.forEach (native)
</code>```

答:
Solved it after a lot of iteration.
Solution:
If you are importing the js in angular-cli.json then no need to import the same again in components. Results in duplication and you will get weird javascript exceptions which will mislead.
Just declare them and use it like the code below.

```<code>declare let $ : any;
</code>```

additionally in Onngint() {} method call the javascript function once again. This has to be called in each and every component this function will be used.
example below:

```<code>    ngOnInit() {
        $(function(){
            $('.button-collapse').sideNav();
        }); // end of document ready
    }
</code>```

Remember to check document ready. Not checking resulted in early execution of scripts.

Body:
Have created an angular 4 project with angular-cli. imported css and js in angular-cli.json file.

"styles": [
    "../node_modules/materialize-css/dist/css/materialize.css",
    "styles.css"
],
"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/hammerjs/hammer.js",
    "../node_modules/materialize-css/dist/js/materialize.js",
    "../src/assets/js/init.js"
],

init.js has below functions

(function($) {
    $(function() {
        $('.slider').slider();
        $('.button-collapse').sideNav();
        $('.carousel').carousel();
        // $('.carousel.carousel-slider').carousel({fullWidth: true});
        $('.carousel').carousel({
            dist: 0,
            shift: 0,
            padding: 20,
        });

    }); // end of document ready
})(jQuery);

imported MaterializeModule  in app.module.ts
import { MaterializeModule } from 'angular2-materialize';

Slider works as expected when we land page first time or when we refresh.

Problem: when we navigate using router-link then page navigates correctly but javascript functions are not getting called.

routing from home page Blog

I tried: `    blog.component.ts

import { Component, OnInit } from '@angular/core';
import { MaterializeModule } from 'angular2-materialize';

import * as $ from 'jquery';

import * as Materialize from 'materialize-css';

declare let Materialize : any;

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.css']
})
export class BlogComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    Materialize('.slider').slider();
  }

}

`
Error:
getting error :
ERROR TypeError: a.addEventListener is not a function

at http://localhost:4200/vendor.bundle.js:15611:765
at Array.forEach (native)

Body:
Solved it after a lot of iteration.
Solution:
If you are importing the js in angular-cli.json then no need to import the same again in components. Results in duplication and you will get weird javascript exceptions which will mislead.
Just declare them and use it like the code below.

declare let $ : any;

additionally in Onngint() {} method call the javascript function once again. This has to be called in each and every component this function will be used.
example below:

    ngOnInit() {
        $(function(){
            $('.button-collapse').sideNav();
        }); // end of document ready
    }

Remember to check document ready. Not checking resulted in early execution of scripts.


问:
compare column of two rows of same table in mysql
I have a table name player_history containing history of player. in this table having column player_id, Final_position,meeting_code,race_no and beaten_time. If a player stood a first or second position the time will be same there are meeting code one day and in each meeting code there are maximum 10 races.

I want to select those records where 1st and second position beaten time are not same.

```<code>player_id Meeting_Code race_no final_position beaten_time
  1         0001          1         1             2
  2         0001          1         2             2
  1         0001          2         1             5
  2         0001          2         2             6
... so on
</code>```

Output should be:

```<code>player_id Meeting_Code race_no final_position beaten_time
  1         0001          2         1             5
  2         0001          2         2             6
</code>```

Also if it is not correct I want to update records of first position only.

答:
Try It:</p>

```<code>select b.player_id,b.meeting_code,b.race_no,b.final_position,b.beaten_time
from player_history a,player_history b
where  a.race_no = b.race_no and a.beaten_time != b.beaten_time;
</code>```

Body:
I have a table name player_history containing history of player. in this table having column player_id, Final_position,meeting_code,race_no and beaten_time. If a player stood a first or second position the time will be same there are meeting code one day and in each meeting code there are maximum 10 races.

I want to select those records where 1st and second position beaten time are not same.

player_id Meeting_Code race_no final_position beaten_time
  1         0001          1         1             2
  2         0001          1         2             2
  1         0001          2         1             5
  2         0001          2         2             6
... so on

Output should be:

player_id Meeting_Code race_no final_position beaten_time
  1         0001          2         1             5
  2         0001          2         2             6

Also if it is not correct I want to update records of first position only.

Body:
Try It:

select b.player_id,b.meeting_code,b.race_no,b.final_position,b.beaten_time
from player_history a,player_history b
where  a.race_no = b.race_no and a.beaten_time != b.beaten_time;


问:
How to extract an object tag from a text
Hi
I've created a system that adds articles in the database, the user can embed youtube or dailymotion or simple flash into the text area. In the home page, I've inserted a slideshow that slides new feed with image, I've writen a simple condition if that checks if the text contains an embeded video using:

```<code>if (ereg('<object>',$text){}
</code>```

I just want to insert the video(object element in general) in the slide show in case there's an object in the text. in other words I want to extract what's between <object> and </object>

thank you

答:
I'm not sure about the slideshow part or if you are also trying to modify the content. But for the extraction part there's two options. You can use a simple-minded regular expression like:

```<code>preg_match("#<object[^>]*>(.+?)</object>#ims", $text, $matches);
print $matches[1];
</code>```

Or a more reliable HTML parser with a readable API like phpQuery or QueryPath:

```<code>print qp($text)->find("object")->text();
</code>```

The latter would also allow you to extract attributes more easily.

ContentLicense: CC BY-SA 2.5

Body:
Hi
I've created a system that adds articles in the database, the user can embed youtube or dailymotion or simple flash into the text area. In the home page, I've inserted a slideshow that slides new feed with image, I've writen a simple condition if that checks if the text contains an embeded video using:

if (ereg('<object>',$text){}

I just want to insert the video(object element in general) in the slide show in case there's an object in the text. in other words I want to extract what's between <object> and </object>

thank you

Body:
I'm not sure about the slideshow part or if you are also trying to modify the content. But for the extraction part there's two options. You can use a simple-minded regular expression like:

preg_match("#<object[^>]*>(.+?)</object>#ims", $text, $matches);
print $matches[1];

Or a more reliable HTML parser with a readable API like phpQuery or QueryPath:

print qp($text)->find("object")->text();

The latter would also allow you to extract attributes more easily.


问:
Get only latest data from last week and past last week and sum some column
Get only latest data from last week and sum some column

I made an example with dat, the actual result and the expected.

http://rextester.com/HMB12638

```<code>--Taking an example kind of like this..

--      user    contact         barcode date                in  out dif
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 80
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 90
-- 3    USER2   Guillermo Tole  987654  13.06.2017 05:27:00 400 380 20
-- 4    USER2   Guillermo Tole  281460  12.06.2017 05:26:00 230 190 40
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 6    USER3   Juan Rulfo      123456  12.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
-- 8    USER3   Pepito Marquez  346234  14.06.2017 05:37:00 450 300 150
</code>```

This is my actual result using  this query.

First. Create a table and keep the IDs you want the info

```<code>with tabla as (
    SELECT distinct on( barcode) barcode  as barcode, id, date
    from table1 as tabla
    where date_trunc('day', date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and date >  '2017-06-25'::date - (interval '2 weeks')::interval
    order by barcode, date desc
)
</code>```

Then make the query using inner join on the previously created table

```<code>select user, contact, t1.barcode, t1.date, "in", out, dif ,  sum("in" - out) over (partition by contact order by t1.barcode)
    from table1 t1
      inner join tabla on tabla.id = t1.id
    where date_trunc('day', t1.date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and t1.date >  '2017-06-25'::date - (interval '2 weeks')::interval
 order by contact, barcode, date desc
 -- PD, "in" is a reserved word, i have to keep it with commas
</code>```

This is the result i get using previous query.

```<code>--      user    contact         barcode date                in  out sum
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
</code>```

This is the expected result, sometimes there won't be data from 2 weeks ago and do will be data from last week, in that case it can be null or empty the this week, and this also can happen viceversa (from last week).

```<code>    --                                      | 2 weeks ago-----------------| | last week ------------------|
    --      user    contact         barcode date                in  out sum date                in  out sum
    -- 1    USER2   Guillermo Tole  987654  8.06.2017 05:27:00  500 420 170 15.06.2017 05:27:00 600 550 100
    -- 2    USER2   Guillermo Tole  281460  6.06.2017 05:36:00  310 220 170 16.06.2017 05:27:00 400 350 100
    -- 5    USER3   Juan Rulfo      123456  9.06.2017 05:37:00  450 300 150 14.06.2017 05:27:00 650 350 300
    -- 7    USER3   Pepito Marquez  346234  7.06.2017 05:37:00  600 360 240 15.06.2017 05:27:00 750 500 250
</code>```

答:
This is a variant of an earlier answer which now works (correctly I believe) by including barcode into the OVER() clause of LAG() and ROW_NUMBER().

```<code>select "user", "contact", "barcode", "prev2date", "prev2in", "prev2out","prev2dif", "prev1date", "prev1in", "prev1out","prev1dif"
     , sum("prev1in"-"prev1out") over(partition by "user", "contact") as "sum"
from (
    select "user", "contact", "barcode", "date", "in", "out","dif"
    , lag("date",2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2date
    , lag("in"  ,2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2in
    , lag("out" ,2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2out
    , lag("dif" ,2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2dif
    , lag("date",1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1date
    , lag("in"  ,1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1in
    , lag("out" ,1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1out
    , lag("dif" ,1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1dif
    , row_number()  over(partition by "user", "contact", "barcode" order by "date" DESC) rn
    from "table1"
    ) d
where rn = 1 and prev1dif is not null
order by 1,2,4 DESC
</code>```

From your sample data, using the query above I got this result:

```<code>+----+-------+----------------+---------+---------------------+---------+----------+----------+---------------------+---------+----------+----------+-----+
|    | user  |    contact     | barcode |      prev2date      | prev2in | prev2out | prev2dif |      prev1date      | prev1in | prev1out | prev1dif | sum |
+----+-------+----------------+---------+---------------------+---------+----------+----------+---------------------+---------+----------+----------+-----+
|  1 | USER2 | Guillermo Tole |  987654 | 23.06.2017 05:27:00 | 700     | 690      | 10       | 28.06.2017 05:27:00 |     800 |      760 |       40 | 120 |
|  2 | USER2 | Guillermo Tole |  281460 | 15.06.2017 05:36:00 | 310     | 220      | 90       | 20.06.2017 09:37:00 |     490 |      410 |       80 | 120 |
|  3 | USER3 | Juan Rulfo     |  123456 | NULL                | NULL    | NULL     | NULL     | 12.06.2017 05:37:00 |     450 |      300 |      150 | 150 |
|  4 | USER3 | Pepito Marquez |  346234 | 27.06.2017 05:37:00 | 900     | 690      | 210      | 30.06.2017 05:37:00 |    1050 |      900 |      150 | 150 |
+----+-------+----------------+---------+---------------------+---------+----------+----------+---------------------+---------+----------+----------+-----+
</code>```

http://rextester.com/WODBE20956

Body:
Get only latest data from last week and sum some column

I made an example with dat, the actual result and the expected.

http://rextester.com/HMB12638

--Taking an example kind of like this..

--      user    contact         barcode date                in  out dif
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 80
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 90
-- 3    USER2   Guillermo Tole  987654  13.06.2017 05:27:00 400 380 20
-- 4    USER2   Guillermo Tole  281460  12.06.2017 05:26:00 230 190 40
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 6    USER3   Juan Rulfo      123456  12.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240
-- 8    USER3   Pepito Marquez  346234  14.06.2017 05:37:00 450 300 150

This is my actual result using  this query.

First. Create a table and keep the IDs you want the info

with tabla as (
    SELECT distinct on( barcode) barcode  as barcode, id, date
    from table1 as tabla
    where date_trunc('day', date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and date >  '2017-06-25'::date - (interval '2 weeks')::interval
    order by barcode, date desc
)

Then make the query using inner join on the previously created table

select user, contact, t1.barcode, t1.date, "in", out, dif ,  sum("in" - out) over (partition by contact order by t1.barcode)
    from table1 t1
      inner join tabla on tabla.id = t1.id
    where date_trunc('day', t1.date) <= '2017-06-25' ::date - (interval '1 week')::interval
 and t1.date >  '2017-06-25'::date - (interval '2 weeks')::interval
 order by contact, barcode, date desc
 -- PD, "in" is a reserved word, i have to keep it with commas

This is the result i get using previous query.

--      user    contact         barcode date                in  out sum
-- 1    USER2   Guillermo Tole  987654  16.06.2017 05:27:00 500 420 170 (80 + 90)
-- 2    USER2   Guillermo Tole  281460  15.06.2017 05:36:00 310 220 170 (80 + 90)
-- 5    USER3   Juan Rulfo      123456  15.06.2017 05:37:00 450 300 150
-- 7    USER3   Pepito Marquez  346234  15.06.2017 05:37:00 600 360 240

This is the expected result, sometimes there won't be data from 2 weeks ago and do will be data from last week, in that case it can be null or empty the this week, and this also can happen viceversa (from last week).

    --                                      | 2 weeks ago-----------------| | last week ------------------|
    --      user    contact         barcode date                in  out sum date                in  out sum
    -- 1    USER2   Guillermo Tole  987654  8.06.2017 05:27:00  500 420 170 15.06.2017 05:27:00 600 550 100
    -- 2    USER2   Guillermo Tole  281460  6.06.2017 05:36:00  310 220 170 16.06.2017 05:27:00 400 350 100
    -- 5    USER3   Juan Rulfo      123456  9.06.2017 05:37:00  450 300 150 14.06.2017 05:27:00 650 350 300
    -- 7    USER3   Pepito Marquez  346234  7.06.2017 05:37:00  600 360 240 15.06.2017 05:27:00 750 500 250

Body:
This is a variant of an earlier answer which now works (correctly I believe) by including barcode into the OVER() clause of LAG() and ROW_NUMBER().

select "user", "contact", "barcode", "prev2date", "prev2in", "prev2out","prev2dif", "prev1date", "prev1in", "prev1out","prev1dif"
     , sum("prev1in"-"prev1out") over(partition by "user", "contact") as "sum"
from (
    select "user", "contact", "barcode", "date", "in", "out","dif"
    , lag("date",2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2date
    , lag("in"  ,2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2in
    , lag("out" ,2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2out
    , lag("dif" ,2) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev2dif
    , lag("date",1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1date
    , lag("in"  ,1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1in
    , lag("out" ,1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1out
    , lag("dif" ,1) over(partition by "user", "contact", "barcode" order by "date" ASC)  prev1dif
    , row_number()  over(partition by "user", "contact", "barcode" order by "date" DESC) rn
    from "table1"
    ) d
where rn = 1 and prev1dif is not null
order by 1,2,4 DESC

From your sample data, using the query above I got this result:

+----+-------+----------------+---------+---------------------+---------+----------+----------+---------------------+---------+----------+----------+-----+
|    | user  |    contact     | barcode |      prev2date      | prev2in | prev2out | prev2dif |      prev1date      | prev1in | prev1out | prev1dif | sum |
+----+-------+----------------+---------+---------------------+---------+----------+----------+---------------------+---------+----------+----------+-----+
|  1 | USER2 | Guillermo Tole |  987654 | 23.06.2017 05:27:00 | 700     | 690      | 10       | 28.06.2017 05:27:00 |     800 |      760 |       40 | 120 |
|  2 | USER2 | Guillermo Tole |  281460 | 15.06.2017 05:36:00 | 310     | 220      | 90       | 20.06.2017 09:37:00 |     490 |      410 |       80 | 120 |
|  3 | USER3 | Juan Rulfo     |  123456 | NULL                | NULL    | NULL     | NULL     | 12.06.2017 05:37:00 |     450 |      300 |      150 | 150 |
|  4 | USER3 | Pepito Marquez |  346234 | 27.06.2017 05:37:00 | 900     | 690      | 210      | 30.06.2017 05:37:00 |    1050 |      900 |      150 | 150 |
+----+-------+----------------+---------+---------------------+---------+----------+----------+---------------------+---------+----------+----------+-----+

http://rextester.com/WODBE20956


问:
How do you assign an action to a button in JScript?
just started learning Js for few days and i've been trying to make a button that when you click it, it would change the text of the 0 xp to 1, 2, 3,etc.. but im struggling to do so. Here is my code, any help would be appreciated.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementsById("singlebutton");

credits.onclick = change() {
  document.getElementsByClassName("money").innerHTML = "i++" + " xp";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title></title>
  <link rel="stylesheet" href="style.css">
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <!-- Optional theme -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>

<body>
  <header>
    <h1>Blank Page</h1>
  </header>
  <main>
    <form>
      <div class="col-md-4 text-center">
        <p><button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button></p>
      </div>
      <div class="credit text-center">
        <div class="earn">
          <p>You have earned: </p>
        </div>
        <div class="money">0 xp</div>
      </div>
    </form>
  </main>
  <script src="main.js"></script>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>

</html></code>```

答:
Here, I have changed your code a bit.

Kudos to you for not mixing JS in your HTML code. I noticed there are some error in your code.

JavaScript don't have getElementsById(), it has getElementById().

To attach an event to an element use
HTMLobject.addEventListener(eventname, myScript).

Declare and
initialise the variable i.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementById("singlebutton");
var i = 0;

button.addEventListener('click',function () {
    credits[0].innerHTML = (++i) + " xp";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-4 text-center">
    <p><button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button>
    </p>
</div>

<div class="credit text-center">
    <div class="earn"><p>You have earned: </p></div>
    <div class="money">0 xp</div>
</div></code>```

Body:
just started learning Js for few days and i've been trying to make a button that when you click it, it would change the text of the 0 xp to 1, 2, 3,etc.. but im struggling to do so. Here is my code, any help would be appreciated.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementsById("singlebutton");

credits.onclick = change() {
  document.getElementsByClassName("money").innerHTML = "i++" + " xp";
}

<!DOCTYPE html>

  <title></title>
  <link rel="stylesheet" href="style.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Blank Page

    <form>

<button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button>

You have earned:

0 xp

    </form>

Body:
Here, I have changed your code a bit.

Kudos to you for not mixing JS in your HTML code. I noticed there are some error in your code.

JavaScript don't have getElementsById(), it has getElementById().

To attach an event to an element use
HTMLobject.addEventListener(eventname, myScript).

Declare and
initialise the variable i.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementById("singlebutton");
var i = 0;

button.addEventListener('click',function () {
    credits[0].innerHTML = (++i) + " xp";
});

<div class="col-md-4 text-center">
    <p><button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button>
    </p>
</div>

<div class="credit text-center">
    <div class="earn"><p>You have earned: </p></div>
    <div class="money">0 xp</div>
</div>


问:
Phonegap/cordova- Ios Device UUID not unique when user uninstall and re-install the app
The issue is with ios device when user uninstall and reinstall the app it will generate new UUID which is not unique.

On an android device we can get a unique device UUID.

答:
Here i got the trick for it.It worked for me.

Use Keychain plugin

The Keychain plugin allows you to securely store data in the iOS
  Keychain.

You can set, get, and remove values in the Keychain using this plugin.
  Items stored in the Keychain survive uninstalls and reinstalls of your
  app. The data is not available to any other app, unless it's signed
  with the same provisioning profile. When a user backs up iOS data, the
  keychain data is backed up, but the secrets in the keychain remain
  encrypted in the backup.

The Keychain stores data as key-value pairs. You need to set and get
  these pairs using the same servicename. If you set an existing key
  with a new value, the old value will be overwritten

Phonegap Build user just use this plugin into config.xml file

```<code> <plugin name="cordova-keychain" source="npm" />
</code>```

How to use it in App?

```<code>// prepare some variables
var servicename = 'MyAppUUID';
var key = 'MyApp';
var value = 'Your UUID'; // Set your Device Id here.

// prepare the callback functions
function onSuccess (msg) {alert(msg)};
function onError (msg) {alert(msg)};

// store your password in the Keychain
new Keychain().setForKey(onSuccess, onError, key, servicename, value);

// get your password from the Keychain
new Keychain().getForKey(onSuccess, onError, key, servicename);

// remove your password from the Keychain
new Keychain().removeForKey(onSuccess, onError, key, servicename);
</code>```

Body:
Here i got the trick for it.It worked for me.

Use Keychain plugin

The Keychain plugin allows you to securely store data in the iOS
  Keychain.

You can set, get, and remove values in the Keychain using this plugin.
  Items stored in the Keychain survive uninstalls and reinstalls of your
  app. The data is not available to any other app, unless it's signed
  with the same provisioning profile. When a user backs up iOS data, the
  keychain data is backed up, but the secrets in the keychain remain
  encrypted in the backup.

The Keychain stores data as key-value pairs. You need to set and get
  these pairs using the same servicename. If you set an existing key
  with a new value, the old value will be overwritten

Phonegap Build user just use this plugin into config.xml file

 <plugin name="cordova-keychain" source="npm" />

How to use it in App?

// prepare some variables
var servicename = 'MyAppUUID';
var key = 'MyApp';
var value = 'Your UUID'; // Set your Device Id here.

// prepare the callback functions
function onSuccess (msg) {alert(msg)};
function onError (msg) {alert(msg)};

// store your password in the Keychain
new Keychain().setForKey(onSuccess, onError, key, servicename, value);

// get your password from the Keychain
new Keychain().getForKey(onSuccess, onError, key, servicename);

// remove your password from the Keychain
new Keychain().removeForKey(onSuccess, onError, key, servicename);


问:
Mongoose Schema extend timestamp to have new properties (username)
I´m using MongoDB and mongoose for a project that needs to track data creation and changes. The requirements are that I need to keep track of records creation and changes including the date/time and the application user (not the OS user) who did it.

I´ve seen the mongoose timestamps option that would solve my date/time issue, but is there a way to extend it to include extra properties, where I´m gonna be adding the application username ?

If not, is there a single place where I can write a function that will be called on every creation/update so that I can include/modify these fields ?

Today I´m insering these properties on every model like below, but I would like to move all of them to a single place.

```<code>var companySchema = mongoose.Schema({

    name: {
        type: String,
        index: true
    },
    phone: {
        type: String
    },
    deleted: {
        type: Boolean
    },
    createdAt: {
        type: Date
    },
    createdBy: {
        type: String
    },
    updatedAt: {
        type: Date
    },
    updatedBy: {
        type: String
    }
});
</code>```

How would be the best approach for it ?

答:
I would approach it by creating two models, one for each Data created, one for each Data Changes.

Data created which will have 6 fields one is createdBy, createdAt, and one will be a field with an array of reference id of Data Changes, deletedBy, deletedAt, deletedFlag.

Data Changes will have fields dataID which will have reference id of data created, updatedBy and updatedAt.

This way it will be easy to keep track of when it was created when it was changes and when it was deleted.

PS: You can remove either of Array in Data created model or dataID ref id in Data Change mode, it was just me being extra cautious while binding.

Body:
I´m using MongoDB and mongoose for a project that needs to track data creation and changes. The requirements are that I need to keep track of records creation and changes including the date/time and the application user (not the OS user) who did it.

I´ve seen the mongoose timestamps option that would solve my date/time issue, but is there a way to extend it to include extra properties, where I´m gonna be adding the application username ?

If not, is there a single place where I can write a function that will be called on every creation/update so that I can include/modify these fields ?

Today I´m insering these properties on every model like below, but I would like to move all of them to a single place.

var companySchema = mongoose.Schema({

    name: {
        type: String,
        index: true
    },
    phone: {
        type: String
    },
    deleted: {
        type: Boolean
    },
    createdAt: {
        type: Date
    },
    createdBy: {
        type: String
    },
    updatedAt: {
        type: Date
    },
    updatedBy: {
        type: String
    }
});

How would be the best approach for it ?


问:
Delete entity in google datastore in python
I want to delete/modify an entity in the google cloud datastore based on an email.

```<code>email = 'john@gmail.com'
query = client.query('email', '=', email)
# delete this entity if it exists??
</code>```

Now that I have this query, how can I go about deleting this entity?

答:
```<code>next_entity = query.fetch()
client.delete(next_entity.key)
</code>```

If you're only deleting the entity and don't need anything other than the key, consider doing a keys_only query to avoid reading data you don't care about.

Body:
I want to delete/modify an entity in the google cloud datastore based on an email.

email = 'john@gmail.com'
query = client.query('email', '=', email)
# delete this entity if it exists??

Now that I have this query, how can I go about deleting this entity?

Body:
next_entity = query.fetch()
client.delete(next_entity.key)

If you're only deleting the entity and don't need anything other than the key, consider doing a keys_only query to avoid reading data you don't care about.


问:
How do I `jsonify` a list in Flask?
Currently Flask would raise an error when jsonifying a list.

I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:

```<code>[
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]
</code>```

instead of

```<code>{ 'results': [
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]}
</code>```

on responding to a application/json request. How can I return a JSON list in Flask using Jsonify?

答:
If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):

```<code>   return jsonify({'ans':bin}), 201
</code>```

Finally, in your client you will obtain something like

{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }

Title: How do I `jsonify` a list in Flask?

Body:
Currently Flask would raise an error when jsonifying a list.

I know there could be security reasons https://github.com/mitsuhiko/flask/issues/170, but I still would like to have a way to return a JSON list like the following:

[
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]

instead of

{ 'results': [
    {'a': 1, 'b': 2},
    {'a': 5, 'b': 10}
]}

on responding to a application/json request. How can I return a JSON list in Flask using Jsonify?

Body:
If you are searching literally the way to return a JSON list in flask and you are completly sure that your variable is a list then the easy way is (where bin is a list of 1's and 0's):

   return jsonify({'ans':bin}), 201

Finally, in your client you will obtain something like

{ "ans": [ 0.0, 0.0, 1.0, 1.0, 0.0 ] }


问:
What is an .episode file..?
what is a .episode file in JAXB..? Is it generated by the JAXB or is it a configuration file that we'd manipulate to avoid regeneration of the same classes by JAXB..?</p>

答:
Just an addon to the answer, I would like to provide an input on how to avoid having .episode file generated while using maven-jaxb2-plugin

```<code>         `<plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.12.3</version>
            <executions>
                <execution>
                    <id>schema-conversion</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/schema/myschema</schemaDirectory>
                        <bindingDirectory>src/main/schema/myschema</bindingDirectory>
                        <bindingIncludes>
                            <include>binding_info.xjb</include>
                        </bindingIncludes>
                        <generateDirectory>src/main/java/</generateDirectory>
                        <episode>false</episode>
                    </configuration>
                </execution>
            </executions>
        </plugin>`
</code>```

<episode>false</episode> will make it disappear.

Title: What is an .episode file..?

Body:
Just an addon to the answer, I would like to provide an input on how to avoid having .episode file generated while using maven-jaxb2-plugin

         `<plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.12.3</version>
            <executions>
                <execution>
                    <id>schema-conversion</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/schema/myschema</schemaDirectory>
                        <bindingDirectory>src/main/schema/myschema</bindingDirectory>
                        <bindingIncludes>
                            <include>binding_info.xjb</include>
                        </bindingIncludes>
                        <generateDirectory>src/main/java/</generateDirectory>
                        <episode>false</episode>
                    </configuration>
                </execution>
            </executions>
        </plugin>`

<episode>false</episode> will make it disappear.


问:
Scatter plot with scalar data
I want to create a scatter plot with matplotlib where the data points have scalar data attached to them and are assigned a color depending on how large their attached value is relative to the other points in the set. I.e., I want something akin to a heatmap. However, I'm looking for a "discrete" heatmap, i.e. nothing should be ploted where there were no points in the original data set and, in particular, no interpolation (in space) should be performed.

Can this be done?

答:
Solving this in Altair.

```<code>import numpy as np
import pylab as pl

x = np.random.uniform(-1, 1, 1000)
y = np.random.uniform(-1, 1, 1000)

z = np.sqrt(x*x+y*y)

df = pd.DataFrame({'x':x,'y':y, 'z':z})

from altair import *

Chart(df).mark_circle().encode(x='x',y='y', color='z')
</code>```

Title: Scatter plot with scalar data

Body:
Solving this in Altair.

import numpy as np
import pylab as pl

x = np.random.uniform(-1, 1, 1000)
y = np.random.uniform(-1, 1, 1000)

z = np.sqrt(x*x+y*y)

df = pd.DataFrame({'x':x,'y':y, 'z':z})

from altair import *

Chart(df).mark_circle().encode(x='x',y='y', color='z')


问:
Sequence data base with Django?
I am learning Django and creating  a Biological Sequence database, contains hundreds of sequences using a model as given bellow, model has two fields,  "Seq_ID" and "sequence". I am trying to write a view so that it can render IDs of all the sequences on home page and clicking on a particular IDs it will shows the associated sequence.

Updated Views and Urls:

Model:

```<code>from __future__ import unicode_literals

from django.db import models

    # Create your models here.
class FastaSeq(models.Model):

    Seq_ID =  models.CharField(max_length=20)
    Sequense = models.TextField()

    def __unicode__(self):

        return self.Seq_ID
</code>```

View:

```<code>from django.shortcuts import render
from django.conf import settings
from .models import FastaSeq

def home(request):
    data = FastaSeq.objects.all()
    context = {'data':data}
    template = 'home.html'
    return render(request, template, context)

def single(request,Seq_ID):
    data = FastaSeq.objects.get(Seq_ID=Seq_ID)
    return render(request,template,{'data':data})
</code>```

urls:

```<code>from django.conf.urls import url
from django.contrib import admin
from new_app import views as new_app_view

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^home/', new_app_view.home, name='home'),
    url(r'^User/(?P<Seq_ID>\d+)/$', new_app_view.single, name='single'),

]
</code>```

Example_Data:

```<code>Seq_ID:
>01_sequence

Sequence:
LARALLLCAAVVCGAANPCCSHPCQNRGVCMSVGFDQYKCDCTRTGFYGENCTTPEFLTRIKLLLKPTP
DTVHYILTHFKGVWNIVNKISFLRNMIMRYVLTSRSHLIESPPTYNVHYSYKSWEAFSNLSYYTRALPPV
PDDCPTPMGVKGRKELPDSKEVVKKVLLRRKFIPDPQGTNLMFAFFAQHFTHQFFKTDIERGPAFTKGKN
HGVDLSHVYGESLERQHNRRLFKDGKMKYQMINGEMYPPTVKDTQVEMIYPPHIPEHLKFAVGQEVFGLV
</code>```

Using this model I have added around 50 Demo sequences into the database but not able to writedown a view which can show the sequence ID on home page and clicking on ID will land you on sequence data.

Updated:

Showing some Error:

```<code>No    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/home/jai/.virtualenvs/env1/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 389, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
NoReverseMatch: Reverse for 'single' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['User/(?P<Seq_ID>\\d+)/$']
[06/Jul/2017 06:46:13] "GET /home/ HTTP/1.1" 500 133824
</code>```

答:
Add the seq_ids to the context:

```<code>context = {'seq_ids': FastaSeq.objects.all()}
</code>```

Then iterate through them in your template.

```<code>{% for id in seq_ids %}
    <your html here>
{% endfor %}
</code>```

Title: Sequence data base with Django?

Body:
I am learning Django and creating  a Biological Sequence database, contains hundreds of sequences using a model as given bellow, model has two fields,  "Seq_ID" and "sequence". I am trying to write a view so that it can render IDs of all the sequences on home page and clicking on a particular IDs it will shows the associated sequence.

Updated Views and Urls:

Model:

from __future__ import unicode_literals

from django.db import models

    # Create your models here.
class FastaSeq(models.Model):

    Seq_ID =  models.CharField(max_length=20)
    Sequense = models.TextField()

    def __unicode__(self):

        return self.Seq_ID

View:

from django.shortcuts import render
from django.conf import settings
from .models import FastaSeq

def home(request):
    data = FastaSeq.objects.all()
    context = {'data':data}
    template = 'home.html'
    return render(request, template, context)

def single(request,Seq_ID):
    data = FastaSeq.objects.get(Seq_ID=Seq_ID)
    return render(request,template,{'data':data})

urls:

from django.conf.urls import url
from django.contrib import admin
from new_app import views as new_app_view

urlpatterns = [

    url(r'^admin/', admin.site.urls),
    url(r'^home/', new_app_view.home, name='home'),
    url(r'^User/(?P<Seq_ID>\d+)/$', new_app_view.single, name='single'),

]

Example_Data:

Seq_ID:
>01_sequence

Sequence:
LARALLLCAAVVCGAANPCCSHPCQNRGVCMSVGFDQYKCDCTRTGFYGENCTTPEFLTRIKLLLKPTP
DTVHYILTHFKGVWNIVNKISFLRNMIMRYVLTSRSHLIESPPTYNVHYSYKSWEAFSNLSYYTRALPPV
PDDCPTPMGVKGRKELPDSKEVVKKVLLRRKFIPDPQGTNLMFAFFAQHFTHQFFKTDIERGPAFTKGKN
HGVDLSHVYGESLERQHNRRLFKDGKMKYQMINGEMYPPTVKDTQVEMIYPPHIPEHLKFAVGQEVFGLV

Using this model I have added around 50 Demo sequences into the database but not able to writedown a view which can show the sequence ID on home page and clicking on ID will land you on sequence data.

Updated:

Showing some Error:

No    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/home/jai/.virtualenvs/env1/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 389, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns)
NoReverseMatch: Reverse for 'single' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['User/(?P<Seq_ID>\\d+)/$']
[06/Jul/2017 06:46:13] "GET /home/ HTTP/1.1" 500 133824

Body:
Add the seq_ids to the context:

context = {'seq_ids': FastaSeq.objects.all()}

Then iterate through them in your template.

{% for id in seq_ids %}
    <your html here>
{% endfor %}


问:
How instance variable are related to class variable in python
```<code>class myclass(object):
    i=0
    def increase(self):
        self.i+=1
        print('increased value:', self.i)

if __name__=='__main__':
    m=myclass()
    m.increase()
</code>```

Here is a class variable and self.i is instance variable , on executing i get o/P as 1.

But if  comment class variable i I get an error

```<code>self.i+=1
AttributeError: 'myclass' object has no attribute 'i'
</code>```

what is the relation between class variable i and instance variable self.i here.

答:
The problem you are facing is the lack of definition of i object after you remove the class variable.
The i=0 statement is the only definition. It is the same with any other variable, nothing special happens here:

```<code>i+=1
</code>```

yields the same error if you put it in main or anywhere. In order to do the increment += you need to have the object declared first.

You can do:

```<code>class myclass(object):
def increase(self):
    self.i=0
    self.i+=1
    print('increased value:', self.i)
</code>```

which makes no sense, but illustrates the issue, i think.

Body:
class myclass(object):
    i=0
    def increase(self):
        self.i+=1
        print('increased value:', self.i)

if __name__=='__main__':
    m=myclass()
    m.increase()

Here is a class variable and self.i is instance variable , on executing i get o/P as 1.

But if  comment class variable i I get an error

self.i+=1
AttributeError: 'myclass' object has no attribute 'i'

what is the relation between class variable i and instance variable self.i here.

Body:
The problem you are facing is the lack of definition of i object after you remove the class variable.
The i=0 statement is the only definition. It is the same with any other variable, nothing special happens here:

i+=1

yields the same error if you put it in main or anywhere. In order to do the increment += you need to have the object declared first.

You can do:

class myclass(object):
def increase(self):
    self.i=0
    self.i+=1
    print('increased value:', self.i)

which makes no sense, but illustrates the issue, i think.


问:
android toast a Chinese message to user
Basically I need to toast a message written in Chinese to user.
However I don't know how to achieve such thing.
Any solution that can help me?</p>

答:
I'm not an Android programmer, but doesn't this work?

```<code>Context context = getApplicationContext();
CharSequence text = "中国的网页";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
</code>```

Code ripped from here.

(Apologies if that means anything offensive. I simply ripped some random characters from here).

Title: android toast a Chinese message to user

Body:
I'm not an Android programmer, but doesn't this work?

Context context = getApplicationContext();
CharSequence text = "中国的网页";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

Code ripped from here.

(Apologies if that means anything offensive. I simply ripped some random characters from here).


问:
APIs are to be protected by wso2 Identity server
I want to secured my all APIs (created by wso2 APIm) by wso2 Identity server.

Could you please let me know how to do configuration set up ?
Thanks.

答:
You can configure WSO2 Identity Server as the key manger of APIM. Refer [1].

[1] https://docs.wso2.com/display/AM210/Configuring+WSO2+Identity+Server+as+a+Key+Manager


问:
Find the minimum value in golang?
In the language there is a minimum function https://golang.org/pkg/math/#Min But what if I have more than 2 numbers? I must to write a manual comparison in a for loop, or is there another way? The numbers are in the slice.</p>

答: You should write a loop. It does not make sense to create dozens of function in standard library to find min/max/count/count_if/all_of/any_of/none_of etc. like in C++ (most of them in 4 flavours according arguments).</p>

Title: Find the minimum value in golang?


问:
Screenshot (PIL)ImageGrab.grab / BitBlt on Win10 only return the Background?
i have a big problem with windows 10, normaly i used PIL (Python) to get a nice and clean screenshot from inside a program.

but with windows 10 this does not work anymore, now i become only everything on the Desktop but my FullScreen Window is missing.

i also tryed to use:

```<code>BitBlt(screen_copy, 0, 0, width, height, screen, left, top, SRCCOPY | CAPTUREBLT)
</code>```

but the result is exactly the same :(

does anybody has any solution or idea what has changed in Win10?

thank you so much.

答:
Another approach that is really fast is the MSS module. It uses only the ctypes standard module, so it does not require any dependencies. It is OS independant, works with Windows 10 and its use is made easy:

```<code>from mss import mss

with mss() as sct:
    sct.shot()
</code>```

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..

Body:
i have a big problem with windows 10, normaly i used PIL (Python) to get a nice and clean screenshot from inside a program.

but with windows 10 this does not work anymore, now i become only everything on the Desktop but my FullScreen Window is missing.

i also tryed to use:

BitBlt(screen_copy, 0, 0, width, height, screen, left, top, SRCCOPY | CAPTUREBLT)

but the result is exactly the same :(

does anybody has any solution or idea what has changed in Win10?

thank you so much.

Body:
Another approach that is really fast is the MSS module. It uses only the ctypes standard module, so it does not require any dependencies. It is OS independant, works with Windows 10 and its use is made easy:

from mss import mss

with mss() as sct:
    sct.shot()

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..


答:
What happens is that you are shadowing the class variable with a member variable.

See what happens when you instanciate another myclass-object and add a few printouts to your code:

```<code>class myclass(object):
    i=0
    def increase(self):
        myclass.i+=1
        print('incresed value:',self.i)

if __name__=='__main__':
    m=myclass()
    n=myclass()
    print("m.i=", m.i)
    print("n.i=", n.i)
    m.increase()
    print("m.i=", m.i)
    print("n.i=", n.i)
</code>```

The output is now:

```<code>m.i= 0
n.i= 0
incresed value: 1
m.i= 1
n.i= 0
</code>```

You see that you incremented the value of the i-member of m, but not of n. This is because self (like this in c++) always refers to the current object instance. If you update your code to the following, you are actually incrementing the class variable:

```<code>def increase(self):
    myclass.i+=1
    print('incresed value:',self.i)
</code>```

And the output changes to the following:

```<code>m.i= 0
n.i= 0
incresed value: 1
m.i= 1
n.i= 1
</code>```

Like Guillaume Jacquenot already stated in his answer, if you'd like to use member variables, it is advisable to initialize them in __init__(). In your case, the interpreter ist just using the class variable with the same name when it can't find a member variable, and in the same line initializing a member variable (with identical name i). If you comment out the class variable, you're trying to increment a variable which does not exist yet, hence the interpreter error.

Title: How instance variable are related to class variable in python

Body:
What happens is that you are shadowing the class variable with a member variable.

See what happens when you instanciate another myclass-object and add a few printouts to your code:

class myclass(object):
    i=0
    def increase(self):
        myclass.i+=1
        print('incresed value:',self.i)

if __name__=='__main__':
    m=myclass()
    n=myclass()
    print("m.i=", m.i)
    print("n.i=", n.i)
    m.increase()
    print("m.i=", m.i)
    print("n.i=", n.i)

The output is now:

m.i= 0
n.i= 0
incresed value: 1
m.i= 1
n.i= 0

You see that you incremented the value of the i-member of m, but not of n. This is because self (like this in c++) always refers to the current object instance. If you update your code to the following, you are actually incrementing the class variable:

def increase(self):
    myclass.i+=1
    print('incresed value:',self.i)

And the output changes to the following:

m.i= 0
n.i= 0
incresed value: 1
m.i= 1
n.i= 1

Like Guillaume Jacquenot already stated in his answer, if you'd like to use member variables, it is advisable to initialize them in __init__(). In your case, the interpreter ist just using the class variable with the same name when it can't find a member variable, and in the same line initializing a member variable (with identical name i). If you comment out the class variable, you're trying to increment a variable which does not exist yet, hence the interpreter error.


问:
How to access "Custom" or non-System TFS workitem fields using PowerShell?
When using PowerShell to extract information from TFS, I find that I can get at the standard fields but not "Custom" fields.  I'm not sure custom is the correct term, but for example if I look at the Process Editor in VS2008 and edit the Work Item type, there are fields such as listed below, with Name, Type and RefName:

```<code>Title         String    System.Title
State         String    System.State
Rev           Integer   System.Rev
Changed By    String    System.ChangedBy
</code>```

I can access these with Get-TfsItemHistory:

```<code>Get-TfsItemHistory "$/path" -Version "D01/12/10~" -R
  | Select -exp WorkItems | Format-Table Title, State, Rev, ChangedBy -Auto
</code>```

So far so good.

However, there are also some other fields in the WorkItem type, which I'm calling "Custom" or non-System fields, e.g.:

```<code>Activated By  String    Microsoft.VSTS.Common.ActivatedBy
Resolved By   String    Microsoft.VSTS.Common.ResolvedBy
</code>```

And the following command does not retrieve the data, just spaces.

```<code>Get-TfsItemHistory "$/path" -Version "D01/12/10~" -R
  | Select -exp WorkItems | Format-Table ActivatedBy, ResolvedBy -Auto
</code>```

I've also tried the names in quotes, the fully qualified refname, but no luck. How do you access these "non-System" fields?

Thanks

Boz

UPDATE:

From Keith's answer I can get the fields I need:

```<code>Get-TfsItemHistory "$/Hermes/Main" -Version "D01/12/10~" -Recurse `
  | Select ChangeSetId, Comment -exp WorkItems `
  | Select ChangeSetId, Comment, @{n='WI-Id'; e={$_.Id}}, Title -exp Fields `
  | Where {$_.ReferenceName -eq 'Microsoft.VSTS.Common.ResolvedBy'} `
  | Format-Table ChangesetId, Comment, WI-Id, Title, @{n='Resolved By'; e={$_.Value}} -Auto
</code>```

Notes:
Renaming of WorkItem's Id to WI-Id necessary because Id is ambiguous with Field Id.
Renaming the Fields Value property gives a column heading name instead of "Value".

答:
There is a Fields collection property in each work item that appears to contain all the work item fields and values.  Access it like so:</p>

```<code>Get-TfsItemHistory . -r -vers "D12/14/2010~" |
    Where {$_.WorkItems.count -gt 0} | Select -Expand workitems |
    Select @{n='WIT-Id';e={$_.Id}},Title -Expand Fields |
    Where {$_.ReferenceName -eq 'Microsoft.VSTS.Common.ActivatedBy'} |
    Format-Table Value,WIT-Id,Title -auto
</code>```

Body:
When using PowerShell to extract information from TFS, I find that I can get at the standard fields but not "Custom" fields.  I'm not sure custom is the correct term, but for example if I look at the Process Editor in VS2008 and edit the Work Item type, there are fields such as listed below, with Name, Type and RefName:

Title         String    System.Title
State         String    System.State
Rev           Integer   System.Rev
Changed By    String    System.ChangedBy

I can access these with Get-TfsItemHistory:

Get-TfsItemHistory "$/path" -Version "D01/12/10~" -R
  | Select -exp WorkItems | Format-Table Title, State, Rev, ChangedBy -Auto

So far so good.

However, there are also some other fields in the WorkItem type, which I'm calling "Custom" or non-System fields, e.g.:

Activated By  String    Microsoft.VSTS.Common.ActivatedBy
Resolved By   String    Microsoft.VSTS.Common.ResolvedBy

And the following command does not retrieve the data, just spaces.

Get-TfsItemHistory "$/path" -Version "D01/12/10~" -R
  | Select -exp WorkItems | Format-Table ActivatedBy, ResolvedBy -Auto

I've also tried the names in quotes, the fully qualified refname, but no luck. How do you access these "non-System" fields?

Thanks

Boz

UPDATE:

From Keith's answer I can get the fields I need:

Get-TfsItemHistory "$/Hermes/Main" -Version "D01/12/10~" -Recurse `
  | Select ChangeSetId, Comment -exp WorkItems `
  | Select ChangeSetId, Comment, @{n='WI-Id'; e={$_.Id}}, Title -exp Fields `
  | Where {$_.ReferenceName -eq 'Microsoft.VSTS.Common.ResolvedBy'} `
  | Format-Table ChangesetId, Comment, WI-Id, Title, @{n='Resolved By'; e={$_.Value}} -Auto

Notes:
Renaming of WorkItem's Id to WI-Id necessary because Id is ambiguous with Field Id.
Renaming the Fields Value property gives a column heading name instead of "Value".

Body:
There is a Fields collection property in each work item that appears to contain all the work item fields and values.  Access it like so:

Get-TfsItemHistory . -r -vers "D12/14/2010~" |
    Where {$_.WorkItems.count -gt 0} | Select -Expand workitems |
    Select @{n='WIT-Id';e={$_.Id}},Title -Expand Fields |
    Where {$_.ReferenceName -eq 'Microsoft.VSTS.Common.ActivatedBy'} |
    Format-Table Value,WIT-Id,Title -auto


问:
back to back or gates with object comparisons. Confusion
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)</p>

```<code>function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

答:
Swap your if statements. because return will exit the function and null=== null so it will execute the first loop and will not go to the next loop</p>

```<code>function deepEqual(a, b) {

   if (a == null || typeof a != "object" ||
       b == null || typeof b != "object") {
       return false;
   }
    if (a === b) {
    return true;
   }

 }
var c = null;
 console.log(deepEqual(c, c));
</code>```

Body:
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true

Body:
Swap your if statements. because return will exit the function and null=== null so it will execute the first loop and will not go to the next loop

function deepEqual(a, b) {

   if (a == null || typeof a != "object" ||
       b == null || typeof b != "object") {
       return false;
   }
    if (a === b) {
    return true;
   }

 }
var c = null;
 console.log(deepEqual(c, c));


问:
PHP Fatal error: Uncaught Error: Class 'DOMDocument' not found on Symfony
I have been checking all questions related, but the solutions did not solve the issue i'm getting.

I'm trying to set a EC2 instance, installing php7.0, mysql, composer, cloned the repository, etc..

This EC2 instance is a Centos 6.5.

But when :

```<code>php bin/console cache:clear --env=prod --no-debug
</code>```

I'm getting:

```<code>PHP Fatal error:  Uncaught Error: Class 'DOMDocument' not found in /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php:52
Stack trace:
#0 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php(263): Symfony\Component\Config\Util\XmlUtils::loadFile('/var/www/html/T...', Array)
#1 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php(41): Symfony\Component\DependencyInjection\Loader\XmlFileLoader->parseFileToDOM('/var/www/html/T...')
#2 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php(72): Symfony\Component\DependencyInjection\Loader\XmlFileLoader->load('web.xml')
#3 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php(59): Symfony\Bundle\FrameworkBundle\Dependen in /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php on line 52
</code>```

Well, searching similar questions, the purposed solution is:

```<code>sudo yum install php-xml
</code>```

I'm getting:

```<code>Loaded plugins: fastestmirror, presto
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: ftp.heanet.ie
 * epel: ftp.heanet.ie
 * extras: ftp.heanet.ie
 * ius: mirrors.ircam.fr
 * updates: ftp.heanet.ie
Resolving Dependencies
--> Running transaction check
---> Package php-xml.x86_64 0:5.3.3-49.el6 will be installed
--> Processing Dependency: php-common(x86-64) = 5.3.3-49.el6 for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.24)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.22)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.18)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.13)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.11)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1()(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libexslt.so.0()(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Running transaction check
---> Package libxslt.x86_64 0:1.1.26-2.el6_3.1 will be installed
---> Package php-common.x86_64 0:5.3.3-49.el6 will be installed
--> Processing Conflict: php70u-common-7.0.20-1.ius.centos6.x86_64 conflicts php-common < 7.0.20
--> Processing Conflict: php70u-json-7.0.20-1.ius.centos6.x86_64 conflicts php-json < 7.0.20
--> Finished Dependency Resolution
Error: php70u-common conflicts with php-common-5.3.3-49.el6.x86_64
Error: php70u-json conflicts with php-common-5.3.3-49.el6.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
</code>```

I Have installed the php70u-common , but how can avoid this conflict with php-common-5.3.3-49?

Thanks in advance

答: As said on the comments, installing php70u-xml solved the problem.

Body:
I have been checking all questions related, but the solutions did not solve the issue i'm getting.

I'm trying to set a EC2 instance, installing php7.0, mysql, composer, cloned the repository, etc..

This EC2 instance is a Centos 6.5.

But when :

php bin/console cache:clear --env=prod --no-debug

I'm getting:

PHP Fatal error:  Uncaught Error: Class 'DOMDocument' not found in /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php:52
Stack trace:
#0 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php(263): Symfony\Component\Config\Util\XmlUtils::loadFile('/var/www/html/T...', Array)
#1 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php(41): Symfony\Component\DependencyInjection\Loader\XmlFileLoader->parseFileToDOM('/var/www/html/T...')
#2 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php(72): Symfony\Component\DependencyInjection\Loader\XmlFileLoader->load('web.xml')
#3 /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Compiler/MergeExtensionConfigurationPass.php(59): Symfony\Bundle\FrameworkBundle\Dependen in /var/www/html/TFM_RedSocialMusical/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php on line 52

Well, searching similar questions, the purposed solution is:

sudo yum install php-xml

I'm getting:

Loaded plugins: fastestmirror, presto
Setting up Install Process
Loading mirror speeds from cached hostfile
 * base: ftp.heanet.ie
 * epel: ftp.heanet.ie
 * extras: ftp.heanet.ie
 * ius: mirrors.ircam.fr
 * updates: ftp.heanet.ie
Resolving Dependencies
--> Running transaction check
---> Package php-xml.x86_64 0:5.3.3-49.el6 will be installed
--> Processing Dependency: php-common(x86-64) = 5.3.3-49.el6 for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.24)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.22)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.18)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.13)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1(LIBXML2_1.0.11)(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libxslt.so.1()(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Processing Dependency: libexslt.so.0()(64bit) for package: php-xml-5.3.3-49.el6.x86_64
--> Running transaction check
---> Package libxslt.x86_64 0:1.1.26-2.el6_3.1 will be installed
---> Package php-common.x86_64 0:5.3.3-49.el6 will be installed
--> Processing Conflict: php70u-common-7.0.20-1.ius.centos6.x86_64 conflicts php-common < 7.0.20
--> Processing Conflict: php70u-json-7.0.20-1.ius.centos6.x86_64 conflicts php-json < 7.0.20
--> Finished Dependency Resolution
Error: php70u-common conflicts with php-common-5.3.3-49.el6.x86_64
Error: php70u-json conflicts with php-common-5.3.3-49.el6.x86_64
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

I Have installed the php70u-common , but how can avoid this conflict with php-common-5.3.3-49?

Thanks in advance


问:
Sql to linq (How to wrtie Sql Query in Linq)
This is my query. it is working fine in SQL and return the result that i want.
how can i write in Linq.

```<code>select * from g2issuetype it,storingsitems si
where 1 not in
(select 1 from contractstoringsitems cs where scontractid=110
and cs.issuetypeid=it.issuetypeid and cs.storingsitemid=si.storingsitemid) order by issuetype,storingsitem
</code>```

i am trying this but its not correct. i am new in Linq any one can help me to write this query in Linq

```<code>(from it in _context.G2issueType
         from si in _context.StoringsItems
         where si.StoringsItemId != (from cs in _context.ContractStoringsitems
                                     where cs.Scontractid == id
                                     && cs.Issuetypeid == it.IssueTypeId
                                     && cs.Storingsitemid == si.StoringsItemId )
         select new StoringsitemsViewMode { })
</code>```

答:
You can use Any(it is like exists/not exists in sql) operator like this

```<code>from it in g2issuetype
            join si in storingsitems
            where !contractstoringsitems.Any(x => scontractid == 110 && x.issuetypeid = it.issuetypeid && x.storingsitemid = si.storingsitemid)
            select new StoringsitemsViewMode { }
</code>```

Body:
This is my query. it is working fine in SQL and return the result that i want.
how can i write in Linq.

select * from g2issuetype it,storingsitems si
where 1 not in
(select 1 from contractstoringsitems cs where scontractid=110
and cs.issuetypeid=it.issuetypeid and cs.storingsitemid=si.storingsitemid) order by issuetype,storingsitem

i am trying this but its not correct. i am new in Linq any one can help me to write this query in Linq

(from it in _context.G2issueType
         from si in _context.StoringsItems
         where si.StoringsItemId != (from cs in _context.ContractStoringsitems
                                     where cs.Scontractid == id
                                     && cs.Issuetypeid == it.IssueTypeId
                                     && cs.Storingsitemid == si.StoringsItemId )
         select new StoringsitemsViewMode { })

Body:
You can use Any(it is like exists/not exists in sql) operator like this

from it in g2issuetype
            join si in storingsitems
            where !contractstoringsitems.Any(x => scontractid == 110 && x.issuetypeid = it.issuetypeid && x.storingsitemid = si.storingsitemid)
            select new StoringsitemsViewMode { }


问:
How to setup protectionController/ProtectionData in dash.js v2
I want to play a protected video using dash.js. I’m using dash v2.0 and it's completely different from v1. the below code which work in v1 no longer works in v2.

```<code>$(function() {
    var AXINOM_DEMO_WV_LS = "http://axpr-wv-fe.cloudapp.net:8080/LicensingService";

    var context = new Dash.di.DashContext();
    var player = new MediaPlayer(context);
    player.startup();
    player.attachView(document.querySelector('#videoPlayer'));
    player.attachProtectionData({"com.widevine.alpha": new MediaPlayer.vo.protection.ProtectionData(AXINOM_DEMO_WV_LS)});

    $('#playButton').click(function() {
        var videoUrl = 'http://level3-cdn.axprod.net/demo/manifestprot.ism/.mpd';
        player.attachSource(videoUrl);
    });
});
</code>```

I have tried to rewrite it again in v2

```<code>$(function() {
    var AXINOM_DEMO_WV_LS = "http://axpr-wv-fe.cloudapp.net:8080/LicensingService";
    var player = dashjs.MediaPlayer().create();
    player.initialize(document.querySelector("#videoPlayer"),"", true);
    player.attachProtectionData({"com.widevine.alpha": new ProtectionData(AXINOM_DEMO_WV_LS)});
    $('#playButton').click(function() {
        var videoUrl = 'http://level3-cdn.axprod.net/demo/manifestprot.ism/.mpd';
        player.attachSource(videoUrl);
    });
});
</code>```

But it's not working. an error is being thrown.

```<code>Uncaught ReferenceError: ProtectionData is not defined
    at HTMLDocument.<anonymous> (main.js:5)
</code>```

I don't know how to correctly define this protection data since there is no tutorial on how to do it. kindly assist.

答:
I was finally able to solve the problem. In dash.js version 2, this is the way protectionData is set.</p>

```<code>var AXINOM_DEMO_WV_LS = "http://axpr-wv-fe.cloudapp.net:8080/LicensingService";
var drmKeySystem ="com.widevine.alpha";
var protData ={drmKeySystem:{serverURL: AXINOM_DEMO_WV_LS}};

 var player = dashjs.MediaPlayer().create();
 player.initialize(document.querySelector("#videoPlayer"),"", true);
 player.setProtectionData(protData);
</code>```

Body:
I want to play a protected video using dash.js. I’m using dash v2.0 and it's completely different from v1. the below code which work in v1 no longer works in v2.

$(function() {
    var AXINOM_DEMO_WV_LS = "http://axpr-wv-fe.cloudapp.net:8080/LicensingService";

    var context = new Dash.di.DashContext();
    var player = new MediaPlayer(context);
    player.startup();
    player.attachView(document.querySelector('#videoPlayer'));
    player.attachProtectionData({"com.widevine.alpha": new MediaPlayer.vo.protection.ProtectionData(AXINOM_DEMO_WV_LS)});

    $('#playButton').click(function() {
        var videoUrl = 'http://level3-cdn.axprod.net/demo/manifestprot.ism/.mpd';
        player.attachSource(videoUrl);
    });
});

I have tried to rewrite it again in v2

$(function() {
    var AXINOM_DEMO_WV_LS = "http://axpr-wv-fe.cloudapp.net:8080/LicensingService";
    var player = dashjs.MediaPlayer().create();
    player.initialize(document.querySelector("#videoPlayer"),"", true);
    player.attachProtectionData({"com.widevine.alpha": new ProtectionData(AXINOM_DEMO_WV_LS)});
    $('#playButton').click(function() {
        var videoUrl = 'http://level3-cdn.axprod.net/demo/manifestprot.ism/.mpd';
        player.attachSource(videoUrl);
    });
});

But it's not working. an error is being thrown.

Uncaught ReferenceError: ProtectionData is not defined
    at HTMLDocument.<anonymous> (main.js:5)

I don't know how to correctly define this protection data since there is no tutorial on how to do it. kindly assist.

Body:
I was finally able to solve the problem. In dash.js version 2, this is the way protectionData is set.

var AXINOM_DEMO_WV_LS = "http://axpr-wv-fe.cloudapp.net:8080/LicensingService";
var drmKeySystem ="com.widevine.alpha";
var protData ={drmKeySystem:{serverURL: AXINOM_DEMO_WV_LS}};

 var player = dashjs.MediaPlayer().create();
 player.initialize(document.querySelector("#videoPlayer"),"", true);
 player.setProtectionData(protData);


问:
Strange use of null smart pointer in COM
As the Picture shows, I don't know why m_spServer, an interface pointer, when tested as null, can be used to call a member function CreateInstance(). Could anyone tell me why?

This is the interface definition, I did't find CreateInstance() in the interface, neither the interface pointer definition.

答:
Look closely at the code:

```<code>m_spServer.CoCreateInstance(...);
</code>```

Two things to note:

m_spSever is not an actual pointer.  Rather it's an instance of a smart pointer template class of type CComPtr.  That is, it has overloaded the -> operator to dereference the underlying raw pointer (IAtlasServer*). Similarly, the == operator is overloaded to test for nullness.

The method is invoked as .CoCreateInstance with a "dot". Not ->CoCreateInstance with an "arrow".  The smart pointer is never "null".  The pointer it contains very well could be.  That means the method is getting invoked on the CComPtr instance itself, not on the underlying raw pointer.

Let's look at the implementation for CComPtr::CoCreateInstance.

```<code>template <class T>
class CComPtrBase
{
    ...

    bool operator==(_In_opt_ T* pT) const throw()
    {
        return p == pT;
    }

    ...

    _Check_return_ HRESULT CoCreateInstance(
        _In_ REFCLSID rclsid,
        _Inout_opt_ LPUNKNOWN pUnkOuter = NULL,
        _In_ DWORD dwClsContext = CLSCTX_ALL) throw()
    {
        ATLASSERT(p == NULL);
        return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&p);
    }

    ...

    T* p;

    ...
};
</code>```

You'll see that CComPtr wraps a native ("raw") pointer member variable named "p".  The overloaded == operator tests p against the native pointer type being compared with.  The method on CComPtr named CoCreateInstance simply asserts that the raw pointer it contains is already null and then attempts to do a native CoCreateInstance call with the raw pointer as the "out" param.

Smart pointers are awesome and are excellent for COM programming.  The destructor of a CComPtr automatically invokes "Release" on the underlying raw pointer appropirately.  If used correctly, you'll avoid common reference count issues without ever having to think about "AddRef" and "Release".

Body:
Look closely at the code:

m_spServer.CoCreateInstance(...);

Two things to note:

m_spSever is not an actual pointer.  Rather it's an instance of a smart pointer template class of type CComPtr.  That is, it has overloaded the -> operator to dereference the underlying raw pointer (IAtlasServer*). Similarly, the == operator is overloaded to test for nullness.

The method is invoked as .CoCreateInstance with a "dot". Not ->CoCreateInstance with an "arrow".  The smart pointer is never "null".  The pointer it contains very well could be.  That means the method is getting invoked on the CComPtr instance itself, not on the underlying raw pointer.

Let's look at the implementation for CComPtr::CoCreateInstance.

template <class T>
class CComPtrBase
{
    ...

    bool operator==(_In_opt_ T* pT) const throw()
    {
        return p == pT;
    }

    ...

    _Check_return_ HRESULT CoCreateInstance(
        _In_ REFCLSID rclsid,
        _Inout_opt_ LPUNKNOWN pUnkOuter = NULL,
        _In_ DWORD dwClsContext = CLSCTX_ALL) throw()
    {
        ATLASSERT(p == NULL);
        return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&p);
    }

    ...

    T* p;

    ...
};

You'll see that CComPtr wraps a native ("raw") pointer member variable named "p".  The overloaded == operator tests p against the native pointer type being compared with.  The method on CComPtr named CoCreateInstance simply asserts that the raw pointer it contains is already null and then attempts to do a native CoCreateInstance call with the raw pointer as the "out" param.

Smart pointers are awesome and are excellent for COM programming.  The destructor of a CComPtr automatically invokes "Release" on the underlying raw pointer appropirately.  If used correctly, you'll avoid common reference count issues without ever having to think about "AddRef" and "Release".


问:
Why don't Scala Lists have an Ordering?
Is there a reason why there is no implicit Ordering for Lists in Scala?

```<code>val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]
</code>```

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

答: I think it's an oversight. Lexicographic ordering does make sense on Seqs. We should add it to the standard library.</p>

Title: Why don't Scala Lists have an Ordering?

Body:
Is there a reason why there is no implicit Ordering for Lists in Scala?

val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.


问:
Sending Pusher events on private channels
I'm doing some tests on Pusher and I've created an authentication method for private channels following the docs and the auth is working like expected.

(docs: https://pusher.com/docs/authenticating_users#implementing_endpoints)

This is the script that I'm using for subscribing into channels using JSONP:

```<code><script>
  Pusher.logToConsole = true;
  var pusher = new Pusher('<%= ENV['PUSHER_KEY'] %>', {
    cluster: 'us2',
    encrypted: true,
    authTransport: 'jsonp',
    authEndpoint: '/pusher_jsonp_auth',
  });

  var channel = pusher.subscribe("private-channel_test");
  channel.bind('pusher:subscription_succeeded', function() {
    console.log("PVT channel");
  });
  channel.bind('greet', function(data) {
    console.log(data);
  });
</script>
</code>```

The channel was correctly subscribed, OK!
The messages I've got on browser's console:

```<code>Pusher : State changed : connecting -> connected with new socket ID 163.232688
pusher.min.js:8 Pusher : Event sent : {"event":"pusher:subscribe","data":{"auth":"1e38f997c10796c55093:4e9e160585dc7c49da68da98e281860c1461ddf7c1b37688aa2fde581b482093","channel":"private-channel_test"}}
pusher.min.js:8 Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"private-channel_test"}
home:35 PVT channel
</code>```

On the backend I've triggered an event to that channel using the socket_id:
Using the ruby pusher gem, I've sent messages like this:

```<code>Pusher.trigger('private-channel_test', 'greet', {greet: 'hello world'}, {socket_id: "163.232688"})
</code>```

The events are sent OK to Pusher, as seen on Debug Console:

But the events are not received on the frontend, and the bind function never runs when using socket_id and Pusher treats these events as API Messages

Anybody knows what am I doing wrong?

Is this code related or is my understanding of so called Private Channels is wrong?

答:
It looks like you're excluding your subscriber from the broadcast as described here.

Try removing the fourth argument from your trigger call:

```<code>Pusher.trigger('private-channel_test', 'greet', {greet: 'hello world'})
</code>```

Body:
I'm doing some tests on Pusher and I've created an authentication method for private channels following the docs and the auth is working like expected.

(docs: https://pusher.com/docs/authenticating_users#implementing_endpoints)

This is the script that I'm using for subscribing into channels using JSONP:

The channel was correctly subscribed, OK!
The messages I've got on browser's console:

Pusher : State changed : connecting -> connected with new socket ID 163.232688
pusher.min.js:8 Pusher : Event sent : {"event":"pusher:subscribe","data":{"auth":"1e38f997c10796c55093:4e9e160585dc7c49da68da98e281860c1461ddf7c1b37688aa2fde581b482093","channel":"private-channel_test"}}
pusher.min.js:8 Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"private-channel_test"}
home:35 PVT channel

On the backend I've triggered an event to that channel using the socket_id:
Using the ruby pusher gem, I've sent messages like this:

Pusher.trigger('private-channel_test', 'greet', {greet: 'hello world'}, {socket_id: "163.232688"})

The events are sent OK to Pusher, as seen on Debug Console:

But the events are not received on the frontend, and the bind function never runs when using socket_id and Pusher treats these events as API Messages

Anybody knows what am I doing wrong?

Is this code related or is my understanding of so called Private Channels is wrong?

Body:
It looks like you're excluding your subscriber from the broadcast as described here.

Try removing the fourth argument from your trigger call:

Pusher.trigger('private-channel_test', 'greet', {greet: 'hello world'})


问:
How to find out if a directory is a valid PostgreSQL cluster
I have some code which calls the pg_ctl command on a given path and checks the output to determine whether it is a valid PostgreSQL cluster:
pg_ctl status -D <data_directory>

However, while unittesting a negative on a known non-cluster directory, it isn't reliably returning the expected result of pg_ctl: directory <data_directory> is not a database cluster directory on my build server; instead it returns pg_ctl: no server running.

Is there a more fool-proof way of determining if the directory is a valid cluster?

答:
Use the following commands to initialize the DB directory.

```<code>$ initdb -D <data_directory>
</code>```

Then you can get the information about initialization.

By the way, if you want to start your psql quickly, set PGDATA variable in configuration file, then use pg_ctl start to start your psql.

Body:
Use the following commands to initialize the DB directory.

$ initdb -D <data_directory>

Then you can get the information about initialization.

By the way, if you want to start your psql quickly, set PGDATA variable in configuration file, then use pg_ctl start to start your psql.