问:
Pass express() app variable from one file to another
Hello guys, first of all, I know here is a lot of similar posts, but unfortunately I still can't figure out my trouble.

I have a file server.js, where I declare my app variable and invoke some config stuff:

```<code>var app = express();
...
</code>```

In my other file which is on path ./server/routes/PostApi.js I need to call code like this:

```<code>app.get('/api/posts', function(req, res) {
// use mongoose to get all posts in the database
Post.find(function(err, posts) {
    // if there is an error retrieving, send the error. nothing after res.send(err) will execute
    if (err) {
        res.send(err);
    }
    res.json(posts); // return all posts in JSON format
});
...
</code>```

on the end of this file i call:

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

which is required in server.js mentioned at first:

```<code>var PostApi = require('./server/routes/PostApi');
</code>```

Please, what is best practice these days for passing app variable to my api file? Thank you!

答:
This works for me :

index.js

```<code>var express = require('express'); // include
var moduleA = require('./moduleA'); // include

var app = express();
var moduleA = new moduleA();

moduleA.execute(app);

app.listen(process.env.PORT || 8080);
</code>```

moduleA.js

```<code>function moduleA() {
}

moduleA.prototype.execute = function(app) {
    // publish endpoints
    app.get('/register',
        function(req, res)
        {
            res.type('text/plain');
            res.send('Hello world express!!');
        }
    );
};

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

And test it with:

http://localhost:8080/register

Body:
Hello guys, first of all, I know here is a lot of similar posts, but unfortunately I still can't figure out my trouble.

I have a file server.js, where I declare my app variable and invoke some config stuff:

var app = express();
...

In my other file which is on path ./server/routes/PostApi.js I need to call code like this:

app.get('/api/posts', function(req, res) {
// use mongoose to get all posts in the database
Post.find(function(err, posts) {
    // if there is an error retrieving, send the error. nothing after res.send(err) will execute
    if (err) {
        res.send(err);
    }
    res.json(posts); // return all posts in JSON format
});
...

on the end of this file i call:

module.exports = PostApi;

which is required in server.js mentioned at first:

var PostApi = require('./server/routes/PostApi');

Please, what is best practice these days for passing app variable to my api file? Thank you!

Body:
This works for me :

index.js

var express = require('express'); // include
var moduleA = require('./moduleA'); // include

var app = express();
var moduleA = new moduleA();

moduleA.execute(app);

app.listen(process.env.PORT || 8080);

moduleA.js

function moduleA() {
}

moduleA.prototype.execute = function(app) {
    // publish endpoints
    app.get('/register',
        function(req, res)
        {
            res.type('text/plain');
            res.send('Hello world express!!');
        }
    );
};

module.exports = moduleA;

And test it with:

http://localhost:8080/register


来源: stackexchange

问:
How do I map true/false/unknown to -1/0/null without repetition?
I am currently working on a tool to help my users port their SQL code to SQL-Server 2005. For this purpose, I parse the SQL into a syntax tree, analyze it for constructs which need attentions, modify it and transform it back into T-SQL.

On thing that I want to support, is the "bools are values too" semantics of other RDBMS. For example, MS-Access allows me to write select A.x and A.y as r from A, which is impossible in T-SQL because:

Columns can't have boolean type (column values can't be and'ed)

Logical predicates can not be used where expressions are expected.

Therefore, my transformation routine converts the above statement into this:

```<code>select case
  when (A.x<>0) and (A.y<>0)
   then -1
  when not((A.x<>0) and (A.y<>0))
   then 0
  else
   null
  end as r
 from A;
</code>```

Which works, but is annoying, because I have to duplicate the logical expression (which can be very complex or contain subqueries etc.) in order to distinguish between true, false and unknown - the latter shall map to null. So I wonder if the T-SQL pro's here know a better way to achieve this?

UPDATE:
I would like to point out, that solutions which try to keep the operands in the integer domain have to take into account, that some operands may be logical expressions in the first place. This means that a efficient solution to convert a bool to a value is stil required. For example:

```<code>select A.x and exists (select * from B where B.y=A.y) from A;
</code>```

答:
EDIT: Based on additional information added to the Question and comments made on one of the suggested Answers, I am reformulating this answer:

If you are porting to SQL Server then I would expect that you are also transforming the data to match SQL Server types. If you have a boolean field then True, False, and Unknown map to 1, 0, and NULL as a NULLable BIT field.

With this in mind, you only need to worry about transforming pure boolean values.  Expressions such as:

```<code>exists (select * from B where B.y=A.y)
</code>```

and:

```<code>A.x in (1,2,3)
</code>```

are already in a workable form.  Meaning, statements like:

```<code>IF (EXISTS(SELECT 1 FROM Table))
</code>```

and:

```<code>IF (value IN (list))
</code>```

are already correct.  So you just need to worry about the fact that "1" for "True" is not by itself enough. Hence, you can convert "1" values to boolean expressions by testing if they are in fact equal to "1".  For example:

```<code>IF (value = 1)
</code>```

is the equivalent of what you previously had as:

```<code>IF (value)
</code>```

Putting all of this together, you should be able to simply translate all instances of pure boolean values of the old code into boolean expressions in the form of "value = 1" since a 1 will produce a True, 0 will produce False, and NULL will give you False.

HOWEVER, the real complexity is that SELECTing the value vs. testing with it via a WHERE condition is different.  Boolean expressions evaluate correctly in WHERE conditions but have no direct representation to SELECT (especially since NULL / Unknown isn't really boolean).  So, you can use the "Value = 1" translation in WHERE conditions but you will still need a CASE statement if you want to SELECT it as a result.

As mentioned briefly a moment ago, since NULL / Unknown isn't truly boolean, it is meaningless trying to convert "NULL AND NULL" to NULL for the purposes of a WHERE condition.  In effect, NULL is truly FALSE since it cannot be determined to be TRUE.  Again, this might be different for your purposes in a SELECT statement which is again why the CASE statement is your only choice there.

ContentLicense: CC BY-SA 2.5

Body:
I am currently working on a tool to help my users port their SQL code to SQL-Server 2005. For this purpose, I parse the SQL into a syntax tree, analyze it for constructs which need attentions, modify it and transform it back into T-SQL.

On thing that I want to support, is the "bools are values too" semantics of other RDBMS. For example, MS-Access allows me to write select A.x and A.y as r from A, which is impossible in T-SQL because:

Columns can't have boolean type (column values can't be and'ed)

Logical predicates can not be used where expressions are expected.

Therefore, my transformation routine converts the above statement into this:

select case
  when (A.x<>0) and (A.y<>0)
   then -1
  when not((A.x<>0) and (A.y<>0))
   then 0
  else
   null
  end as r
 from A;

Which works, but is annoying, because I have to duplicate the logical expression (which can be very complex or contain subqueries etc.) in order to distinguish between true, false and unknown - the latter shall map to null. So I wonder if the T-SQL pro's here know a better way to achieve this?

UPDATE:
I would like to point out, that solutions which try to keep the operands in the integer domain have to take into account, that some operands may be logical expressions in the first place. This means that a efficient solution to convert a bool to a value is stil required. For example:

select A.x and exists (select * from B where B.y=A.y) from A;

Body:
EDIT: Based on additional information added to the Question and comments made on one of the suggested Answers, I am reformulating this answer:

If you are porting to SQL Server then I would expect that you are also transforming the data to match SQL Server types. If you have a boolean field then True, False, and Unknown map to 1, 0, and NULL as a NULLable BIT field.

With this in mind, you only need to worry about transforming pure boolean values.  Expressions such as:

exists (select * from B where B.y=A.y)

and:

A.x in (1,2,3)

are already in a workable form.  Meaning, statements like:

IF (EXISTS(SELECT 1 FROM Table))

and:

IF (value IN (list))

are already correct.  So you just need to worry about the fact that "1" for "True" is not by itself enough. Hence, you can convert "1" values to boolean expressions by testing if they are in fact equal to "1".  For example:

IF (value = 1)

is the equivalent of what you previously had as:

IF (value)

Putting all of this together, you should be able to simply translate all instances of pure boolean values of the old code into boolean expressions in the form of "value = 1" since a 1 will produce a True, 0 will produce False, and NULL will give you False.

HOWEVER, the real complexity is that SELECTing the value vs. testing with it via a WHERE condition is different.  Boolean expressions evaluate correctly in WHERE conditions but have no direct representation to SELECT (especially since NULL / Unknown isn't really boolean).  So, you can use the "Value = 1" translation in WHERE conditions but you will still need a CASE statement if you want to SELECT it as a result.

As mentioned briefly a moment ago, since NULL / Unknown isn't truly boolean, it is meaningless trying to convert "NULL AND NULL" to NULL for the purposes of a WHERE condition.  In effect, NULL is truly FALSE since it cannot be determined to be TRUE.  Again, this might be different for your purposes in a SELECT statement which is again why the CASE statement is your only choice there.


问:
Argument unpacking with a Dict
I have a CSV file I'd like to parse as a Dict, so that the first item with the key of "key" can be unpacked to a variable, then the rest of the values as a list of keyed languages. Is there a nice, clean way of doing this?

My CSV is like so:

```<code>key,english,spanish
wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
something_else,"Hello!","hola!"
</code>```

Dict object as such:

```<code>[{'key': 'wanna_play_a_game', 'english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?'}, {'key': 'something_else', 'english': 'Hello', 'spanish': 'hola!'}]
</code>```

I did have a go but then realised that unpacking isn't the same with dicts (I assume) because they're not ordered like with lists. Am I overcomplicating things and should just saved the row['key'] to a variable and then remove it from the dict? Python isn't my bread & butter language so I'm not that knowledgable on the more magicky bits of the syntax.

This is what I was kinda getting at before realising I'm lost:

```<code>import csv
class Translate:

    def __init__(self):
        self.translations = self.readCSV('translations.csv')

    def readCSV(self, filename):
        with open(filename, 'rt') as csvfile:
            reader = csv.DictReader(csvfile)
            return [dict(d) for d in reader]

    def parse(self, line):
        # for t_key, *langs in self.translations:
        # for k, (t_key, *langs) in self.translations:
        # ... some magic function?
