问:
How to pass JWT token from a microservice that consumes another microservice?
I have two microservices say A and B. In all REST endpoints for both microservices, I have implemented JWT authentication. A user has to hit an endpoint ("/login") with username and password and generate a token and pass this as a RequestHeader to all end points in both the services.
Say in microservice A, I have an endpoint ("test1/createSomething"). In B I have another have an endpoint ("test2/getSomething"). Now I am able to call ("test2/getSomething") from service B, in ("test1/createSomething") in service A using Feign client.

But I am not sure how to implement this in a way that I generate the JWT token in service A and pass it along to service B, to consume its services.

Please help. Beginner in microservices and exploring things.

答:
One approach you can try is by having a separate session/jwt service.
Roles and responsibility of that service would be to store/validate and authenticate having following endpoints.

create_token() : create new JWT token with given input data(say user info, expiration time etc)

is_token_valid() : check if token is valid or not

So you can have a flow like this :-

```<code>
 1. First hit to login-service > login service getting token from jwt-service > returning jwt token to UI/client.
 2. UI/Client passing received jwt token to service-b via headers> which indeed pass jwt token to service-a, where each service independently calls is_token_valid() of jwt-service and process the request only after getting success response.
</code>```

To implement this in spring-boot, what you can do is by adding an interceptor layer, that is being called before every Controller class, where is reads headers, extracts jwt-token and validates that from jwt-service.

You can look at the similar answer here.
Another reference here

Body:
One approach you can try is by having a separate session/jwt service.
Roles and responsibility of that service would be to store/validate and authenticate having following endpoints.

create_token() : create new JWT token with given input data(say user info, expiration time etc)

is_token_valid() : check if token is valid or not

So you can have a flow like this :-

 1. First hit to login-service > login service getting token from jwt-service > returning jwt token to UI/client.
 2. UI/Client passing received jwt token to service-b via headers> which indeed pass jwt token to service-a, where each service independently calls is_token_valid() of jwt-service and process the request only after getting success response.

To implement this in spring-boot, what you can do is by adding an interceptor layer, that is being called before every Controller class, where is reads headers, extracts jwt-token and validates that from jwt-service.

You can look at the similar answer here.
Another reference here


来源: stackexchange

问:
remove validation on name in laravel 6 on creating new user
I want to remove validation on the name in laravel 6 on creating a new user. The user is created successfully but when I enter a name with space or capital letters, the login page opens up. But if I remove all spaces from the name everything works fine with the following code.

```<code>protected function validator(array $data)
{
    return Validator::make($data, [
        'name'     => ['required', 'string', 'max:255'],
        'email'    => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

protected function create(array $data)
{
    $username = slugify($data['name']) . "-" . mt_rand(10000, 99999);

    return User::create([
        'name'     => $data['name'],
        'username' => $username,
        'email'    => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
</code>```

blade.php code

https://codeshare.io/5e1kX7

ContentLicense: CC BY-SA 4.0

Body:
I want to remove validation on the name in laravel 6 on creating a new user. The user is created successfully but when I enter a name with space or capital letters, the login page opens up. But if I remove all spaces from the name everything works fine with the following code.

