问:
iPhone - NSTimer not repeating after fire
I am creating and firing a NSTimer with:

```<code>ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                           target:self
                                         selector:@selector(handleTimer:)
                                         userInfo:nil
                                          repeats:YES];
[ncTimer fire];
</code>```

AND

```<code>- (void)handleTimer:(NSTimer *)chkTimer {
    // do stuff
}
</code>```

I am retaining my timer with:

```<code>@property (nonatomic, retain) NSTimer *ncTimer;
</code>```

For some reason the timer is not repeating. It is firing once only and than never again.

答:
You could write the same thing in Swift without running in main loops by:

```<code>ncTimer = Timer.scheduledTimer(timeInterval: 1.0,
                               target: self,
                               selector: #selector(self.handleTimer),
                               userInfo: nil,
                               repeats: true)
ncTimer.fire()
</code>```

Body:
I am creating and firing a NSTimer with:

ncTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                           target:self
                                         selector:@selector(handleTimer:)
                                         userInfo:nil
                                          repeats:YES];
[ncTimer fire];

AND

- (void)handleTimer:(NSTimer *)chkTimer {
    // do stuff
}

I am retaining my timer with:

@property (nonatomic, retain) NSTimer *ncTimer;

For some reason the timer is not repeating. It is firing once only and than never again.

Body:
You could write the same thing in Swift without running in main loops by:

ncTimer = Timer.scheduledTimer(timeInterval: 1.0,
                               target: self,
                               selector: #selector(self.handleTimer),
                               userInfo: nil,
                               repeats: true)
ncTimer.fire()


来源: stackexchange

问:
Codeigniter: unable to upload image (You did not select a file to upload)
When I try to upload a image to my uploads folder i get the following error:

Array ( [error] =>
  You did not select a file to upload.)

My View:

```<code><form action="<?=base_url('create_public_profile_job') ?>" class="create-profile-form" method="POST">
     <input type="file" name="userfile" size="20000" />
     <button type="submit" class="create-profile-button">Submit</button>
</form>
</code>```

My Controller

```<code>public function create_public_profile_job()
{
    if(isset($_POST['userfile']))
    {
            $this->User_model->do_upload($_POST['userfile']);
    }
}
</code>```

My Model

```<code>public function do_upload($userfile)
{
    $this->load->helper('form');
    $this->load->helper('url');

    $config['upload_path']          = 'assets/uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 1000000;
    $config['max_width']            = 10240000;
    $config['max_height']           = 7680000;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload($userfile))
    {
            $error = array('error' => $this->upload->display_errors());
            print_r($userfile);
            print_r($error);
    }
    else
    {
            $data = array('upload_data' => $this->upload->data());

            print_r($data);
    }
}
</code>```

The Model part is from the Codeigniter userguide https://codeigniter.com/userguide3/libraries/file_uploading.html

Don't really know where the issue is, because I pass the image through all functions

答: You have to add the  enctype="multipart/form-data" in the form tag to upload the data through the forms.

ContentLicense: CC BY-SA 4.0

Body:
When I try to upload a image to my uploads folder i get the following error:

Array ( [error] =>
  You did not select a file to upload.)

My View:

<form action="<?=base_url('create_public_profile_job') ?>" class="create-profile-form" method="POST">
     <input type="file" name="userfile" size="20000" />
     <button type="submit" class="create-profile-button">Submit</button>
</form>

My Controller

public function create_public_profile_job()
{
    if(isset($_POST['userfile']))
    {
            $this->User_model->do_upload($_POST['userfile']);
    }
}

My Model

public function do_upload($userfile)
{
    $this->load->helper('form');
    $this->load->helper('url');

    $config['upload_path']          = 'assets/uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 1000000;
    $config['max_width']            = 10240000;
    $config['max_height']           = 7680000;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload($userfile))
    {
            $error = array('error' => $this->upload->display_errors());
            print_r($userfile);
            print_r($error);
    }
    else
    {
            $data = array('upload_data' => $this->upload->data());

            print_r($data);
    }
}

The Model part is from the Codeigniter userguide https://codeigniter.com/userguide3/libraries/file_uploading.html

Don't really know where the issue is, because I pass the image through all functions


问:
How does the try catch finally block work?
In C#, how does a try catch finally block work?

So if there is an exception, I know that it will jump to the catch block and then jump to the finally block.

But what if there is no error, the catch block wont get run, but does the finally block get run then?

答:
Yes, Finally will always execute.

Even if there is no catch block after try, finally block will still execute.

Basically finally can be used to release resources such as a file streams, database connections and graphics handlers without waiting for the garbage collector in the runtime to finalize the object.

```<code>       try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            Console.WriteLine("Finally block is executed");
        }
        Console.WriteLine("Some more code here");
</code>```

Output:

System.DivideByZeroException: Attempted to divide by zero.

Finally block is executed

Rest of the code

Source : Exception handling in C# (With try-catch-finally block details)

ContentLicense: CC BY-SA 3.0

Body:
Yes, Finally will always execute.

Even if there is no catch block after try, finally block will still execute.

Basically finally can be used to release resources such as a file streams, database connections and graphics handlers without waiting for the garbage collector in the runtime to finalize the object.

       try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            Console.WriteLine("Finally block is executed");
        }
        Console.WriteLine("Some more code here");

Output:

System.DivideByZeroException: Attempted to divide by zero.

Finally block is executed

Rest of the code

Source : Exception handling in C# (With try-catch-finally block details)


问:
GET request returning 404 not found
I have a spring boot application where I am just sending a GET request to fetch some data from a pre populated list.
The list exists inside the controller class. When I am hitting the URL, I am constantly getting 404 error.

Student.java

```<code>package com.SpringBootDemo.entities;

public class Student {

    private Integer studentId;
    private String studentName;

    public Student(Integer studentId, String studentName) {
        super();
        this.studentId = studentId;
        this.studentName = studentName;
    }
    public Integer getStudentId() {
        return studentId;
    }
    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

}

</code>```

StudentController.java

```<code>package com.SpringBootDemo.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.SpringBootDemo.entities.Student;

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
            new Student(1,"ABC"),
            new Student(2,"DEF"),
            new Student(3,"HIJ"));

    @GetMapping(path = "{studentId}")
    public Student getStudentById(@PathVariable("studentId")Integer studentId)
    {
        System.out.println("inside the controller");
        return STUDENTS.stream()
                .filter(student -> studentId.equals(student.getStudentId()))
                .findFirst()
                .orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));

    }

}

</code>```

Application.properties

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/spring_project
spring.datasource.username=root
spring.datasource.password=Pblock@20
server.port = 8081
spring.jpa.show-sql=true
</code>```

My stacktrace

```<code>020-06-01 15:07:29.879  INFO 21012 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-06-01 15:07:30.275  INFO 21012 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-06-01 15:07:30.281  INFO 21012 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-01 15:07:30.281  INFO 21012 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
</code>```

答:
When I added @ComponentScan(basePackageClasses=StudentController.class) to my base class, it worked.

SpringSecurityDemoApplication

```<code>package com.SpringSecurityDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

import com.SpringBootDemo.controller.StudentController;

@SpringBootApplication
@ComponentScan(basePackageClasses=StudentController.class)
public class SpringSecurityDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityDemoApplication.class, args);
    }

}

</code>```

Title: GET request returning 404 not found

Body:
I have a spring boot application where I am just sending a GET request to fetch some data from a pre populated list.
The list exists inside the controller class. When I am hitting the URL, I am constantly getting 404 error.

Student.java

package com.SpringBootDemo.entities;

public class Student {

    private Integer studentId;
    private String studentName;

    public Student(Integer studentId, String studentName) {
        super();
        this.studentId = studentId;
        this.studentName = studentName;
    }
    public Integer getStudentId() {
        return studentId;
    }
    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

}

StudentController.java

package com.SpringBootDemo.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.SpringBootDemo.entities.Student;

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
            new Student(1,"ABC"),
            new Student(2,"DEF"),
            new Student(3,"HIJ"));

    @GetMapping(path = "{studentId}")
    public Student getStudentById(@PathVariable("studentId")Integer studentId)
    {
        System.out.println("inside the controller");
        return STUDENTS.stream()
                .filter(student -> studentId.equals(student.getStudentId()))
                .findFirst()
                .orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));

    }

}

Application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/spring_project
spring.datasource.username=root
spring.datasource.password=Pblock@20
server.port = 8081
spring.jpa.show-sql=true

My stacktrace

020-06-01 15:07:29.879  INFO 21012 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-06-01 15:07:30.275  INFO 21012 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-06-01 15:07:30.281  INFO 21012 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-01 15:07:30.281  INFO 21012 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]

Body:
When I added @ComponentScan(basePackageClasses=StudentController.class) to my base class, it worked.

SpringSecurityDemoApplication

package com.SpringSecurityDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

import com.SpringBootDemo.controller.StudentController;

@SpringBootApplication
@ComponentScan(basePackageClasses=StudentController.class)
public class SpringSecurityDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityDemoApplication.class, args);
    }

}


问:
How can I calculate the number of weights and bias values in a single CNN layer?
Given the following image, how can I calculate the number of parameters:

CNN Layer

This particular layer consists of 4x4 convolutions and 64 feature maps; how can I complete a calculation that satisfies my initial question?

Update - Full Architecture

答:
Filter size is contains N * kernel_size * kernel_size weight parameters and one for each channel so

N * kernel_size * kernel_size* n_channels then N bais parmaters so the final cacluation for this layer is  n_params = N * kernel_size * kernel_size* n_channels + N

N : number of features

kernel_size : is conv2d shape (height and width)

n_channels : is the number of channels

n_params : is the total number of your parameters

Ex

n_params = 64 * (4 * 4) * 3 + 64 = 3136


问:
How to position cursor in input field after icon
I have an input field that has a search icon positioned inside of it using the background property and every time I type in it the cursor sticks in the beginning like shown in the picture:

https://imgur.com/ocJRux8

How can I position the cursor after the search icon? I tried setting the padding-left and the text-indent but that also moves the placeholder which is not desirable.

Here is my input field:

```<code>import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import { Link } from 'react-router-dom';

