问:
Installing Node.js (and npm) on Windows 10
I had some issues trying to install Node on Windows 10 and found the solution.

The error was as follows:

C:\Users\Stephan>npm

  Error: ENOENT, stat 'C:\Users\Stephan\AppData\Roaming\npm'

The solution is below.

答:
Everything should be installed in %appdata% (C:\Users\\AppData\Roaming), not 'program files'.

Here's why...

The default MSI installer puts Node and the NPM that comes with it in 'program files' and adds this to the system path, but it sets the user path for NPM to %appdata% (c:\users[username]\appdata\roaming) since the user doesn't have sufficient priveleges to write to 'program files'.

This creates a mess as all modules go into %appdata%, and when you upgrade NPM itself - which NPM themselves recommend you do right away - you end up with two copies: the original still in 'program files' since NPM can't erase that, and the new one inn %appdata%.

Even worse, if you mistakenly perform NPM operations as admin (much easier on Windows then on *nix) then it will operate on the 'program files' copy of NPM node_modules.  Potentially a real mess.

So, when you run the installer simply point it to %appdata% and avoid all this.

And note that this isn't anything wierd - it’s what would happen if you ran the installer with just user priveleges.


来源: stackexchange

问:
Error: Can't set headers after they are sent while reading files
I'm getting below error while trying to read file and sending the response back to browser.

```<code>[ 'Error: Can\'t set headers after they are sent.',
  '    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)',
  '    at ServerResponse.setWriteHeadHeaders (/somepath/node_modules/on-headers/index.js:82:19)',
  '    at ServerResponse.writeHead (/somepath/node_modules/on-headers/index.js:41:36)',
  '    at /somepath/server/custom.js:71:13',
  '    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)' ]
</code>```

var fs = require('fs');

exports.customPageChatStatus = function(req, res) {
 if(req.params._pagename === 'Test123')
 {
      fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 if(req.params._pagename === 'SecondFile')
 {
      fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 else {
  fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
};```

Interestingly I'm seeing the above error only when reading 1st file (Test123.txt) and no issue when reading "SecondFile.txt".

Appreciate any help on resolving this!

答:
here if you use else if in your statements that will resolve your issue</p>

```<code>var fs = require('fs');

    exports.customPageChatStatus = function(req, res) {
        if(req.params._pagename === 'Test123')
        {
                fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
              if (err) console.log(err);
               res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
            res.end(data);
                });
        }
        else if(req.params._pagename === 'SecondFile')
        {
                fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
               if (err) console.log(err);
               res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
            res.end(data);
                });
        }
        else {
            fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
               res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
            res.end(data);
                });
        }
    };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm getting below error while trying to read file and sending the response back to browser.

[ 'Error: Can\'t set headers after they are sent.',
  '    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)',
  '    at ServerResponse.setWriteHeadHeaders (/somepath/node_modules/on-headers/index.js:82:19)',
  '    at ServerResponse.writeHead (/somepath/node_modules/on-headers/index.js:41:36)',
  '    at /somepath/server/custom.js:71:13',
  '    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)' ]

var fs = require('fs');

exports.customPageChatStatus = function(req, res) {
 if(req.params._pagename === 'Test123')
 {
      fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 if(req.params._pagename === 'SecondFile')
 {
      fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
        if (err) console.log(err);
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
 else {
  fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
        res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
        res.end(data);
      });
 }
};

Interestingly I'm seeing the above error only when reading 1st file (Test123.txt) and no issue when reading "SecondFile.txt".

Appreciate any help on resolving this!

Body:
here if you use else if in your statements that will resolve your issue

var fs = require('fs');

    exports.customPageChatStatus = function(req, res) {
        if(req.params._pagename === 'Test123')
        {
                fs.readFile("/somepath/Test123.txt", 'utf-8', function(err, data) {
              if (err) console.log(err);
               res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
            res.end(data);
                });
        }
        else if(req.params._pagename === 'SecondFile')
        {
                fs.readFile("/somepath/SecondFile.txt", 'utf-8', function(err, data) {
               if (err) console.log(err);
               res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
            res.end(data);
                });
        }
        else {
            fs.readFile("/somepath/InActive.txt", 'utf-8', function(err, data) {
               res.writeHead(200, {'Content-Type':'text/plain', 'Access-Control-Allow-Origin':'*' });
            res.end(data);
                });
        }
    };


问:
What to do, Learn while Developing the app or Learn first and then develop the app
I am planning to develop a web and mobile application. Have a look on this Question on OnStartups

I have some PHP & MySql knowledge, however I didn't do any major projects so far.

My skills on a scale of 5

PHP&MySql 3/5,

Javascript 3/5

CSS 3/5

Android 1.5/5

IPhone    0/5

web development (2/5)

web    design(2/5)

Software Development &    management
(1.5/5)

My app, as said in one of the answers
in the question, is not much complex
as Mint. If the complexity of Mint is
rated 8. My app would be 5/8

I have lot of interest in programming. Only thing bothering and bogging me is the time to make the app live. I don't understand how to estimate the time as I am not so experienced.

Should I start developing the app and learn all the concepts on the way?

or

should I wait learn programming completely first and then develop the app.?

Edit: A small Edit based on below answers. How should I test myself to know whether I have the minimum web development knowledge to start developing the application.

