问:
Making Bank account in Python 3
Need help with the code below i need it to basically print out the name of the account holder and their balance when a pin is entered into the program. Also any advice would be nice in how to implement the ability to add and remove accounts from the program, any help is much appreciated.enter code here

```<code>class BankAccount:

     # constructor or initializer
    def __init__(self, name, money, pin):
         self.__name = name
         self.__balance = money   # __balance is private now, so it is only accessible inside the class
         self.__pin = pin
   def pincheck(self):
       pin = input("Enter Pin")
       if pin == self.__pin
       return True
       else:
           print("Error try again")

    def deposit(self, money):
         self.__balance += money

    def withdraw(self, money):
         if self.__balance > money :
             self.__balance -= money
             return money
         else:
             return "Insufficient funds"

    def checkbalance(self):
         return self.__balance

b1 = BankAccount('Obi Ezeakachi', 5000, 1111)
b2 = BankAccount('Tasha St.Patrick', 80000, 2222)
b3 = BankAccount('Tommy Egan', 7000, 3333)
d1 = 0
d2 = 0
d3 = 0

print("Obi Ezeakachi: £",b1.checkbalance())
y1 = int(input("Enter 1 if you want to make a withdrawal, enter 2 if you don't"))
if y1 == 1:
   w1= int(input("How much do you want to withdraw"))
   print("Withdrawal: £",b1.withdraw(w1))
else:
   d1= int(input("How much do you want to deposit"))
   b1.deposit(d1)
   print("Current Balance:",b1.checkbalance())

print("Tasha St.Patrick:",b2.checkbalance())
y1 = int(input("Enter 1 if you want to make a withdrawal, enter 2 if you don't"))
if y1 == 1:
   w2= int(input("How much do you want to withdraw"))
   print(b2.withdraw(w2))
else:
   d2= int(input("How much do you want to deposit"))
   b2.deposit(d2)

print("Tommy Egan:",b3.checkbalance())
y1 = int(input("Enter 1 if you want to make a withdrawal, enter 2 if you don't"))
if y1 == 1:
   w3= int(input("How much do you want to withdraw"))
   print("Withdrawal:",b3.withdraw(w3))
else:
   d3= int(input("How much do you want to deposit"))
   b3.deposit(d3)

print("Current Balance:",b3.checkbalance())
</code>```

答:
Consider saving all the details in a dictionary with the primary key as the name and pin & balance as secondary keys. Then, you can save it to a json file.

```<code>import json
accdict ={}
accdict['Obi'] = {'Name':'Obi Ezeakachi','Pin':1111,'Balance': 5000}
</code>```

Continue for all the accounts.

```<code>with open('accounts.json','w') as f:
     f.write(json.dumps(accdict))
</code>```

You can now manipulate this dictionary however you want and repeat.

Also, you should call the pin checker function before making a transaction. If you're serious about it and want it make it like an ATM, use threading to check for pin in the background while you access the details and interact with the user.

Title: Making Bank account in Python 3

Body:
Need help with the code below i need it to basically print out the name of the account holder and their balance when a pin is entered into the program. Also any advice would be nice in how to implement the ability to add and remove accounts from the program, any help is much appreciated.enter code here

class BankAccount:

     # constructor or initializer
    def __init__(self, name, money, pin):
         self.__name = name
         self.__balance = money   # __balance is private now, so it is only accessible inside the class
         self.__pin = pin
   def pincheck(self):
       pin = input("Enter Pin")
       if pin == self.__pin
       return True
       else:
           print("Error try again")

    def deposit(self, money):
         self.__balance += money

    def withdraw(self, money):
         if self.__balance > money :
             self.__balance -= money
             return money
         else:
             return "Insufficient funds"

    def checkbalance(self):
         return self.__balance

b1 = BankAccount('Obi Ezeakachi', 5000, 1111)
b2 = BankAccount('Tasha St.Patrick', 80000, 2222)
b3 = BankAccount('Tommy Egan', 7000, 3333)
d1 = 0
d2 = 0
d3 = 0

print("Obi Ezeakachi: £",b1.checkbalance())
y1 = int(input("Enter 1 if you want to make a withdrawal, enter 2 if you don't"))
if y1 == 1:
   w1= int(input("How much do you want to withdraw"))
   print("Withdrawal: £",b1.withdraw(w1))
else:
   d1= int(input("How much do you want to deposit"))
   b1.deposit(d1)
   print("Current Balance:",b1.checkbalance())

print("Tasha St.Patrick:",b2.checkbalance())
y1 = int(input("Enter 1 if you want to make a withdrawal, enter 2 if you don't"))
if y1 == 1:
   w2= int(input("How much do you want to withdraw"))
   print(b2.withdraw(w2))
else:
   d2= int(input("How much do you want to deposit"))
   b2.deposit(d2)

print("Tommy Egan:",b3.checkbalance())
y1 = int(input("Enter 1 if you want to make a withdrawal, enter 2 if you don't"))
if y1 == 1:
   w3= int(input("How much do you want to withdraw"))
   print("Withdrawal:",b3.withdraw(w3))
else:
   d3= int(input("How much do you want to deposit"))
   b3.deposit(d3)

print("Current Balance:",b3.checkbalance())

Body:
Consider saving all the details in a dictionary with the primary key as the name and pin & balance as secondary keys. Then, you can save it to a json file.

import json
accdict ={}
accdict['Obi'] = {'Name':'Obi Ezeakachi','Pin':1111,'Balance': 5000}

Continue for all the accounts.

with open('accounts.json','w') as f:
     f.write(json.dumps(accdict))

You can now manipulate this dictionary however you want and repeat.

Also, you should call the pin checker function before making a transaction. If you're serious about it and want it make it like an ATM, use threading to check for pin in the background while you access the details and interact with the user.


来源: stackexchange

问:
How to fetch a row with PDO
I'm trying not to get frustrated, but I've recently learned that mysql_* is deprecated in PHP. I've decided that I would learn how to use PDO.

I've just been looking at it this afternoon, and connecting to the database using it was easy, but then I wanted to fetch a row with it and save the row as an array indexed by the column names (the same way as the function mysql_fetch_array did). I can't figure it out to save my life.

I'll post my code to clarify, and I'm sure it is something simple (all programming errors are always simple), but I am definitely doing something wrong.

```<code>// Connect to the database
$host    = $_PARAM["DatabaseServer"];
$db        = $_PARAM["MainDatabase"];
$dbuser    = $_PARAM["DatabaseUser"];
$dbpass    = $_PARAM["DatabasePass"];
try
{
    $Database = new PDO("mysql:host=$host;dbname=$db", $dbuser, $dbpass);
}
catch (PDOException $e)
{
    echo "There was an unexpected error. Please try again, or contact us with concerns";
}

$stmt = $Database->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($sUserCook));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo $row["username"];
</code>```

答:
Use

```<code>$row = $stmt->fetch(PDO::FETCH_ASSOC);
</code>```

You will get the first query result.

ContentLicense: CC BY-SA 4.0

Title: How to fetch a row with PDO

Body:
I'm trying not to get frustrated, but I've recently learned that mysql_* is deprecated in PHP. I've decided that I would learn how to use PDO.

I've just been looking at it this afternoon, and connecting to the database using it was easy, but then I wanted to fetch a row with it and save the row as an array indexed by the column names (the same way as the function mysql_fetch_array did). I can't figure it out to save my life.

I'll post my code to clarify, and I'm sure it is something simple (all programming errors are always simple), but I am definitely doing something wrong.

// Connect to the database
$host    = $_PARAM["DatabaseServer"];
$db        = $_PARAM["MainDatabase"];
$dbuser    = $_PARAM["DatabaseUser"];
$dbpass    = $_PARAM["DatabasePass"];
try
{
    $Database = new PDO("mysql:host=$host;dbname=$db", $dbuser, $dbpass);
}
catch (PDOException $e)
{
    echo "There was an unexpected error. Please try again, or contact us with concerns";
}

$stmt = $Database->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($sUserCook));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo $row["username"];

Body:
Use

$row = $stmt->fetch(PDO::FETCH_ASSOC);

You will get the first query result.

ContentLicense: CC BY-SA 3.0


问:
import and append data
I'm trying to import tables from Excel to Access and keep the relationships between those tables.

I have some empty tables in Access that are connected to eachother with foreign keys, and what I basically want to do is fill those tables with data from Access without losing any relationship. E.g. the table "ProductsTests" will still inherit the foreign keys of the table "Products" when data is added.

What do you think is the best way to do it? Thank you for any help.

答:
Well, if you just import the Excel file into a different table, and then use an SQL query to add the data to the desired table, there's no problem (as long as you import in the right order so you don't violate referential integrity, and don't do one to one relationships).

Overwriting a table with relationships is somewhat more difficult, this is from one of my projects:

Add the following code to a module:

```<code>'This function makes a duplicate of the provided relation
Public Function DuplicateRelation(SourceRelation As Relation) As Relation
    Set DuplicateRelation = CurrentDb.CreateRelation(SourceRelation.NAME, SourceRelation.Table, SourceRelation.ForeignTable)
    DuplicateRelation.Attributes = SourceRelation.Attributes
    Dim i As Integer
    Dim fldLoop As Field
    Do While i < SourceRelation.Fields.Count
        Set fldLoop = DuplicateRelation.CreateField(SourceRelation.Fields(i).NAME)
        fldLoop.ForeignName = SourceRelation.Fields(i).ForeignName
        DuplicateRelation.Fields.Append fldLoop
        i = i + 1
    Loop
End Function

'This function creates a collection containing duplicates of all relations involving strTablename, and then deletes those relations
Public Function DeleteRelationshipsCreateBackup(strTablename As String) As Collection
    Dim ReturnCollection As Collection
    Set ReturnCollection = New Collection
    Dim i As Integer
    Dim o As Integer
    Do While i <= (CurrentDb.Relations.Count - 1)
        Select Case strTablename
            Case Is = CurrentDb.Relations(i).Table
                ReturnCollection.Add DuplicateRelation(CurrentDb.Relations(i))
                o = o + 1
                CurrentDb.Relations.Delete CurrentDb.Relations(i).NAME
            Case Is = CurrentDb.Relations(i).ForeignTable
                ReturnCollection.Add DuplicateRelation(CurrentDb.Relations(i))
                o = o + 1
                CurrentDb.Relations.Delete CurrentDb.Relations(i).NAME
            Case Else
                i = i + 1
        End Select
    Loop
    Set DeleteRelationshipsCreateBackup = ReturnCollection
End Function

'This function restores the duplicate created by DeleteRelationshipsCreateBackup
Public Sub RestoreRelationBackup(collRelationBackup As Collection)
    Dim relBackup As Variant
    If collRelationBackup.Count = 0 Then Exit Sub
    For Each relBackup In collRelationBackup
        CurrentDb.Relations.Append relBackup
    Next relBackup
End Sub
</code>```