import axios from "axios";

class Search extends Component {

    state = {
        searchResults: [],
        isLoading: false
    }

    getSearchQuery = (event) => {
        const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;

        const queryString = document.querySelector(
            ".search-input"
        ).value;
        if (event.keyCode === 13) {
            this.setState({ ...this.state, isLoading: true });
            axios.post(SEARCH_RESULTS_ENDPOINT, {
                queryString: queryString,

            }).then(response => {
                this.setState({ ...this.state, searchResults: response.data });
                this.setState({ ...this.state, isLoading: false });
            });
        }
    };

    render() {
        if (this.state.isLoading) {
            return <Spinner />
        }
        return (

            <div>
                <input
                    type="text"
                    placeholder="Search"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}

                />
                <div>
                    {this.state.searchResults.map(result => (
                        <div key={result._id} >
                            <img src={result.picture} alt="avatar" />
                            <div >
                                <div>
                                    <h2>{result.title}</h2>
                                    <p>{result.date}</p>
                                    <p>{result.postContent}</p>
                                    <Link to={`/post/${result._id}`} className="read-more-btn">
                                        <button className="read-more-btn">Read more</button>
                                    </Link>
                                </div>
                            </div>
                        </div>
                    ))}

                </div>
            </div>
        );
    }
}

export default Search;
</code>```

and here is my CSS:

```<code>.search-input {
    background: url(../../assets/images/search-icon.png) no-repeat scroll 12px 12px;
    background-size: 20px 20px;
    margin: auto;
    display: block;
    width: 500px;
    margin-top: 30px;
    height: 40px;
    border: solid 1px #AAAAAA;
    // text-indent: 30px;
}

.search-icon {
  height: 20px;
  width: 20px;
}

.no-results-found {
 text-align: center;
 margin-top: 50px;
}

.search-input::-webkit-input-placeholder { /* Chrome/Opera/Safari */
    padding-left:35px;
}

input:focus{
  outline: none;
}

  ::-moz-placeholder { /* Firefox 19+ */
    padding-left:20px;
}
  :-ms-input-placeholder { /* IE 10+ */
    padding-left:20px;
}
  :-moz-placeholder { /* Firefox 18- */
    padding-left:20px;
}
</code>```

答:
Here's how I would do it.

Example with 2 variants

const { useState, useEffect } = React;

const App = () => {

return

    <input className="input" type="Text" placeholder="Search"/>

    <input className="input1" type="Text" placeholder="Search"/>

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  border: 1px solid black;
  width: 300px;
}

.input {
  padding: .5rem .5rem .5rem 2rem;
  border: none;
}

.input:focus {
  outline: none;
}

.icon {
  position: absolute;
  margin-top: .5rem;
  margin-left: .5rem;
}

.container1 {
  margin-top: 1rem;
  border: 1px solid black;
  width: 300px;
  display: flex;
}

.icon1 {
  padding: .5rem 0 .5rem .5rem;
}

.input1 {
  flex: 1 1 auto;
  padding: .5rem;
  border: none;
}

.input1:focus {
  outline: none;
}</code>```

