问:
Scss not working
So I have my navbar scss working perfectly fine but for some reason I cant get any scss to work on my posts. I have no clue why its not working. Here is some of my code.

Here is my _posts.html.erb

```<code><div class="col-sm-6 col-lg-4">
 <div class="card">
   <div class="card-topper" style="background-image: url();"></div>
    <div class="card-block">
        <h4 class="card-title"><%= link_to post.title, post %></h4>
        <p class="published-date">Published Today</p>
        <p class="card-text"><%= truncate(post.description, length: 130) %></p>
        <%= link_to "Read", post, class: "btn btn-read" %>
    </div>
</div>
</code>```

Im calling this in my posts index.html.erb

```<code><div class="row">
 <%=render @posts %>
</div>
</code>```

This is my _posts.scss

```<code>.posts.index {
 .card {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid #181818;
    height: 400px;
    margin-bottom: 20px;
    .card-topper {
        height: 200px;
        width: 100%;
        background-size: cover;
        background-position: center;
    }
    .card-block {
        padding: 10px;
        .btn-read {
            background-color: #e8e8e8;
            font-weight: 300;
            border-radius: 0;
            color: black;
            &:hover {
                background-color: #d8d8d8;
            }
        }
        .card-title {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
            a {
                color: black;
                text-decoration: none;
            }
        }
        .published-date {
            font-size: 0.8rem;
            color: #787878;
            font-weight: 300;
            margin-top: 0.3rem;
            margin-bottom: 0.3rem;
        }
        .card-text {
            font-size: 0.9rem;
        }
    }
}
}
</code>```

This is my application.scss

```<code>@import "bootstrap";
@import "navbar";
@import "posts";
</code>```

Im importing the _posts.scss to my application.scsss just like I am with my _navbar.scss. Just dont understand why it seems to have no impact on my posts. Im using rails 5 and bootstrap 4.0.0.alpha3

答:
Option 1: Rename _posts.scss to posts.scss (remove underscore). (I prefer this way).

Option 2: Change @import "posts"; to @import "_posts"; (add underscore).

I see .posts.index { .... in your _posts.scss, did you wrap your posts with these class some thing like this:

```<code><div class="posts index">
  <div class="row">
    <%=render @posts %>
  </div>
</div>
</code>```

Title: Scss not working

Body:
So I have my navbar scss working perfectly fine but for some reason I cant get any scss to work on my posts. I have no clue why its not working. Here is some of my code.

Here is my _posts.html.erb

<%= link_to post.title, post %>

Published Today

<%= truncate(post.description, length: 130) %>

        <%= link_to "Read", post, class: "btn btn-read" %>

Im calling this in my posts index.html.erb

 <%=render @posts %>

This is my _posts.scss

.posts.index {
 .card {
    border: none;
    border-radius: 0;
    border-bottom: 1px solid #181818;
    height: 400px;
    margin-bottom: 20px;
    .card-topper {
        height: 200px;
        width: 100%;
        background-size: cover;
        background-position: center;
    }
    .card-block {
        padding: 10px;
        .btn-read {
            background-color: #e8e8e8;
            font-weight: 300;
            border-radius: 0;
            color: black;
            &:hover {
                background-color: #d8d8d8;
            }
        }
        .card-title {
            font-size: 1.3rem;
            margin-bottom: 0.5rem;
            a {
                color: black;
                text-decoration: none;
            }
        }
        .published-date {
            font-size: 0.8rem;
            color: #787878;
            font-weight: 300;
            margin-top: 0.3rem;
            margin-bottom: 0.3rem;
        }
        .card-text {
            font-size: 0.9rem;
        }
    }
}
}

This is my application.scss

@import "bootstrap";
@import "navbar";
@import "posts";

Im importing the _posts.scss to my application.scsss just like I am with my _navbar.scss. Just dont understand why it seems to have no impact on my posts. Im using rails 5 and bootstrap 4.0.0.alpha3

Body:
Option 1: Rename _posts.scss to posts.scss (remove underscore). (I prefer this way).

Option 2: Change @import "posts"; to @import "_posts"; (add underscore).

I see .posts.index { .... in your _posts.scss, did you wrap your posts with these class some thing like this:

<div class="posts index">
  <div class="row">
    <%=render @posts %>
  </div>
</div>


来源: stackexchange

问:
Setting 2 fonts with different sizes in MacVim
I'm using Vim in MacVim on Mac OS X. I have following config in .gvimrc:

```<code>set guifont=Inconsolata:h15
</code>```

But I'd like to set to different font and font size for non-ASCII symbols (because Inconsolata didn't have russian symbols).

Problem is that Inconsolata id visually a lot smaller, than Monaco that I'd like to to use for russian characters.

In iTerm 2 I have following preferences:

Regular font: 15px Inconsolata

Non-ASCII Font: 12pt Monaco

I'd tried to use:

```<code>set guifont=Inconsolata:h15,Monaco:h12
</code>```

But :h12 part didn't work (while Monaco part worked). Is there a way to fix it?

答:
You can have a look at :set guifontset=-*-*-medium-r-normal--16-*-*-*-c-*-*-*

From :h guifontset:

When not empty, specifies two (or more) fonts to be used.  The first
  one for normal English, the second one for your special language.  See
  |xfontset|

ContentLicense: CC BY-SA 3.0

Body:
I'm using Vim in MacVim on Mac OS X. I have following config in .gvimrc:

set guifont=Inconsolata:h15

But I'd like to set to different font and font size for non-ASCII symbols (because Inconsolata didn't have russian symbols).

Problem is that Inconsolata id visually a lot smaller, than Monaco that I'd like to to use for russian characters.

In iTerm 2 I have following preferences:

Regular font: 15px Inconsolata

Non-ASCII Font: 12pt Monaco

I'd tried to use:

set guifont=Inconsolata:h15,Monaco:h12

But :h12 part didn't work (while Monaco part worked). Is there a way to fix it?


问:
How to dynamically change the field order of a class in FileHelpers
On a daily basis - I need to process 5 files in a c# application using the FileHelpers library. Each file comes from a different client.

The files all represent the same entity - so I have an "Individual" class in my program that contains all the fields and I need to load the data from the files into this object. (the files are delimited files)

The problem is that each file arrives with it's columns in it's own order.
So:
Client 1 sends: Name, Surname, SSN, Age
Client 2 sends: Name, Age, Surname, SSN
Client 3 sends: Name,  SSN ,Surname (age is optional - so this client doesn't send it)

I'd really like to handle this using a single class and not create one class for each client - since my client base will hopefully grow :-)

Does anyone have any clever ideas for handling this situation with FileHelpers?

Thanks

答:
Personally, I would instead strongly push for any one of these approaches:

a) Mandate the field order (and exact specification of each column data type, uniqueness etc.) New clients use the prescribed format, and you encourage old clients to switch when they make other changes to their export.

b) Get your clients to switch to a format you specify where field order doesn't matter, e.g. JSON or XML. Sell it with e.g. "it allows more features".

c) If a) & b) are unworkable, do use multiple classes where needed, as pre-processing before converting to your own internal class. If you can't mandate field order to your clients, it's very likely that other things than field order will also differ at some point, so you will end up doing client specific processing anyway. Still use as few classes as possible, maybe some clients could use the same order & content.

My 0.02SKr worth (being Swedish :)


问:
PHP Log in page with hashed password issue
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.

```<code><?php

session_start();
include 'databaseconnection.php';

$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);

$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);

if ($hash == 0) {
  header("Location: error.php")
  exit();
} else {

$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);

if (!row = mysqli_fetch_assoc($result)); {
  echo "your email address or password is incorrect!";
} else {
  $_SESSION['id'] = $row['id'];
}

header("Location: profile.php")
</code>```

If someone could simply suggest what changes I should make, I would really appreciate it.

答:
First check request second filter input third use pdo

```<code>   <?php
    session_start();
    include 'databaseconnection.php';
    if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
    $pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
    $hashed = sha1($pwd);

    $sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
    $sql->execute(array($email, $pwd));
    $row = $sql->fetch();

    if($row['email'] !== $email || $row['password'] !== $hashed){

      header("Location: error.php");
      exit();
    } else {

      $_SESSION['id'] = $row['id'];
      header("Location: profile.php");
    }
    }else {
      echo 'error';
    }
?>
</code>```

Body:
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.

<?php

session_start();
include 'databaseconnection.php';

$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);

$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);

if ($hash == 0) {
  header("Location: error.php")
  exit();
} else {

$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);

if (!row = mysqli_fetch_assoc($result)); {
  echo "your email address or password is incorrect!";
} else {
  $_SESSION['id'] = $row['id'];
}

header("Location: profile.php")

If someone could simply suggest what changes I should make, I would really appreciate it.

Body:
First check request second filter input third use pdo

   <?php
    session_start();
    include 'databaseconnection.php';
    if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    $email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
    $pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
    $hashed = sha1($pwd);

    $sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
    $sql->execute(array($email, $pwd));
    $row = $sql->fetch();

    if($row['email'] !== $email || $row['password'] !== $hashed){

      header("Location: error.php");
      exit();
    } else {

      $_SESSION['id'] = $row['id'];
      header("Location: profile.php");
    }
    }else {
      echo 'error';
    }
?>


问:
What is the best way to implement "Copy to new" functionality with FormView control and content templates
I have a FormView control in an ASP.NET page. I use the InsertItemTemplate and EditItemTemplate to provide data manipulation functionality, and it is working very well. I would like to allow the user to "Copy to new" from an existing item. In other words, I want the user to be able to display an item as if they are going to edit it, then, if they click a "Copy to new" button, it will load the information from that item into an "Insert" form so they could just change the bits of data that they want, and insert the new item.

The data objects we are dealing with are fairly large so, providing this functionality will save the user a lot of data entry misery.