</code>```

The basic thing I'm trying to get is t_key to be "wanna_play_a_game" and langs to be ('english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?')

答:
You can try something like this using the split() method :

```<code>final_list=[]
with open('file.txt','r') as f:

    for line_no,data in enumerate(f):
        if line_no==0:
            pass
        else:
            dict_1 = {}

            key,english,spanish=data.split(',')
            dict_1['key'] = key
            dict_1['English'] = english

            dict_1['Spanish']=spanish.strip('\n')

            final_list.append(dict_1)

print(final_list)
</code>```

output:

```<code>[{'English': '"Wanna play a game?"', 'key': 'wanna_play_a_game', 'Spanish': '"¿Quiero jugar a un juego?"'}, {'English': '"Hello!"', 'key': 'something_else', 'Spanish': '"hola!"'}]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Argument unpacking with a Dict

Body:
I have a CSV file I'd like to parse as a Dict, so that the first item with the key of "key" can be unpacked to a variable, then the rest of the values as a list of keyed languages. Is there a nice, clean way of doing this?

My CSV is like so:

key,english,spanish
wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
something_else,"Hello!","hola!"

Dict object as such:

[{'key': 'wanna_play_a_game', 'english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?'}, {'key': 'something_else', 'english': 'Hello', 'spanish': 'hola!'}]

I did have a go but then realised that unpacking isn't the same with dicts (I assume) because they're not ordered like with lists. Am I overcomplicating things and should just saved the row['key'] to a variable and then remove it from the dict? Python isn't my bread & butter language so I'm not that knowledgable on the more magicky bits of the syntax.

This is what I was kinda getting at before realising I'm lost:

import csv
class Translate:

    def __init__(self):
        self.translations = self.readCSV('translations.csv')

    def readCSV(self, filename):
        with open(filename, 'rt') as csvfile:
            reader = csv.DictReader(csvfile)
            return [dict(d) for d in reader]

    def parse(self, line):
        # for t_key, *langs in self.translations:
        # for k, (t_key, *langs) in self.translations:
        # ... some magic function?

The basic thing I'm trying to get is t_key to be "wanna_play_a_game" and langs to be ('english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?')

Body:
You can try something like this using the split() method :

final_list=[]
with open('file.txt','r') as f:

    for line_no,data in enumerate(f):
        if line_no==0:
            pass
        else:
            dict_1 = {}

            key,english,spanish=data.split(',')
            dict_1['key'] = key
            dict_1['English'] = english

            dict_1['Spanish']=spanish.strip('\n')

            final_list.append(dict_1)

print(final_list)

output:

[{'English': '"Wanna play a game?"', 'key': 'wanna_play_a_game', 'Spanish': '"¿Quiero jugar a un juego?"'}, {'English': '"Hello!"', 'key': 'something_else', 'Spanish': '"hola!"'}]


问:
Retrieving Image URL from HTML code
```<code>private String getPersonImageUrl(Document doc){
    String result = "";
    Elements wrapper = doc.getElementsByClass("article name-overview");

    return result;
}
</code>```

Hello, I am kind of new to this information gathering from the website. I've encountered a problem I can't solve.

What I need is to retrieve the "src" image url to string "result". The "src" can be found in the link below. I've selected the class "article name-overview", because "image" can be found multiple times in the website there. What I don't know is how to proceed to retrieve the image link, located in src= value. Any help perhaps? Thank you.

P.S. Document doc = Jsoup.connect(url).get() in other class passed to getPersonImageUrl method. Also getting person's name is working, only struggling with picture url itself.
P.S.S. Information retrieved are for personal, non-commercial use.

src value

答:
use the .src attribute</p>

```<code>return doc.getElementById("name-poster").src
</code>```

Title: Retrieving Image URL from HTML code

Body:
private String getPersonImageUrl(Document doc){
    String result = "";
    Elements wrapper = doc.getElementsByClass("article name-overview");

    return result;
}

Hello, I am kind of new to this information gathering from the website. I've encountered a problem I can't solve.

What I need is to retrieve the "src" image url to string "result". The "src" can be found in the link below. I've selected the class "article name-overview", because "image" can be found multiple times in the website there. What I don't know is how to proceed to retrieve the image link, located in src= value. Any help perhaps? Thank you.

P.S. Document doc = Jsoup.connect(url).get() in other class passed to getPersonImageUrl method. Also getting person's name is working, only struggling with picture url itself.
P.S.S. Information retrieved are for personal, non-commercial use.

src value

Body:
use the .src attribute

return doc.getElementById("name-poster").src


问:
Apache - Ubuntu desktop edition 9.04
Not Found

The requested URL / was not found on this server.
Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.2 with Suhosin-Patch Server at localhost Port 80

Am getting this error while am accessing http://localhost/

Apache,phpmyadmin and mysql running fine.

Bugzilla3 also working fine

Need some help to change the listening port for bugzilla in this ubuntu desktop

Please am new to linux am not that much aware about commands or configuration
Please give some idea to change the listening ports and my httpd.conf file is empty.

Thanks,
Ramesh V

答:
With that little information is difficult to provide an answer.

First, the httpd.conf it is empty by default on Ubuntu (at least on old version like 9), the config is in apache2.conf, ant the virtualhosts are defined in /etc/apache2/sites-available and th actives are in /etc/apache2/sites-enabled.

You should ckeck:

Check the apache error log (/var/log/apache2/error.log)

Is apache running?

Is there a default virtual host configured

Check that you have a line in "127.0.0.1  localhost" in /etc/hosts

whithout more information is difficult to provide a precise answer.

Title: Apache - Ubuntu desktop edition 9.04


问:
How to highlight selected text within excel
I would like to write a VBA function to highlight specific text within an excel cell. Is this possible? I've been googling but it's unclear at this point.

to clarify, I would like to search a specific column for a text value (actually a list of values) and highlight the matched text in say yellow.

Note: this is what I ended up doing:

```<code>  Sub Colors()

    Dim searchString As String
    Dim targetString As String
    Dim startPos As Integer

    searchString = "abc"
    targetString = Cells(2, 1).Value
    startPos = InStr(targetString, searchString)

    If startPos > 0 Then

        Cells(2, 1).Characters(startPos, Len(searchString)).Font.Color = vbRed

    End If

 End Sub
</code>```

答:
This is answer is specifically for @t.ztrk who has cities in Col1 and text to search for those cities in column 2. He posted his question over here:
is it possible to find and change color of the text in excel

I borrowed from this code from another solution (sorry if it was not the original):https://stackoverflow.com/a/11676031/8716187

```<code>Sub test4String2color()
Dim strTest As String
Dim strLen As Integer
 strTest = Range("F1")
 strLen = Len(strTest)
For Each cell In Range("A1:D100")
 If InStr(cell, strTest) > 0 Then
  cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed
 End If
Next
End Sub
</code>```

I know this might not be elegant but I punched it out in a few minutes to meet the users need.  Sorry in advance if the solutions provided above are (1) more flexible or (2) more efficient.  Also sorry for my C++ nested loop habits coming through.

@t.ztrk you can record a macro and just stop it (delete whatever is there) or insert a button control and paste the code there.  Not sure what your VB familiarity is.  Just be sure to select a cell on the worksheet you want to process before you run the macro (it should run on any sheet and can be made to work on any workbook).

```<code>Sub Macro1()
'Searches all text in Column 2 on a Sheet for the string located in Column 1
'If found it highlights that text
Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim i As Integer
Dim y As Integer

Dim Col1 As Double
Dim Col2 As Double

Dim Col1_rowSTART As Double
Dim Col1_rowEND As Double

Dim Col2_rowSTART As Double
Dim Col2_rowEND As Double

Dim strTest As String
Dim strLen As Integer

'Set up parameter that we know
Set ThisWB = ActiveWorkbook
Set ThisWS = ActiveSheet
Col1 = 1 'city column
Col2 = 2 'text search column
'Define Starting Row for each column
Col1_rowSTART = 1
Col2_rowSTART = 1
'Define ending row for each column
Col1_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col1).End(xlUp).Row
Col2_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col2).End(xlUp).Row

'Could be fancy and see which column is shorter ....
'Won't do that here

For i = Col1_rowSTART To Col1_rowEND
    'make a string out of each cell value in Col1
    strTest = CStr(ThisWS.Cells(i, Col1))
    strLen = Len(strTest)
    'Roll thorugh all of Column 2 in search of the target string
    For y = Col2_rowSTART To Col2_rowEND
        'Check if Col1 string is in Col2 String
        If InStr(CStr(ThisWS.Cells(y, Col2)), strTest) > 0 Then
            ThisWS.Cells(y, Col2).Characters(InStr(ThisWS.Cells(y, Col2), strTest), strLen).Font.Color = vbRed
        End If
    Next y
Next i

MsgBox ("City Search Complete!")

End Sub
</code>```