```

Body:
I have an input field that has a search icon positioned inside of it using the background property and every time I type in it the cursor sticks in the beginning like shown in the picture:

https://imgur.com/ocJRux8

How can I position the cursor after the search icon? I tried setting the padding-left and the text-indent but that also moves the placeholder which is not desirable.

Here is my input field:

import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import { Link } from 'react-router-dom';

import axios from "axios";

class Search extends Component {

    state = {
        searchResults: [],
        isLoading: false
    }

    getSearchQuery = (event) => {
        const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;

        const queryString = document.querySelector(
            ".search-input"
        ).value;
        if (event.keyCode === 13) {
            this.setState({ ...this.state, isLoading: true });
            axios.post(SEARCH_RESULTS_ENDPOINT, {
                queryString: queryString,

            }).then(response => {
                this.setState({ ...this.state, searchResults: response.data });
                this.setState({ ...this.state, isLoading: false });
            });
        }
    };

    render() {
        if (this.state.isLoading) {
            return <Spinner />
        }
        return (

                <input
                    type="text"
                    placeholder="Search"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}

                />

                    {this.state.searchResults.map(result => (

{result.title}

{result.date}

{result.postContent}

                                    <Link to={`/post/${result._id}`} className="read-more-btn">
                                        <button className="read-more-btn">Read more</button>
                                    </Link>

                    ))}

        );
    }
}

export default Search;

and here is my CSS:

.search-input {
    background: url(../../assets/images/search-icon.png) no-repeat scroll 12px 12px;
    background-size: 20px 20px;
    margin: auto;
    display: block;
    width: 500px;
    margin-top: 30px;
    height: 40px;
    border: solid 1px #AAAAAA;
    // text-indent: 30px;
}

.search-icon {
  height: 20px;
  width: 20px;
}

.no-results-found {
 text-align: center;
 margin-top: 50px;
}

.search-input::-webkit-input-placeholder { /* Chrome/Opera/Safari */
    padding-left:35px;
}

input:focus{
  outline: none;
}

  ::-moz-placeholder { /* Firefox 19+ */
    padding-left:20px;
}
  :-ms-input-placeholder { /* IE 10+ */
    padding-left:20px;
}
  :-moz-placeholder { /* Firefox 18- */
    padding-left:20px;
}

Body:
Here's how I would do it.

Example with 2 variants

const { useState, useEffect } = React;

const App = () => {

return <div>
  <div className="container">
    <span className="icon">
      <i className="fas fa-search"></i>
    </span>
    <input className="input" type="Text" placeholder="Search"/>
  </div>
  <div className="container1">
    <span className="icon1">
      <i className="fas fa-search"></i>
    </span>
    <input className="input1" type="Text" placeholder="Search"/>
  </div>
</div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

.container {
  border: 1px solid black;
  width: 300px;
}

.input {
  padding: .5rem .5rem .5rem 2rem;
  border: none;
}

.input:focus {
  outline: none;
}

.icon {
  position: absolute;
  margin-top: .5rem;
  margin-left: .5rem;
}

.container1 {
  margin-top: 1rem;
  border: 1px solid black;
  width: 300px;
  display: flex;
}

.icon1 {
  padding: .5rem 0 .5rem .5rem;
}

.input1 {
  flex: 1 1 auto;
  padding: .5rem;
  border: none;
}

.input1:focus {
  outline: none;
}

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js"></script>
<div id="root"></div>


问:
How get products from product table based on the category search in django restframework, How do inner join in django restframework
I am very much new in django restframework,I tried to create a search api.

I have 2 models designed

```<code>class Category(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    product_Comments = models.CharField(max_length=255)
    size = models.CharField(max_length=10, null=True)
    product_Status = models.BooleanField(default=True)
    category = models.ForeignKey(Category,  on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.product_Description
</code>```

I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it.

My Views.py

```<code>class productList(generics.ListAPIView):
   serializer_class = productSerializer
   def get_queryset(self):
       queryset = Product.objects.all()
       search = self.request.query_params.get('search', None)
       if search is not None:
           queryset = queryset.filter(product_name__icontains=search)
</code>```

my urls

```<code>path('product_search/',views.productList.as_view()),
</code>```

答:
You're almost there, you just need to add filtering.

Also, you almost never need to override the get() method of a generic view. Look for the method that let's you do the least amount of work. For any view, you will do most work in get_queryset and a view specific method:

List: view.list()

Create: view.create()

Retrieve: view.retrieve()

Update: view.perform_update()

Destroy: view.perform_destroy()

The rest can be customized by setting the correct class attributes. There are very few cases where it is necessary to override a view's "get" or "post" methods.

So, get_queryset is the place to modify the collection of objects that you are going to work on. This is perfect for filtering and thus search. A lot of work is already available in DRF and you can use it:

class productList(generics.ListAPIView):
    serializer_class = productSerializer
    def get_queryset(self):
        queryset = Product.objects.all()
        search = self.request.query_params.get('search', None)
        if search is not None:
            queryset = queryset.filter(category__name__icontains=search)
        # don't forget to return the queryset
        return queryset
```

Body:
I am very much new in django restframework,I tried to create a search api.

I have 2 models designed

class Category(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Product(models.Model):
    product_name = models.CharField(max_length=255)
    product_Comments = models.CharField(max_length=255)
    size = models.CharField(max_length=10, null=True)
    product_Status = models.BooleanField(default=True)
    category = models.ForeignKey(Category,  on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.product_Description

I want to create a rest API, in which I can search the category and based on the search i want to list the product which related to that category. How can I do it.

My Views.py

class productList(generics.ListAPIView):
   serializer_class = productSerializer
   def get_queryset(self):
       queryset = Product.objects.all()
       search = self.request.query_params.get('search', None)
       if search is not None:
           queryset = queryset.filter(product_name__icontains=search)

my urls

path('product_search/',views.productList.as_view()),


问:
Tensorflow Keras Metrics Not showing
I have a simple Neural Network

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, MaxPool2D
model = Sequential([
    Conv2D(16,(3,3),padding='same', input_shape=(1,28,28),data_format='channels_first'),
    MaxPooling2D((3,3), data_format='channels_first')
])
print(model.summary())
```

<p>summary of model is</p>

```Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_2 (Conv2D)            (None, 16, 28, 28)        160
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 16, 9, 9)          0
=================================================================
Total params: 160
Trainable params: 160
Non-trainable params: 0
_________________________________________________________________
None
```

<p>and compilation as </p>

<pre class="lang-py prettyprint-override"><code>opt = tf.keras.optimizers.Adam(learning_rate=0.005)
model.compile(optimizer=opt,
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy(),
              tf.keras.metrics.MeanAbsoluteError()]
              )
</code>```

Now when I print Model attributes, it gives an empty list on metrics. Why is it so?

print(f"{model.metrics}\n{model.optimizer},\n,{model.loss}\n{model.optimizer.lr}")
```

<p>This is output</p>

```[]
<tensorflow.python.keras.optimizer_v2.adam.Adam object at 0x000001FB10F2EDC8>,
,<tensorflow.python.keras.losses.BinaryCrossentropy object at 0x000001FB10F2EEC8>
<tf.Variable 'learning_rate:0' shape=() dtype=float32, numpy=0.005>
```

答: Currently, this is a bug in Tensorflow version 2.2.0. Might be fixed later</p>

Title: Tensorflow Keras Metrics Not showing

Body:
I have a simple Neural Network

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, MaxPool2D
model = Sequential([
    Conv2D(16,(3,3),padding='same', input_shape=(1,28,28),data_format='channels_first'),
    MaxPooling2D((3,3), data_format='channels_first')
])
print(model.summary())

summary of model is

Model: "sequential_4"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_2 (Conv2D)            (None, 16, 28, 28)        160
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 16, 9, 9)          0
=================================================================
Total params: 160
Trainable params: 160
Non-trainable params: 0
_________________________________________________________________
None

and compilation as

opt = tf.keras.optimizers.Adam(learning_rate=0.005)
model.compile(optimizer=opt,
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy(),
              tf.keras.metrics.MeanAbsoluteError()]
              )

Now when I print Model attributes, it gives an empty list on metrics. Why is it so?

print(f"{model.metrics}\n{model.optimizer},\n,{model.loss}\n{model.optimizer.lr}")

This is output

[]
<tensorflow.python.keras.optimizer_v2.adam.Adam object at 0x000001FB10F2EDC8>,
,<tensorflow.python.keras.losses.BinaryCrossentropy object at 0x000001FB10F2EEC8>
<tf.Variable 'learning_rate:0' shape=() dtype=float32, numpy=0.005>


问:
How to setstate in a loop?
i am getting error at this.setState({ Url: resp.data.Url }); in GETAPI
TypeError: Cannot read property 'setState' of undefined..
 Please suggest.
 The GETAPI is basically used to render the data from the API. My use-case is to store all the URLs in state and pass it to DownloadButton component. I need this URL to download the required data.

The hirerachy of code is invokeGetReport which will give all the reports in array. I have looped in and invoked invokeGetReportDetails method. Under invokeGetReportDetails , i am calling invokeImageURL which will contain the URL'of all the reports. I need to store all the URLs in state & passed it to next component

```<code>class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      Url: [],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
   return (
      <div>
        <DownloadButton imageUrl={this.Url} />
      </div>
    );
  }
}

export default GetAPI;
</code>```

答:
In the context of your functions there is no 'this'.
Move your methods invokeGetReport, invokeGetReportDetails and invokeImageURL to class GetAPI and call them through 'this'.

```<code>class GetAPI extends Component {

    componentDidMount() {
        ...
          this.invokeGetReport(accesstoken);
        ...
    }

    invokeGetReportDetails = (accesstoken, reportID) => {
        ...
          this.invokeImageURL(accesstoken, expenseEntryId);
        ...
    };

    invokeImageURL = (accesstoken, expenseEntryId) => {
        ...
         this.setState({ Url: resp.data.Url });
        ...
    };

    invokeGetReport = (accesstoken) => {
        ...
         this.invokeGetReportDetails(accesstoken, reportID);
        ...
    };

    render() {
        ...
    }
}

export default GetAPI;
</code>```

Or use lambda-functions:

```<code>const invokeGetReportDetails = (accesstoken, reportID) => {...}
const invokeImageURL = (accesstoken, expenseEntryId) => {...}
</code>```

etc

Or call them through fn.call(this)

Title: How to setstate in a loop?

Body:
i am getting error at this.setState({ Url: resp.data.Url }); in GETAPI
TypeError: Cannot read property 'setState' of undefined..
 Please suggest.
 The GETAPI is basically used to render the data from the API. My use-case is to store all the URLs in state and pass it to DownloadButton component. I need this URL to download the required data.

The hirerachy of code is invokeGetReport which will give all the reports in array. I have looped in and invoked invokeGetReportDetails method. Under invokeGetReportDetails , i am calling invokeImageURL which will contain the URL'of all the reports. I need to store all the URLs in state & passed it to next component

class GetAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ID: [],
      Url: [],
    };
  }

  componentDidMount() {

    console.log(this.props.exptype);
    var accesstoken;
    let reports = [];

    axios
      .post(API, qs.stringify(requestBody), config)
      .then((result) => {
        console.log(result);
        this.setState({ token: result.data.access_token });
        accesstoken = result.data.access_token;
        console.log("access token ins " + accesstoken);
        invokeGetReport(accesstoken);
      })
      .catch((error) => {
        console.log(error);
        console.log(error.data);
      });

    function invokeGetReport(accesstoken) {
      console.log("access token is " + accesstoken);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(test_report_url, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("data id is " + resp.data.Items.length);

          //  debugger;
          for (let i = 0; i < resp.data.Items.length; i++) {
            let reportName = resp.data.Items[i].Name;
            let reportID = resp.data.Items[i].ID;
            console.log("id is : " + reportID + "Report Name : " + reportName);
            invokeGetReportDetails(accesstoken, reportID);
            reports.push(reportID);
          }
          //  invokeGetReportDetails(accesstoken, reports);
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeGetReportDetails(accesstoken, reportID) {
      console.log("reportID in detail API is " + reportID);
      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(report_details + reportID, config_req)
        .then((resp) => {
          console.log(resp);
          console.log(
            "report data id is " + resp.data.ExpenseEntriesList.length
          );
          for (let i = 0; i < resp.data.ExpenseEntriesList.length; i++) {
            let expenseEntryId = resp.data.ExpenseEntriesList[i].ReportEntryID;
            let ExpenseTypeName =
              resp.data.ExpenseEntriesList[i].ExpenseTypeName;
            console.log(
              "id is : " +
                expenseEntryId +
                " ExpenseTypeName : " +
                ExpenseTypeName
            );
            invokeImageURL(accesstoken, expenseEntryId);
          }
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    function invokeImageURL(accesstoken, expenseEntryId) {
      console.log("expenseEntryId in detail API is " + expenseEntryId);

      const config_req = {
        headers: {
          Accept: "application/json",
          Authorization: "Bearer " + accesstoken,
        },
      };

      axios
        .get(image_url + expenseEntryId, config_req)
        .then((resp) => {
          console.log(resp);
          console.log("URL is " + resp.data.Url);
          this.setState({ Url: resp.data.Url });
        })
        .catch((error) => {
          console.log(error);
          console.log(error.data);
        });
    }

    console.log("repoddrts sdda " + reports[1]);
    console.log("prop value is " + this.props);
    // console.log("report id " + this.state.ID);
  }

  render() {
   return (

        <DownloadButton imageUrl={this.Url} />

    );
  }
}

export default GetAPI;

Body:
In the context of your functions there is no 'this'.
Move your methods invokeGetReport, invokeGetReportDetails and invokeImageURL to class GetAPI and call them through 'this'.

class GetAPI extends Component {

    componentDidMount() {
        ...
          this.invokeGetReport(accesstoken);
        ...
    }

    invokeGetReportDetails = (accesstoken, reportID) => {
        ...
          this.invokeImageURL(accesstoken, expenseEntryId);
        ...
    };

    invokeImageURL = (accesstoken, expenseEntryId) => {
        ...
         this.setState({ Url: resp.data.Url });
        ...
    };

    invokeGetReport = (accesstoken) => {
        ...
         this.invokeGetReportDetails(accesstoken, reportID);
        ...
    };

    render() {
        ...
    }
}

export default GetAPI;

Or use lambda-functions:

const invokeGetReportDetails = (accesstoken, reportID) => {...}
const invokeImageURL = (accesstoken, expenseEntryId) => {...}

etc

Or call them through fn.call(this)


问:
Laravel Join other tables in relation
I have a Situation Like This:

User Model:

```<code>public function role() {
        return $this->hasOne('App\model\Roles' , 'id' ,'role');
    }

    public function userMetaData() {
        return $this->hasOne('App\model\UserMetaData' , 'user_id' ,'id');
    }

    public function userBet() {
        return $this->hasMany('App\model\UserBet' , 'user_id' , 'id');
    }

    public function userComission() {
        return $this->hasMany('App\model\UserComission' , 'user_id' , 'id');
    }

    public function userPartnership() {
        return $this->hasMany('App\model\UserPartneShip' , 'user_id' , 'id');
    }
    // Self Call
    public function parentData() {
        return $this->hasOne('App\User','id','parent_id');
    }
</code>```

Controller

```<code>$userData = User::with(['userMetaData','userBet','userComission','userPartnership','role','parentData'])
                            ->where('id',$id)
                            ->get();
</code>```

Now The Point Is In role i am getting the roles Of the User and In the parentData i am getting the creator of the user(parent) from the same user table by self calling now that parent also has a role

My Question Is How can i get that role object inside the parentData  Object?
Thanks!

答:
First of all.. the relationship you've set is wrong it should be belongsTo

```<code>public function role() {
    return $this->belongsTo('App\model\Roles' ,'role', 'id');
}

public function parentData() {
    return $this->belongsTo('App\User','parent_id','id');
}
</code>```

Now as you want role object inside the parentData set with as below.

```<code>$userData = User::with(['userMetaData','userBet','userComission','userPartnership','parentData.role'])
                  ->where('id',$id)
                  ->get();
</code>```

Title: Laravel Join other tables in relation

Body:
I have a Situation Like This:

User Model:

public function role() {
        return $this->hasOne('App\model\Roles' , 'id' ,'role');
    }

    public function userMetaData() {
        return $this->hasOne('App\model\UserMetaData' , 'user_id' ,'id');
    }

    public function userBet() {
        return $this->hasMany('App\model\UserBet' , 'user_id' , 'id');
    }

    public function userComission() {
        return $this->hasMany('App\model\UserComission' , 'user_id' , 'id');
    }

    public function userPartnership() {
        return $this->hasMany('App\model\UserPartneShip' , 'user_id' , 'id');
    }
    // Self Call
    public function parentData() {
        return $this->hasOne('App\User','id','parent_id');
    }

Controller

$userData = User::with(['userMetaData','userBet','userComission','userPartnership','role','parentData'])
                            ->where('id',$id)
                            ->get();

Now The Point Is In role i am getting the roles Of the User and In the parentData i am getting the creator of the user(parent) from the same user table by self calling now that parent also has a role

My Question Is How can i get that role object inside the parentData  Object?
Thanks!

Body:
First of all.. the relationship you've set is wrong it should be belongsTo

public function role() {
    return $this->belongsTo('App\model\Roles' ,'role', 'id');
}

public function parentData() {
    return $this->belongsTo('App\User','parent_id','id');
}

Now as you want role object inside the parentData set with as below.

$userData = User::with(['userMetaData','userBet','userComission','userPartnership','parentData.role'])
                  ->where('id',$id)
                  ->get();


问:
Create a Shell Script for Uploading Previous Data Backup via cronjob On linux
I have a backup file which created every night at 23:59. now i want a script to upload the file to s3 on the next day..
i have created a script but its not running as its saying that you don't have any file for current day.
below is the script i created...

```<code>#!/bin/bash

 FILENAME1="file.log.`date +%Y-%m-%d`"
 FILENAME2="file2.log.`date +%Y-%m-%d `.gz"
 BUCKET="file-logs"
 SAVEDIR="/home/ubuntu/logs"

 sudo  gzip -k ${SAVEDIR}/${FILENAME1}
 if [ -e ${SAVEDIR}/${FILENAME1} ]; then

    # Upload to AWS
    aws s3 cp ${SAVEDIR}/${FILENAME2} s3://${BUCKET}

    # Test result of last command run
    if [ "$?" -ne "0" ]; then
        echo "Upload to AWS failed"
        exit 1
    fi

    # If success, remove backup file
    # sudo  rm ${SAVEDIR}/${FILENAME1}

    # Exit with no error
    #exit 0
  fi
</code>```

If anyone could help me out here..as i'm not too familiar with shell-script &  all.

答: You can ask date to format any date instead of "now" using --date so you could ask it to format date +%Y-%m-%d --date=yesterday

Body:
I have a backup file which created every night at 23:59. now i want a script to upload the file to s3 on the next day..
i have created a script but its not running as its saying that you don't have any file for current day.
below is the script i created...

#!/bin/bash

 FILENAME1="file.log.`date +%Y-%m-%d`"
 FILENAME2="file2.log.`date +%Y-%m-%d `.gz"
 BUCKET="file-logs"
 SAVEDIR="/home/ubuntu/logs"

 sudo  gzip -k ${SAVEDIR}/${FILENAME1}
 if [ -e ${SAVEDIR}/${FILENAME1} ]; then

    # Upload to AWS
    aws s3 cp ${SAVEDIR}/${FILENAME2} s3://${BUCKET}

    # Test result of last command run
    if [ "$?" -ne "0" ]; then
        echo "Upload to AWS failed"
        exit 1
    fi

    # If success, remove backup file
    # sudo  rm ${SAVEDIR}/${FILENAME1}

    # Exit with no error
    #exit 0
  fi

If anyone could help me out here..as i'm not too familiar with shell-script &  all.


问:
Sorting std::unordered_map by key
How can I sort an unordered_map by key? I need to print an unordered_map sorted by key.

答:
An alternate solution is to construct a vector of the keys, sort the vector, and print per that sorted vector. This will be considerably faster than the approaches that constructed a map from the ordered map, but will also involve more code.</p>

```<code>std::unordered_map<KeyType, MapType> unordered;
std::vector<KeyType> keys;

keys.reserve (unordered.size());
for (auto& it : unordered) {
    keys.push_back(it.first);
}
std::sort (keys.begin(), keys.end());
for (auto& it : keys) {
    std::cout << unordered[it] << ' ';
}
</code>```

Title: Sorting std::unordered_map by key

Body:
An alternate solution is to construct a vector of the keys, sort the vector, and print per that sorted vector. This will be considerably faster than the approaches that constructed a map from the ordered map, but will also involve more code.

std::unordered_map<KeyType, MapType> unordered;
std::vector<KeyType> keys;

keys.reserve (unordered.size());
for (auto& it : unordered) {
    keys.push_back(it.first);
}
std::sort (keys.begin(), keys.end());
for (auto& it : keys) {
    std::cout << unordered[it] << ' ';
}


问:
How to fix type inference for a component variable in a jest Shallow test built with reactjs?
My scenario is a react project built in typescript, and specifically regarding a unit test involving shallow from Enzyme.
I'm working on aligning the project with the tsconfig parameter "noImplicitAny": true,
I'm wondering how to fix the let component issue described under.

```<code>let component

beforeEach(() => {
  component = shallow(<MyComponent format="%MM : %SS" />)
})

describe('#render', () => {
  it('shows the component correctly', () => {
    expect(component.find('.my-component').exists()).toEqual(true)
  })
})
</code>```

error

```<code>Variable 'component' implicitly has type 'any' in some locations where its type cannot be determined.ts(7034)
</code>```

how to create the inference of type MyComponent to variable component?

答:
You will need to type the component variable as a ShallowWrapper, with the generic type parameter of MyComponent. This is how it can be done:

```<code>import { shallow, ShallowWrapper } from 'enzyme';

let component: ShallowWrapper<MyComponentProps>;
component = shallow<MyComponentProps>(<MyComponent format="%MM : %SS" />)
</code>```

Body:
My scenario is a react project built in typescript, and specifically regarding a unit test involving shallow from Enzyme.
I'm working on aligning the project with the tsconfig parameter "noImplicitAny": true,
I'm wondering how to fix the let component issue described under.

let component

beforeEach(() => {
  component = shallow(<MyComponent format="%MM : %SS" />)
})

describe('#render', () => {
  it('shows the component correctly', () => {
    expect(component.find('.my-component').exists()).toEqual(true)
  })
})

error

Variable 'component' implicitly has type 'any' in some locations where its type cannot be determined.ts(7034)

how to create the inference of type MyComponent to variable component?

Body:
You will need to type the component variable as a ShallowWrapper, with the generic type parameter of MyComponent. This is how it can be done:

import { shallow, ShallowWrapper } from 'enzyme';

let component: ShallowWrapper<MyComponentProps>;
component = shallow<MyComponentProps>(<MyComponent format="%MM : %SS" />)


答:
As You have not given the proper url, the url you are hitting is not recognizing for get. Hence throwing 404 not found status.
Change the mapping of your rest controller as @GetMapping("/{studentId}") and then hit the url http://localhost:8081/api/v1/students/1</p>

Title: GET request returning 404 not found


答:
I did it using padding as a tuple of 2 tuples of 2 ints: interpreted as ((top_pad, bottom_pad), (left_pad, right_pad)). And setting ZeroPadding2D at the end of convolution 7 layer:

```<code>#################################
# Decoder
#################################
#conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(conv6)
conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_1')(upsp2)
conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_2')(conv7)
conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_3')(conv7)
zero1 = ZeroPadding2D(padding =  ((1, 0), (1, 0)), data_format = 'channels_last', name='zero1')(conv7)
</code>```

Title: ZeroPadding2D pad twices when I set padding to 1

Body:
I've just started to learn Tensorflow (2.1.0), Keras (2.3.7) with Python 3.7.7.

I'm trying an encoder-decoder network using VGG16.

I need to Upsample a layer from (12, 12, ...) to (25, 25, ...) to make conv7_1 has the same shape as conv4_3 layer. The layer with the 'problem' is upsp2:

conv4_3 (Conv2D)             (None, 25, 25, 512)       2359808
_________________________________________________________________
pool_4 (MaxPooling2D)        (None, 12, 12, 512)       0
_________________________________________________________________
conv5_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv5_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
pool_5 (MaxPooling2D)        (None, 6, 6, 512)         0
_________________________________________________________________
upsp1 (UpSampling2D)         (None, 12, 12, 512)       0
_________________________________________________________________
conv6_1 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv6_2 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
conv6_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
upsp2 (UpSampling2D)         (None, 24, 24, 512)       0
_________________________________________________________________
conv7_1 (Conv2D)             (None, 24, 24, 512)       2359808

I have tried this:

#################################
# Decoder
#################################
#conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

zero1 = ZeroPadding2D(padding = (1,1), data_format = 'channels_last', name='zero1')(conv6)
upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(zero1)

But I get that shape (12, 12, ...) gets into (14, 14, ...) at zero1 layer:

conv6_3 (Conv2D)             (None, 12, 12, 512)       2359808
_________________________________________________________________
zero1 (ZeroPadding2D)        (None, 14, 14, 512)       0
_________________________________________________________________
upsp2 (UpSampling2D)         (None, 28, 28, 512)       0
_________________________________________________________________

How can I upsample (12,12,512) to (25,25,512)?

Body:
I did it using padding as a tuple of 2 tuples of 2 ints: interpreted as ((top_pad, bottom_pad), (left_pad, right_pad)). And setting ZeroPadding2D at the end of convolution 7 layer:

#################################
# Decoder
#################################
#conv1 = Conv2DTranspose(512, (2, 2), strides = 2, name = 'conv1')(pool5)

upsp1 = UpSampling2D(size = (2,2), name = 'upsp1')(pool5)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_1')(upsp1)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_2')(conv6)
conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv6_3')(conv6)

upsp2 = UpSampling2D(size = (2,2), name = 'upsp2')(conv6)
conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_1')(upsp2)
conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_2')(conv7)
conv7 = Conv2D(512, 3, activation = 'relu', padding = 'same', name = 'conv7_3')(conv7)
zero1 = ZeroPadding2D(padding =  ((1, 0), (1, 0)), data_format = 'channels_last', name='zero1')(conv7)


问:
I don't fully understand how containerisation doesn't lead to over provisioning instances from the start
I understand the basics how containers and how they differ from running virtual machines. I also get that auto scaling when resources are low and how services such as AWS can horizontally scale and provision more resources for you.

What I don't understand however is how containerisation management technologies such as swarm or kubernetes stop over provisioning.

In my mind -  you still have to have the resources available in order to add more containers as the container management solution is only managing the containers themselves. Correct?

So if I had an ec2 (in the AWS world) which I was using for my application and kubernetes was running on it to manage containers for my application I would still need to have a auto scaling and have to spin up another ec2 if vm itself was being pushed to capacity by my application.

Perhaps because I've not worked with container orchestration as yet I can't grasp the mechanics of this but in principal I don't see how this works harmoniously.

答:
Kubernetes for example,has Cluster Autoscaler,which increases or decreases the size of a cluster by adding or removing nodes, based on the presence of pending pods and node utilization metrics. The implementation can change depending on the solution:Google Kubernetes Engine, Amazon EKS, unmanaged AWS EC2, and others.

But if the infrastructure allows it, Kubernetes can communicate with the underlying cloud provider and provision new VMs to host new nodes as necessary, and remove them as well. It does not need to wait for a human operator to provision these instances.


问:
Is it better to have an "ORDER BY" column in a different table?
I have the following table which stores images:

```<code>id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ...
12        img_2.png        2            3          text ...        text ...
22        img_3.png        1            1          text ...        text ...
....
..
Around 2,000,000 rows
</code>```

Let's say I need to obtain the images for client 1 in order of their priorities. I can execute a simple query like select image from images order by priority.

Since a large number of rows are involved, is it better to have a separate table for which simply stores the image_id and priority like this

```<code>id        image_id       priority
1            1              1
2            12             2
3            22             1
</code>```

So in order to get the same result, I'll use a simple join: select a.image from priorities b join images a on a.id = b.image_id order by b.priority

Which of the two will be faster?

答:
If you need the images for client = 1, then the query would be:

```<code>select i.image
from images i
where i.client_id = 1
order by i.priority;
</code>```

This query can take advantage of an index on images(client_id, priority) -- and no explicit sorting would be necessary.

The query that you want would be:

```<code>select i.image
from priorities p join
     images i
     on p.id = i.image_id
where i.client_id = 1
order by bp.priority;
</code>```

In this query, the where uses columns from one table and the select from a different table.  That is very hard to optimize, so I'm guessing you can't get around doing a sort.

From this performance perspective, it is better to have the data in a single table -- with the right index.

Body:
I have the following table which stores images:

id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ...
12        img_2.png        2            3          text ...        text ...
22        img_3.png        1            1          text ...        text ...
....
..
Around 2,000,000 rows

Let's say I need to obtain the images for client 1 in order of their priorities. I can execute a simple query like select image from images order by priority.

Since a large number of rows are involved, is it better to have a separate table for which simply stores the image_id and priority like this

id        image_id       priority
1            1              1
2            12             2
3            22             1

So in order to get the same result, I'll use a simple join: select a.image from priorities b join images a on a.id = b.image_id order by b.priority

Which of the two will be faster?

Body:
If you need the images for client = 1, then the query would be:

select i.image
from images i
where i.client_id = 1
order by i.priority;

This query can take advantage of an index on images(client_id, priority) -- and no explicit sorting would be necessary.

The query that you want would be:

select i.image
from priorities p join
     images i
     on p.id = i.image_id
where i.client_id = 1
order by bp.priority;

In this query, the where uses columns from one table and the select from a different table.  That is very hard to optimize, so I'm guessing you can't get around doing a sort.

From this performance perspective, it is better to have the data in a single table -- with the right index.


问:
Calculate the area of a polygon
I need to get the area of a polygon in my map. I looked for an example of new google.maps.geometry.spherical.computeArea, but I can't make it work, and I don't know why.

```<code>function dibuV(area){
  var i;
  var a = new Array();
  for(i=0; i<area.length; i++){
    var uno = area[i].split(",");
    a[i] = new google.maps.LatLng(uno[0],uno[1]);
  }
  poligon = new google.maps.Polygon({
    paths: a,
    strokeColor: "#22B14C",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#22B14C",
    fillOpacity: 0.35
  })
  poligon.setMap(map);//until here is ok
  var z = new google.maps.geometry.spherical.computeArea(poligon.getPath());
  alert(z); //this is not working
}
</code>```

答:
Please look at my below code</p>

```<code>var z = google.maps.geometry.spherical.computeArea(poligon.getPath());
</code>```

Title: Calculate the area of a polygon

Body:
I need to get the area of a polygon in my map. I looked for an example of new google.maps.geometry.spherical.computeArea, but I can't make it work, and I don't know why.

function dibuV(area){
  var i;
  var a = new Array();
  for(i=0; i<area.length; i++){
    var uno = area[i].split(",");
    a[i] = new google.maps.LatLng(uno[0],uno[1]);
  }
  poligon = new google.maps.Polygon({
    paths: a,
    strokeColor: "#22B14C",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#22B14C",
    fillOpacity: 0.35
  })
  poligon.setMap(map);//until here is ok
  var z = new google.maps.geometry.spherical.computeArea(poligon.getPath());
  alert(z); //this is not working
}

Body:
Please look at my below code

var z = google.maps.geometry.spherical.computeArea(poligon.getPath());


问:
How to fix Fatal error: Index out of Range
In my multi-dimensional list I am having an issue when I try to delete a Row - Thread 1: Fatal error: Index out of range:

```<code>struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar")]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            List {
                ForEach (0..<appState.parents.count) { parentIndex in
                    NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                        Text(self.appState.parents[parentIndex].name) // Thread 1: Fatal error: Index out of range
                    }
                }
                .onDelete(perform: deleteItem)
            }
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        List {
            ForEach (0..<(appState.parents[parentIndex].children?.count ?? 0)) { childIndex in
                Text(self.appState.parents[self.parentIndex].children![childIndex].name)
            }
        }
    }
}
</code>```

I rebuilt the situation as I am having this issue in a bigger project with more code. Especially there I am having the issue in the Children View when I try to delete a parent that has children. For parents without children, I am able to remove them.
In this code I'm not able to remove a row at all.

I think the issue is somehow related to the parentIndex that is not decreasing while the view is reloading through the Observable Object change.

答:
The issue occurs because the range in the foreach loop is constant. It must be changed to:

ForEach (appState.parents.indices, id: \.self) { parentIndex in

Body:
In my multi-dimensional list I am having an issue when I try to delete a Row - Thread 1: Fatal error: Index out of range:

struct Parent: Identifiable {
    let id = UUID()
    let name: String
    var children: [Child]?
}

struct Child: Identifiable {
    let id = UUID()
    let name: String
}

class AppState: ObservableObject {
    @Published var parents: [Parent]
    init() {
        self.parents = [
            Parent(name: "Foo", children: [Child(name: "bar")]),
            Parent(name: "FooBar", children: nil)
        ]
    }
}

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    var body: some View {
        NavigationView {
            List {
                ForEach (0..<appState.parents.count) { parentIndex in
                    NavigationLink (destination: ChildrenView(parentIndex: parentIndex).environmentObject(self.appState)) {
                        Text(self.appState.parents[parentIndex].name) // Thread 1: Fatal error: Index out of range
                    }
                }
                .onDelete(perform: deleteItem)
            }
        }
    }
    private func deleteItem(at indexSet: IndexSet) {
        self.appState.parents.remove(atOffsets: indexSet)
    }
}

struct ChildrenView: View {
    @EnvironmentObject var appState: AppState
    var parentIndex: Int
    var body: some View {
        List {
            ForEach (0..<(appState.parents[parentIndex].children?.count ?? 0)) { childIndex in
                Text(self.appState.parents[self.parentIndex].children![childIndex].name)
            }
        }
    }
}

I rebuilt the situation as I am having this issue in a bigger project with more code. Especially there I am having the issue in the Children View when I try to delete a parent that has children. For parents without children, I am able to remove them.
In this code I'm not able to remove a row at all.

I think the issue is somehow related to the parentIndex that is not decreasing while the view is reloading through the Observable Object change.


问:
Getting stackoverflow error on inverting a binary tree using a global variable
I am trying to invert a binary tree as in Java:

```<code>class Solution {
    TreeNode node;
    public TreeNode invertTree(TreeNode root)
    {
        if(root == null)
            return null;

        node = root;

        node.left = invertTree(root.right);

        node.right = invertTree(root.left);

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

However on running this code I am getting a stackoverflow error. Can anyone explain why?

答:
After inverting left subtree and right subtree, you need to swap the left node and right node too to make an inverted binary tree. You just need to add the code of swap two values.</p>

```<code>class Solution {
TreeNode node;
public TreeNode invertTree(TreeNode root)
    {
    if(root == null)
        return root;

    invertTree(root.left);
    invertTree(root.right);

     TreeNode temp=root.left;
     root.left=root.right;
    root.right=temp;

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

Body:
I am trying to invert a binary tree as in Java:

class Solution {
    TreeNode node;
    public TreeNode invertTree(TreeNode root)
    {
        if(root == null)
            return null;

        node = root;

        node.left = invertTree(root.right);

        node.right = invertTree(root.left);

        return node;
    }
}

However on running this code I am getting a stackoverflow error. Can anyone explain why?

Body:
After inverting left subtree and right subtree, you need to swap the left node and right node too to make an inverted binary tree. You just need to add the code of swap two values.

class Solution {
TreeNode node;
public TreeNode invertTree(TreeNode root)
    {
    if(root == null)
        return root;

    invertTree(root.left);
    invertTree(root.right);

     TreeNode temp=root.left;
     root.left=root.right;
    root.right=temp;

    return node;
    }
}


问:
Preg_match a string, must containing Letters and numbers
The sentence maybe:
BenQ G2420HDBL 23.6" Wide LCD Monitor

Need to grab the "G2420HDBL" part. The letters and numbers may be in a different order but still remains a string with both letters and numbers present.

答:
You can use the following regex in case-insensitive mode:

```<code>(?=[a-z]*[0-9])(?=[0-9]*[a-z])[a-z0-9-]+
</code>```

Basically it matches the first string that is made up of only letters and numbers with atleast one letter and atleast one number.

In PHP:

```<code>if(preg_match("/(?=[a-z]*[0-9])(?=[0-9]*[a-z])([a-z0-9-]+)/i",$input,$match)) {
   echo $match[1];
}
</code>```

See it

Body:
You can use the following regex in case-insensitive mode:

(?=[a-z]*[0-9])(?=[0-9]*[a-z])[a-z0-9-]+

Basically it matches the first string that is made up of only letters and numbers with atleast one letter and atleast one number.

In PHP:

if(preg_match("/(?=[a-z]*[0-9])(?=[0-9]*[a-z])([a-z0-9-]+)/i",$input,$match)) {
   echo $match[1];
}

See it


问:
Julian to Gregorian date conversion in Scala
I need to convert Julian date (YYYYDDD) to Gregorian date (YYYYMMDD) in Scala.
I got this far:

```<code>import java.text.SimpleDateFormat;
val format1 = new java.text.SimpleDateFormat("yyyyddd")
println(format1.parse("2018022"))
</code>```

The result is: Mon Jan 22 00:00:00 CST 2018

I need help to get output in "YYYYMMDD" format

答:
You can use below functions to convert the same. I'am using the same function on my website.</p>

```<code>function julian2d($indate) {
    $year = substr($indate,0,2);
    $day = ltrim(substr($indate,strlen($indate)-3,3),'0');    /* Day part with leading zeroes stripped    */
    if ($year == 70 && $day == 1) $outdate = 1;
    else if ($year == 70) $outdate = ($day-1)*24*60*60;
    else if ($year >= 0 && $year <= 99 && $day > 0 && $day <= 366) {
        $outdate = strtotime('01-Jan-' . $year);        /* Date on Jan 1 of the year    */
        if ($outdate >= 0) {
            $outdate = $outdate + ($day-1)*24*60*60;
        } else $outdate = FALSE;
    } else $outdate = FALSE;
    return $outdate;
}
</code>```

Body:
I need to convert Julian date (YYYYDDD) to Gregorian date (YYYYMMDD) in Scala.
I got this far:

import java.text.SimpleDateFormat;
val format1 = new java.text.SimpleDateFormat("yyyyddd")
println(format1.parse("2018022"))

The result is: Mon Jan 22 00:00:00 CST 2018

I need help to get output in "YYYYMMDD" format

Body:
You can use below functions to convert the same. I'am using the same function on my website.

function julian2d($indate) {
    $year = substr($indate,0,2);
    $day = ltrim(substr($indate,strlen($indate)-3,3),'0');    /* Day part with leading zeroes stripped    */
    if ($year == 70 && $day == 1) $outdate = 1;
    else if ($year == 70) $outdate = ($day-1)*24*60*60;
    else if ($year >= 0 && $year <= 99 && $day > 0 && $day <= 366) {
        $outdate = strtotime('01-Jan-' . $year);        /* Date on Jan 1 of the year    */
        if ($outdate >= 0) {
            $outdate = $outdate + ($day-1)*24*60*60;
        } else $outdate = FALSE;
    } else $outdate = FALSE;
    return $outdate;
}


问:
Python Matplotlib on Android
I have a python script that uses matplotlib's plt.show() method to plot graphs. Problem is, my program does not display graphs. What is an easy approach to displaying matplotlib's graphs on say layout xml file? Is this even possible?

I use Kotlin on Android Studio and it calls my Python scripts using Chaquopy btw.

答:
I've answered your question at https://github.com/chaquo/chaquopy/issues/294:

The easiest way is to save the image in PNG format, then load it using Android's BitmapFactory. You can do this either:

Via a temporary file; or

Via a Python bytes object which you convert to a Java byte[] array using PyObject.toJava. If matplotlib doesn't have an API to save a PNG directly to a bytes object, then you can use BytesIO.

Title: Python Matplotlib on Android


问:
Function is not working when called inside "addEventListener"
I am trying to make a slideshow in a webpage.

I created the next and previous button for changing images in different way. The next button is working but the previous button in not working. The display property of the images is set to none by default.

var nextbutton = document.querySelector(".next");
var prevbutton = document.querySelector(".prev");
var slide = document.querySelectorAll('.slideshow');
var slideindex = 1 ;

var show = function(n){
  var i;
  if (n > slide.length) { slideindex = 1};
  if (n < 1) {slideindex = slide.length};
  for (i = 0; i < slide.length; i++) {
    slide[i].style.display = "none";
  };
  slide[slideindex-1].style.display = "block";

};

var cl = function(p) {
  show(slideindex += p);
};

/* next button is working */
nextbutton.addEventListener("click", function(){
  show(slideindex += 1 );
} );

/* previous button is not working */
prevbutton.addEventListener("click" , cl(-1));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slideshow {
  width:100%;
  height: 500px !important ;
  border-radius: 7px;
  display: none;
 }</code>```

            ❮
            ❯

```

答:
```<code>prevbutton.addEventListener("click" , cl(-1));
</code>```

This calls the function immediately, when you bind the event, not when the event fires. You avoid this mistake when binding the next button event.

Change to:

```<code>prevbutton.addEventListener("click", evt => cl(-1));
</code>```

or

```<code>prevbutton.addEventListener("click", function(evt) { cl(-1); });
</code>```

Body:
I am trying to make a slideshow in a webpage.

I created the next and previous button for changing images in different way. The next button is working but the previous button in not working. The display property of the images is set to none by default.

var nextbutton = document.querySelector(".next");
var prevbutton = document.querySelector(".prev");
var slide = document.querySelectorAll('.slideshow');
var slideindex = 1 ;

var show = function(n){
  var i;
  if (n > slide.length) { slideindex = 1};
  if (n < 1) {slideindex = slide.length};
  for (i = 0; i < slide.length; i++) {
    slide[i].style.display = "none";
  };
  slide[slideindex-1].style.display = "block";

};

var cl = function(p) {
  show(slideindex += p);
};

/* next button is working */
nextbutton.addEventListener("click", function(){
  show(slideindex += 1 );
} );

/* previous button is not working */
prevbutton.addEventListener("click" , cl(-1));

.slideshow {
  width:100%;
  height: 500px !important ;
  border-radius: 7px;
  display: none;
 }

            ❮
            ❯

Body:
prevbutton.addEventListener("click" , cl(-1));

This calls the function immediately, when you bind the event, not when the event fires. You avoid this mistake when binding the next button event.

Change to:

prevbutton.addEventListener("click", evt => cl(-1));

or

prevbutton.addEventListener("click", function(evt) { cl(-1); });


问:
New line after input
I would like to have the following output:

```<code>Type in something random:
2
</code>```

I used the following code:

```<code>input("Type in something random:")
</code>```

and my output is

```<code>Type in something random:2
</code>```

(Output for when the user inputs "2")

How can I have the output given to me in  a new line, as demonstrated above?

I am using Python 3.

答:
Just add a \n (new line character) to the end of the string, like this:

```<code>input("Type in something random:\n")
</code>```

Title: New line after input

Body:
I would like to have the following output:

Type in something random:
2

I used the following code:

input("Type in something random:")

and my output is

Type in something random:2

(Output for when the user inputs "2")

How can I have the output given to me in  a new line, as demonstrated above?

I am using Python 3.

Body:
Just add a \n (new line character) to the end of the string, like this:

input("Type in something random:\n")


问:
Load parent and children dynamically in react
I am trying to figure out how to load data dynamically in react.

I made a example where I am loading all the parents as div.cards. Each parent do have a checkbox. Whenever you press a checkbox, you should get the chosen parents children.

The problem I am facing right now:

Whenever I press a checkbox, I load all childrens to all parents. I just want to load the children to the chosen parent(clicked checkbox div).

Since I am loading the data dynamically, all checkboxes seems to get the same ID, any suggestions on how to fix this aswell?

Can I somehow also destroy the div of the children if I uncheck the checkbox?

I made a example here:
https://jscomplete.com/playground/s504328

Help is appreciated, and if you see something I could Improve, please let me know.

答:
You are rendering childData based on this.state.childData which will be referenced by both the parents.

I suggest you change the structure to something like

```<code> this.state = {
            parentData: [{
              "title": "ParentTitle",
              "id": 1,
              "childData": [{
                 "title": "child1",
                 "id": 1
              }]
            }],
            loading: true,
            id: '',
        };
</code>```

I have created a fiddle with the solution you require.
https://jsfiddle.net/8w0o5a2m/1/
I have removed the async functions from code for simplicity

Body:
You are rendering childData based on this.state.childData which will be referenced by both the parents.

I suggest you change the structure to something like

 this.state = {
            parentData: [{
              "title": "ParentTitle",
              "id": 1,
              "childData": [{
                 "title": "child1",
                 "id": 1
              }]
            }],
            loading: true,
            id: '',
        };

I have created a fiddle with the solution you require.
https://jsfiddle.net/8w0o5a2m/1/
I have removed the async functions from code for simplicity


问:
function inside a function in android
what is this technique in java and android?
please give basics about this technique

```<code>    objlistview.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position,long id)
        {
            Cursor cr=(Cursor)parent.getItemAtPosition(position);
            int _id=cr.getInt(cr.getColumnIndex("_id"));
            callview(_id);
        }

    });