Then, when replacing a table in VBA, do the following

```<code>dim collRelationBackup As Collection
Set collRelationBackup = DeleteRelationsCreateBackup("MyTable")
'Delete MyTable here
'Then make sure you create a drop-in replacement with the right field names and field types for the relation to be created
RestoreRelationBackup collRelation
</code>```

As you can see, often clearing the table and appending it is more easy, but this can be a problem with referential integrity (other tables might be cleared as well), or changes in table structure. Make sure that when you use this code, all the required fields for all the relations are there after your table has been replaced, else you will run into a runtime error and those relations will be gone.

Dependent on if you have multiple relationships with referential integrity, you might first want to duplicate the relationships of all involved tables (you can put those in a collection), then do all the deleting and replacing of tables, and then restore all of them,

Title: import and append data

Body:
Well, if you just import the Excel file into a different table, and then use an SQL query to add the data to the desired table, there's no problem (as long as you import in the right order so you don't violate referential integrity, and don't do one to one relationships).

Overwriting a table with relationships is somewhat more difficult, this is from one of my projects:

Add the following code to a module:

'This function makes a duplicate of the provided relation
Public Function DuplicateRelation(SourceRelation As Relation) As Relation
    Set DuplicateRelation = CurrentDb.CreateRelation(SourceRelation.NAME, SourceRelation.Table, SourceRelation.ForeignTable)
    DuplicateRelation.Attributes = SourceRelation.Attributes
    Dim i As Integer
    Dim fldLoop As Field
    Do While i < SourceRelation.Fields.Count
        Set fldLoop = DuplicateRelation.CreateField(SourceRelation.Fields(i).NAME)
        fldLoop.ForeignName = SourceRelation.Fields(i).ForeignName
        DuplicateRelation.Fields.Append fldLoop
        i = i + 1
    Loop
End Function

'This function creates a collection containing duplicates of all relations involving strTablename, and then deletes those relations
Public Function DeleteRelationshipsCreateBackup(strTablename As String) As Collection
    Dim ReturnCollection As Collection
    Set ReturnCollection = New Collection
    Dim i As Integer
    Dim o As Integer
    Do While i <= (CurrentDb.Relations.Count - 1)
        Select Case strTablename
            Case Is = CurrentDb.Relations(i).Table
                ReturnCollection.Add DuplicateRelation(CurrentDb.Relations(i))
                o = o + 1
                CurrentDb.Relations.Delete CurrentDb.Relations(i).NAME
            Case Is = CurrentDb.Relations(i).ForeignTable
                ReturnCollection.Add DuplicateRelation(CurrentDb.Relations(i))
                o = o + 1
                CurrentDb.Relations.Delete CurrentDb.Relations(i).NAME
            Case Else
                i = i + 1
        End Select
    Loop
    Set DeleteRelationshipsCreateBackup = ReturnCollection
End Function

'This function restores the duplicate created by DeleteRelationshipsCreateBackup
Public Sub RestoreRelationBackup(collRelationBackup As Collection)
    Dim relBackup As Variant
    If collRelationBackup.Count = 0 Then Exit Sub
    For Each relBackup In collRelationBackup
        CurrentDb.Relations.Append relBackup
    Next relBackup
End Sub

Then, when replacing a table in VBA, do the following

dim collRelationBackup As Collection
Set collRelationBackup = DeleteRelationsCreateBackup("MyTable")
'Delete MyTable here
'Then make sure you create a drop-in replacement with the right field names and field types for the relation to be created
RestoreRelationBackup collRelation

As you can see, often clearing the table and appending it is more easy, but this can be a problem with referential integrity (other tables might be cleared as well), or changes in table structure. Make sure that when you use this code, all the required fields for all the relations are there after your table has been replaced, else you will run into a runtime error and those relations will be gone.

Dependent on if you have multiple relationships with referential integrity, you might first want to duplicate the relationships of all involved tables (you can put those in a collection), then do all the deleting and replacing of tables, and then restore all of them,


问:
SQL - Dividing data from the same dataset with matching values in specific columns
I'm trying to find the proportion of females in a dataset that meet certain criteria: company id, job category, gender, timeframe, state id, and state kind. In order to do this, I have to divide the total # of females that meet this criteria by the total number of males and females that meet the criteria.
I'm currently querying data to find the # females from company 20, in engineering, from all time, with kind and id = 0 and dividing it by the total # male and females that meet that criteria:

```<code>/* number of females in eng. jobs */
(SELECT 1.0*sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND dimension_value = 'Female'
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0) /
/* number of m+f in eng */
(SELECT sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND (dimension_value = 'Female'
  OR dimension_value = 'Male')
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0))
</code>```

The problem is that I want to calculate this for all the companies in the dataset across all job categories, kinds, and ids. I'm unsure of how to do this without specifying those myself, and was wondering if anyone could help. I am using SQLWorkbench which is a DBMS-independent, cross-platform SQL query tool. I would appreciate some help (I am not using TSQL or PL/pgSQL).

Apologies for the formatting as well.

答:
You need to group by your list of columns that you'd like to identify the percentage of females, it will produce the counts separately. And the count itself is produced by conditional aggregation:

```<code>SELECT
 m.company_id
,c.standard_job_cat
,time_frame
,state_kind
,state_item_id
,sum(case when dimension_value = 'Female' then hiring_sample_count else 0 end) as females
,sum(hiring_sample_count) as total
,1.0*sum(case when dimension_value = 'Female' then hiring_sample_count else 0 end)/sum(hiring_sample_count) as female_proportion
FROM metrics m
JOIN category c
ON m.job_id = c.job_id
GROUP BY 1,2,3,4,5
ORDER BY 1,2,3,4,5;
</code>```

1.0* is added to avoid integer division, and females and total columns are just given to perceive the context

Body:
I'm trying to find the proportion of females in a dataset that meet certain criteria: company id, job category, gender, timeframe, state id, and state kind. In order to do this, I have to divide the total # of females that meet this criteria by the total number of males and females that meet the criteria.
I'm currently querying data to find the # females from company 20, in engineering, from all time, with kind and id = 0 and dividing it by the total # male and females that meet that criteria:

/* number of females in eng. jobs */
(SELECT 1.0*sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND dimension_value = 'Female'
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0) /
/* number of m+f in eng */
(SELECT sum(hiring_sample_count)
FROM metrics m
JOIN category c ON
m.job_id = c.job_id
AND m.company_id = 20
AND c.standard_job_cat = 'Engineering'
AND (dimension_value = 'Female'
  OR dimension_value = 'Male')
AND time_frame = 'ALLTIME'
AND state_kind = 0
AND state_item_id =0))

The problem is that I want to calculate this for all the companies in the dataset across all job categories, kinds, and ids. I'm unsure of how to do this without specifying those myself, and was wondering if anyone could help. I am using SQLWorkbench which is a DBMS-independent, cross-platform SQL query tool. I would appreciate some help (I am not using TSQL or PL/pgSQL).

Apologies for the formatting as well.

Body:
You need to group by your list of columns that you'd like to identify the percentage of females, it will produce the counts separately. And the count itself is produced by conditional aggregation:

SELECT
 m.company_id
,c.standard_job_cat
,time_frame
,state_kind
,state_item_id
,sum(case when dimension_value = 'Female' then hiring_sample_count else 0 end) as females
,sum(hiring_sample_count) as total
,1.0*sum(case when dimension_value = 'Female' then hiring_sample_count else 0 end)/sum(hiring_sample_count) as female_proportion
FROM metrics m
JOIN category c
ON m.job_id = c.job_id
GROUP BY 1,2,3,4,5
ORDER BY 1,2,3,4,5;

1.0* is added to avoid integer division, and females and total columns are just given to perceive the context


问:
Correct use of keys when joining tables in SQL
Currently learning data science with SQLite and Pandas. Working on a political contributions dataset. I'm wondering what is the purpose of WHERE contributors.candidate_id = candidates.id in the code below when joining two tables. Given my aim is to extract contributors for a particular candidate and include their name from another table, would the output not be the same without this condition?

implicit_join_sel = """
SELECT
    contributors.last_name, contributors.first_name, contributors.amount, candidates.last_name
FROM
    contributors, candidates
WHERE
    contributors.candidate_id = candidates.id
AND candidates.last_name = 'Obama';
"""

db.cursor().execute(implicit_join_sel)
```

<p>Output:</p>

<pre class="lang-html prettyprint-override"><code>contributors.last_name  contributors.first_name contributors.amount candidates.last_name
0   Buckler Steve   50.0    Obama
1   Buckler Steve   25.0    Obama
2   Buckheit    Bruce   100.0   Obama
3   Buckel  Linda   2300.0  Obama
4   Buckel  Linda   -2300.0 Obama
</code>```

FYI summary of tables:

--Candidates--
    id  first_name  last_name   middle_name party
0   33  Joseph  Biden   NaN D
1   36  Samuel  Brownback   NaN R

--Contributors--
    last_name   first_name  middle_name street_1    street_2    city    state   zip amount  date    candidate_id
