问:
Turtle animation randomly speeding up/slowing down
How do I stop turtle animation from randomly speeding up/slowing down?

I have been trying to make a pong game with Python; however, the ball seems to speed up and slow down randomly from time to time.  How do I stop this from happening?

I have tried changing the speed variables of the ball, but that doesn't help. I've also researched a fix to this issue but I can't find anything useful.

```<code>import turtle

# Window settings
wn = turtle.Screen()
wn.title('Classic Pong v1.0')
wn.bgcolor('black')
wn.setup(width=800, height=600)
wn.tracer(0)

# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.dx = 0.1   # Ball moves by 0.1 pixels every time
ball.dy = 0.1

# Main game loop
while True:
    wn.update()

    # Moving the ball
    ball.setx(ball.xcor() + ball.dx)    # Updates the position of the ball every time
    ball.sety(ball.ycor() + ball.dy)

    # Border collision checking
    if ball.ycor() > 290:
        ball.sety(290)
        ball.dy *= -1

    if ball.ycor() < -280:      # Set to 280 to account for extra space
        ball.sety(-280)
        ball.dy *= -1

    if ball.xcor() > 380:       # Set to 280 to account for extra space
        ball.goto(0, 0)
        ball.dx *= -1

    if ball.xcor() < -390:
        ball.goto(0, 0)
        ball.dx *= -1
</code>```

I expect the animation of the ball to be smooth; however, the speed of the animation varies randomly.

答:
I don't see off hand why your animation speeds up and slows down.  Regardless, below is how I would write this same code based on the following issues:

A while True: loop has no place in an event-based environment like
turtle -- if it's not a problem currently, it will become one.  I've
replaced it with timer events.

A pixel movement of 0.1 is awfully small and will always seem slow in
turtle.

Avoid asking turtle to do anything it doesn't need to in the critical loop.
Between calls to setx(), sety(), xcor(), ycor() and goto()
you make a dozen method invocations on your turtle instance.  In my
rewrite I just have two turtle calls in the critical loop, position() and
setposition().

I dropped tracer() and update() as I instrumented my
critical loop and there was only one turtle call that changed the
screen on each update and that's the default setting for tracer()
-- so nothing gained.

The revised code:

```<code>from turtle import Screen, Turtle

WIDTH, HEIGHT = 800, 600
CURSOR_SIZE = 20

ball_dx = 1
ball_dy = -2.5

def move():
    global ball_dx, ball_dy

    x, y = ball.position()

    y += ball_dy

    # Border collision checking
    if not CURSOR_SIZE - HEIGHT/2 < y < HEIGHT/2 - CURSOR_SIZE:
        ball_dy *= -1

    x += ball_dx

    if not CURSOR_SIZE - WIDTH/2 < x < WIDTH/2 - CURSOR_SIZE:
        x = y = 0
        ball_dx *= -1

    ball.setposition(x, y)

    screen.ontimer(move, 50)

# Window settings
screen = Screen()
screen.title('Classic Pong v1.1')
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('black')

# Ball
ball = Turtle()
ball.shape('square')
ball.color('white')
ball.speed('fastest')
ball.penup()

move()
screen.mainloop()
</code>```

Body:
How do I stop turtle animation from randomly speeding up/slowing down?

I have been trying to make a pong game with Python; however, the ball seems to speed up and slow down randomly from time to time.  How do I stop this from happening?

I have tried changing the speed variables of the ball, but that doesn't help. I've also researched a fix to this issue but I can't find anything useful.

import turtle

# Window settings
wn = turtle.Screen()
wn.title('Classic Pong v1.0')
wn.bgcolor('black')
wn.setup(width=800, height=600)
wn.tracer(0)

# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape('square')
ball.color('white')
ball.penup()
ball.dx = 0.1   # Ball moves by 0.1 pixels every time
ball.dy = 0.1

# Main game loop
while True:
    wn.update()

    # Moving the ball
    ball.setx(ball.xcor() + ball.dx)    # Updates the position of the ball every time
    ball.sety(ball.ycor() + ball.dy)

    # Border collision checking
    if ball.ycor() > 290:
        ball.sety(290)
        ball.dy *= -1

    if ball.ycor() < -280:      # Set to 280 to account for extra space
        ball.sety(-280)
        ball.dy *= -1

    if ball.xcor() > 380:       # Set to 280 to account for extra space
        ball.goto(0, 0)
        ball.dx *= -1

    if ball.xcor() < -390:
        ball.goto(0, 0)
        ball.dx *= -1

I expect the animation of the ball to be smooth; however, the speed of the animation varies randomly.

Body:
I don't see off hand why your animation speeds up and slows down.  Regardless, below is how I would write this same code based on the following issues:

A while True: loop has no place in an event-based environment like
turtle -- if it's not a problem currently, it will become one.  I've
replaced it with timer events.

A pixel movement of 0.1 is awfully small and will always seem slow in
turtle.

Avoid asking turtle to do anything it doesn't need to in the critical loop.
Between calls to setx(), sety(), xcor(), ycor() and goto()
you make a dozen method invocations on your turtle instance.  In my
rewrite I just have two turtle calls in the critical loop, position() and
setposition().

I dropped tracer() and update() as I instrumented my
critical loop and there was only one turtle call that changed the
screen on each update and that's the default setting for tracer()
-- so nothing gained.

The revised code:

from turtle import Screen, Turtle

WIDTH, HEIGHT = 800, 600
CURSOR_SIZE = 20

ball_dx = 1
ball_dy = -2.5

def move():
    global ball_dx, ball_dy

    x, y = ball.position()

    y += ball_dy

    # Border collision checking
    if not CURSOR_SIZE - HEIGHT/2 < y < HEIGHT/2 - CURSOR_SIZE:
        ball_dy *= -1

    x += ball_dx

    if not CURSOR_SIZE - WIDTH/2 < x < WIDTH/2 - CURSOR_SIZE:
        x = y = 0
        ball_dx *= -1

    ball.setposition(x, y)

    screen.ontimer(move, 50)

# Window settings
screen = Screen()
screen.title('Classic Pong v1.1')
screen.setup(WIDTH, HEIGHT)
screen.bgcolor('black')

# Ball
ball = Turtle()
ball.shape('square')
ball.color('white')
ball.speed('fastest')
ball.penup()

move()
screen.mainloop()


来源: stackexchange

问:
Syntax for a single-line while loop in Bash
I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:</p>

```<code>while [ 1 ]
do
    foo
    sleep 2
done
</code>```

答:
Using while:

```<code>while true; do echo 'while'; sleep 2s; done
</code>```

Using for Loop:

```<code>for ((;;)); do echo 'forloop'; sleep 2; done
</code>```