</code>```

thank you...

答: It's an anonymous class - very popular for ActionListeners where you create them just where you need them.  In your example, each time you create an instance of the OnItemClickListener via the new keyword you can specify the onItemClick behaviour (via the method) right where it's needed and bind it appropriately.  This is all done in a succinct syntax and scope.

Title: function inside a function in android

Body:
what is this technique in java and android?
please give basics about this technique

    objlistview.setOnItemClickListener(new OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position,long id)
        {
            Cursor cr=(Cursor)parent.getItemAtPosition(position);
            int _id=cr.getInt(cr.getColumnIndex("_id"));
            callview(_id);
        }

    });

thank you...


问:
Count of rows linked by ids in Pandas dataframe
I have a table of ids, and previous ids (see image 1), I want to count the number of unique ids in total linked in one chain, e.g. if we take the latest id as the 'parent' then the result for the example data below would be something like Image 2, where 'a' is linked to 5 total ids (a, b, c, d & e) and 'w' is linked to 4 ids (w, x, y & z). In practicality, I am dealing with randomly generated ids, not sequenced letters.

Python Code to produce example dataframes:

```<code>import pandas as pd

raw_data = pd.DataFrame([['a','b'], ['b','c'], ['c', 'd'],['d','e'],['e','-'],
                         ['w','x'], ['x', 'y'], ['y','z'], ['z','-']], columns=['id', 'previous_id'])