0   Agee    Steven  NaN 549 Laurel Branch Road  NaN Floyd   VA  24091   500.0   2007-06-30  16
4   Akin    Charles NaN 10187 Sugar Creek Road  NaN Bentonville AR  72712   100.0   2007-06-16  16
```

答:
The sytax of the FROM clause, alone, would cause every row of the contributors table to be joined to every row of the candidates table.  The WHERE clause limits the join to only those pairs of rows with the same candidate ID.

The form of your FROM and WHERE clauses is not as clear as more modern SQL syntax, which would express this as

```<code>FROM
   contributors
   inner join candidates on contributors.candidate_id = candidates.id
</code>```

Body:
Currently learning data science with SQLite and Pandas. Working on a political contributions dataset. I'm wondering what is the purpose of WHERE contributors.candidate_id = candidates.id in the code below when joining two tables. Given my aim is to extract contributors for a particular candidate and include their name from another table, would the output not be the same without this condition?

implicit_join_sel = """
SELECT
    contributors.last_name, contributors.first_name, contributors.amount, candidates.last_name
FROM
    contributors, candidates
WHERE
    contributors.candidate_id = candidates.id
AND candidates.last_name = 'Obama';
"""

db.cursor().execute(implicit_join_sel)

Output:

contributors.last_name  contributors.first_name contributors.amount candidates.last_name
0   Buckler Steve   50.0    Obama
1   Buckler Steve   25.0    Obama
2   Buckheit    Bruce   100.0   Obama
3   Buckel  Linda   2300.0  Obama
4   Buckel  Linda   -2300.0 Obama

FYI summary of tables:

--Candidates--
    id  first_name  last_name   middle_name party
0   33  Joseph  Biden   NaN D
1   36  Samuel  Brownback   NaN R

--Contributors--
    last_name   first_name  middle_name street_1    street_2    city    state   zip amount  date    candidate_id
0   Agee    Steven  NaN 549 Laurel Branch Road  NaN Floyd   VA  24091   500.0   2007-06-30  16
4   Akin    Charles NaN 10187 Sugar Creek Road  NaN Bentonville AR  72712   100.0   2007-06-16  16

Body:
The sytax of the FROM clause, alone, would cause every row of the contributors table to be joined to every row of the candidates table.  The WHERE clause limits the join to only those pairs of rows with the same candidate ID.

The form of your FROM and WHERE clauses is not as clear as more modern SQL syntax, which would express this as

FROM
   contributors
   inner join candidates on contributors.candidate_id = candidates.id


问:
Graph: TreeSet is not adding all the edges
I am working on an undirected graph problem. I have a Node class which contains nodeName and List<Edge>. Then I have Edge class which holds Node start, Node end and weight. And finally I have a Graph class which has one instance variable Map<String, Node>.

I want to add all distinct edges to a set and order them in an increasing order based on their edge weight. Hence I chose TreeSet to store all the edges in an unique sorted fashion. But when I call the addAllEdges() it doesn't add all the edges. The graph has 9 vertices and 14 edges. However the treeSet saves only 10 of those.

Code Structure:

Graph:

```<code>class Graph {
    private Map<String, Node> verticesMap = new HashMap<>();

    public void addEdge(String src, String dest, int weight) {
        Node srcNode = verticesMap.get(src) == null ? new Node(src) : verticesMap.get(src);
        Node destNode = verticesMap.get(dest) == null ? new Node(dest) : verticesMap.get(dest);
        Edge edge = new Edge(srcNode, destNode, weight);
        srcNode.getEdgeList().add(edge);
        verticesMap.put(src, srcNode);
        verticesMap.put(dest, destNode);
    }

    public Set<Edge> addAllEdges() {
        Set<Edge> allEdgesSet = new TreeSet<>(getComparatorBasedOnEdgeWeight());
        for (Node node : verticesMap.values()) {
            for (Edge edge : node.getEdgeList()) {
            // sysout for debugging purpose only
                if(allEdgesSet.add(edge)) {
                    System.out.println("Added edge: " + edge);
                } else {
                    System.out.println("Did not add edge: " + edge);
                }
            }
        }
        return allEdgesSet;
    }

    private Comparator<Edge> getComparatorBasedOnEdgeWeight() {
        return (e1, e2) -> Integer.compare(e1.getWeight(), e2.getWeight());
    }
}
</code>```

Node:

```<code>class Node {
    private String name;
    private List<Edge> edgeList;

    public Node(String name) {
        this.name = name;
        edgeList = new ArrayList<>();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Node other = (Node) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return name;
    }
}
</code>```

Edge:

```<code>class Edge {
    private Node src;
    private Node dest;
    private int weight;

    public Edge(Node src, Node dest, int weight) {
        this.src = src;
        this.dest = dest;
        this.weight = weight;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((dest == null) ? 0 : dest.hashCode());
        result = prime * result + ((src == null) ? 0 : src.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Edge other = (Edge) obj;
        if (dest == null) {
            if (other.dest != null)
                return false;
        } else if (!dest.equals(other.dest))
            return false;
        if (src == null) {
            if (other.src != null)
                return false;
        } else if (!src.equals(other.src))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return src + "-->" + dest + "[" + weight + "]";
    }
}
</code>```

Test:

```<code> public class Test {
        public static void main(String[] args) {
            Graph graph = new Graph();
            graph.addEdge("A", "B", 4);
            graph.addEdge("B", "A", 4);
            graph.addEdge("A", "I", 8);
            graph.addEdge("I", "A", 8);
            graph.addEdge("B", "C", 8);
            graph.addEdge("C", "B", 8);
            graph.addEdge("B", "I", 11);
            graph.addEdge("I", "B", 11);
            graph.addEdge("C", "H", 2);
            graph.addEdge("H", "C", 2);
            graph.addEdge("C", "D", 7);
            graph.addEdge("D", "C", 7);
            graph.addEdge("C", "F", 4);
            graph.addEdge("F", "C", 4);
            graph.addEdge("H", "I", 7);
            graph.addEdge("I", "H", 7);
            graph.addEdge("H", "G", 6);
            graph.addEdge("G", "H", 6);
            graph.addEdge("I", "G", 1);
            graph.addEdge("G", "I", 1);
            graph.addEdge("G", "F", 2);
            graph.addEdge("F", "G", 2);
            graph.addEdge("F", "D", 14);
            graph.addEdge("D", "F", 14);
            graph.addEdge("F", "E", 10);
            graph.addEdge("E", "F", 10);
            graph.addEdge("E", "D", 9);
            graph.addEdge("D", "E", 9);
            graph.addAllEdges();
        }
    }
</code>```

Output:

```<code>Added edge: A-->B[4]
Added edge: A-->I[9]
Did not add edge: B-->A[4]
Added edge: B-->C[8]
Added edge: B-->I[11]
Did not add edge: C-->B[8]
Added edge: C-->H[2]
Added edge: C-->D[7]
Did not add edge: C-->F[4]
Did not add edge: D-->C[7]
Added edge: D-->F[14]
Did not add edge: D-->E[9]
Added edge: E-->F[10]
Did not add edge: E-->D[9]
Did not add edge: F-->C[4]
Did not add edge: F-->G[2]
Did not add edge: F-->D[14]
Did not add edge: F-->E[10]
Added edge: G-->H[6]
Added edge: G-->I[1]
Did not add edge: G-->F[2]
Did not add edge: H-->C[2]
Did not add edge: H-->I[7]
Did not add edge: H-->G[6]
Did not add edge: I-->A[9]
Did not add edge: I-->B[11]
Did not add edge: I-->H[7]
Did not add edge: I-->G[1]

Edges in the TreeSet:
[G-->I[1], C-->H[2], A-->B[4], G-->H[6], C-->D[7], B-->C[8], A-->I[9], E-->F[10], B-->I[11], D-->F[14]]
</code>```

The output above shows that it is iterating through 28 edges (14 vertices * 2). I am not able to figure out why treeSet is returning false for those edges which aren't even present in the set yet.

答:
TreeSet uses the Comparator for the ordering, but also for the uniqueness of objects. It does not use equals() or hashCode().

Your Comparator needs to compare nodes too, e.g. using node name.

Also, if your graph was truly undirected, you should not need to do graph.addEdge("A", "B", 4) and graph.addEdge("B", "A", 4), since they represent the same undirected edge. An undirected edge has no "source" or "destination".

I would suggest that you change Edge, renaming src and dest to node1 and node2, and ensure that name of node1 is less than name of node2.

That way, your Comparator can then simply compare weight, node1.name, and node2.name:

```<code>private Comparator<Edge> getComparatorBasedOnEdgeWeight() {
    return (e1, e2) -> {
        int cmp = Integer.compare(e1.getWeight(), e2.getWeight());
        if (cmp == 0)
            cmp = e1.getNode1().getName().compareTo(e2.getNode1().getName());
        if (cmp == 0)
            cmp = e1.getNode2().getName().compareTo(e2.getNode2().getName());
        return cmp;
    };
}
</code>```

Body:
I am working on an undirected graph problem. I have a Node class which contains nodeName and List<Edge>. Then I have Edge class which holds Node start, Node end and weight. And finally I have a Graph class which has one instance variable Map<String, Node>.

I want to add all distinct edges to a set and order them in an increasing order based on their edge weight. Hence I chose TreeSet to store all the edges in an unique sorted fashion. But when I call the addAllEdges() it doesn't add all the edges. The graph has 9 vertices and 14 edges. However the treeSet saves only 10 of those.

Code Structure:

Graph:

class Graph {
    private Map<String, Node> verticesMap = new HashMap<>();

    public void addEdge(String src, String dest, int weight) {
        Node srcNode = verticesMap.get(src) == null ? new Node(src) : verticesMap.get(src);
        Node destNode = verticesMap.get(dest) == null ? new Node(dest) : verticesMap.get(dest);
        Edge edge = new Edge(srcNode, destNode, weight);
        srcNode.getEdgeList().add(edge);
        verticesMap.put(src, srcNode);
        verticesMap.put(dest, destNode);
    }

    public Set<Edge> addAllEdges() {
        Set<Edge> allEdgesSet = new TreeSet<>(getComparatorBasedOnEdgeWeight());
        for (Node node : verticesMap.values()) {
            for (Edge edge : node.getEdgeList()) {
            // sysout for debugging purpose only
                if(allEdgesSet.add(edge)) {
                    System.out.println("Added edge: " + edge);
                } else {
                    System.out.println("Did not add edge: " + edge);
                }
            }
        }
        return allEdgesSet;
    }

    private Comparator<Edge> getComparatorBasedOnEdgeWeight() {
        return (e1, e2) -> Integer.compare(e1.getWeight(), e2.getWeight());
    }
}

Node:

class Node {
    private String name;
    private List<Edge> edgeList;

    public Node(String name) {
        this.name = name;
        edgeList = new ArrayList<>();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Node other = (Node) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return name;
    }
}

Edge:

class Edge {
    private Node src;
    private Node dest;
    private int weight;

    public Edge(Node src, Node dest, int weight) {
        this.src = src;
        this.dest = dest;
        this.weight = weight;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((dest == null) ? 0 : dest.hashCode());
        result = prime * result + ((src == null) ? 0 : src.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Edge other = (Edge) obj;
        if (dest == null) {
            if (other.dest != null)
                return false;
        } else if (!dest.equals(other.dest))
            return false;
        if (src == null) {
            if (other.src != null)
                return false;
        } else if (!src.equals(other.src))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return src + "-->" + dest + "[" + weight + "]";
    }
}

Test:

 public class Test {
        public static void main(String[] args) {
            Graph graph = new Graph();
            graph.addEdge("A", "B", 4);
            graph.addEdge("B", "A", 4);
            graph.addEdge("A", "I", 8);
            graph.addEdge("I", "A", 8);
            graph.addEdge("B", "C", 8);
            graph.addEdge("C", "B", 8);
            graph.addEdge("B", "I", 11);
            graph.addEdge("I", "B", 11);
            graph.addEdge("C", "H", 2);
            graph.addEdge("H", "C", 2);
            graph.addEdge("C", "D", 7);
            graph.addEdge("D", "C", 7);
            graph.addEdge("C", "F", 4);
            graph.addEdge("F", "C", 4);
            graph.addEdge("H", "I", 7);
            graph.addEdge("I", "H", 7);
            graph.addEdge("H", "G", 6);
            graph.addEdge("G", "H", 6);
            graph.addEdge("I", "G", 1);
            graph.addEdge("G", "I", 1);
            graph.addEdge("G", "F", 2);
            graph.addEdge("F", "G", 2);
            graph.addEdge("F", "D", 14);
            graph.addEdge("D", "F", 14);
            graph.addEdge("F", "E", 10);
            graph.addEdge("E", "F", 10);
            graph.addEdge("E", "D", 9);
            graph.addEdge("D", "E", 9);
            graph.addAllEdges();
        }
    }

Output:

Added edge: A-->B[4]
Added edge: A-->I[9]
Did not add edge: B-->A[4]
Added edge: B-->C[8]
Added edge: B-->I[11]
Did not add edge: C-->B[8]
Added edge: C-->H[2]
Added edge: C-->D[7]
Did not add edge: C-->F[4]
Did not add edge: D-->C[7]
Added edge: D-->F[14]
Did not add edge: D-->E[9]
Added edge: E-->F[10]
Did not add edge: E-->D[9]
Did not add edge: F-->C[4]
Did not add edge: F-->G[2]
Did not add edge: F-->D[14]
Did not add edge: F-->E[10]
Added edge: G-->H[6]
Added edge: G-->I[1]
Did not add edge: G-->F[2]
Did not add edge: H-->C[2]
Did not add edge: H-->I[7]
Did not add edge: H-->G[6]
Did not add edge: I-->A[9]
Did not add edge: I-->B[11]
Did not add edge: I-->H[7]
Did not add edge: I-->G[1]

Edges in the TreeSet:
[G-->I[1], C-->H[2], A-->B[4], G-->H[6], C-->D[7], B-->C[8], A-->I[9], E-->F[10], B-->I[11], D-->F[14]]

The output above shows that it is iterating through 28 edges (14 vertices * 2). I am not able to figure out why treeSet is returning false for those edges which aren't even present in the set yet.

Body:
TreeSet uses the Comparator for the ordering, but also for the uniqueness of objects. It does not use equals() or hashCode().

Your Comparator needs to compare nodes too, e.g. using node name.

Also, if your graph was truly undirected, you should not need to do graph.addEdge("A", "B", 4) and graph.addEdge("B", "A", 4), since they represent the same undirected edge. An undirected edge has no "source" or "destination".

I would suggest that you change Edge, renaming src and dest to node1 and node2, and ensure that name of node1 is less than name of node2.

That way, your Comparator can then simply compare weight, node1.name, and node2.name:

private Comparator<Edge> getComparatorBasedOnEdgeWeight() {
    return (e1, e2) -> {
        int cmp = Integer.compare(e1.getWeight(), e2.getWeight());
        if (cmp == 0)
            cmp = e1.getNode1().getName().compareTo(e2.getNode1().getName());
        if (cmp == 0)
            cmp = e1.getNode2().getName().compareTo(e2.getNode2().getName());
        return cmp;
    };
}


问:
Gensim: cannot import name 'Phraser'
It may be very basic problem but i have stuck with this since 2 hours.
I am trying to execute below line of code:

```<code>from gensim.models.phrases import Phrases , Phraser
</code>```

but i am getting error: cannot import name 'Phraser' as for as i know we get this kind of error when Phraser is neither variable nor function in gensim.models.phrases but i have checked gensim's homepage and found this:

class gensim.models.phrases.Phraser(phrases_model)

I have gensim's latest module 0.13.4 and i am using Python 3.5.2 |Anaconda 4.1.1 (64-bit), on windows 10.

答:
I was able to import Phraser like this on Windows 8:

```<code>from gensim.models.phrases import Phraser
</code>```

Using Anaconda with Python 2.7 and gensim 1.0.1

Title: Gensim: cannot import name 'Phraser'

Body:
It may be very basic problem but i have stuck with this since 2 hours.
I am trying to execute below line of code:

from gensim.models.phrases import Phrases , Phraser

but i am getting error: cannot import name 'Phraser' as for as i know we get this kind of error when Phraser is neither variable nor function in gensim.models.phrases but i have checked gensim's homepage and found this:

class gensim.models.phrases.Phraser(phrases_model)

I have gensim's latest module 0.13.4 and i am using Python 3.5.2 |Anaconda 4.1.1 (64-bit), on windows 10.

Body:
I was able to import Phraser like this on Windows 8:

from gensim.models.phrases import Phraser

Using Anaconda with Python 2.7 and gensim 1.0.1


问:
Radio input and submit pass value
Im trying to make a radio button form where the chosen option, "123, 456" value is passed to the "data-offer-id" part of my submit button.  I think this needs to be javascript but I don't know how to do this.  Please help if you can!.  Thanks in advance</p>

```<code><form>
  <input type="radio" name="data-offer-id" value="123"> 123<br>
  <input type="radio" name="data-offer-id" value="456"> 456<br>
 </form>

<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id="***Need Value to dynamically populate here****"
                   data-completed-callback="cleengCallbackHandler(result)">
<span style="color: #ffffff">$9.95 / Month
</span></button>
</code>```

答:
hope this will help</p>

```<code><!DOCTYPE html>
<html>
<body>

<input type="radio" name="offer-id" value="123">123<br>
<input type="radio" name="offer-id" value="456">456<br>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.querySelector('input[name="offer-id"]:checked').value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
</code>```

Title: Radio input and submit pass value

Body:
Im trying to make a radio button form where the chosen option, "123, 456" value is passed to the "data-offer-id" part of my submit button.  I think this needs to be javascript but I don't know how to do this.  Please help if you can!.  Thanks in advance

<form>
  <input type="radio" name="data-offer-id" value="123"> 123

  <input type="radio" name="data-offer-id" value="456"> 456

 </form>

<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id="***Need Value to dynamically populate here****"
                   data-completed-callback="cleengCallbackHandler(result)">
$9.95 / Month
</button>

Body:
hope this will help

<!DOCTYPE html>
<html>
<body>

<input type="radio" name="offer-id" value="123">123<br>
<input type="radio" name="offer-id" value="456">456<br>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.querySelector('input[name="offer-id"]:checked').value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>


问:
I want to get the type of a variable at runtime
I want to get the type of a variable at runtime.
How do I do this?</p>

答:
i have tested that and it worked</p>

```<code>val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}
</code>```

Body:
i have tested that and it worked

val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}


问:
how often optimize table query called
Actually i queried optimize table query for one table. then i didn't do any operation on that table. then again i'm querying optimize table query at the end of every month. but the data in the table may be changed once in four or 8 months. is it create any problem in performance of the mysql query?</p>

答:
If you don't do DML operations on the table, OPTIMIZE TABLE is useless.

OPTIMIZE TABLE cleans the table of deleted records, sorts the index pages (brings the physical order of the pages in consistence to logical one) and recalculates the statistics.

For the duration of the command, the table is unavailable both for reading and writing, and the command may take long for large tables.

ContentLicense: CC BY-SA 2.5

Title: how often optimize table query called


问:
Check if a class has a member function of a given signature
I'm asking for a template trick to detect if a class has a specific member function of a given signature.

The problem is similar to the one cited here
http://www.gotw.ca/gotw/071.htm
but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE  a member function with a particular signature, else the program won't compile. In my problem I need to do something if a class has that function, else do "something else".

A similar problem was faced by boost::serialization but I don't like the solution they adopted: a template function that invokes by default a free function (that you have to define) with a particular signature unless you define a particular member function (in their case "serialize" that takes 2 parameters of a given type) with a particular signature, else a compile error will happens. That is to implement both intrusive and non-intrusive serialization.

I don't like that solution for two reasons:

To be non intrusive you must override the global "serialize" function that is in boost::serialization namespace, so you have IN YOUR CLIENT CODE to open namespace boost and namespace serialization!

The stack to resolve that
mess was 10 to 12 function invocations.

I need to define a custom behavior for classes that has not that member function, and my entities are inside different namespaces (and I don't want to override a global function defined in one namespace while I'm in another one)

Can you give me a hint to solve this puzzle?

答:
Without C++11 support (decltype) this might work:

SSCCE

```<code>#include <iostream>
using namespace std;