答:
In my opinion, it depends on wether you're gonna develop the project alone, or eventually let other people join you in your development. Having some experiences in working with beginner-programmers, I'd say the biggest problem is the way they structure (or don't structure) the application and code they produce, often making it very difficult to get an understanding of the structure and layout.

If you're in this on your own though, I'd say just go for it, start programming and learn on the way.

ContentLicense: CC BY-SA 2.5


问:
Finding most similar items by euclidean and cosine
How do I go about finding similarities in R? In particular, the similarity metrics I care most about are cosine and a KNN-# value. I guess the key aspect of this is so that the data comes out in a usable shape for me.

For example using the built in mtcars dataset, I would want to find the most similar items.

```<code> library(tidyverse)
mtcars$item = rownames(mtcars)
mtcars = mtcars %>% select(item, mpg, hp, qsec) # use these 3 fields to find similar items.
  #help <here>

#desired format would be have the <N> most similar items in <N> columns indicating their respective importance
# desired format would also have the weightings of each of these items
mtcars$similar_1 = #most similar item
mtcars$similar_1_score = #.8
...
mtcars$similar_5 = #5th most similar item
mtcars$similar_5_score = #score associated with them.
</code>```

I'd like to be able to do this again with a KNN approach using Euclidean distance and then a separate cosine score.

答:
Here is one possible solituin, where you're using the dist() function for calculating the Eucledian distances. First, you calculate the distances for all items, then get the order for all items. From that order you pick the ith one and select that score and item label for each item and put that in a data frame, which you bind to your original one after.

```<code>    mtcars$item = rownames(mtcars)
    data <- (mtcars %>% select(item, mpg, hp, qsec))[1:10,]

    euc_dist <- as.matrix(dist(data[1:10,-1]))

    # Get the ith cars label name for one car
    ith_item <- function(col, euc_dist, top_i) {
      labels(euc_dist)[[1]][top_i[col]]
    }

    # Get the ith cars score from one column
    ith_score <- function(col, euc_dist, top_i) {
      euc_dist[top_i[col], col]
    }

    # Create a dataframe with the ith most similar item for all items
    ith_similar <- function(euc_dist, i) {
      orders <- apply(euc_dist, 2, order)
      top_i <- orders[i + 1, ]

      top_i_score <- sapply(1:ncol(euc_dist), ith_score, euc_dist, top_i)
      top_i_items <- sapply(1:ncol(euc_dist), ith_item, euc_dist, top_i)

      similarities <- data.frame(placeholder1 = top_i_score,
                                 placeholder2 = top_i_items)

      colnames <- c(paste0("similar_", i, "_score"), paste0("similar_", i))
      names(similarities) <- colnames

      similarities
    }

    # For example top 2 similarities
    n <- 2

    for(i in 1:n) {
      tmp_similarities <- ith_similar(euc_dist, i)

      data <- cbind(data, tmp_similarities)
    }

    data
</code>```

This will give the output of:

```<code>                           item  mpg  hp  qsec similar_1_score         similar_1 similar_2_score      similar_2
Mazda RX4                 Mazda RX4 21.0 110 16.46        0.560000     Mazda RX4 Wag        3.006726 Hornet 4 Drive
Mazda RX4 Wag         Mazda RX4 Wag 21.0 110 17.02        0.560000         Mazda RX4        2.452835 Hornet 4 Drive
Datsun 710               Datsun 710 22.8  93 18.61        4.733297          Merc 230       12.987767        Valiant
Hornet 4 Drive       Hornet 4 Drive 21.4 110 19.44        2.452835     Mazda RX4 Wag        3.006726      Mazda RX4
Hornet Sportabout Hornet Sportabout 18.7 175 17.02       52.018155          Merc 280       65.040680  Mazda RX4 Wag
Valiant                     Valiant 18.1 105 20.22        6.041391    Hornet 4 Drive        6.606815  Mazda RX4 Wag
Duster 360               Duster 360 14.3 245 15.84       70.148075 Hornet Sportabout      122.123141       Merc 280
Merc 240D                 Merc 240D 24.4  62 20.00       31.072369        Datsun 710       33.165796       Merc 230
Merc 230                   Merc 230 22.8  95 22.90        4.733297        Datsun 710       11.369802        Valiant
Merc 280                   Merc 280 19.2 123 18.30       13.186296     Mazda RX4 Wag       13.234032 Hornet 4 Drive
</code>```

Body:
How do I go about finding similarities in R? In particular, the similarity metrics I care most about are cosine and a KNN-# value. I guess the key aspect of this is so that the data comes out in a usable shape for me.

For example using the built in mtcars dataset, I would want to find the most similar items.

 library(tidyverse)
mtcars$item = rownames(mtcars)
mtcars = mtcars %>% select(item, mpg, hp, qsec) # use these 3 fields to find similar items.
  #help <here>

#desired format would be have the <N> most similar items in <N> columns indicating their respective importance
# desired format would also have the weightings of each of these items
mtcars$similar_1 = #most similar item
mtcars$similar_1_score = #.8
...
mtcars$similar_5 = #5th most similar item
mtcars$similar_5_score = #score associated with them.

I'd like to be able to do this again with a KNN approach using Euclidean distance and then a separate cosine score.

Body:
Here is one possible solituin, where you're using the dist() function for calculating the Eucledian distances. First, you calculate the distances for all items, then get the order for all items. From that order you pick the ith one and select that score and item label for each item and put that in a data frame, which you bind to your original one after.

    mtcars$item = rownames(mtcars)
    data <- (mtcars %>% select(item, mpg, hp, qsec))[1:10,]

    euc_dist <- as.matrix(dist(data[1:10,-1]))

    # Get the ith cars label name for one car
    ith_item <- function(col, euc_dist, top_i) {
      labels(euc_dist)[[1]][top_i[col]]
    }

    # Get the ith cars score from one column
    ith_score <- function(col, euc_dist, top_i) {
      euc_dist[top_i[col], col]
    }

    # Create a dataframe with the ith most similar item for all items
    ith_similar <- function(euc_dist, i) {
      orders <- apply(euc_dist, 2, order)
      top_i <- orders[i + 1, ]

      top_i_score <- sapply(1:ncol(euc_dist), ith_score, euc_dist, top_i)
      top_i_items <- sapply(1:ncol(euc_dist), ith_item, euc_dist, top_i)

      similarities <- data.frame(placeholder1 = top_i_score,
                                 placeholder2 = top_i_items)

      colnames <- c(paste0("similar_", i, "_score"), paste0("similar_", i))
      names(similarities) <- colnames

      similarities
    }

    # For example top 2 similarities
    n <- 2

    for(i in 1:n) {
      tmp_similarities <- ith_similar(euc_dist, i)

      data <- cbind(data, tmp_similarities)
    }

    data

This will give the output of:

                           item  mpg  hp  qsec similar_1_score         similar_1 similar_2_score      similar_2
Mazda RX4                 Mazda RX4 21.0 110 16.46        0.560000     Mazda RX4 Wag        3.006726 Hornet 4 Drive
Mazda RX4 Wag         Mazda RX4 Wag 21.0 110 17.02        0.560000         Mazda RX4        2.452835 Hornet 4 Drive
Datsun 710               Datsun 710 22.8  93 18.61        4.733297          Merc 230       12.987767        Valiant
Hornet 4 Drive       Hornet 4 Drive 21.4 110 19.44        2.452835     Mazda RX4 Wag        3.006726      Mazda RX4
Hornet Sportabout Hornet Sportabout 18.7 175 17.02       52.018155          Merc 280       65.040680  Mazda RX4 Wag
Valiant                     Valiant 18.1 105 20.22        6.041391    Hornet 4 Drive        6.606815  Mazda RX4 Wag
Duster 360               Duster 360 14.3 245 15.84       70.148075 Hornet Sportabout      122.123141       Merc 280
Merc 240D                 Merc 240D 24.4  62 20.00       31.072369        Datsun 710       33.165796       Merc 230
Merc 230                   Merc 230 22.8  95 22.90        4.733297        Datsun 710       11.369802        Valiant
Merc 280                   Merc 280 19.2 123 18.30       13.186296     Mazda RX4 Wag       13.234032 Hornet 4 Drive


问:
Reading the contents of several files into a list in Python
I have a shell script which pipes the files of a certain directory into a file titled "list.txt".
I am trying to write a python script that reads in the names of the files inside list.txt, opens them, and saves their contents to a list. Each file inside of list.txt contains two numbers on two different lines. So far, I have been able to read in the files of the names of the files in the directory, however I keep getting an error when trying to read in the contents of the files:

IndexError: list assignment index out of range

Below is the code I have written so far:

```<code>f = open("list.txt")
file = f.readlines()
f.close()
del file[0]
del file[0]
file = [w.replace('\n','') for w in file]
#print file

length_file = len(file)
data = []

for i in range(0,1):
        fa = open(file[i])
#       print fa
        data[i] = fa.read()
        fa.close()
        data[i] = [t.replace('\n','') for t in data]
#print i
#print data
#print data[1]
</code>```

The error occurs on the line data[i] = fa.read() statement.

Any help is greatly appreciated! Thanks in advance!

答:
Getting this error

```<code>IndexError: list assignment index out of range
</code>```

When trying to access at element means that the location in the list does not exist.

Since your range is setup to have only an index of 0, that means that file is empty when you try to call it.

I assume it has something to do with this deleting the entries in file before you try to call them further down in that for loop, but cannot be sure:

```<code>del file[0]
del file[0]
</code>```

What you can do to check is print file in that loop.  Also, it is more idiomatic to setup a for loop using readlines like this:

```<code>f = open('yourfile.txt','r')
for line in f.readlines():
    # do something
f.close()
</code>```

Body:
I have a shell script which pipes the files of a certain directory into a file titled "list.txt".
I am trying to write a python script that reads in the names of the files inside list.txt, opens them, and saves their contents to a list. Each file inside of list.txt contains two numbers on two different lines. So far, I have been able to read in the files of the names of the files in the directory, however I keep getting an error when trying to read in the contents of the files:

IndexError: list assignment index out of range

Below is the code I have written so far:

f = open("list.txt")
file = f.readlines()
f.close()
del file[0]
del file[0]
file = [w.replace('\n','') for w in file]
#print file

length_file = len(file)
data = []

for i in range(0,1):
        fa = open(file[i])
#       print fa
        data[i] = fa.read()
        fa.close()
        data[i] = [t.replace('\n','') for t in data]
#print i
#print data
#print data[1]

The error occurs on the line data[i] = fa.read() statement.

Any help is greatly appreciated! Thanks in advance!

Body:
Getting this error

IndexError: list assignment index out of range

When trying to access at element means that the location in the list does not exist.

Since your range is setup to have only an index of 0, that means that file is empty when you try to call it.

I assume it has something to do with this deleting the entries in file before you try to call them further down in that for loop, but cannot be sure:

del file[0]
del file[0]

What you can do to check is print file in that loop.  Also, it is more idiomatic to setup a for loop using readlines like this:

f = open('yourfile.txt','r')
for line in f.readlines():
    # do something
f.close()


问:
Using PyQt to integrate a qml based Chart to an existing ui
I am using PyQt and have the legacy application in it. In this UI based application I would like to add real time graphs defined in qml(say using QtCharts). I am able to load a basic qml file with QtQuick 2.0 and QtQuick.Controls. But I am not able to import qml files with QtCharts. </p>

<p>Is there any other better way of plotting real time graphs efficiently using qml on a PyQt application ? </p>

答:
QtChart solution(Refer creator example qmloscilloscope)

In QML file Call python function with QML LineSeries object as argument. Property useOpenGL is supported only for LineSeries and ScatterSeries. Other series, such as BarSeries is less efficient than these two.

QML file:

```<code>    LineSeries{
        id: lineSeries
        name: "signal"
        useOpenGL: true
        axisX: ValueAxis {
            id: axisX
            min: 0
            max: 10
        }
        axisY: ValueAxis {
            id: axisY
            min: 0
            max: 100
        }
    }
    Timer {
        interval: 1000/25
        running: true
        repeat: true
        onTriggered: modelSpectrum.update(lineSeries)
    }
</code>```

Python file:

```<code>...
@pyqtSlot(QObject)
def update(self, series):
    series.clear()
    for i in range(10):
        series.append(i, random.random()*100)
</code>```

Body:
I am using PyQt and have the legacy application in it. In this UI based application I would like to add real time graphs defined in qml(say using QtCharts). I am able to load a basic qml file with QtQuick 2.0 and QtQuick.Controls. But I am not able to import qml files with QtCharts.

Is there any other better way of plotting real time graphs efficiently using qml on a PyQt application ?

Body:
QtChart solution(Refer creator example qmloscilloscope)

In QML file Call python function with QML LineSeries object as argument. Property useOpenGL is supported only for LineSeries and ScatterSeries. Other series, such as BarSeries is less efficient than these two.

QML file:

    LineSeries{
        id: lineSeries
        name: "signal"
        useOpenGL: true
        axisX: ValueAxis {
            id: axisX
            min: 0
            max: 10
        }
        axisY: ValueAxis {
            id: axisY
            min: 0
            max: 100
        }
    }
    Timer {
        interval: 1000/25
        running: true
        repeat: true
        onTriggered: modelSpectrum.update(lineSeries)
    }

Python file:

...
@pyqtSlot(QObject)
def update(self, series):
    series.clear()
    for i in range(10):
        series.append(i, random.random()*100)


问:
Printing from a method
```<code>public class Simple2DArray {

    public static void main(String[] args) {

    }
    public static void fill()
    {
        int[][] grid = new int[5][5];
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                grid[r][c] = (int)(Math.random()*100);
            }
        }
    }
    public static int biggest(int[][] grid, int big)
    {
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                if(grid[r][c]> big)
                {
                    big = grid[r][c];
                }
            }
        }
        System.out.println(big);
        return big;
    }
}
</code>```

I would like for it to print big. How do I do this? I tried putting System.out.println(biggest(null,big) in the main method but that did not work.

答:
I got solution

But first of all go through https://stackoverflow.com/help/how-to-ask

Your solution

I made some changes in your code.

```<code>public class Simple2DArray {

public static void main(String[] args) {

    int[][] grid = fill();

    System.out.println(biggest(grid, 20));

}

public static int[][] fill()
{
    int[][] grid = new int[5][5];
    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            grid[r][c] = (int)(Math.random()*100);
        }
    }

    System.out.println("Input 2D");

    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            System.out.print(grid[r][c]);
            System.out.print("\t");
        }

        System.out.println("");
    }

    return grid;
}

public static int biggest(int[][] grid, int big)
{
    if (grid != null) {
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] > big) {
                    big = grid[r][c];
                }
            }
        }
    }

    return big;
}

}
</code>```

Title: Printing from a method

Body:
public class Simple2DArray {

    public static void main(String[] args) {

    }
    public static void fill()
    {
        int[][] grid = new int[5][5];
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                grid[r][c] = (int)(Math.random()*100);
            }
        }
    }
    public static int biggest(int[][] grid, int big)
    {
        for(int r=0;r<grid.length;r++)
        {
            for(int c=0;c<grid[r].length;r++)
            {
                if(grid[r][c]> big)
                {
                    big = grid[r][c];
                }
            }
        }
        System.out.println(big);
        return big;
    }
}