output = pd.DataFrame([['a',5],['w',4]], columns = ['parent_id','linked_ids'])
</code>```

答:
Use convert_matrix.from_pandas_edgelist with connected_components first, then create dictionary for mapping, get first mapped values per groups by Series.map filtered by Series.duplicated and last add new column by Series.map with Counter for mapp dictionary:

```<code>df1 = raw_data[raw_data['previous_id'].ne('-')]

import networkx as nx
from collections import Counter

g = nx.from_pandas_edgelist(df1,'id','previous_id')

connected_components = nx.connected_components(g)

d = {y:i for i, x in enumerate(connected_components) for y in x}
print (d)
{'c': 0, 'e': 0, 'b': 0, 'd': 0, 'a': 0, 'y': 1, 'x': 1, 'w': 1, 'z': 1}

c = Counter(d.values())
mapp = {k: c[v] for k, v in d.items()}
print (mapp)

{'c': 5, 'e': 5, 'b': 5, 'd': 5, 'a': 5, 'y': 4, 'x': 4, 'w': 4, 'z': 4}

df = (raw_data.loc[~raw_data['id'].map(d).duplicated(), ['id']]
            .rename(columns={'id':'parent_id'})
            .assign(linked_ids = lambda x: x['parent_id'].map(mapp)))