protected function validator(array $data)
{
    return Validator::make($data, [
        'name'     => ['required', 'string', 'max:255'],
        'email'    => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

protected function create(array $data)
{
    $username = slugify($data['name']) . "-" . mt_rand(10000, 99999);

    return User::create([
        'name'     => $data['name'],
        'username' => $username,
        'email'    => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

blade.php code

https://codeshare.io/5e1kX7

Body:
Try

//...
'name' => ['required', 'string', 'regex:/^[a-zA-Z0-9\s]+$/', 'max:255'],
//...


问:
How to give each cell random digit number
I want to give each cell a random double-digit number between 50-500
i'm trying to use math.floor(math.random() as function but no success so far

also how I can target only one cell, for example i have 5x5 slots 5 rows 5 col, and I want to target the top left cell in the corner alone, and instead of random generated numbers like the rest cells, i want to give it a symbol where i can control it, so if the symbol is in top left corner, i click on middle for example and it moves there, replacing the generated number which was in the middle and keeping the top left right corner empty

sorry for the trouble, any help really appreciated

```<code><html>
<head>
<style>
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
</style>

<body>
<div id='ff'></div>

<script>
var isCol=0;
var board=[];
for(r=0;r<7;r++){
    var line=[];
    for(c=0;c<7;c++){
        line.push(r);
    }
    board.push(line);
}

function prs(c,r){
    showTable(c,r);
    isCol=(isCol+1)%2;
}

function toColor(col,row,chosen_col,chosen_row){
var ret=false;
switch(isCol){
    case 0:
        if(row==chosen_row){
            ret=true;
        }
        break;
    case 1:
        if(col==chosen_col){
            ret=true;
        }
        break;
}

return ret;
}

function showTable(chosen_col,chosen_row){
var str="";
str+="<table border=1>";
for(row=0;row<7;row++){
    str+="<tr>";
    for(col=0;col<7;col++){
        str+="<td onclick='prs("+col+","+row+")'";
        if(toColor(col,row,chosen_col,chosen_row)){
            str+=" class='grn' ";
        }
        str+=">";
str+=board[row][col];
        str+="</td>";
    }
    str+="</tr>";
}
str+="</table>";

 document.getElementById("ff").innerHTML=str;
}

showTable(-1);
</script>
</body>
</html>

</code>```

答:
Besides Stack Overflow - how to generate a random number in range...

I think you're overcomplicating the code.  Here's a suggestion:

const size = 5;
const rand = (min, max) => ~~(Math.random() * (max - min) + min);
let tdEmpty = null;            // A place to store the currently empty cell

const moveValue = evt => {
  const text = evt.target.textContent; // Get cell text
  if (!text) return;           // Clicked empty one, stop function.
  tdEmpty.textContent = text;  // Move text to the currently empty
  evt.target.textContent = ''; // Clear text from the clicked one
  tdEmpty = evt.target;        // Store the new empty TD cell.
};

const newTD = TR => {
  const td = TR.insertCell();
  const text = tdEmpty ? rand(50, 501) : ""; // Create "num" or ""
  td.appendChild(document.createTextNode(text));
  td.addEventListener('click', moveValue); // Assign a click callback
  if (!tdEmpty) tdEmpty = td;              // Store the first empty cell
};

const newTR = TABLE => {
  const tr = TABLE.insertRow();
  for (let i=0; i<size; i++) newTD(tr);
};

const table = document.createElement('table');
for (let i=0; i<size; i++) newTR(table);

document.querySelector('#ff').appendChild(table);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td { border: 2px solid black; }
td:hover { background-color: lightgreen; }</code>```

```

Useful links:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertCell

https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode

Generating random whole numbers in JavaScript in a specific range?

Body:
Besides Stack Overflow - how to generate a random number in range...

I think you're overcomplicating the code.  Here's a suggestion:

const size = 5;
const rand = (min, max) => ~~(Math.random() * (max - min) + min);
let tdEmpty = null;            // A place to store the currently empty cell

const moveValue = evt => {
  const text = evt.target.textContent; // Get cell text
  if (!text) return;           // Clicked empty one, stop function.
  tdEmpty.textContent = text;  // Move text to the currently empty
  evt.target.textContent = ''; // Clear text from the clicked one
  tdEmpty = evt.target;        // Store the new empty TD cell.
};

const newTD = TR => {
  const td = TR.insertCell();
  const text = tdEmpty ? rand(50, 501) : ""; // Create "num" or ""
  td.appendChild(document.createTextNode(text));
  td.addEventListener('click', moveValue); // Assign a click callback
  if (!tdEmpty) tdEmpty = td;              // Store the first empty cell
};

const newTR = TABLE => {
  const tr = TABLE.insertRow();
  for (let i=0; i<size; i++) newTD(tr);
};

const table = document.createElement('table');
for (let i=0; i<size; i++) newTR(table);

document.querySelector('#ff').appendChild(table);

td { border: 2px solid black; }
td:hover { background-color: lightgreen; }

<div id='ff'></div>

Useful links:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertCell

https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode

Generating random whole numbers in JavaScript in a specific range?


问:
How show list certain row in view?
The list in the view is limited to showing columns. I want to include the column that I want in the columns shown in the view.

How should I do?

```<code>@State var showMyRow = false

var body: some view {
   Vstack {
     Button(“bt”) {
          self.showMyRow.toggle()
      }
    ImageView
     ....
   List {
            ForEach
            .
            .
            . // if showMyRow is true, view show this row
    }
  }
}
</code>```

Above image, showMyRow is false.

After button action, showMyRow is true.
If showMyRow is true, show me at the 7row

答:
Updated Answer:
Not sure if I understood your question perfectly, but if you just want a list that you can add and delete things from, then the easiest would be to create a separate SwiftUI file holding a struct for the row and an ObservableObject class that checks for any changes.

1) SwiftUI File with ListItem struct & ObservableObject class:

```<code>import SwiftUI

struct ListItem: Identifiable {
    let id = UUID()
    let title: String
}

class Items: ObservableObject {
    @Published var rows = [ListItem]()
}
</code>```

2) ContentView with your image view and list:

This also has a removeItems method so you can swipe any row to delete it.

```<code>struct ContentView: View {

    @ObservedObject var items = Items()

    var body: some View {
        NavigationView{
            VStack{
                Image("image")
                    .resizable()
                    .frame(width: 200, height: 200)
                    .padding(50)
                List {
                    ForEach(items.rows) { item in
                        Text(item.title)
                    }
                .onDelete(perform: removeItems)
                }
            }
        .navigationBarTitle("My List")
            .navigationBarItems(trailing: Button(action : {
                let row = ListItem(title: "New Row")
                self.items.rows.append(row)
            }) {
                Image(systemName: "plus")
            }
            )
        }
    }

    func removeItems(at offsets: IndexSet) {
        items.rows.remove(atOffsets: offsets)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Title: How show list certain row in view?

Body:
The list in the view is limited to showing columns. I want to include the column that I want in the columns shown in the view.

How should I do?

@State var showMyRow = false

var body: some view {
   Vstack {
     Button(“bt”) {
          self.showMyRow.toggle()
      }
    ImageView
     ....
   List {
            ForEach
            .
            .
            . // if showMyRow is true, view show this row
    }
  }
}

Above image, showMyRow is false.

After button action, showMyRow is true.
If showMyRow is true, show me at the 7row

Body:
Updated Answer:
Not sure if I understood your question perfectly, but if you just want a list that you can add and delete things from, then the easiest would be to create a separate SwiftUI file holding a struct for the row and an ObservableObject class that checks for any changes.

1) SwiftUI File with ListItem struct & ObservableObject class:

import SwiftUI

struct ListItem: Identifiable {
    let id = UUID()
    let title: String
}

class Items: ObservableObject {
    @Published var rows = [ListItem]()
}

2) ContentView with your image view and list:

This also has a removeItems method so you can swipe any row to delete it.

struct ContentView: View {

    @ObservedObject var items = Items()

    var body: some View {
        NavigationView{
            VStack{
                Image("image")
                    .resizable()
                    .frame(width: 200, height: 200)
                    .padding(50)
                List {
                    ForEach(items.rows) { item in
                        Text(item.title)
                    }
                .onDelete(perform: removeItems)
                }
            }
        .navigationBarTitle("My List")
            .navigationBarItems(trailing: Button(action : {
                let row = ListItem(title: "New Row")
                self.items.rows.append(row)
            }) {
                Image(systemName: "plus")
            }
            )
        }
    }

    func removeItems(at offsets: IndexSet) {
        items.rows.remove(atOffsets: offsets)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
How to re-scale vertices to fit within certain range while preserving aspect ratio?
I'm trying to normalize the vertices of a mesh to fit within a bounding box that ranges from -0.5 to +0.5. Using the following logic, I've accomplished that:

```<code># Calculate max and min values for each axis to
# get existing bounding box
x_max = np.max(vertices[:, 0])
y_max = np.max(vertices[:, 1])
z_max = np.max(vertices[:, 2])

x_min = np.min(vertices[:, 0])
y_min = np.min(vertices[:, 1])
z_min = np.min(vertices[:, 2])

# Calculate normalized vertices
normalized_x = 1 * (vertices[:, 0] - x_min) / (x_max - x_min) - 0.5
normalized_y = 1 * (vertices[:, 1] - y_min) / (y_max - y_min) - 0.5
normalized_z = 1 * (vertices[:, 2] - z_min) / (z_max - z_min) - 0.5

normalized_vertices = np.column_stack((normalized_x, normalized_y, normalized_z))
</code>```

However, my problem is that while my mesh vertices are now in the proper range, the aspect ratio isn't preserved (so like the longer dimension is completely squashed). How would I scale this properly so that my points still range within the max of -0.5 to +0.5, but the original aspect ratio is preserved?

答:
Use the greatest value of:

```<code>(x_max - x_min)
(y_max - y_min)
(z_max - z_min)
</code>```

and divide by this value, let say it is max_value:

```<code>normalized_x = 1 * (vertices[:, 0] - x_min) / max_value - 0.5
normalized_y = 1 * (vertices[:, 1] - y_min) / max_value - 0.5
normalized_z = 1 * (vertices[:, 2] - z_min) / max_value - 0.5
</code>```

Body:
I'm trying to normalize the vertices of a mesh to fit within a bounding box that ranges from -0.5 to +0.5. Using the following logic, I've accomplished that:

# Calculate max and min values for each axis to
# get existing bounding box
x_max = np.max(vertices[:, 0])
y_max = np.max(vertices[:, 1])
z_max = np.max(vertices[:, 2])

x_min = np.min(vertices[:, 0])
y_min = np.min(vertices[:, 1])
z_min = np.min(vertices[:, 2])

# Calculate normalized vertices
normalized_x = 1 * (vertices[:, 0] - x_min) / (x_max - x_min) - 0.5
normalized_y = 1 * (vertices[:, 1] - y_min) / (y_max - y_min) - 0.5
normalized_z = 1 * (vertices[:, 2] - z_min) / (z_max - z_min) - 0.5

normalized_vertices = np.column_stack((normalized_x, normalized_y, normalized_z))

However, my problem is that while my mesh vertices are now in the proper range, the aspect ratio isn't preserved (so like the longer dimension is completely squashed). How would I scale this properly so that my points still range within the max of -0.5 to +0.5, but the original aspect ratio is preserved?

Body:
Use the greatest value of:

(x_max - x_min)
(y_max - y_min)
(z_max - z_min)

and divide by this value, let say it is max_value:

normalized_x = 1 * (vertices[:, 0] - x_min) / max_value - 0.5
normalized_y = 1 * (vertices[:, 1] - y_min) / max_value - 0.5
normalized_z = 1 * (vertices[:, 2] - z_min) / max_value - 0.5


问:
In EF4.1 code first, What is the difference between configuring entities using annotations, configuration files, or in the OnModelCreating?
Currently I am using separate configuration files and calling them like:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProductConfiguration());
    base.OnModelCreating(modelBuilder);
}
</code>```

It seems like most of the examples online are really basic so they define their models, the DbContext and the model configurations all in a single class.  Are there and performance issues or other compelling reasons to use one over the other?

答: No, it's only a matter of readability. As your model grows you will probably get a very large configuration in OnModelCreating. As to make this more readable you break it up into separate configurations.</p>

ContentLicense: CC BY-SA 3.0

Body:
Currently I am using separate configuration files and calling them like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProductConfiguration());
    base.OnModelCreating(modelBuilder);
}

It seems like most of the examples online are really basic so they define their models, the DbContext and the model configurations all in a single class.  Are there and performance issues or other compelling reasons to use one over the other?


问:
Use Log Likelihood to compare different mallet topic models?
I'm trying to find out if it's possbible - or what's the best way - to compare programmatically different topic models created with mallet to determine the "best" fitting model for the given corpus.

The API offers a Method to determine the Log Likelihood of the generated model. See f.e. : #modelLogLikelihood()

Afaik it's possible to compare different models based on the log likelihood of held-out data. But this method computes the likelihood of .. the whole model, I guess? I already checked the source code, but this didn't bring light into the darkness.

So my question is:
Is the output of the above mentioned method suitable to compare different topic modeling algorithms like Hierarchical PAM, LDA, DMR, ... to find out which model (theoretically) represents the corpus the best way?

答:
The intention of the log likelihood calculation is to provide a metric that is comparable across different models. That said, I wouldn't recommend using it in that way.

First, if you actually care about language model predictive likelihood, you should use one of many more recent deep neural models.

Second, likelihood is very sensitive to smoothing parameters, so the fact that you get consistent differences may be just an artifact of your own settings. Preprocessing decisions like tokenization and multi-word terms can also have a bigger impact than choice of model.

Third, if you are actually interested in topic model output, you should be clear about what you want from the model, and what characteristics of a model make it useful for your specific needs. I like to suggest that people think of a topic model as more like making a map than fitting a regression. The best resolution of the map depends on where you want to go.

Finally, you are almost certainly better off with the simplest model.


问:
SQL count users with winning streaks
I am fairly new to SQL and have been messing about with some small projects to get to grips with how it can be used for large scale statistics.

The problem I am currently working on is just counting the number of users who have had a winning streak in a time period.

Given a table of the format

```<code>user_id,date_time,user_team,win_team
ab542a,2018-01-02 18:45:25,team1,team1
ef72da,2018-01-02 08:20:01,team2,team1
f5c776,2017-12-30 15:25:25,team1,team2
5a278a,2018-01-01 14:27:15,team2,team2
ae346d,2018-01-01 14:27:15,team2,team2
2b13d8,2017-12-31 12:33:34,team1,team2
ace797,2018-01-02 08:20:01,team2,team2
ace797,2018-01-03 18:18:22,team1,team2
ab542a,2018-01-03 18:45:25,team1,team1
ef72da,2018-01-03 08:20:01,team2,team1
f5c776,2017-12-31 15:25:25,team1,team2
5a278a,2018-01-02 14:27:15,team2,team2
ae346d,2018-01-02 14:27:15,team2,team2
2b13d8,2018-01-01 12:33:34,team1,team2
ace797,2018-01-03 08:20:01,team1,team1
ace797,2018-01-04 18:18:22,team1,team1
ab542a,2018-01-04 18:45:25,team1,team1
ef72da,2018-01-04 08:20:01,team2,team1
f5c776,2018-01-01 15:25:25,team1,team2
5a278a,2018-01-03 14:27:15,team2,team2
ae346d,2018-01-03 14:27:15,team2,team2
2b13d8,2018-01-02 12:33:34,team1,team2
ace797,2018-01-04 08:20:01,team2,team2
ace797,2018-01-05 18:18:22,team1,team1
</code>```

where user is the users id, date is the date of the match, team is the side the user played for and winner is the winning side from the match. How could I count all the users that have had a winning streak (at least 3 consecutive wins)?

Furthermore, say I want to also keep track of the game being played (chess, backgammon, etc.) in the same table, would it be possible in the same query to track streaks in multiple games?

In python this could be achieved with a relatively simple loop over user ids but would be computationally expensive and probably wouldn't scale well

答:
If you want users with at least 3 wins in a row, you can use window functions like this:

```<code>select count(distinct t.user)
from (select t.*,
             lead(date, 2) over (partition by user order by date) as date_2,
             lead(date, 2) over (partition by user, (case when team = winner then 'win' else 'lose' end
                                 order by date
                                ) date_same_2
      from t
      where date >= ? and date < ?
     ) t
where team = winner;
</code>```

What this is doing is checking the row for the user 2 rows ahead by two criteria.  The first is just by date.  The second is when the user's team is the winner.   If these are the same -- and the current row is a winning row -- then you have three wins in a row.

Title: SQL count users with winning streaks

Body:
I am fairly new to SQL and have been messing about with some small projects to get to grips with how it can be used for large scale statistics.

The problem I am currently working on is just counting the number of users who have had a winning streak in a time period.

Given a table of the format

user_id,date_time,user_team,win_team
ab542a,2018-01-02 18:45:25,team1,team1
ef72da,2018-01-02 08:20:01,team2,team1
f5c776,2017-12-30 15:25:25,team1,team2
5a278a,2018-01-01 14:27:15,team2,team2
ae346d,2018-01-01 14:27:15,team2,team2
2b13d8,2017-12-31 12:33:34,team1,team2
ace797,2018-01-02 08:20:01,team2,team2
ace797,2018-01-03 18:18:22,team1,team2
ab542a,2018-01-03 18:45:25,team1,team1
ef72da,2018-01-03 08:20:01,team2,team1
f5c776,2017-12-31 15:25:25,team1,team2
5a278a,2018-01-02 14:27:15,team2,team2
ae346d,2018-01-02 14:27:15,team2,team2
2b13d8,2018-01-01 12:33:34,team1,team2
ace797,2018-01-03 08:20:01,team1,team1
ace797,2018-01-04 18:18:22,team1,team1
ab542a,2018-01-04 18:45:25,team1,team1
ef72da,2018-01-04 08:20:01,team2,team1
f5c776,2018-01-01 15:25:25,team1,team2
5a278a,2018-01-03 14:27:15,team2,team2
ae346d,2018-01-03 14:27:15,team2,team2
2b13d8,2018-01-02 12:33:34,team1,team2
ace797,2018-01-04 08:20:01,team2,team2
ace797,2018-01-05 18:18:22,team1,team1

where user is the users id, date is the date of the match, team is the side the user played for and winner is the winning side from the match. How could I count all the users that have had a winning streak (at least 3 consecutive wins)?

Furthermore, say I want to also keep track of the game being played (chess, backgammon, etc.) in the same table, would it be possible in the same query to track streaks in multiple games?

In python this could be achieved with a relatively simple loop over user ids but would be computationally expensive and probably wouldn't scale well

Body:
If you want users with at least 3 wins in a row, you can use window functions like this:

select count(distinct t.user)
from (select t.*,
             lead(date, 2) over (partition by user order by date) as date_2,
             lead(date, 2) over (partition by user, (case when team = winner then 'win' else 'lose' end
                                 order by date
                                ) date_same_2
      from t
      where date >= ? and date < ?
     ) t
where team = winner;

What this is doing is checking the row for the user 2 rows ahead by two criteria.  The first is just by date.  The second is when the user's team is the winner.   If these are the same -- and the current row is a winning row -- then you have three wins in a row.


问:
C# testing - mock class in contructor call
I'm new to using Moq with Xunit in Visual Studio 2019.

I want to mock the contructor call of a class that is being called in the contructor of my tested class.
A simple demonstration of my problem:

```<code>public class MockedClass : IMockedClass
{
   public MockedClass()
   {
      // don't call this
   }
   public List<string> Function1()
   { /* return a List<string> here */ }
}
</code>```

```<code>public class MyClass
{
   readonly IMockedClass mockedClass = null;
   public MyClass()
   {
      mockedClass = new MockedClass();
   }
   public string Function2()
   { /* return a string here */ }
}
</code>```

```<code>public class MyClassTest
{
   [Fact]
   public string Function2Test()
   {
      var returnMock = new List<string>() { "1", "2", "3" };
      var mockMockedClass = new Mock<IMockedClass>();
      mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
      var myClass = new MyClass();
      var result = myClass.Function2();
      ...
   }
}
</code>```

My problem is, that in the test Function2Test the constructor of MyClass is being called that calls the constructor of MockedClass.
But I don't want the constructor of MockedClass being called.

How can I mock the constructor of MockedClass?

答:
You were on the right direction to mock dependencies, but you lack the implementation of the Dependency Inversion Principle.

With your code as-is, you are tying your MyClass to the MockedClass, and furthermore you let MyClass control the MockedClass object's lifetime.

What you should do, is alter the constructor of MyClass to accept an IMockedClass object. Note that you should pass the interface, not the class type.

```<code>public class MyClass
{
   readonly IMockedClass mockedClass = null;
   public MyClass(IMockedClass mockedClass)
   {
      this.mockedClass = mockedClass();
   }
   public string Function2()
   { /* return a string here */ }
}
</code>```

and your test code will be:

```<code>public string Function2Test()
   {
      var returnMock = new List<string>() { "1", "2", "3" };
      var mockMockedClass = new Mock<IMockedClass>();
      mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
      var myClass = new MyClass(mockMockedClass.Object);
      var result = myClass.Function2();
      ...
   }
</code>```

Body:
I'm new to using Moq with Xunit in Visual Studio 2019.

I want to mock the contructor call of a class that is being called in the contructor of my tested class.
A simple demonstration of my problem:

public class MockedClass : IMockedClass
{
   public MockedClass()
   {
      // don't call this
   }
   public List<string> Function1()
   { /* return a List<string> here */ }
}

public class MyClass
{
   readonly IMockedClass mockedClass = null;
   public MyClass()
   {
      mockedClass = new MockedClass();
   }
   public string Function2()
   { /* return a string here */ }
}

public class MyClassTest
{
   [Fact]
   public string Function2Test()
   {
      var returnMock = new List<string>() { "1", "2", "3" };
      var mockMockedClass = new Mock<IMockedClass>();
      mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
      var myClass = new MyClass();
      var result = myClass.Function2();
      ...
   }
}

My problem is, that in the test Function2Test the constructor of MyClass is being called that calls the constructor of MockedClass.
But I don't want the constructor of MockedClass being called.

How can I mock the constructor of MockedClass?

Body:
You were on the right direction to mock dependencies, but you lack the implementation of the Dependency Inversion Principle.

With your code as-is, you are tying your MyClass to the MockedClass, and furthermore you let MyClass control the MockedClass object's lifetime.

What you should do, is alter the constructor of MyClass to accept an IMockedClass object. Note that you should pass the interface, not the class type.

public class MyClass
{
   readonly IMockedClass mockedClass = null;
   public MyClass(IMockedClass mockedClass)
   {
      this.mockedClass = mockedClass();
   }
   public string Function2()
   { /* return a string here */ }
}

and your test code will be:

public string Function2Test()
   {
      var returnMock = new List<string>() { "1", "2", "3" };
      var mockMockedClass = new Mock<IMockedClass>();
      mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
      var myClass = new MyClass(mockMockedClass.Object);
      var result = myClass.Function2();
      ...
   }


问:
How to redirect URL via JavaScript based on a number (if 1, redirect to A; if 2, to B...)
I want to redirect a visitor based on a variable in their URL. Use case is a quiz with Gravity Forms where the user will be redirected to example.com/processing?quizresult={n}

Where n is a numerical value (0-50).

There are 3 possible outcomes (0-15, 16-30, 31-50).

I’ve found JavaScript to redirect based on if a URL contains a variable, but not a range of variables. Is there a better way than 50 “IF” statements?

```<code><script>
if(document.location.href.indexOf('1') > -1) {
    document.location.href = 'http://www.example.com/resultA';
}

if(document.location.href.indexOf('2') > -1) {
    document.location.href = 'http://www.example.com/resultA';
}

if(document.location.href.indexOf('3') > -1) {
    document.location.href = 'http://www.example.com/resultA';
}
</code>```

答:
Hey Your solutions is here,

Try this.

if (document.location.href.indexOf(1) > -1) {
      alert("your url contains the name franky");
    } else if (document.location.href.indexOf(2) > -1) {
      alert("your url contains the name franky");
    } else if (document.location.href.indexOf(3) > -1) {
      alert("your url contains the name franky");
    } else{ alert("not matach any value");}```


问:
Another exception was thrown: NoSuchMethodError: The getter 'id' was called on null. in Flutter
I am developing a shopping cart application using flutter.After user clicks the add button in product detail page product should be added to the cart.But when i click the add button it shows an error like this

This is my CartModel code

```<code>import 'package:cart_application/model/product.dart';
    import 'package:flutter/material.dart';

    class CartBloc extends ChangeNotifier {
      Map<int, int> _cart = {};

      Map<int, int> get cart => _cart;

      void addToCart(ProductsListItem productsListItem) {
          _cart[productsListItem.id] ;

        notifyListeners();
      }

      void clear(ProductsListItem productsListItem) {
          _cart.remove(productsListItem.id);
          notifyListeners();
        }
      }
</code>```

This is my ProductListItemPage.

```<code>import 'package:flutter/material.dart';
import '../util/constants.dart';

class ProductsListItem extends StatelessWidget {
  final int id;
  final String name;
  final int currentPrice;
  final int originalPrice;
  final int discount;
  final String imageUrl;

  const ProductsListItem({Key key,
    this.id,
    this.name,
    this.currentPrice,
    this.originalPrice,
    this.discount,
    this.imageUrl})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _buildProductItemCard(context),
        _buildProductItemCard(context),
      ],
    );
  }

  _buildProductItemCard(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(Constants.ROUTE_PRODUCT_DETAIL);
      },
      child: Card(
        elevation: 4.0,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Image.network(
                imageUrl,
              ),
              height: 250.0,
              width: MediaQuery
                  .of(context)
                  .size
                  .width / 2.2,
            ),
            SizedBox(
              height: 8.0,
            ),
            Padding(
              padding: const EdgeInsets.only(
                left: 8.0,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    name,
                    style: TextStyle(fontSize: 16.0, color: Colors.grey),
                  ),
                  SizedBox(
                    height: 2.0,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Text(
                        "\$$currentPrice",
                        style: TextStyle(fontSize: 16.0, color: Colors.black),
                      ),
                      SizedBox(
                        width: 8.0,
                      ),
                      Text(
                        "\$$originalPrice",
                        style: TextStyle(
                          fontSize: 12.0,
                          color: Colors.grey,
                          decoration: TextDecoration.lineThrough,
                        ),
                      ),
                      SizedBox(
                        width: 8.0,
                      ),
                      Text(
                        "$discount\% off",
                        style: TextStyle(fontSize: 12.0, color: Colors.grey),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 8.0,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

This is where my Add to cart method called in ProductListPage.

```<code> _buildBottomNavigationBar(BuildContext context) {
    ProductsListItem  item;
    var bloc = Provider.of<CartBloc>(context);
    int totalCount = 0;
    if (bloc.cart.length > 0) {
      totalCount = bloc.cart.values.reduce((a, b) => a + b);
    }
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 50.0,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Flexible(
            fit: FlexFit.tight,
            flex: 1,
            child: RaisedButton(
              onPressed: () {},
              color: Colors.grey,
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(
                      Icons.list,
                      color: Colors.white,
                    ),
                    SizedBox(
                      width: 4.0,
                    ),
                    Text(
                      "SAVE",
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Flexible(
            flex: 2,
            **child: RaisedButton(
              onPressed: (){bloc.addToCart(item);},**

              color: Colors.greenAccent,
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(
                      Icons.card_travel,
                      color: Colors.white,
                    ),
                    SizedBox(
                      width: 4.0,
                    ),
                    Text(
                      "ADD TO BAG",
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
</code>```

And this is my CartPage

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../model/cart_bloc.dart';

class CartPage extends StatefulWidget {
  CartPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {

  @override
  Widget build(BuildContext context) {

    var bloc = Provider.of<CartBloc>(context,listen: false);
    var cart = bloc.cart;
    return Scaffold(
      appBar: AppBar(
        title: Text("Shopping Cart"),
        leading: IconButton(
          icon: Icon(
            Icons.chevron_left,
            size: 40.0,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),

      ),
      body:
        ListView.builder(
          itemCount: cart.length,
          itemBuilder: (context, index) {
            int giftIndex = cart.keys.toList()[index];
            int count = cart[giftIndex];
            return ListTile(
              leading: Container(
                height: 70,
                width: 70,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("${giftIndex + 1}.jpg"),
                    fit: BoxFit.fitWidth,
                  ),
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              title: Text('Item Count: $count'),
              trailing: RaisedButton(
                child: Text('Clear'),
                color: Theme.of(context).buttonColor,
                elevation: 1.0,
                splashColor: Colors.blueGrey,
                onPressed: () {

                },
              ),
            );
          },
        ),

    );
  }
}
</code>```

And i am using Android Studio as the IDE.

答:
This might not be the main issue here but it sure might help that you actually add the item to the cart. The nethod add is never called on your _cart list.

```<code>void addToCart(ProductsListItem productsListItem) {
        //this
        _cart.add(productsListItem.id);

        //instead of this
        _cart[productsListItem.id];

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

Maybe the main problem doesn't come from there but it will at least help you locate it.

Body:
I am developing a shopping cart application using flutter.After user clicks the add button in product detail page product should be added to the cart.But when i click the add button it shows an error like this

This is my CartModel code

import 'package:cart_application/model/product.dart';
    import 'package:flutter/material.dart';

    class CartBloc extends ChangeNotifier {
      Map<int, int> _cart = {};

      Map<int, int> get cart => _cart;

      void addToCart(ProductsListItem productsListItem) {
          _cart[productsListItem.id] ;

        notifyListeners();
      }

      void clear(ProductsListItem productsListItem) {
          _cart.remove(productsListItem.id);
          notifyListeners();
        }
      }

This is my ProductListItemPage.

import 'package:flutter/material.dart';
import '../util/constants.dart';

class ProductsListItem extends StatelessWidget {
  final int id;
  final String name;
  final int currentPrice;
  final int originalPrice;
  final int discount;
  final String imageUrl;

  const ProductsListItem({Key key,
    this.id,
    this.name,
    this.currentPrice,
    this.originalPrice,
    this.discount,
    this.imageUrl})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _buildProductItemCard(context),
        _buildProductItemCard(context),
      ],
    );
  }

  _buildProductItemCard(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(Constants.ROUTE_PRODUCT_DETAIL);
      },
      child: Card(
        elevation: 4.0,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Image.network(
                imageUrl,
              ),
              height: 250.0,
              width: MediaQuery
                  .of(context)
                  .size
                  .width / 2.2,
            ),
            SizedBox(
              height: 8.0,
            ),
            Padding(
              padding: const EdgeInsets.only(
                left: 8.0,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    name,
                    style: TextStyle(fontSize: 16.0, color: Colors.grey),
                  ),
                  SizedBox(
                    height: 2.0,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Text(
                        "\$$currentPrice",
                        style: TextStyle(fontSize: 16.0, color: Colors.black),
                      ),
                      SizedBox(
                        width: 8.0,
                      ),
                      Text(
                        "\$$originalPrice",
                        style: TextStyle(
                          fontSize: 12.0,
                          color: Colors.grey,
                          decoration: TextDecoration.lineThrough,
                        ),
                      ),
                      SizedBox(
                        width: 8.0,
                      ),
                      Text(
                        "$discount\% off",
                        style: TextStyle(fontSize: 12.0, color: Colors.grey),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 8.0,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

This is where my Add to cart method called in ProductListPage.

 _buildBottomNavigationBar(BuildContext context) {
    ProductsListItem  item;
    var bloc = Provider.of<CartBloc>(context);
    int totalCount = 0;
    if (bloc.cart.length > 0) {
      totalCount = bloc.cart.values.reduce((a, b) => a + b);
    }
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 50.0,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Flexible(
            fit: FlexFit.tight,
            flex: 1,
            child: RaisedButton(
              onPressed: () {},
              color: Colors.grey,
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(
                      Icons.list,
                      color: Colors.white,
                    ),
                    SizedBox(
                      width: 4.0,
                    ),
                    Text(
                      "SAVE",
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Flexible(
            flex: 2,
            **child: RaisedButton(
              onPressed: (){bloc.addToCart(item);},**

              color: Colors.greenAccent,
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(
                      Icons.card_travel,
                      color: Colors.white,
                    ),
                    SizedBox(
                      width: 4.0,
                    ),
                    Text(
                      "ADD TO BAG",
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

And this is my CartPage

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../model/cart_bloc.dart';

class CartPage extends StatefulWidget {
  CartPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {

  @override
  Widget build(BuildContext context) {

    var bloc = Provider.of<CartBloc>(context,listen: false);
    var cart = bloc.cart;
    return Scaffold(
      appBar: AppBar(
        title: Text("Shopping Cart"),
        leading: IconButton(
          icon: Icon(
            Icons.chevron_left,
            size: 40.0,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),

      ),
      body:
        ListView.builder(
          itemCount: cart.length,
          itemBuilder: (context, index) {
            int giftIndex = cart.keys.toList()[index];
            int count = cart[giftIndex];
            return ListTile(
              leading: Container(
                height: 70,
                width: 70,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("${giftIndex + 1}.jpg"),
                    fit: BoxFit.fitWidth,
                  ),
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              title: Text('Item Count: $count'),
              trailing: RaisedButton(
                child: Text('Clear'),
                color: Theme.of(context).buttonColor,
                elevation: 1.0,
                splashColor: Colors.blueGrey,
                onPressed: () {

                },
              ),
            );
          },
        ),

    );
  }
}

And i am using Android Studio as the IDE.

Body:
This might not be the main issue here but it sure might help that you actually add the item to the cart. The nethod add is never called on your _cart list.

void addToCart(ProductsListItem productsListItem) {
        //this
        _cart.add(productsListItem.id);

        //instead of this
        _cart[productsListItem.id];

        notifyListeners();
      }

Maybe the main problem doesn't come from there but it will at least help you locate it.


问:
Weird characters when scraping HTML tables generated by Javascript
I'm trying to scrape some data from https://www.flashscore.com/tennis/atp-singles/australian-open-2020/results/

In particular, I'm interested in the "tournament-page-data-results" div in the source code. The data does appear in the HTML source code when I pull it up, but it looks something like this:

```<code>"SA÷2¬~ZA÷ATP - SINGLES: Australian Open (Australia), hard¬ZEE÷MP4jLdJh¬ZB÷3473162¬ZC÷n5bYULYo¬ZD÷p¬ZE÷6N6d2yER¬ZF÷0¬ZO÷0¬ZG÷2¬ZH÷9011_MP4jLdJh¬ZJ÷5¬ZL÷/tennis/atp-singles/australian-open/¬ZX÷01110...000Australian O021, hard00000000Australian O027ralia)¬ZHS÷5724¬ZCC÷0¬ZAF÷ATP - Singles¬~AA÷WEJGUHfb¬AD÷1580633100¬ADE÷1580633100¬AB÷3¬CR÷3¬AC÷3¬CX÷Thiem
</code>```

with the real data mixed in with random characters. I have tried to convert from 'utf-8' to 'ascii' but it has the same issue just with different random characters.

What is the proper encoding I need here? Or is there a different approach altogether? I'm scraping with R (rvest package) to avoid opening every page in a browser window. I can switch to Python if that is easier.

答:
As people have mentioned in the comments, this is not an encoding issue. The text content of the div is written in a type of table markup language which is interpreted by javascript.

You can reverse engineer the parser. To start with, each match is split by a tilde (~) character, and the data fields are split by the "¬" character. Each field is in the form of a key-value pair split by a "÷".

It isn't easy to turn this into a data frame, since the data isn't rectangular. It would be easier to convert to JSON.

Here's an example of how to get some of the fields of interest:

```<code>"https://www.flashscore.com/tennis/atp-singles/australian-open-2020/results/" %>%
  xml2::read_html() %>%
  rvest::html_node("#tournament-page-data-results") %>%
  rvest::html_text() %>% strsplit("[~]") %>% unlist() %>% strsplit("\u00ac") %>%
  lapply(function(x) gsub("^.*\u00f7", "", x)) %>%
  lapply(function(x){
    y <- as.numeric(grep("\\d{10}", x, value = TRUE))
    y <- as.difftime(y, units = "secs") + as.POSIXct("1970-01-01 00:00:00")
    x[grep("\\d{10}", x)] <- as.character(y)
    return(x)}) %>%
  lapply(`[`, -(1:2)) %>%
  lapply(function(x) x[!grepl("^[[:alnum:]]{8}$", x)]) %>%
  lapply(function(x) grep("[a-z ]", x, value = TRUE)[-c(2,4,6,8)]) %>%
  `[`(-(1:2)) %>%
  {do.call(rbind, .)} %>%
  as.data.frame(stringsAsFactors = FALSE) %>%
  `names<-`(c("Date", "Stage", "Player1", "Player2")) %>%
  tibble::as.tibble()
#> # A tibble: 127 x 4
#>    Date                Stage          Player1           Player2
#>    <chr>               <chr>          <chr>             <chr>
#>  1 2020-02-02 07:45:00 Final          Djokovic N. (Srb) Thiem D. (Aut)
#>  2 2020-01-31 07:45:00 Semi-finals    Thiem D. (Aut)    Zverev A. (Ger)
#>  3 2020-01-30 07:45:00 Semi-finals    Federer R. (Sui)  Djokovic N. (Srb)
#>  4 2020-01-29 07:45:00 Quarter-finals Thiem D. (Aut)    Nadal R. (Esp)
#>  5 2020-01-29 02:45:00 Quarter-finals Wawrinka S. (Sui) Zverev A. (Ger)
#>  6 2020-01-28 07:50:00 Quarter-finals Raonic M. (Can)   Djokovic N. (Srb)
#>  7 2020-01-28 03:15:00 Quarter-finals Sandgren T. (Usa) Federer R. (Sui)
#>  8 2020-01-27 08:05:00 1/8-finals     Rublev A. (Rus)   Zverev A. (Ger)
#>  9 2020-01-27 07:15:00 1/8-finals     Nadal R. (Esp)    Kyrgios N. (Aus)
#> 10 2020-01-27 03:15:00 1/8-finals     Medvedev D. (Rus) Wawrinka S. (Sui)
#> # ... with 117 more rows
</code>```

Body:
I'm trying to scrape some data from https://www.flashscore.com/tennis/atp-singles/australian-open-2020/results/

In particular, I'm interested in the "tournament-page-data-results" div in the source code. The data does appear in the HTML source code when I pull it up, but it looks something like this:

"SA÷2¬~ZA÷ATP - SINGLES: Australian Open (Australia), hard¬ZEE÷MP4jLdJh¬ZB÷3473162¬ZC÷n5bYULYo¬ZD÷p¬ZE÷6N6d2yER¬ZF÷0¬ZO÷0¬ZG÷2¬ZH÷9011_MP4jLdJh¬ZJ÷5¬ZL÷/tennis/atp-singles/australian-open/¬ZX÷01110...000Australian O021, hard00000000Australian O027ralia)¬ZHS÷5724¬ZCC÷0¬ZAF÷ATP - Singles¬~AA÷WEJGUHfb¬AD÷1580633100¬ADE÷1580633100¬AB÷3¬CR÷3¬AC÷3¬CX÷Thiem

with the real data mixed in with random characters. I have tried to convert from 'utf-8' to 'ascii' but it has the same issue just with different random characters.

What is the proper encoding I need here? Or is there a different approach altogether? I'm scraping with R (rvest package) to avoid opening every page in a browser window. I can switch to Python if that is easier.

Body:
As people have mentioned in the comments, this is not an encoding issue. The text content of the div is written in a type of table markup language which is interpreted by javascript.

You can reverse engineer the parser. To start with, each match is split by a tilde (~) character, and the data fields are split by the "¬" character. Each field is in the form of a key-value pair split by a "÷".

It isn't easy to turn this into a data frame, since the data isn't rectangular. It would be easier to convert to JSON.

Here's an example of how to get some of the fields of interest:

"https://www.flashscore.com/tennis/atp-singles/australian-open-2020/results/" %>%
  xml2::read_html() %>%
  rvest::html_node("#tournament-page-data-results") %>%
  rvest::html_text() %>% strsplit("[~]") %>% unlist() %>% strsplit("\u00ac") %>%
  lapply(function(x) gsub("^.*\u00f7", "", x)) %>%
  lapply(function(x){
    y <- as.numeric(grep("\\d{10}", x, value = TRUE))
    y <- as.difftime(y, units = "secs") + as.POSIXct("1970-01-01 00:00:00")
    x[grep("\\d{10}", x)] <- as.character(y)
    return(x)}) %>%
  lapply(`[`, -(1:2)) %>%
  lapply(function(x) x[!grepl("^[[:alnum:]]{8}$", x)]) %>%
  lapply(function(x) grep("[a-z ]", x, value = TRUE)[-c(2,4,6,8)]) %>%
  `[`(-(1:2)) %>%
  {do.call(rbind, .)} %>%
  as.data.frame(stringsAsFactors = FALSE) %>%
  `names<-`(c("Date", "Stage", "Player1", "Player2")) %>%
  tibble::as.tibble()
#> # A tibble: 127 x 4
#>    Date                Stage          Player1           Player2
#>    <chr>               <chr>          <chr>             <chr>
#>  1 2020-02-02 07:45:00 Final          Djokovic N. (Srb) Thiem D. (Aut)
#>  2 2020-01-31 07:45:00 Semi-finals    Thiem D. (Aut)    Zverev A. (Ger)
#>  3 2020-01-30 07:45:00 Semi-finals    Federer R. (Sui)  Djokovic N. (Srb)
#>  4 2020-01-29 07:45:00 Quarter-finals Thiem D. (Aut)    Nadal R. (Esp)
#>  5 2020-01-29 02:45:00 Quarter-finals Wawrinka S. (Sui) Zverev A. (Ger)
#>  6 2020-01-28 07:50:00 Quarter-finals Raonic M. (Can)   Djokovic N. (Srb)
#>  7 2020-01-28 03:15:00 Quarter-finals Sandgren T. (Usa) Federer R. (Sui)
#>  8 2020-01-27 08:05:00 1/8-finals     Rublev A. (Rus)   Zverev A. (Ger)
#>  9 2020-01-27 07:15:00 1/8-finals     Nadal R. (Esp)    Kyrgios N. (Aus)
#> 10 2020-01-27 03:15:00 1/8-finals     Medvedev D. (Rus) Wawrinka S. (Sui)
#> # ... with 117 more rows


问:
Remove unnecessary NuGet references
I'm creating a simple desktop app in Visual Studio 2019 Community, specifically C# .NET Core. I'm using the Microsoft.Windows.Compatibility package to be able to use some functions from .NET Framework, specifically for displaying Tray Icon using Windows Forms.

It works, however, upon building, having to use that compatibility package floods the target forget with completely unrelated DLLs that definitely will not be used in the project; removing them manually from the build folder and launching the application works just like that.

I tried using Resharper to use its "Optimize references" option, however they come right back when VS is restarted, also it doesn't remove all of them.

How can I remove these redundant DLL references?

答:
This seems similar to what you're asking.

C# .net: How to modify a Nuget package's source code installed in my project?

Title: Remove unnecessary NuGet references


问:
Heroku worker suddenly crashes, logs don't show any of my scripts. What happened?
I have a flask, gunicorn, postgresql project hosted on heroku and it suddenly failed. I can access the logs, but there is no script that I wrote, so I am confused. I haven't added anything between "working" and "not working" so I don't know where I can start.

The log can be found in this pastebin.
The last part is:

```<code>2020-02-06T21:09:02.748093+00:00 app[web.1]: from werkzeug.contrib.cache import FileSystemCache
2020-02-06T21:09:02.748100+00:00 app[web.1]: ModuleNotFoundError: No module named 'werkzeug.contrib'
2020-02-06T21:09:02.748789+00:00 app[web.1]: [2020-02-06 21:09:02 +0000] [10] [INFO] Worker exiting (pid: 10)
</code>```

I tried to add werkzeug to the requirements.txt, but that did not help. Which would have been strange anyway, because it was working fine without the change in the requirement.

If you could help me reducing the requirements.txt, it would be greatly appreciated.

Original requirements.txt:

```<code>cs50
Flask
Flask-Session
requests
gunicorn
psycopg2-binary
openpyxl
</code>```

New, working ones:

```<code>astroid==2.3.3
attrs==19.3.0
Authlib==0.13
autopep8==1.5
awscli==1.17.9
backports.shutil-get-terminal-size==1.0.0
backports.shutil-which==3.5.2
beautifulsoup4==4.8.2
botocore==1.14.9
bs4==0.0.1
cairocffi==1.1.0
CairoSVG==2.4.2
certifi==2019.11.28
cffi==1.13.2
chardet==3.0.4
check50==3.0.10
Click==7.0
colorama==0.4.1
compare50==1.1.2
cryptography==2.8
cs50==5.0.3
cssselect2==0.2.2
cycler==0.10.0
defusedxml==0.6.0
docutils==0.15.2
EditorConfig==0.12.2
et-xmlfile==1.0.1
Flask==1.1.1
Flask-Session==0.3.1
help50==3.0.0
html5lib==1.0.1
icdiff==1.9.1
idna==2.8
ikp3db==1.4.1
intervaltree==2.1.0
isort==4.3.21
itsdangerous==1.1.0
jdcal==1.4.1
jellyfish==0.7.2
Jinja2==2.11.1
jmespath==0.9.4
jsbeautifier==1.10.3
kiwisolver==1.1.0
lazy-object-proxy==1.4.3
lib50==2.0.7
logger==1.4
MarkupSafe==1.1.1
matplotlib==3.1.3
mccabe==0.6.1
natsort==7.0.1
nltk==3.4.5
numpy==1.18.1
oauthlib==3.1.0
openpyxl==3.0.3
pandas==1.0.0
pexpect==4.8.0
Pillow==7.0.0
plotly==4.5.0
psycopg2-binary==2.8.4
ptyprocess==0.6.0
pyasn1==0.4.8
pycodestyle==2.5.0
pycparser==2.19
Pygments==2.5.2
pylint==2.4.4
pylint-django==2.0.13
pylint-flask==0.6
pylint-plugin-utils==0.6
pyparsing==2.4.6
PyPDF2==1.26.0
Pyphen==0.9.5
python-dateutil==2.8.1
python-magic==0.4.15
pytz==2019.3
PyYAML==5.2
render50==3.1.3
requests==2.22.0
requests-oauthlib==1.3.0
retrying==1.3.3
rsa==3.4.2
s3cmd==2.0.2
s3transfer==0.3.2
six==1.14.0
sortedcontainers==2.1.0
soupsieve==1.9.5
SQLAlchemy==1.3.13
sqlparse==0.3.0
style50==2.7.4
submit50==3.0.2
termcolor==1.1.0
tinycss2==1.0.2
tqdm==4.42.1
twython==3.7.0
typed-ast==1.4.1
urllib3==1.25.8
virtualenv==16.7.9
WeasyPrint==49
webencodings==0.5.1
Werkzeug==0.16.1
wrapt==1.11.2
gunicorn
</code>```

答:
Here's another solution that might work for you.

Since that Werkzeug 1.0.0 has removed deprecated code from werkzeug.contrib.

I ran into the same issue when trying to use Proxyfix in werkzeug==1.0.0

After downgrading to werkzeug==0.16.0, I got these warnings:

```<code>DeprecationWarning: 'werkzeug.contrib.fixers.ProxyFix' has moved to 'werkzeug.middleware.proxy_fix.ProxyFix'.
This import is deprecated as of version 0.15 and will be removed in 1.0.
DeprecationWarning: 'werkzeug.contrib.cache' is deprecated as of version 0.15 and will be removed in version 1.0. It has moved to pallets.
from werkzeug.contrib.cache import FileSystemCache
</code>```

To fix the issues:

```<code>pip install werkzeug==1.0.0
</code>```

For ProxyFix:

```<code>from werkzeug.middleware.proxy_fix import ProxyFix
</code>```

For FileSystemCache, you will have to install pallets:

```<code>pip install -U cachelib
from cachelib.file import FileSystemCache
</code>```

I hope this helps and fix your issues

Body:
I have a flask, gunicorn, postgresql project hosted on heroku and it suddenly failed. I can access the logs, but there is no script that I wrote, so I am confused. I haven't added anything between "working" and "not working" so I don't know where I can start.

The log can be found in this pastebin.
The last part is:

2020-02-06T21:09:02.748093+00:00 app[web.1]: from werkzeug.contrib.cache import FileSystemCache
2020-02-06T21:09:02.748100+00:00 app[web.1]: ModuleNotFoundError: No module named 'werkzeug.contrib'
2020-02-06T21:09:02.748789+00:00 app[web.1]: [2020-02-06 21:09:02 +0000] [10] [INFO] Worker exiting (pid: 10)

I tried to add werkzeug to the requirements.txt, but that did not help. Which would have been strange anyway, because it was working fine without the change in the requirement.

If you could help me reducing the requirements.txt, it would be greatly appreciated.

Original requirements.txt:

cs50
Flask
Flask-Session
requests
gunicorn
psycopg2-binary
openpyxl

New, working ones:

astroid==2.3.3
attrs==19.3.0
Authlib==0.13
autopep8==1.5
awscli==1.17.9
backports.shutil-get-terminal-size==1.0.0
backports.shutil-which==3.5.2
beautifulsoup4==4.8.2
botocore==1.14.9
bs4==0.0.1
cairocffi==1.1.0
CairoSVG==2.4.2
certifi==2019.11.28
cffi==1.13.2
chardet==3.0.4
check50==3.0.10
Click==7.0
colorama==0.4.1
compare50==1.1.2
cryptography==2.8
cs50==5.0.3
cssselect2==0.2.2
cycler==0.10.0
defusedxml==0.6.0
docutils==0.15.2
EditorConfig==0.12.2
et-xmlfile==1.0.1
Flask==1.1.1
Flask-Session==0.3.1
help50==3.0.0
html5lib==1.0.1
icdiff==1.9.1
idna==2.8
ikp3db==1.4.1
intervaltree==2.1.0
isort==4.3.21
itsdangerous==1.1.0
jdcal==1.4.1
jellyfish==0.7.2
Jinja2==2.11.1
jmespath==0.9.4
jsbeautifier==1.10.3
kiwisolver==1.1.0
lazy-object-proxy==1.4.3
lib50==2.0.7
logger==1.4
MarkupSafe==1.1.1
matplotlib==3.1.3
mccabe==0.6.1
natsort==7.0.1
nltk==3.4.5
numpy==1.18.1
oauthlib==3.1.0
openpyxl==3.0.3
pandas==1.0.0
pexpect==4.8.0
Pillow==7.0.0
plotly==4.5.0
psycopg2-binary==2.8.4
ptyprocess==0.6.0
pyasn1==0.4.8
pycodestyle==2.5.0
pycparser==2.19
Pygments==2.5.2
pylint==2.4.4
pylint-django==2.0.13
pylint-flask==0.6
pylint-plugin-utils==0.6
pyparsing==2.4.6
PyPDF2==1.26.0
Pyphen==0.9.5
python-dateutil==2.8.1
python-magic==0.4.15
pytz==2019.3
PyYAML==5.2
render50==3.1.3
requests==2.22.0
requests-oauthlib==1.3.0
retrying==1.3.3
rsa==3.4.2
s3cmd==2.0.2
s3transfer==0.3.2
six==1.14.0
sortedcontainers==2.1.0
soupsieve==1.9.5
SQLAlchemy==1.3.13
sqlparse==0.3.0
style50==2.7.4
submit50==3.0.2
termcolor==1.1.0
tinycss2==1.0.2
tqdm==4.42.1
twython==3.7.0
typed-ast==1.4.1
urllib3==1.25.8
virtualenv==16.7.9
WeasyPrint==49
webencodings==0.5.1
Werkzeug==0.16.1
wrapt==1.11.2
gunicorn

Body:
Here's another solution that might work for you.

Since that Werkzeug 1.0.0 has removed deprecated code from werkzeug.contrib.

I ran into the same issue when trying to use Proxyfix in werkzeug==1.0.0

After downgrading to werkzeug==0.16.0, I got these warnings:

DeprecationWarning: 'werkzeug.contrib.fixers.ProxyFix' has moved to 'werkzeug.middleware.proxy_fix.ProxyFix'.
This import is deprecated as of version 0.15 and will be removed in 1.0.
DeprecationWarning: 'werkzeug.contrib.cache' is deprecated as of version 0.15 and will be removed in version 1.0. It has moved to pallets.
from werkzeug.contrib.cache import FileSystemCache

To fix the issues:

pip install werkzeug==1.0.0

For ProxyFix:

from werkzeug.middleware.proxy_fix import ProxyFix

For FileSystemCache, you will have to install pallets:

pip install -U cachelib
from cachelib.file import FileSystemCache

I hope this helps and fix your issues


问:
Best algorithm to test if a linked list has a cycle
What's the best (halting) algorithm for determining if a linked list has a cycle in it?

[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.

[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".

答:
Precondition: Keep track of the list size (update the size whenenver a node is added or deleted).

Loop detection:

Keep a counter when traversing the list size.

If the counter exceeds the list size, there is a possible cycle.

Complexity: O(n)

Note: the comparison between the counter and the list size, as well as the update operation of the list size, must be made thread-safe.

OwnerDisplayName: cdleary

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: cdleary


问:
How to find the variance between two groups in python pandas?
I have a dataframe like this,

```<code>ID   total_sec   is_weekday
1      300           1
1      200           0
2      280           1
2      260           0
3      190           1
4      290           0
5      500           1
5      520           0
</code>```

I want to find the ID with the largest variance between weekdays and weekends. If we missed the records for either weekdays or weekends, we calculate the variance as 0.
My expected output will be,

```<code>ID   variance
1       100
2       20
3       0
4       0
5       20
</code>```

答:
You can do:

df.pivot(index="ID", columns="is_weekday", values="total_sec").diff(axis=1)[1].fillna(0)
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>ID
1    100.0
2     20.0
3      0.0
4      0.0
5    -20.0
Name: 1, dtype: float64
</code>```

Body:
I have a dataframe like this,

ID   total_sec   is_weekday
1      300           1
1      200           0
2      280           1
2      260           0
3      190           1
4      290           0
5      500           1
5      520           0

I want to find the ID with the largest variance between weekdays and weekends. If we missed the records for either weekdays or weekends, we calculate the variance as 0.
My expected output will be,

ID   variance
1       100
2       20
3       0
4       0
5       20

Body:
You can do:

df.pivot(index="ID", columns="is_weekday", values="total_sec").diff(axis=1)[1].fillna(0)

Outputs:

ID
1    100.0
2     20.0
3      0.0
4      0.0
5    -20.0
Name: 1, dtype: float64


问:
Create project-level permissions at project initialization
When I first run manage.py migrate on a Django project, I would like the database to be initialized with some extra permissions. I have seen here that this can be done at the app level, in the apps.py files.  However the permissions I would like to have are rather related to the whole project than to one of its apps.

My questions are:

Is it OK to define project-level permissions, or are permissions meant to always be part on an app?

If project-level permissions are fine, what would be the appropriate place to define them so that they are created at project initialization?

答:
To create a permission you need a ContentType and they live in the apps, so you can't create "project-level" permissions. The permissions must to be created in some app (everything is an app) and after install the app in your project you will be able to reference to the permission in the whole project.

As the permission is related to a ContentType (a model) you can create the permission inside you models like this:

```<code>class SomeModelClass(models.Model):
    # ...
    class Meta:
        permissions = (
            ("can_drive", "Can drive"),
            ("can_vote", "Can vote in elections"),
            ("can_drink", "Can drink alcohol"),
</code>```

Note: all the models have 4 default permissions

The other way to create you permission can be programatically somewhere, maybe a signal, a custom migration... take a look here

Body:
To create a permission you need a ContentType and they live in the apps, so you can't create "project-level" permissions. The permissions must to be created in some app (everything is an app) and after install the app in your project you will be able to reference to the permission in the whole project.

As the permission is related to a ContentType (a model) you can create the permission inside you models like this:

class SomeModelClass(models.Model):
    # ...
    class Meta:
        permissions = (
            ("can_drive", "Can drive"),
            ("can_vote", "Can vote in elections"),
            ("can_drink", "Can drink alcohol"),

Note: all the models have 4 default permissions

The other way to create you permission can be programatically somewhere, maybe a signal, a custom migration... take a look here


问:
Select SQL Server DatetimeOffset as .Net DateTimeOffset.Ticks
I send a SQL query and receive FOR JSON .

```<code>SqlCommand comm = new SqlCommand(@"select top (1000) Date,[open],high,low,[close] from dbo.[foo"] where date > @backDate and date <= @Date  order by date FOR JSON AUTO", conn);

comm.Parameters.AddWithValue("@Date", _definition.dateFrom);
comm.Parameters.AddWithValue("@backDate", lowLimit);

string json = (string)comm.ExecuteScalar();

Debug.WriteLine(json);

/* this causes invalid deserialization */
CudaEngine.OHLC[] stream = JsonConvert.DeserializeObject<CudaEngine.OHLC[]>(json);
</code>```

So the DateTimeOffset in json result looks like this:

[{"Date":"2019-07-30T00:29:00Z","open":1.241829000000000e+004,"high":1.245195000000000e+004,

My ohcl struct have to be like this with date as long.

```<code>public struct OHLC
{
    public long UTCdate;
    public double open;
    public double High;
    public double Low;
    public double Close;
}
</code>```

How can I cast date directly from SQL statement to receive a .Net long either ticks   or millisecond? How can I deserialize without the invalidCastException?

答:
This is simple to convert in the SQL query.  The only tricky part (as always) is dealing with time zones.

If the SQL Server data type is datetimeoffset then you need to translate it to UTC time, then convert it to a datetime2, like this:

```<code>cast( [Date] at time zone 'UTC' as datetime2 )
</code>```

If the SQL Server data type is a datetime or datetime2 and already represents UTC time then you don't need this conversion.  And if they are datetime or datetime2 stored in some local time zone, you need to convert to a datetimeoffset in with the appropriate time zone, then translate to UTC as above.  EG

```<code>cast( [Date] at time zone 'Central Standard Time' at time zone 'UTC' as datetime2 )
</code>```

So assuming the SQL column is a datetimeoffset and you are converting to Unix Epoch Time, the query would look like:

```<code>var sql = @"
select top (1000)
  datediff(second, '19700101', cast( [Date] at time zone 'UTC' as datetime2 ) ) Date,
  [open],
  high,
  low,
  [close]
  from dbo.[foo"]
  where date > @backDate
  and date <= @Date
  order by date
  FOR JSON AUTO";

SqlCommand comm = new SqlCommand(sql, conn);
</code>```

Body:
I send a SQL query and receive FOR JSON .

SqlCommand comm = new SqlCommand(@"select top (1000) Date,[open],high,low,[close] from dbo.[foo"] where date > @backDate and date <= @Date  order by date FOR JSON AUTO", conn);

comm.Parameters.AddWithValue("@Date", _definition.dateFrom);
comm.Parameters.AddWithValue("@backDate", lowLimit);

string json = (string)comm.ExecuteScalar();

Debug.WriteLine(json);

/* this causes invalid deserialization */
CudaEngine.OHLC[] stream = JsonConvert.DeserializeObject<CudaEngine.OHLC[]>(json);

So the DateTimeOffset in json result looks like this:

[{"Date":"2019-07-30T00:29:00Z","open":1.241829000000000e+004,"high":1.245195000000000e+004,

My ohcl struct have to be like this with date as long.

public struct OHLC
{
    public long UTCdate;
    public double open;
    public double High;
    public double Low;
    public double Close;
}

How can I cast date directly from SQL statement to receive a .Net long either ticks   or millisecond? How can I deserialize without the invalidCastException?

Body:
This is simple to convert in the SQL query.  The only tricky part (as always) is dealing with time zones.

If the SQL Server data type is datetimeoffset then you need to translate it to UTC time, then convert it to a datetime2, like this:

cast( [Date] at time zone 'UTC' as datetime2 )

If the SQL Server data type is a datetime or datetime2 and already represents UTC time then you don't need this conversion.  And if they are datetime or datetime2 stored in some local time zone, you need to convert to a datetimeoffset in with the appropriate time zone, then translate to UTC as above.  EG

cast( [Date] at time zone 'Central Standard Time' at time zone 'UTC' as datetime2 )

So assuming the SQL column is a datetimeoffset and you are converting to Unix Epoch Time, the query would look like:

var sql = @"
select top (1000)
  datediff(second, '19700101', cast( [Date] at time zone 'UTC' as datetime2 ) ) Date,
  [open],
  high,
  low,
  [close]
  from dbo.[foo"]
  where date > @backDate
  and date <= @Date
  order by date
  FOR JSON AUTO";

SqlCommand comm = new SqlCommand(sql, conn);


问:
How does one filter json after type?
So, I have a json which looks a little bit like this:

```<code>{
  "data": {
    "user": {
      "edge_followed_by": {
        "count": 22,
        "page_info": {
          "has_next_page": true,
          "end_cursor": "Base64"
        },
        "edges": [
          {
            "node": {
              "id": "id",
              "username": "Username",
              "full_name": "played",
              "profile_pic_url": "URL"
            }
          }
        ]
      }
    }
  }
}
</code>```

And I want to filter out the username. How do I do that?

答:
This can be a little tricky to understand from the question first of all.

My interpretation of this is you want to extract a username

"Filtering" also could mean you want to remove something from a collection that passes a condition (or test) of some kind.

For example: Removing all even numbers from an array

```<code>let x = [1, 2, 4, 5, 6];
let filtered = x.filter(value => value % 2 === 0);
</code>```

Now, I've looked at your json, and I think the best point of targeting this is by getting the "edges" property and running it through an inbuilt function like map; that could be used to get usernames. The edges is an array as well.

data.user.edge_followed_by.edges.map(userObject => userObject.username)

That would effectively remove all usernames from the edges if your tech stack of choice was javascript.

I got this info from a post like: https://coderin90.com/blog/2019/map-js

Title: How does one filter json after type?

Body:
So, I have a json which looks a little bit like this:

{
  "data": {
    "user": {
      "edge_followed_by": {
        "count": 22,
        "page_info": {
          "has_next_page": true,
          "end_cursor": "Base64"
        },
        "edges": [
          {
            "node": {
              "id": "id",
              "username": "Username",
              "full_name": "played",
              "profile_pic_url": "URL"
            }
          }
        ]
      }
    }
  }
}

And I want to filter out the username. How do I do that?

Body:
This can be a little tricky to understand from the question first of all.

My interpretation of this is you want to extract a username

"Filtering" also could mean you want to remove something from a collection that passes a condition (or test) of some kind.

For example: Removing all even numbers from an array

let x = [1, 2, 4, 5, 6];
let filtered = x.filter(value => value % 2 === 0);

Now, I've looked at your json, and I think the best point of targeting this is by getting the "edges" property and running it through an inbuilt function like map; that could be used to get usernames. The edges is an array as well.

data.user.edge_followed_by.edges.map(userObject => userObject.username)

That would effectively remove all usernames from the edges if your tech stack of choice was javascript.

I got this info from a post like: https://coderin90.com/blog/2019/map-js


问:
I need to access a Tuple in Python
I was using get request to get some data by this code

```<code>at = airtable.Airtable('BASE_ID', 'API_KEY')
airtable_data = at.get('Table 3')
print(airtable_data)
</code>```

and the results was

```<code>OrderedDict([('records', [OrderedDict([('id', 'rec3qP7SjyowO'), ('fields',OrderedDict([('User', 'User'), ('Text', 'TEST'), ('Date', '2020-01-15T13:09:03.000Z')])), ('createdTime', '2020-01-15T13:09:09.000Z')]), OrderedDict([('id', 'recOUVoNXHak'), ('fields', OrderedDict([('User', 'user'), ('Text', 'TEST'), ('Date', '2020-01-15T13:05:43.000Z')])), ('createdTime', '2020-01-15T13:08:55.000Z')])])])
</code>```

then I used

```<code>airtable_list = (list(airtable_data))
print(airtable_list[0])
</code>```

the results was
records
only and I can't find a way to extract the rest of the data

答:
The issue is that when you pass that OrderdDict through List, it gives you value of key which is records.

To display the proper data, you can use below logic.

```<code>from collections import OrderedDict
airtable_data = OrderedDict([('records', [OrderedDict([('id', 'rec3qP7SjyowO'), ('fields',OrderedDict([('User', 'User'), ('Text', 'TEST'), ('Date', '2020-01-15T13:09:03.000Z')])), ('createdTime', '2020-01-15T13:09:09.000Z')]), OrderedDict([('id', 'recOUVoNXHak'), ('fields', OrderedDict([('User', 'user'), ('Text', 'TEST'), ('Date', '2020-01-15T13:05:43.000Z')])), ('createdTime', '2020-01-15T13:08:55.000Z')])])])

for k,v in airtable_data.items():
    i = 0
    for data in v:
        i += 1
        for k1, v1 in data.items():
            print(k1,'---->', v1)
        print('Data displayed for item number ', i)
        print('----------------------------------------------------')
        print(' ')
</code>```

Title: I need to access a Tuple in Python

Body:
I was using get request to get some data by this code

at = airtable.Airtable('BASE_ID', 'API_KEY')
airtable_data = at.get('Table 3')
print(airtable_data)

and the results was

OrderedDict([('records', [OrderedDict([('id', 'rec3qP7SjyowO'), ('fields',OrderedDict([('User', 'User'), ('Text', 'TEST'), ('Date', '2020-01-15T13:09:03.000Z')])), ('createdTime', '2020-01-15T13:09:09.000Z')]), OrderedDict([('id', 'recOUVoNXHak'), ('fields', OrderedDict([('User', 'user'), ('Text', 'TEST'), ('Date', '2020-01-15T13:05:43.000Z')])), ('createdTime', '2020-01-15T13:08:55.000Z')])])])

then I used

airtable_list = (list(airtable_data))
print(airtable_list[0])

the results was
records
only and I can't find a way to extract the rest of the data

Body:
The issue is that when you pass that OrderdDict through List, it gives you value of key which is records.

To display the proper data, you can use below logic.

from collections import OrderedDict
airtable_data = OrderedDict([('records', [OrderedDict([('id', 'rec3qP7SjyowO'), ('fields',OrderedDict([('User', 'User'), ('Text', 'TEST'), ('Date', '2020-01-15T13:09:03.000Z')])), ('createdTime', '2020-01-15T13:09:09.000Z')]), OrderedDict([('id', 'recOUVoNXHak'), ('fields', OrderedDict([('User', 'user'), ('Text', 'TEST'), ('Date', '2020-01-15T13:05:43.000Z')])), ('createdTime', '2020-01-15T13:08:55.000Z')])])])

for k,v in airtable_data.items():
    i = 0
    for data in v:
        i += 1
        for k1, v1 in data.items():
            print(k1,'---->', v1)
        print('Data displayed for item number ', i)
        print('----------------------------------------------------')
        print(' ')


答:
You could retrieve it with a map function there

const dataSample = {
  "data": {
    "user": {
      "edge_followed_by": {
        "count": 22,
        "page_info": {
          "has_next_page": true,
          "end_cursor": "Base64"
        },
        "edges": [
          {
            "node": {
              "id": "id",
              "username": "Username",
              "full_name": "played",
              "profile_pic_url": "URL"
            }
          }
        ]
      }
    }
  }
}

const getUsernames = data => {
  return data.data.user.edge_followed_by.edges.map(e => e.node.username)
}

console.log(getUsernames(dataSample))```

:)

Title: How does one filter json after type?

Body:
You could retrieve it with a map function there

const dataSample = {
  "data": {
    "user": {
      "edge_followed_by": {
        "count": 22,
        "page_info": {
          "has_next_page": true,
          "end_cursor": "Base64"
        },
        "edges": [
          {
            "node": {
              "id": "id",
              "username": "Username",
              "full_name": "played",
              "profile_pic_url": "URL"
            }
          }
        ]
      }
    }
  }
}

const getUsernames = data => {
  return data.data.user.edge_followed_by.edges.map(e => e.node.username)
}

console.log(getUsernames(dataSample))

:)


问:
Can GoogleCloudVision API for PDF OCR output to PubSub?
I am using the following code to request an OCR operation on the Google cloud vision API:

```<code>    from google.cloud import vision
    from google.cloud import storage
    from google.protobuf import json_format
    # Supported mime_types are: 'application/pdf' and 'image/tiff'
    mime_type = 'application/pdf'

    # How many pages should be grouped into each json output file.
    batch_size = 2

    client = vision.ImageAnnotatorClient()

    feature = vision.types.Feature(
        type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)

    gcs_source = vision.types.GcsSource(uri=gcs_source_uri)
    input_config = vision.types.InputConfig(
        gcs_source=gcs_source, mime_type=mime_type)

    gcs_destination = vision.types.GcsDestination(uri=gcs_destination_uri)
    output_config = vision.types.OutputConfig(
        gcs_destination=gcs_destination, batch_size=batch_size)

    async_request = vision.types.AsyncAnnotateFileRequest(
        features=[feature], input_config=input_config,
        output_config=output_config)

    operation = client.async_batch_annotate_files(
        requests=[async_request])
</code>```

When I call the AsyncAnnotateFileRequest operation I am passing a GcsDestination OutputConfig object. With this object I am telling the API to write the result to a GoogleCloudStorage bucket. I wonder if it is possible to write to PubSub instead? I looked around the documentation but it looks like it is not possible, as last resort thought to ask here. Maybe I am missing something?

EDIT:
I am exploring synchronous requests, where I can request the OCR, receive the text as response and then write to PubSub. Like this:

```<code>request = vision.types.AnnotateFileReques(features=[feature], input_config=input_config)

response = vision_client.batch_annotate_files(requests=[request])
</code>```

but I am getting
AttributeError: module 'google.cloud.vision_v1.types' has no attribute 'AnnotateFileReques' but from the doc it should be there.
Suggestions?

答:
The async annotate method writes final results to GCS. You can set up a GCS trigger to process the results when written to your GCS bucket.

See storage triggers: https://cloud.google.com/functions/docs/calling/storage

Body:
I am using the following code to request an OCR operation on the Google cloud vision API:

    from google.cloud import vision
    from google.cloud import storage
    from google.protobuf import json_format
    # Supported mime_types are: 'application/pdf' and 'image/tiff'
    mime_type = 'application/pdf'

    # How many pages should be grouped into each json output file.
    batch_size = 2

    client = vision.ImageAnnotatorClient()

    feature = vision.types.Feature(
        type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION)

    gcs_source = vision.types.GcsSource(uri=gcs_source_uri)
    input_config = vision.types.InputConfig(
        gcs_source=gcs_source, mime_type=mime_type)

    gcs_destination = vision.types.GcsDestination(uri=gcs_destination_uri)
    output_config = vision.types.OutputConfig(
        gcs_destination=gcs_destination, batch_size=batch_size)

    async_request = vision.types.AsyncAnnotateFileRequest(
        features=[feature], input_config=input_config,
        output_config=output_config)

    operation = client.async_batch_annotate_files(
        requests=[async_request])

When I call the AsyncAnnotateFileRequest operation I am passing a GcsDestination OutputConfig object. With this object I am telling the API to write the result to a GoogleCloudStorage bucket. I wonder if it is possible to write to PubSub instead? I looked around the documentation but it looks like it is not possible, as last resort thought to ask here. Maybe I am missing something?

EDIT:
I am exploring synchronous requests, where I can request the OCR, receive the text as response and then write to PubSub. Like this:

request = vision.types.AnnotateFileReques(features=[feature], input_config=input_config)

response = vision_client.batch_annotate_files(requests=[request])

but I am getting
AttributeError: module 'google.cloud.vision_v1.types' has no attribute 'AnnotateFileReques' but from the doc it should be there.
Suggestions?


问:
file renaming/deleting
I have a few files like this-

*.sss and  *_passive.sss

If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.

I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.

Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.

```<code>import os, fnmatch

def locate(pattern, root=os.curdir):

    #ignore directories- uncomment to make ignore work
    #ignored = ["0201", "0306"]
  for path, dirs, files in os.walk(os.path.abspath(root)):
         #for dir in ignored:                  # if dir in dirs:                        #dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
       yield os.path.join(path, filename)

for filename in locate("*_passive.sss"):
               #found the files that i want to rename, but os.rename() refuses to overwrite !!
    newfilename=filename.rstrip("_passive.sss") + ".sss"
    os.rename(filename,newfilename)
</code>```

答:
Here's a python solution:</p>

```<code>import os
from glob import glob

# Write out test files.
with open('foo.sss', 'w'):  pass
with open('foo_passive.sss', 'w'):  pass
with open('bar.sss', 'w'):  pass

# Rename files.
files = glob('*.sss')
for filename in files:
  if filename.endswith('_passive.sss'):  continue
  passive_fname = filename.split('.sss')[0] + '_passive.sss'
  if passive_fname in files:
    os.remove(filename)
    os.rename(passive_fname, filename)
  else:
    print 'no passive: ', filename
</code>```

Title: file renaming/deleting

Body:
I have a few files like this-

*.sss and  *_passive.sss

If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.

I was able to locate all the *_passive.sss files but I would like to know the awk/sed etc command that could rename the *_passive.sss to *.sss.

Edit: Right now i have this but os.rename does not overwrite files, i need it to overwrite though.

import os, fnmatch

def locate(pattern, root=os.curdir):

    #ignore directories- uncomment to make ignore work
    #ignored = ["0201", "0306"]
  for path, dirs, files in os.walk(os.path.abspath(root)):
         #for dir in ignored:                  # if dir in dirs:                        #dirs.remove(dir)
    for filename in fnmatch.filter(files, pattern):
       yield os.path.join(path, filename)

for filename in locate("*_passive.sss"):
               #found the files that i want to rename, but os.rename() refuses to overwrite !!
    newfilename=filename.rstrip("_passive.sss") + ".sss"
    os.rename(filename,newfilename)

Body:
Here's a python solution:

import os
from glob import glob

# Write out test files.
with open('foo.sss', 'w'):  pass
with open('foo_passive.sss', 'w'):  pass
with open('bar.sss', 'w'):  pass

# Rename files.
files = glob('*.sss')
for filename in files:
  if filename.endswith('_passive.sss'):  continue
  passive_fname = filename.split('.sss')[0] + '_passive.sss'
  if passive_fname in files:
    os.remove(filename)
    os.rename(passive_fname, filename)
  else:
    print 'no passive: ', filename