Here is your testing screenshot.

Cheers - Keep learning and applying.
-WWC

Body:
I would like to write a VBA function to highlight specific text within an excel cell. Is this possible? I've been googling but it's unclear at this point.

to clarify, I would like to search a specific column for a text value (actually a list of values) and highlight the matched text in say yellow.

Note: this is what I ended up doing:

  Sub Colors()

    Dim searchString As String
    Dim targetString As String
    Dim startPos As Integer

    searchString = "abc"
    targetString = Cells(2, 1).Value
    startPos = InStr(targetString, searchString)

    If startPos > 0 Then

        Cells(2, 1).Characters(startPos, Len(searchString)).Font.Color = vbRed

    End If

 End Sub

Body:
This is answer is specifically for @t.ztrk who has cities in Col1 and text to search for those cities in column 2. He posted his question over here:
is it possible to find and change color of the text in excel

I borrowed from this code from another solution (sorry if it was not the original):https://stackoverflow.com/a/11676031/8716187

Sub test4String2color()
Dim strTest As String
Dim strLen As Integer
 strTest = Range("F1")
 strLen = Len(strTest)
For Each cell In Range("A1:D100")
 If InStr(cell, strTest) > 0 Then
  cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed
 End If
Next
End Sub

I know this might not be elegant but I punched it out in a few minutes to meet the users need.  Sorry in advance if the solutions provided above are (1) more flexible or (2) more efficient.  Also sorry for my C++ nested loop habits coming through.

@t.ztrk you can record a macro and just stop it (delete whatever is there) or insert a button control and paste the code there.  Not sure what your VB familiarity is.  Just be sure to select a cell on the worksheet you want to process before you run the macro (it should run on any sheet and can be made to work on any workbook).

Sub Macro1()
'Searches all text in Column 2 on a Sheet for the string located in Column 1
'If found it highlights that text
Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim i As Integer
Dim y As Integer

Dim Col1 As Double
Dim Col2 As Double

Dim Col1_rowSTART As Double
Dim Col1_rowEND As Double

Dim Col2_rowSTART As Double
Dim Col2_rowEND As Double

Dim strTest As String
Dim strLen As Integer

'Set up parameter that we know
Set ThisWB = ActiveWorkbook
Set ThisWS = ActiveSheet
Col1 = 1 'city column
Col2 = 2 'text search column
'Define Starting Row for each column
Col1_rowSTART = 1
Col2_rowSTART = 1
'Define ending row for each column
Col1_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col1).End(xlUp).Row
Col2_rowEND = ThisWS.Cells(ThisWS.Rows.Count, Col2).End(xlUp).Row

'Could be fancy and see which column is shorter ....
'Won't do that here

For i = Col1_rowSTART To Col1_rowEND
    'make a string out of each cell value in Col1
    strTest = CStr(ThisWS.Cells(i, Col1))
    strLen = Len(strTest)
    'Roll thorugh all of Column 2 in search of the target string
    For y = Col2_rowSTART To Col2_rowEND
        'Check if Col1 string is in Col2 String
        If InStr(CStr(ThisWS.Cells(y, Col2)), strTest) > 0 Then
            ThisWS.Cells(y, Col2).Characters(InStr(ThisWS.Cells(y, Col2), strTest), strLen).Font.Color = vbRed
        End If
    Next y
Next i

MsgBox ("City Search Complete!")

End Sub

Here is your testing screenshot.

Cheers - Keep learning and applying.
-WWC


问:
Freeman Chain Code in Java
Okay, hopefully this makes more sense. I have an array hard coded with only 1s and 0s. I am trying to write a function that reads each element to see if it is a 0 or 1. If it is a 1, it will execute another function and then change that 1 to a 0 so that it is not read again. I have it printing simply as a placeholder for the other function I will be implementing later. I'm having trouble getting the findfirst1 function to check every element in the array. I have tried putting the incrementors for i and k in different places within the flow of the code but nothing I have tried gets me the correct output.</p>

```<code>public static void main(String[] args)
{
    int[][] testarray = {{1,0,0,0,0,0,0,1},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{1,0,0,0,0,0,0,1}};

    findfirst1(testarray);
}

public static void findfirst1(int[][] array1)
{
    int value = 0;
    for(int i = 0; i < 6;i++)
    {
        for(int k = 0; k < 7;k++)
        {
            value = array1[i][k];
            if(value == 1)
            {
                System.out.println(value);
                array1[i][k] = 0;
            }
            else
            {
                System.out.println(value);
            }
        }
    }

}
</code>```

答:
Okay, so after starting completely over and writing it all from scratch I figured it out. The array.length was right all along. I had trouble wrapping my head around it because I was so focused on the idea of the "image".

Edit: I just found an error where it wouldn't print the last line for array1, so I just added an extra row of 0s and it worked.

```<code>public class ChainCodeClass {

public static void main(String[] args)
{
    int[][] array1 = {{0,1,0,0,0,0,0,0},{0,1,0,0,0,1,0,0},{0,1,1,1,0,0,1,0},
            {0,0,0,1,1,0,0,1},{0,0,0,0,1,0,0,1},{0,0,0,0,0,1,0,0},
            {0,0,0,0,0,0,1,0}**,{0,0,0,0,0,0,0,0}**};

    int[][] array2 = {{0,0,0,0,0,0,0,0},{0,1,1,1,1,0,1,0},{0,0,0,0,1,0,1,0},
            {0,0,1,1,1,0,1,0},{0,0,1,0,0,0,1,0},{0,0,1,0,0,0,1,0},{0,0,0,0,0,0,1,1},
            {0,0,0,0,0,0,0,0}};

    System.out.print("First Image");
    print(array1);
    findfirst1(array1);
    print(array1);

    System.out.print("Second Image");
    print(array2);
    outline8(array2);
}

public static void findfirst1(int[][] array)
{
    int value = 0;
    for(int i = 0; i < array.length; i++)
    {
        for(int k = 0; k < array.length; k++)
        {
            value = array[i][k];
            if(value == 1)
            {
                System.out.print(value + "  ");
                array[i][k] = 0;
            }
            else
            {
                System.out.println(value);
            }
        }
    }

}

public static void print(int[][] array)
{
for(int i = 0; i < array.length; i++) // print function for the array using incrementors
{
    System.out.print("\n");

    for(int k = 0; k < array.length; k++)
    {
        System.out.print(array[i][k] + "    ");
    }
}
    System.out.println();
}
 }
</code>```

Title: Freeman Chain Code in Java

Body:
Okay, hopefully this makes more sense. I have an array hard coded with only 1s and 0s. I am trying to write a function that reads each element to see if it is a 0 or 1. If it is a 1, it will execute another function and then change that 1 to a 0 so that it is not read again. I have it printing simply as a placeholder for the other function I will be implementing later. I'm having trouble getting the findfirst1 function to check every element in the array. I have tried putting the incrementors for i and k in different places within the flow of the code but nothing I have tried gets me the correct output.

public static void main(String[] args)
{
    int[][] testarray = {{1,0,0,0,0,0,0,1},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},
            {0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{1,0,0,0,0,0,0,1}};

    findfirst1(testarray);
}

public static void findfirst1(int[][] array1)
{
    int value = 0;
    for(int i = 0; i < 6;i++)
    {
        for(int k = 0; k < 7;k++)
        {
            value = array1[i][k];
            if(value == 1)
            {
                System.out.println(value);
                array1[i][k] = 0;
            }
            else
            {
                System.out.println(value);
            }
        }
    }

}

Body:
Okay, so after starting completely over and writing it all from scratch I figured it out. The array.length was right all along. I had trouble wrapping my head around it because I was so focused on the idea of the "image".

Edit: I just found an error where it wouldn't print the last line for array1, so I just added an extra row of 0s and it worked.

public class ChainCodeClass {

public static void main(String[] args)
{
    int[][] array1 = {{0,1,0,0,0,0,0,0},{0,1,0,0,0,1,0,0},{0,1,1,1,0,0,1,0},
            {0,0,0,1,1,0,0,1},{0,0,0,0,1,0,0,1},{0,0,0,0,0,1,0,0},
            {0,0,0,0,0,0,1,0}**,{0,0,0,0,0,0,0,0}**};

    int[][] array2 = {{0,0,0,0,0,0,0,0},{0,1,1,1,1,0,1,0},{0,0,0,0,1,0,1,0},
            {0,0,1,1,1,0,1,0},{0,0,1,0,0,0,1,0},{0,0,1,0,0,0,1,0},{0,0,0,0,0,0,1,1},
            {0,0,0,0,0,0,0,0}};

    System.out.print("First Image");
    print(array1);
    findfirst1(array1);
    print(array1);

    System.out.print("Second Image");
    print(array2);
    outline8(array2);
}

public static void findfirst1(int[][] array)
{
    int value = 0;
    for(int i = 0; i < array.length; i++)
    {
        for(int k = 0; k < array.length; k++)
        {
            value = array[i][k];
            if(value == 1)
            {
                System.out.print(value + "  ");
                array[i][k] = 0;
            }
            else
            {
                System.out.println(value);
            }
        }
    }

}

public static void print(int[][] array)
{
for(int i = 0; i < array.length; i++) // print function for the array using incrementors
{
    System.out.print("\n");

    for(int k = 0; k < array.length; k++)
    {
        System.out.print(array[i][k] + "    ");
    }
}
    System.out.println();
}
 }