print (df)
  parent_id  linked_ids
0         a           5
5         w           4
</code>```

Body:
I have a table of ids, and previous ids (see image 1), I want to count the number of unique ids in total linked in one chain, e.g. if we take the latest id as the 'parent' then the result for the example data below would be something like Image 2, where 'a' is linked to 5 total ids (a, b, c, d & e) and 'w' is linked to 4 ids (w, x, y & z). In practicality, I am dealing with randomly generated ids, not sequenced letters.

Python Code to produce example dataframes:

import pandas as pd

raw_data = pd.DataFrame([['a','b'], ['b','c'], ['c', 'd'],['d','e'],['e','-'],
                         ['w','x'], ['x', 'y'], ['y','z'], ['z','-']], columns=['id', 'previous_id'])

output = pd.DataFrame([['a',5],['w',4]], columns = ['parent_id','linked_ids'])

Body:
Use convert_matrix.from_pandas_edgelist with connected_components first, then create dictionary for mapping, get first mapped values per groups by Series.map filtered by Series.duplicated and last add new column by Series.map with Counter for mapp dictionary:

df1 = raw_data[raw_data['previous_id'].ne('-')]

import networkx as nx
from collections import Counter

g = nx.from_pandas_edgelist(df1,'id','previous_id')

connected_components = nx.connected_components(g)

d = {y:i for i, x in enumerate(connected_components) for y in x}
print (d)
{'c': 0, 'e': 0, 'b': 0, 'd': 0, 'a': 0, 'y': 1, 'x': 1, 'w': 1, 'z': 1}

c = Counter(d.values())
mapp = {k: c[v] for k, v in d.items()}
print (mapp)

{'c': 5, 'e': 5, 'b': 5, 'd': 5, 'a': 5, 'y': 4, 'x': 4, 'w': 4, 'z': 4}

df = (raw_data.loc[~raw_data['id'].map(d).duplicated(), ['id']]
            .rename(columns={'id':'parent_id'})
            .assign(linked_ids = lambda x: x['parent_id'].map(mapp)))

print (df)
  parent_id  linked_ids
0         a           5
5         w           4


问:
MSI mechanical keyboard gives wrong inputs on MacBook Pro
I'm trying to use an MSI mechanical keyboard on my MacBook Pro, however, when using a keyboard tester the computer registers two inputs for one keyboard stroke (E.g. I press number 5 and the computer registers 5a). I've looked online but have not been able to find anyone else having a similar problem.</p>

答: Just for completion, I ended asking the manufacturer (MSI) and this particular keyboard does not support macOS. So better check next time.</p>


问:
python automatically pass variables to function
I have code like this

```<code>def function3():
    print(text)