struct A { void foo(void); };
struct Aa: public A { };
struct B { };

struct retA { int foo(void); };
struct argA { void foo(double); };
struct constA { void foo(void) const; };
struct varA { int foo; };

template<typename T>
struct FooFinder {
    typedef char true_type[1];
    typedef char false_type[2];

    template<int>
    struct TypeSink;

    template<class U>
    static true_type &match(U);

    template<class U>
    static true_type &test(TypeSink<sizeof( matchType<void (U::*)(void)>( &U::foo ) )> *);

    template<class U>
    static false_type &test(...);

    enum { value = (sizeof(test<T>(0, 0)) == sizeof(true_type)) };
};

int main() {
    cout << FooFinder<A>::value << endl;
    cout << FooFinder<Aa>::value << endl;
    cout << FooFinder<B>::value << endl;

    cout << FooFinder<retA>::value << endl;
    cout << FooFinder<argA>::value << endl;
    cout << FooFinder<constA>::value << endl;
    cout << FooFinder<varA>::value << endl;
}
</code>```

How it hopefully works

A, Aa and B are the clases in question, Aa being the special one that inherits the member we're looking for.

In the FooFinder the true_type and false_type are the replacements for the correspondent C++11 classes. Also for the understanding of template meta programming, they reveal the very basis of the SFINAE-sizeof-trick.

The TypeSink is a template struct that is used later to sink the integral result of the sizeof operator into a template instantiation to form a type.

The match function is another SFINAE kind of template that is left without a generic counterpart. It can hence only be instantiated if the type of its argument matches the type it was specialized for.

Both the test functions together with the enum declaration finally form the central SFINAE pattern. There is a generic one using an ellipsis that returns the false_type and a counterpart with more specific arguments to take precedence.

To be able to instantiate the test function with a template argument of T, the match function must be instantiated, as its return type is required to instantiate the TypeSink argument. The caveat is that &U::foo, being wrapped in a function argument, is not referred to from within a template argument specialization, so inherited member lookup still takes place.

OwnerDisplayName: ugasoft

LastEditorDisplayName: Head Geek

Body:
Without C++11 support (decltype) this might work:

SSCCE

#include <iostream>
using namespace std;

struct A { void foo(void); };
struct Aa: public A { };
struct B { };

struct retA { int foo(void); };
struct argA { void foo(double); };
struct constA { void foo(void) const; };
struct varA { int foo; };

template<typename T>
struct FooFinder {
    typedef char true_type[1];
    typedef char false_type[2];

    template<int>
    struct TypeSink;

    template<class U>
    static true_type &match(U);

    template<class U>
    static true_type &test(TypeSink<sizeof( matchType<void (U::*)(void)>( &U::foo ) )> *);

    template<class U>
    static false_type &test(...);

    enum { value = (sizeof(test<T>(0, 0)) == sizeof(true_type)) };
};

int main() {
    cout << FooFinder<A>::value << endl;
    cout << FooFinder<Aa>::value << endl;
    cout << FooFinder<B>::value << endl;

    cout << FooFinder<retA>::value << endl;
    cout << FooFinder<argA>::value << endl;
    cout << FooFinder<constA>::value << endl;
    cout << FooFinder<varA>::value << endl;
}

How it hopefully works

A, Aa and B are the clases in question, Aa being the special one that inherits the member we're looking for.

In the FooFinder the true_type and false_type are the replacements for the correspondent C++11 classes. Also for the understanding of template meta programming, they reveal the very basis of the SFINAE-sizeof-trick.

The TypeSink is a template struct that is used later to sink the integral result of the sizeof operator into a template instantiation to form a type.

The match function is another SFINAE kind of template that is left without a generic counterpart. It can hence only be instantiated if the type of its argument matches the type it was specialized for.

Both the test functions together with the enum declaration finally form the central SFINAE pattern. There is a generic one using an ellipsis that returns the false_type and a counterpart with more specific arguments to take precedence.

To be able to instantiate the test function with a template argument of T, the match function must be instantiated, as its return type is required to instantiate the TypeSink argument. The caveat is that &U::foo, being wrapped in a function argument, is not referred to from within a template argument specialization, so inherited member lookup still takes place.


问:
Bootstrap datetimepicker and Laravel timezones
My Laravel app is currently set to use UTC as a timezone. It uses this for all of the dates such as created_at and updated_at.

However, in my app I have a form which allows a user to specify a scheduled_at date using the Bootstrap datetimepicker plugin. Now the problem here is that the datetimepicker plugin uses momentjs in order to automatically display the date of the input in the users local timezone.

So I am trying to come up with a solution that will insert the date they enter as UTC. The biggest hurdle is that I want it to still display the input date in their current timezone, and then convert it before database insertion.

I was thinking I could have a hidden input field which would use momentjs to automatically populate it with their timezone name, and then use that hidden field to convert the date to UTC via Carbon.

Is this the best or only option I have?

答: Ended up using the moment-timezone-with-data plugin and auto-populating a hidden timezone field with moment.tz.guess().


问:
How to remove element from postgres jsonb by key value?
I have a jsonb column with this format.

```<code>{
    "categoryList": [{
        "category_menu_id": "51",
        "is_featured_product": 0
    }, {
        "category_menu_id": "54",
        "is_featured_product": 1
    }]
}
</code>```

How to remove category by category_menu_id?

This select query is working fine by category_menu_id.

```<code>select product_category
from product
where product_category->'categoryList' @> '[{"category_menu_id": "51"}]';
</code>```

答:
Example data (note that I have added a primary key id to enable updating the table):

```<code>create table product(id int primary key, product_category jsonb);
insert into product values
(1,
'{
    "categoryList": [{
        "category_menu_id": "51",
        "is_featured_product": 0
    }, {
        "category_menu_id": "54",
        "is_featured_product": 1
    }]
}');
</code>```

This query skips the element with "category_menu_id": "51" from the json array:

```<code>select jsonb_build_object('categoryList', jsonb_agg(value))
from product,
jsonb_array_elements(product_category->'categoryList')
where value->>'category_menu_id' <> '51';

                            jsonb_build_object