问:
use pre-defined schema in pyspark json
Currently, if i want to read a json with pyspark, either I use interfered schema, or I have to define manually my schema StructType

Is it possible to use a file as reference for the schema ?

答:
You can indeed use a file to define your schema. For example, for the following schema:

```<code>TICKET:string
TRANSFERRED:string
ACCOUNT:integer
</code>```

you can use this code to import it:

```<code>import csv
from collections import OrderedDict
from pyspark.sql.types import StructType, StructField, StringType,IntegerType

schema = OrderedDict()
with open(r'schema.txt') as csvfile:
    schemareader = csv.reader(csvfile, delimiter=':')
    for row in schemareader:
        schema[row[0]]=row[1]
</code>```

and then you can use it to create your StructType schema on the fly:

```<code>mapping = {"string": StringType, "integer": IntegerType}

schema = StructType([
    StructField(k, mapping.get(v.lower())(), True) for (k, v) in schema.items()])
</code>```

You may have to create a more complex schema file for JSON file, however, please note that you can't use a JSON file to define your schema as the order of the columns is not guaranteed when parsing JSON.

Title: use pre-defined schema in pyspark json

Body:
You can indeed use a file to define your schema. For example, for the following schema:

TICKET:string
TRANSFERRED:string
ACCOUNT:integer

you can use this code to import it:

import csv
from collections import OrderedDict
from pyspark.sql.types import StructType, StructField, StringType,IntegerType

schema = OrderedDict()
with open(r'schema.txt') as csvfile:
    schemareader = csv.reader(csvfile, delimiter=':')
    for row in schemareader:
        schema[row[0]]=row[1]

and then you can use it to create your StructType schema on the fly:

mapping = {"string": StringType, "integer": IntegerType}

schema = StructType([
    StructField(k, mapping.get(v.lower())(), True) for (k, v) in schema.items()])

You may have to create a more complex schema file for JSON file, however, please note that you can't use a JSON file to define your schema as the order of the columns is not guaranteed when parsing JSON.


答:
Your question is tagged Python 3.6, and in 3.6, DictReader returns OrderedDict instances, so unpacking should actually not be a problem, if you just change return [dict(d) for d in reader] to return list(reader), otherwise you are converting those OrderedDict back to regular unordered dict.

Tested with the online interactive Python shell as I'm stuck with 3.5 here:

```<code>>>> text = '''key,english,spanish
... wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
... something_else,"Hello!","hola!"'''
>>> r = csv.DictReader(io.StringIO(text))
>>> ds = list(r)
>>> key, eng, esp = ds[0].values()
>>> key, eng, esp
('wanna_play_a_game', 'Wanna play a game?', '¿Quiero jugar a un juego?')
</code>```

Or if the number of languages is not known, * unpack to a list:

```<code>>>> key, *langs = ds[1].values()
>>> key, langs
('something_else', ['Hello!', 'hola!'])
</code>```

In your case, you probably need this (also remember to return list(reader)):

```<code>for d in self.translations:
    key, *langs = d.values()
    # do stuff with key and langs
</code>```

Alternatively, you could also use a dict-comprehension to create a dictionary mapping the value of the "key" key to an OrderedDict of the translations for the different languages:

```<code>>>> {d.pop("key"): d for d in ds}
{'wanna_play_a_game': OrderedDict([('english', 'Wanna play a game?'), ('spanish', '¿Quiero jugar a un juego?')]),
 'something_else': OrderedDict([('english', 'Hello!'), ('spanish', 'hola!')])}
</code>```

Note, however, that this modifies the dicts in the list as you create the dictionary comprehension, which can be considered bad practice, but in this case, and considering that you do not keep a reference to the original dicts in the first place, I think this can be used.

Title: Argument unpacking with a Dict

Body:
Your question is tagged Python 3.6, and in 3.6, DictReader returns OrderedDict instances, so unpacking should actually not be a problem, if you just change return [dict(d) for d in reader] to return list(reader), otherwise you are converting those OrderedDict back to regular unordered dict.

Tested with the online interactive Python shell as I'm stuck with 3.5 here:

>>> text = '''key,english,spanish
... wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
... something_else,"Hello!","hola!"'''
>>> r = csv.DictReader(io.StringIO(text))
>>> ds = list(r)
>>> key, eng, esp = ds[0].values()
>>> key, eng, esp
('wanna_play_a_game', 'Wanna play a game?', '¿Quiero jugar a un juego?')

Or if the number of languages is not known, * unpack to a list:

>>> key, *langs = ds[1].values()
>>> key, langs
('something_else', ['Hello!', 'hola!'])

In your case, you probably need this (also remember to return list(reader)):

for d in self.translations:
    key, *langs = d.values()
    # do stuff with key and langs

Alternatively, you could also use a dict-comprehension to create a dictionary mapping the value of the "key" key to an OrderedDict of the translations for the different languages:

>>> {d.pop("key"): d for d in ds}
{'wanna_play_a_game': OrderedDict([('english', 'Wanna play a game?'), ('spanish', '¿Quiero jugar a un juego?')]),
 'something_else': OrderedDict([('english', 'Hello!'), ('spanish', 'hola!')])}

Note, however, that this modifies the dicts in the list as you create the dictionary comprehension, which can be considered bad practice, but in this case, and considering that you do not keep a reference to the original dicts in the first place, I think this can be used.


问:
What's the best strategy to provide different comparison operators for the same class?
Consider this simple class storing a value and a time.

```<code>class A
{
public:
    boost::posix_time::ptime when;
    double value;
};
</code>```

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

答:
Another approach, very simple: add template comparator functions to the A class makes it easy to do a comparison in the end and is really error prone:</p>

```<code>#include <iostream>
#include <set>

using namespace std;

class A
{
public:
    int when;
    double value;

    int getTime() const { return when; }
    double getValue() const { return value; }

    template<typename T>
    bool isLower( T (A::*getter)() const,
                  bool strict,
                  const A& right ) const
    {
        if ( strict )
            return ((*this).*getter)() < (right.*getter)();
        else
            return ((*this).*getter)() <= (right.*getter)();
    }

    template<typename T>
    bool isGreater( T (A::*getter)() const,
                    bool strict,
                    const A& right ) const
    {
        if ( strict )
            return ((*this).*getter)() > (right.*getter)();
        else
            return ((*this).*getter)() >= (right.*getter)();
    }

    template<typename T>
    bool isEqual( T (A::*getter)() const,
                  const A& right ) const
    {
        return ((*this).*getter)() == (right.*getter)();
    }
};

struct byTime_compare {
    bool operator() (const A& lhs, const A& rhs) const {
        return lhs.isLower( &A::getTime, true, rhs );
    }
};

int main()
{
    A a, b;

    if ( a.isLower( &A::getValue, true, b ) ) // means a < b by value
    {
        // ...
    }

    std::set<A, byTime_compare> mySet;
}
</code>```

Body:
Consider this simple class storing a value and a time.

class A
{
public:
    boost::posix_time::ptime when;
    double value;
};

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

Body:
Another approach, very simple: add template comparator functions to the A class makes it easy to do a comparison in the end and is really error prone:

#include <iostream>
#include <set>

using namespace std;

class A
{
public:
    int when;
    double value;

    int getTime() const { return when; }
    double getValue() const { return value; }

    template<typename T>
    bool isLower( T (A::*getter)() const,
                  bool strict,
                  const A& right ) const
    {
        if ( strict )
            return ((*this).*getter)() < (right.*getter)();
        else
            return ((*this).*getter)() <= (right.*getter)();
    }

    template<typename T>
    bool isGreater( T (A::*getter)() const,
                    bool strict,
                    const A& right ) const
    {
        if ( strict )
            return ((*this).*getter)() > (right.*getter)();
        else
            return ((*this).*getter)() >= (right.*getter)();
    }

    template<typename T>
    bool isEqual( T (A::*getter)() const,
                  const A& right ) const
    {
        return ((*this).*getter)() == (right.*getter)();
    }
};

struct byTime_compare {
    bool operator() (const A& lhs, const A& rhs) const {
        return lhs.isLower( &A::getTime, true, rhs );
    }
};

int main()
{
    A a, b;

    if ( a.isLower( &A::getValue, true, b ) ) // means a < b by value
    {
        // ...
    }

    std::set<A, byTime_compare> mySet;
}


问:
if char equals a letter then execute a code
Please help I cannot run this block of code:</p>

```<code>import java.util.Scanner;

public class Methods_in_java {

    public static void main(String[] args) {
        boolean gameover = true;
        int score = 5000;
        int Levelcomplete = 5;
        int bonus = 100;
        boolean prize = true;
        System.out.println("Please enter your name");
        Scanner lic = new Scanner(System.in);
        String ab = lic.nextLine();
        char fir = Character.toUpperCase(ab.charAt(1));
        if(fir == 'A'){
                prize = true;
        }
        Calculatescore(gameover,score,Levelcomplete,bonus,prize);
    }
    public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
        if(gameover){
            int finalscore = score + (levelcomplete * bonus);
            if (prize){
                finalscore += 1000;
            }
            System.out.println("Your final score is "+ finalscore);
        }
    }
}
</code>```

答:
```<code>String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
</code>```

Is fir supposed to be the first character in the user String? In that case you want to make sure to take zero-based indexing into account:

```<code>char fir = Character.toUpperCase(ab.charAt(0));
</code>```

Body:
Please help I cannot run this block of code:

import java.util.Scanner;

public class Methods_in_java {

    public static void main(String[] args) {
        boolean gameover = true;
        int score = 5000;
        int Levelcomplete = 5;
        int bonus = 100;
        boolean prize = true;
        System.out.println("Please enter your name");
        Scanner lic = new Scanner(System.in);
        String ab = lic.nextLine();
        char fir = Character.toUpperCase(ab.charAt(1));
        if(fir == 'A'){
                prize = true;
        }
        Calculatescore(gameover,score,Levelcomplete,bonus,prize);
    }
    public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
        if(gameover){
            int finalscore = score + (levelcomplete * bonus);
            if (prize){
                finalscore += 1000;
            }
            System.out.println("Your final score is "+ finalscore);
        }
    }
}

Body:
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));

Is fir supposed to be the first character in the user String? In that case you want to make sure to take zero-based indexing into account:

char fir = Character.toUpperCase(ab.charAt(0));


问:
GDPR compliance
Just found about this new regulation, it will be law in 2018 and affects anybody who stores data about EU citizens, that can be used to identify a person. More detail here.

I have a page that doesn't store names and exact addresses but it stores birth dates and country/city as location and uses these two to provide a service (which is the core service, so I can't just stop collecting these data).

From what I understand I have to take some action to ensure compliance with GDPR, but I haven't found reasonable explanations what that means. There is a dozen articles that rephrase paragraphs of GDPR, that is not helping at all.

I don't mind full deletion, explaing what data I store to the users and simmilar points ... What I am mostly worried about is the part about anonymizing data so in case of a breach they can not be used to identify a person. How am I supposed to do that? If I store an email address used to verify an user account and tie birth date and location data via PK to that verified email, they are no longer anonymous ... and they can't be, right?

Any thought about practical solutions to become GDPR compliant?

答:
I agree with the above - GDPR is a great thing for privacy rights and data control - I also agree that there are a million sites out there just rephrasing gdpr!
In terms of practical steps, more guidance is going to be released by the ICO this month. But it makes sense to begin by mapping out what user data you process, whether the reasons for this are justified and whether there you have asked for EXPLICIT permission to use that data in that way. Further to this you should think about how you can delete data if it's requested.

There are services that will keep independent record of opt ins and alert you to data vulnerabilities. Anonomisation works in some cases, in others, if you have permission, then all you need is process to delete and an audit trail.

Title: GDPR compliance


问:
Why does C# array not have Count property?

Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

```<code>double[] test = new double[1];
</code>```

support the Length property to get the size of the array. But arrays also implement an IList interface:

```<code>IList<double> list = test;
</code>```

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.

答:
The Count property is hidden using the explicit interface declaration style, for example like this in a class definition:

```<code>int IList.Count {
    get {
        // ...etc...
    }
}
</code>```

You can access methods and properties hidden like this using a type cast, e.g.

```<code>((IList<double>) myArray).Count
</code>```

Body:
Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

double[] test = new double[1];

support the Length property to get the size of the array. But arrays also implement an IList interface:

IList<double> list = test;

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.

Body:
The Count property is hidden using the explicit interface declaration style, for example like this in a class definition:

int IList.Count {
    get {
        // ...etc...
    }
}

You can access methods and properties hidden like this using a type cast, e.g.

((IList<double>) myArray).Count


问:
Design Patterns: How to create database object/connection only when needed?
I've a simple application, say it has some classes and an "extra" one that handles database requests. Currently i'm creating the database object everytime the app is used, but in some cases there's no need for a database connection. I'm doing it like this (PHP btw):

```<code>$db = new Database();
$foo = new Foo($db); // passing the db
</code>```

But sometimes the $foo object does not need db access, as only methods without database actions are called. So my question is: What's the professional way to handle situations like this / how to create the db connection/object only when needed ?

My goal is to avoid unnecessary database connections.

答:
```<code> <?php

    mysql_select_db('foo',mysql_connect('localhost','root',''))or die(mysql_error());
    session_start();

    function antiinjection($data)
    {
        $filter_sql = stripcslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
        return $filter_sql;
    }

    $username = antiinjection($_POST['username']);
    $password = antiinjection($_POST['password']);

    /* student */
        $query = "SELECT * FROM student WHERE username='$username' AND password='$password'";
        $result = mysql_query($query)or die(mysql_error());
        $row = mysql_fetch_array($result);
        $num_row = mysql_num_rows($result);
    /* teacher */
    $query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
    $num_row_teacher = mysql_num_rows($query_teacher);
    $row_teahcer = mysql_fetch_array($query_teacher);
    if( $num_row > 0 ) {
    $_SESSION['id']=$row['student_id'];
    echo 'true_student';
    }else if ($num_row_teacher > 0){
    $_SESSION['id']=$row_teahcer['teacher_id'];
    echo 'true';

     }else{
            echo 'false';
    }

    ?>
</code>```

and in the php file insert javascript

```<code>   <script>
                    jQuery(document).ready(function(){
                    jQuery("#login_form1").submit(function(e){
                            e.preventDefault();
                            var formData = jQuery(this).serialize();
                            $.ajax({
                                type: "POST",
                                url: "login.php",
                                data: formData,
                                success: function(html){
                                if(html=='true')
                                {
                                    window.location = 'folder_a/index.php';
                                }else if (html == 'true_student'){
                                    window.location = 'folder_b/index.php';
                                }else
                                {
                                    { header: 'Login Failed' };
                                }
                                }
                            });
                            return false;
                        });
                    });
                    </script>
</code>```

another connection

```<code>    <?php

  class DbConnector {

   var $theQuery;
   var $link;

   function DbConnector(){

    // Get the main settings from the array we just loaded
    $host = 'localhost';
    $db = 'db_lms1';
    $user = 'root';
    $pass = '';

    // Connect to the database
    $this->link = mysql_connect($host, $user, $pass);
    mysql_select_db($db);
    register_shutdown_function(array(&$this, 'close'));

}

    //*** Function: query, Purpose: Execute a database query ***
function query($query) {

    $this->theQuery = $query;
    return mysql_query($query, $this->link);

}

//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {

    return mysql_fetch_array($result);

}

//*** Function: close, Purpose: Close the connection ***
function close() {

    mysql_close($this->link);

}

  }

  ?>
</code>```

Body:
I've a simple application, say it has some classes and an "extra" one that handles database requests. Currently i'm creating the database object everytime the app is used, but in some cases there's no need for a database connection. I'm doing it like this (PHP btw):

$db = new Database();
$foo = new Foo($db); // passing the db

But sometimes the $foo object does not need db access, as only methods without database actions are called. So my question is: What's the professional way to handle situations like this / how to create the db connection/object only when needed ?

My goal is to avoid unnecessary database connections.

Body:
 <?php

    mysql_select_db('foo',mysql_connect('localhost','root',''))or die(mysql_error());
    session_start();

    function antiinjection($data)
    {
        $filter_sql = stripcslashes(strip_tags(htmlspecialchars($data,ENT_QUOTES)));
        return $filter_sql;
    }

    $username = antiinjection($_POST['username']);
    $password = antiinjection($_POST['password']);

    /* student */
        $query = "SELECT * FROM student WHERE username='$username' AND password='$password'";
        $result = mysql_query($query)or die(mysql_error());
        $row = mysql_fetch_array($result);
        $num_row = mysql_num_rows($result);
    /* teacher */
    $query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
    $num_row_teacher = mysql_num_rows($query_teacher);
    $row_teahcer = mysql_fetch_array($query_teacher);
    if( $num_row > 0 ) {
    $_SESSION['id']=$row['student_id'];
    echo 'true_student';
    }else if ($num_row_teacher > 0){
    $_SESSION['id']=$row_teahcer['teacher_id'];
    echo 'true';

     }else{
            echo 'false';
    }

    ?>

and in the php file insert javascript

   <script>
                    jQuery(document).ready(function(){
                    jQuery("#login_form1").submit(function(e){
                            e.preventDefault();
                            var formData = jQuery(this).serialize();
                            $.ajax({
                                type: "POST",
                                url: "login.php",
                                data: formData,
                                success: function(html){
                                if(html=='true')
                                {
                                    window.location = 'folder_a/index.php';
                                }else if (html == 'true_student'){
                                    window.location = 'folder_b/index.php';
                                }else
                                {
                                    { header: 'Login Failed' };
                                }
                                }
                            });
                            return false;
                        });
                    });
                    </script>

another connection

    <?php

  class DbConnector {

   var $theQuery;
   var $link;

   function DbConnector(){

    // Get the main settings from the array we just loaded
    $host = 'localhost';
    $db = 'db_lms1';
    $user = 'root';
    $pass = '';

    // Connect to the database
    $this->link = mysql_connect($host, $user, $pass);
    mysql_select_db($db);
    register_shutdown_function(array(&$this, 'close'));

}

    //*** Function: query, Purpose: Execute a database query ***
function query($query) {

    $this->theQuery = $query;
    return mysql_query($query, $this->link);

}

//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {

    return mysql_fetch_array($result);

}

//*** Function: close, Purpose: Close the connection ***
function close() {

    mysql_close($this->link);

}

  }

  ?>


问:
My Dialog with a list doesn't work
I'm new on android studio and i have a litle problem.
I want an dialog with some choices to select from an ArrayList (participantsShare in my code) but when i'm triying to open this dialog the app just stop,
What am I doing wrong ?