def function2():
    text = "Hello"
    function3()

def function1():
    text = "World"
    function3()
</code>```

Like you see i want to automatically pass variable from function2 and function1 to function3. This variable should be visible only on this three functions (so I can't set it global). Also I don't want to pass this variable every time between round brackets, because I will use function3 thousands of times.
Is there a something like keyword use in php?

```<code>function3() use (text):
    print(text)
</code>```

答:
There is nothing directly equivalent, you would normally just pass the arguments around.

From what I understand, the use keyword in PHP to manually add variables to an anonymous function's closure. In python, function scopes already create closures for you automatically using lexical scoping rules. You can do something like this:

```<code>def function_maker():
    text = None # need to initialize a variable in the outer function scope
    def function3():
        print(text)

    def function2():
        nonlocal text
        text = "Hello"
        function3()

    def function1():
        nonlocal text
        text = "World"
        function3()

    return function1, function2, function3

function1, function2, function3 = function_maker()
</code>```

But this pattern wouldn't be common in Python, you would just use a class:

```<code>class MyClass:
    def __init__(self, text): # maybe add a constructor
        self.text = text

    def function3(self):
        print(self.text)

    def function2(self):
        self.text = "Hello"
        self.function3()

    def function1(self):
        self.text = "World"
        self.function3()