--------------------------------------------------------------------------
 {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)
</code>```

Use the above query to update the table:

```<code>update product p
set product_category = (
    select jsonb_build_object('categoryList', jsonb_agg(value))
    from product ps,
    jsonb_array_elements(product_category->'categoryList')
    where ps.id = p.id      -- important! primary key to identify a row
    and value->>'category_menu_id' <> '51')
returning *;

 id |                             product_category
----+--------------------------------------------------------------------------
  1 | {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)
</code>```

Body:
I have a jsonb column with this format.

{
    "categoryList": [{
        "category_menu_id": "51",
        "is_featured_product": 0
    }, {
        "category_menu_id": "54",
        "is_featured_product": 1
    }]
}

How to remove category by category_menu_id?

This select query is working fine by category_menu_id.

select product_category
from product
where product_category->'categoryList' @> '[{"category_menu_id": "51"}]';

Body:
Example data (note that I have added a primary key id to enable updating the table):

create table product(id int primary key, product_category jsonb);
insert into product values
(1,
'{
    "categoryList": [{
        "category_menu_id": "51",
        "is_featured_product": 0
    }, {
        "category_menu_id": "54",
        "is_featured_product": 1
    }]
}');

This query skips the element with "category_menu_id": "51" from the json array:

select jsonb_build_object('categoryList', jsonb_agg(value))
from product,
jsonb_array_elements(product_category->'categoryList')
where value->>'category_menu_id' <> '51';

                            jsonb_build_object
--------------------------------------------------------------------------
 {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)

Use the above query to update the table:

update product p
set product_category = (
    select jsonb_build_object('categoryList', jsonb_agg(value))
    from product ps,
    jsonb_array_elements(product_category->'categoryList')
    where ps.id = p.id      -- important! primary key to identify a row
    and value->>'category_menu_id' <> '51')
returning *;

 id |                             product_category
----+--------------------------------------------------------------------------
  1 | {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)


问:
Changing or preventing the use of E in Python?
I'm currently trying to write a script that will create a unique ID for a user relying on a number of variables, like birthdate, name, hometown, etc. This creates a very long number that is completely unique to that user, however, to try to make the number even more unique, I want to change a random number in the string. This is what I have so far:

```<code>rand = randint(1,15)
tempid = id / 10**rand
if randint(1,2) == 1:
    tempid = tempid + randint(2,10000)
else:
    tempid = tempid - randint(5,7500)
print(id)
id = tempid * (10**rand)
print(str(id))
</code>```

The code is fairly simple. It makes the number much smaller by dividing it by a large multiple of 10, adds or subtracts a random number, and multiplies it back to it's original length, with some changed numbers in the middle. The only problem is, because it must be an integer to be able to do any math with it, Python shortens it to 1.[something]e+[something]. This isn't helpful at all, becasue now it's not an ID. Is there anyway I can change it back to its original form, where it's just a long string, or perhaps change the code so it never becomes e? Thank you!

答:
I also agree with the other answers; as far as best practice goes, you should not do it this way at all. You will almost certainly make a worse than optimal solution. However, to solve the actual problem you pose, I would want to approach it in a different manner.

The problem is, as stated, that your division will not leave you with an integer result, which makes Python automatically convert to a float. This is not what you want if you want to keep your value unique. You want to do all your calculations on integers only. To achieve that, the simplest way is to multiply your modifiers, instead of dividing your original number. That way you will never leave the integer domain, and there is no need to convert you value back to an integer:

```<code>print(id)
rand = randint(1,15)
multiplier = 10**rand
if randint(1,2) == 1:
    id += multiplier * randint(2,10000)