I would like for it to print big. How do I do this? I tried putting System.out.println(biggest(null,big) in the main method but that did not work.

Body:
I got solution

But first of all go through https://stackoverflow.com/help/how-to-ask

Your solution

I made some changes in your code.

public class Simple2DArray {

public static void main(String[] args) {

    int[][] grid = fill();

    System.out.println(biggest(grid, 20));

}

public static int[][] fill()
{
    int[][] grid = new int[5][5];
    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            grid[r][c] = (int)(Math.random()*100);
        }
    }

    System.out.println("Input 2D");

    for(int r=0;r<grid.length;r++)
    {
        for(int c=0;c<grid[r].length;c++)
        {
            System.out.print(grid[r][c]);
            System.out.print("\t");
        }

        System.out.println("");
    }

    return grid;
}

public static int biggest(int[][] grid, int big)
{
    if (grid != null) {
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] > big) {
                    big = grid[r][c];
                }
            }
        }
    }

    return big;
}

}


问:
Print keys and values from dictionary in descending order without importing operator(Python)
For my assignment I'm writing a program that will take the contents of a file, store it into a dictionary, count and output the number of occurrences of each word in the file, and output the ten most frequently occurring words in descending order.

Here is my code. I didn't want to use import operator, but I'm trying to sort the contents in my dictionary. Right now I have the values printing in sorted order but not with the key in front. How do I print the key words from the dictionary, with the number of occurrences attached, in descending order?

```<code>done = False
while not done:
    try:
        print("ENTER A FILE NAME, IF NOT IN SAME FILE LOCATION AS PROGRAM, SPECIFY PATH")
        input_file_name = input("Please Enter the name of your text file: ")
        infile = open(input_file_name, "r")
        done = True

    except FileNotFoundError:
        done = False
        print("File not Found")

myDict = {}
file = infile.read()
line = file.split()
unwanted_chars = ".,!-_)(*&^%$#@:;'<>?/\{}[]|+=~`"

for symbol in line:
    word = symbol.strip(unwanted_chars)
    if word not in myDict:
        myDict[word] = 0
    myDict[word] = myDict[word] + 1

sortedValues = sorted(myDict.values())

print(myDict)
print(sortedValues)