```<code>final AlertDialog.Builder builder = new AlertDialog.Builder(Paiements.this);
builder.setTitle("Qui a payé ?");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Paiements.this, android.R.layout.simple_list_item_1, participantsShare );

builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        participant.setText(participantsShare.get(item));
        dialog.cancel();
    }
});

AlertDialog dialog = builder.create();
dialog.show();
</code>```

(participantsShare is an ArrayList<String> and participant is an EditText)

答:
Use this code for showing an list in dialog.</p>

```<code>AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");

builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
                builderInner.setMessage(strName);
                builderInner.setTitle("Your Selected Item is");
                builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,int which) {
                                dialog.dismiss();
                            }
                        });
                builderInner.show();
            }
        });
builderSingle.show();
</code>```

Title: My Dialog with a list doesn't work

Body:
I'm new on android studio and i have a litle problem.
I want an dialog with some choices to select from an ArrayList (participantsShare in my code) but when i'm triying to open this dialog the app just stop,
What am I doing wrong ?

final AlertDialog.Builder builder = new AlertDialog.Builder(Paiements.this);
builder.setTitle("Qui a payé ?");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Paiements.this, android.R.layout.simple_list_item_1, participantsShare );

builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        participant.setText(participantsShare.get(item));
        dialog.cancel();
    }
});

AlertDialog dialog = builder.create();
dialog.show();

(participantsShare is an ArrayList<String> and participant is an EditText)

Body:
Use this code for showing an list in dialog.

AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");

builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
                builderInner.setMessage(strName);
                builderInner.setTitle("Your Selected Item is");
                builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,int which) {
                                dialog.dismiss();
                            }
                        });
                builderInner.show();
            }
        });
builderSingle.show();


问:
"Toggle fullscreen view" event for Google Maps
Is there a way to capture event where a user clicks toggle fullscreen view button on the map?

答:
You can use HTML5 Fullscreen API which has the fullscreenchange event:

"When fullscreen mode is successfully engaged, the document which
  contains the element receives a fullscreenchange event. When
  fullscreen mode is exited, the document again receives a
  fullscreenchange event".

Please note All browsers implement this APIs. Nevertheless some implement it with prefixed names with slightly different spelling; e.g., instead of requestFullscreen(), there is MozRequestFullScreen().


问:
Set class to active on additional li elements upon navbar click
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

```<code>$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>

</ul>
</code>```

Now I have similar items at the top of the page presented as a connected circle:

```<code><div class="connected-line">
  <ul>
    <li class="active">1
      <p> System </p>
    </li>
    <li id="hosts">2
      <p> Hosts </p>
    </li>
    <li>3
      <p> Cards </p>
    </li>
    <li>4
      <p> Devices </p>
    </li>
  </ul>
</div>
</code>```

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

答:
Replace the code in your code. I hope, you can do it. Let me know, If any problem.</p>

```<code>$(document).ready(function() {
  $(".nav li a").click(function() {

      $(".connected-line ul li").removeClass("active");
       id = $(this).prop('id');
     $("#" + id).addClass("active")

  });

});

<div class="connected-line">
  <ul>
    <li class="active"  id="system-settings">1
      <p> System </p>
    </li>
    <li id="hosts">2
      <p> Hosts </p>
    </li>
    <li  id="card-range">3
      <p> Cards </p>
    </li>
    <li id="pinpads">4
      <p> Devices </p>
    </li>
    <li id="xmls" >5
      <p> Lanes </p>
    </li>
  </ul>
</div>

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>

</ul>
</code>```

Body:
I have the following side bar menu code. Upon click on any of the nav items it highlights / makes the class active.

$(document).ready(function() {
  $(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
      $(this).removeClass("active");
    }
    $(this).addClass("active");
  });

});

    System Settings

    Hosts

    Cards

    Printer

    Pinpad

Now I have similar items at the top of the page presented as a connected circle:

1

 System

2

 Hosts

3

 Cards

4

 Devices

See jsfiddle:
https://jsfiddle.net/vk3qw09f/345/

Now if the user clicks on the side bar menu, it should also set corresponding  class as active on the "connected-line" list elements.

For eg: Cliking on navbar "System Settings" should also add a class 'active' to the li item inside the circled li "System"

I know it's not recommednded to have the same 2 ids on the same page. So looking for a smarter way to achieve this.

EDIT: my current code will only make that class active: $(this).addClass("active");

I probably want to make all classes that share the same name active

Body:
Replace the code in your code. I hope, you can do it. Let me know, If any problem.

$(document).ready(function() {
  $(".nav li a").click(function() {

      $(".connected-line ul li").removeClass("active");
       id = $(this).prop('id');
     $("#" + id).addClass("active")

  });

});

<div class="connected-line">
  <ul>
    <li class="active"  id="system-settings">1
      <p> System </p>
    </li>
    <li id="hosts">2
      <p> Hosts </p>
    </li>
    <li  id="card-range">3
      <p> Cards </p>
    </li>
    <li id="pinpads">4
      <p> Devices </p>
    </li>
    <li id="xmls" >5
      <p> Lanes </p>
    </li>
  </ul>
</div>

<ul class="nav">
  <li class="nav-item">
    <a data-target="#system-settings" data-toggle="pill" class="nav-link" href="#system-settings" id="system-settings">System Settings</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#hosts" id="hosts" data-parent="#hosts">Hosts</a>
  </li>
  <li class="nav-item ">
    <a class="nav-link" href="#card-range" id="card-range">Cards</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="pinpads" href="#pinpads">Printer</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" id="xmls" href="#xmls">Pinpad</a>
  </li>

</ul>


答:
charAt is zero based.
You should use ab.charAt(0) if you use only a single char.

Another good advice is to start method names with a lower case and use the camelCase format.

Title: if char equals a letter then execute a code


问:
Bash preserve whitespaces and newlines from file content to variable
I have this code

```<code>TOKEN=$(cat ./config/token)

echo "$TOKEN"

cat > variables.env <<EOF
TOKEN=`echo "$TOKEN"`
EOF
</code>```

I am trying to get the content of a file and output it in a new file prefixed by some text. The first echo in the console echoes the output I want, keeping the whitespaces and newlines.

However, in the new file the output is just the first line of the original string, while I'd like the same output I can see in the console with the first echo.

答:
Use printf %q (in ksh or bash) to escape content in such a way that it will always evaluate back to its literal value:

```<code>printf 'TOKEN=%q\n' "$(<./config/token)" >variables.env
</code>```

$(<file) is a ksh and bash extension which acts as a more efficient replacement for $(cat file) (as the regular command substitution needs to fork off a subprocess, set up a FIFO, and spawn an external copy of /bin/cat, whereas the $(<file) form simply tells the shell to read the file directly).

This way a taken containing an otherwise-hostile string such as $(rm -rf ~) or content that could simply be expanded as a variable ($$) will be emitted as literal content.

Providing an explicit example of how this behaves:

```<code>printf '%s\n' "first line" "second line" >token # write two lines to the file "token"
printf 'TOKEN=%q\n' "$(<token)" >variables.env # write a shell command which assigns those
                                               # two lines to a variable to variables.env
source variables.env   # execute variables.env in the current shell
echo "$TOKEN"          # emit the value of TOKEN, as given in the current shell
</code>```

...when run with bash, will emit the exact output:

```<code>first line
second line
</code>```

...after writing the following (with bash 3.2.48; may vary with other releases) to variables.env:

```<code>TOKEN=$'first line\nsecond line'
</code>```

Body:
I have this code

TOKEN=$(cat ./config/token)

echo "$TOKEN"

cat > variables.env <<EOF
TOKEN=`echo "$TOKEN"`
EOF

I am trying to get the content of a file and output it in a new file prefixed by some text. The first echo in the console echoes the output I want, keeping the whitespaces and newlines.

However, in the new file the output is just the first line of the original string, while I'd like the same output I can see in the console with the first echo.

Body:
Use printf %q (in ksh or bash) to escape content in such a way that it will always evaluate back to its literal value:

printf 'TOKEN=%q\n' "$(<./config/token)" >variables.env

$(<file) is a ksh and bash extension which acts as a more efficient replacement for $(cat file) (as the regular command substitution needs to fork off a subprocess, set up a FIFO, and spawn an external copy of /bin/cat, whereas the $(<file) form simply tells the shell to read the file directly).

This way a taken containing an otherwise-hostile string such as $(rm -rf ~) or content that could simply be expanded as a variable ($$) will be emitted as literal content.

Providing an explicit example of how this behaves:

printf '%s\n' "first line" "second line" >token # write two lines to the file "token"
printf 'TOKEN=%q\n' "$(<token)" >variables.env # write a shell command which assigns those
                                               # two lines to a variable to variables.env
source variables.env   # execute variables.env in the current shell
echo "$TOKEN"          # emit the value of TOKEN, as given in the current shell

...when run with bash, will emit the exact output:

first line
second line

...after writing the following (with bash 3.2.48; may vary with other releases) to variables.env:

TOKEN=$'first line\nsecond line'


问:
State callback function being called before Fysom initialization from inside a class
I'm using Fysom to create a finite state machine in Python, and I'm seeing one issue which I don't know why it's happening.

I create a MyClass class, and inside that class I create a self.fsm member which is an instance of Fysom.

For some reason, the fsm member of my class seems to not exist when the first state of the finite state machine is reached. But when the second state is reached, it does exist.

from fysom import Fysom