else:
    id -= multiplier * randint(5,7500)
print(id)
</code>```

In addition I have used a bit of syntactic sugar, that I find rather nice, namely += and -=. They add and subtract a value from your variables respectively: a = a + 3 <=> a += 3.

Body:
I'm currently trying to write a script that will create a unique ID for a user relying on a number of variables, like birthdate, name, hometown, etc. This creates a very long number that is completely unique to that user, however, to try to make the number even more unique, I want to change a random number in the string. This is what I have so far:

rand = randint(1,15)
tempid = id / 10**rand
if randint(1,2) == 1:
    tempid = tempid + randint(2,10000)
else:
    tempid = tempid - randint(5,7500)
print(id)
id = tempid * (10**rand)
print(str(id))

The code is fairly simple. It makes the number much smaller by dividing it by a large multiple of 10, adds or subtracts a random number, and multiplies it back to it's original length, with some changed numbers in the middle. The only problem is, because it must be an integer to be able to do any math with it, Python shortens it to 1.[something]e+[something]. This isn't helpful at all, becasue now it's not an ID. Is there anyway I can change it back to its original form, where it's just a long string, or perhaps change the code so it never becomes e? Thank you!

Body:
I also agree with the other answers; as far as best practice goes, you should not do it this way at all. You will almost certainly make a worse than optimal solution. However, to solve the actual problem you pose, I would want to approach it in a different manner.

The problem is, as stated, that your division will not leave you with an integer result, which makes Python automatically convert to a float. This is not what you want if you want to keep your value unique. You want to do all your calculations on integers only. To achieve that, the simplest way is to multiply your modifiers, instead of dividing your original number. That way you will never leave the integer domain, and there is no need to convert you value back to an integer:

print(id)
rand = randint(1,15)
multiplier = 10**rand
if randint(1,2) == 1:
    id += multiplier * randint(2,10000)
else:
    id -= multiplier * randint(5,7500)
print(id)

In addition I have used a bit of syntactic sugar, that I find rather nice, namely += and -=. They add and subtract a value from your variables respectively: a = a + 3 <=> a += 3.


问:
Where to start REST web service in C# or ASP.Net
I am thinking to start writing some REST web services as a way to provide data. I guess that when my REST web services are available, then some of my web applications and console applications will be able to use REST web service as data service to get, add, update and delete data to databases. In addition to that, I would like to add authentication feature to identify any request.

My question is that where should I start? I saw Microsoft ADO.Net Data Services. Not sure if this is a good start place? Are there any examples available?

答:
You may also want to check out servicestack.net An Open Source, cross-platform, high-performance web service framework that lets you develop web services using code-first, strongly-typed DTO's which will automatically (without any configuration) be immediately available on a variety of different endpoints out-of-the-box (i.e. XML, JSON, JSV, SOAP 1.1/1.2).

REST, RPC and SOAP out of the box

In addition, your same web services can also be made available via any ReST-ful url of your choice where the preferred serialization format can be specified by your REST client i.e.

Using the HTTP Accept: header

Appending the preferred format to the query string e.g. ?format=xml

See the Nothing but REST! web service example for how to develop a complete REST-ful Ajax CRUD app with only 1 page of jQuery and 1 page of C#.

A good place to start is the Hello World example to see how to easily add ServiceStack web services to any existing ASP.NET web application.

Performance

For the performance conscience, ServiceStack makes an excellent Ajax server as it comes bundled with the fastest JSON Serializer for .NET (> 3x faster than other JSON Serializers).

Checkout this live Ajax app for a taste (Live demo hosted on Linux/Nginx/MONO).

Simple Northwind Example

ServiceStack also makes it easy to create strong-typed frictionless web services where with just the code below is all you need to return a List of Customer POCOs:

```<code>    public class CustomersService : RestServiceBase<Customers>
    {
            public IDbConnectionFactory DbFactory { get; set; }

            public override object OnGet(Customers request)
            {
              return new CustomersResponse { Customers = DbFactory.Exec(dbCmd =>
                    dbCmd.Select<Customer>())
            };
    }
</code>```

With no other config, you can now call the above webservice REST-fully returning all of:

XML

JSON

CSV

HTML

JSV

SOAP

Accessing web services on the client

You can call the above web service re-using the same DTOs that your web services were defined with (i.e. no code-gen is required) using your preferred generic ServiceClient (i.e Json, Xml, etc). This allows you to call your web services using a strong-typed API with just 1 Line of code:

C# Sync Example

```<code>IServiceClient client = new JsonServiceClient("http://host/service");
var customers = client.Send<CustomersResponse>(new Customers());
</code>```

And since your web services are also REST services, it works seamlessly with JavaScript ajax clients, e.g:

Using jQuery

```<code>$.getJSON("http://host/service", function(r) { alert(r.Customers.length); });
</code>```

Body:
You may also want to check out servicestack.net An Open Source, cross-platform, high-performance web service framework that lets you develop web services using code-first, strongly-typed DTO's which will automatically (without any configuration) be immediately available on a variety of different endpoints out-of-the-box (i.e. XML, JSON, JSV, SOAP 1.1/1.2).

REST, RPC and SOAP out of the box

In addition, your same web services can also be made available via any ReST-ful url of your choice where the preferred serialization format can be specified by your REST client i.e.

Using the HTTP Accept: header

Appending the preferred format to the query string e.g. ?format=xml

See the Nothing but REST! web service example for how to develop a complete REST-ful Ajax CRUD app with only 1 page of jQuery and 1 page of C#.

A good place to start is the Hello World example to see how to easily add ServiceStack web services to any existing ASP.NET web application.

Performance

For the performance conscience, ServiceStack makes an excellent Ajax server as it comes bundled with the fastest JSON Serializer for .NET (> 3x faster than other JSON Serializers).

Checkout this live Ajax app for a taste (Live demo hosted on Linux/Nginx/MONO).

Simple Northwind Example

ServiceStack also makes it easy to create strong-typed frictionless web services where with just the code below is all you need to return a List of Customer POCOs:

    public class CustomersService : RestServiceBase<Customers>
    {
            public IDbConnectionFactory DbFactory { get; set; }

            public override object OnGet(Customers request)
            {
              return new CustomersResponse { Customers = DbFactory.Exec(dbCmd =>
                    dbCmd.Select<Customer>())
            };
    }

With no other config, you can now call the above webservice REST-fully returning all of:

XML

JSON

CSV

HTML

JSV

SOAP

Accessing web services on the client

You can call the above web service re-using the same DTOs that your web services were defined with (i.e. no code-gen is required) using your preferred generic ServiceClient (i.e Json, Xml, etc). This allows you to call your web services using a strong-typed API with just 1 Line of code:

C# Sync Example

IServiceClient client = new JsonServiceClient("http://host/service");
var customers = client.Send<CustomersResponse>(new Customers());

And since your web services are also REST services, it works seamlessly with JavaScript ajax clients, e.g:

Using jQuery

$.getJSON("http://host/service", function(r) { alert(r.Customers.length); });


问:
need express.js controller oop tips
I'm newbie in web development and have developed a web server using node and express. I've used MVC pattern for this, with models being sequelizejs objects. But, for my controllers, thee's little to no OOP currently and I'd like to know some OO-way of writing controllers rather than using anonymous functions to serve requests:

```<code>app.get('/test',function(req,res){})
</code>```

Maybe I can create objects for each route by using the URL and model as properties and methods that are HTTP verbs:

```<code>//Use test.model for interacting with model
app.get(test.URL,test.get);
app.post(test.URL,test.post);
app.put(test.URL,test.put);
app.patch(test.URL,test.patch);
app.delete(test.URL,test.delete);
</code>```

But, it looks like overkill because most/all controller objects made this way will end up being singletons with no inheritance, polymorphism and reuse.

Question: Is there a better OO way to write controllers ?

答:
I have written a simple example in TypeScript which shows how to write a controller for an express application, having Object-oriented programming in mind. It can be easily applied to ES6:

Server.ts

```<code>import * as express from 'express';
import {CategoryController} from 'src/view/CategoryController';

export default class Server {
  public app: express.Application;

  constructor() {
    this.app = express();
    this.app.get('/', (request, response) => response.send('Root page without OOP.'));
    // Using a controller to serve a view
    this.app.use('/categories', CategoryController);
  }
}
</code>```

CategoryController.ts

```<code>import {Router, Request, Response} from 'express';

const router: Router = Router();

router.get('/', (request: Request, response: Response): Response => {
  const payload: { [index: string]: string[] } = {categories: ['CSS', 'HTML', 'JavaScript', 'TypeScript']};
  return response.json(payload);
});

export const CategoryController: Router = router;
</code>```

Title: need express.js controller oop tips

Body:
I'm newbie in web development and have developed a web server using node and express. I've used MVC pattern for this, with models being sequelizejs objects. But, for my controllers, thee's little to no OOP currently and I'd like to know some OO-way of writing controllers rather than using anonymous functions to serve requests:

app.get('/test',function(req,res){})

Maybe I can create objects for each route by using the URL and model as properties and methods that are HTTP verbs:

//Use test.model for interacting with model
app.get(test.URL,test.get);
app.post(test.URL,test.post);
app.put(test.URL,test.put);
app.patch(test.URL,test.patch);
app.delete(test.URL,test.delete);

But, it looks like overkill because most/all controller objects made this way will end up being singletons with no inheritance, polymorphism and reuse.

Question: Is there a better OO way to write controllers ?

Body:
I have written a simple example in TypeScript which shows how to write a controller for an express application, having Object-oriented programming in mind. It can be easily applied to ES6:

Server.ts

import * as express from 'express';
import {CategoryController} from 'src/view/CategoryController';

export default class Server {
  public app: express.Application;

  constructor() {
    this.app = express();
    this.app.get('/', (request, response) => response.send('Root page without OOP.'));
    // Using a controller to serve a view
    this.app.use('/categories', CategoryController);
  }
}

CategoryController.ts

import {Router, Request, Response} from 'express';

const router: Router = Router();

router.get('/', (request: Request, response: Response): Response => {
  const payload: { [index: string]: string[] } = {categories: ['CSS', 'HTML', 'JavaScript', 'TypeScript']};
  return response.json(payload);
});

export const CategoryController: Router = router;


问:
How to use masks while displaying names in tables using sql fuctions

if the record [name surname] it must be masked except the first two letters

if the record [name name surname] the second name must be masked too

if name and surname have only 2 letters nothing changes

答:
You can use REGEXP_REPLACE and provide REGEX expression

For example : replace all characters starting from third position.

```<code>SELECT
  REGEXP_REPLACE(customer_name, '(\w+)', '*', 3) "REGEXP_REPLACE"
  FROM myTable;
</code>```

Body:
You can use REGEXP_REPLACE and provide REGEX expression

For example : replace all characters starting from third position.

SELECT
  REGEXP_REPLACE(customer_name, '(\w+)', '*', 3) "REGEXP_REPLACE"
  FROM myTable;


问:
Difference between Object Identifier(OID) and Primary Key in terms of Object Oriented Design?
Well I know what OID is and means but is it same as Primary Key?In that case, how is it same and what are the differences between the two (if any)?</p>

答: Not all databases have Object Identifiers (OIDs). If you use PostgreSQL, it is an internal identifier used by PostgreSQL to identify system tables. You do not add OIDs to your user-created tables. The primary key is defined when you create your tables. But of course, you still can use OIDs (if so desired) by specifying WITH OIDS when you create your table. Attached is a link to the PostgreSQL documentation for you to review. https://www.postgresql.org/docs/8.1/static/datatype-oid.html


问:
Adding view from another class as presentViewController causes UIEvents not working
I am trying to build a simple library with working UIElements. What I am trying to do is, creating UIViewController objects from one class instances and push that new ViewController on the current VC Stack with the presentViewController method.

I can see that the UIElements has been successfully adding on the stack, but GestureRecognizer and UIButton's target does not work. When I am checking on ViewDebug, these settings are <NSNull null>.

This is my class method which I am creating the UI and putting on the current view stack.

```<code>-(void)displayAd{

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
            //Run UI Updates
            fullPageView = [[UIViewController alloc] init];
            fullPageView.view.frame = CurrentVC.view.bounds;
            fullPageView.view.backgroundColor = [UIColor redColor];
            UIImageView *staticImageView = [[UIImageView alloc] init];
            staticImageView.frame = CurrentVC.view.frame;

            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
            singleTap.numberOfTapsRequired = 1;
            [staticImageView addGestureRecognizer:singleTap];
            staticImageView.userInteractionEnabled = YES;
            [fullPageView.view addSubview:staticImageView];

            staticImageView.image = [UIImage imageWithData:imageData];
            [CurrentVC.view addSubview:fullPageView.view];
            //[fullPageView didMoveToParentViewController:self];
            [CurrentVC presentViewController:fullPageView animated:YES completion:^{
                NSLog(@"Tagon Ads is about to showing.");
                UIButton *closeButton = [self createButtonWithAssetName:@"tagonAssets.bundle/close_button" TargetMethod:@"closeModal" andView:staticImageView];
                [staticImageView addSubview:closeButton];
                [CurrentVC.view bringSubviewToFront:closeButton];
            }];
        });
    });
}
</code>```

CurrentVC is the current viewController that I am sending as a parameter through my library's method in order to add a new viewController stack on to it.

答:
Where is closeModal action? Probably same class as your currentVC. If so, your closeButton referenced currentVC but you already gone to fullPageView from there. So, your button lost his reference.

Just create new controller, send imageData there, create custom initializer, create new UIImageView and UIButton in there. With this way, your button gonna be reference own root and your problem should be solved.

Body:
I am trying to build a simple library with working UIElements. What I am trying to do is, creating UIViewController objects from one class instances and push that new ViewController on the current VC Stack with the presentViewController method.

I can see that the UIElements has been successfully adding on the stack, but GestureRecognizer and UIButton's target does not work. When I am checking on ViewDebug, these settings are <NSNull null>.

This is my class method which I am creating the UI and putting on the current view stack.

-(void)displayAd{

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
            //Run UI Updates
            fullPageView = [[UIViewController alloc] init];
            fullPageView.view.frame = CurrentVC.view.bounds;
            fullPageView.view.backgroundColor = [UIColor redColor];
            UIImageView *staticImageView = [[UIImageView alloc] init];
            staticImageView.frame = CurrentVC.view.frame;

            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
            singleTap.numberOfTapsRequired = 1;
            [staticImageView addGestureRecognizer:singleTap];
            staticImageView.userInteractionEnabled = YES;
            [fullPageView.view addSubview:staticImageView];

            staticImageView.image = [UIImage imageWithData:imageData];
            [CurrentVC.view addSubview:fullPageView.view];
            //[fullPageView didMoveToParentViewController:self];
            [CurrentVC presentViewController:fullPageView animated:YES completion:^{
                NSLog(@"Tagon Ads is about to showing.");
                UIButton *closeButton = [self createButtonWithAssetName:@"tagonAssets.bundle/close_button" TargetMethod:@"closeModal" andView:staticImageView];
                [staticImageView addSubview:closeButton];
                [CurrentVC.view bringSubviewToFront:closeButton];
            }];
        });
    });
}

CurrentVC is the current viewController that I am sending as a parameter through my library's method in order to add a new viewController stack on to it.


问:
UITableViewController layout not working
I am trying to position UITableView to the left side of the app, whole height but taking just 1 / 3 of the available width with the code like this:

```<code>class ViewController: UIViewController {
    var tableController: UITableViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableController = UITableViewController();

        addChildViewController(tableController!)
        self.view.addSubview(tableController!.view)
        tableController!.didMove(toParentViewController: self)
    }

    override func viewDidLayoutSubviews() {
        tableController!.view.backgroundColor = UIColor.red

        tableController!.view.frame = CGRect(
            x: 0,
            y: 0,
            width: view.bounds.width / 3,
            height: view.bounds.height);

        //tableController!.view.frame = view.bounds
    }
}
</code>```

And it looks like this:

And I don't get why the lines are not correctly aligned horizontally and it looks like being cut on the right.

If I give the view controller full width / height by uncommenting the last line, it looks better:

答:
Question 1

Are you properly constraining the TableView in the parent view?  You can set proportional constraints.  Please see this post on the topic: AutoLayout to keep view sizes proportional

Side Note

For iOS 11, constraining views to layout guides will trigger warnings in your IDE.  Consider embedding UI components inside another view that takes up the entire width of the parent view using Auto-resizing Masks.  See the topic here: Xcode Auto Layout Resizing Issue

Body:
I am trying to position UITableView to the left side of the app, whole height but taking just 1 / 3 of the available width with the code like this:

class ViewController: UIViewController {
    var tableController: UITableViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableController = UITableViewController();

        addChildViewController(tableController!)
        self.view.addSubview(tableController!.view)
        tableController!.didMove(toParentViewController: self)
    }

    override func viewDidLayoutSubviews() {
        tableController!.view.backgroundColor = UIColor.red

        tableController!.view.frame = CGRect(
            x: 0,
            y: 0,
            width: view.bounds.width / 3,
            height: view.bounds.height);

        //tableController!.view.frame = view.bounds
    }
}

And it looks like this:

And I don't get why the lines are not correctly aligned horizontally and it looks like being cut on the right.

If I give the view controller full width / height by uncommenting the last line, it looks better:


问:
Using pecl to install the Mongodb driver on OS X El Capitan (v10.11.1)
I am trying to install the php mongo driver for OS X. I've tried following these instructions to no avail.

$ which pecl -> /usr/local/Cellar/php56/5.6.13_2/bin/pecl

$ sudo pecl install mongo -> full build results here but the problem the is the error:

```<code>In file included from /private/tmp/pear/install/mongo/io_stream.c:34:
/private/tmp/pear/install/mongo/contrib/php-ssl.h:33:10: fatal error: 'openssl/evp.h' file not found
#include <openssl/evp.h>
</code>```

My Xcode command-line tools are up to date (I used $ xcode-select --install to be sure).

I'm sure how to fix this problem.

答:
Do this</p>

```<code>$ cd /usr/local/include
$ ln -s ../opt/openssl/include/openssl
</code>```

Body:
I am trying to install the php mongo driver for OS X. I've tried following these instructions to no avail.

$ which pecl -> /usr/local/Cellar/php56/5.6.13_2/bin/pecl

$ sudo pecl install mongo -> full build results here but the problem the is the error:

In file included from /private/tmp/pear/install/mongo/io_stream.c:34:
/private/tmp/pear/install/mongo/contrib/php-ssl.h:33:10: fatal error: 'openssl/evp.h' file not found
#include <openssl/evp.h>

My Xcode command-line tools are up to date (I used $ xcode-select --install to be sure).

I'm sure how to fix this problem.

Body:
Do this

$ cd /usr/local/include
$ ln -s ../opt/openssl/include/openssl


问:
How to check if the mouse is clicked in a certain area (pygame)
I am trying to make a program in pygame which will print something if the mouse is pressed in a certain area. I have tried using the mouse.get_pos and mouse.get_pressed but I am not sure if I am using them correctly. Here is my code    </p>

```<code>while True:
    DISPLAYSURF.fill(BLACK)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            mpos = pygame.mouse.get_pos()
            mpress = pygame.mouse.get_pressed()
            if mpos[0] >= 400 and mpos[1] <= 600 and mpress == True:
                print "Switching Tab"