infile.close()
</code>```

答:
Python 2

```<code>sorted_dict = sorted([(value,key) for (key,value) in myDict.iteritems()])
</code>```

Python 3

```<code>sorted_dict = sorted([(value,key) for (key,value) in myDict.items()])
</code>```

Printing for both python 2 and 3

```<code>print([(key, value) for value, key in sorted_dict]
</code>```

Body:
For my assignment I'm writing a program that will take the contents of a file, store it into a dictionary, count and output the number of occurrences of each word in the file, and output the ten most frequently occurring words in descending order.

Here is my code. I didn't want to use import operator, but I'm trying to sort the contents in my dictionary. Right now I have the values printing in sorted order but not with the key in front. How do I print the key words from the dictionary, with the number of occurrences attached, in descending order?

done = False
while not done:
    try:
        print("ENTER A FILE NAME, IF NOT IN SAME FILE LOCATION AS PROGRAM, SPECIFY PATH")
        input_file_name = input("Please Enter the name of your text file: ")
        infile = open(input_file_name, "r")
        done = True

    except FileNotFoundError:
        done = False
        print("File not Found")

myDict = {}
file = infile.read()
line = file.split()
unwanted_chars = ".,!-_)(*&^%$#@:;'<>?/\{}[]|+=~`"

for symbol in line:
    word = symbol.strip(unwanted_chars)
    if word not in myDict:
        myDict[word] = 0
    myDict[word] = myDict[word] + 1

sortedValues = sorted(myDict.values())

print(myDict)
print(sortedValues)

infile.close()

Body:
Python 2

sorted_dict = sorted([(value,key) for (key,value) in myDict.iteritems()])

Python 3

sorted_dict = sorted([(value,key) for (key,value) in myDict.items()])

Printing for both python 2 and 3

print([(key, value) for value, key in sorted_dict]


问:
HttpURLConnection crashes application
I want to receive and send data with a web server but the code does not work
What do I do for this code to work?

Note this code inside onCreate

```<code>try {

    URL url = new URL("http://myweb.com/");
    HttpURLConnection   connection = (HttpURLConnection) url.openConnection();
    InputStream Stream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(Stream);
    BufferedReader b = new BufferedReader(reader);
    StringBuilder s = new StringBuilder();
    String str ="";

    while ((str = b.readLine())!=null)  {
        s.append(str);

    }
    String data = s.toString();
    TextView myText = (TextView) findViewById(R.id.Text);
    myText.setText(data);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答:
All your code runs in Main thread which should be always used for setting up the UI and to listen for UI events such as on click listeners.

Network calls are not allowed on this thread as they might take long time. Use AsyncTask API of android which is designed for running code in separate thread.

Create a class like one below for all GET request tasks.

```<code>public class DownloadTask extends AsyncTask<String, Void, Integer> {

    private String TAG = "InDownloadTask";
    private DownloadCallback callback;
    private String data;

    public DownloadTask(DownloadCallback cb){
        callback = cb;
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                data = response.toString();
                result = 1;
            } else {
                result = 0;
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        callback.onFinishDownload(data, integer);
    }

}
</code>```

Create a callback interface that we use for the above class.

```<code>public interface DownloadCallback {
    public void onFinishDownload(String data, Integer result);
}
</code>```

Now from your activity onCreate

```<code>String url = "http://myweb.com/";
new DownloadTask(new DownloadCallback() {
    public void onFinishDownload(String data, Integer result) {
        if(result == 1)
            myText.setText(data);
        else
            myText.setText("Error");
    }
}).execute(url);
</code>```

If you have many network related operations, use a Network library such as Volley which will take care of this.

Title: HttpURLConnection crashes application

Body:
I want to receive and send data with a web server but the code does not work
What do I do for this code to work?

Note this code inside onCreate

try {

    URL url = new URL("http://myweb.com/");
    HttpURLConnection   connection = (HttpURLConnection) url.openConnection();
    InputStream Stream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(Stream);
    BufferedReader b = new BufferedReader(reader);
    StringBuilder s = new StringBuilder();
    String str ="";

    while ((str = b.readLine())!=null)  {
        s.append(str);

    }
    String data = s.toString();
    TextView myText = (TextView) findViewById(R.id.Text);
    myText.setText(data);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Body:
All your code runs in Main thread which should be always used for setting up the UI and to listen for UI events such as on click listeners.

Network calls are not allowed on this thread as they might take long time. Use AsyncTask API of android which is designed for running code in separate thread.

Create a class like one below for all GET request tasks.

public class DownloadTask extends AsyncTask<String, Void, Integer> {

    private String TAG = "InDownloadTask";
    private DownloadCallback callback;
    private String data;

    public DownloadTask(DownloadCallback cb){
        callback = cb;
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                data = response.toString();
                result = 1;
            } else {
                result = 0;
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        callback.onFinishDownload(data, integer);
    }

}

Create a callback interface that we use for the above class.

public interface DownloadCallback {
    public void onFinishDownload(String data, Integer result);
}

Now from your activity onCreate

String url = "http://myweb.com/";
new DownloadTask(new DownloadCallback() {
    public void onFinishDownload(String data, Integer result) {
        if(result == 1)
            myText.setText(data);
        else
            myText.setText("Error");
    }
}).execute(url);

If you have many network related operations, use a Network library such as Volley which will take care of this.


问:
How to get HP thin clients (t420) and Windows Server 2016's Multipoint VDI work together?
So we have fourteen HP t420 and one Windows Server 2016 machine with Multipoint set up. If we create users in Multipoint Manager then the clients can connect via RDP as those users all right. But we can't get it work with VDI. We've created a Windows 10 template from an ISO, but can't figure out how to create stations from it. Clicling on the create stations option tells virtual desktop station created for -t, but nothing new appears in the list of virtual desktops. Tried that with a couple of clients connected as users - no difference.

Also, when restarting the server it gives a screen telling to press "B", but nothing happens if we press it. No such screens appear on the clients (they just disconnect if the server is restarted), no idea if they are supposed to.

Can't find any manual better then the official help file, and it just tells to use the create stations option, nothing on whether clients should be online or offline or anything, but we've tried both, nothing happens.

Ah, and we did the customize template thing where you are supposed to run a cmd file from its desktop before creating stations.

And the clients are connected via LAN. Each has a monitor, mouse and keyboard.

What else... can't get when the create stations option becomes available or not. Previosly it seemed to get it to appear we had to restart the server and then log as administrator on one of the clients. But now we suddenly see it available on the server (still doesn't work though), though we're not sure what exactly we've done for this affect.
The manual suggests it might only be available in station mode, but it doesn't explain what that is. We assumed it means log in from a client, but now it seems it's somethine else?

答:
Okay, so by trial and error we've ended up doing this:

via Server Manager add roles for Remote Desktop Services

open Remote Desktop Services in Server Manager and get an error saying you should log in as a domain user

luckily we've already had a domain set up, so we've joined this server to the domain and created a user for it (the user should have domain admin rights!)

a group should also be created in the domain to be later selected in collection creation to give this group access to VMs, populate this group with users

open Remote Desktop Services again, now as a domain user with domain admin rights, and create a collection from the template created by multipoint

assign each station to a user (there's an option to do it automatically, but we wanted VM1 to be assigned to User1, VM2 to User2 and I imagine the automation could mess it up)

on the thin clients configure web connection to server.domain/RDweb

it connects, but the log in process is overly complicated

scrap the web connection and configure an rdp connection directly to the VMs (so in "server address" you put not server.domain, but VM1.domain, VM2.domain etc)

now it connects just by double click on the connection, also each thin client ends up linked to a particular VM as the user doesn't get to enter username and password by themselves; probably won't work if the VMs aren't already running, but that shouldn't be a big problem

open Multipoint Dashboard and see that it doesn't see any of the connections

open Multipoint Manager and click "add personal computers to control" or something along these lines, it doesn't see any, so use the "add manually" input box to input the names one by one: VM1.domain, VM2.domain etc

for each added PC it will ask a username and password, by trial and error we figured out it should be the local admin account, the one set up when creating the template in Multipoint

somehow it doesn't always work for each VM, sometimes some random ones among them would be unable to connect, in such case close the Multipoint Manager and then reopen it, it will try to connect again

once the Multipoint Manager succesfully connects to all the VMs, open Multipoint Dashboard and now it sees them all (actually, it only sees them if there is and RDP connection, it won't just show the desktop of a VM to which noone is connected via RDP; the clients might automatically disconnect after some minutes of inactivity, but with reconnecting taking just a double click it shouldn't be a problem)

and of course set up the licensing; I wasn't personally setting up this part, so can't tell any details on it

All seems to work fine now... or not. In Multipoint Dashboard some functions work and some don't:

seeing users desktops works just fine

PM works fine

remotely starting and closing apps works fine (the list from which it suggests to choose though is a list of apps on the server, but what it really does is trying to start the app by the same path on the station, it will give an error if there isn't one)

taking control over a station doesn't work: just shows a black screen on the server

sharing server's screen works, but stopping it doesn't, leaving the stations with white screens which seem to only be fixed by reconnecting them

forcing stations to disconnect works, but if you choose to disconnect all of them at once, one desktop will remain shown in the dashboard even though in thin client it will be disconnected

I wonder if there is a way to fix these?..


问:
Filter out Git history for all items NOT present in current HEAD
I have a repo that I want to filter to remove the commit history for all files/directories that are NOT present in the current HEAD (even if they have already been deleted in prior commits). It would be nice to output the list of items that get filtered out as well for auditing.

I am attempting to collapse history to only items in the current HEAD.

I suspect this is a filter-branch or similar operation but not quite sure how to pull this off.

答:
Suppose the repository does not involve any submodule.

1.Find all the files that are in HEAD, as Group 1.

```<code>git ls-tree -r --name-only HEAD | sort -u
</code>```

2.Find all the file that are in the ancestors of HEAD, as Group 2.

```<code>sort -u <(
    for commit in $(git log --pretty=%H $(git log --pretty=%P HEAD));do
        git ls-tree -r --name-only $commit
    done;
)
</code>```

3.Find the files that are in Group 2 and not in Group 1.

```<code>diff -B <(git ls-tree -r --name-only HEAD | sort -u) <(
    sort -u <(
        for commit in $(git log --pretty=%H $(git log --pretty=%P HEAD));do
            git ls-tree -r --name-only $commit
        done;
    )
) | awk '/^>/{print "\""$2"\""}'
</code>```

4.Combine these files in one line as "path1" "path2" "path3"

```<code>paths=$(
    diff -B <(git ls-tree -r --name-only HEAD | sort -u) <(
        sort -u <(
            for commit in $(git log --pretty=%H $(git log --pretty=%P HEAD));do
                git ls-tree -r --name-only $commit
            done;
        )
    ) | awk '/^>/{print "\""$2"\""}'
)
</code>```

5.Remove these files from the history of HEAD.

```<code>git filter-branch --prune-empty -f --tree-filter 'rm -rf $paths'
</code>```

Body:
Suppose the repository does not involve any submodule.

1.Find all the files that are in HEAD, as Group 1.

git ls-tree -r --name-only HEAD | sort -u

2.Find all the file that are in the ancestors of HEAD, as Group 2.

sort -u <(
    for commit in $(git log --pretty=%H $(git log --pretty=%P HEAD));do
        git ls-tree -r --name-only $commit
    done;
)

3.Find the files that are in Group 2 and not in Group 1.

diff -B <(git ls-tree -r --name-only HEAD | sort -u) <(
    sort -u <(
        for commit in $(git log --pretty=%H $(git log --pretty=%P HEAD));do
            git ls-tree -r --name-only $commit
        done;
    )
) | awk '/^>/{print "\""$2"\""}'

4.Combine these files in one line as "path1" "path2" "path3"

paths=$(
    diff -B <(git ls-tree -r --name-only HEAD | sort -u) <(
        sort -u <(
            for commit in $(git log --pretty=%H $(git log --pretty=%P HEAD));do
                git ls-tree -r --name-only $commit
            done;
        )
    ) | awk '/^>/{print "\""$2"\""}'
)

5.Remove these files from the history of HEAD.

git filter-branch --prune-empty -f --tree-filter 'rm -rf $paths'


问:
Gitlab CI using Badges for each job
Let's say I have configured multiple jobs for a project like following:

```<code>build_win32:
  script: ...

build_ios:
  script: ...

unit_tests:
  script: ...

server_tests:
  script: ...

client_tests:
  script: ...
</code>```

What I want to achieve is to configure badges per each job under README.md so that I can have immediate feedback of specifically which part went wrong.

There is a Gitlab Documentation on setting badges but this has a limitation that it shows how to configure badges for build and coverage status only.

I'm wondering if there is such a build-in feature in Gitlab CI. I could use 3rd party plugins also. Any helps will be appreciated.

答:
You can achieve what you need by creating badges in your pipeline steps, registering the badge files as pipeline artifacts, and publishing them to GitLab Pages.  From there you can reference the badges in your README.md

How to do what you asked

1. Generate the badge

In each of your CI steps you would need to generate badge files, and store them under public/<badge-file>.svg

You can generate badge files using http://shields.io.  I have written my own Python badge generator, which can be found here: https://github.com/jongracecox/anybadge

2. Register badge as pipeline artifact

Register each of the generated badge files as artifacts in the CI job by including this in each job in the .gitlab-ci.yml:

```<code>build_win32:
  script: ...
    - <generate public/build_win32.svg>
  artifacts:
    paths:
      - public/build_win32.svg

build_ios:
  script: ...
    - <generate public/build_ios.svg>
  artifacts:
    paths:
      - public/build_ios.svg

unit_tests:
  script: ...
    - <generate public/unit_tests.svg>
  artifacts:
    paths:
      - public/unit_tests.svg

server_tests:
  script: ...
    - <generate public/server_tests.svg>
  artifacts:
    paths:
      - public/server_tests.svg

client_tests:
  script: ...
    - <generate public/client_tests.svg>
  artifacts:
    paths:
      - public/client_tests.svg
</code>```

3. Publish badge to GitLab Pages

Include a new pages publish step, which deploys everything in the public directory to GitLab pages:

```<code>pages:
  stage: deploy
  artifacts:
    paths:
    - public
  only:
  - master
</code>```

You shouldn't need to modify the above.  Once this job runs, all the files in public will be available via the GitLab pages web server.  This is often http://NAMESPACE.GITLABPAGESSERVER/project

Read more about GitLab pages here: https://docs.gitlab.com/ce/user/project/pages/index.html

4. Include badges in README.md

When the master pipeline runs for the project, the badge files are published to GitLab Pages, and can then be referenced from the project README.md.

Why this might not make sense

I understand why you would ask this question, but I would like to explain why you might not want to do that.

GitLab pipelines run on every push to the project - on every branch.  Typically you would only want to generate badges for your README file from the master branch (or a release) branch, so you would restrict the pages step to only run on master@group/project.

Also consider that a pipeline will usually be configured to stop when a job errors.  This would mean that if a master pipeline job failed then the badges for that pipeline would not get generated, and would therefore not be helpful in determining which job failed.

The best place to get your immediate feedback is in the pipeline view, and you could add the pipeline success badge to your readme with a link to the pipeline, usually something like  https://gitlabserver/namespace/project/badges/branch/build.svg

If you still want to use the approach you have described then my suggestion would be to set each pipeline stage to allow failure.  This would allow the full pipeline to run, despite failures in any job, and the badges should still get generated, and published to Pages.

Title: Gitlab CI using Badges for each job

Body:
Let's say I have configured multiple jobs for a project like following:

build_win32:
  script: ...

build_ios:
  script: ...

unit_tests:
  script: ...

server_tests:
  script: ...

client_tests:
  script: ...

What I want to achieve is to configure badges per each job under README.md so that I can have immediate feedback of specifically which part went wrong.

There is a Gitlab Documentation on setting badges but this has a limitation that it shows how to configure badges for build and coverage status only.

I'm wondering if there is such a build-in feature in Gitlab CI. I could use 3rd party plugins also. Any helps will be appreciated.

Body:
You can achieve what you need by creating badges in your pipeline steps, registering the badge files as pipeline artifacts, and publishing them to GitLab Pages.  From there you can reference the badges in your README.md

How to do what you asked

1. Generate the badge

In each of your CI steps you would need to generate badge files, and store them under public/<badge-file>.svg

You can generate badge files using http://shields.io.  I have written my own Python badge generator, which can be found here: https://github.com/jongracecox/anybadge

2. Register badge as pipeline artifact

Register each of the generated badge files as artifacts in the CI job by including this in each job in the .gitlab-ci.yml:

build_win32:
  script: ...
    - <generate public/build_win32.svg>
  artifacts:
    paths:
      - public/build_win32.svg

build_ios:
  script: ...
    - <generate public/build_ios.svg>
  artifacts:
    paths:
      - public/build_ios.svg

unit_tests:
  script: ...
    - <generate public/unit_tests.svg>
  artifacts:
    paths:
      - public/unit_tests.svg

server_tests:
  script: ...
    - <generate public/server_tests.svg>
  artifacts:
    paths:
      - public/server_tests.svg

client_tests:
  script: ...
    - <generate public/client_tests.svg>
  artifacts:
    paths:
      - public/client_tests.svg

3. Publish badge to GitLab Pages

Include a new pages publish step, which deploys everything in the public directory to GitLab pages:

pages:
  stage: deploy
  artifacts:
    paths:
    - public
  only:
  - master

You shouldn't need to modify the above.  Once this job runs, all the files in public will be available via the GitLab pages web server.  This is often http://NAMESPACE.GITLABPAGESSERVER/project

Read more about GitLab pages here: https://docs.gitlab.com/ce/user/project/pages/index.html

4. Include badges in README.md

When the master pipeline runs for the project, the badge files are published to GitLab Pages, and can then be referenced from the project README.md.

Why this might not make sense

I understand why you would ask this question, but I would like to explain why you might not want to do that.

GitLab pipelines run on every push to the project - on every branch.  Typically you would only want to generate badges for your README file from the master branch (or a release) branch, so you would restrict the pages step to only run on master@group/project.

Also consider that a pipeline will usually be configured to stop when a job errors.  This would mean that if a master pipeline job failed then the badges for that pipeline would not get generated, and would therefore not be helpful in determining which job failed.

The best place to get your immediate feedback is in the pipeline view, and you could add the pipeline success badge to your readme with a link to the pipeline, usually something like  https://gitlabserver/namespace/project/badges/branch/build.svg

If you still want to use the approach you have described then my suggestion would be to set each pipeline stage to allow failure.  This would allow the full pipeline to run, despite failures in any job, and the badges should still get generated, and published to Pages.


问:
CloudFoundry UAA Multi instances
What’s the recommended setup across CloudFoundry foundations for UAA? When clients can get routed between the foundations how are clients ensured they don't get re-authenticate?
More specifically: If an access/id token is generated in one foundation can it be used in the other foundation?</p>

答: If you want to ensure that clients do not have to re-authenticate across multiple UAAs, you will have to ensure that the JWT signing key is the same in each foundation. You probably also want to make sure that the issuer field (properties.uaa.issuer in the BOSH deployment) is the same, though I'm less sure that that's required.

Title: CloudFoundry UAA Multi instances


问:
Using 'conditional' transitions with Vue
I have a sort of simple question.  Im building a carousel which rotates vertically using vue.  When the user clicks the forward button, I want vue to transition the elements in/out using my 'forward' transition (moving them down).  When the user clicks the backward button, I want vue to transition the elements in/out using my 'backward' transition (moving them up).

Right now, I just have one transition that performs my forward transition, whether the user is navigating forward or backward.

Is there any way to accomplish this?

Heres my component:

```<code><template>
<div class="carousel__container">
    <div class="carousel__visible">
        <div class="carousel__slides">

            <transition-group name="carouselNext">
                <div v-for="(quote, index) in quotes" class="carousel__slide" key="index" v-show="index === currentSlide">
                    <blockquote>{{ quote.quote }}</blockquote>
                    <cite>{{ quote.cite }}</cite>
                </div>
            </transition-group>

        </div>

    </div>

    <button class="btn btn--alt" @click="prev">Back</button>

    <button class="btn btn--primary" @click="next">Next</button>
</div>
</code>```

Thanks!

答:
Easiest way is to change the transition name based on direction
<transition-group name="carouselNext"> can become <transition-group :name="direction">

add new direction data var and include toggling based on methods

    prev(){
      this.direction = "carouselPrev"
      this.currentSlide = (this.currentSlide + this.quotes.length - 1)%this.quotes.length
    },
    next(){
      this.direction = "carouselNext"
      this.currentSlide = (this.currentSlide + 1)%this.quotes.length
    }
```

and finally add the alternate carouselPrev css transition classes

here's a working example https://codepen.io/scorch/pen/NwwpxM

Body:
I have a sort of simple question.  Im building a carousel which rotates vertically using vue.  When the user clicks the forward button, I want vue to transition the elements in/out using my 'forward' transition (moving them down).  When the user clicks the backward button, I want vue to transition the elements in/out using my 'backward' transition (moving them up).

Right now, I just have one transition that performs my forward transition, whether the user is navigating forward or backward.

Is there any way to accomplish this?

Heres my component:

<template>

            <transition-group name="carouselNext">

{{ quote.quote }}

                    {{ quote.cite }}

            </transition-group>

    <button class="btn btn--alt" @click="prev">Back</button>

    <button class="btn btn--primary" @click="next">Next</button>

Thanks!

Body:
Easiest way is to change the transition name based on direction
<transition-group name="carouselNext"> can become <transition-group :name="direction">

add new direction data var and include toggling based on methods

    prev(){
      this.direction = "carouselPrev"
      this.currentSlide = (this.currentSlide + this.quotes.length - 1)%this.quotes.length
    },
    next(){
      this.direction = "carouselNext"
      this.currentSlide = (this.currentSlide + 1)%this.quotes.length
    }

and finally add the alternate carouselPrev css transition classes

here's a working example https://codepen.io/scorch/pen/NwwpxM

ContentLicense: CC BY-SA 4.0


问:
Pass function to optional argument in Python
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:

```<code>NameError: name 'self' is not defined
</code>```

Please see the sample code below:

```<code>class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()
</code>```

Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.

答:
You can't do it that way.

And that's a good thing - because the default is evaluated at function creation (ie, not when it's called). If it did happen to work, then the random number would have been generated when the program first loads this function, and then kept the same random number for every call afterwards.

This should give you the effect you want though;

```<code>def print_rand(self, num=None):
    if num is None:
        num = self.rand()
    # ...
</code>```

Body:
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:

NameError: name 'self' is not defined

Please see the sample code below:

class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()

Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.

Body:
You can't do it that way.

And that's a good thing - because the default is evaluated at function creation (ie, not when it's called). If it did happen to work, then the random number would have been generated when the program first loads this function, and then kept the same random number for every call afterwards.