class MyClass(object):
    def __init__(self):
        self.fsm = Fysom({
            'initial': 'start',
            'events': [ { 'src': 'start', 'name': 'go', 'dst': 'end' } ],
            'callbacks': {
                # States callbacks
                'onstart': self.on_start_callback,
                'onend': self.on_end_callback,
                # Events callbacks
                'onbeforego': self.show_event
            }
        })

    def on_start_callback(self, event):
        print "state: start"
        print "self attrs: {}".format(self.__dict__)

    def on_end_callback(self, event):
        print "state: end"
        print "self attrs: {}".format(self.__dict__)

    def show_event(_, event):
        print "event: {}".format(event.event)

def main():
    instance = MyClass()
    instance.fsm.go()

if __name__ == "__main__":
    main()
```

<p>And this is the output:</p>

```state: start
self attrs: {}
event: go
state: end
self attrs: {'fsm': <fysom.Fysom object at 0x7fe948f11510>}
```

Why the fsm member of MyClass doesn't exists when the initial state (start) is reached? Is not supposed to be created and initialized at the class constructor __init__?

My guess is that the on_start_callback (which is the callback for the initial state of the finite state machine) is called when the Fysom instance is being created and before it's assigned to the fsm member, therefore it fails when trying to access self.fsm. Is that what actually happens and is that the correct behavior?

I have found a workaround for that issue by creating an initial state that does nothing (or at least it doesn't access self at all) and then from the main function I manually trigger the event that transits to the real initial state which does access self (at that point is already defined).

答:
You guess is correct and it's the correct behavior. __init__ is executed in order. Your callback happens when the fsm is created and before it's assigned to self.fsm, so self.__dict__ is still empty.

After you've successfully instantiated and assigned the fsm, you could initialize it within the __init__:

```<code>class MyClass(object):
    def __init__(self):
        self.fsm = Fysom({
            'initial': 'none',
            'events': [
                { 'name': 'initialize', 'src': 'none', 'dst': 'start'},
                { 'src': 'start', 'name': 'go', 'dst': 'end' } ],
            'callbacks': {
                # States callbacks
                'onstart': self.on_start_callback,
                'onend': self.on_end_callback,
                # Events callbacks
                'onbeforego': self.show_event
            }
        })
        self.fsm.initialize()
</code>```

Body:
I'm using Fysom to create a finite state machine in Python, and I'm seeing one issue which I don't know why it's happening.

I create a MyClass class, and inside that class I create a self.fsm member which is an instance of Fysom.

For some reason, the fsm member of my class seems to not exist when the first state of the finite state machine is reached. But when the second state is reached, it does exist.

from fysom import Fysom

class MyClass(object):
    def __init__(self):
        self.fsm = Fysom({
            'initial': 'start',
            'events': [ { 'src': 'start', 'name': 'go', 'dst': 'end' } ],
            'callbacks': {
                # States callbacks
                'onstart': self.on_start_callback,
                'onend': self.on_end_callback,
                # Events callbacks
                'onbeforego': self.show_event
            }
        })

    def on_start_callback(self, event):
        print "state: start"
        print "self attrs: {}".format(self.__dict__)

    def on_end_callback(self, event):
        print "state: end"
        print "self attrs: {}".format(self.__dict__)

    def show_event(_, event):
        print "event: {}".format(event.event)

def main():
    instance = MyClass()
    instance.fsm.go()

if __name__ == "__main__":
    main()

And this is the output:

state: start
self attrs: {}
event: go
state: end
self attrs: {'fsm': <fysom.Fysom object at 0x7fe948f11510>}

Why the fsm member of MyClass doesn't exists when the initial state (start) is reached? Is not supposed to be created and initialized at the class constructor __init__?

My guess is that the on_start_callback (which is the callback for the initial state of the finite state machine) is called when the Fysom instance is being created and before it's assigned to the fsm member, therefore it fails when trying to access self.fsm. Is that what actually happens and is that the correct behavior?

I have found a workaround for that issue by creating an initial state that does nothing (or at least it doesn't access self at all) and then from the main function I manually trigger the event that transits to the real initial state which does access self (at that point is already defined).

Body:
You guess is correct and it's the correct behavior. __init__ is executed in order. Your callback happens when the fsm is created and before it's assigned to self.fsm, so self.__dict__ is still empty.

After you've successfully instantiated and assigned the fsm, you could initialize it within the __init__:

class MyClass(object):
    def __init__(self):
        self.fsm = Fysom({
            'initial': 'none',
            'events': [
                { 'name': 'initialize', 'src': 'none', 'dst': 'start'},
                { 'src': 'start', 'name': 'go', 'dst': 'end' } ],
            'callbacks': {
                # States callbacks
                'onstart': self.on_start_callback,
                'onend': self.on_end_callback,
                # Events callbacks
                'onbeforego': self.show_event
            }
        })
        self.fsm.initialize()


问:
ASP.NET MVC REST frameworks
There are number of REST frameworks around for ASP.NET MVC. Which one is the most mature in your opinion? Following are few I briefly looked at, but I couldn't decide.

Snooze

BistroMVC

Restful Service with WCF

OpenRasta

Siesta

REST support build in ASP.Net MVC SDK

.... there are few more.

答: Personally I would go with the default ASP.NET routing engine which is built and supported by Microsoft. This will ensure that you won't find yourself one day into the position of having to migrate some code which has become obsolete because the authors simply decided to abandon the project. Of course if there is something specific that you want to implement which isn't supported out of the box you could search for alternatives. But as far as exposing a RESTful API is concerned the routing engine should work just fine.</p>

Title: ASP.NET MVC REST frameworks


问:
bluetooth low energy; ble security
I am working on bluetooth low energy product which has no I/O capabilities. Wondering how we can make pair two products secure with out exchanging the key?

Thanks in advance

答:
There are two possible approaches:

1) Configure your product to generate a fixed key, if possible, and include the key value in the user guide for your product.
2) Use the "JustWorks" pairing method.  This uses the Numeric Comparison protocol but the user is never shown a number.  From the Bluetooth standard (V4.2): "The JustWorks association model provides the same protection as the Numeric Comparison association model against passive eavesdropping but offers no protection against the MITM (man-in-the-middle) attack."

Consult the documentation for your radio or contact the radio supplier for information on how to implement either of these methods.

Title: bluetooth low energy; ble security


问:
PHP7 - SQL Server
I have the problem to retrieve information from SQL server database.
But no problem to insert data.

this is the simple code:

```<code>$serverName = "xx.xx.xx.xx\SQLEXPRESS,1433";
$connectionOptions = array(
    "Database" => "Test",
    "Uid" => "User",
    "PWD" => "Password"
);

$connection = sqlsrv_connect($serverName, $connectionOptions);

if (!connection) {
    die("Database connection failed: " . mssql_get_last_message() );
} else {
    echo("Connected Successfully </br>" );
}

$sql = " INSERT INTO Imaging (ap) VALUES (1)";
$result = sqlsrv_query( $connection, $sql);
</code>```

This code working perfectly.

But if I trying to retrieve data

```<code>$sql = "select ap from Imaging ";
$result = sqlsrv_query( $connection, $sql);

var_dump($result);
</code>```

I have this result.
Connected Successfully
resource(2) of type (SQL Server Statement)

What is wrong?

Thank you

答:
That's because $result is a resource;

From the man page of sqlsrv_fetch_array your code must be like so:

```<code>while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
    echo $row['ap'];
}
</code>```

Title: PHP7 - SQL Server

Body:
I have the problem to retrieve information from SQL server database.
But no problem to insert data.

this is the simple code:

$serverName = "xx.xx.xx.xx\SQLEXPRESS,1433";
$connectionOptions = array(
    "Database" => "Test",
    "Uid" => "User",
    "PWD" => "Password"
);

$connection = sqlsrv_connect($serverName, $connectionOptions);

if (!connection) {
    die("Database connection failed: " . mssql_get_last_message() );
} else {
    echo("Connected Successfully
" );
}

$sql = " INSERT INTO Imaging (ap) VALUES (1)";
$result = sqlsrv_query( $connection, $sql);

This code working perfectly.

But if I trying to retrieve data

$sql = "select ap from Imaging ";
$result = sqlsrv_query( $connection, $sql);

var_dump($result);

I have this result.
Connected Successfully
resource(2) of type (SQL Server Statement)

What is wrong?

Thank you

Body:
That's because $result is a resource;

From the man page of sqlsrv_fetch_array your code must be like so:

while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
    echo $row['ap'];
}


问:
Automatically Add Layers to a Dictionary in Python

I'm creating a program that uses a dictionary to store large trees of web links in Python. Basically, you start with the root URL, and that creates a dictionary based on the URLs found from the HTML of the root. In the next step, I want to get the pages of each of those URLs and grab the links on those URLs. Eventually, I want to have a dictionary with all the links in it and their relation to each other.

This is what I have for the first two depths

```<code>for link in soup.find_all('a'):
   url = link.get('href')
   url_tree[siteurl][url]
 #Get page source
   for link in soup.find_all('a'):
     url = link.get('href')
     url_tree[siteurl][secondurl][url]
</code>```

This system works, but as you can tell, if I want a dictionary N layers deep, that gets to be a lot of blocks of code. Is there a way to automatically add more layers? Any help is appreciated!

答:
This can be done using recursive functions.

A basic example which will crawl all the urls found in a page one by one, then crawl all the urls found in that page one by one, and so on... It will also print out every url it finds.

```<code>def recursive_fetch(url_to_fetch):
    # get page source from url_to_fetch
    # make a new soup
    for link in soup.find_all('a'):
        url = link.get('href')
        print url
        # run the function recursively
        # for the current url
        recursive_fetch(url)