Using Recursion, (a little bit different than above, keyboard interrupt won't stop it)

```<code>list(){ echo 'recursion'; sleep 2; list; } && list;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble coming up with the right combination of semicolons and/or braces. I'd like to do this, but as a one-liner from the command line:

while [ 1 ]
do
    foo
    sleep 2
done

Body:
Using while:

while true; do echo 'while'; sleep 2s; done

Using for Loop:

for ((;;)); do echo 'forloop'; sleep 2; done

Using Recursion, (a little bit different than above, keyboard interrupt won't stop it)

list(){ echo 'recursion'; sleep 2; list; } && list;


问:
SocketIO is not listening to 'on' function
I've tried this for 6+ hours now. I am using Flask-SocketIO and react native to just try to get a test setup working. It seems that some listener is not working. Here is my code:

```<code>SERVER SIDE PYTHON FILE (running on flask development server)

@socketio.on('connect')
def connect():
    print('listening to connect')

@socketio.on('emission')
def emission(data):
    print('listen to emission')
    message = data['hello']
    emit('emission', message, broadcast=True)

CLIENT SIDE REACT NATIVE

import io from 'socket.io-client/dist/socket.io';
socket = null
export default class trial extends Component {

constructor(props) {
    super(props)

        this.state = {
        returned:'',
        }
     }

componentDidMount() {
    console.log('test')
}

click() {
    //connect
    socket = io.connect('http://127.0.0.1:5000', {transports:
    ["websocket"]} );

socket.on('emission', (data) => {
    this.setState({returned:data})
    console.log('emission was emitted by someone and sent', data);
    });
}

click2() {
    socket.disconnect()
}

click3() {
    console.log('emission')
    socket.emit('emission', {hello: 'emitting message to server'});
}
</code>```

I am trying to listen to connect, and that succeeds and Flask development server prints out 'listening to connect'

I am then trying to listen to 'emission', send it a message, then have it sent back. This part wont work and nothing prints to development server.

I have tried socket.io.on , connect and disconnect work

答:
You have to run Flask-SocketIO with

```<code>python flask_script.py
</code>```

not

```<code>flask run
</code>```

This is to ensure that gevent is running and able to manage websockets; otherwise, anything you use websockets for will not work.

Body:
I've tried this for 6+ hours now. I am using Flask-SocketIO and react native to just try to get a test setup working. It seems that some listener is not working. Here is my code:

SERVER SIDE PYTHON FILE (running on flask development server)

@socketio.on('connect')
def connect():
    print('listening to connect')

@socketio.on('emission')
def emission(data):
    print('listen to emission')
    message = data['hello']
    emit('emission', message, broadcast=True)

CLIENT SIDE REACT NATIVE

import io from 'socket.io-client/dist/socket.io';
socket = null
export default class trial extends Component {

constructor(props) {
    super(props)

        this.state = {
        returned:'',
        }
     }

componentDidMount() {
    console.log('test')
}

click() {
    //connect
    socket = io.connect('http://127.0.0.1:5000', {transports:
    ["websocket"]} );

socket.on('emission', (data) => {
    this.setState({returned:data})
    console.log('emission was emitted by someone and sent', data);
    });
}

click2() {
    socket.disconnect()
}

click3() {
    console.log('emission')
    socket.emit('emission', {hello: 'emitting message to server'});
}

I am trying to listen to connect, and that succeeds and Flask development server prints out 'listening to connect'

I am then trying to listen to 'emission', send it a message, then have it sent back. This part wont work and nothing prints to development server.

I have tried socket.io.on , connect and disconnect work

Body:
You have to run Flask-SocketIO with

python flask_script.py

not

flask run

This is to ensure that gevent is running and able to manage websockets; otherwise, anything you use websockets for will not work.


问:
How to add "book button to each car product"?
I want to add "book" button to each car product.But it only display only one button for first car only.

```<code>$sql = "SELECT * FROM car";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "<table>";
        echo "<tr>";
            echo "<th>Id</th>";
            echo "<th>Name</th>";
            echo "<th>Price(RM)</th>";
            echo "<th>Colour</th>";
            echo "<th>Mode</th>";
            echo "<th>Image</th>";
            echo "<th>Status</th>";
            echo "<td><button onclick=\"book_car('" . $row['car_id'] .
            "')\">Book</button></td>";
    while($row = mysqli_fetch_array($result)){
        echo "<tr>";
            echo "<td>" . $row['car_id'] . "</td>";
            echo "<td>" . $row['car_name'] . "</td>";
            echo "<td>" . $row['car_price'] . "</td>";
            echo "<td>" . $row['car_colour'] . "</td>";
            echo "<td>" . $row['car_mode'] . "</td>";
            echo "<td><img src='" . $row['car_image'] . "' height='100'
            width='100'></td>";
            echo "<td>" . $row['car_status'] . "</td>";

        echo "</tr>";
    }
</code>```

There is no error.But i just want "book" button display for each car products.

答:
This is simply because your button is out of the while loop !

Also you did not close first tr tag .

Correct code :

```<code>$sql = "SELECT * FROM car";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
    echo "<tr>";
        echo "<th>Id</th>";
        echo "<th>Name</th>";
        echo "<th>Price(RM)</th>";
        echo "<th>Colour</th>";
        echo "<th>Mode</th>";
        echo "<th>Image</th>";
        echo "<th>Status</th>";
        echo "<th>action</th>";<!-- Added this line -->
     echo "</tr>";<!-- Added this line -->

while($row = mysqli_fetch_array($result)){
    echo "<tr>";
        echo "<td>" . $row['car_id'] . "</td>";
        echo "<td>" . $row['car_name'] . "</td>";
        echo "<td>" . $row['car_price'] . "</td>";
        echo "<td>" . $row['car_colour'] . "</td>";
        echo "<td>" . $row['car_mode'] . "</td>";
        echo "<td><img src='" . $row['car_image'] . "' height='100'
        width='100'></td>";
        echo "<td>" . $row['car_status'] . "</td>";
        echo "<td><button onclick=\"book_car('" . $row['car_id'] .
        "')\">Book</button></td>";<!-- Replaced This line -->

    echo "</tr>";
}
echo "</table>";
</code>```

I hope this helps you :)

Body:
I want to add "book" button to each car product.But it only display only one button for first car only.

$sql = "SELECT * FROM car";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
    echo "
";
        echo "
";
            echo "Id	";
            echo "Name	";
            echo "Price(RM)	";
            echo "Colour	";
            echo "Mode	";
            echo "Image	";
            echo "Status	";
            echo "<button onclick=\"book_car('" . $row['car_id'] .
            "')\">Book</button>	";
    while($row = mysqli_fetch_array($result)){
        echo "
";
            echo "" . $row['car_id'] . "	";
            echo "" . $row['car_name'] . "	";
            echo "" . $row['car_price'] . "	";
            echo "" . $row['car_colour'] . "	";
            echo "" . $row['car_mode'] . "	";
            echo "	";
            echo "" . $row['car_status'] . "	";

        echo "
";
    }

There is no error.But i just want "book" button display for each car products.

Body:
This is simply because your button is out of the while loop !

Also you did not close first tr tag .

Correct code :

$sql = "SELECT * FROM car";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
    echo "<tr>";
        echo "<th>Id</th>";
        echo "<th>Name</th>";
        echo "<th>Price(RM)</th>";
        echo "<th>Colour</th>";
        echo "<th>Mode</th>";
        echo "<th>Image</th>";
        echo "<th>Status</th>";
        echo "<th>action</th>";<!-- Added this line -->
     echo "</tr>";<!-- Added this line -->

while($row = mysqli_fetch_array($result)){
    echo "<tr>";
        echo "<td>" . $row['car_id'] . "</td>";
        echo "<td>" . $row['car_name'] . "</td>";
        echo "<td>" . $row['car_price'] . "</td>";
        echo "<td>" . $row['car_colour'] . "</td>";
        echo "<td>" . $row['car_mode'] . "</td>";
        echo "<td><img src='" . $row['car_image'] . "' height='100'
        width='100'></td>";
        echo "<td>" . $row['car_status'] . "</td>";
        echo "<td><button onclick=\"book_car('" . $row['car_id'] .
        "')\">Book</button></td>";<!-- Replaced This line -->

    echo "</tr>";
}
echo "</table>";

I hope this helps you :)


问:
How to fix error in error 'InvalidArgument=Value of '7' is not valid for 'index'
I'm setting the listview to a format of backcolor if ever the loop finds the string it will trigger the event.

I've already trapped the function to the if else statement but the error still there.

```<code>foreach (ListViewItem li in listView1.Items)
        {
            for (int i = 0; i < listView1.Columns.Count; i++)
            {

                if (li.SubItems[i].Text.ToString() == "Pending")
                {
                    li.BackColor = Color.Turquoise;
                    li.ForeColor = Color.White;
                }
                else if (li.SubItems[i].Text.ToString() == "Paid")
                {
                    li.BackColor = Color.Green;
                    li.ForeColor = Color.White;
                }
                else if (li.SubItems[i].Text.ToString() == "Over Due")
                {
                    li.BackColor = Color.Red;
                    li.ForeColor = Color.White;
                }

            }

        }
</code>```

This is the error I've got. 'InvalidArgument=Value of '7' is not valid for 'index'

答:
Issue is in your inner for loop, you are iterating over listView1.Columns instead of itemRow.SubItems

you should update your for loop, like

```<code>foreach (ListViewItem li in listView1.Items)
    {
        for (int i = 0; i < listView1.SubItems.Count; i++)
        {                           //^^^^^^^^ this is what you need to change
            //Your code goes here
        }
    }
</code>```

Or you can use foreach loop,

```<code>foreach (ListViewItem li in listView1.Items)
    {
        foreach (var subItem in li.SubItems)
        {
            if (subItem.Text.ToString() == "Pending") {
                  li.BackColor = Color.Turquoise;
              }
            else if (subItem.Text.ToString() == "Paid") {
                  li.BackColor = Color.Green;
              }
            else if (subItem.Text.ToString() == "Over Due") {
                  li.BackColor = Color.Red;
              }
        }
    li.ForeColor = Color.White;
    }
</code>```

Your code is giving error might be because of
  listView1.Columns.Count is greater listView1.SubItems.Count

Bonus : li.ForeColor = Color.White; is same in all if..else conditions, you can write it outside of if..else ladder instead of writing it in each condition. Kindly check my updated code

Body:
I'm setting the listview to a format of backcolor if ever the loop finds the string it will trigger the event.

I've already trapped the function to the if else statement but the error still there.

foreach (ListViewItem li in listView1.Items)
        {
            for (int i = 0; i < listView1.Columns.Count; i++)
            {

                if (li.SubItems[i].Text.ToString() == "Pending")
                {
                    li.BackColor = Color.Turquoise;
                    li.ForeColor = Color.White;
                }
                else if (li.SubItems[i].Text.ToString() == "Paid")
                {
                    li.BackColor = Color.Green;
                    li.ForeColor = Color.White;
                }
                else if (li.SubItems[i].Text.ToString() == "Over Due")
                {
                    li.BackColor = Color.Red;
                    li.ForeColor = Color.White;
                }

            }

        }

This is the error I've got. 'InvalidArgument=Value of '7' is not valid for 'index'

Body:
Issue is in your inner for loop, you are iterating over listView1.Columns instead of itemRow.SubItems

you should update your for loop, like

foreach (ListViewItem li in listView1.Items)
    {
        for (int i = 0; i < listView1.SubItems.Count; i++)
        {                           //^^^^^^^^ this is what you need to change
            //Your code goes here
        }
    }

Or you can use foreach loop,

foreach (ListViewItem li in listView1.Items)
    {
        foreach (var subItem in li.SubItems)
        {
            if (subItem.Text.ToString() == "Pending") {
                  li.BackColor = Color.Turquoise;
              }
            else if (subItem.Text.ToString() == "Paid") {
                  li.BackColor = Color.Green;
              }
            else if (subItem.Text.ToString() == "Over Due") {
                  li.BackColor = Color.Red;
              }
        }
    li.ForeColor = Color.White;
    }

Your code is giving error might be because of
  listView1.Columns.Count is greater listView1.SubItems.Count

Bonus : li.ForeColor = Color.White; is same in all if..else conditions, you can write it outside of if..else ladder instead of writing it in each condition. Kindly check my updated code


问:
Can't pre-fetch data with resolver on angular 7
I'm having issues to pre fetch API data, but i don't seem to get it right. The route is still activated before the data is fetched. I'm trying to use a resolver service in angular 7 to load a list of users.

Here you have my route resolver on the routing module:

```<code>`const routes: Routes = [
  {
    path: 'list',
    component: ShowListComponent,
    resolve: {personList: ResolverService}
  },
  {path: 'add', component: AddComponent},
  {path: 'edit', component: EditComponent},
  {path: 'edit/:id', component: EditComponent}
];`
</code>```

This is where I'm invoking my resolver:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import {ServiceService} from '../../Service/service.service';
import { Person } from 'src/app/Model/Person';

@Component({
  selector: 'app-show-list',
  templateUrl: './show-list.component.html',
  styleUrls: ['./show-list.component.css']
})
export class ShowListComponent implements OnInit {

  persons:Person[];
  constructor(private service:ServiceService, private aRoute: ActivatedRoute ) {

  }

  ngOnInit() {
    // Invoking resolver service
    this.persons = this.aRoute.snapshot.data['personList'];

  }
}
</code>```

This is my resolver service:

```<code>import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Person } from '../Model/Person';
import { Observable} from 'rxjs';
import { ServiceService } from './service.service';

@Injectable({
  providedIn: 'root'
})
export class ResolverService implements Resolve<Person[]> {

  constructor(private _persons: ServiceService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Person[]> | Observable<never> {
    return this._persons.getPersons();
  }
}
</code>```

And finally this is my service implementation:

```<code>import { Injectable, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Person} from '../Model/Person';
import { identifierModuleUrl } from '@angular/compiler';

@Injectable({
  providedIn: 'root'
})
export class ServiceService  {

  persons: Person[];
  constructor(private http: HttpClient) { }

  List = 'http://localhost:8080/todoangular/persons';

  getPersons() {
    return this.http.get<Person[]>(this.List);
  }
}
</code>```

答:
I think what is happening is you're creating a singleton instance of your ResolverService. So that service is only being created once, with whatever state is in the ActivatedRouteSnapshot at the moment of its instantiation.

Take a look at the Angular docs and you'll notice they only decorate the resolver with Injectable() (not providedIn: 'root'). Then they pass the ResolverService into the providers array for the module.

Body:
I'm having issues to pre fetch API data, but i don't seem to get it right. The route is still activated before the data is fetched. I'm trying to use a resolver service in angular 7 to load a list of users.

Here you have my route resolver on the routing module:

`const routes: Routes = [
  {
    path: 'list',
    component: ShowListComponent,
    resolve: {personList: ResolverService}
  },
  {path: 'add', component: AddComponent},
  {path: 'edit', component: EditComponent},
  {path: 'edit/:id', component: EditComponent}
];`

This is where I'm invoking my resolver:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import {ServiceService} from '../../Service/service.service';
import { Person } from 'src/app/Model/Person';

@Component({
  selector: 'app-show-list',
  templateUrl: './show-list.component.html',
  styleUrls: ['./show-list.component.css']
})
export class ShowListComponent implements OnInit {

  persons:Person[];
  constructor(private service:ServiceService, private aRoute: ActivatedRoute ) {

  }

  ngOnInit() {
    // Invoking resolver service
    this.persons = this.aRoute.snapshot.data['personList'];

  }
}

This is my resolver service:

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Person } from '../Model/Person';
import { Observable} from 'rxjs';
import { ServiceService } from './service.service';

@Injectable({
  providedIn: 'root'
})
export class ResolverService implements Resolve<Person[]> {

  constructor(private _persons: ServiceService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Person[]> | Observable<never> {
    return this._persons.getPersons();
  }
}

And finally this is my service implementation:

import { Injectable, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Person} from '../Model/Person';
import { identifierModuleUrl } from '@angular/compiler';

@Injectable({
  providedIn: 'root'
})
export class ServiceService  {

  persons: Person[];
  constructor(private http: HttpClient) { }

  List = 'http://localhost:8080/todoangular/persons';

  getPersons() {
    return this.http.get<Person[]>(this.List);
  }
}


问:
How to get dynamic location direction on map in iphone
I am creating a map application.I want that as a person travels from his current location to some other location the same should be simultaneously plotted on the map.how is this possible.Please if anybody have source code regarding this please provide me.
Thanks.</p>

答:
The GPS of iPhone is so power full that It will automatically identify the current location.

If you want to check then just move out side your office to some other place, even though the Wi-Fi and Sim cards are not available still the GPS will show the perfect location and provides you the exact Latitude and Longitude.

You can use This Code and can get the current location using the GPS of iPhone.

Hope this is what you were needed.

ContentLicense: CC BY-SA 3.0


问:
How to fix "RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.7"?
Importing keras failed on macOS 10.14.4 failed with the error:

```<code>RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.7
</code>```

答:
I am setting up my environment (Mac OsX 10.14.4) based on this tutorial on machinelearningmastery, and when I first ran the deep_versions.py (prints versions of theano, tensorflow, and keras) I got the same RuntimeWarning as OP describes. It looks like the version that got installed when I ran:

$ conda install theano
...
$ conda install -c conda-forge tensorflow
```

<p>installed a version of tensorflow that was compiled using Python 3.6. I found this GitHub issue comment from August 2018 that claims they don't have (at the time) a native binary for Python 3.7 yet.</p>

<p>Based on AKAWei's answer in this question I ran:</p>

<pre class="lang-sh prettyprint-override"><code>$ conda update tensorflow
</code>```

and that got rid of the RuntimeWarning.

Body:
Importing keras failed on macOS 10.14.4 failed with the error:

RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.7

Body:
I am setting up my environment (Mac OsX 10.14.4) based on this tutorial on machinelearningmastery, and when I first ran the deep_versions.py (prints versions of theano, tensorflow, and keras) I got the same RuntimeWarning as OP describes. It looks like the version that got installed when I ran:

$ conda install theano
...
$ conda install -c conda-forge tensorflow

installed a version of tensorflow that was compiled using Python 3.6. I found this GitHub issue comment from August 2018 that claims they don't have (at the time) a native binary for Python 3.7 yet.

Based on AKAWei's answer in this question I ran:

$ conda update tensorflow

and that got rid of the RuntimeWarning.


问:
Iterating over JSON structure in JS
I need to set the radius of some circles, i have the following data, made up of links and nodes. I need to set the radius of the circles(nodes), to the sum of the links connected to the nodes

```<code>var data = {
    "nodes": [
        {
            "id": "s1",
            "val": 12
        },
        {
            "id": "s2",
            "val": 12
        },
        {
            "id": "s3",
            "val": 12
        },
        {
            "id": "s4",
            "val": 12
        },
        {
            "id": "s5",
            "val": 12
        },
        {
            "id": "s6",
            "val": 12
        }
    ],
    "Links": [
        {
            "n1": "s1",
            "n2": "s2",
            "amount": 10
        },
        {
            "n1": "s2",
            "n2": "s3",
            "amount": 10
        },
        {
            "n1": "s2",
            "n2": "s4",
            "amount": 10
        },
        {
            "n1": "s2",
            "n2": "s6",
            "amount": 10
        },
        {
            "n1": "s3",
            "n2": "s1",
            "amount": 10
        },
        {
            "n1": "s4",
            "n2": "s5",
            "amount": 10
        },
        {
            "n1": "s5",
            "n2": "s6",
            "amount": 10
        }
    ]
};
</code>```

i.e. ( i expect the node to be in context at this point), i have written some pseudo code  below

```<code>val1 = 0
val2 = 0
for i to len.links
  if (links.node1 = nodes.id)
    val1 = val1 + links.amount
  else if (links.node02 = nodes.id)
    val2 = val2 + links.amount
next
sum = val1 + val2
</code>```

The code below, puts the circles to the screen, i have tried various methods but allays results in what i am referring to as the white screen of death

```<code>  var w = 1200;
  var h = 800;
  var svg = d3.select("body").append("svg").attr("width",w).attr("height", h);
      var lines = svg.attr("class", "line")
  d3.json("data.json", function(error, data) {
        console.log(data);

        var circles = svg.selectAll("foo")
  .data(data.nodes)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", 20); // <- i want to put this calculation here
</code>```

I am new to JS and have no idea how to translate this in to Javascript

答:
I felt like this would take too long to explain without typing it out as d3 can be confusing, and js on its own... well anyways. I hacked this together in a jsbin and added some comments. You should be able to follow through line by line and figure out what's going on. Google the syntax if you don't understand or leave a comment and I'll try and help you reason through it.

jsbin with working example

```<code>const data = {
  "nodes": [
      {
          "id": "s1",
          "val": 12
      },
      {
          "id": "s2",
          "val": 12
      },
      {
          "id": "s3",
          "val": 12
      },
      {
          "id": "s4",
          "val": 12
      },
      {
          "id": "s5",
          "val": 12
      },
      {
          "id": "s6",
          "val": 12
      }
  ],
  "links": [
      {
          "n1": "s1",
          "n2": "s2",
          "amount": 10
      },
      {
          "n1": "s2",
          "n2": "s3",
          "amount": 10
      },
      {
          "n1": "s2",
          "n2": "s4",
          "amount": 10
      },
      {
          "n1": "s2",
          "n2": "s6",
          "amount": 10
      },
      {
          "n1": "s3",
          "n2": "s1",
          "amount": 10
      },
      {
          "n1": "s4",
          "n2": "s5",
          "amount": 10
      },
      {
          "n1": "s5",
          "n2": "s6",
          "amount": 10
      }
  ]
};

const width = window.innerWidth;
const height = window.innerHeight;
//set up the svg container
const svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('background-color', 'lightgray'); // just to see the outline

//update our data to have referable x, y positions for each node
data.nodes.forEach(n => {
  n.x = Math.random()*width; //since I don't know how you want them arranged...
  n.y = Math.random()*height;//...i'm setting them randomly
})

//draw the lines
//each line has an x1,y1 and an x2,y2
//again not sure how you wanted them connected...
//so just doing the obvious based on the link info
const lines = svg.selectAll('line')
.data(data.links)
.enter()
.append('line')
.attr('stroke', 'black')
.attr('x1', l => {
  let node = data.nodes.filter(n => n.id === l.n1)[0];
  return node.x;
})
.attr('y1', l => {
  let node = data.nodes.filter(n => n.id === l.n1)[0];
  return node.y;
})
.attr('x2', l => {
  let node = data.nodes.filter(n => n.id === l.n2)[0];
  return node.x;
})
.attr('y2', l => {
  let node = data.nodes.filter(n => n.id === l.n2)[0];
  return node.y;
})
//draw the circles
const circles = svg.selectAll('circle')
.data(data.nodes)
.enter()
.append('circle')
// basically just random colors
.attr('fill', () => d3.color('#'+Math.floor(Math.random() * Math.pow(2,32) ^ 0xffffff).toString(16).substr(-6)))
.attr('cx', n => n.x)
.attr('cy', n => n.y)
.attr('r', n => {
  //for each node, first i find all the links that contain...
  //either n1 or n2 that matches the node's id
  let rels = data.links.filter(l => n.id === l.n1 || n.id === l.n2);
  //just google the reduce fn... it'll be easier...
  let sum = rels.reduce((a,b) => a + b.amount,0);
  return sum;
});
//add labels so we know whats what
const labels = svg.selectAll('text')
.data(data.nodes)
.enter()
.append('text')
.attr('x', n => n.x)
.attr('y', n => n.y)
.attr('text-anchor', 'middle') //horizontal align
.attr('alignment-baseline', 'central') //vertical align
.text(n => n.id)
</code>```

Try updating the amounts in your links to see a dynamic update / resizing!

Title: Iterating over JSON structure in JS

Body:
I need to set the radius of some circles, i have the following data, made up of links and nodes. I need to set the radius of the circles(nodes), to the sum of the links connected to the nodes

var data = {
    "nodes": [
        {
            "id": "s1",
            "val": 12
        },
        {
            "id": "s2",
            "val": 12
        },
        {
            "id": "s3",
            "val": 12
        },
        {
            "id": "s4",
            "val": 12
        },
        {
            "id": "s5",
            "val": 12
        },
        {
            "id": "s6",
            "val": 12
        }
    ],
    "Links": [
        {
            "n1": "s1",
            "n2": "s2",
            "amount": 10
        },
        {
            "n1": "s2",
            "n2": "s3",
            "amount": 10
        },
        {
            "n1": "s2",
            "n2": "s4",
            "amount": 10
        },
        {
            "n1": "s2",
            "n2": "s6",
            "amount": 10
        },
        {
            "n1": "s3",
            "n2": "s1",
            "amount": 10
        },
        {
            "n1": "s4",
            "n2": "s5",
            "amount": 10
        },
        {
            "n1": "s5",
            "n2": "s6",
            "amount": 10
        }
    ]
};

i.e. ( i expect the node to be in context at this point), i have written some pseudo code  below

val1 = 0
val2 = 0
for i to len.links
  if (links.node1 = nodes.id)
    val1 = val1 + links.amount
  else if (links.node02 = nodes.id)
    val2 = val2 + links.amount
next
sum = val1 + val2

The code below, puts the circles to the screen, i have tried various methods but allays results in what i am referring to as the white screen of death

  var w = 1200;
  var h = 800;
  var svg = d3.select("body").append("svg").attr("width",w).attr("height", h);
      var lines = svg.attr("class", "line")
  d3.json("data.json", function(error, data) {
        console.log(data);

        var circles = svg.selectAll("foo")
  .data(data.nodes)
  .enter()
  .append("circle")
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", 20); // <- i want to put this calculation here

I am new to JS and have no idea how to translate this in to Javascript

Body:
I felt like this would take too long to explain without typing it out as d3 can be confusing, and js on its own... well anyways. I hacked this together in a jsbin and added some comments. You should be able to follow through line by line and figure out what's going on. Google the syntax if you don't understand or leave a comment and I'll try and help you reason through it.

jsbin with working example

const data = {
  "nodes": [
      {
          "id": "s1",
          "val": 12
      },
      {
          "id": "s2",
          "val": 12
      },
      {
          "id": "s3",
          "val": 12
      },
      {
          "id": "s4",
          "val": 12
      },
      {
          "id": "s5",
          "val": 12
      },
      {
          "id": "s6",
          "val": 12
      }
  ],
  "links": [
      {
          "n1": "s1",
          "n2": "s2",
          "amount": 10
      },
      {
          "n1": "s2",
          "n2": "s3",
          "amount": 10
      },
      {
          "n1": "s2",
          "n2": "s4",
          "amount": 10
      },
      {
          "n1": "s2",
          "n2": "s6",
          "amount": 10
      },
      {
          "n1": "s3",
          "n2": "s1",
          "amount": 10
      },
      {
          "n1": "s4",
          "n2": "s5",
          "amount": 10
      },
      {
          "n1": "s5",
          "n2": "s6",
          "amount": 10
      }
  ]
};

const width = window.innerWidth;
const height = window.innerHeight;
//set up the svg container
const svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.style('background-color', 'lightgray'); // just to see the outline

//update our data to have referable x, y positions for each node
data.nodes.forEach(n => {
  n.x = Math.random()*width; //since I don't know how you want them arranged...
  n.y = Math.random()*height;//...i'm setting them randomly
})

//draw the lines
//each line has an x1,y1 and an x2,y2
//again not sure how you wanted them connected...
//so just doing the obvious based on the link info
const lines = svg.selectAll('line')
.data(data.links)
.enter()
.append('line')
.attr('stroke', 'black')
.attr('x1', l => {
  let node = data.nodes.filter(n => n.id === l.n1)[0];
  return node.x;
})
.attr('y1', l => {
  let node = data.nodes.filter(n => n.id === l.n1)[0];
  return node.y;
})
.attr('x2', l => {
  let node = data.nodes.filter(n => n.id === l.n2)[0];
  return node.x;
})
.attr('y2', l => {
  let node = data.nodes.filter(n => n.id === l.n2)[0];
  return node.y;
})
//draw the circles
const circles = svg.selectAll('circle')
.data(data.nodes)
.enter()
.append('circle')
// basically just random colors
.attr('fill', () => d3.color('#'+Math.floor(Math.random() * Math.pow(2,32) ^ 0xffffff).toString(16).substr(-6)))
.attr('cx', n => n.x)
.attr('cy', n => n.y)
.attr('r', n => {
  //for each node, first i find all the links that contain...
  //either n1 or n2 that matches the node's id
  let rels = data.links.filter(l => n.id === l.n1 || n.id === l.n2);
  //just google the reduce fn... it'll be easier...
  let sum = rels.reduce((a,b) => a + b.amount,0);
  return sum;
});
//add labels so we know whats what
const labels = svg.selectAll('text')
.data(data.nodes)
.enter()
.append('text')
.attr('x', n => n.x)
.attr('y', n => n.y)
.attr('text-anchor', 'middle') //horizontal align
.attr('alignment-baseline', 'central') //vertical align
.text(n => n.id)

Try updating the amounts in your links to see a dynamic update / resizing!


问:
itext, Flying Saucer: xhtml to pdf ClassCastException
```<code>public void createPDF() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpSession session = (HttpSession) externalContext.getSession(true);
    String url = "http://localhost:8080/comap/pages/admin/student.xhtml";
    try {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        response.reset();
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition","C://user//first.pdf");
        java.io.OutputStream browserStream = response.getOutputStream();
        renderer.createPDF(browserStream);
        browserStream.close();
        session.invalidate();
    } catch (Exception ex) {
    ex.printStackTrace();
    }

    facesContext.responseComplete();
}
</code>```

here is the exception..

java.lang.ClassCastException: org.xhtmlrenderer.render.BlockBox cannot be cast to org.xhtmlrenderer.newtable.TableBox

答: This commit has fixed the issue. You can download the Class and place it in your src directory so that you don't have to rebuild the jar. </p>

Body:
public void createPDF() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpSession session = (HttpSession) externalContext.getSession(true);
    String url = "http://localhost:8080/comap/pages/admin/student.xhtml";
    try {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        renderer.layout();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        response.reset();
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition","C://user//first.pdf");
        java.io.OutputStream browserStream = response.getOutputStream();
        renderer.createPDF(browserStream);
        browserStream.close();
        session.invalidate();
    } catch (Exception ex) {
    ex.printStackTrace();
    }

    facesContext.responseComplete();
}

here is the exception..

java.lang.ClassCastException: org.xhtmlrenderer.render.BlockBox cannot be cast to org.xhtmlrenderer.newtable.TableBox


问:
How can I build entire project structure with babel cli
I have a complete project structure(in node) with most of my codes in src/ folder and some helper functions in helper/ folder both are sitting in the project root directory and I had to use

```<code>"babel src -d public/src  && babel helper -d public/helper && babel index -d public/index -w"

</code>```

in order to preserve the import and export folder structure when babel finishes the tranpilling. Is there an easier way to do this?

I have read about babel and gain some knowledge but all the tutorials i see doesn't involve this kind of scenario.

The folder project structure is preserve this way and everything works well in node though.

答:
You can do this:

```<code>babel public/folder1 public/folder2 public/folder3 ... -d -w
</code>```

Or using wildcard:

```<code>babel public/** -d -w
</code>```

Body:
I have a complete project structure(in node) with most of my codes in src/ folder and some helper functions in helper/ folder both are sitting in the project root directory and I had to use

"babel src -d public/src  && babel helper -d public/helper && babel index -d public/index -w"

in order to preserve the import and export folder structure when babel finishes the tranpilling. Is there an easier way to do this?

I have read about babel and gain some knowledge but all the tutorials i see doesn't involve this kind of scenario.

The folder project structure is preserve this way and everything works well in node though.

Body:
You can do this:

babel public/folder1 public/folder2 public/folder3 ... -d -w

Or using wildcard:

babel public/** -d -w


问:
How to scroll two pdf side by side synchronously in html?
I am creating a side by side view in html to compare two pdfs , i tried to use pdfjs to display two pdfs side by side but dropped the ide , currently i have this code :

```<code><div class="row">
        <div class="col-md-6">
            <object data="uploaded\\1.pdf" id="pdf1" onscroll="scroll1();" type="application/pdf" width="100%" height="100%">
            </object>
        </div>
       <div class="col-md-6">
            <object data="uploaded\\2.pdf" id="pdf2" onscroll="scroll2();"
            type="application/pdf" width="100%" height="100%">
            </object>
        </div>
 </div>

</code>```

it did display the pdf correctly side by side but there scroll isn't sync.

For scrolling i have used on scroll event and tried to print something in console just to check whether onscoll event is working or not but no luck , also i tried  iframe  in place of  object  , but issue remains , is there any way to display pdf side by side and sync there scrolls.?

Any other approach rather than this is also welcome.

答:
I solved my issue with this :

```<code>$("#pdf1").on('load', function() {
  $("#pdf1").contents().find("#viewerContainer").on('scroll', function() {
    $("#pdf2").contents().find("#viewerContainer").scrollTop($(this).scrollTop());
  });
});

$("#pdf2").on('load', function() {
  $("#pdf2").contents().find("#viewerContainer").on('scroll', function() {
    $("#pdf1").contents().find("#viewerContainer").scrollTop($(this).scrollTop());
  });
});
</code>```

I removed the scroll function calling on onScroll of iFrame which doesn't work and added on load function,then i added the scroll function on child of the iFrame and sync the iFrame's child's it.

Body:
I am creating a side by side view in html to compare two pdfs , i tried to use pdfjs to display two pdfs side by side but dropped the ide , currently i have this code :

            <object data="uploaded\\1.pdf" id="pdf1" onscroll="scroll1();" type="application/pdf" width="100%" height="100%">
            </object>

            <object data="uploaded\\2.pdf" id="pdf2" onscroll="scroll2();"
            type="application/pdf" width="100%" height="100%">
            </object>

it did display the pdf correctly side by side but there scroll isn't sync.

For scrolling i have used on scroll event and tried to print something in console just to check whether onscoll event is working or not but no luck , also i tried  iframe  in place of  object  , but issue remains , is there any way to display pdf side by side and sync there scrolls.?

Any other approach rather than this is also welcome.

Body:
I solved my issue with this :

$("#pdf1").on('load', function() {
  $("#pdf1").contents().find("#viewerContainer").on('scroll', function() {
    $("#pdf2").contents().find("#viewerContainer").scrollTop($(this).scrollTop());
  });
});

$("#pdf2").on('load', function() {
  $("#pdf2").contents().find("#viewerContainer").on('scroll', function() {
    $("#pdf1").contents().find("#viewerContainer").scrollTop($(this).scrollTop());
  });
});

I removed the scroll function calling on onScroll of iFrame which doesn't work and added on load function,then i added the scroll function on child of the iFrame and sync the iFrame's child's it.


问:
Magnify search box similar to that on Apple.com
If you go to http://apple.com and click in the search box, you'll notice it grows/magnifies onfocus, and onblur it collapses back to it's original state.

I'm wondering if there's a jquery plugin or similar to do this job easily.

I don't want to use the JS that's on the Apple website since it's not fully cross browser. I also don't have time to roll my own. If there's nothing prebuilt, that's ok, but if anyone knows of anything pre-made, I'd be very grateful.

答:
I guess you want something like this.It is working in IE,firfox,chrome.I didnt check for others

```<code>$('input').focus(function() {
         $(this).css({'width': '50px'});
});

$('input').blur(function() {
         $(this).css({'width': '100px'});
 });
</code>```

Similarly you could use background-color property to toggle between color

----- Edit by OP ---

I marked this as answer, however I did modify it to be a lot more like the Apple website.

```<code>$('input').focus(function() {
         $(this).animate({width: 150}, 'slow');
});

$('input').blur(function() {
         $(this).animate({width: 100}, 'slow');
 });
</code>```

Body:
I guess you want something like this.It is working in IE,firfox,chrome.I didnt check for others

$('input').focus(function() {
         $(this).css({'width': '50px'});
});

$('input').blur(function() {
         $(this).css({'width': '100px'});
 });

Similarly you could use background-color property to toggle between color

----- Edit by OP ---

I marked this as answer, however I did modify it to be a lot more like the Apple website.

$('input').focus(function() {
         $(this).animate({width: 150}, 'slow');
});

$('input').blur(function() {
         $(this).animate({width: 100}, 'slow');
 });


问:
Geosphere/dplyr: create matrix of distance between coordinates
I want to create a "matrix" of the distance between multiple coordinates with each other. Preferably using dplyr/geosphere. I already saw that the geosphere package offers this. I managed to create the distance between two vectors but I have difficulties creating the full matrix.

This is the sample table with multiple coordinates.

```<code>df <- data.frame(latitude = c(49.48609,-8.14671,11.28625),
                 longitude = c(8.463678,143.05793,-11.18285))

  latitude  longitude
1 49.48609   8.463678
2 -8.14671 143.057930
3 11.28625 -11.182850
</code>```

And this is the output I am looking for:

```<code>  latitude    longitude    distance-latlon1    distance-latlon2   distance-latlon3
1 49.48609     8.463678    NA                  *latlon2><latlon1  *latlon3><latlon1
2 -8.14671   143.057930    *latlon1><latlon2   NA                 *latlon3><latlon2
3 11.28625   -11.182850    *latlon1><latlon3   *latlon2><latlon3  NA
</code>```

I tried out using geosphere but I only found a way to calculate the distance between two columns (which in this snippet results in a 0).

```<code>library(geosphere)
df$distance <- distVincentyEllipsoid(df[,c('longitude','latitude')],
                                     df[,c('longitude','latitude')])
</code>```

答:
Instead of distVincentyEllipsoid I would use the faster and more precise distGeo

```<code>df = df[,2:1] # the order should be longitude, latitude!
distm(df, df, distGeo)
</code>```

or

```<code>library(raster)
d <- pointDistance(df)
</code>```

perhaps followed by

```<code>as.matrix(as.dist(d))
</code>```

Body:
I want to create a "matrix" of the distance between multiple coordinates with each other. Preferably using dplyr/geosphere. I already saw that the geosphere package offers this. I managed to create the distance between two vectors but I have difficulties creating the full matrix.

This is the sample table with multiple coordinates.

df <- data.frame(latitude = c(49.48609,-8.14671,11.28625),
                 longitude = c(8.463678,143.05793,-11.18285))

  latitude  longitude
1 49.48609   8.463678
2 -8.14671 143.057930
3 11.28625 -11.182850

And this is the output I am looking for:

  latitude    longitude    distance-latlon1    distance-latlon2   distance-latlon3
1 49.48609     8.463678    NA                  *latlon2><latlon1  *latlon3><latlon1
2 -8.14671   143.057930    *latlon1><latlon2   NA                 *latlon3><latlon2
3 11.28625   -11.182850    *latlon1><latlon3   *latlon2><latlon3  NA

I tried out using geosphere but I only found a way to calculate the distance between two columns (which in this snippet results in a 0).

library(geosphere)
df$distance <- distVincentyEllipsoid(df[,c('longitude','latitude')],
                                     df[,c('longitude','latitude')])

Body:
Instead of distVincentyEllipsoid I would use the faster and more precise distGeo

df = df[,2:1] # the order should be longitude, latitude!
distm(df, df, distGeo)

or

library(raster)
d <- pointDistance(df)

perhaps followed by

as.matrix(as.dist(d))


问:
The image doesn´t appear in the website. Explorer path is already checked
The image which i want to have in the header doesn´t appear.

I checked the explorer path and capital letters. I already typed the whole path.

Image doesn´t appear.

答:
you need a slash before graphics/examplelogo.png. So, your code should be:

```<code><header>
    <img src="/graphics/examplelogo.png" alt="Logo" height="150" width="600">
</header>
</code>```

Body:
you need a slash before graphics/examplelogo.png. So, your code should be:

<header>
    <img src="/graphics/examplelogo.png" alt="Logo" height="150" width="600">
</header>


问:
How do I get the Podio app item name found in App Settings?
How can I get the App Item name in this picture in C#?

答:
Have you looked into Podio API?

Applications: Get app

```<code>GET /app/{app_id}
</code>```

Gets the definition of an app and can include configuration and fields. This method will always return the latest revision of the app definition.

The result (micro result):

```<code>{
  "app_id": The id of the app,
  "name": The name of the app,
  "item_name": The name of each item in an app,
  "icon": The name of the icon used to represent the app
}
</code>```

All you need is to make a simple REST request with HttpClient or start using Podio-dotnet NUGET package.

```<code>using PodioAPI;

var podio = new Podio(clientId, clientSecret);
podio.AuthenticateWithApp(appId, appSecret);

var application = await podio.ApplicationService.GetApp(appId, "micro");
</code>```

ItemName can be accessed via application.ItemName.

For more information, this is the signature of the method GetApp.

```<code>/// <summary>
///     Gets the definition of an app and can include configuration and fields.
///     <para>Podio API Reference: https://developers.podio.com/doc/applications/get-app-22349 </para>
/// </summary>
/// <param name="appId"></param>
/// <param name="view">
///     The type of the view of the app requested. Can be either "full", "short", "mini" or "micro". Default
///     value: full
/// </param>
/// <param name="fields">
///     This parameter can be used to include more or less content in responses than the defaults provided by Podio.
///     E.g. space.view(full)
/// </param>
/// <returns></returns>
public async Task<Application> GetApp(int appId, string view = "full", string fields = null)
</code>```

If you need to know what other fields Application class has, take a look on its source.

Body:
Have you looked into Podio API?

Applications: Get app

GET /app/{app_id}

Gets the definition of an app and can include configuration and fields. This method will always return the latest revision of the app definition.

The result (micro result):

{
  "app_id": The id of the app,
  "name": The name of the app,
  "item_name": The name of each item in an app,
  "icon": The name of the icon used to represent the app
}

All you need is to make a simple REST request with HttpClient or start using Podio-dotnet NUGET package.

using PodioAPI;

var podio = new Podio(clientId, clientSecret);
podio.AuthenticateWithApp(appId, appSecret);

var application = await podio.ApplicationService.GetApp(appId, "micro");

ItemName can be accessed via application.ItemName.

For more information, this is the signature of the method GetApp.

/// <summary>
///     Gets the definition of an app and can include configuration and fields.
///     <para>Podio API Reference: https://developers.podio.com/doc/applications/get-app-22349 </para>
/// </summary>
/// <param name="appId"></param>
/// <param name="view">
///     The type of the view of the app requested. Can be either "full", "short", "mini" or "micro". Default
///     value: full
/// </param>
/// <param name="fields">
///     This parameter can be used to include more or less content in responses than the defaults provided by Podio.
///     E.g. space.view(full)
/// </param>
/// <returns></returns>
public async Task<Application> GetApp(int appId, string view = "full", string fields = null)

If you need to know what other fields Application class has, take a look on its source.


问:
IceCast Stats on website
I came across this php script to pull IceCast stats (listeners,current song) from my streaming server.

It was published here

Use PHP to show Icecast2 statistics

```<code><?php

/*
 * SCRIPT CONFIGURATIONS
*/
$SERVER = 'http://myserver.com:8000'; //URL TO YOUR ICECAST SERVER
$STATS_FILE = '/status.xsl'; //PATH TO STATUS.XSL PAGE YOU CAN SEE IN YOUR BROWSER (LEAVE BLANK UNLESS DIFFERENT)

///////////////////// END OF CONFIGURATION --- DO NOT EDIT BELOW THIS LINE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//create a new curl resource
$ch = curl_init();

//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);

//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

//$output = our stauts.xsl file
$output = curl_exec($ch);

//close curl resource to free up system resources
curl_close($ch);

//build array to store our radio stats for later use
$radio_info = array();
$radio_info['server'] = $SERVER;
$radio_info['title'] = '';
$radio_info['description'] = '';
$radio_info['content_type'] = '';
$radio_info['mount_start'] = '';
$radio_info['bit_rate'] = '';
$radio_info['listeners'] = '';
$radio_info['most_listeners'] = '';
$radio_info['genre'] = '';
$radio_info['url'] = '';
$radio_info['now_playing'] = array();
   $radio_info['now_playing']['artist'] = '';
   $radio_info['now_playing']['track'] = '';

//loop through $ouput and sort into our different arrays
$temp_array = array();

$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');

if(preg_match_all("/$search_for/siU",$output,$matches)) {
   foreach($matches[0] as $match) {
      $to_push = str_replace($search_td,'',$match);
      $to_push = trim($to_push);
      array_push($temp_array,$to_push);
   }
}

//sort our temp array into our ral array
$radio_info['title'] = $temp_array[0];
$radio_info['description'] = $temp_array[1];
$radio_info['content_type'] = $temp_array[2];
$radio_info['mount_start'] = $temp_array[3];
$radio_info['bit_rate'] = $temp_array[4];
$radio_info['listeners'] = $temp_array[5];
$radio_info['most_listeners'] = $temp_array[6];
$radio_info['genre'] = $temp_array[7];
$radio_info['url'] = $temp_array[8];

$x = explode(" - ",$temp_array[9]);
$radio_info['now_playing']['artist'] = $x[0];
$radio_info['now_playing']['track'] = $x[1];

?>
</code>```

Dose someone know where to insert the script?

答:
We download the stats in xml then process the stats daily buy importing to sql

```<code>// download icecast stats
$username = '';
$password = '';
$url = 'localhost:8000/stats';
$file = 'h:\\stream\\stats\\' . date('Ymd_His') . '.xml';
</code>```

c:\\stream\\curl.exe --user $username:$password $url -o $file;

```<code>//Process to sql by looping through the stats folder and get filenames...

foreach(glob($path . "*.xml") as $filename) {
   $content = file_get_contents($filename);
   $filename = substr($filename, strlen($path), -4);
    process($db, $filename, $content);
  }
   function process($db, $filename, $content) {
    $xml = new SimpleXMLElement($content);
    if(!preg_match('/^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$/', $filename,
    $date)) throw new Exception('Filename does not look like a date.');

foreach($xml->source as $source) {
    $date_sql = $db->real_escape_string(sprintf("%04d-%02d-%02d %02d:%02d:%02d",
    $date[1], $date[2], $date[3], $date[4], $date[5], $date[6]));
    $stream_sql = $db->real_escape_string($source->genre);
    $title_sql = $db->real_escape_string($source->title);
    $listeners_sql = (int)$source->listeners;

    $sql = "REPLACE INTO song_stats SET date_and_time = '$date_sql', stream =
   '$stream_sql', title = '$title_sql', listeners = $listeners_sql";

    $db->query($sql);
   }

 }
</code>```

Title: IceCast Stats on website

Body:
I came across this php script to pull IceCast stats (listeners,current song) from my streaming server.

It was published here

Use PHP to show Icecast2 statistics

<?php

/*
 * SCRIPT CONFIGURATIONS
*/
$SERVER = 'http://myserver.com:8000'; //URL TO YOUR ICECAST SERVER
$STATS_FILE = '/status.xsl'; //PATH TO STATUS.XSL PAGE YOU CAN SEE IN YOUR BROWSER (LEAVE BLANK UNLESS DIFFERENT)

///////////////////// END OF CONFIGURATION --- DO NOT EDIT BELOW THIS LINE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//create a new curl resource
$ch = curl_init();

//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);

//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

//$output = our stauts.xsl file
$output = curl_exec($ch);

//close curl resource to free up system resources
curl_close($ch);

//build array to store our radio stats for later use
$radio_info = array();
$radio_info['server'] = $SERVER;
$radio_info['title'] = '';
$radio_info['description'] = '';
$radio_info['content_type'] = '';
$radio_info['mount_start'] = '';
$radio_info['bit_rate'] = '';
$radio_info['listeners'] = '';
$radio_info['most_listeners'] = '';
$radio_info['genre'] = '';
$radio_info['url'] = '';
$radio_info['now_playing'] = array();
   $radio_info['now_playing']['artist'] = '';
   $radio_info['now_playing']['track'] = '';

//loop through $ouput and sort into our different arrays
$temp_array = array();

$search_for = "]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('','	');

if(preg_match_all("/$search_for/siU",$output,$matches)) {
   foreach($matches[0] as $match) {
      $to_push = str_replace($search_td,'',$match);
      $to_push = trim($to_push);
      array_push($temp_array,$to_push);
   }
}

//sort our temp array into our ral array
$radio_info['title'] = $temp_array[0];
$radio_info['description'] = $temp_array[1];
$radio_info['content_type'] = $temp_array[2];
$radio_info['mount_start'] = $temp_array[3];
$radio_info['bit_rate'] = $temp_array[4];
$radio_info['listeners'] = $temp_array[5];
$radio_info['most_listeners'] = $temp_array[6];
$radio_info['genre'] = $temp_array[7];
$radio_info['url'] = $temp_array[8];

$x = explode(" - ",$temp_array[9]);
$radio_info['now_playing']['artist'] = $x[0];
$radio_info['now_playing']['track'] = $x[1];

?>

Dose someone know where to insert the script?

Body:
We download the stats in xml then process the stats daily buy importing to sql

// download icecast stats
$username = '';
$password = '';
$url = 'localhost:8000/stats';
$file = 'h:\\stream\\stats\\' . date('Ymd_His') . '.xml';

c:\\stream\\curl.exe --user $username:$password $url -o $file;

//Process to sql by looping through the stats folder and get filenames...

foreach(glob($path . "*.xml") as $filename) {
   $content = file_get_contents($filename);
   $filename = substr($filename, strlen($path), -4);
    process($db, $filename, $content);
  }
   function process($db, $filename, $content) {
    $xml = new SimpleXMLElement($content);
    if(!preg_match('/^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$/', $filename,
    $date)) throw new Exception('Filename does not look like a date.');

foreach($xml->source as $source) {
    $date_sql = $db->real_escape_string(sprintf("%04d-%02d-%02d %02d:%02d:%02d",
    $date[1], $date[2], $date[3], $date[4], $date[5], $date[6]));
    $stream_sql = $db->real_escape_string($source->genre);
    $title_sql = $db->real_escape_string($source->title);
    $listeners_sql = (int)$source->listeners;

    $sql = "REPLACE INTO song_stats SET date_and_time = '$date_sql', stream =
   '$stream_sql', title = '$title_sql', listeners = $listeners_sql";

    $db->query($sql);
   }

 }


问:
How to load firestore subcollection to redux store?
I'm having trouble loading firestore subcollection in redux store. I'm trying to load respective subcollection inside the child component.

The component structure looks like this:

Dashboard
--Project list
--project summary
--comments

I have loaded collection named Projects using firestoreConnect inside Dashboard component passing data to Project list mapping data to Project Summary. comments is a child component of project summary

My firestore collection structure looks like this:

Projects
--project1
--comments

Dashboard:

```<code>class Dashboard extends Component {
  render() {
    const { projects, auth, notifications } = this.props
    if (!auth.uid) return <Redirect to='/signin' />
    return(
      <div className="dashboard container">
        <div className="row">
          <div className="col s12 m8 offset-m2 l8">
            <ProjectList projects={projects} />
          </div>
          <div className="col s12 offset-m1 hide-on-med-and-down l4">
            <Notification notifications={notifications} />
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  // console.log("ref: ",state)
  return {
    projects: state.firestore.ordered.projects,
    initials: state.firebase.profile.initials,
    auth: state.firebase.auth,
    notifications: state.firestore.ordered.notifications
  }
}

export default compose (
  connect(mapStateToProps),
  firestoreConnect([
    { collection: 'projects', orderBy: ['createdAt', 'desc'] },
    { collection: 'notifications', limit: 3, orderBy: ['time', 'desc'] }
  ])
)(Dashboard)
</code>```

Project list Component:

```<code>const ProjectList = ({ projects }) => {
  return(
    <div className="project-list section">
      {projects && projects.map((project) => {
        return(
          <div key={project.id}>
              <ProjectSummary project={project}/>
          </div>
        )
      })}
    </div>
  )
}

export default ProjectList
</code>```

Project summry:

```<code>const ProjectSummary = ({ project }) => {
    return(
      <div className="card z-depth-0 project-summary show-up post">

        <div className="name">
          <div className="">
            <span className="btn btn-floating z-depth-0 black user-indicator">
              {project.authorFirstName && project.authorFirstName[0]}{project.authorSecondName && project.authorSecondName[0]}
            </span>
             <span> {project.authorFirstName {project.authorSecondName} </span>
             <span className="right options"> <i className="material-icons">more_vert</i> </span>
          </div>
        </div>

        <div className="card-image">
          <img src={project.imageUrl} alt="art" />
          <PostCredits />
        </div>

        <div className="card-reveal">
          <Comments id={project.id} />
        </div>

        <div className="card-content">
          <Link to={'/projectdetails/' + project.id} className="black-text">
            <p className="post-title"> {project.title} </p>
          </Link>
          <p className="grey-text lighten-3 load-comments activator"> Load comments </p>
          <p className="grey-text date-format">
            {project.createdAt && project.createdAt
              .toDate()
              .toLocaleDateString('indian', {
                year: "numeric", month: "short", day: "numeric"
            })}
          </p>
        </div>
        <div className="add-comment">
          <AddComment projectId={project.id} />
        </div>

      </div>
    )
}

export default ProjectSummary
</code>```

Comment:

```<code>const Comment = (props) => {
    return(
      <div>
        <div className="loaded-comments">
          <span className="card-title grey-text text-darken-4"> Comments <i className="material-icons right">close</i> </span>
          <p> <span className="commentor"> Joe </span>  </p>
        </div>
      </div>
    )
}

const mapStateToProps = (state, ownProps) => {
  console.log("state: ", state)
  return {

  }
}

export default compose (
  connect(mapStateToProps),
  firestoreConnect(props => {
    return [
      { collection: 'projects',
        doc: props.id,
        subcollections: [
          {
            collection: 'comments'
          }
        ]
      }
    ]
  })
)(Comment)
</code>```

Expected Result:

*Want to load Project collection's subcollection named Comments

Actual Result:

*No error occurs but still no data is loaded.

Thanks in advance!

答:
There is a possibility that you just don't see that sub-collection.
If you look under in your browser console, navigate to firebase > ordered > prjoects > comments. you should be able to see an array of your comment

Example:

```<code>|-firestore
|--ordered:
|---projects: Array(1)
|----0:
|-----id: *uid*
|------comments: Array(2)
|-------0: {*comment details*}
|-------1: {*comment details*}
|------length: 2
|-----__proto__: Array(0)
</code>```

After you can map your data based on your key.

```<code>const mapStateToProps = (state) => {
  return {
    projects: state.firestore.ordered.projects.comments,
  }
}
</code>```

Once connected you will be able to use your data.

Body:
I'm having trouble loading firestore subcollection in redux store. I'm trying to load respective subcollection inside the child component.

The component structure looks like this:

Dashboard
--Project list
--project summary
--comments

I have loaded collection named Projects using firestoreConnect inside Dashboard component passing data to Project list mapping data to Project Summary. comments is a child component of project summary

My firestore collection structure looks like this:

Projects
--project1
--comments

Dashboard:

class Dashboard extends Component {
  render() {
    const { projects, auth, notifications } = this.props
    if (!auth.uid) return <Redirect to='/signin' />
    return(

            <ProjectList projects={projects} />

            <Notification notifications={notifications} />

    )
  }
}

const mapStateToProps = (state) => {
  // console.log("ref: ",state)
  return {
    projects: state.firestore.ordered.projects,
    initials: state.firebase.profile.initials,
    auth: state.firebase.auth,
    notifications: state.firestore.ordered.notifications
  }
}

export default compose (
  connect(mapStateToProps),
  firestoreConnect([
    { collection: 'projects', orderBy: ['createdAt', 'desc'] },
    { collection: 'notifications', limit: 3, orderBy: ['time', 'desc'] }
  ])
)(Dashboard)

Project list Component:

const ProjectList = ({ projects }) => {
  return(

      {projects && projects.map((project) => {
        return(

              <ProjectSummary project={project}/>

        )
      })}

  )
}

export default ProjectList

Project summry:

const ProjectSummary = ({ project }) => {
    return(

              {project.authorFirstName && project.authorFirstName[0]}{project.authorSecondName && project.authorSecondName[0]}

              {project.authorFirstName {project.authorSecondName}
              more_vert

          <PostCredits />

          <Comments id={project.id} />

          <Link to={'/projectdetails/' + project.id} className="black-text">

 {project.title}

          </Link>

 Load comments

            {project.createdAt && project.createdAt
              .toDate()
              .toLocaleDateString('indian', {
                year: "numeric", month: "short", day: "numeric"
            })}

          <AddComment projectId={project.id} />

    )
}

export default ProjectSummary

Comment:

const Comment = (props) => {
    return(

           Comments close

  Joe

    )
}

const mapStateToProps = (state, ownProps) => {
  console.log("state: ", state)
  return {

  }
}

export default compose (
  connect(mapStateToProps),
  firestoreConnect(props => {
    return [
      { collection: 'projects',
        doc: props.id,
        subcollections: [
          {
            collection: 'comments'
          }
        ]
      }
    ]
  })
)(Comment)

Expected Result:

*Want to load Project collection's subcollection named Comments

Actual Result:

*No error occurs but still no data is loaded.

Thanks in advance!

Body:
There is a possibility that you just don't see that sub-collection.
If you look under in your browser console, navigate to firebase > ordered > prjoects > comments. you should be able to see an array of your comment

Example:

|-firestore
|--ordered:
|---projects: Array(1)
|----0:
|-----id: *uid*
|------comments: Array(2)
|-------0: {*comment details*}
|-------1: {*comment details*}
|------length: 2
|-----__proto__: Array(0)

After you can map your data based on your key.

const mapStateToProps = (state) => {
  return {
    projects: state.firestore.ordered.projects.comments,
  }
}

Once connected you will be able to use your data.


问:
how to repeat table header in a new page-break
I have a dynamic table in my web page that sometimes contains lots of rows. I made the page-break after 22 rows. i need to repeat certain table (info table, see image) in a new page. how do i do that?

image
https://i.ibb.co/LN8gVbD/Screen-Shot-2019-05-26-at-03-34-26.png

the other thing, I'm unable to get the page-break in Chrome. it's only working in Firefox, how to fix that in Chrome?

```<code> <style type="text/css">
    #receipt-data { font-size: 12px; }
        @media print {
                tr.page-break{
                page-break-inside: avoid;;
                page-break-before:always;
            }
            @page {
              size:portrait;
                }
        }
    </style>

    <div id="receipt-data">
<table class="table hed">
<thead style="text-align:center;">
<tr style="text-align:center;">
    <th colspan="1">Name</th>
<th colspan="2">{{$customer_data->name}}i</th>
<th colspan="1">Customer Tax No</th>
<th colspan="2">{{$customer_data->tax_no}}</th>
</tr>
</thead>
</table>

 <table class="table table-bordered" style="text-align:center;">
            <thead>
                <tr>
                    <th>S</th>
                    <th>Item Code</th>
                    <th>Description</th>
                    <th>Unit</th>
                    <th>Unit Price</th>
                    <th>Qty</th>
                    <th>Amount($)
                    </th>
                </tr>
            </thead>
            <tbody>

                @foreach($product_sale_data as $key=>$product_sale_data)
                @php
          $product_data = \App\Product::find($product_sale_data->product_id);
                    if($product_data->sale_unit_id)
      $unit = \App\Unit::find($product_data->sale_unit_id)->unit_name;
                    else
                        $unit = 'N/A';
                @endphp
    <tr class =  @if  ( $key % 22 == 0 && $key ) "page-break"   @endif>
 <td>{{$key+1}}</td>
  <td>{{$product_data->code}}</td>
  <td>{{$product_data->name}}</td>
 <td>{{$unit}}</td>
<td>{{number_format($product_sale_data->total / $product_sale_data->qty, 2)}}</td>
                    <td>{{$product_sale_data->qty}}</td>
                    <td>{{number_format($product_sale_data->total, 2)}}</td>
                @endforeach
                 <br>
</code>```

答:
NOTE: If $key value start with 0 then below
 is not need but if $key starts with 1 then below is needed for one time no need to loop in foreach

```<code>    <thead>
        <tr>
            <th>S</th>
            <th>Item Code</th>
            <th>Description</th>
            <th>Unit</th>
            <th>Unit Price</th>
            <th>Qty</th>
            <th>Amount($)
            </th>
        </tr>
    </thead>
    @foreach($product_sale_data as $key=>$product_sale_data)
        @if  ( $key % 22 == 0 && $key ) // so here every 22 rows after this will go
            <thead>
                <tr>
                    <th>S</th>
                    <th>Item Code</th>
                    <th>Description</th>
                    <th>Unit</th>
                    <th>Unit Price</th>
                    <th>Qty</th>
                    <th>Amount($)
                    </th>
                </tr>
            </thead>
        @endif
        <tbody>
            @php
            $product_data = \App\Product::find($product_sale_data->product_id);
                if($product_data->sale_unit_id)

            ...continue your code
</code>```

Body:
I have a dynamic table in my web page that sometimes contains lots of rows. I made the page-break after 22 rows. i need to repeat certain table (info table, see image) in a new page. how do i do that?

image
https://i.ibb.co/LN8gVbD/Screen-Shot-2019-05-26-at-03-34-26.png

the other thing, I'm unable to get the page-break in Chrome. it's only working in Firefox, how to fix that in Chrome?

    Name
{{$customer_data->name}}i
Customer Tax No
{{$customer_data->tax_no}}

                    S
                    Item Code
                    Description
                    Unit
                    Unit Price
                    Qty
                    Amount($)

                @foreach($product_sale_data as $key=>$product_sale_data)
                @php
          $product_data = \App\Product::find($product_sale_data->product_id);
                    if($product_data->sale_unit_id)
      $unit = \App\Unit::find($product_data->sale_unit_id)->unit_name;
                    else
                        $unit = 'N/A';
                @endphp

 {{$key+1}}
  {{$product_data->code}}
  {{$product_data->name}}
 {{$unit}}
{{number_format($product_sale_data->total / $product_sale_data->qty, 2)}}
                    {{$product_sale_data->qty}}
                    {{number_format($product_sale_data->total, 2)}}
                @endforeach

Body:
NOTE: If $key value start with 0 then below <thead> is not need but if $key starts with 1 then below is needed for one time no need to loop in foreach

    <thead>
        <tr>
            <th>S</th>
            <th>Item Code</th>
            <th>Description</th>
            <th>Unit</th>
            <th>Unit Price</th>
            <th>Qty</th>
            <th>Amount($)
            </th>
        </tr>
    </thead>
    @foreach($product_sale_data as $key=>$product_sale_data)
        @if  ( $key % 22 == 0 && $key ) // so here every 22 rows after this will go
            <thead>
                <tr>
                    <th>S</th>
                    <th>Item Code</th>
                    <th>Description</th>
                    <th>Unit</th>
                    <th>Unit Price</th>
                    <th>Qty</th>
                    <th>Amount($)
                    </th>
                </tr>
            </thead>
        @endif
        <tbody>
            @php
            $product_data = \App\Product::find($product_sale_data->product_id);
                if($product_data->sale_unit_id)

            ...continue your code


问:
How to use bitwise flags in Python
```<code>from enum import Enum

class InputTypes(Enum):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = 0b00000001,
    MOUSE_BUTTONS = 0b00000010,
    MOUSE_MOVE = 0b00000100,
    ALL = 0b11111111

if __name__ == "__main__":
    x = (InputTypes.KEYBOARD | InputTypes.MOUSE_BUTTONS)
</code>```

I am getting an error:

```<code>TypeError: unsupported operand type(s) for |: 'InputTypes' and 'InputTypes'
</code>```

How do I properly define some flags and use them, in python 2.7 and in python3?

答:
For Python 2 you want to use aenum (Advanced Enum)1.  If the numeric values are not important you can use Flag:

```<code>from aenum import Flag, auto

class InputTypes(Flag):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = auto()
    MOUSE_BUTTONS = auto()
    MOUSE_MOVE = auto()
    ALL = KEYBOARD | MOUSE_BUTTONS | MOUSE_MOVE
</code>```

If the values are important (meaning you'll be using them as integers), then use IntFlag instead.

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

Title: How to use bitwise flags in Python

Body:
from enum import Enum

class InputTypes(Enum):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = 0b00000001,
    MOUSE_BUTTONS = 0b00000010,
    MOUSE_MOVE = 0b00000100,
    ALL = 0b11111111

if __name__ == "__main__":
    x = (InputTypes.KEYBOARD | InputTypes.MOUSE_BUTTONS)

I am getting an error:

TypeError: unsupported operand type(s) for |: 'InputTypes' and 'InputTypes'

How do I properly define some flags and use them, in python 2.7 and in python3?

Body:
For Python 2 you want to use aenum (Advanced Enum)1.  If the numeric values are not important you can use Flag:

from aenum import Flag, auto

class InputTypes(Flag):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = auto()
    MOUSE_BUTTONS = auto()
    MOUSE_MOVE = auto()
    ALL = KEYBOARD | MOUSE_BUTTONS | MOUSE_MOVE

If the values are important (meaning you'll be using them as integers), then use IntFlag instead.

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.


问:
jQuery load() is not loading content properly
I am trying to load new links without page refresh using html5 window.history.pushState() function.

Everything works good but when I open my inspect element in Chrome or in Firefox the head tag and body tag are missing. I don't know why.

Here is my code:

```<code>function goto(event,el)
{
    url=el.href;
    event.preventDefault();
    window.history.pushState('','',url);
    $('html').load(url);
}
</code>```

and the new loading page is this:-

```<code><html>
<head>
<script type="text/javascript" src="http://localhost/js/jquery.js"></script>
</head>
<body>
<div id="menu">
<a href="menu1.php">Menu1</a>
<a href="menu2.php">Menu2</a>
</div>
</body>
</html>
</code>```

I really want to navigate through pages without page refresh properly.

How to solve this issue using history.pushstate() function or is there any other way.

My main motive is to achieve speed like Facebook or Twitter.

答:
Load your page by AJAX like this and use replaceWith:

```<code>$.get( url, function( data ) {
    //data is the new page html
    document.open();
    document.write(data);
    document.close();
});
</code>```

UPDATE

I highly recommend using this library from Github instead:

smoothState

Body:
I am trying to load new links without page refresh using html5 window.history.pushState() function.

Everything works good but when I open my inspect element in Chrome or in Firefox the head tag and body tag are missing. I don't know why.

Here is my code:

function goto(event,el)
{
    url=el.href;
    event.preventDefault();
    window.history.pushState('','',url);
    $('html').load(url);
}

and the new loading page is this:-

Menu1
Menu2

I really want to navigate through pages without page refresh properly.

How to solve this issue using history.pushstate() function or is there any other way.

My main motive is to achieve speed like Facebook or Twitter.

Body:
Load your page by AJAX like this and use replaceWith:

$.get( url, function( data ) {
    //data is the new page html
    document.open();
    document.write(data);
    document.close();
});

UPDATE

I highly recommend using this library from Github instead:

smoothState


问:
how to fix arguments '{'pk'}' not found. 1 pattern(s) tried: ['post/(?P<slug>[^/]+)/$'] in PostDetailView
I use slug in the post url, but when sending a post update I get an error

I have this error in views.py return super().form_valid(form)

Reverse for 'postdetail' with keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['post/(?P[^/]+)/$']

models.py

```<code>
class Post(models.Model):
    title = models.CharField(max_length=60)
    slug = models.SlugField(max_length=60, unique=True)
    first_image = models.ImageField(null=True, upload_to='post_image')
    content = RichTextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        super().save(*args,**kwargs)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('postdetail', kwargs={'pk': self.pk})

def post_slug(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug =  unique_slug_generator(instance)

pre_save.connect(post_slug, sender=Post)

</code>```

views.py

```<code>.........

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'first_image', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
</code>```

urls.py

```<code>from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import (
    PostListView,
    PostDetailView,
    PostCreateView,
    PostUpdateView,
    PostDeleteView,
    UserPostListView
)
from . import views

urlpatterns = [
......

    path('post/<slug>/update/', PostUpdateView.as_view(), name='postupdate'),
    path('post/<slug>/', PostDetailView.as_view(), name='postdetail'),

......
]
</code>```

答:
The postdetail url only accepts the argument named slug. While you're passing it pk. Obviously it will fail.

Change this:

```<code>return reverse('postdetail', kwargs={'pk': self.pk})
</code>```

to this:

```<code>return reverse('postdetail', kwargs={'slug': self.slug})
</code>```

Body:
I use slug in the post url, but when sending a post update I get an error

I have this error in views.py return super().form_valid(form)

Reverse for 'postdetail' with keyword arguments '{'pk': 2}' not found. 1 pattern(s) tried: ['post/(?P[^/]+)/$']

models.py

class Post(models.Model):
    title = models.CharField(max_length=60)
    slug = models.SlugField(max_length=60, unique=True)
    first_image = models.ImageField(null=True, upload_to='post_image')
    content = RichTextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        super().save(*args,**kwargs)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('postdetail', kwargs={'pk': self.pk})

def post_slug(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug =  unique_slug_generator(instance)

pre_save.connect(post_slug, sender=Post)

views.py

.........

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'first_image', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

urls.py

from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import (
    PostListView,
    PostDetailView,
    PostCreateView,
    PostUpdateView,
    PostDeleteView,
    UserPostListView
)
from . import views

urlpatterns = [
......

    path('post/<slug>/update/', PostUpdateView.as_view(), name='postupdate'),
    path('post/<slug>/', PostDetailView.as_view(), name='postdetail'),

......
]

Body:
The postdetail url only accepts the argument named slug. While you're passing it pk. Obviously it will fail.

Change this:

return reverse('postdetail', kwargs={'pk': self.pk})

to this:

return reverse('postdetail', kwargs={'slug': self.slug})


问:
What's the definition name for fonts loaded at runtime created with fontswf?
I ran into the 'fontswf' utility to embed TTF fonts into SWF and I am struggling to load them at runtime from my app. All the examples I find online refer to loading the font via [Embed] but I am actually loading them with a flash.display.Loader and from what I gather, once the Loader.contentLoaderInfo fires an Event.INIT I need to register the font, like so:

```<code>public function handleLoaderComplete( event:Event ):void {
  var FontClass:Class = event.target.applicationDomain.getDefinition( fontName );
  Font.registerFont( FontClass );
}
</code>```

The problem is I don't know what to pass in as fontName. I am generating my SWF through:

```<code>$ fontswf -a belshaw -o belshaw.swf belshaw.ttf
</code>```

But when I try to call getDefinition( 'belshaw' ), I get an error saying 'Variable belshaw is not defined'. Any suggestions on how to accomplish this?

The alternative is to generate my on SWF files through templating an .as file and compiling them, but I would rather use a built in tool like fontswf if it's already there.

Thanks

Ruy

答:
You could use a decompiler psoftware to decompile your font SWF to see what fonts are embedded.

Or ...

You can loop through the fonts in the embedded file runtime:

```<code>import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.events.Event;

var fontLoader:Loader = new Loader();
var fontLoaderInfo:LoaderInfo = fontLoader.contentLoaderInfo;

fontLoaderInfo.addEventListener(Event.COMPLETE, onFontLoaded);

fontLoader.load(new URLRequest("Verdana.swf"));

function onFontLoaded (e:Event):void {
   var info:LoaderInfo = e.currentTarget as LoaderInfo;
   var loader:Loader = info.content as Loader;
   var embeddedFonts:Array = Font.enumerateFonts(false);
   for(var i:Number = 0; i < embeddedFonts.length; i++){
      var item:Font = embeddedFonts[i];
      trace("[" + i + "] name:" + item.fontName + ", style: " + item.fontStyle + ", type: " + item.fontType);
   }
}
</code>```

This is not tested, I found it here

Body:
I ran into the 'fontswf' utility to embed TTF fonts into SWF and I am struggling to load them at runtime from my app. All the examples I find online refer to loading the font via [Embed] but I am actually loading them with a flash.display.Loader and from what I gather, once the Loader.contentLoaderInfo fires an Event.INIT I need to register the font, like so:

public function handleLoaderComplete( event:Event ):void {
  var FontClass:Class = event.target.applicationDomain.getDefinition( fontName );
  Font.registerFont( FontClass );
}

The problem is I don't know what to pass in as fontName. I am generating my SWF through:

$ fontswf -a belshaw -o belshaw.swf belshaw.ttf

But when I try to call getDefinition( 'belshaw' ), I get an error saying 'Variable belshaw is not defined'. Any suggestions on how to accomplish this?

The alternative is to generate my on SWF files through templating an .as file and compiling them, but I would rather use a built in tool like fontswf if it's already there.

Thanks

Ruy

Body:
You could use a decompiler psoftware to decompile your font SWF to see what fonts are embedded.

Or ...

You can loop through the fonts in the embedded file runtime:

import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.events.Event;

var fontLoader:Loader = new Loader();
var fontLoaderInfo:LoaderInfo = fontLoader.contentLoaderInfo;

fontLoaderInfo.addEventListener(Event.COMPLETE, onFontLoaded);

fontLoader.load(new URLRequest("Verdana.swf"));

function onFontLoaded (e:Event):void {
   var info:LoaderInfo = e.currentTarget as LoaderInfo;
   var loader:Loader = info.content as Loader;
   var embeddedFonts:Array = Font.enumerateFonts(false);
   for(var i:Number = 0; i < embeddedFonts.length; i++){
      var item:Font = embeddedFonts[i];
      trace("[" + i + "] name:" + item.fontName + ", style: " + item.fontStyle + ", type: " + item.fontType);
   }
}

This is not tested, I found it here


问:
how to make perfect media player in android with url type source
I have created a media player which get data from url. Url is based on volley response. I'm creating a MediaPlayer on item click so the onItemClick create every time a new MediaPlayer() . so i declared it in onCreate() but after it's giving too much errors .
below my code with MediaPlayer() declaration in onItemClick please help me anyone thanks

my motive:- i want to stop the playing song when another song is playing on item click

```<code>public class MusicsActivity extends AppCompatActivity{

private MediaPlayer mMediaPlayer;
}

   public void OnItemClickActivity(int position,String video,String thumbnail,String thumbnails) {
    String webUrl = "https://musicexample.com/";
    Glide.with(this).load(webUrl + image).into(image);
    text.setText(text);
    Atext.setText(Atext);
    mMediaPlayer = new MediaPlayer();
    if (mMediaPlayer.isPlaying() && mMediaPlayer != null)
    {
        mMediaPlayer.stop();
        mMediaPlayer.reset();;
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            togglePlayPause();
        }
    });
    try {
        mMediaPlayer.setDataSource(webUrl + src);
        mMediaPlayer.prepareAsync();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

答:
To stop the Media Player without the risk of an Illegal State Exception, you must do</p>

```<code>  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }
</code>```

Body:
I have created a media player which get data from url. Url is based on volley response. I'm creating a MediaPlayer on item click so the onItemClick create every time a new MediaPlayer() . so i declared it in onCreate() but after it's giving too much errors .
below my code with MediaPlayer() declaration in onItemClick please help me anyone thanks

my motive:- i want to stop the playing song when another song is playing on item click

public class MusicsActivity extends AppCompatActivity{

private MediaPlayer mMediaPlayer;
}

   public void OnItemClickActivity(int position,String video,String thumbnail,String thumbnails) {
    String webUrl = "https://musicexample.com/";
    Glide.with(this).load(webUrl + image).into(image);
    text.setText(text);
    Atext.setText(Atext);
    mMediaPlayer = new MediaPlayer();
    if (mMediaPlayer.isPlaying() && mMediaPlayer != null)
    {
        mMediaPlayer.stop();
        mMediaPlayer.reset();;
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            togglePlayPause();
        }
    });
    try {
        mMediaPlayer.setDataSource(webUrl + src);
        mMediaPlayer.prepareAsync();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Body:
To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }


问:
Webpack DevServer do not reload page
I am using webpack devServer. Every time I change my source files the files get built and the page served by devServer gets reloaded. I do not want devServer to reload the page. I want the devServer to only build and serve files while I reload the page manually.

Here is my webpack configuration for DevServer.

```<code>devServer: {
    contentBase: './dist',
    port: 8002,
    watchContentBase: false,
  },
</code>```

I tried setting hot: false and hotOnly: false but the devServer still builds and reloads the webpage every time the source file changes.

答: There is two options: devServer.injectClient and devServer.injectHot. Try to set it to false. No WDS client on a board - no problem. Depends on CLI, check that no HotModuleReplacementPlugin attached.

Title: Webpack DevServer do not reload page

Body:
I am using webpack devServer. Every time I change my source files the files get built and the page served by devServer gets reloaded. I do not want devServer to reload the page. I want the devServer to only build and serve files while I reload the page manually.

Here is my webpack configuration for DevServer.

devServer: {
    contentBase: './dist',
    port: 8002,
    watchContentBase: false,
  },

I tried setting hot: false and hotOnly: false but the devServer still builds and reloads the webpage every time the source file changes.


问:
How to give a custom (id || key) for every item in flutter listview?
Is there a way to give custom id to every item in flutter's listview?

I need to update a single item in flutter listview by its id or key.

Why I want to update by Id?

because I want to update a specific item without rebuilding the entire listview items, this may boost performance of my app.

答:
I guess you can just use itemBuilder's index since it's not repetitive.

```<code>return ListView.builder(
         itemCount: items.length,
         itemBuilder: (context, int index) {
           return ListTile(key: new Key(index.toString()));...
      },
    );
</code>```

Body:
I guess you can just use itemBuilder's index since it's not repetitive.

return ListView.builder(
         itemCount: items.length,
         itemBuilder: (context, int index) {
           return ListTile(key: new Key(index.toString()));...
      },
    );