This should give you the effect you want though;

def print_rand(self, num=None):
    if num is None:
        num = self.rand()
    # ...


问:
Using lambda to create a new variable in Pandas
if I want to do the following in Pandas, how do I do it using Lambda:

```<code>df['c'] = 0
df['c'][(df['a']==1) | (df['b'] ==1)] = 1
</code>```

Thanks

答:
You can use apply but change the axis. </p>

```<code>import pandas as pd

df =pd.DataFrame({'a':[1,2], 'b':[1,2]})
df['c'] = df.apply(lambda df: 1 if(df['a'] == 1| df['b']==1) else 0, axis = 1)
</code>```

Body:
if I want to do the following in Pandas, how do I do it using Lambda:

df['c'] = 0
df['c'][(df['a']==1) | (df['b'] ==1)] = 1

Thanks

Body:
You can use apply but change the axis.

import pandas as pd

df =pd.DataFrame({'a':[1,2], 'b':[1,2]})
df['c'] = df.apply(lambda df: 1 if(df['a'] == 1| df['b']==1) else 0, axis = 1)


问:
What type files should be put into .gitignore file in Django project
From my other post, I know the __pycache__ should be put into the .gitignore when I use git.

And in the other post I saw, there are also .pyc and .pyo files.

whether them should all be put into the .gitignore file?

Can we summarize in the Python/Django project, what files should be put into . gitignore file?

答:
There is a popular web service called Gitignore.io that help developers generate gitignore files for popular framework and languages. You can see the Django one here.

```<code>*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
media
</code>```

On top of that I would also recommend you to ignore things environment items such as virtualenv, or .env files that are related to the local environment that the code is being run from. This also allow you to store passwords and secrets in environment files, and keep them out of your git repo.

```<code>.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
</code>```

Lastly I would also add the django static folder to the list of files to ignore since it is collected with collectstatic whenever you deploy your code.

Body:
There is a popular web service called Gitignore.io that help developers generate gitignore files for popular framework and languages. You can see the Django one here.

*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
media

On top of that I would also recommend you to ignore things environment items such as virtualenv, or .env files that are related to the local environment that the code is being run from. This also allow you to store passwords and secrets in environment files, and keep them out of your git repo.

.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

Lastly I would also add the django static folder to the list of files to ignore since it is collected with collectstatic whenever you deploy your code.


问:
$expand=permissions failed with notSupported error
The documentation clearly states that this endpoint supports $expand to modify the search result:

```<code>users/{user-id}/drive/root/search(q='{search-text}')?$expand=permissions
</code>```

But the request returns the following body in its response:

{
    "error": {
        "code": "notSupported",
        "message": "The request is not supported by the system.",
        "innerError": {
            "request-id": "30fc9988-6f4f-46ba-a5b4-91b150c4a1a5",
            "date": "2017-11-17T02:30:49"
        }
    }
}
```

This is also the case for other relationships. Though trying to expand createdByUser results in a BadRequest.

We want to do this request to avoid doing subsequent requests. Because at the moment we use a SharePoint ListItemUniqueId (due to backwards comparability) to find the corresponding DriveItem. Then we want to retrieve the permissions of this DriveItem. But right now we need to do two requests to achieve this.

We also can't use /users/{user-id}/drive/items because it does not support $filter.

Are we misunderstanding the docs or is this an issue on the Microsoft Graph side?

答:
You cannot expand the permissions collection. From the documentation:

The permissions relationship of DriveItem cannot be expanded as part of a call to get DriveItem or a collection of DriveItems. You must access the permissions property directly.

The reason $expand=createdByUser returns a BadRequest is because it is already expanded by default.

Properties that are not supported are in $expand on the /search endpoint are:

children - Since /search returns files, this logically wouldn't make any sense here.

lastModifiedByUser - included by default

content - logically the content of each file wouldn't make sense to be included in a collection of DriveItems

Thumbnails can be expanded however ($expand=thumbnails).

Body:
The documentation clearly states that this endpoint supports $expand to modify the search result:

users/{user-id}/drive/root/search(q='{search-text}')?$expand=permissions

But the request returns the following body in its response:

{
    "error": {
        "code": "notSupported",
        "message": "The request is not supported by the system.",
        "innerError": {
            "request-id": "30fc9988-6f4f-46ba-a5b4-91b150c4a1a5",
            "date": "2017-11-17T02:30:49"
        }
    }
}

This is also the case for other relationships. Though trying to expand createdByUser results in a BadRequest.

We want to do this request to avoid doing subsequent requests. Because at the moment we use a SharePoint ListItemUniqueId (due to backwards comparability) to find the corresponding DriveItem. Then we want to retrieve the permissions of this DriveItem. But right now we need to do two requests to achieve this.

We also can't use /users/{user-id}/drive/items because it does not support $filter.

Are we misunderstanding the docs or is this an issue on the Microsoft Graph side?


问:
Passing custom class objects using parcelable
How can i access custom class object in a class implementing parcelable

I have a parcelable class as folows

```<code>class A implements Parcelable{
      private CustomClass B;
}
</code>```

Is it possible to use that custom class as a normal variable during writeToParcel() and readParcel(Parcel in)

PS: I can't implement parcelable on class B as it is in Non-Android module

答:
First you need to make your CustomClass parcelable as in

```<code>class CustomClass implements Parcelable{
   // write logic to write and read from parcel
}
</code>```

Then, in your class A

```<code>class A implements Parcelable{
      private CustomClass B;

       @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(B, flags); // saving object
    }

    private A(Parcel in) {
        this.B= in.readParcelable(CustomClass.class.getClassLoader()); //retrieving from parcel
    }
}
</code>```

EDIT

If you can't make CustomClass as Parcelable, convert class as Json String using google gson and write it to Parcel and while reading, read String and convert back to object

```<code>class A implements Parcelable{
      private CustomClass B;

       @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(new Gson().toJson(B), flags); // saving object
    }

    private A(Parcel in) {
        this.B= new Gson().fromJson(in.readString(),CustomClass.class); //retrieving string and convert it to object and assign
    }
}
</code>```

Body:
How can i access custom class object in a class implementing parcelable

I have a parcelable class as folows

class A implements Parcelable{
      private CustomClass B;
}

Is it possible to use that custom class as a normal variable during writeToParcel() and readParcel(Parcel in)

PS: I can't implement parcelable on class B as it is in Non-Android module

Body:
First you need to make your CustomClass parcelable as in

class CustomClass implements Parcelable{
   // write logic to write and read from parcel
}

Then, in your class A

class A implements Parcelable{
      private CustomClass B;

       @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(B, flags); // saving object
    }

    private A(Parcel in) {
        this.B= in.readParcelable(CustomClass.class.getClassLoader()); //retrieving from parcel
    }
}

EDIT

If you can't make CustomClass as Parcelable, convert class as Json String using google gson and write it to Parcel and while reading, read String and convert back to object

class A implements Parcelable{
      private CustomClass B;

       @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(new Gson().toJson(B), flags); // saving object
    }

    private A(Parcel in) {
        this.B= new Gson().fromJson(in.readString(),CustomClass.class); //retrieving string and convert it to object and assign
    }
}


问:
Clock on webpage using server and system time?
I need to add a clock to a web page. The clock needs to be synchronized with a server but I really don't want to have it constantly check the server as the page will be open 24/7 on several PCs. Is there some way to get the time from the server and then use the systems clock to keep it updated and check the server every 15 minutes or so to keep it synced?</p>

答:
you just get one time date time from server, on load call this method and use moments js for format date:</p>

```<code>var timeMiliSecond = new Date(serverTime).getTime();
 callRepeatedly() {
    setTimeout(() => {
         timeMiliSecond = timeMiliSecond+1000;
         serverTime=moment(newDate(timeMiliSecond)).format('MM-DD-YYYY HH:mm:ss');
         this.callRepeatedly();
      }, 1000)
  }
</code>```

Body:
you just get one time date time from server, on load call this method and use moments js for format date:

var timeMiliSecond = new Date(serverTime).getTime();
 callRepeatedly() {
    setTimeout(() => {
         timeMiliSecond = timeMiliSecond+1000;
         serverTime=moment(newDate(timeMiliSecond)).format('MM-DD-YYYY HH:mm:ss');
         this.callRepeatedly();
      }, 1000)
  }


问:
Check if a binary tree is traversed from left to right in Haskell
I have the following tree and this is how I access the Int values of its nodes and leaves. What I want to do is to write a function "areValuesIncreasing" to check if the values of the nodes/leaves are increasing as the tree is traversed from left to right. Any help would be appreciated.</p>

```<code>       4                    4
     /   \                /   \
    2     3              3     2
   / \   / \            / \   / \
  1   3 4   5  - True  1   3 5   4 - False

   data Tree = Node Tree Int Tree | Leaf Int deriving Show

   treeToInt (Node _ n _) = n
   treeToInt (Leaf n ) = n

   areValuesIncreasing:: Tree -> Bool
</code>```

答:
I heavily recommend changing Tree to

```<code>data Tree a = Node (Tree a) a (Tree a)
            | Leaf a
            deriving (...)
</code>```

and will use this in my answer, but transforming it to your Tree is as easy as setting a ~ Int everywhere and replacing Tree Int with Tree.

Create a list of elements for each layer, and then check that all of those are sorted. Assuming you have a function

```<code>foldTree :: (a -> b) ->           -- Leaf case
            (b -> a -> b -> b) -> -- Node case
            Tree a -> b
</code>```

The leaves produce a list containing a singleton list followed by repeat [], as a leaf is a single element on a level followed by infinitely many empty levels

```<code>leafCase x = [x] : repeat []
</code>```

And the internal nodes concatenate the subtrees' lists' sublists pairwise, while also placing their element in a singleton list on top:

```<code>nodeCase l x r = [x] : zipWith (++) l r
</code>```

Fold this over a Tree to get a list of levels, and cut it off after the last nonempty one:

```<code>levels = takeWhile (not . null) . foldTree leafCase nodeCase
</code>```

Check that each level is sorted:

```<code>sorted = all (uncurry (<=)) . (zip <*> tail)
</code>```

Mix it all up into one function

```<code>sortedTree = all sorted . takeWhile (not . null) . levels
  where sorted = all (uncurry (<=)) . (zip <*> tail)
        levels = foldTree (\l -> [l] : repeat []) (\l x r -> [x] : zipWith (++) l r)
</code>```

Same thing with recursion-schemes:

```<code>makeBaseFunctor ''Tree
-- data TreeF a b = NodeF b a b | LeafF a
-- ...
levelsSorted :: (Recursive t, Foldable (Base t), Ord a) => (Base t [[a]] -> a) -> t -> Bool
levelsSorted get = all sorted . takeWhile (not . null) . levels
    where sorted = all (uncurry (<=)) . (zip <*> tail)
          levels = cata $ \x -> [get x] : foldr (zipWith (++)) (repeat []) x

levelsSortedTree :: Ord a => Tree a -> Bool
levelsSortedTree = levelsSorted $ \case { LeafF _ x _ -> x; NodeF x -> x }
</code>```

Body:
I have the following tree and this is how I access the Int values of its nodes and leaves. What I want to do is to write a function "areValuesIncreasing" to check if the values of the nodes/leaves are increasing as the tree is traversed from left to right. Any help would be appreciated.

       4                    4
     /   \                /   \
    2     3              3     2
   / \   / \            / \   / \
  1   3 4   5  - True  1   3 5   4 - False

   data Tree = Node Tree Int Tree | Leaf Int deriving Show

   treeToInt (Node _ n _) = n
   treeToInt (Leaf n ) = n

   areValuesIncreasing:: Tree -> Bool

Body:
I heavily recommend changing Tree to

data Tree a = Node (Tree a) a (Tree a)
            | Leaf a
            deriving (...)

and will use this in my answer, but transforming it to your Tree is as easy as setting a ~ Int everywhere and replacing Tree Int with Tree.

Create a list of elements for each layer, and then check that all of those are sorted. Assuming you have a function

foldTree :: (a -> b) ->           -- Leaf case
            (b -> a -> b -> b) -> -- Node case
            Tree a -> b

The leaves produce a list containing a singleton list followed by repeat [], as a leaf is a single element on a level followed by infinitely many empty levels

leafCase x = [x] : repeat []

And the internal nodes concatenate the subtrees' lists' sublists pairwise, while also placing their element in a singleton list on top:

nodeCase l x r = [x] : zipWith (++) l r

Fold this over a Tree to get a list of levels, and cut it off after the last nonempty one:

levels = takeWhile (not . null) . foldTree leafCase nodeCase

Check that each level is sorted:

sorted = all (uncurry (<=)) . (zip <*> tail)

Mix it all up into one function

sortedTree = all sorted . takeWhile (not . null) . levels
  where sorted = all (uncurry (<=)) . (zip <*> tail)
        levels = foldTree (\l -> [l] : repeat []) (\l x r -> [x] : zipWith (++) l r)

Same thing with recursion-schemes:

makeBaseFunctor ''Tree
-- data TreeF a b = NodeF b a b | LeafF a
-- ...
levelsSorted :: (Recursive t, Foldable (Base t), Ord a) => (Base t [[a]] -> a) -> t -> Bool
levelsSorted get = all sorted . takeWhile (not . null) . levels
    where sorted = all (uncurry (<=)) . (zip <*> tail)
          levels = cata $ \x -> [get x] : foldr (zipWith (++)) (repeat []) x

levelsSortedTree :: Ord a => Tree a -> Bool
levelsSortedTree = levelsSorted $ \case { LeafF _ x _ -> x; NodeF x -> x }


问:
OSX - How to get the creation & modification time of a file from the command line
While solving some programming puzzle, I wanted to see how long it took me to write a solution to the problem. To do so, I thought it'd be a good idea to compare the file creation date with the latest modification date.

In the terminal (OSX), I tried the following command and was surprised to see the same date three times in a row:

```<code>stat my_file.py
16777220 10280844 -rw-r--r-- 1 username staff 0 7214 \
"Dec  5 08:32:39 2015"  \
"Dec  5 08:32:39 2015"  \
"Dec  5 08:32:39 2015"  \
"Dec  5 08:32:39 2015" 4096 16 0 my_file.py
</code>```

The way I created then modified the file:

```<code>touch my_file.py
vim my_file.py   # <- modify some content
stat my_file.py
</code>```

Any idea on how to get these two dates from the command line?

Clarification: I do not want to time the execution time of the script.

EDIT : The issue was with vim changing the creation date on save, the accepted answer still answers the question in depth for those who are interested.

答:
As you already identified, the real culprit was that vim resets all 4 datetime stamps.

But to answer your original question, here is a stat formatting for Mac OSX that will clearly show the 4 datetime stamps (including Creation/Birth and Modify):

# Access (atime)
stat -f "%Sa" file.txt
# Modify (mtime)
stat -f "%Sm" file.txt
# Change (ctime)
stat -f "%Sc" file.txt
# Birth  (Btime)
stat -f "%SB" file.txt
```
<p>All together in one command:</p>
```stat -f "Access (atime): %Sa%nModify (mtime): %Sm%nChange (ctime): %Sc%nBirth  (Btime): %SB" file.txt

Access (atime): Nov 16 19:44:55 2017
Modify (mtime): Nov 16 19:44:25 2017
Change (ctime): Nov 16 19:44:48 2017
Birth  (Btime): Nov 16 19:44:05 2017
```