</code>```

答:
in my games I used MOUSEBUTTONDOWN to check mouse press:

```<code>while True:
    DISPLAYSURF.fill(BLACK)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        (x, y)= pygame.mouse.get_pos()
        if x >= 400 and y <= 600 and event.type == pygame.MOUSEBUTTONDOWN:
            print "Switching Tab"
</code>```

Body:
I am trying to make a program in pygame which will print something if the mouse is pressed in a certain area. I have tried using the mouse.get_pos and mouse.get_pressed but I am not sure if I am using them correctly. Here is my code

while True:
    DISPLAYSURF.fill(BLACK)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            mpos = pygame.mouse.get_pos()
            mpress = pygame.mouse.get_pressed()
            if mpos[0] >= 400 and mpos[1] <= 600 and mpress == True:
                print "Switching Tab"

Body:
in my games I used MOUSEBUTTONDOWN to check mouse press:

while True:
    DISPLAYSURF.fill(BLACK)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        (x, y)= pygame.mouse.get_pos()
        if x >= 400 and y <= 600 and event.type == pygame.MOUSEBUTTONDOWN:
            print "Switching Tab"


问:
angular.js cant take result from view
I have a button in view

```<code><a class="btn btn-xs btn-white" ng-click="getUser('{{customer.id}}')"><i class="fa fa-eye"></i> Görüntüle </a>
</code>```

this button is in ng-repeat, customer.id is string when I call it from controller.js

```<code>$scope.getUser = function (param) {
            console.log(param);

        };