# Usage
recursive_fetch(root_url)
</code>```

Since you want to have a dict of tree of all the urls found, the above code isn't much helpful, but it's a start.

This is where it gets really complex. Because now you'll also need to keep track of the parent of the current url being crawled, the parent of that url, parent of that url, parent of that url, parent of ...

You see, what I mean? It gets very complex, very fast.

Below is the code that does all that. I've written comments in the code to explain it as best as I can. But you'll need to actually understand how recursive functions work for a better understanding.

First, let's look at another function which will be very helpful in getting the parent of a url from the tree:

```<code>def get_parent(tree, parent_list):
    """How it works:

    Let's say the `tree` looks like this:

        tree = {
            'root-url': {
                'link-1': {
                    'link-1-a': {...}
                }
            }
        }

    and `parent_list` looks like this:

        parent_list = ['root-url', 'link-1', 'link-1-a']

    this function will chain the values in the list and
    perform a dict lookup like this:

        tree['root-url']['link-1']['link-1-a']
    """

    first, rest = parent_list[0], parent_list[1:]
    try:
        if tree[first] and rest:
            # if tree or rest aren't empty
            # run the function recursively
            return get_parent(tree[first], rest)
        else:
            return tree[first]
    except KeyError:
        # this is required for creating the
        # root_url dict in the tree
        # because it doesn't exist yet

        tree[first] = {}
        return tree[first]
</code>```

And the recursive_fetch function will look like this:

```<code>url_tree = {} # dict to store the url tree

def recursive_fetch(fetch_url, parents=None):
    """
    `parents` is a list of parents of the current url
     Example:
         parents = ['root-url', 'link-1', ... 'parent-link']
    """
    parents = parents or []

    parents.append(fetch_url)

    # get page source from fetch_url
    # make new soup object

    for link in soup.find_all('a'):
        url = link.get('href')

        if parents:
            parent = get_parent(url_tree, parents)
        else:
            parent = None

        if parent is not None:
            # this will run when parent is not None
            # i.e. even if parent is empty dict {}

            # create a new dict of the current url
            # inside the parent dict
            parent[url] = {}
        else:
            # this url has no parent,
            # insert this directly in the url_tree
            url_tree[url] = {}

        # now crawl the current url
        recursive_fetch(url, parents)

    # Next is the most import block of code
    # Whenever 1 recursion completes,
    # it will pop the last parent from
    # the `parents` list so that in the
    # next recursion, the parents are correct.
    # Whithout this block, the url_tree wouldn't
    # look as expected.
    # It took me many hours to figure this out

    try:
        parents.pop(-1)
    except IndexError:
        pass
</code>```

Body:
I'm creating a program that uses a dictionary to store large trees of web links in Python. Basically, you start with the root URL, and that creates a dictionary based on the URLs found from the HTML of the root. In the next step, I want to get the pages of each of those URLs and grab the links on those URLs. Eventually, I want to have a dictionary with all the links in it and their relation to each other.

This is what I have for the first two depths

for link in soup.find_all('a'):
   url = link.get('href')
   url_tree[siteurl][url]
 #Get page source
   for link in soup.find_all('a'):
     url = link.get('href')
     url_tree[siteurl][secondurl][url]

This system works, but as you can tell, if I want a dictionary N layers deep, that gets to be a lot of blocks of code. Is there a way to automatically add more layers? Any help is appreciated!

Body:
This can be done using recursive functions.

A basic example which will crawl all the urls found in a page one by one, then crawl all the urls found in that page one by one, and so on... It will also print out every url it finds.

def recursive_fetch(url_to_fetch):
    # get page source from url_to_fetch
    # make a new soup
    for link in soup.find_all('a'):
        url = link.get('href')
        print url
        # run the function recursively
        # for the current url
        recursive_fetch(url)

# Usage
recursive_fetch(root_url)

Since you want to have a dict of tree of all the urls found, the above code isn't much helpful, but it's a start.

This is where it gets really complex. Because now you'll also need to keep track of the parent of the current url being crawled, the parent of that url, parent of that url, parent of that url, parent of ...

You see, what I mean? It gets very complex, very fast.

Below is the code that does all that. I've written comments in the code to explain it as best as I can. But you'll need to actually understand how recursive functions work for a better understanding.

First, let's look at another function which will be very helpful in getting the parent of a url from the tree:

def get_parent(tree, parent_list):
    """How it works:

    Let's say the `tree` looks like this:

        tree = {
            'root-url': {
                'link-1': {
                    'link-1-a': {...}
                }
            }
        }

    and `parent_list` looks like this:

        parent_list = ['root-url', 'link-1', 'link-1-a']

    this function will chain the values in the list and
    perform a dict lookup like this:

        tree['root-url']['link-1']['link-1-a']
    """

    first, rest = parent_list[0], parent_list[1:]
    try:
        if tree[first] and rest:
            # if tree or rest aren't empty
            # run the function recursively
            return get_parent(tree[first], rest)
        else:
            return tree[first]
    except KeyError:
        # this is required for creating the
        # root_url dict in the tree
        # because it doesn't exist yet

        tree[first] = {}
        return tree[first]

And the recursive_fetch function will look like this:

url_tree = {} # dict to store the url tree

def recursive_fetch(fetch_url, parents=None):
    """
    `parents` is a list of parents of the current url
     Example:
         parents = ['root-url', 'link-1', ... 'parent-link']
    """
    parents = parents or []

    parents.append(fetch_url)

    # get page source from fetch_url
    # make new soup object

    for link in soup.find_all('a'):
        url = link.get('href')

        if parents:
            parent = get_parent(url_tree, parents)
        else:
            parent = None

        if parent is not None:
            # this will run when parent is not None
            # i.e. even if parent is empty dict {}

            # create a new dict of the current url
            # inside the parent dict
            parent[url] = {}
        else:
            # this url has no parent,
            # insert this directly in the url_tree
            url_tree[url] = {}

        # now crawl the current url
        recursive_fetch(url, parents)

    # Next is the most import block of code
    # Whenever 1 recursion completes,
    # it will pop the last parent from
    # the `parents` list so that in the
    # next recursion, the parents are correct.
    # Whithout this block, the url_tree wouldn't
    # look as expected.
    # It took me many hours to figure this out

    try:
        parents.pop(-1)
    except IndexError:
        pass


问:
Reading 2-D array from a file
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is : </p>

```<code>import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}
</code>```

答:
while (input.next()!=null)

This will consume something from the scanner input stream. Instead, try using while (input.hasNextInt())

Depending on how robust you want your code to be, you should also check inside the for loop that something is available to be read.

```<code>Scanner input = new Scanner (new File("src/array.txt"));
// pre-read in the number of rows/columns
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
    ++rows;
    Scanner colReader = new Scanner(input.nextLine());
    while(colReader.hasNextInt())
    {
        ++columns;
    }
}
int[][] a = new int[rows][columns];

input.close();

// read in the data
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i &lt rows; ++i)
{
    for(int j = 0; j &lt columns; ++j)
    {
        if(input.hasNextInt())
        {
            a[i][j] = input.nextInt();
        }
    }
}
</code>```

An alternative using ArrayLists (no pre-reading required):

```<code>// read in the data
ArrayList&ltArrayList&ltInteger&gt&gt a = new ArrayList&ltArrayList&ltInteger&gt&gt();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
    Scanner colReader = new Scanner(input.nextLine());
    ArrayList col = new ArrayList();
    while(colReader.hasNextInt())
    {
        col.add(colReader.nextInt());
    }
    a.add(col);
}
</code>```

Title: Reading 2-D array from a file

Body:
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :

import java.util.*;
import java.lang.*;
import java.io.*;

public class appMainNineSix {

    /**
     * @param args
     */
    public static void main(String[] args)
        throws java.io.FileNotFoundException{
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("src/array.txt"));
        int m = 3;
        int n = 5;
        int[][] a = new int [m][n];
        while (input.next()!=null){
            for (int i=0;i<m;i++){
                for (int j=0;j<n;j++)
                    a[i][j]= input.nextInt();
            }

        }
        //print the input matrix
        System.out.println("The input sorted matrix is : ");
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++)
                System.out.println(a[i][j]);
        }

    }

}

Body:
while (input.next()!=null)

This will consume something from the scanner input stream. Instead, try using while (input.hasNextInt())

Depending on how robust you want your code to be, you should also check inside the for loop that something is available to be read.

Scanner input = new Scanner (new File("src/array.txt"));
// pre-read in the number of rows/columns
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
    ++rows;
    Scanner colReader = new Scanner(input.nextLine());
    while(colReader.hasNextInt())
    {
        ++columns;
    }
}
int[][] a = new int[rows][columns];

input.close();

// read in the data
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i &lt rows; ++i)
{
    for(int j = 0; j &lt columns; ++j)
    {
        if(input.hasNextInt())
        {
            a[i][j] = input.nextInt();
        }
    }
}

An alternative using ArrayLists (no pre-reading required):

// read in the data
ArrayList&ltArrayList&ltInteger&gt&gt a = new ArrayList&ltArrayList&ltInteger&gt&gt();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
    Scanner colReader = new Scanner(input.nextLine());
    ArrayList col = new ArrayList();
    while(colReader.hasNextInt())
    {
        col.add(colReader.nextInt());
    }
    a.add(col);
}