Body:
While solving some programming puzzle, I wanted to see how long it took me to write a solution to the problem. To do so, I thought it'd be a good idea to compare the file creation date with the latest modification date.

In the terminal (OSX), I tried the following command and was surprised to see the same date three times in a row:

stat my_file.py
16777220 10280844 -rw-r--r-- 1 username staff 0 7214 \
"Dec  5 08:32:39 2015"  \
"Dec  5 08:32:39 2015"  \
"Dec  5 08:32:39 2015"  \
"Dec  5 08:32:39 2015" 4096 16 0 my_file.py

The way I created then modified the file:

touch my_file.py
vim my_file.py   # <- modify some content
stat my_file.py

Any idea on how to get these two dates from the command line?

Clarification: I do not want to time the execution time of the script.

EDIT : The issue was with vim changing the creation date on save, the accepted answer still answers the question in depth for those who are interested.

Body:
As you already identified, the real culprit was that vim resets all 4 datetime stamps.

But to answer your original question, here is a stat formatting for Mac OSX that will clearly show the 4 datetime stamps (including Creation/Birth and Modify):

# Access (atime)
stat -f "%Sa" file.txt
# Modify (mtime)
stat -f "%Sm" file.txt
# Change (ctime)
stat -f "%Sc" file.txt
# Birth  (Btime)
stat -f "%SB" file.txt

All together in one command:

stat -f "Access (atime): %Sa%nModify (mtime): %Sm%nChange (ctime): %Sc%nBirth  (Btime): %SB" file.txt

Access (atime): Nov 16 19:44:55 2017
Modify (mtime): Nov 16 19:44:25 2017
Change (ctime): Nov 16 19:44:48 2017
Birth  (Btime): Nov 16 19:44:05 2017


问:
Help regarding a shell script
I was creating a init.d service, and was reading a few scripts for reference. I found this one in a skeleton:

What does this snippet do? I get that this is a switch:case. I am asking about the case within the case.

```<code>case "$1" in
  start)
        echo test
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
</code>```

PS: Excuse the title, I couldn't think of a better name

Thanks.

答: Seems like the actual script might have had something more substantial than 'echo test'. $? is the exit code returned by the echo command in this script. The inner case statement prints the log message that is appropriate for the termination code. 0|1 most likely is success. 2 is probably an error.</p>

Title: Help regarding a shell script

Body:
I was creating a init.d service, and was reading a few scripts for reference. I found this one in a skeleton:

What does this snippet do? I get that this is a switch:case. I am asking about the case within the case.

case "$1" in
  start)
        echo test
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac

PS: Excuse the title, I couldn't think of a better name

Thanks.


问:
Sinon stub callFake function not replacing original function
So this is the (snipped) code for a chatbot. I want to override the sendMessage() function to just echo the message argument. In this case, the original function runs and gives an error at the 2nd line of the function. Obviously, modules aren't loaded and I don't need them to. This is a test for the eventHandler to echo the right messages. Ideas?

var modules = require('./modules');
console.log('[tose] Loading modules: ', Object.keys(modules));

function eventHandler(channel, type, data, react=()=>{}) {
  switch (type) {
    case 'new_message':
      console.log('[tose][new_message]', channel, 'from:', data.cid, 'message:', data.message);
      if (regexTemplates.testSearch.test(data.message.toLowerCase())) {
        ...
      } else {
        sendMessage(channel, data.cid, data.message);    // Basic echo message
      }
      break;
  }
}

// The function to be stubbed
function sendMessage(channel, cid, message) {
  console.log('[tose][send_message]', channel, 'to:', cid, 'message:', message);
  coms[channel].sendMessage(cid, message); // Getting error here thus not really stubbed
}

exports.eventHandler = eventHandler;
exports.sendMessage = sendMessage```
</div>
</div>
</p>

<p>And the test:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>describe('Tose core', function() {
  describe('Process messages', function() {

    before(function() {
      var stub = sinon.stub(tose, 'sendMessage').callsFake(function(channel, cid, message) {
        assert.equal(message, 'Test message');
        return message
      });
    });

    after(function() {
      tose.sendMessage.restore();
    });

    it('should echo messages', function() {
      var data = {message: 'Test message'}
      tose.eventHandler('test', 'new_message', data)
      assert(tose.sendMessage.calledOnce);
    });

  });
});</code>```

答:
The problem here is that when you use Sinon to stub an object's function, you're stubbing that (and only that) object's function.

Your code (the first code block) is using the local definition of the sendMessage function.

When you stub the tose object (in the second code block), you are changing the sendMessage function thats on the tose object and not the local definition of the function.

There are many different ways you could approach this, one of which is:

```<code>var modules = require('./modules');
var functions = {
  eventHandler: eventHandler,
  sendMessage: sendMessage,
};
console.log('[tose] Loading modules: ', Object.keys(modules));

function eventHandler(channel, type, data, react=()=>{}) {
  switch (type) {
    case 'new_message':
      console.log('[tose][new_message]', channel, 'from:', data.cid, 'message:', data.message);
      if (regexTemplates.testSearch.test(data.message.toLowerCase())) {
        ...
      } else {
        functions.sendMessage(channel, data.cid, data.message);    // Basic echo message
      }
      break;
  }
}

// The function to be stubbed
function sendMessage(channel, cid, message) {
  console.log('[tose][send_message]', channel, 'to:', cid, 'message:', message);
  coms[channel].sendMessage(cid, message); // Getting error here thus not really stubbed
}

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

Note: functions is not a descriptive name - feel free to change it to something that is more meaningful.

Body:
So this is the (snipped) code for a chatbot. I want to override the sendMessage() function to just echo the message argument. In this case, the original function runs and gives an error at the 2nd line of the function. Obviously, modules aren't loaded and I don't need them to. This is a test for the eventHandler to echo the right messages. Ideas?

var modules = require('./modules');
console.log('[tose] Loading modules: ', Object.keys(modules));

function eventHandler(channel, type, data, react=()=>{}) {
  switch (type) {
    case 'new_message':
      console.log('[tose][new_message]', channel, 'from:', data.cid, 'message:', data.message);
      if (regexTemplates.testSearch.test(data.message.toLowerCase())) {
        ...
      } else {
        sendMessage(channel, data.cid, data.message);    // Basic echo message
      }
      break;
  }
}

// The function to be stubbed
function sendMessage(channel, cid, message) {
  console.log('[tose][send_message]', channel, 'to:', cid, 'message:', message);
  coms[channel].sendMessage(cid, message); // Getting error here thus not really stubbed
}

exports.eventHandler = eventHandler;
exports.sendMessage = sendMessage

And the test:

describe('Tose core', function() {
  describe('Process messages', function() {

    before(function() {
      var stub = sinon.stub(tose, 'sendMessage').callsFake(function(channel, cid, message) {
        assert.equal(message, 'Test message');
        return message
      });
    });

    after(function() {
      tose.sendMessage.restore();
    });

    it('should echo messages', function() {
      var data = {message: 'Test message'}
      tose.eventHandler('test', 'new_message', data)
      assert(tose.sendMessage.calledOnce);
    });

  });
});

Body:
The problem here is that when you use Sinon to stub an object's function, you're stubbing that (and only that) object's function.

Your code (the first code block) is using the local definition of the sendMessage function.

When you stub the tose object (in the second code block), you are changing the sendMessage function thats on the tose object and not the local definition of the function.

There are many different ways you could approach this, one of which is:

var modules = require('./modules');
var functions = {
  eventHandler: eventHandler,
  sendMessage: sendMessage,
};
console.log('[tose] Loading modules: ', Object.keys(modules));

function eventHandler(channel, type, data, react=()=>{}) {
  switch (type) {
    case 'new_message':
      console.log('[tose][new_message]', channel, 'from:', data.cid, 'message:', data.message);
      if (regexTemplates.testSearch.test(data.message.toLowerCase())) {
        ...
      } else {
        functions.sendMessage(channel, data.cid, data.message);    // Basic echo message
      }
      break;
  }
}

// The function to be stubbed
function sendMessage(channel, cid, message) {
  console.log('[tose][send_message]', channel, 'to:', cid, 'message:', message);
  coms[channel].sendMessage(cid, message); // Getting error here thus not really stubbed
}

module.exports = functions;

Note: functions is not a descriptive name - feel free to change it to something that is more meaningful.


问:
Failing to make a line-by-line list from a file?
This is what I have (which includes extra processing):

```<code>import string