</code>```

console.writes

{{customer.id}}

as result. This language makes me crazy, Where do I make mistake

Thanks,

答:
You don't have to pass angular expression in your ng-click. So change your ng-click to

```<code>ng-click="getUser(customer.id)"
</code>```

Title: angular.js cant take result from view

Body:
I have a button in view

 Görüntüle

this button is in ng-repeat, customer.id is string when I call it from controller.js

$scope.getUser = function (param) {
            console.log(param);

        };

console.writes

{{customer.id}}

as result. This language makes me crazy, Where do I make mistake

Thanks,

Body:
You don't have to pass angular expression in your ng-click. So change your ng-click to

ng-click="getUser(customer.id)"


问:
Line continuation with pgfortran
I am trying to compile a file with pgf90 or pgfortran(that can handle all kinds of source files i.e. f90 or f77) that is written with fortran 77 constructs(i.e. has a .f extension). The question I have  is with line continuation.

```<code>open(10,file='/home/adaba/original/potentialenergy/vorticity/data/run/fort.10')
</code>```

So this line clearly goes beyond column 72. Here is what I tried. I tried breaking this up into two lines by using the '&' character at column 6 in the new line and compiled it. It compiles fine but when I run the program I get an error saying no such file found because it interprets the line continuation as an extra space between run and fort.10 and it reports file not found.

So I kept the code in one line and then added -Mextend which is pgi specific instruction for line extension. Now it seems to add some weird characters to the end of another file name much later in a subroutine. It does open fort.10 properly but it fails to open another file much later in the code and adds some weird characters to end of that file(in binary). In Emacs which is my editor I can see only purple color after the fort.10 statement (indicating that something is not right).

Can somebody with pgi fortran experience help ?

UPDATE

```<code>open(10,file='/home/adabas/originalPV/potentialenergy/vorticity/' // &
 &     'data/run/fort.10')
</code>```

I get a pgf90-s-0034 syntax error at or near &(on the upper line)

The pgf version is 17.0.4 64 bit

答:
Expanding on @Ross answer above:
In free format Fortran standard, there is another way: you can use STRING continuation syntax like the following:

open(10,file = "/home/adaba/original/&
                &potentialenergy/vorticity/data/run/fort.10" )

Here there is only one single string split and continued in two lines. The white space between the two ampersands is completely ignored. But anything before the first and after the second ampersands, even white space, counts as part of the string.

Title: Line continuation with pgfortran

Body:
I am trying to compile a file with pgf90 or pgfortran(that can handle all kinds of source files i.e. f90 or f77) that is written with fortran 77 constructs(i.e. has a .f extension). The question I have  is with line continuation.

open(10,file='/home/adaba/original/potentialenergy/vorticity/data/run/fort.10')

So this line clearly goes beyond column 72. Here is what I tried. I tried breaking this up into two lines by using the '&' character at column 6 in the new line and compiled it. It compiles fine but when I run the program I get an error saying no such file found because it interprets the line continuation as an extra space between run and fort.10 and it reports file not found.

So I kept the code in one line and then added -Mextend which is pgi specific instruction for line extension. Now it seems to add some weird characters to the end of another file name much later in a subroutine. It does open fort.10 properly but it fails to open another file much later in the code and adds some weird characters to end of that file(in binary). In Emacs which is my editor I can see only purple color after the fort.10 statement (indicating that something is not right).

Can somebody with pgi fortran experience help ?

UPDATE

open(10,file='/home/adabas/originalPV/potentialenergy/vorticity/' // &
 &     'data/run/fort.10')

I get a pgf90-s-0034 syntax error at or near &(on the upper line)

The pgf version is 17.0.4 64 bit


问:
Python Unique words in text file
I am in need of inserting unique words into a text file. One word per line and that word will be unique in whole file.

Whenever a new word comes as variable "word" then I need a way to check if it exists in the file. If it exists then it will again pick another word. It will again check if it exists or not and will do so until an unique word comes.

How can I do that?

By the way, I was doing:

```<code>    newword = "learn"
    f = open('wordlist.txt')
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    while s.find(newword) != -1:
        return newword
    else:
        return newword
</code>```

Thanks in advance.

答:
Assuming the file isn't too large, you could just read it all to memory, and check if the word is there:

```<code>def word_in_file(filename, word):
    with open(filename) as f:
        words = f.read().splitlines()

    return word in words
</code>```

If you're going to do this more than once, you'd better keep the words list and append to it each word you add to the file instead of reading it multiple times.
Additionally, creating a set from words should improve the search time and may be worth the "effort" if you're adding multiple words to the file.

Title: Python Unique words in text file

Body:
I am in need of inserting unique words into a text file. One word per line and that word will be unique in whole file.

Whenever a new word comes as variable "word" then I need a way to check if it exists in the file. If it exists then it will again pick another word. It will again check if it exists or not and will do so until an unique word comes.

How can I do that?

By the way, I was doing:

    newword = "learn"
    f = open('wordlist.txt')
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    while s.find(newword) != -1:
        return newword
    else:
        return newword

Thanks in advance.

Body:
Assuming the file isn't too large, you could just read it all to memory, and check if the word is there:

def word_in_file(filename, word):
    with open(filename) as f:
        words = f.read().splitlines()

    return word in words

If you're going to do this more than once, you'd better keep the words list and append to it each word you add to the file instead of reading it multiple times.
Additionally, creating a set from words should improve the search time and may be worth the "effort" if you're adding multiple words to the file.


问:
systemctl command in centos
I am trying to execute npm run command as background process in centos by creating it as systemd service . But when I am trying to start, it is giving error Unit not found and when running systemctl enable  it gives error as no such file or directory.</p>

答: But you did "systemctl daemon-reload" after installing the unit file? ;) </p>

Title: systemctl command in centos


问:
SEO friendly url in PHP htaccess
I use Godaddy Apache server to build my own blog, and I did some search of SEO friendly url tutorials, and applied the following code in my web root .htaccess file to transfer links like http://www.bgmemo.com/blog.php?url=2012/08/23/4-steps-to-initialize-Apache-Derby-10-9-1-0-in-Netbeans-7-1-1.html to http://www.bgmemo.com/blog/2012/08/23/4-steps-to-initialize-Apache-Derby-10-9-1-0-in-Netbeans-7-1-1.html :

```<code>RewriteEngine on
RewriteRule ^([a-zA-Z0-9-/]+).html$ blog.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ blog.php?url=$1
</code>```

But it does not work. The htaccess is working and other code in it is applied. Who can tell me what is wrong? Thanks in advance.

答:
This is the correctly way for don´t have problems with your .htaccess</p>

```<code><IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteBase /
  RewriteRule ^blog/([a-zA-Z0-9\-/\.]+)/?$ blog.php?url=$1 [L]
</IfModule>
</code>```

Title: SEO friendly url in PHP htaccess

Body:
I use Godaddy Apache server to build my own blog, and I did some search of SEO friendly url tutorials, and applied the following code in my web root .htaccess file to transfer links like http://www.bgmemo.com/blog.php?url=2012/08/23/4-steps-to-initialize-Apache-Derby-10-9-1-0-in-Netbeans-7-1-1.html to http://www.bgmemo.com/blog/2012/08/23/4-steps-to-initialize-Apache-Derby-10-9-1-0-in-Netbeans-7-1-1.html :

RewriteEngine on
RewriteRule ^([a-zA-Z0-9-/]+).html$ blog.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ blog.php?url=$1

But it does not work. The htaccess is working and other code in it is applied. Who can tell me what is wrong? Thanks in advance.

Body:
This is the correctly way for don´t have problems with your .htaccess

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteBase /
  RewriteRule ^blog/([a-zA-Z0-9\-/\.]+)/?$ blog.php?url=$1 [L]
</IfModule>


问:
Chrome on android - not loading local website javascript and css
I have strange problem on Chrome for Android with local website.

It works perfect on Firefox for Andorid, but not for Chrome.

On my site here: https://passcombo.com there is download link with a zip file.

What I do is:

download file to local file system (not SSD! - external storage makes
another problem!)

I unzip the package and go to the site in local storage using File Commander

I open the html file with Chrome - only HTML loads, no CSS, no JS, no images, no fonts.

Looks like there is path problem with relative paths?

But firefox works!

Working alternative is Firefox, but there you need to write correct strange path: "file:///storage/emulated/0/..../...html"
But...
Currently Chrome is mostly used on Andorid so it's bad local sites not working :/

答:
The only solution I found is to:

[update 2021] use Opera (Firefox did work before recent update!)

copy folder with my html/css/js to local storage
(somewhere)

open the sitewith path like:
[current Opera] file:///storage/0000-0000/MyFolder/index.html
[old  in firefox ] file:///storage/emulated/0/myfolder/index.html

where 'file:///storage/0000-0000/' OR 'file:///storage/emulated/0/' is the main path to local storage, and if you copied your folder somehwre deeper then you need to change the 'myfolder' to /somefolder1/somesubfolder/.../ sth

Shame it's the only way to create a web browser app for adroid.