I have experimented with copying the existing EditItemTemplate controls in the Copy button's click event, storing them, and writing them to the new InsertItemTemplate controls, once the form is reloaded (in the Page_PreRender event). But this is pretty ugly stuff. There has to be a better/simpler way.

Does anyone have any suggestions?

Thanks very much for whatever advice you can give.

答:
Well, why not just leave it in edit view, have Copy to new set a flag, then handle the ItemEditing event, and if in copy to new mode, then you insert a new record instead of proceeding with the update.  That might save you a lot of work.

HTH.

ContentLicense: CC BY-SA 2.5


问:
Not the version that should be when installing Anaconda
I have installed Anaconda 4.3.1, Python 3.6, on my Ubuntu. Now when i run Python it is saying that the version is 2.7 and not 3.6 as i wanted it to be. and there is no mention to Anaconda beside the version. I am quite sure that i installed Anaconda the right way. What could i do?</p>

答:
Try using python3 in your terminal instead of python. This should start the python 3.X interpreter.

Note that other scripts like pip also have an equivalent pip3 for python 3.X.


问:
Using Dynamic Class Objects - C#
There are two different services. Those services have different processes but give us same result. A helper method needs to use that services and service responses. User is going to choose the which service will using. So, I am going to create a helper method and it takes chosen service and its parameters. The problem is that services need different parameters with different size.(a few of them is common but not most of them)

I create an  abstract class and then two class inherited from it. Abstract class contains an standart method. But inherited class methods needs different type and size parameters. Because of that, I planning to use dynamic class object as a parameter. Is that proper solution?

```<code>public abstract class ServiceBase
{
    public abstract int StandartMethod(dynamic parameters);
}

public class ServiceForA : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceA with spesific parameters
        //(parameters.Ticket, parameter.myType1, string p1 , int n1, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public class ServiceForB : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceB with spesific parameters
        //(parameters.UserName,parameters.Password, parameters.myType1,int beginRange, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public static int HelperMethod(ServiceBase service, ServiceParameters parameters)
{
   //Do required stuff
   return service.StandartMethod(parameters);
}

static void Main(string[] args)
        {
            ServiceBase serviceA = new ServiceForA();

            dynamic obj1 = new ServiceParameters();

            obj1.Ticket = GetTicket(UserName,Pass);
            obj1.p1 = "Parameter1";
            obj1.n1 = 10;

            var result = HelperMethod(serviceA, obj1);

            Console.WriteLine("RESULT 1: " + result);

            ServiceBase serviceB = new ServiceForB();

            dynamic obj2 = new ServiceParameters();
            obj2.UserName = "slyn";
            obj2.Password = "****";
            ...
            obj2.beginRange = 1;

            var result2 = HelperMethod(serviceB, obj2);

            Console.WriteLine("RESULT2: " + result2);

        }
</code>```

Service object type will be ServiceForA or ServiceForB. It doesn't matter, StandartMethod is implemented both classes. And ServiceParameters class is inherited from System.Dynamic.DynamicObject

It seems solve the problem, but is it proper solution?
Any suggestion?

答:
Usually you end up using generics for this:

```<code>public abstract class ServiceBase<TArgs>
{
    public abstract int StandardMethod(TArgs args);
}

public class Arguments
{
     public string Text { get; set; }
     public int Number { get; set; }
}

public class ServiceForB : ServiceBase<Arguments>
{
    public override int StandardMethod(Arguments arguments)
    {
        // Thanks to generics, arguments are strongly-typed and
        // and you can access its properties as usual!
        string text = arguments.Text;
        int number = arguments.Number;

        return 0;
    }
}
</code>```

BTW this approach has a possible problem: what if you need another method as part of the abstract class to support the same scenario? You would end up with many generic type parameters for each of them. Anyway, as you stated that your issue is just with one method, this should work fine.

Title: Using Dynamic Class Objects - C#

Body:
There are two different services. Those services have different processes but give us same result. A helper method needs to use that services and service responses. User is going to choose the which service will using. So, I am going to create a helper method and it takes chosen service and its parameters. The problem is that services need different parameters with different size.(a few of them is common but not most of them)

I create an  abstract class and then two class inherited from it. Abstract class contains an standart method. But inherited class methods needs different type and size parameters. Because of that, I planning to use dynamic class object as a parameter. Is that proper solution?

public abstract class ServiceBase
{
    public abstract int StandartMethod(dynamic parameters);
}

public class ServiceForA : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceA with spesific parameters
        //(parameters.Ticket, parameter.myType1, string p1 , int n1, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public class ServiceForB : ServiceBase
{
    public override int StandartMethod(dynamic parameters)
    {
        //Service Request is send to ServiceB with spesific parameters
        //(parameters.UserName,parameters.Password, parameters.myType1,int beginRange, ..)
        //----
        //Service Response received and processed
        return requiredInfo;
    }
}

public static int HelperMethod(ServiceBase service, ServiceParameters parameters)
{
   //Do required stuff
   return service.StandartMethod(parameters);
}

static void Main(string[] args)
        {
            ServiceBase serviceA = new ServiceForA();

            dynamic obj1 = new ServiceParameters();

            obj1.Ticket = GetTicket(UserName,Pass);
            obj1.p1 = "Parameter1";
            obj1.n1 = 10;

            var result = HelperMethod(serviceA, obj1);

            Console.WriteLine("RESULT 1: " + result);

            ServiceBase serviceB = new ServiceForB();

            dynamic obj2 = new ServiceParameters();
            obj2.UserName = "slyn";
            obj2.Password = "****";
            ...
            obj2.beginRange = 1;

            var result2 = HelperMethod(serviceB, obj2);

            Console.WriteLine("RESULT2: " + result2);

        }

Service object type will be ServiceForA or ServiceForB. It doesn't matter, StandartMethod is implemented both classes. And ServiceParameters class is inherited from System.Dynamic.DynamicObject

It seems solve the problem, but is it proper solution?
Any suggestion?

Body:
Usually you end up using generics for this:

public abstract class ServiceBase<TArgs>
{
    public abstract int StandardMethod(TArgs args);
}

public class Arguments
{
     public string Text { get; set; }
     public int Number { get; set; }
}

public class ServiceForB : ServiceBase<Arguments>
{
    public override int StandardMethod(Arguments arguments)
    {
        // Thanks to generics, arguments are strongly-typed and
        // and you can access its properties as usual!
        string text = arguments.Text;
        int number = arguments.Number;

        return 0;
    }
}

BTW this approach has a possible problem: what if you need another method as part of the abstract class to support the same scenario? You would end up with many generic type parameters for each of them. Anyway, as you stated that your issue is just with one method, this should work fine.


问:
Finding parents by their children's properties
I have a database containing information about members of a choir (which is divided into sections) and their parents. I need to build an e-mail list containing all children in a specific section of the choir as well as their parents.

There is a large table COMPersonen which contains all the personal information I need (especially their ID number Nummer and primary e-mail address Serienbrief E-Mail Adresse).

Another table COMPBereiche contains all the details about which section(s) (Bereich (Nr)) of the choir a certain person belonged to at a certain time. It is linked to the primary table via Nummer/Person (Nr). The [Bis] (= "until") field can be used to determine whether a person is currently a section member by checking if that field is either empty or set to a future date.

Lastly (at least for this purpose) there is a table COMElternKind that contains the ID number of all the parents (Elternteil (Nr)) and the ID numbers of their children (Kind (Nr)). Of course, each parent can have more than one child and vice versa.

So far, this is pretty straightforward. In Access, the relations look like this:

The easy part was building a query that returns all the addresses for the children in a specific section of the choir (for example the section with the ID Bereich (Nr) = 4):

```<code>SELECT COMPersonen.Nummer, COMPersonen.[Serienbrief E-Mail Adresse],
       COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
FROM COMPersonen
INNER JOIN COMPBereiche ON COMPersonen.[Nummer] = COMPBereiche.[Person (Nr)]
WHERE (((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
AND ((COMPBereiche.[Bereich (Nr)])=4)
AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date()));
</code>```

But now I also need the addresses of the parents whose children are in section 4 of the choir at the moment. How would I go about that? Finally, the two SELECT statements would need to be combined, but my guess is that that's a simple UNION, right?

答:
Do you think that this is too simplistic?

First query (children):

```<code>SELECT p.*, b.[Bereich (Nr)]
FROM COMPBereiche b INNER JOIN COMPersonen p ON b.[Person (Nr)] = p.Nummer
WHERE b.[Bereich (Nr)] = 1001
AND (b.Bis IS NULL OR b.Bis >= '2016-01-01')
and p.[Serienbrief E-Mail Adresse] IS NOT NULL
</code>```

Second query (parents):

```<code>SELECT DISTINCTROW e.*
FROM ((COMPBereiche b INNER JOIN COMPersonen p ON b.[Person (Nr)] = p.Nummer)
INNER JOIN COMElternKind k ON p.Nummer = k.[Kind (Nr)])
INNER JOIN COMPersonen e ON e.Nummer = k.[Elternteil (Nr)]
WHERE b.[Bereich (Nr)] = 1001
AND (b.Bis IS NULL OR b.Bis >= '2016-01-01')
AND e.[Serienbrief E-Mail Adresse] IS NOT NULL
</code>```

Body:
I have a database containing information about members of a choir (which is divided into sections) and their parents. I need to build an e-mail list containing all children in a specific section of the choir as well as their parents.

There is a large table COMPersonen which contains all the personal information I need (especially their ID number Nummer and primary e-mail address Serienbrief E-Mail Adresse).

Another table COMPBereiche contains all the details about which section(s) (Bereich (Nr)) of the choir a certain person belonged to at a certain time. It is linked to the primary table via Nummer/Person (Nr). The [Bis] (= "until") field can be used to determine whether a person is currently a section member by checking if that field is either empty or set to a future date.