</code>```

Body:
I have code like this

def function3():
    print(text)

def function2():
    text = "Hello"
    function3()

def function1():
    text = "World"
    function3()

Like you see i want to automatically pass variable from function2 and function1 to function3. This variable should be visible only on this three functions (so I can't set it global). Also I don't want to pass this variable every time between round brackets, because I will use function3 thousands of times.
Is there a something like keyword use in php?

function3() use (text):
    print(text)

Body:
There is nothing directly equivalent, you would normally just pass the arguments around.

From what I understand, the use keyword in PHP to manually add variables to an anonymous function's closure. In python, function scopes already create closures for you automatically using lexical scoping rules. You can do something like this:

def function_maker():
    text = None # need to initialize a variable in the outer function scope
    def function3():
        print(text)

    def function2():
        nonlocal text
        text = "Hello"
        function3()

    def function1():
        nonlocal text
        text = "World"
        function3()

    return function1, function2, function3

function1, function2, function3 = function_maker()

But this pattern wouldn't be common in Python, you would just use a class:

class MyClass:
    def __init__(self, text): # maybe add a constructor
        self.text = text

    def function3(self):
        print(self.text)

    def function2(self):
        self.text = "Hello"
        self.function3()

    def function1(self):
        self.text = "World"
        self.function3()


问:
Why spinlocks can become performance issue in multithreaded programs?
I know what spinlocks are and that they use busy waiting. But why can it become a performance problem in multithreaded programs on a multicore processor?

And what can be done about it?

答:
Your first issue, is that in cases where a spinlock protected section becomes contented, is usually a situation where there are more threads ready for execution than you have cores available. That means each thread wasting time in a spinlock is potentially starving another thread which would had something proper to do.

Then there is the cost of the spinock itself. You are burning through your budget of memory transactions, and that budget is actually shared between processor cores. Effectively, this can result in slowing down the operations within the critical sections.

A good example for that would be the memory allocator in the Windows kernel, in versions between 1703 and 1803. On systems with more than 16 threads, once a 50% total CPU utilization as exceeded, a spinlock in that path went out of control and would start eating up 90% of the CPU time. Time spent inside the critical section increased over tenfold due to the competing threads burning the memory bandwidth.

The naive solution is to use nano-sleeps in between spin cycles in order to at least reduce the performance burnt on the locks themselves. But that's pretty bad as well, as the cores still remain blocked, not doing any real work.

Try and yield in the spin locks instead? Just turns even slower, and you end up with a minimum delay proportional to the scheduling rate of the operating system. At a rate of 1ms (Windows realtime mode, active when any process requests it), 5ms (Linux default 200Hz scheduler), 10ms (Windows default mode), that's a huge delay this is introducing into execution. And if you happen to hit the critical section again, it was wasteful as you now added the overhead for context switch without any gains.

Ultimately, use operating system primitives for critical sections. The common approach is to use atomic operations to probe if any contention has occurred, and when it has, only then to involve the operating system.

Either way, the operating system below has better means to resolve the contention, mostly in the form of wait lists. Meaning threads waiting on a semaphore only wait up exactly when they are allowed to resume, and are guaranteed to hold the corresponding lock. When leaving the contended region, the thread owning the lock checks via lightweight means if there had been any contention, and only if so notifies the OS to resume operation on the other threads.

Not that you should actually reinvent the wheel though...

In Windows, that's already how Slim Reader/Writer Locks are implemented.
If you use a plain std::mutex or alike, you will usually already end up with such mechanism under the hood.

"Old" literature (10-15 years) will still warn you not to use OS primitives for scheduling, but that's seriously outdated and does not reflect the improvements made on the OS side. What used to be 10ms+ delay for every context switch is essentially down to being barely measurable nowadays.


问:
Is there a better way to mask a Credit Card number in python?
So I have a csv file that contains full credit-card numbers.. We dont need the full number, and so I am writing a quick script to parse through the csv and replace the cc number with a masked representation. (all *'s except the last four).  I am pretty new to python and hacked this up, and it works, but in order to learn I want to know if it could be done easier.

Assume that "str" will be a full creditcard number.  But for the sake of my example I am just using the string "CREDITCARDNUMBER".

```<code>str = "CREDITCARDNUMBER";
strlength = len(str)
masked = strlength - 4
slimstr = str[masked:]
print "*" * masked + slimstr
</code>```

The output is exactly what I want

```<code>************MBER
</code>```

But I am sure there is a more elegant solution. :) Thanks!

答:
We also can use this function:</p>

```<code>def maskify(cc):
    if len(cc) < 4:
        return cc
    return "#" * (len(cc)-4) + cc[-4:]
</code>```

Body:
So I have a csv file that contains full credit-card numbers.. We dont need the full number, and so I am writing a quick script to parse through the csv and replace the cc number with a masked representation. (all *'s except the last four).  I am pretty new to python and hacked this up, and it works, but in order to learn I want to know if it could be done easier.

Assume that "str" will be a full creditcard number.  But for the sake of my example I am just using the string "CREDITCARDNUMBER".

str = "CREDITCARDNUMBER";
strlength = len(str)
masked = strlength - 4
slimstr = str[masked:]
print "*" * masked + slimstr

The output is exactly what I want

************MBER

But I am sure there is a more elegant solution. :) Thanks!

Body:
We also can use this function:

def maskify(cc):
    if len(cc) < 4:
        return cc
    return "#" * (len(cc)-4) + cc[-4:]


问:
Upgrade process for fontawesome from 4 to 5
We contributed to font-awesome 5 (yea), and we are looking from moving from our existing icons (Symbol set) to font-awesome.   Will the naming of icons and usage of font-awesome 5 be backwards compatible with font-awesome 4.7?

IE: Should we go to 4.7 now, and have very easy upgrade to 5.0?
OR should we hold off until font-awesome 5 comes out?

答:
I made (yet another) script:

Gist here: https://gist.github.com/cloakedninjas/9e4e029c92a141c547dabdabe9ccbb1d

It's in Node, it uses a CSV input file based off of https://fontawesome.com/how-to-use/on-the-web/setup/upgrading-from-version-4#name-changes (copied into Google Sheets and exported as CSV.

The thinking being, if future upgrades follow the same table structure, it will be trivial to re-run.


答:
Try to add a new line character as below

```<code>input("Type in something random: \n")
</code>```

so that you will get output like this

```<code>Type in something random:
6
'6'
</code>```

Title: New line after input

Body:
Try to add a new line character as below

input("Type in something random: \n")

so that you will get output like this

Type in something random:
6
'6'


问:
Pyspark: transform categorial column into a binary array
I have a dataframe where there is a column where each value is a string, and i wish to transform it such that each appearance of a string for the specific id (represented in a different column) would serve as a one in the array in the appropriate location. As an example if i have this dataset:

```<code>category   id
a          1
b          1
c          1
a          2
d          2
</code>```

I wish to transform it into:

```<code>id   result
1    [1,1,1,0]
2    [1,0,0,1]
</code>```

Any idea on how to do this?

EDIT: i tried using the string indexer but all it did was count the amount of appearences up when i really wanted to get the array itself.

答:
you can first pivot and fill null with 0 then convert the columns apart from the id column to an array:

```<code>import pyspark.sql.functions as F

res = df.groupBy('id').pivot("category").agg(F.count("category")).fillna(0)
res.select("id",F.array(*[F.col(i) for i in res.columns[1:]]).alias("result")).show()
</code>```

```<code>+---+------------+
| id|      result|
+---+------------+
|  1|[1, 1, 1, 0]|
|  2|[1, 0, 0, 1]|
+---+------------+
</code>```

Note that if elements can repeat, you can have counts more than 1 in which case you can add a when+otherwise:

```<code>(res.select("id",F.array(*[F.when(F.col(i)>=1,1).otherwise(0)
                       for i in res.columns[1:]]).alias("result"))).show()
</code>```

Body:
I have a dataframe where there is a column where each value is a string, and i wish to transform it such that each appearance of a string for the specific id (represented in a different column) would serve as a one in the array in the appropriate location. As an example if i have this dataset:

category   id
a          1
b          1
c          1
a          2
d          2

I wish to transform it into:

id   result
1    [1,1,1,0]
2    [1,0,0,1]

Any idea on how to do this?

EDIT: i tried using the string indexer but all it did was count the amount of appearences up when i really wanted to get the array itself.

Body:
you can first pivot and fill null with 0 then convert the columns apart from the id column to an array:

import pyspark.sql.functions as F

res = df.groupBy('id').pivot("category").agg(F.count("category")).fillna(0)
res.select("id",F.array(*[F.col(i) for i in res.columns[1:]]).alias("result")).show()

+---+------------+
| id|      result|
+---+------------+
|  1|[1, 1, 1, 0]|
|  2|[1, 0, 0, 1]|
+---+------------+

Note that if elements can repeat, you can have counts more than 1 in which case you can add a when+otherwise:

(res.select("id",F.array(*[F.when(F.col(i)>=1,1).otherwise(0)
                       for i in res.columns[1:]]).alias("result"))).show()


问:
Duplicate element of tensor while perserving gradient values
So I have a vector that I computed somehow with size k

```<code>x = torch.FloatTensor([0.5, 0.3, 0.1, 0.7])
x = x + 2
</code>```

I want to take its first element x[0] and create a vector of size k-1 filled with the value x[0] so that the gradients that come along with this element are present in the new vector.

I tried using torch.full and filling it up with x[0] but that does not preserve gradients.

Using pytorch 1.4

答:
You can simply use indexing for that:

y = x[[0] * (k - 1)]  # take x[0] k-1 times
```

Body:
So I have a vector that I computed somehow with size k

x = torch.FloatTensor([0.5, 0.3, 0.1, 0.7])
x = x + 2

I want to take its first element x[0] and create a vector of size k-1 filled with the value x[0] so that the gradients that come along with this element are present in the new vector.

I tried using torch.full and filling it up with x[0] but that does not preserve gradients.

Using pytorch 1.4