def main():
    fileInput = open("A tisket a tasket.txt",'r')
    characters, words, lines = countEmUp(fileInput)
    printCounts(characters, words, lines)
    tokenList = splitToTokens(fileInput)
    print(tokenList)

def countEmUp(someFileInput):
    lines, words, chars = 0, 0, 0
    for line in someFileInput:
        chars += len(line)  # using += for nice and concise updates
        words += len(line.split())
        lines += 1
    return chars, words, lines

def printCounts(ch,wd,ln):
    print("Your file contains the following:")
    print("Characters:",ch)
    print("Words:",wd)
    print("Lines:",ln)

def splitToTokens(aFileInput):
    tokenList = []
    for line in aFileInput:
        tokenList.extend(line.split())
    return tokenList

  main()
</code>```

The problem starts at the splitToTokens function.

What I'm trying to do is create an empty list, iterate through a file I opened for reading line-by-line, and add the tokens in that line to my tokenList so I can process the tokens later.

When I print tokenList in my main() function it's still an empty list.

I suspect that maybe it has to do with my fileInput already being called? I'm trying not to open the file more than once.

答:
You are trying to re-read file, you have to move the cursor to the beginning of the file:

```<code>file.seek(0)
</code>```

change your code to:

```<code>import string

def main():
    fileInput = open("A tisket a tasket.txt",'r')
    characters, words, lines = countEmUp(fileInput)
    fileInput.seek(0) #offset of 0
    printCounts(characters, words, lines)
    tokenList = splitToTokens(fileInput)
    print(tokenList)

def countEmUp(someFileInput):
    lines, words, chars = 0, 0, 0
    for line in someFileInput:
        chars += len(line)  # using += for nice and concise updates
        words += len(line.split())
        lines += 1
    return chars, words, lines

def printCounts(ch,wd,ln):
    print("Your file contains the following:")
    print("Characters:",ch)
    print("Words:",wd)
    print("Lines:",ln)

def splitToTokens(aFileInput):
    tokenList = []
    for line in aFileInput:
        tokenList.extend(line.split())
    return tokenList
main()
</code>```

Body:
This is what I have (which includes extra processing):

import string

def main():
    fileInput = open("A tisket a tasket.txt",'r')
    characters, words, lines = countEmUp(fileInput)
    printCounts(characters, words, lines)
    tokenList = splitToTokens(fileInput)
    print(tokenList)

def countEmUp(someFileInput):
    lines, words, chars = 0, 0, 0
    for line in someFileInput:
        chars += len(line)  # using += for nice and concise updates
        words += len(line.split())
        lines += 1
    return chars, words, lines

def printCounts(ch,wd,ln):
    print("Your file contains the following:")
    print("Characters:",ch)
    print("Words:",wd)
    print("Lines:",ln)

def splitToTokens(aFileInput):
    tokenList = []
    for line in aFileInput:
        tokenList.extend(line.split())
    return tokenList

  main()

The problem starts at the splitToTokens function.

What I'm trying to do is create an empty list, iterate through a file I opened for reading line-by-line, and add the tokens in that line to my tokenList so I can process the tokens later.

When I print tokenList in my main() function it's still an empty list.

I suspect that maybe it has to do with my fileInput already being called? I'm trying not to open the file more than once.

Body:
You are trying to re-read file, you have to move the cursor to the beginning of the file:

file.seek(0)

change your code to:

import string

def main():
    fileInput = open("A tisket a tasket.txt",'r')
    characters, words, lines = countEmUp(fileInput)
    fileInput.seek(0) #offset of 0
    printCounts(characters, words, lines)
    tokenList = splitToTokens(fileInput)
    print(tokenList)

def countEmUp(someFileInput):
    lines, words, chars = 0, 0, 0
    for line in someFileInput:
        chars += len(line)  # using += for nice and concise updates
        words += len(line.split())
        lines += 1
    return chars, words, lines

def printCounts(ch,wd,ln):
    print("Your file contains the following:")
    print("Characters:",ch)
    print("Words:",wd)
    print("Lines:",ln)

def splitToTokens(aFileInput):
    tokenList = []
    for line in aFileInput:
        tokenList.extend(line.split())
    return tokenList
main()


问:
Playing a video file from network folder
I am trying to play a video file from my network path which is

\\alan\movies\kids\alladin.mp4.

I am able to see and browse the directory from my Mac.

The code below work fine if I add the video file as part of the project

```<code>import UIKit
import AVFoundation
import AVKit

class ViewController: AVPlayerViewController {

    @IBOutlet var vwVideoView: UIView!

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    private func playVideo() {
        if let path = NSBundle.mainBundle().pathForResource("Alladin", ofType: "mp4") {
            let url = NSURL(fileURLWithPath: path)
            player = AVPlayer(URL: url)
        }
        else {
            print("Oops, something wrong when playing video")
        }
    }
}
</code>```

I copied the video file from network folder to my local movies folder as below

```<code>NSBundle.mainBundle().pathForResource("file://localhost/Users/alan/Movies/test/Alladin", ofType: "mp4")
</code>```

The video file is still not playing.  Is this even possible to play video file from network?

regards,
-Alan-

答:
because of MPMoviePlayerViewController deprecated in iOS9, so, It's better to use Apple's recommendation.</p>

```<code>- (void)playVidea:(UIButton *)btn {
    // play local video
    // NSURL *url = [[NSBundle mainBundle] URLForResource:@"Alladin" withExtension:@"mp4"];

    // play video from service
    NSURL *url = [NSURL URLWithString:@"http://119.23.148.104/image/931345031250313216.mp4"];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:item];

    AVPlayerViewController *playController = [[AVPlayerViewController alloc] init];
    playController.player = player;
    [playController.player play];
    [self presentViewController:playController animated:YES completion:nil];
}
</code>```

Body:
I am trying to play a video file from my network path which is

\\alan\movies\kids\alladin.mp4.

I am able to see and browse the directory from my Mac.

The code below work fine if I add the video file as part of the project

import UIKit
import AVFoundation
import AVKit

class ViewController: AVPlayerViewController {

    @IBOutlet var vwVideoView: UIView!

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    private func playVideo() {
        if let path = NSBundle.mainBundle().pathForResource("Alladin", ofType: "mp4") {
            let url = NSURL(fileURLWithPath: path)
            player = AVPlayer(URL: url)
        }
        else {
            print("Oops, something wrong when playing video")
        }
    }
}

I copied the video file from network folder to my local movies folder as below

NSBundle.mainBundle().pathForResource("file://localhost/Users/alan/Movies/test/Alladin", ofType: "mp4")

The video file is still not playing.  Is this even possible to play video file from network?

regards,
-Alan-

Body:
because of MPMoviePlayerViewController deprecated in iOS9, so, It's better to use Apple's recommendation.

- (void)playVidea:(UIButton *)btn {
    // play local video
    // NSURL *url = [[NSBundle mainBundle] URLForResource:@"Alladin" withExtension:@"mp4"];

    // play video from service
    NSURL *url = [NSURL URLWithString:@"http://119.23.148.104/image/931345031250313216.mp4"];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:item];

    AVPlayerViewController *playController = [[AVPlayerViewController alloc] init];
    playController.player = player;
    [playController.player play];
    [self presentViewController:playController animated:YES completion:nil];
}


问:
Force CakePHP plugin to use its own layout
I have written a CakePHP plugin https://github.com/anuj9196/CakePHP-App-Installer

The plugin is using default.ctp layout from plugin_path/src/template/layout/default.ctp

When there is some other theme used in the host application. Like in my case I have setup one in AppController's beforeRender()

```<code>$this->viewBuilder()->setTheme('DashboardTemplate');
</code>```

DashboardTemplate is in application's /plugin/ directory.

Now, when I access my plugin's URL using example.com/installer/install

The template loads on top of DashboardTemplate theme.

How can I disable them in plugin's AppController?

The AppController inside plugin directory contains

```<code><?php
namespace Installer\Controller;

use App\Controller\AppController as BaseController;

class AppController extends BaseController
{
    // nothing here
}
</code>```

答:
You can switch between layouts in your view and controllers  fairly easily.. using plugin syntax

```<code>// inside controller
  $this ->layout = 'Plugin.layout';

//inside view template
    $this ->layout = 'Plugin.layout';
</code>```

If you just want to disable the theme, use Mathew's method above. But be careful that will disable the theme for the whole application not just this plugin in case some of your app code is ran after your plugin

Body:
I have written a CakePHP plugin https://github.com/anuj9196/CakePHP-App-Installer

The plugin is using default.ctp layout from plugin_path/src/template/layout/default.ctp

When there is some other theme used in the host application. Like in my case I have setup one in AppController's beforeRender()

$this->viewBuilder()->setTheme('DashboardTemplate');

DashboardTemplate is in application's /plugin/ directory.

Now, when I access my plugin's URL using example.com/installer/install

The template loads on top of DashboardTemplate theme.

How can I disable them in plugin's AppController?

The AppController inside plugin directory contains

<?php
namespace Installer\Controller;

use App\Controller\AppController as BaseController;

class AppController extends BaseController
{
    // nothing here
}

Body:
You can switch between layouts in your view and controllers  fairly easily.. using plugin syntax

// inside controller
  $this ->layout = 'Plugin.layout';

//inside view template
    $this ->layout = 'Plugin.layout';

If you just want to disable the theme, use Mathew's method above. But be careful that will disable the theme for the whole application not just this plugin in case some of your app code is ran after your plugin