Lastly (at least for this purpose) there is a table COMElternKind that contains the ID number of all the parents (Elternteil (Nr)) and the ID numbers of their children (Kind (Nr)). Of course, each parent can have more than one child and vice versa.

So far, this is pretty straightforward. In Access, the relations look like this:

The easy part was building a query that returns all the addresses for the children in a specific section of the choir (for example the section with the ID Bereich (Nr) = 4):

SELECT COMPersonen.Nummer, COMPersonen.[Serienbrief E-Mail Adresse],
       COMPBereiche.[Bereich (Nr)], COMPBereiche.Bis
FROM COMPersonen
INNER JOIN COMPBereiche ON COMPersonen.[Nummer] = COMPBereiche.[Person (Nr)]
WHERE (((COMPersonen.[Serienbrief E-Mail Adresse]) Is Not Null)
AND ((COMPBereiche.[Bereich (Nr)])=4)
AND ((COMPBereiche.[Bis]) Is Null Or (COMPBereiche.[Bis])>=Date()));

But now I also need the addresses of the parents whose children are in section 4 of the choir at the moment. How would I go about that? Finally, the two SELECT statements would need to be combined, but my guess is that that's a simple UNION, right?

Body:
Do you think that this is too simplistic?

First query (children):

SELECT p.*, b.[Bereich (Nr)]
FROM COMPBereiche b INNER JOIN COMPersonen p ON b.[Person (Nr)] = p.Nummer
WHERE b.[Bereich (Nr)] = 1001
AND (b.Bis IS NULL OR b.Bis >= '2016-01-01')
and p.[Serienbrief E-Mail Adresse] IS NOT NULL

Second query (parents):

SELECT DISTINCTROW e.*
FROM ((COMPBereiche b INNER JOIN COMPersonen p ON b.[Person (Nr)] = p.Nummer)
INNER JOIN COMElternKind k ON p.Nummer = k.[Kind (Nr)])
INNER JOIN COMPersonen e ON e.Nummer = k.[Elternteil (Nr)]
WHERE b.[Bereich (Nr)] = 1001
AND (b.Bis IS NULL OR b.Bis >= '2016-01-01')
AND e.[Serienbrief E-Mail Adresse] IS NOT NULL


问:
Pythonic way to sort the records with multiple columns
Let's say we have a lot of records in a file in the following fashion.

10.10.10.10(tcp/443) : Some SSL Vulnerability : Medium : Patched

10.10.10.11(tcp/888) : Some RCE Vulnerability : High : Not Patched

These records have the 3rd column with values Critical, High, Medium, Low.

What's the best possible pythonic way to sort these records in this manner :
1. Critical, 2.High, 3.Medium 4. Low ?

答:
Example using IntEnum for a list of dictionary.

```<code>from enum import IntEnum
class Vulnerability(IntEnum):
    CRITICAL = 1
    HIGH = 2
    MEDIUM = 3
    LOW = 4

records = []
records.append({'v': Vulnerability.MEDIUM})
records.append({'v': Vulnerability.HIGH})
records.append({'v': Vulnerability.CRITICAL})
records.append({'v': Vulnerability.LOW})

print(records)
# [{'v': <Vulnerability.MEDIUM: 3>}, {'v': <Vulnerability.HIGH: 2>}, {'v': <Vulnerability.CRITICAL: 1>}, {'v': <Vulnerability.LOW: 4>}]

print(records[0]['v'] < records[1]['v'])
# False

print(sorted(records, key = lambda k: k['v']))
# [{'v': <Vulnerability.CRITICAL: 1>}, {'v': <Vulnerability.HIGH: 2>}, {'v': <Vulnerability.MEDIUM: 3>}, {'v': <Vulnerability.LOW: 4>}]
</code>```

Body:
Example using IntEnum for a list of dictionary.

from enum import IntEnum
class Vulnerability(IntEnum):
    CRITICAL = 1
    HIGH = 2
    MEDIUM = 3
    LOW = 4

records = []
records.append({'v': Vulnerability.MEDIUM})
records.append({'v': Vulnerability.HIGH})
records.append({'v': Vulnerability.CRITICAL})
records.append({'v': Vulnerability.LOW})

print(records)
# [{'v': <Vulnerability.MEDIUM: 3>}, {'v': <Vulnerability.HIGH: 2>}, {'v': <Vulnerability.CRITICAL: 1>}, {'v': <Vulnerability.LOW: 4>}]

print(records[0]['v'] < records[1]['v'])
# False

print(sorted(records, key = lambda k: k['v']))
# [{'v': <Vulnerability.CRITICAL: 1>}, {'v': <Vulnerability.HIGH: 2>}, {'v': <Vulnerability.MEDIUM: 3>}, {'v': <Vulnerability.LOW: 4>}]


问:
Guidance: Want to develop an application which will convert a website into mobile app
I am new to android programming. I am working on a project which will convert a website into mobile application. I tried creating it this way -> check the image at the link: Website to Mobile App

However by this method, I am only able to open the website like in my mobile via my app. This looks similar to how to you open the website in google chrome in full desktop view. However this is not what I want. I want to develop an app like how Youtube has actually has an app on playstore.

Can anybody guide me over how to begin with it?

Best Regards,
Code Funda

答:
Hello, I just work same as you so this is the code of mine. I hope It will help you

and you can see code here => Link:  http://www.androidcodinghub.com/2017/04/youtube-in-webview.html

```<code>public class YoutubeActivity extends AppCompatActivity {
    private static final String stringUrl = "https://www.youtube.com/";
    WebView webView;
    private static final String TAG = "YoutubeActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_youtube);
        webView = (WebView) findViewById(R.id.web_view);
        getUI();
    }

    private void getUI() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().getBuiltInZoomControls();
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().getDefaultFontSize();
        webView.getSettings().supportZoom();
        webView.loadUrl(stringUrl);
        webView.setWebViewClient(new MyWebViewClient());

    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Log.e(TAG, "onReceivedError: " + error.toString());
        }

        @Override
        public void onPageFinished(WebView view, String url) {
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else
            super.onBackPressed();
    }
}
</code>```

Body:
Hello, I just work same as you so this is the code of mine. I hope It will help you

and you can see code here => Link:  http://www.androidcodinghub.com/2017/04/youtube-in-webview.html

public class YoutubeActivity extends AppCompatActivity {
    private static final String stringUrl = "https://www.youtube.com/";
    WebView webView;
    private static final String TAG = "YoutubeActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_youtube);
        webView = (WebView) findViewById(R.id.web_view);
        getUI();
    }

    private void getUI() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().getBuiltInZoomControls();
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().getDefaultFontSize();
        webView.getSettings().supportZoom();
        webView.loadUrl(stringUrl);
        webView.setWebViewClient(new MyWebViewClient());

    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Log.e(TAG, "onReceivedError: " + error.toString());
        }

        @Override
        public void onPageFinished(WebView view, String url) {
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else
            super.onBackPressed();
    }
}


问:
Generate a random matrix in R which the sum of each rows is equal to 1
I want to generate a matrix(4 rows and 30 columns) in R software, with random elements, by range of the elements between 0 and 1, which the sum of each rows equal to 1.</p>

答:
Here's a solution based on the softmax (multinomial logit) transform.</p>

```<code>m <- matrix(rnorm(4 * 30), nrow=30)
prob <- exp(m)/rowSums(exp(m))

rowSums(prob)
#[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

all(prob > 0 & prob < 1)
#[1] TRUE
</code>```

Body:
Here's a solution based on the softmax (multinomial logit) transform.

m <- matrix(rnorm(4 * 30), nrow=30)
prob <- exp(m)/rowSums(exp(m))

rowSums(prob)
#[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

all(prob > 0 & prob < 1)
#[1] TRUE


问:
Django Models - How to store fields in a dict
I have a fairly simple user-model perfectly working.
In order to reduce code redundancy, I try to store fields inside a dictory for reasons you can easily guess.

Example:

```<code>def get_social_token(self,social_net=""):
   return self.social_dict[social_net]["token"]
</code>```

If I don't do such a structure I must do some "if/then ... elif... else".
And of course I need to modify my code whenever I decide to add a new social network to my app.

I have tried two different approaches, both of them give me the same result:

No error

No field is actually detected and created in the DB

I'd like to mention that if I use a "conventional manner" to implement this behaviour such as:

twitter_social_token = EncryptedCharField(max_length=500, default='', blank=True, null=True)

It perfectly works, so it comes from the use of a dictionary.

Any idea to solve this ?
Btw. I would prefer avoiding using a new model and a foreign key... Only a One-to-One association, I would prefer not having to perform any "join" or select in another table...

Bellow, you'll find the two attempts I made which doesn't work (and I don't know why):

First attempt:

```<code>social_fields = {
    'twitter' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'facebook' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'gplus' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'linkedin' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
}
</code>```

Second attempt:

```<code>social_tokens = dict()

social_tokens["twitter"] = dict()
social_tokens["facebook"] = dict()
social_tokens["linkedin"] = dict()
social_tokens["gplus"] = dict()

social_tokens["twitter"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["twitter"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["facebook"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["facebook"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["linkedin"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["linkedin"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["gplus"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["gplus"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
</code>```

Thanks for the help dear friends,

Jonathan

答:
As far as I know, without using join you have 3 different way:

django-picklefield

django-picklefield provides an implementation of a pickled object
  field. Such fields can contain any picklable objects.

From their documentation, to use; just define a field in your model:

```<code>>>> from picklefield.fields import PickledObjectField
... class SomeObject(models.Model):
...     args = PickledObjectField()
</code>```

and assign whatever you like (as long as it’s picklable) to the field:

```<code>>>> obj = SomeObject()
>>> obj.args = ['fancy', {'objects': 'inside'}]
>>> obj.save()
</code>```

django-jsonfield

django-jsonfield is a reusable Django field that allows you to store
  validated JSON in your model.
  It silently takes care of serialization. To use, simply add the field
  to one of your models.

To use, just install the package, and then use the field:

```<code>from django.db import models
import jsonfield

class MyModel(models.Model):
    the_json = jsonfield.JSONField()
</code>```

hstorefield iff you're using PostgreSQL

A field for storing mappings of strings to strings. The Python data
  type used is a dict.

```<code>from django.contrib.postgres.fields import HStoreField
from django.db import models

class Dog(models.Model):
    name = models.CharField(max_length=200)
    data = HStoreField()

Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
</code>```

Body:
I have a fairly simple user-model perfectly working.
In order to reduce code redundancy, I try to store fields inside a dictory for reasons you can easily guess.

Example:

def get_social_token(self,social_net=""):
   return self.social_dict[social_net]["token"]

If I don't do such a structure I must do some "if/then ... elif... else".
And of course I need to modify my code whenever I decide to add a new social network to my app.

I have tried two different approaches, both of them give me the same result:

No error

No field is actually detected and created in the DB

I'd like to mention that if I use a "conventional manner" to implement this behaviour such as:

twitter_social_token = EncryptedCharField(max_length=500, default='', blank=True, null=True)

It perfectly works, so it comes from the use of a dictionary.

Any idea to solve this ?
Btw. I would prefer avoiding using a new model and a foreign key... Only a One-to-One association, I would prefer not having to perform any "join" or select in another table...

Bellow, you'll find the two attempts I made which doesn't work (and I don't know why):

First attempt:

social_fields = {
    'twitter' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'facebook' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'gplus' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'linkedin' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
}

Second attempt:

social_tokens = dict()

social_tokens["twitter"] = dict()
social_tokens["facebook"] = dict()
social_tokens["linkedin"] = dict()
social_tokens["gplus"] = dict()

social_tokens["twitter"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["twitter"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["facebook"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["facebook"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["linkedin"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["linkedin"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["gplus"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["gplus"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

Thanks for the help dear friends,

Jonathan

Body:
As far as I know, without using join you have 3 different way:

django-picklefield

django-picklefield provides an implementation of a pickled object
  field. Such fields can contain any picklable objects.

From their documentation, to use; just define a field in your model:

>>> from picklefield.fields import PickledObjectField
... class SomeObject(models.Model):
...     args = PickledObjectField()

and assign whatever you like (as long as it’s picklable) to the field:

>>> obj = SomeObject()
>>> obj.args = ['fancy', {'objects': 'inside'}]
>>> obj.save()

django-jsonfield

django-jsonfield is a reusable Django field that allows you to store
  validated JSON in your model.
  It silently takes care of serialization. To use, simply add the field
  to one of your models.

To use, just install the package, and then use the field:

from django.db import models
import jsonfield

class MyModel(models.Model):
    the_json = jsonfield.JSONField()

hstorefield iff you're using PostgreSQL

A field for storing mappings of strings to strings. The Python data
  type used is a dict.

from django.contrib.postgres.fields import HStoreField
from django.db import models

class Dog(models.Model):
    name = models.CharField(max_length=200)
    data = HStoreField()

Dog.objects.create(name='Rufus', data={'breed': 'labrador'})


问:
How to register singleton qml type with std function for a callback in Qt?
Is there a way to register a singleton qml type using custom std function for a callback? If there is not, are there particular reasons for not allowing it?
In Qt docmentation I could only find  qmlRegisterSingletonType which take function pointer.

Thanks

答:
If there is not, are there particular reasons for not allowing it?

Because it affects Qt's binary compatibility promise. This thread on the development mailing list explains it:

Hi,

I understand that there are limitations (to put it mildly) regarding the use
    of API from the C++ standard library in Qt API itself due to the inability
    to extend our binary compatibility promise. I'm curious though whether
    std::function falls under the same umbrella?

Yes, it does: the binary representation (including size), or the
  mangling is  not guaranteed to be the same across stdlib
  implementations.

So here are the choice:

1- Re-implement QFunction, with similar semantic as std::function.

2- Lift the constraint that we can't use the stdlib in our ABI

3- Do nothing and keep using awkward interface when we need callback.

#3 is, as usual, the easier (status quo) and will probably happen. #1 is a  somewhat difficult task, but not that hard. We will just end up
  with a poor  copy of std::function. #2 was always dismissed in the
  past, but I think it  should be seriously considered.

(The same applies to std::unique_ptr, too)

I understand that we permit the use of std::function in Windows specific API
    of QProcess, which may or may not be different. However I'm curious about
    this in the context of API that is intended to be fully cross-platform.

Actually, this is breaking the policy. Even on Windows, there are
  different  std lib implementations.


问:
get key and parameter values of json
I want to get the individual values of JSON Object keys as well as of its elements too with the help of the iteration

My json will looks like this:-

```<code>var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}
</code>```

答:
You can retrieve the [keys] and [values] of your {a} object dynamically like this:

```<code>for (var sIndexKey in a) {
    if (a.hasOwnProperty(sIndexKey) === true) {
        var oJsonData = a[sIndexKey]; // in this case the 2 objects inside your {a} object
        var sObjectKeys = Object.keys(oJsonData); //e.g atomic_number / abbreviation / atomic_weight
        for (var iIndex = 0; iIndex < sObjectKeys.length; iIndex++) {
            var sJsonKeys = sObjectKeys[iIndex];
            var sJsonValues = oJsonData[sJsonKeys];
            console.log(sJsonKeys);
            console.log(sJsonValues);
        }
    }
}
</code>```

Here's a jsfiddle for further reference: http://jsfiddle.net/q37ehka9/

Hope this helps for your case

Title: get key and parameter values of json

Body:
I want to get the individual values of JSON Object keys as well as of its elements too with the help of the iteration

My json will looks like this:-

var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}

Body:
You can retrieve the [keys] and [values] of your {a} object dynamically like this:

for (var sIndexKey in a) {
    if (a.hasOwnProperty(sIndexKey) === true) {
        var oJsonData = a[sIndexKey]; // in this case the 2 objects inside your {a} object
        var sObjectKeys = Object.keys(oJsonData); //e.g atomic_number / abbreviation / atomic_weight
        for (var iIndex = 0; iIndex < sObjectKeys.length; iIndex++) {
            var sJsonKeys = sObjectKeys[iIndex];
            var sJsonValues = oJsonData[sJsonKeys];
            console.log(sJsonKeys);
            console.log(sJsonValues);
        }
    }
}

Here's a jsfiddle for further reference: http://jsfiddle.net/q37ehka9/

Hope this helps for your case


问:
regex pattern to match current directory in dir output
I try to extract the creation date of a specific directory from the output produced by the dir command in Windows.

Example:

dir c:\folder\Myfolder\ /T:C /A:D

Output:

```<code>22-11-2013  15:09    <DIR>          .
22-11-2013  15:09    <DIR>          ..
21-03-2015  14:32    <DIR>          Folder1
12-09-2014  11:03    <DIR>          Folder2
18-10-2016  13:29    <DIR>          Folder3
</code>```

I tried to pipe the output to findstr in order to use a regular expression. But dir c:\folder\Myfolder\ /T:C /A:D | findstr \r "\." shows both the . and .. lines.

What I need is the date and time of Myfolder (i.e. line with the single .) in order to create a timestamp for this folder.

答:
```<code>dir c:\folder\Myfolder\ /ad /t:c|findstr /L /e /c:" ."
</code>```

should yield your desireed data

findstr /L literal /e at end /c:" ." constant string Space.

Body:
I try to extract the creation date of a specific directory from the output produced by the dir command in Windows.

Example:

dir c:\folder\Myfolder\ /T:C /A:D

Output:

22-11-2013  15:09    <DIR>          .
22-11-2013  15:09    <DIR>          ..
21-03-2015  14:32    <DIR>          Folder1
12-09-2014  11:03    <DIR>          Folder2
18-10-2016  13:29    <DIR>          Folder3

I tried to pipe the output to findstr in order to use a regular expression. But dir c:\folder\Myfolder\ /T:C /A:D | findstr \r "\." shows both the . and .. lines.

What I need is the date and time of Myfolder (i.e. line with the single .) in order to create a timestamp for this folder.

Body:
dir c:\folder\Myfolder\ /ad /t:c|findstr /L /e /c:" ."

should yield your desireed data

findstr /L literal /e at end /c:" ." constant string Space.


问:
Get URL headers without the HTML
A bit of a strange question. Is there a way to ask a webserver to return only the headers and not the HTML itself ?

I want to ask a server for a URL and see if its valid (not 404/500/etc) and follow the redirections (if present) but not get the actual HTML content.

Thanks

Preferably a way to do this in Ruby

答: Use Ruby's net/http and the HEAD method that Mak mentioned. Check ri Net::HTTP#head from the command line for info.

Title: Get URL headers without the HTML


答:
```<code>var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}

  for (i=0;i<1;i++)
  {
  console.log(Object.keys(a)[i])
  console.log(a[Object.keys(a)[i]].atomic_number)
  console.log(a[Object.keys(a)[i]].atomic_weight)
  console.log(a[Object.keys(a)[i]].abbreviation)
}
</code>```

Title: get key and parameter values of json


问:
Is it possible to create a selector that accesses multiple branches of the state tree?
I am working on a Redux project with a bunch of reducers that are combined

```<code>const rootReducer = combineReducers({
    reducer1,
    reducer2,
    ...
});
</code>```

The reducers each update a branch of the store

```<code>sampleStore = {
    reducer1: {a1: 7, b1: 5, c1: 6, ...},
    reducer2: {a2: 3, b2: 2, c2: 9, ...},
    reducer3: {a3: 1, b3: 4, c3: 2, ...},
    ...
}
</code>```

Now I am trying to add logic that requires access to both branches of the store without restructuring the entire project. For instance, I want a reducer with the ability to perform: set c3 = f(a1, a2).

At the moment I am trying to use reselect but I am getting lost. In reducer1/selector.js I have

```<code>export const derivedVariableSelector = createSelector(
    a1Selector,
    a2Selector,
    (a1, a2) => a1 + a2
);
</code>```

And I am trying to create a reducer

```<code>function setC3(state) {
    return Object.assign({}, state, {
        c3: state.c3 + derivedVariableSelector(state)
    });
}
</code>```

However, when setC3 is called, derivedVariableSelector will never receive enough of the store to do its job. Either it will receive the branch containing a1 or the branch containing a2, but I don't know of a way to supply both. Is this possible?

答:
The short answer is "No", so long as you're using combineReducers to combine all your reducers.

The longer answer is taken from the redux documentation:

The combineReducers utility included with Redux is very useful, but is
  deliberately limited to handle a single common use case: updating a
  state tree that is a plain Javascript object, by delegating the work
  of updating each slice of state to a specific slice reducer. It does
  not handle other use cases, such as a state tree made up of
  Immutable.js Maps, trying to pass other portions of the state tree as
  an additional argument to a slice reducer, or performing "ordering" of
  slice reducer calls. It also does not care how a given slice reducer
  does its work.

The common question, then, is "How can I use combineReducers to handle
  these other use cases?". The answer to that is simply: "you don't -
  you probably need to use something else". Once you go past the core
  use case for combineReducers, it's time to use more "custom" reducer
  logic, whether it be specific logic for a one-off use case, or a
  reusable function that could be widely shared.

On the same page of the docs are some suggestions for how the create reducers that share more of the state but it's going to be a bit more manual than comibineReducers is.

I haven't tried anything like this myself before, but following examples in the docs, something like this might work for you:

```<code>import { combineReducers } from 'redux'
import reduceReducers from 'reduce-reducers'

const reducer1 = (state = {}, action) => {
    switch (action.type) {
        // handle actions
        default:
            return state
    }
}

const reducer2 = (state = {}, action) => {
    switch (action.type) {
        // handle actions
        default:
            return state
    }
}

const reducer3 = (state) => {
    return {
        ...state,
        // use the root state for the reducerC value
        reducerC: makeValue(state.reducer1, state.reducer2)
    }
}

const rootReducer = reduceReducers(combineReducers({reducer1, reducer2}), reducer3)
</code>```

This uses the library reduce-reducers to combine reducers in a different way.

Body:
I am working on a Redux project with a bunch of reducers that are combined

const rootReducer = combineReducers({
    reducer1,
    reducer2,
    ...
});

The reducers each update a branch of the store

sampleStore = {
    reducer1: {a1: 7, b1: 5, c1: 6, ...},
    reducer2: {a2: 3, b2: 2, c2: 9, ...},
    reducer3: {a3: 1, b3: 4, c3: 2, ...},
    ...
}

Now I am trying to add logic that requires access to both branches of the store without restructuring the entire project. For instance, I want a reducer with the ability to perform: set c3 = f(a1, a2).

At the moment I am trying to use reselect but I am getting lost. In reducer1/selector.js I have

export const derivedVariableSelector = createSelector(
    a1Selector,
    a2Selector,
    (a1, a2) => a1 + a2
);

And I am trying to create a reducer

function setC3(state) {
    return Object.assign({}, state, {
        c3: state.c3 + derivedVariableSelector(state)
    });
}

However, when setC3 is called, derivedVariableSelector will never receive enough of the store to do its job. Either it will receive the branch containing a1 or the branch containing a2, but I don't know of a way to supply both. Is this possible?

Body:
The short answer is "No", so long as you're using combineReducers to combine all your reducers.

The longer answer is taken from the redux documentation:

The combineReducers utility included with Redux is very useful, but is
  deliberately limited to handle a single common use case: updating a
  state tree that is a plain Javascript object, by delegating the work
  of updating each slice of state to a specific slice reducer. It does
  not handle other use cases, such as a state tree made up of
  Immutable.js Maps, trying to pass other portions of the state tree as
  an additional argument to a slice reducer, or performing "ordering" of
  slice reducer calls. It also does not care how a given slice reducer
  does its work.

The common question, then, is "How can I use combineReducers to handle
  these other use cases?". The answer to that is simply: "you don't -
  you probably need to use something else". Once you go past the core
  use case for combineReducers, it's time to use more "custom" reducer
  logic, whether it be specific logic for a one-off use case, or a
  reusable function that could be widely shared.

On the same page of the docs are some suggestions for how the create reducers that share more of the state but it's going to be a bit more manual than comibineReducers is.

I haven't tried anything like this myself before, but following examples in the docs, something like this might work for you:

import { combineReducers } from 'redux'
import reduceReducers from 'reduce-reducers'

const reducer1 = (state = {}, action) => {
    switch (action.type) {
        // handle actions
        default:
            return state
    }
}

const reducer2 = (state = {}, action) => {
    switch (action.type) {
        // handle actions
        default:
            return state
    }
}

const reducer3 = (state) => {
    return {
        ...state,
        // use the root state for the reducerC value
        reducerC: makeValue(state.reducer1, state.reducer2)
    }
}

const rootReducer = reduceReducers(combineReducers({reducer1, reducer2}), reducer3)

This uses the library reduce-reducers to combine reducers in a different way.


问:
Array to string conversion when seeding a table
When trying to seed a table, it's showing an 'array to string conversion' error.

This is the output of the error:

```<code>[Illuminate\Database\QueryException]
Array to string conversion (SQL: insert into `reviews` (`user_id`, `name`, `location`, `header`, `comments`, `identifier`, `stars`, `privacy`, `actioned`, `appr
oved`, `created_at`) values (10, Bradley Davis, Paulastad, Commodi quas expedita eum., Voluptas magni iusto nemo ea vitae harum quasi., 6c621319-c6ba-41c1-bb0b-696b602470
ef, 5, 1, 0, 1, 2017-03-25 11:44:12))
</code>```

Table structure:

```<code>Schema::create('reviews', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('name')->nullable();
    $table->string('location')->nullable();
    $table->string('header')->nullable();
    $table->string('comments')->nullable();
    $table->uuid('identifier');
    $table->integer('stars')->nullable();
    $table->boolean('privacy')->default('1');
    $table->boolean('actioned')->default('0');
    $table->boolean('approved')->default('0');
    $table->nullableTimestamps();
});
</code>```

Seed function:

```<code>for ($i = 1; $i < 41; $i++) {

    $name = User::where('id', $i + 9)->pluck('name')->all();
    $uuid = Uuid::generate(4);

    $review = [
        'user_id' => $i + 9,
        'name' => $name,
        'location' => $faker->city,
        'header' => $faker->sentence($nbWords = 3, $variableNbWords = true),
        'comments' => $faker->text($maxNbChars = 50),
        'identifier' => $uuid,
        'stars' => [1, 2, 3, 4, 5][rand(0, count([1, 2, 3, 4, 5]) - 1)],
        'privacy' => [1, 0][rand(0, count([1, 0]) - 1)],
        'actioned' => [1, 0][rand(0, count([1, 0]) - 1)],
        'approved' => [0, 1][rand(0, count([0, 1]) - 1)],
        'created_at' => Carbon::now()->subWeeks(array_rand([2, 3, 4, 5, 6, 7], 1))
   ];
}

DB::table('reviews')->insert($review);
</code>```

print_r($review):

```<code>Array
(
    [user_id] => 10
    [name] => Array
        (
            [0] => David Robertson
        )

    [location] => Lake Suzannechester
    [header] => Repellendus aut alias exercitationem.
    [comments] => Sunt non temporibus pariatur totam aut qui.
    [identifier] => Webpatser\Uuid\Uuid Object
        (
            [bytes:protected] => �a�?�IB��"�mLC�
            [hex:protected] =>
            [string:protected] => d51961bb-3fcf-4942-a0d9-22a56d4c4392
            [urn:protected] =>
            [version:protected] =>
            [variant:protected] =>
            [node:protected] =>
            [time:protected] =>
        )

    [stars] => 4
    [privacy] => 1
    [actioned] => 1
    [approved] => 1
    [created_at] => Carbon\Carbon Object
        (
            [date] => 2017-03-04 12:04:01.225487
            [timezone_type] => 3
            [timezone] => UTC
        )

)
</code>```

答:
As you see there are multiple problems here, for example $name doesn't hold name, but it holds the array, you should use:

```<code>$name = User::find($i + 9)->name;
</code>```

instead.

Similar is for $uuid - it should return string instead of some object.

Also when I look at this part:

```<code>'stars' => [1, 2, 3, 4, 5][rand(0, count([1, 2, 3, 4, 5]) - 1)],
'privacy' => [1, 0][rand(0, count([1, 0]) - 1)],
'actioned' => [1, 0][rand(0, count([1, 0]) - 1)],
'approved' => [0, 1][rand(0, count([0, 1]) - 1)],
'created_at' => Carbon::now()->subWeeks(array_rand([2, 3, 4, 5, 6, 7], 1))
</code>```

it's far too complicated.

You could use here something like this:

```<code>'stars' => rand(1, 5),
'privacy' => rand(0, 1),
'actioned' => rand(0, 1),
'approved' => rand(0, 1),
'created_at' => Carbon::now()->subWeeks(rand(2, 7))->toDateTimeString(),
</code>```

Also:

```<code>DB::table('reviews')->insert($review);
</code>```

do you use it outside of loop? If so, it does not make much sense, as in each loop run you set it again. However if you do it inside loop, you could also optimized this to not run so many inserts (obviously for 41 records it won't make much difference but for thousands it would do).

Body:
When trying to seed a table, it's showing an 'array to string conversion' error.

This is the output of the error:

[Illuminate\Database\QueryException]
Array to string conversion (SQL: insert into `reviews` (`user_id`, `name`, `location`, `header`, `comments`, `identifier`, `stars`, `privacy`, `actioned`, `appr
oved`, `created_at`) values (10, Bradley Davis, Paulastad, Commodi quas expedita eum., Voluptas magni iusto nemo ea vitae harum quasi., 6c621319-c6ba-41c1-bb0b-696b602470
ef, 5, 1, 0, 1, 2017-03-25 11:44:12))

Table structure:

Schema::create('reviews', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('name')->nullable();
    $table->string('location')->nullable();
    $table->string('header')->nullable();
    $table->string('comments')->nullable();
    $table->uuid('identifier');
    $table->integer('stars')->nullable();
    $table->boolean('privacy')->default('1');
    $table->boolean('actioned')->default('0');
    $table->boolean('approved')->default('0');
    $table->nullableTimestamps();
});

Seed function:

for ($i = 1; $i < 41; $i++) {

    $name = User::where('id', $i + 9)->pluck('name')->all();
    $uuid = Uuid::generate(4);

    $review = [
        'user_id' => $i + 9,
        'name' => $name,
        'location' => $faker->city,
        'header' => $faker->sentence($nbWords = 3, $variableNbWords = true),
        'comments' => $faker->text($maxNbChars = 50),
        'identifier' => $uuid,
        'stars' => [1, 2, 3, 4, 5][rand(0, count([1, 2, 3, 4, 5]) - 1)],
        'privacy' => [1, 0][rand(0, count([1, 0]) - 1)],
        'actioned' => [1, 0][rand(0, count([1, 0]) - 1)],
        'approved' => [0, 1][rand(0, count([0, 1]) - 1)],
        'created_at' => Carbon::now()->subWeeks(array_rand([2, 3, 4, 5, 6, 7], 1))
   ];
}

DB::table('reviews')->insert($review);

print_r($review):

Array
(
    [user_id] => 10
    [name] => Array
        (
            [0] => David Robertson
        )

    [location] => Lake Suzannechester
    [header] => Repellendus aut alias exercitationem.
    [comments] => Sunt non temporibus pariatur totam aut qui.
    [identifier] => Webpatser\Uuid\Uuid Object
        (
            [bytes:protected] => �a�?�IB��"�mLC�
            [hex:protected] =>
            [string:protected] => d51961bb-3fcf-4942-a0d9-22a56d4c4392
            [urn:protected] =>
            [version:protected] =>
            [variant:protected] =>
            [node:protected] =>
            [time:protected] =>
        )

    [stars] => 4
    [privacy] => 1
    [actioned] => 1
    [approved] => 1
    [created_at] => Carbon\Carbon Object
        (
            [date] => 2017-03-04 12:04:01.225487
            [timezone_type] => 3
            [timezone] => UTC
        )

)

Body:
As you see there are multiple problems here, for example $name doesn't hold name, but it holds the array, you should use:

$name = User::find($i + 9)->name;

instead.

Similar is for $uuid - it should return string instead of some object.

Also when I look at this part:

'stars' => [1, 2, 3, 4, 5][rand(0, count([1, 2, 3, 4, 5]) - 1)],
'privacy' => [1, 0][rand(0, count([1, 0]) - 1)],
'actioned' => [1, 0][rand(0, count([1, 0]) - 1)],
'approved' => [0, 1][rand(0, count([0, 1]) - 1)],
'created_at' => Carbon::now()->subWeeks(array_rand([2, 3, 4, 5, 6, 7], 1))

it's far too complicated.

You could use here something like this:

'stars' => rand(1, 5),
'privacy' => rand(0, 1),
'actioned' => rand(0, 1),
'approved' => rand(0, 1),
'created_at' => Carbon::now()->subWeeks(rand(2, 7))->toDateTimeString(),

Also:

DB::table('reviews')->insert($review);

do you use it outside of loop? If so, it does not make much sense, as in each loop run you set it again. However if you do it inside loop, you could also optimized this to not run so many inserts (obviously for 41 records it won't make much difference but for thousands it would do).


问:
Python socket reconnecting
I have a socket program and I want to keep the connection running all the time, if someone disconnects I want to start listening to a new connection and keep the program running.

I used this code:

```<code>import socket

socket = socket.socket()
socket.bind(('127.0.0.1', 80))
socket.listen(1)
(con, address) = socket.accept()
while con.recv(1024) != b'exit':
    pass
else:
    con.close()
    socket.listen(1)
    (con, address) = socket.accept()
</code>```

However, after the else clause the program runs further and the while statement will not run again and I do want the while statement to repeat itself. How can I achieve this?

答:
simply make a containing loop...</p>

```<code>import socket

while True:
    socket = socket.socket()
    socket.bind(('127.0.0.1', 80))
    socket.listen(1)
    (con, address) = socket.accept()
    while con.recv(1024) != b'exit':
        pass
    else:
        con.close()
</code>```

Title: Python socket reconnecting

Body:
I have a socket program and I want to keep the connection running all the time, if someone disconnects I want to start listening to a new connection and keep the program running.

I used this code:

import socket

socket = socket.socket()
socket.bind(('127.0.0.1', 80))
socket.listen(1)
(con, address) = socket.accept()
while con.recv(1024) != b'exit':
    pass
else:
    con.close()
    socket.listen(1)
    (con, address) = socket.accept()

However, after the else clause the program runs further and the while statement will not run again and I do want the while statement to repeat itself. How can I achieve this?

Body:
simply make a containing loop...

import socket

while True:
    socket = socket.socket()
    socket.bind(('127.0.0.1', 80))
    socket.listen(1)
    (con, address) = socket.accept()
    while con.recv(1024) != b'exit':
        pass
    else:
        con.close()


问:
I am performing ngclick show hide but can't get any output
i am using angular 1.6 and trying to perform ng-click hide show of profile data but anyhow i dont know where i am going wrong.
here the code

```<code><div class="col-sm-12 col-lg-10" ng-controller="profile">
<div class="text-center">
    <div class="col-sm-12">
    <div class="pull-right">
        <a ng-click="edit-form = ! edit-form"> <i class="fa fa-pencil fa-2x" style="cursor:pointer;color:#f7972f;"> </i> </a>
    </div>
        <div class="image-upload edit-picture">
            <label for="file-input">
                <i class="fa fa-camera fa-2x" style="cursor:pointer;color:#f7972f;"> </i>
            </label>
            <input id="file-input" type="file"/>
        </div>
        <img src="amit.jpg" class="img img-circle edit-image" style="width:150px;">
        <h3> Amit Singh Chauhan </h3>
    </div>
    <div class="col-sm-12" ng-show="edit-form">
        <div class="col-sm-1"></div>
        <div class="col-sm-10" >
        <form action="" novalidate="novalidate">
            <p><span class="wpcf7-form-control-wrap first-name"><input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="First Name"></span></p>
            <p><span class="wpcf7-form-control-wrap last-name"><input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name"></span></p>
            <p><span class="wpcf7-form-control-wrap email-address"><input type="email" name="email-address" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address"></span></p>
            <div><span class="wpcf7-form-control-wrap your-message"><textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Comment"></textarea></span></div>
            <div><input type="submit" value="Save Profile" class="wpcf7-form-control wpcf7-submit mkd-contact3"><span class="ajax-loader"></span></div>
        </form>
        </div>
        <div class="col-sm-1"></div>
    </div>
</div>
</code>```

```<code> <script>
     var app = angular.module("myApp", []).controller ("profile",  function         ($scope){
 });
</script>
</code>```

答: Try changing edit-form to editForm.

Body:
i am using angular 1.6 and trying to perform ng-click hide show of profile data but anyhow i dont know where i am going wrong.
here the code

            <input id="file-input" type="file"/>

 Amit Singh Chauhan

        <form action="" novalidate="novalidate">

<input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="First Name">

<input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name">

<input type="email" name="email-address" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address">

<textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Comment"></textarea>

<input type="submit" value="Save Profile" class="wpcf7-form-control wpcf7-submit mkd-contact3">

        </form>

Body: Try changing edit-form to editForm.


问:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled
I, for the life of me, can't get rid of this error message. I have tried almost everything that I can.

MyDBContext.cs

```<code>        public MyDBContext() : base("ConnStr_Dev")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, DbMigrationsConfiguration<MyDBContext>>());
        //Database.SetInitializer<MyDBContext>(null);
        base.OnModelCreating(modelBuilder);
    }
</code>```

GenericRepository.cs

```<code>        public void Insert(T obj)
    {
        table.Add(obj);      //this is where it throws the error, inserting first time.
    }
</code>```

Tried all of these in different combinations

Enable-Migrations -EnableAutomaticMigrations -Force

Add-migration Initial -IgnoreChanges

Update-Database

I have tried deleting the Migrations table, deleting the entire database, everything.

Any Migrations experts please?

Edit: the DAL contains the GenericRepository and the context class.

答:
Delete your Migrations folder from your solution

Delete the dbo.__MigrationHistory table from your database

Open Package Manager Console and Enable-Migrations

Add your initial migration Add-Migration Initial

Update-Database

Done

Body:
I, for the life of me, can't get rid of this error message. I have tried almost everything that I can.

MyDBContext.cs

        public MyDBContext() : base("ConnStr_Dev")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, DbMigrationsConfiguration<MyDBContext>>());
        //Database.SetInitializer<MyDBContext>(null);
        base.OnModelCreating(modelBuilder);
    }

GenericRepository.cs

        public void Insert(T obj)
    {
        table.Add(obj);      //this is where it throws the error, inserting first time.
    }

Tried all of these in different combinations

Enable-Migrations -EnableAutomaticMigrations -Force

Add-migration Initial -IgnoreChanges

Update-Database

I have tried deleting the Migrations table, deleting the entire database, everything.

Any Migrations experts please?

Edit: the DAL contains the GenericRepository and the context class.


问:
initialize static pointer array c++
I have my class:

```<code>class Exec {
  static Process* procs_table[];

 public:
 Exec(int num, info_init_proc* proc);
};
</code>```

info_init_proc is a custom struct with information necessary for initializing the Process object

And try to create the constructor as below:

```<code>Exec::Exec(int num, info_init_proc* proc) {
   int i;
   for (i = 0; i < num; i++) {
     Exec::procs_table[i] = new Process(proc[i]);
  }
}
</code>```

It can be compiled, but when i build i get the "Undefined symbol procs_table" error.

What should be modified ?

答:
The immediate problem is that your static array is declared, but not defined. Adding this line to your CPP file will fix that:

```<code>Process* Exec::procs_table[SOME_MAX_VALUE];
</code>```

However, it appears that the choice of static is fundamentally incorrect here, because you do not know n, the size of the allocation, until run-time. In this situation a singleton object with std::vector of process pointers would be more appropriate.

Title: initialize static pointer array c++

Body:
I have my class:

class Exec {
  static Process* procs_table[];

 public:
 Exec(int num, info_init_proc* proc);
};

info_init_proc is a custom struct with information necessary for initializing the Process object

And try to create the constructor as below:

Exec::Exec(int num, info_init_proc* proc) {
   int i;
   for (i = 0; i < num; i++) {
     Exec::procs_table[i] = new Process(proc[i]);
  }
}

It can be compiled, but when i build i get the "Undefined symbol procs_table" error.

What should be modified ?

Body:
The immediate problem is that your static array is declared, but not defined. Adding this line to your CPP file will fix that:

Process* Exec::procs_table[SOME_MAX_VALUE];

However, it appears that the choice of static is fundamentally incorrect here, because you do not know n, the size of the allocation, until run-time. In this situation a singleton object with std::vector of process pointers would be more appropriate.


问:
Return identity of last inserted row from stored procedure
I am trying to return identity of last inserted row from a stored procedure.

A simplified version of my code looks like this:

```<code>CREATE PROCEDURE [sp_name]
    @AuthorisationCode uniqueidentifier
AS
    INSERT INTO [tablename]
           ([AuthorisationCode]
           )
     VALUES
           (@AuthorisationCode
           )

 RETURN @@IDENTITY

GO
</code>```

I am calling this stored procedure via Execute Scalar in Enterprise library 4.1.

It returns null. Anybody see what I am doing wrong.

答:
You should use select rather than return, but you should also use SCOPE_IDENTITY to prevent issues with the wrong identity being returned, @@IDENTITY is not limited to a specific scope.

```<code>SELECT SCOPE_IDENTITY()
</code>```

More information can be found here:

http://msdn.microsoft.com/en-us/library/ms190315.aspx

Body:
I am trying to return identity of last inserted row from a stored procedure.

A simplified version of my code looks like this:

CREATE PROCEDURE [sp_name]
    @AuthorisationCode uniqueidentifier
AS
    INSERT INTO [tablename]
           ([AuthorisationCode]
           )
     VALUES
           (@AuthorisationCode
           )

 RETURN @@IDENTITY

GO

I am calling this stored procedure via Execute Scalar in Enterprise library 4.1.

It returns null. Anybody see what I am doing wrong.

Body:
You should use select rather than return, but you should also use SCOPE_IDENTITY to prevent issues with the wrong identity being returned, @@IDENTITY is not limited to a specific scope.

SELECT SCOPE_IDENTITY()

More information can be found here:

http://msdn.microsoft.com/en-us/library/ms190315.aspx


问:
How can the gradle plugin repository be changed?
I work at a big company with a strict policy forbidding the unfiltered use of outside libraries. We have to pull everything from blessed corporate repositories, and not the bare internet, including gradle.org.

Using gradle's original apply plugin syntax, in conjunction with a buildscript block, I can add (blessed) plugins to our repo and use them in builds. In other words:

```<code>buildscript {
    repositories {
        maven { url "https://privaterepo.myemployer.com" }
    }

    dependencies {
        // various dependencies
        classpath "org.something:some-plugin:1.0"
        ...
    }

apply plugin: "someplugin"
</code>```

Instead, I want to be able to use the new plugins DSL, i.e.

```<code>plugins {
    id 'org.something.some-plugin' version '1.0'
}
</code>```

(I realize that the private repo url would need to be defined somewhere)

The new plugin syntax always goes to gradle.org and does not appear to have any means to provide an alternate download url. Does anyone know of a way?

I've scrutinized the documentation and the Internet and can't find the answer. Apologies if the answer is completely obvious.

Many Thanks!

答:
It`s need to define pluginRepositories in settings Gradle

https://docs.gradle.org/current/userguide/plugins.html#sec:custom_plugin_repositories

The pluginRepositories {} block may only appear in the settings.gradle file, and must be the first block in the file.

```<code>pluginRepositories {
  maven {
    url 'maven-repo'
  }
  gradlePluginPortal()
  ivy {
    url 'ivy-repo'
  }
}
</code>```

Body:
I work at a big company with a strict policy forbidding the unfiltered use of outside libraries. We have to pull everything from blessed corporate repositories, and not the bare internet, including gradle.org.

Using gradle's original apply plugin syntax, in conjunction with a buildscript block, I can add (blessed) plugins to our repo and use them in builds. In other words:

buildscript {
    repositories {
        maven { url "https://privaterepo.myemployer.com" }
    }

    dependencies {
        // various dependencies
        classpath "org.something:some-plugin:1.0"
        ...
    }

apply plugin: "someplugin"

Instead, I want to be able to use the new plugins DSL, i.e.

plugins {
    id 'org.something.some-plugin' version '1.0'
}

(I realize that the private repo url would need to be defined somewhere)

The new plugin syntax always goes to gradle.org and does not appear to have any means to provide an alternate download url. Does anyone know of a way?

I've scrutinized the documentation and the Internet and can't find the answer. Apologies if the answer is completely obvious.

Many Thanks!

Body:
It`s need to define pluginRepositories in settings Gradle

https://docs.gradle.org/current/userguide/plugins.html#sec:custom_plugin_repositories

The pluginRepositories {} block may only appear in the settings.gradle file, and must be the first block in the file.

pluginRepositories {
  maven {
    url 'maven-repo'
  }
  gradlePluginPortal()
  ivy {
    url 'ivy-repo'
  }
}


问:
PHP Log in page with hashed password issue
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.

```<code><?php

session_start();
include 'databaseconnection.php';

$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);

$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);

if ($hash == 0) {
  header("Location: error.php")
  exit();
} else {

$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);

if (!row = mysqli_fetch_assoc($result)); {
  echo "your email address or password is incorrect!";
} else {
  $_SESSION['id'] = $row['id'];
}

header("Location: profile.php")
</code>```

If someone could simply suggest what changes I should make, I would really appreciate it.

答:
There you go simple code</p>

```<code><?php

session_start();
include 'databaseconnection.php';

$email = $_POST['email'];
$pwd = $_POST['pwd'];

$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database

// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
    $_SESSION['id'] = $row['id'];
    header('Location: profile.php');
}
else
{
    header("Location: error.php")
    exit();
}

?>
</code>```

Body:
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.

<?php

session_start();
include 'databaseconnection.php';

$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);

$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);

if ($hash == 0) {
  header("Location: error.php")
  exit();
} else {

$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);

if (!row = mysqli_fetch_assoc($result)); {
  echo "your email address or password is incorrect!";
} else {
  $_SESSION['id'] = $row['id'];
}

header("Location: profile.php")

If someone could simply suggest what changes I should make, I would really appreciate it.

Body:
There you go simple code

<?php

session_start();
include 'databaseconnection.php';

$email = $_POST['email'];
$pwd = $_POST['pwd'];

$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database

// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
    $_SESSION['id'] = $row['id'];
    header('Location: profile.php');
}
else
{
    header("Location: error.php")
    exit();
}

?>


问:
SQL export to ListView using C#
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

```<code>string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}
</code>```

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

```<code>foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}
</code>```

答:
The following assumes that your ListView has columns in the order |Pro|Size|Date|</p>

```<code>foreach (DataRow row in poplb6ds.Tables[0].Rows) {
    ListViewItem item = new ListViewItem(row["Pro"].ToString());
    item.SubItems.Add(row["size"].ToString());
    item.SubItems.Add(row["Date"].ToString());
    listView1.Items.Add(item);
}
</code>```

Title: SQL export to ListView using C#

Body:
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}

Body:
The following assumes that your ListView has columns in the order |Pro|Size|Date|

foreach (DataRow row in poplb6ds.Tables[0].Rows) {
    ListViewItem item = new ListViewItem(row["Pro"].ToString());
    item.SubItems.Add(row["size"].ToString());
    item.SubItems.Add(row["Date"].ToString());
    listView1.Items.Add(item);
}


问:
Angular localStorage array keeps getting reset on page refresh
Objective:

I want the  localStorage cached  answers array to be prepopulated only by the contents of the 4 object  var questions array  the first time it is loaded
on subsequent page refreshes I want the modified localStorage answers array to be loaded  e.g. there may be many more objects or spliced objects in array

At the moment every time I page refresh it reverts back to the original  4 object array .

```<code> var questions = [{"id":9,"Index":9,"Answered":"No","Correct":"?"},{"id":10,"Index":10,"Answered":"No","Correct":"?"},{"id":11,"Index":11,"Answered":"No","Correct":"?"},{"id":12,"Index":12,"Answered":"No","Correct":"?"}];

// storing our array as a string
localStorage.setItem("answers", JSON.stringify(questions));

// retrieving our data and converting it back into an array

var retrievedData = localStorage.getItem("answers");

// Possible Solution  this intial array  gets created every time the page refreshes and needs some logic to determine
// if it's intial length if not choose existing localstorage answers array in cache

   $scope.answers = JSON.parse(localStorage.getItem('answers'))

   $scope.addAnswer = function (){
    $scope.answers.push({"id":10,"Index":10,"Answered":"Yes","Correct":"Correct"})
        $scope.newAnswer = ''
    }

   $scope.spliceAnswer = function (){
    $scope.answers.splice(1, 1, {"id":10,"Index":10,"Answered":"Yes","Correct":"InCorrect"})
    $scope.replaceAnswer = ''
  }

   $scope.$watch('answers',function(newValue, oldValue){
    if(newValue!=oldValue){
        localStorage.setItem('answers',JSON.stringify(newValue))
    }
}, true)
</code>```

HTML

```<code><form name="frm" ng-submit="addAnswer()">
    <input type="text" name="newAnswer" ng-model="newAnswer" required />
    <button >Add </button>
</form>
<form name="frm" ng-submit="spliceAnswer()">
<input type="text" name="replaceAnswer" ng-model="replaceAnswer" required />
<button >Replace </button>
</form>
<h6>Answers : {answers}</h6>
</code>```

答:
```<code>              $scope.key = ($cookieStore.get('arraySize')) ? ($cookieStore.get('arraySize')) :0 ;

$scope.$watch('key', function () {
    if($scope.key == 0) {
        localStorage.setItem("answers", JSON.stringify(questions));
    } else{
        $scope.answers = JSON.parse(localStorage.getItem('answers'));
    }
});

          $scope.$watch('answers',function(newValue, oldValue){
                if(newValue!=oldValue){
                    localStorage.setItem('answers',JSON.stringify(newValue))
                    $scope.size = (JSON.parse(localStorage.getItem('answers'))).length;
                    $cookieStore.put( 'arraySize' , $scope.size );

                }
            }, true)

            $scope.arrayLength = $cookieStore.get('arraySize');

            $scope.key = parseInt($cookieStore.get('arraySize'));
</code>```

Body:
Objective:

I want the  localStorage cached  answers array to be prepopulated only by the contents of the 4 object  var questions array  the first time it is loaded
on subsequent page refreshes I want the modified localStorage answers array to be loaded  e.g. there may be many more objects or spliced objects in array

At the moment every time I page refresh it reverts back to the original  4 object array .

 var questions = [{"id":9,"Index":9,"Answered":"No","Correct":"?"},{"id":10,"Index":10,"Answered":"No","Correct":"?"},{"id":11,"Index":11,"Answered":"No","Correct":"?"},{"id":12,"Index":12,"Answered":"No","Correct":"?"}];

// storing our array as a string
localStorage.setItem("answers", JSON.stringify(questions));

// retrieving our data and converting it back into an array

var retrievedData = localStorage.getItem("answers");

// Possible Solution  this intial array  gets created every time the page refreshes and needs some logic to determine
// if it's intial length if not choose existing localstorage answers array in cache

   $scope.answers = JSON.parse(localStorage.getItem('answers'))

   $scope.addAnswer = function (){
    $scope.answers.push({"id":10,"Index":10,"Answered":"Yes","Correct":"Correct"})
        $scope.newAnswer = ''
    }

   $scope.spliceAnswer = function (){
    $scope.answers.splice(1, 1, {"id":10,"Index":10,"Answered":"Yes","Correct":"InCorrect"})
    $scope.replaceAnswer = ''
  }

   $scope.$watch('answers',function(newValue, oldValue){
    if(newValue!=oldValue){
        localStorage.setItem('answers',JSON.stringify(newValue))
    }
}, true)

HTML

<form name="frm" ng-submit="addAnswer()">
    <input type="text" name="newAnswer" ng-model="newAnswer" required />
    <button >Add </button>
</form>
<form name="frm" ng-submit="spliceAnswer()">
<input type="text" name="replaceAnswer" ng-model="replaceAnswer" required />
<button >Replace </button>
</form>

Answers : {answers}


问:
How to spy on window.scrollTo in Jest?
I got a very simple react component with following functionallity:

```<code>componentDidMount() {
  window.scrollTo(0, 0)
}
</code>```

It seems that you cannot do something like

```<code>window.scrollTo = jest.fn()
</code>```

to spy on scrollTo function.

Therefor, I want to know what is the best way to spy on this function and assert that it has been used in my tests.

Thanks

答:
In jest the global name space must be accessed by global not window.

```<code>global.scrollTo = jest.fn()
</code>```

Title: How to spy on window.scrollTo in Jest?

Body:
I got a very simple react component with following functionallity:

componentDidMount() {
  window.scrollTo(0, 0)
}

It seems that you cannot do something like

window.scrollTo = jest.fn()

to spy on scrollTo function.

Therefor, I want to know what is the best way to spy on this function and assert that it has been used in my tests.

Thanks

Body:
In jest the global name space must be accessed by global not window.

global.scrollTo = jest.fn()


问:
How to genericly construct objects from data fetched from database
I have a database with multiple tables and corresponding objects for the table's data. For (almost) all tables I have a Model class, which handle the interaction with it's corresponding table (adding records, fetching data and instantiate an object holding the data.

All Model classes have a getById(int id) method, so I thought it would be nice to put it in a superclass (CoreModel).

But here the thing:
Since the Model classes are just a sort of interaction layers, I see no use in creating an instance of it. So I thought I make the class final and it's methods static, but then the problem arises that super() methods cannot be called from static methods.

My question: How is this usually done? I'm sorta new to OOP and am pretty baffled by the whole polymorphism thing. Are there any design patterns or standard solutions to solve this problem in a generic way?

Example code:

```<code>public final class CoreModel {

public static ResultSet getById(int id, String table){
    Statement stat = null;
    ResultSet res = null;

    try {
        stat = DatabaseModel.getStatement();
        res = stat.executeQuery("SELECT * FROM `"+table+"` WHERE `id` = " +id);

        res.next();

        stat.close();
        res.close();

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        }
    return res;
    }
}

public final class PersonModel extends CoreModel {

public static Person getById(int id) {
    ResultSet personResult = super.getById(id, "person");
    // instatiate Person object
    return personObj;
    }
}
</code>```

答:
Since the Model classes are just a sort of interaction layers, I see
  no use in creating an instance of it. So I thought I make the class
  final and it's methods static, but then the problem arises that
  super() methods cannot be called from static methods.

First thing is that your CoreModel is final class and you can't extend final classes which you did in your PersonModel and your code will not compile.

Also, it would be good to renameCoreModel as CoreDAO & PersonModel as PersonDAO (which are actually Data Access Objects) because they contain the logic to access database tables/connections/etc. (which is called as DAO layer, look here for this pattern).

In general, Model objects (like Person, Product, etc.. are plain data classes with getters/setters) which are NOT singletons whereas DAO objects (like PersonDAO, CoreDAO, etc..)  are singletons.

DAO layer classes need to be singleton (single threadsafe instance for the whole application) which hold only behavior (i.e., contain logic fetching/storing data to/from the database).

Are there any design patterns or standard solutions to solve this
  problem in a generic way?

In order to avoid the boilerplate code to load the objects (like Person, etc..) from database, you can actually use ORM (Object Relational Mapping) frameworks (implementation of JPA)  like Hibernate, spring-data-jpa, etc.. i.e.,
 these frameworks will provide you the API to load/save the objects from/to the persistent store without we directly dealing with lots of PreparedStatement and ResultSet objects.

I suggest you don't need to reinvent/rewriting this boilerplate logic, rather directly use the JPA API. One more point here is that if you use JPA, then you are NOT locked into single ORM vendor, rather you can have the portability to switch across the vendors.

Body:
I have a database with multiple tables and corresponding objects for the table's data. For (almost) all tables I have a Model class, which handle the interaction with it's corresponding table (adding records, fetching data and instantiate an object holding the data.

All Model classes have a getById(int id) method, so I thought it would be nice to put it in a superclass (CoreModel).

But here the thing:
Since the Model classes are just a sort of interaction layers, I see no use in creating an instance of it. So I thought I make the class final and it's methods static, but then the problem arises that super() methods cannot be called from static methods.

My question: How is this usually done? I'm sorta new to OOP and am pretty baffled by the whole polymorphism thing. Are there any design patterns or standard solutions to solve this problem in a generic way?

Example code:

public final class CoreModel {

public static ResultSet getById(int id, String table){
    Statement stat = null;
    ResultSet res = null;

    try {
        stat = DatabaseModel.getStatement();
        res = stat.executeQuery("SELECT * FROM `"+table+"` WHERE `id` = " +id);

        res.next();

        stat.close();
        res.close();

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        }
    return res;
    }
}

public final class PersonModel extends CoreModel {

public static Person getById(int id) {
    ResultSet personResult = super.getById(id, "person");
    // instatiate Person object
    return personObj;
    }
}


问:
Sort an array without using loops in java
How to get second maximum value from array without using nested loops in java?
For eg: int [] arr = {2,4,1,6,5,9,0,7}
        Output : 7</p>

答:
You can use array sort method easily.</p>

```<code>int [] arr = {2,4,1,6,5,9,0,7};
Arrays.sort(arr);
System.out.println(arr[arr.length - 2]);
</code>```

Body:
You can use array sort method easily.

int [] arr = {2,4,1,6,5,9,0,7};
Arrays.sort(arr);
System.out.println(arr[arr.length - 2]);


问:
What is the best way to limit the amount of text that can be entered into a 'textarea'?
What is the best way to limit the amount of text that a user can enter into a 'textarea' field on a web page? The application in question is ASP .NET, but a platform agnostic answer is preferred.

I understand that some amount of javascript is likely needed to get this done as I do not wish to actually perform the 'post' with that amount of data if possible as ASP .NET does have an upper limit to the size of the request that it will service (though I don't know what that is exactly).

So maybe the real question is, what's the best way to do this in javascript that will meet the following criteria:

-Must work equally well for both users simply typing data and copy/paste'ing data in from another source.

-Must be as '508 compliance' friendly as possible.

答: jQuery also provides some options here. Options, options, and options.</p>

OwnerDisplayName: Jesse