问:
trying to have a different color my login form
hi i have decided to face my fears of frontend development and I am having a little bit of trouble here so I am trying to put a 50 px which is a rough estimate around my login form and I wanna change the color of it so the back ground is #423075 but I want the back of the actual login section tobe #300C94 what is the best way todo this with my code

index.html

```<code><html>
<header>
    <title>Login-1</title>

    <link rel="stylesheet" href="assets/css/styles.css" >

</header>

<body>

    <form class="form" >
              <div class="form-back" name="form-back" >
        <input  name="username" type="text" placeholder="username" required>
        <br>
        <input  name="password" type="password" placeholder="password" required>
        <br>
        <input  name="confirm_password" type="password" placeholder="Confirm Password" required>
        <br>
        <input  name="submit" type="submit">
</div>
    </form>

</body>

</html>
</code>```

styles.css

```<code>body{

    margin-top: 300px;
    text-align: center;
    background-color: #423075;

}

form{
    display: inline-block;

}

div{

    border-radius: 10px;
     border-radius: 30px;
    background: #300C94;
}

input[type=submit] {
    width: 100%;

}
</code>```

any suggestions would be great

答:
You can put padding around your <form> tag then add a background-color property to define the color of the form background. You can see here, I just kept your code and just changed a small portion in the form tag css.

```<code>form{
  display: inline-block;
  padding: 50px;
  background-color: #300C94;
}
</code>```

body{

    margin-top: 300px;
    text-align: center;
    background-color: #423075;

}

form{
    display: inline-block;
  padding: 50px;
  background-color: #300C94;

}

div{

    border-radius: 10px;
     border-radius: 30px;
    background: #300C94;
}

input[type=submit] {
    width: 100%;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <form class="form" >
              <div class="form-back" name="form-back" >
        <input  name="username" type="text" placeholder="username" required>
        <br>
        <input  name="password" type="password" placeholder="password" required>
        <br>
        <input  name="confirm_password" type="password" placeholder="Confirm Password" required>
        <br>
        <input  name="submit" type="submit">
</div>
    </form></code>```

Body:
hi i have decided to face my fears of frontend development and I am having a little bit of trouble here so I am trying to put a 50 px which is a rough estimate around my login form and I wanna change the color of it so the back ground is #423075 but I want the back of the actual login section tobe #300C94 what is the best way todo this with my code

index.html

    <title>Login-1</title>

    <link rel="stylesheet" href="assets/css/styles.css" >

    <form class="form" >

        <input  name="username" type="text" placeholder="username" required>

        <input  name="password" type="password" placeholder="password" required>

        <input  name="confirm_password" type="password" placeholder="Confirm Password" required>

        <input  name="submit" type="submit">

    </form>

styles.css

body{

    margin-top: 300px;
    text-align: center;
    background-color: #423075;

}

form{
    display: inline-block;

}

div{

    border-radius: 10px;
     border-radius: 30px;
    background: #300C94;
}

input[type=submit] {
    width: 100%;

}

any suggestions would be great

Body:
You can put padding around your <form> tag then add a background-color property to define the color of the form background. You can see here, I just kept your code and just changed a small portion in the form tag css.

form{
  display: inline-block;
  padding: 50px;
  background-color: #300C94;
}

body{

    margin-top: 300px;
    text-align: center;
    background-color: #423075;

}

form{
    display: inline-block;
  padding: 50px;
  background-color: #300C94;

}

div{

    border-radius: 10px;
     border-radius: 30px;
    background: #300C94;
}

input[type=submit] {
    width: 100%;

}

    <form class="form" >
              <div class="form-back" name="form-back" >
        <input  name="username" type="text" placeholder="username" required>
        <br>
        <input  name="password" type="password" placeholder="password" required>
        <br>
        <input  name="confirm_password" type="password" placeholder="Confirm Password" required>
        <br>
        <input  name="submit" type="submit">
</div>
    </form>


来源: stackexchange

问:
What is the best way to transfer large files through Django app hosted on HEROKU?

HEROKU gives me H12 error on transferring the file to an API from my Django application (Understood it's a long running process and there is some memory/worker tradeoff I guess so). I am on one single hobby Dyno right now.

The function just runs smoothly for around 50MB file. The file itself is coming from a different source ( requests python package )

The idea is to build a file transfer utility using Django app on HEROKU. The file will not gets stored in my app side. Its just getting from point A and sending to point B.

Went through multiple discussions along with the standard HEROKU documentations, however I am struggling in between in some concepts:

Will this problem be solved by background tasks really? (If YES, I am finding explanation of the process than the direct way to do it such that I can optimize my flow)

As mentioned in standard docs, they recommend background tasks using RQ package for python, I am using Postgre SQL at moment. Will I need to install and manage Redis Database as well for this. Is this even related to Database?

Some recommend using extra Worker other than the WEB worker we have by default. How does this relate to my problem?

Some say to add multiple workers, not sure how this solve it. Let's say today it starts working for large files using background tasks, what if the load of users at same time increases. How this will impact my solution and how should I plan the mitigation plan around the risks.

If someone here has a strong understanding with respect to the architecture, I am here to listen your experiences and thoughts. Also, let me know if there is other way than HEROKU from a solution standpoint which will make this more easy for me.

答:
Here is my final take on this after full evaluation, trials and earlier recommendations made here, thanks @arun.

HEROKU needs a web worker to deliver the website runtime which hold 512MB of memory, operations your perform if are below this limits should be fine.

Beyond that let's say you have scenarios like mentioned above where a large file is coming from one source api and going into another target api with Django app, you will have to:

First, you will have to run the file upload function as a background process since it will take time more than 30 seconds to respond which HEROKU expects to return. If not H12 Error is waiting for you. Solution to this is implementing Django Background tasks, Celery worked in my case. So here Celery  is your same Django app functionality running as a background handler which needs its own app Dyno ( The Worker ) This can be scaled as needed in future.

To make your Django WSGI ( Frontend App ) talk to the Celery ( Background App), you need a message broker in between which can be HEROKU Redis, RabbitMQ, etc.

Second, the problems doesn't gets solved here even though you have a new Worker dedicated for the Celery app, the memory limits will still apply as its also a Dyno with its own memory.

To overcome this, your Python requests module should download the file in stream instead of direct downloading complete file in a single memory buffer. Iterate and load the stream data in chunks and send the file chunks to target endpoint.

Even chunk size plays here an important role. I will not put exact number here since it depends on various factors:

Should not be too small, else it will take more time to transfer.

Should not be too big to be handled by either of the source/target endpoint servers.

ContentLicense: CC BY-SA 4.0


问:
Window is undefined in Nextjs but values are needed in useState
Trying to get the exact window values as the screen size changes. How can i get the window values into useState()? Since useState cannot be used in a conditional, and window is undefined outside a useEffect?</p>
```<code>    const isSSR = typeof window !== "undefined";
    const [windowSize, setWindowSize] = React.useState({
        width: isSSR ? 1200 : window.innerWidth,
        height: isSSR ? 800 : window.innerHeight,
    });

    function changeWindowSize() {
        setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    }

    React.useEffect(() => {
        window.addEventListener("resize", changeWindowSize);

        return () => {
            window.removeEventListener("resize", changeWindowSize);
        };
    }, []);

    return windowSize;
}
</code>```

答:
Two things to be corrected,

Your isSSR logic is not right. due to that, window.innerWidth and window.innerHeight were evaluated in the server. It should be === not !==.

```<code>const isSSR = typeof window === "undefined";
</code>```

And change the client-side function to be safe like below.

```<code>function changeWindowSize() {
    if(!isSSR){
        setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    }
}
</code>```

*** changeWindowSize change is not needed since you call it only within a useEffect and useEffect hook is not executed in the server.

Body:
Trying to get the exact window values as the screen size changes. How can i get the window values into useState()? Since useState cannot be used in a conditional, and window is undefined outside a useEffect?

    const isSSR = typeof window !== "undefined";
    const [windowSize, setWindowSize] = React.useState({
        width: isSSR ? 1200 : window.innerWidth,
        height: isSSR ? 800 : window.innerHeight,
    });

    function changeWindowSize() {
        setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    }

    React.useEffect(() => {
        window.addEventListener("resize", changeWindowSize);

        return () => {
            window.removeEventListener("resize", changeWindowSize);
        };
    }, []);

    return windowSize;
}

Body:
Two things to be corrected,

Your isSSR logic is not right. due to that, window.innerWidth and window.innerHeight were evaluated in the server. It should be === not !==.

const isSSR = typeof window === "undefined";

And change the client-side function to be safe like below.

function changeWindowSize() {
    if(!isSSR){
        setWindowSize({ width: window.innerWidth, height: window.innerHeight });
    }
}

*** changeWindowSize change is not needed since you call it only within a useEffect and useEffect hook is not executed in the server.


问:
Convert a txt document to a list to a list starting with [[, instead of ['[
I have a .txt document with this type of text:

[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]

(which represents a sentence and the Parts of Speech tags for each word)

I want to have a list of list in python, like this:

[[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]]

But I obtain this:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\n']

The code I'm using is:

```<code>import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)
</code>```

How can I avoid the ['[ .... ]\n']  ?

Thank you!

答:
it looks like you can just do

```<code>import json
data = json.load(open('test.txt'))
</code>```

this answer was wrong sorry... [("word","QQ")] is NOT valid json as json does not support tuples

instead you should be able to do

```<code>import ast
data = ast.literal_eval(io.open("test.txt", mode="r", encoding="utf-8-sig").read())
</code>```

here is my version

```<code>import io,ast,requests

#text file available at
text_url = "https://gist.githubusercontent.com/joranbeasley/a50d940d9ac47e8458f027d3cc88e236/raw/3a65169d30e653e085284de16b1ee715f3596c95/example.txt"
with open("example.txt","wb") as f:
    # download and save textfile
    f.write(requests.get(text_url).content)

data = ast.literal_eval(io.open('example.txt',encoding='utf8').read())
print(data)
print(data[0])
print(data[0][0])
</code>```

results in

```<code>[('Vazhdo', 'verb'), ('të', 'particle'), ('ecësh', 'verb'), ('!', 'excl.')]
('Vazhdo', 'verb')
Vazhdo
</code>```

Body:
I have a .txt document with this type of text:

[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]

(which represents a sentence and the Parts of Speech tags for each word)

I want to have a list of list in python, like this:

[[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]]

But I obtain this:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\n']

The code I'm using is:

import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)

How can I avoid the ['[ .... ]\n']  ?

Thank you!

Body:
it looks like you can just do

import json
data = json.load(open('test.txt'))

this answer was wrong sorry... [("word","QQ")] is NOT valid json as json does not support tuples

instead you should be able to do

import ast
data = ast.literal_eval(io.open("test.txt", mode="r", encoding="utf-8-sig").read())

here is my version

import io,ast,requests

#text file available at
text_url = "https://gist.githubusercontent.com/joranbeasley/a50d940d9ac47e8458f027d3cc88e236/raw/3a65169d30e653e085284de16b1ee715f3596c95/example.txt"
with open("example.txt","wb") as f:
    # download and save textfile
    f.write(requests.get(text_url).content)

data = ast.literal_eval(io.open('example.txt',encoding='utf8').read())
print(data)
print(data[0])
print(data[0][0])

results in

[('Vazhdo', 'verb'), ('të', 'particle'), ('ecësh', 'verb'), ('!', 'excl.')]
('Vazhdo', 'verb')
Vazhdo


问:
"You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter
"You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without 'android:exported' property set. This file can't be installed on Android 12 or higher."

My Client is getting this error while uploading my App on Play Store. I have resolved the issue on on my side. but how Can I test this on Android Studio. As I was not getting the error earlier as well? (How I solved this ? I defined android:exported Property in Manifest.xml).

Complied SDK : 31
minSDK : 19

答:
Yes, you can test it on the emulator. Install an emulator with 31 SDK
create emulator

It helps you check your fix


问:
Network error with axios and react native
I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:

```<code>Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
    at XMLHttpRequest.js:493
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:353)
    at MessageQueue.js:118
    at MessageQueue.__guardSafe (MessageQueue.js:316)
</code>```

This is my axios call in my react native component:

```<code>    componentDidMount() {
        axios.get('mydomain.com/get/').then(response => {  // localhost:8000/get works
            this.setState({foo:response.data});
        }).catch(error => {
            console.log(error);
        });
    }
</code>```

答:
If you are using android then open your command prompt and type ipconfig. Then get your ip address and replce it with localhost.

In my case, first I used http://localhost:8080/api/admin/1. Then I changed it to http://192.168.1.10:8080/api/admin/1. It worked for me.

ContentLicense: CC BY-SA 3.0

Body:
I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
    at XMLHttpRequest.js:493
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:353)
    at MessageQueue.js:118
    at MessageQueue.__guardSafe (MessageQueue.js:316)

This is my axios call in my react native component:

    componentDidMount() {
        axios.get('mydomain.com/get/').then(response => {  // localhost:8000/get works
            this.setState({foo:response.data});
        }).catch(error => {
            console.log(error);
        });
    }


问:
Printf Problem with While Loop
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.</p>

```<code>#include <stdio.h>

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}
</code>```

答:
Choose a precision and compare it with the difference between hf and lf(abs value).
Also keep in mind with a random fixed step you will not always reach the top value of the interval. it might work if step divides h-l but it won't work otherwise.</p>

Title: Printf Problem with While Loop

Body:
I'm creating a temperature converter in C. Basically, you input a minimum and maximum value in degrees Celsius, along with a step, and it displays that information in a list, along with the Fahrenheit equivalent. On some occasions, I have noticed the last Fahrenheit entry not being displayed when it should. For example, when you input a lower limit of 10, a higher limit of 30, and a step of 4, it cuts off the last Fahrenheit temperature. I know it's something to do with the last while loop, but I just can't figure it out.

#include <stdio.h>

int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;

/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
        printf("Lower limit must be greater than 0: ");
        scanf("%4lf", &l);
}

/* Stores value for Fahrenheit conversion */
lf = l;

/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
        printf("Higher limit must be greater than lower limit: ");
        scanf("%4lf", &h);
}

while (h >= 50000) {
        printf("Higher limit must be less than 50000: ");
        scanf("%4lf", &h);
}

hf = h;

/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
        printf("Step must be greater than 0: ");
        scanf("%4lf", &s);
}

while (s >= h - l) {
        printf("Step must be less than the difference in temperatures: ");
        scanf("%4lf", &s);
}

sf = s;

/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
    printf("%i. %4lf\n", num1, l);
    num1++;
    l = l + s;
}

/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
    printf("%i. %4lf\n", num2, lf);
    num2++;
    lf = lf + sf;
}

return 0;

}


问:
Problem with setting state.index on click
I'm creating a webpage slide show. I created a file called SlideshowData.js where I exported an array of objects with all image links and ids. So using react I mapped through the photos and added dots to them. I created the dots and each time the photos switch the dot changes color from gray to black to indicate that the current photo is active.

The problem occurs now that I keep trying to figure out how to make them clickable. So for example you would click on the first dot it would bring you to the first slide. I tried to do it with a "set.state" function and set the initial index to the "event.target.key" which I assigned slide.id but it doesn't work.

Thank you for your time. I attached the code below.

```<code>class Slideshow extends React.Component{
constructor(props){
    super(props);
    this.state = {
        index: 0,
        delay: 5000,
        length: SlideshowData.length,
    }
    this.clickedDot = this.clickedDot.bind(this)
}

componentDidMount(){

    document.addEventListener("onClick", this.clickedDot)

    if(this.state.index === this.state.length -1){
        setTimeout(()=> this.setState(()=>({
            index: 0
        })),this.state.delay)
    }else{
        setTimeout(()=> this.setState((state)=>({
            index: state.index + 1,
        })),this.state.delay)
    }

}
componentDidUpdate(){
    document.addEventListener("onClick", this.clickedDot)

    if(this.state.index === this.state.length -1){
        setTimeout(()=> this.setState(()=>({
            index: 0
        })),this.state.delay)
    }else{
        setTimeout(()=> this.setState((state)=>({
            index: state.index + 1,
        })),this.state.delay)
    }

}
clickedDot(){
    this.setState((slide) =>({
        index: this.state.length
    }))
    console.log(this.state.index)
}
render(){
    return(
        <div className="slidesContainer">
            <div className="SlideshowSlider" style={{ transform: `translate3d(${-this.state.index * 100}%, 0, 0)` }}>
                {SlideshowData.map((slide,index) => (
                <img className="slides" src={slide.image} key={index} alt="travel"/>
                ))}
            </div>
            <div className = "slideshowDots">
                {SlideshowData.map((slide,idx) => (
                <div onClick={this.clickedDot} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} ></div>
                ))}
            </div>
        </div>
    )
  }
}
export default Slideshow
</code>```

答:
You can pass the index inside your onClick function on the dots such as this:

```<code><div onClick={(idx) => this.clickedDot(idx)} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} >
</code>```

and then use the index to change the slide accordingly in your clickedDot function.

Body:
I'm creating a webpage slide show. I created a file called SlideshowData.js where I exported an array of objects with all image links and ids. So using react I mapped through the photos and added dots to them. I created the dots and each time the photos switch the dot changes color from gray to black to indicate that the current photo is active.

The problem occurs now that I keep trying to figure out how to make them clickable. So for example you would click on the first dot it would bring you to the first slide. I tried to do it with a "set.state" function and set the initial index to the "event.target.key" which I assigned slide.id but it doesn't work.

Thank you for your time. I attached the code below.

class Slideshow extends React.Component{
constructor(props){
    super(props);
    this.state = {
        index: 0,
        delay: 5000,
        length: SlideshowData.length,
    }
    this.clickedDot = this.clickedDot.bind(this)
}

componentDidMount(){

    document.addEventListener("onClick", this.clickedDot)

    if(this.state.index === this.state.length -1){
        setTimeout(()=> this.setState(()=>({
            index: 0
        })),this.state.delay)
    }else{
        setTimeout(()=> this.setState((state)=>({
            index: state.index + 1,
        })),this.state.delay)
    }

}
componentDidUpdate(){
    document.addEventListener("onClick", this.clickedDot)

    if(this.state.index === this.state.length -1){
        setTimeout(()=> this.setState(()=>({
            index: 0
        })),this.state.delay)
    }else{
        setTimeout(()=> this.setState((state)=>({
            index: state.index + 1,
        })),this.state.delay)
    }

}
clickedDot(){
    this.setState((slide) =>({
        index: this.state.length
    }))
    console.log(this.state.index)
}
render(){
    return(

            <div className="SlideshowSlider" style={{ transform: `translate3d(${-this.state.index * 100}%, 0, 0)` }}>
                {SlideshowData.map((slide,index) => (

                ))}

                {SlideshowData.map((slide,idx) => (
                <div onClick={this.clickedDot} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} >

                ))}

    )
  }
}
export default Slideshow

Body:
You can pass the index inside your onClick function on the dots such as this:

<div onClick={(idx) => this.clickedDot(idx)} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} >

and then use the index to change the slide accordingly in your clickedDot function.


问:
Dropping only UDP packets in RPL
1)I am trying to drop only UDP packets in RPL in Contigi-ng OS.

I modified the code in/contiki/core/net/tcpip.c as:

```<code>...
    static void
    packet_input(void)
    {
    #if DEST_PORT_IS_MAL_DROP
    if ((UIP_IP_BUF->proto == UIP_PROTO_UDP) &&
    (uip_ntohs(UIP_UDP_BUF->destport)==UDP_MALICIOUS_PORT)){
    uip_len=0;}
    #endif
    #if UIP_CONF_IP_FORWARD
    if(uip_len > 0){
...
</code>```

This drops all packets whose destport = UDP_MALICIOUS_PORT and do not know how to drop only UDP packets and allow control messages.

Thanks in advance

答:
You should change  uip6.c in the "os/net/ipv6/uip6.c" path.
please see this paper :A Reference Implementation for RPL Attacks Using Contiki-NG and COOJA.
This is good reference for implementing attacks in Contiki-ng.</p>

Title: Dropping only UDP packets in RPL

Body:
1)I am trying to drop only UDP packets in RPL in Contigi-ng OS.

I modified the code in/contiki/core/net/tcpip.c as:

...
    static void
    packet_input(void)
    {
    #if DEST_PORT_IS_MAL_DROP
    if ((UIP_IP_BUF->proto == UIP_PROTO_UDP) &&
    (uip_ntohs(UIP_UDP_BUF->destport)==UDP_MALICIOUS_PORT)){
    uip_len=0;}
    #endif
    #if UIP_CONF_IP_FORWARD
    if(uip_len > 0){
...

This drops all packets whose destport = UDP_MALICIOUS_PORT and do not know how to drop only UDP packets and allow control messages.

Thanks in advance


问:
How to setup VPN from on-premises database to Google Cloud
I want to be able to connect from on premises database to google cloud.
I have VPC set, external IP address and VPN but not connected yet.
Is there something I missed? Do I have to create a compute engine first?</p>

答:
I would recommend you to first read this link which is the cloud VPN overview to mainly understand the type of VPN that you are creating for this setup and then setup your VPN.

In this other link you will find some guides to setup the VPN with devices such as Cisco or even other cloud providers. I hope you find this links useful since your question doesn't have much information to better understand if you have any error message or kind of peer device you're using for this set up

Cheers


问:
Clarification required on use of context package in golang
I am learning the Go language.
I understand that cancelling a context enables aborting of operations once the parent or related operation is cancelled. This is supposed to save resources of ongoing operations whose results will not be used. Now consider the simple code below:

```<code> package main

 import (
    "context"
    "fmt"
    "time"
 )

 func main() {
    var result int
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    ch1 := make(chan int)

    go func() {
        time.Sleep(time.Second * 5)
        //...do some processing
        //Send result on the channel or cancel if error
        //Lets send result...
        ch1 <- 11
    }()

    go func() {
        time.Sleep(time.Second * 2)
        //...do some processing
        //Send result on the channel or cancel if error
        //Lets cancel...
        cancel()
    }()

    select {
    case result = <-ch1:
        fmt.Println("Processing completed", result)
    case <-ctx.Done():
        fmt.Println("ctx Cancelled")
    }

    //Some other processing...

 }
</code>```

The select statement is satisfied by the ctx.Done(). The question that I have is that even after the cancel is invoked, the first goroutine will continue as the program proceeds with "Some other processing..."
Therefore, the basic purpose of using context is not served. I think that I am missing something in my understanding or is there a way to abort the goroutine whose result will not be of any use after the context is cancelled.
Please clarify.

答:
The point is you should notify the first goroutine that sth happened, and it need to exit the current routine. That is what select doing as an io-multiplexing provided by golang. The first goroutine should look like this

```<code> go func() {
        select {
        case <-time.After(time.Second * 5):
            //...do some processing
            //Send result on the channel or cancel if error
            //Lets send result...
            ch1 <- 11
        case <-ctx.Done():
            fmt.Println("ctx Cancelled again.")
            return
        }
    }()
</code>```

Body:
I am learning the Go language.
I understand that cancelling a context enables aborting of operations once the parent or related operation is cancelled. This is supposed to save resources of ongoing operations whose results will not be used. Now consider the simple code below:

 package main

 import (
    "context"
    "fmt"
    "time"
 )

 func main() {
    var result int
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    ch1 := make(chan int)

    go func() {
        time.Sleep(time.Second * 5)
        //...do some processing
        //Send result on the channel or cancel if error
        //Lets send result...
        ch1 <- 11
    }()

    go func() {
        time.Sleep(time.Second * 2)
        //...do some processing
        //Send result on the channel or cancel if error
        //Lets cancel...
        cancel()
    }()

    select {
    case result = <-ch1:
        fmt.Println("Processing completed", result)
    case <-ctx.Done():
        fmt.Println("ctx Cancelled")
    }

    //Some other processing...

 }

The select statement is satisfied by the ctx.Done(). The question that I have is that even after the cancel is invoked, the first goroutine will continue as the program proceeds with "Some other processing..."
Therefore, the basic purpose of using context is not served. I think that I am missing something in my understanding or is there a way to abort the goroutine whose result will not be of any use after the context is cancelled.
Please clarify.

Body:
The point is you should notify the first goroutine that sth happened, and it need to exit the current routine. That is what select doing as an io-multiplexing provided by golang. The first goroutine should look like this

 go func() {
        select {
        case <-time.After(time.Second * 5):
            //...do some processing
            //Send result on the channel or cancel if error
            //Lets send result...
            ch1 <- 11
        case <-ctx.Done():
            fmt.Println("ctx Cancelled again.")
            return
        }
    }()


问:
How to write to a file, using the logging Python module?
How can I use the logging module in Python to write to a file? Every time I try to use it, it just prints out the message.</p>

答:
```<code>import logging

from datetime import datetime

filename = datetime.now().strftime("%d-%m-%Y %H-%M-%S")#Setting the filename from current date and time
logging.basicConfig(filename=filename, filemode='a',
                    format="%(asctime)s, %(msecs)d %(name)s %(levelname)s [ %(filename)s-%(module)s-%(lineno)d ]  : %(message)s",
                    datefmt="%H:%M:%S",
                    level=logging.DEBUG)
</code>```

asctime

%(asctime)s

Human-readable time when the LogRecord was created. By default this
is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma
are millisecond portion of the time).

created

%(created)f

Time when the LogRecord was created (as returned by time.time()).

exc_info

You shouldn’t need to format this yourself.

Exception tuple (à la sys.exc_info) or, if no exception has occurred,
None.

filename

%(filename)s

Filename portion of pathname.

funcName

%(funcName)s

Name of function containing the logging call.

levelname

%(levelname)s

Text logging level for the message ('DEBUG', 'INFO', 'WARNING',
'ERROR', 'CRITICAL').

levelno

%(levelno)s

Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR,
CRITICAL).

lineno

%(lineno)d

Source line number where the logging call was issued (if available).

message

%(message)s

The logged message, computed as msg % args. This is set when
Formatter.format() is invoked.

module

%(module)s

Module (name portion of filename).

msecs

%(msecs)d

Millisecond portion of the time when the LogRecord was created.

msg

You shouldn’t need to format this yourself.

The format string passed in the original logging call. Merged with
args to produce message, or an arbitrary object (see Using arbitrary
objects as messages).

name

%(name)s

Name of the logger used to log the call.

pathname

%(pathname)s

Full pathname of the source file where the logging call was issued
(if available).

process

%(process)d

Process ID (if available).

processName

%(processName)s

Process name (if available).

relativeCreated

%(relativeCreated)d

Time in milliseconds when the LogRecord was created, relative to the
time the logging module was loaded.

stack_info

You shouldn’t need to format this yourself.

Stack frame information (where available) from the bottom of the
stack in the current thread, up to and including the stack frame of
the logging call which resulted in the creation of this record.

thread

%(thread)d

Thread ID (if available).

threadName

%(threadName)s

Thread name (if available).

Head over to official python3 page for more info regarding logging.

Body:
import logging

from datetime import datetime

filename = datetime.now().strftime("%d-%m-%Y %H-%M-%S")#Setting the filename from current date and time
logging.basicConfig(filename=filename, filemode='a',
                    format="%(asctime)s, %(msecs)d %(name)s %(levelname)s [ %(filename)s-%(module)s-%(lineno)d ]  : %(message)s",
                    datefmt="%H:%M:%S",
                    level=logging.DEBUG)

asctime

%(asctime)s

Human-readable time when the LogRecord was created. By default this
is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma
are millisecond portion of the time).

created

%(created)f

Time when the LogRecord was created (as returned by time.time()).

exc_info

You shouldn’t need to format this yourself.

Exception tuple (à la sys.exc_info) or, if no exception has occurred,
None.

filename

%(filename)s

Filename portion of pathname.

funcName

%(funcName)s

Name of function containing the logging call.

levelname

%(levelname)s

Text logging level for the message ('DEBUG', 'INFO', 'WARNING',
'ERROR', 'CRITICAL').

levelno

%(levelno)s

Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR,
CRITICAL).

lineno

%(lineno)d

Source line number where the logging call was issued (if available).

message

%(message)s

The logged message, computed as msg % args. This is set when
Formatter.format() is invoked.

module

%(module)s

Module (name portion of filename).

msecs

%(msecs)d

Millisecond portion of the time when the LogRecord was created.

msg

You shouldn’t need to format this yourself.

The format string passed in the original logging call. Merged with
args to produce message, or an arbitrary object (see Using arbitrary
objects as messages).

name

%(name)s

Name of the logger used to log the call.

pathname

%(pathname)s

Full pathname of the source file where the logging call was issued
(if available).

process

%(process)d

Process ID (if available).

processName

%(processName)s

Process name (if available).

relativeCreated

%(relativeCreated)d

Time in milliseconds when the LogRecord was created, relative to the
time the logging module was loaded.

stack_info

You shouldn’t need to format this yourself.

Stack frame information (where available) from the bottom of the
stack in the current thread, up to and including the stack frame of
the logging call which resulted in the creation of this record.

thread

%(thread)d

Thread ID (if available).

threadName

%(threadName)s

Thread name (if available).

Head over to official python3 page for more info regarding logging.


问:
Why is "a =(b>0)?1:0" better than "if-else" version in CUDA?
Could you tell me why

```<code>a =(b>0)?1:0
</code>```

is better than

```<code>if (b>0)a=1; else a =0;
</code>```

version in CUDA? Please give details. Many thanks.

Yik

答:
Don't know for CUDA, but in C++ and C99, using the former you can initialize a const variable.

```<code>int const a = (b>0) ? 1 : 0;
</code>```

Whereas with the latter, you cannot make your a variable const as you have to declare it before the if.

Note that it could be written even shorter:

```<code>int const a = (b>0);
</code>```

And you could even remove the parenthesis ... but IMHO it does not improve reading.

Body:
Could you tell me why

a =(b>0)?1:0

is better than

if (b>0)a=1; else a =0;

version in CUDA? Please give details. Many thanks.

Yik

Body:
Don't know for CUDA, but in C++ and C99, using the former you can initialize a const variable.

int const a = (b>0) ? 1 : 0;

Whereas with the latter, you cannot make your a variable const as you have to declare it before the if.

Note that it could be written even shorter:

int const a = (b>0);

And you could even remove the parenthesis ... but IMHO it does not improve reading.


问:
is it possible to use the result of a defquery by a defrule?
i'm moving along in jess. the problem that i'm using jess for is to allocate docks
to members based on a set of rules. the process starts when a dock is put in the
pool of available docks. the list of available docks is then compared to the
dock request list. i did this part using a defquery. for simplicity i have just
one available dock with 2 members requesting it. at this point i would like to
start to apply the rules to the result of the query.

i have successfully tested the defquery and the defrule - separately, but don't
understand how to have the rule act on the defquery result.

is it possible?
i have included the defrule and defquery below

duetto

```<code>(defglobal ?*curSlip* = nil ?*cand* = nil)
(deftemplate bid
  (slot person)
  (slot slipRequestedID)
  (slot boatID))
(deftemplate slip
  (slot slipID)
  (slot slength)
  (slot swidth)
  (slot sdepth))
(deftemplate person
  (slot name)
  (slot bycseniority)
  (slot boatID)
  (slot currentSlip))
(deffacts members
  (person (name John)(bycseniority 34)(boatID GEM)(currentSlip A8))
  (person (name Joe)(bycseniority  50)(boatID MS#$)(currentSlip B9))
  (person (name Frank)(bycseniority  120)(boatID DoryO)(currentSlip B8)))
(deffacts bids
  (bid (person John) (slipRequestedID A13) (boatID GEM))
  (bid (person Joe) (slipRequestedID A13) (boatID FarNiente))
  (bid (person Frank) (slipRequestedID B9) (boatID DoryO)))
(deffacts freeSlips
  (slip (slipID A13)))
(defrule mostSenior
   (person (name ?name) (bycseniority ?senior))
   (not (person (name ~?name) (bycseniority ?bycmem&:(< ?bycmem ?senior))))
   =>
   (bind ?*cand* ?name)
   (printout t ?*cand* " is the most senior." crlf))
(defquery bidLookup
    (declare (variables ?slipID))
        (bid (person ?pers) (slipRequestedID ?slipID)))
(reset)
(bind ?collOfBids (run-query* bidLookup A13))
    (while (?collOfBids next)
        (printout t (?collOfBids getString pers) crlf)
    )
</code>```

答:
You are leaving the rule-based approach after locating the most senior person. The fact(s) you need for assigning (or denying) a slot request to the most senior person are already in working-memory. Therefore, running a query doesn't yield any new information.

You could add conditions to the mostSenior rule, first establishing that the most senior person has made a bid (any bids) and, second, that the requested slip has a matching slip. If this rule fires, you have the first allocation (and may remove a bid and a slip).

You'll need to consider what happens when the most senior member isn't requesting anything: perhaps write another rule to remove him from WM. Also, a bid of the most senior member may not have a match, and you may have to remove that to make the "senior-has-no-bids" rule to fire.

Don't worry about duplicating conditions in different rules. The engine is built to deal efficiently with this.

Body:
i'm moving along in jess. the problem that i'm using jess for is to allocate docks
to members based on a set of rules. the process starts when a dock is put in the
pool of available docks. the list of available docks is then compared to the
dock request list. i did this part using a defquery. for simplicity i have just
one available dock with 2 members requesting it. at this point i would like to
start to apply the rules to the result of the query.

i have successfully tested the defquery and the defrule - separately, but don't
understand how to have the rule act on the defquery result.

is it possible?
i have included the defrule and defquery below

duetto

(defglobal ?*curSlip* = nil ?*cand* = nil)
(deftemplate bid
  (slot person)
  (slot slipRequestedID)
  (slot boatID))
(deftemplate slip
  (slot slipID)
  (slot slength)
  (slot swidth)
  (slot sdepth))
(deftemplate person
  (slot name)
  (slot bycseniority)
  (slot boatID)
  (slot currentSlip))
(deffacts members
  (person (name John)(bycseniority 34)(boatID GEM)(currentSlip A8))
  (person (name Joe)(bycseniority  50)(boatID MS#$)(currentSlip B9))
  (person (name Frank)(bycseniority  120)(boatID DoryO)(currentSlip B8)))
(deffacts bids
  (bid (person John) (slipRequestedID A13) (boatID GEM))
  (bid (person Joe) (slipRequestedID A13) (boatID FarNiente))
  (bid (person Frank) (slipRequestedID B9) (boatID DoryO)))
(deffacts freeSlips
  (slip (slipID A13)))
(defrule mostSenior
   (person (name ?name) (bycseniority ?senior))
   (not (person (name ~?name) (bycseniority ?bycmem&:(< ?bycmem ?senior))))
   =>
   (bind ?*cand* ?name)
   (printout t ?*cand* " is the most senior." crlf))
(defquery bidLookup
    (declare (variables ?slipID))
        (bid (person ?pers) (slipRequestedID ?slipID)))
(reset)
(bind ?collOfBids (run-query* bidLookup A13))
    (while (?collOfBids next)
        (printout t (?collOfBids getString pers) crlf)
    )


问:
Convert scanned pdf to text python
I have a scanned pdf file and I try to extract text from it.
I tried to use pypdfocr to make ocr on it but I have error:

"could not found ghostscript in the usual place"

After searching I found this solution Linking Ghostscript to pypdfocr in Windows Platform and I tried to download GhostScript and put it in environment variable but it still has the same error.

How can I searh text in my scanned pdf file using python?

Thanks.

Edit: here is my code sample:

```<code>import os
import sys
import re
import json
import shutil
import glob
from pypdfocr import pypdfocr_gs
from pypdfocr import pypdfocr_tesseract
from PIL import Image

path = PATH_TO_MY_SCANNED_PDF
mainL = []
kk = {}

def new_init(self, kk):
    self.lang = 'heb'
    self.binary = "tesseract"
    self.msgs = {
            'TS_MISSING': """
                Could not execute %s
                Please make sure you have Tesseract installed correctly
                """ % self.binary,
            'TS_VERSION':'Tesseract version is too old',
            'TS_img_MISSING':'Cannot find specified tiff file',
            'TS_FAILED': 'Tesseract-OCR execution failed!',
        }

pypdfocr_tesseract.PyTesseract.__init__ = new_init

wow = pypdfocr_gs.PyGs(kk)
tt = pypdfocr_tesseract.PyTesseract(kk)

def secFile(filename,oldfilename):
    wow.make_img_from_pdf(filename)

    files = glob.glob("X:/e206333106/ocr-114/balagan/" + '*.jpg')
    for file in files:
        im = Image.open(file)
        im.save(file + ".tiff")

    files = glob.glob("PATH" + '*.tiff')
    for file in files:
        tt.make_hocr_from_pnm(file)
    pdftxt = ""
    files = glob.glob("PATH" + '*.html')
    for file in files:
        with open(file) as myfile:
            pdftxt = pdftxt + "#" + "".join(line.rstrip() for line in myfile)
    findNum(pdftxt,oldfilename)

    folder ="PATH"

    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception, e:
            print e

def pdf2ocr(filename):
    pdffile = filename
    os.system('pypdfocr -l heb ' + pdffile)

def ocr2txt(filename):
    pdffile = filename

    output1 = pdffile.replace(".pdf","_ocr.txt")
    output1 = "PATH" + os.path.basename(output1)

    input1 = pdffile.replace(".pdf","_ocr.pdf")

    os.system("pdf2txt" -o  + output1 + " " + input1)

    with open(output1) as myfile:
        pdftxt="".join(line.rstrip() for line in myfile)
    findNum(pdftxt,filename)

def findNum(pdftxt,pdffile):
    l = re.findall(r'\b\d+\b', pdftxt)

    output = open('PATH' + os.path.basename(pdffile) + '.txt', 'w')
    for i in l:
        output.write(",")
        output.write(i)
    output.close()

def is_ascii(s):
    return all(ord(c) < 128 for c in s)

i = 0
files = glob.glob(path + '\\*.pdf')
print path
print files
for file in files:
    if file.endswith(".pdf"):
        if is_ascii(file):
            print file
            pdf2ocr(file)
            ocr2txt(file)
        else:
            newname = "PATH" + str(i) + ".pdf"
            shutil.copyfile(file, newname)
            print newname
            secFile(newname,file)
        i = i + 1

files = glob.glob(path + '\\' + '*_ocr.pdf')

for file in files:
    print file
    shutil.copyfile(file, "PATH" + os.path.basename(file))
    os.remove(file)
</code>```

答:
This solution works for Linux operating system(NoelOCR)

Install NoelOCR

```<code> pip3 install NoelOCR
</code>```

Use it

```<code> import NoelOCR as nm
 text = nm.processPDF('input.pdf')
 print(text)
</code>```

After that you should have your plain text from scanned PDF.

Title: Convert scanned pdf to text python

Body:
I have a scanned pdf file and I try to extract text from it.
I tried to use pypdfocr to make ocr on it but I have error:

"could not found ghostscript in the usual place"

After searching I found this solution Linking Ghostscript to pypdfocr in Windows Platform and I tried to download GhostScript and put it in environment variable but it still has the same error.

How can I searh text in my scanned pdf file using python?

Thanks.

Edit: here is my code sample:

import os
import sys
import re
import json
import shutil
import glob
from pypdfocr import pypdfocr_gs
from pypdfocr import pypdfocr_tesseract
from PIL import Image

path = PATH_TO_MY_SCANNED_PDF
mainL = []
kk = {}

def new_init(self, kk):
    self.lang = 'heb'
    self.binary = "tesseract"
    self.msgs = {
            'TS_MISSING': """
                Could not execute %s
                Please make sure you have Tesseract installed correctly
                """ % self.binary,
            'TS_VERSION':'Tesseract version is too old',
            'TS_img_MISSING':'Cannot find specified tiff file',
            'TS_FAILED': 'Tesseract-OCR execution failed!',
        }

pypdfocr_tesseract.PyTesseract.__init__ = new_init

wow = pypdfocr_gs.PyGs(kk)
tt = pypdfocr_tesseract.PyTesseract(kk)

def secFile(filename,oldfilename):
    wow.make_img_from_pdf(filename)

    files = glob.glob("X:/e206333106/ocr-114/balagan/" + '*.jpg')
    for file in files:
        im = Image.open(file)
        im.save(file + ".tiff")

    files = glob.glob("PATH" + '*.tiff')
    for file in files:
        tt.make_hocr_from_pnm(file)
    pdftxt = ""
    files = glob.glob("PATH" + '*.html')
    for file in files:
        with open(file) as myfile:
            pdftxt = pdftxt + "#" + "".join(line.rstrip() for line in myfile)
    findNum(pdftxt,oldfilename)

    folder ="PATH"

    for the_file in os.listdir(folder):
        file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception, e:
            print e

def pdf2ocr(filename):
    pdffile = filename
    os.system('pypdfocr -l heb ' + pdffile)

def ocr2txt(filename):
    pdffile = filename

    output1 = pdffile.replace(".pdf","_ocr.txt")
    output1 = "PATH" + os.path.basename(output1)

    input1 = pdffile.replace(".pdf","_ocr.pdf")

    os.system("pdf2txt" -o  + output1 + " " + input1)

    with open(output1) as myfile:
        pdftxt="".join(line.rstrip() for line in myfile)
    findNum(pdftxt,filename)

def findNum(pdftxt,pdffile):
    l = re.findall(r'\b\d+\b', pdftxt)

    output = open('PATH' + os.path.basename(pdffile) + '.txt', 'w')
    for i in l:
        output.write(",")
        output.write(i)
    output.close()

def is_ascii(s):
    return all(ord(c) < 128 for c in s)

i = 0
files = glob.glob(path + '\\*.pdf')
print path
print files
for file in files:
    if file.endswith(".pdf"):
        if is_ascii(file):
            print file
            pdf2ocr(file)
            ocr2txt(file)
        else:
            newname = "PATH" + str(i) + ".pdf"
            shutil.copyfile(file, newname)
            print newname
            secFile(newname,file)
        i = i + 1

files = glob.glob(path + '\\' + '*_ocr.pdf')

for file in files:
    print file
    shutil.copyfile(file, "PATH" + os.path.basename(file))
    os.remove(file)

Body:
This solution works for Linux operating system(NoelOCR)

Install NoelOCR

 pip3 install NoelOCR

Use it

 import NoelOCR as nm
 text = nm.processPDF('input.pdf')
 print(text)

After that you should have your plain text from scanned PDF.


问:
Python - How to filter out files that contain char at specific index?
I would like to filter out all files that doesn't contain "-" at index 82.

Sorry, real new to programming in general, any help is appreciated.

答:
You can run the below code directly for files present in your directory(without making a text list of the names if you wish)</p>
```<code>import fnmatch
import os

#assuming there is -- can't come at any other position
pattern = '*--*.docx'

#specify directory path of files
files = os.listdir('')
for name in files:
    if(fnmatch.fnmatch(name, pattern)):
        print ('Filename:',name)
</code>```

Body:
You can run the below code directly for files present in your directory(without making a text list of the names if you wish)

import fnmatch
import os

#assuming there is -- can't come at any other position
pattern = '*--*.docx'

#specify directory path of files
files = os.listdir('')
for name in files:
    if(fnmatch.fnmatch(name, pattern)):
        print ('Filename:',name)


问:
Scrollable responsive content between components
I am trying to make a mobile responsive terms of service page that has a title, content and two buttons. The requirements are:

Components must not exceed 100% of the viewport so the content is scrollable

The Buttons are sticky (bottom)

If the content is short, it has to be just below the title and not in the middle

The page is mobile first friendly (landscape and portrait)

I have done most of it. Using the device toolbar, I am able to view it in mobile (landscape and portrait). The issue is, if toggling to landscape, the components goes beyond 100% of the height. I have tried using flexGrow but it doesn't seem to work so my workaround for now is to specify the height which is not ideal to make it responsive.

Reference: div with 3 rows and scrollable content at the middle

Here is a self-contained sample: https://stackblitz.com/edit/react-em99kh?file=src/App.js

App.js

```<code>const App = () => {
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        height: '100vh',
      }}
    >
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            alignContent: 'center',
            mb: 3,
            mt: 3,
          }}
        >
          <Typography variant="h3">{'Terms of Service'}</Typography>
        </Box>
        <Box
          sx={{
            display: 'flex',
            overflow: 'scroll',
            //Don't want to specify height
            height: '70vh',
            //flexgrow does nothing even if height is removed
            flexGrow: 1,
          }}
        >
          <Typography variant="body1">{data()}</Typography>
        </Box>
      </Box>
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          mb: 3,
          mt: 3,
        }}
      >
        <Button
          id="decline-btn"
          color="primary"
          variant="outlined"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Decline'}
        </Button>
        <Button
          id="accept-btn"
          color="primary"
          variant="contained"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Accept'}
        </Button>
      </Box>
    </Box>
  );
};

export default App;

</code>```

答:
You should probably reorganize a bit the page and then the content part should have a flex: 1 instead of having height: 70vh. Right now your flex-grow does nothing cause the parent div of the flew-grow is not the one with 100vh but the child of it which has no defined height.

Try to have this tree:

```<code>Main div: 100vh - no scroll
 Title Box
 content div: flex-1 scrollable
 Buttons Box
</code>```

Couldn't test but should look like this:

```<code>const App = () => {
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        height: '100vh',
      }}
    >
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            alignContent: 'center',
            mb: 3,
            mt: 3,
          }}
        >
          <Typography variant="h3">{'Terms of Service'}</Typography>
        </Box>
        <Box
          sx={{
            display: 'flex',
            overflow: 'scroll',
            flexGrow: 1,
          }}
        >
          <Typography variant="body1">{data()}</Typography>
        </Box>

      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          mb: 3,
          mt: 3,
        }}
      >
        <Button
          id="decline-btn"
          color="primary"
          variant="outlined"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Decline'}
        </Button>
        <Button
          id="accept-btn"
          color="primary"
          variant="contained"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Accept'}
        </Button>
      </Box>
    </Box>
  );
};

export default App;
</code>```

Body:
I am trying to make a mobile responsive terms of service page that has a title, content and two buttons. The requirements are:

Components must not exceed 100% of the viewport so the content is scrollable

The Buttons are sticky (bottom)

If the content is short, it has to be just below the title and not in the middle

The page is mobile first friendly (landscape and portrait)

I have done most of it. Using the device toolbar, I am able to view it in mobile (landscape and portrait). The issue is, if toggling to landscape, the components goes beyond 100% of the height. I have tried using flexGrow but it doesn't seem to work so my workaround for now is to specify the height which is not ideal to make it responsive.

Reference: div with 3 rows and scrollable content at the middle

Here is a self-contained sample: https://stackblitz.com/edit/react-em99kh?file=src/App.js

App.js

const App = () => {
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        height: '100vh',
      }}
    >
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            alignContent: 'center',
            mb: 3,
            mt: 3,
          }}
        >
          <Typography variant="h3">{'Terms of Service'}</Typography>
        </Box>
        <Box
          sx={{
            display: 'flex',
            overflow: 'scroll',
            //Don't want to specify height
            height: '70vh',
            //flexgrow does nothing even if height is removed
            flexGrow: 1,
          }}
        >
          <Typography variant="body1">{data()}</Typography>
        </Box>
      </Box>
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          mb: 3,
          mt: 3,
        }}
      >
        <Button
          id="decline-btn"
          color="primary"
          variant="outlined"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Decline'}
        </Button>
        <Button
          id="accept-btn"
          color="primary"
          variant="contained"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Accept'}
        </Button>
      </Box>
    </Box>
  );
};

export default App;

Body:
You should probably reorganize a bit the page and then the content part should have a flex: 1 instead of having height: 70vh. Right now your flex-grow does nothing cause the parent div of the flew-grow is not the one with 100vh but the child of it which has no defined height.

Try to have this tree:

Main div: 100vh - no scroll
 Title Box
 content div: flex-1 scrollable
 Buttons Box

Couldn't test but should look like this:

const App = () => {
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'space-between',
        height: '100vh',
      }}
    >
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            alignContent: 'center',
            mb: 3,
            mt: 3,
          }}
        >
          <Typography variant="h3">{'Terms of Service'}</Typography>
        </Box>
        <Box
          sx={{
            display: 'flex',
            overflow: 'scroll',
            flexGrow: 1,
          }}
        >
          <Typography variant="body1">{data()}</Typography>
        </Box>

      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          mb: 3,
          mt: 3,
        }}
      >
        <Button
          id="decline-btn"
          color="primary"
          variant="outlined"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Decline'}
        </Button>
        <Button
          id="accept-btn"
          color="primary"
          variant="contained"
          sx={{
            borderRadius: 16,
            width: '47%',
            height: '50px',
          }}
        >
          {'Accept'}
        </Button>
      </Box>
    </Box>
  );
};

export default App;


问:
How can I use a variable string with getRangeList() to select noncontinguous rows in a Sheet?
I need to be able to create variable strings that will be used by getRangeList() to select non-contiguous rows in a Google Sheet. The string will be different every time it's run. It might be gathering 20 rows one time and 4 the next (always in 2-row sets, incidentally). When I record a macro to select sample rows 8 and 9 and then 14 and 15, it gives me this:

```<code>function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRangeList(['8:9', '14:15']).activate();
};
</code>```

Running this does fine--selecting the four rows. I hoped that this meant I could simply use script to create a string like "'8:9', '14:15'" as a variable and embed it in the code, as in:

```<code>function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "'8:9', '14:15'";
  spreadsheet.getRangeList([myRange]).activate();
};
</code>```

This gives me the error "Exception: Range not found."

I considered that the problem was in the special characters and tried this instead:

```<code>function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "\'8:9\', \'14:15\'";
  spreadsheet.getRangeList([myRange]).activate();
};
</code>```

This gives me the same error: "Exception: Range not found."

I wondered if the problem was with the brackets inside the parentheses and tried this:

```<code>function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "[\'8:9\', \'14:15\']";
  spreadsheet.getRangeList(myRange).activate();
};
</code>```

I got this error: "Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Spreadsheet.getRangeList."

I got the same error when I tried it with the brackets embedded in the string with the first example--the one without the slashes for the special characters, so:

```<code>function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "['8:9', '14:15']";
  spreadsheet.getRangeList(myRange).activate();
};

How can I create variable strings that will work with getRangeList() to select non-contiguous pairs of rows?

</code>```

答:
Try

```<code>function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = []
  myRange.push("8:9")
  myRange.push("14:15")
  spreadsheet.getRangeList(myRange).activate();
};
</code>```

myRange is an array

Body:
I need to be able to create variable strings that will be used by getRangeList() to select non-contiguous rows in a Google Sheet. The string will be different every time it's run. It might be gathering 20 rows one time and 4 the next (always in 2-row sets, incidentally). When I record a macro to select sample rows 8 and 9 and then 14 and 15, it gives me this:

function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRangeList(['8:9', '14:15']).activate();
};

Running this does fine--selecting the four rows. I hoped that this meant I could simply use script to create a string like "'8:9', '14:15'" as a variable and embed it in the code, as in:

function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "'8:9', '14:15'";
  spreadsheet.getRangeList([myRange]).activate();
};

This gives me the error "Exception: Range not found."

I considered that the problem was in the special characters and tried this instead:

function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "\'8:9\', \'14:15\'";
  spreadsheet.getRangeList([myRange]).activate();
};

This gives me the same error: "Exception: Range not found."

I wondered if the problem was with the brackets inside the parentheses and tried this:

function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "[\'8:9\', \'14:15\']";
  spreadsheet.getRangeList(myRange).activate();
};

I got this error: "Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Spreadsheet.getRangeList."

I got the same error when I tried it with the brackets embedded in the string with the first example--the one without the slashes for the special characters, so:

function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = "['8:9', '14:15']";
  spreadsheet.getRangeList(myRange).activate();
};

How can I create variable strings that will work with getRangeList() to select non-contiguous pairs of rows?

Body:
Try

function testMe() {
  var spreadsheet = SpreadsheetApp.getActive();
  var myRange = []
  myRange.push("8:9")
  myRange.push("14:15")
  spreadsheet.getRangeList(myRange).activate();
};

myRange is an array


问:
Git prompts for username and password for git push origin master command

Every time I was trying to push the new commits to the master branch through git push origin master command, git was prompting me with credentials. I wanted to convert the url from HTTPS to SSH through these commands:

```<code>$git remote add origin https://github.com/Ananya2001-an/FirstRepository
$git config --global credential.helper store
$git config --global credential.helper cache
</code>```

But now though it is not asking for the credentials, it's still not pushing the commits and instead showing me that Permission to access is denied and I can't read from my remote repository.
Kindly help me with this issue that I am facing right now.

答:
First of all, get git repository link from your GitHub account

e.g. https://github.com/imrankabir/my-react-app.git

git remote set-url origin https://imrankabir@github.com/imrankabir/my-react-app.git

Notice the username added after https://{imrankabir@}

now run the following command

git config credential.helper store

git pull origin master

it will ask for your GitHub password just for once same it on the machine.

if the future it will not ask for the password again.

Body:
Every time I was trying to push the new commits to the master branch through git push origin master command, git was prompting me with credentials. I wanted to convert the url from HTTPS to SSH through these commands:

$git remote add origin https://github.com/Ananya2001-an/FirstRepository
$git config --global credential.helper store
$git config --global credential.helper cache

But now though it is not asking for the credentials, it's still not pushing the commits and instead showing me that Permission to access is denied and I can't read from my remote repository.
Kindly help me with this issue that I am facing right now.


问:
Can Retrofit with OKHttp use cache data when offline
I'm trying to use Retrofit & OKHttp to cache HTTP responses. I followed this gist and, ended up with this code:

File httpCacheDirectory = new File(context.getCacheDir(), "responses");

HttpResponseCache httpResponseCache = null;
try {
     httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
     Log.e("Retrofit", "Could not create http cache", e);
}

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);

api = new RestAdapter.Builder()
          .setEndpoint(API_URL)
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setClient(new OkClient(okHttpClient))
          .build()
          .create(MyApi.class);
```

<p>And this is MyApi with the Cache-Control headers
</p>

```public interface MyApi {
   @Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=2419200")
   @GET("/api/v1/person/1/")
   void requestPerson(
           Callback<Person> callback
   );
```

First I request online and check the cache files. The correct JSON response and headers are there. But when I try to request offline, I always get RetrofitError UnknownHostException. Is there anything else I should do to make Retrofit read the response from cache?

EDIT:
Since OKHttp 2.0.x HttpResponseCache is Cache, setResponseCache is setCache

答: Attention! OkHttp build in cache only work for GET method(refer to above solution). If you want to cache POST request, you must implement yourself.

Body:
I'm trying to use Retrofit & OKHttp to cache HTTP responses. I followed this gist and, ended up with this code:

File httpCacheDirectory = new File(context.getCacheDir(), "responses");

HttpResponseCache httpResponseCache = null;
try {
     httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024);
} catch (IOException e) {
     Log.e("Retrofit", "Could not create http cache", e);
}

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);

api = new RestAdapter.Builder()
          .setEndpoint(API_URL)
          .setLogLevel(RestAdapter.LogLevel.FULL)
          .setClient(new OkClient(okHttpClient))
          .build()
          .create(MyApi.class);

And this is MyApi with the Cache-Control headers

public interface MyApi {
   @Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=2419200")
   @GET("/api/v1/person/1/")
   void requestPerson(
           Callback<Person> callback
   );

First I request online and check the cache files. The correct JSON response and headers are there. But when I try to request offline, I always get RetrofitError UnknownHostException. Is there anything else I should do to make Retrofit read the response from cache?

EDIT:
Since OKHttp 2.0.x HttpResponseCache is Cache, setResponseCache is setCache


问:
Mocking Entity Framework Context
I'm using the entity framework to access my database and I want to mock the database context inside my unit tests so that I can test my middle tier classes free of their dependency on real data. I know that I'm not the first to ask about this (Mocking an Entity Framework Model), but after some googling I have an instinct that it might be possible to instantiate the context based on the model's metadata alone.

Has anyone been able to do this?

答: You can do it with just metadata, there's a good article on it, and unit testing EF in general, here.</p>

ContentLicense: CC BY-SA 2.5

Title: Mocking Entity Framework Context

OwnerDisplayName: Steve Robbins


问:
Reproduce uuid from java code in python
In a Java application files are created where the filename is a UUID generated from a protein sequence (e.g. TTCCPSIVARSNFNVCRLPGTPEAICATYTGCIIIPGATCPGDYAN) created using the function UUID.nameUUIDFromBytes. This results in the UUID c6a0deb5-0c4f-3961-9d19-3f0fde0517c2.

UUID.namedUUIDFromBytes doesn't take a namespace as a parameter, whereas in python uuid.uuid3 does. According to What namespace does the JDK use to generate a UUID with nameUUIDFromBytes?, the namespace should have been passed as part of the name, but it's no longer possible to change the java code.

Is there a way to create a custom namespace in the python code such that it will produce the same UUID's as the Java code?

答:
@turbomeri's answer is right.. just python code didn't had few mistakes, so corrected the version</p>
```<code>a = 'sometextinhere'
namespaceUUID = uuid.UUID('9db60607-6b12-41eb-8848-eafd26681583')
print(str(uuid.uuid3(namespaceUUID, a)))```
</code>```

Title: Reproduce uuid from java code in python

Body:
@turbomeri's answer is right.. just python code didn't had few mistakes, so corrected the version

a = 'sometextinhere'
namespaceUUID = uuid.UUID('9db60607-6b12-41eb-8848-eafd26681583')
print(str(uuid.uuid3(namespaceUUID, a)))```


问:
Flutter List with background color shades in descending order
Attached is the screenshot of the problem I need to solve.

There is a simple list which needs to be color coded according to the priority.

The first list element will have highest priority with the darkest color shade and the color will fade with each list item traversed down.

I've tried making a separate list of variation of a color and using them by calling explicitly for ListTile background but it's not optimal for a list that can have infinite items.

I thought ColorTween may help but I'm still not able to figure it out.

答:
By using opacity or alpha option of Color, you can change background color.

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _buildBody() {
    return ListView.builder(
      itemCount: 60,
      itemBuilder: (BuildContext ctx, int index) {
        double opcaity = (1.0 - 0.01 * index) < 0 ? 0 : (1.0 - 0.01 * index);
        return Stack(
          children: [
            Container(
              height: 50,
              width: double.infinity,
              color: Colors.blue.withOpacity(opcaity),
              child: Text(
                '$index',
                style: TextStyle(
                  fontSize: 25,
                  color: Colors.white,
                ),
              ),
            ),
            Positioned(
              right: 0,
              child: Container(
                  width: 50,
                  height: 50,
                  color: Colors.white.withOpacity(0.1),
                  child: Text(
                    '0',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 25,
                      color: Colors.white,
                    ),
                  )),
            )
          ],
        );
      },
    );
  }
}

</code>```

Body:
By using opacity or alpha option of Color, you can change background color.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _buildBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _buildBody() {
    return ListView.builder(
      itemCount: 60,
      itemBuilder: (BuildContext ctx, int index) {
        double opcaity = (1.0 - 0.01 * index) < 0 ? 0 : (1.0 - 0.01 * index);
        return Stack(
          children: [
            Container(
              height: 50,
              width: double.infinity,
              color: Colors.blue.withOpacity(opcaity),
              child: Text(
                '$index',
                style: TextStyle(
                  fontSize: 25,
                  color: Colors.white,
                ),
              ),
            ),
            Positioned(
              right: 0,
              child: Container(
                  width: 50,
                  height: 50,
                  color: Colors.white.withOpacity(0.1),
                  child: Text(
                    '0',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 25,
                      color: Colors.white,
                    ),
                  )),
            )
          ],
        );
      },
    );
  }
}


答:
For moviepy==1.0.3

use

```<code>logger=None
</code>```

Title: Moviepy still prints a progress bar even after setting `verbose` to `False`

Body:
I tried to suppress the console output produced from moviepy when calling the "write_videofile" method.
I passed the verbose argument as False to no avail.
It still outputs something like:

0%| | 0/1624 [00:00<?, ?it/s]
0%| | 8/1624 [00:00<00:20, 77.64it/s]
1%| | 16/1624 [00:00<00:20, 78.31it/s]
2%|1 | 25/1624 [00:00<00:20, 77.90it/s]
2%|2 | 34/1624 [00:00<00:19, 80.80it/s]
3%|2 | 42/1624 [00:00<00:20, 75.91it/s]
3%|3 | 51/1624 [00:00<00:20, 76.07it/s]
4%|3 | 58/1624 [00:00<00:25, 62.44it/s]
4%|4 | 65/1624 [00:00<00:28, 54.77it/s]
4%|4 | 71/1624 [00:01<00:28, 53.63it/s]
5%|4 | 77/1624 [00:01<00:29, 52.69it/s]
5%|5 | 83/1624 [00:01<00:28, 54.06it/s]
5%|5 | 89/1624 [00:01<00:29, 52.80it/s]
6%|5 | 96/1624 [00:01<00:26, 56.95it/s]
6%|6 | 102/1624 [00:01<00:29, 52.38it/s]
7%|6 | 108/1624 [00:01<00:29, 51.74it/s]
...
...
...
100%|#########9| 1621/1624 [00:28<00:00, 51.43it/s]
100%|##########| 1624/1624 [00:28<00:00, 57.75it/s]

Is there any way to suppress completely the output?

Body:
For moviepy==1.0.3

use

logger=None


问:
Convert a txt document to a list to a list starting with [[, instead of ['[
I have a .txt document with this type of text:

[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]

(which represents a sentence and the Parts of Speech tags for each word)

I want to have a list of list in python, like this:

[[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]]

But I obtain this:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\n']

The code I'm using is:

```<code>import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)
</code>```

How can I avoid the ['[ .... ]\n']  ?

Thank you!

答:
you can delete a blank line with strip method, like:</p>
```<code>f_list[0] = f_list[0].rstrip()
</code>```

Body:
I have a .txt document with this type of text:

[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]

(which represents a sentence and the Parts of Speech tags for each word)

I want to have a list of list in python, like this:

[[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]]

But I obtain this:

['[(“Vazhdo”,”verb”),(“të”,”particle”),(“ecësh”,”verb”),(“!”,”excl.”)]\n']

The code I'm using is:

import io
f=io.open("test.txt", mode="r", encoding="utf-8-sig")
f_list = list(f)

How can I avoid the ['[ .... ]\n']  ?

Thank you!

Body:
you can delete a blank line with strip method, like:

f_list[0] = f_list[0].rstrip()


问:
Is Sitemesh 2.4 release broken?
We've recently upgraded one of our projects. This involves new versions of JARs also.

Sitemesh was one of them. We updated from 2.2.1 to 2.4.2. Things stopped working.

We had a custom filter extend Sitemesh's PageFilter which now does not work because in v2.4 PageFilter extends SiteMeshFilter which does not expose the same methods (the ones we were overriding).

OK, no biggy, we'll just change our code to match, but then I saw this in the source code I downloaded from http://java.net/downloads/sitemesh/

```<code>/**
 * Core Filter for integrating SiteMesh into a Java web application.
 *
 * @author Joe Walnes
 * @author Scott Farquhar
 * @since SiteMesh 3
 */
public class SiteMeshFilter implements Filter {

    private FilterConfig filterConfig;
    private ContainerTweaks containerTweaks;
    private static final String ALREADY_APPLIED_KEY = "com.opensymphony.sitemesh.APPLIED_ONCE";
............
</code>```

@since SiteMesh 3? This is v2.4.2. What 3?

Is the release corrupt or what? Am I missing something?

答:
I'm using sitemesh 2.4.2 in one project and it works fine.

You can see that that change (which mentions Sitemesh 3) was done back in 2005 when they refactored the architecture to be compatible with sitemesh3. Here's the commit in github.

I remember getting a similar impression when I was browsing the javadocs a few months ago :).

So the answer is: The jar is not corrupt, it's just the result of a crooked merge.

Title: Is Sitemesh 2.4 release broken?

Body:
We've recently upgraded one of our projects. This involves new versions of JARs also.

Sitemesh was one of them. We updated from 2.2.1 to 2.4.2. Things stopped working.

We had a custom filter extend Sitemesh's PageFilter which now does not work because in v2.4 PageFilter extends SiteMeshFilter which does not expose the same methods (the ones we were overriding).

OK, no biggy, we'll just change our code to match, but then I saw this in the source code I downloaded from http://java.net/downloads/sitemesh/

/**
 * Core Filter for integrating SiteMesh into a Java web application.
 *
 * @author Joe Walnes
 * @author Scott Farquhar
 * @since SiteMesh 3
 */
public class SiteMeshFilter implements Filter {

    private FilterConfig filterConfig;
    private ContainerTweaks containerTweaks;
    private static final String ALREADY_APPLIED_KEY = "com.opensymphony.sitemesh.APPLIED_ONCE";
............

@since SiteMesh 3? This is v2.4.2. What 3?

Is the release corrupt or what? Am I missing something?


问:
create-react-app, react-slick, video playback holds while sound is playing
I'm implementing kiosk program using react.
There is a problem which is really weird.

The first screen shows slides using react-slick.

Slides include pictures and videos.

Sometimes, video stops playing while only the sound of the video is playing.

I checked event from video element. While the video stops, 'play' event is triggered.

In order to play sound, you need to change settings in chrome.

Input chrome://settings/content/sound in chrome address, and add a site 'localhost' to 'allowed sites to play sound'.
This problem reproduces randomly.

You can test with 'npm start' command.

Here's github source code link.
source

答:
The problem was solved.
I changed slide library from react-slick to swiper-react.
I don't know exactly why the problem was solved.
You can see the source code in my github.</p>


问:
How to convert a String column to Date column for a PySpark dataframe using strptime function?
I want to convert a string column to a date column for a pyspark dataframe as follows :

|Date|
+-------+---
|10-Nov-15|

|11-Oct-17|

I know strptime function would work, but unable to use it with PySpark dataframe.

答:
You can directly use to_date , which is natively present in Pyspark

The key is to find the appropriate parsing patterns.

The available DateTime Patterns for Parsing can be found - https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html

Furthermore to handle edge cases , like - 2-Feb-20 and 02-Feb-20 , you can set the timeParserPolicy=LEGACY as the above link is applicable for Spark 3.x , more info about this can be found here

Data Preparation

```<code>d = {
        'date_col':['10-Oct-15', '11-Oct-17', '2-Feb-20', '02-Feb-20']
    }

sparkDF = sql.createDataFrame(pd.DataFrame(d))

sparkDF.show()
+---------+
| date_col|
+---------+
|10-Oct-15|
|11-Oct-17|
| 2-Feb-20|
|02-Feb-20|
+---------+

sparkDF.printSchema()

root
 |-- date_col: string (nullable = true)
</code>```

To Date

```<code>sql.sql("set spark.sql.legacy.timeParserPolicy=LEGACY")

sparkDF = sparkDF.withColumn('date_col_parsed',F.to_date(F.col('date_col'),'dd-MMM-yy'))

+---------+---------------+
| date_col|date_col_parsed|
+---------+---------------+
|10-Oct-15|     2015-10-10|
|11-Oct-17|     2017-10-11|
| 2-Feb-20|     2020-02-02|
|02-Feb-20|     2020-02-02|
+---------+---------------+

sparkDF.printSchema()

root
 |-- date_col: string (nullable = true)
 |-- date_col_parsed: date (nullable = true)
</code>```

To Date - SparkSQL

```<code>sparkDF.registerTempTable("TB1")

sql.sql(
    """
    SELECT
         date_col
        ,TO_DATE(date_col,'dd-MMM-yy') as date_col_parsed
    FROM TB1
    """
).show()

+---------+---------------+
| date_col|date_col_parsed|
+---------+---------------+
|10-Oct-15|     2015-10-10|
|11-Oct-17|     2017-10-11|
| 2-Feb-20|     2020-02-02|
|02-Feb-20|     2020-02-02|
+---------+---------------+
</code>```

Body:
You can directly use to_date , which is natively present in Pyspark

The key is to find the appropriate parsing patterns.

The available DateTime Patterns for Parsing can be found - https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html

Furthermore to handle edge cases , like - 2-Feb-20 and 02-Feb-20 , you can set the timeParserPolicy=LEGACY as the above link is applicable for Spark 3.x , more info about this can be found here

Data Preparation

d = {
        'date_col':['10-Oct-15', '11-Oct-17', '2-Feb-20', '02-Feb-20']
    }

sparkDF = sql.createDataFrame(pd.DataFrame(d))

sparkDF.show()
+---------+
| date_col|
+---------+
|10-Oct-15|
|11-Oct-17|
| 2-Feb-20|
|02-Feb-20|
+---------+

sparkDF.printSchema()

root
 |-- date_col: string (nullable = true)

To Date

sql.sql("set spark.sql.legacy.timeParserPolicy=LEGACY")

sparkDF = sparkDF.withColumn('date_col_parsed',F.to_date(F.col('date_col'),'dd-MMM-yy'))

+---------+---------------+
| date_col|date_col_parsed|
+---------+---------------+
|10-Oct-15|     2015-10-10|
|11-Oct-17|     2017-10-11|
| 2-Feb-20|     2020-02-02|
|02-Feb-20|     2020-02-02|
+---------+---------------+

sparkDF.printSchema()

root
 |-- date_col: string (nullable = true)
 |-- date_col_parsed: date (nullable = true)

To Date - SparkSQL

sparkDF.registerTempTable("TB1")

sql.sql(
    """
    SELECT
         date_col
        ,TO_DATE(date_col,'dd-MMM-yy') as date_col_parsed
    FROM TB1
    """
).show()

+---------+---------------+
| date_col|date_col_parsed|
+---------+---------------+
|10-Oct-15|     2015-10-10|
|11-Oct-17|     2017-10-11|
| 2-Feb-20|     2020-02-02|
|02-Feb-20|     2020-02-02|
+---------+---------------+


问:
Huawei - Cannot upload watch face with the latest version Health app
I cannot upload my custom watch face with the latest version Health app.</p>

答:
Cannot you upload, watch face with the latest version Health app,

There could be following reasons:

You must install the beta version of the Huawei Health app; otherwise, you cannot add watch faces for testing.

If the beta version fails to be installed, uninstall the official Huawei Health app from your phone, and then reinstall the beta version.

You must sign in to the app using a HUAWEI ID that has passed designer certification; otherwise, you cannot add watch faces for testing.

For details about designer certification, please refer to Registration & Certification.

For details , please check below guide
https://developer.huawei.com/consumer/en/doc/distribution/content/gtwatch-specification-0000001077917528#section1978213113313


问:
How do you use fetch api to an ec2 instance?
I've been trying to find a good free server for our school project so I've decided to try ec2 and just make my pc the server that I will use. I've managed to install my node server onto the ec2. I can post requests using postman but when I'm trying to fetch data from my html file to the ec2 instance, it says:

Fetch API cannot load ec2xxxxxx.amazonaws.com:3000/login. URL scheme "ecxxxxxxx.compute-1.amazonaws.com" is not supported.

Is there any workaround for this? Thanks in advance!!!

答:
The error is literally telling you what the problem is:

"URL scheme... is not supported"

Do you know what the "scheme" portion of a url is? This link should help, but it's the something:// portion of a uri/url.

So it indicates that you need to specify a scheme that will get you to your aws server, which is likely either http:// or https://

So to be clear your fetch needs fetch('http://ec2xxxxxx.amazonaws.com:3000/login').


问:
Unable to display VBO in OpenGL
I have a VBO and an IBO in OpenGL, but am unable to draw them properly. Could you please let me know what I could have forgotten in the frame display function ?
- struct Point3D is a struct with 3 floats inside (x,y,z).
- nbVertex is the amount of vertexes in the glVertex array.
- nbVBOInd is the amount of indices in the VBOInd array.

```<code>    glGenBuffers(1, &VertexVBOID);
    glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(struct Point3D)*nbVertex, glVertex, GL_STATIC_DRAW);

    glGenBuffers(1, &IndexVBOID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBOID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)*nbVBOInd, VBOInd, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3, GL_FLOAT, sizeof(glVertex), BUFFER_OFFSET(0));   //The starting point of the VBO, for the vertices

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBOID);
    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));   //The starting point of the IBO
</code>```

Thanks !

答:
Try changing the last line to:

```<code>glDrawElements(GL_TRIANGLES, nbVBOInd, GL_UNSIGNED_INT, BUFFER_OFFSET(0));
</code>```

Unless your data in the IndexVBOID are really short, but then, the sizeof(int) above would be wrong.

Title: Unable to display VBO in OpenGL

Body:
I have a VBO and an IBO in OpenGL, but am unable to draw them properly. Could you please let me know what I could have forgotten in the frame display function ?
- struct Point3D is a struct with 3 floats inside (x,y,z).
- nbVertex is the amount of vertexes in the glVertex array.
- nbVBOInd is the amount of indices in the VBOInd array.

    glGenBuffers(1, &VertexVBOID);
    glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(struct Point3D)*nbVertex, glVertex, GL_STATIC_DRAW);

    glGenBuffers(1, &IndexVBOID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBOID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int)*nbVBOInd, VBOInd, GL_STATIC_DRAW);

    glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(3, GL_FLOAT, sizeof(glVertex), BUFFER_OFFSET(0));   //The starting point of the VBO, for the vertices

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexVBOID);
    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));   //The starting point of the IBO

Thanks !

Body:
Try changing the last line to:

glDrawElements(GL_TRIANGLES, nbVBOInd, GL_UNSIGNED_INT, BUFFER_OFFSET(0));

Unless your data in the IndexVBOID are really short, but then, the sizeof(int) above would be wrong.


问:
MySQL; GROUP BY but only if column is not empty
I have the following SQL query:

```<code>SELECT * FROM my_table GROUP BY B,D,F;
</code>```

If there are some rows where B is empty and D is empty AND F is empty, it'll grouped to a single row where all the three columns are empty.

But instead I want: in case all three columns (B, D, F) of a row are empty don't group this row show it.

Means: If I have the following:

result should be:

How can I do this?

答:
try

```<code>SELECT * FROM my_table GROUP BY B,D,F,IF((B="" AND D="" AND F=""),id,0);
</code>```

assuming that id is a unique key.

if any of the columns you want to group by aren't empty, zero is retuned instead of id, but if all three ARE empty, then id is returned, and thus ones with all three others empty are no longer grouped.

And yes, this works with select *.

Body:
I have the following SQL query:

SELECT * FROM my_table GROUP BY B,D,F;

If there are some rows where B is empty and D is empty AND F is empty, it'll grouped to a single row where all the three columns are empty.

But instead I want: in case all three columns (B, D, F) of a row are empty don't group this row show it.

Means: If I have the following:

result should be:

How can I do this?

Body:
try

SELECT * FROM my_table GROUP BY B,D,F,IF((B="" AND D="" AND F=""),id,0);

assuming that id is a unique key.

if any of the columns you want to group by aren't empty, zero is retuned instead of id, but if all three ARE empty, then id is returned, and thus ones with all three others empty are no longer grouped.

And yes, this works with select *.


问:
Best way to Try/Catch HTTP response in Google Script
I'm still new to JavaScript and Google apps script, and this is the first time I'm trying to use a 'Try/Catch' statement.

I'm running a script that connects to a page. It connects most of the time without issue, but occasionally it won't respond and throw a http error (Or, the response will be empty). I want to try/catch this response to have it run a second time if I get an error code, but I'm not 100% sure I understand the syntax, because no matter how I format it, It either never throws the exception, or always throws it.

Here is some sample code I've been experimenting with:

```<code>function myFunction() {
  var response =  UrlFetchApp.fetch("google.com");
  Logger.log('Response Code: ' + response.getResponseCode());

try {if(response.getResponseCode() === 200);
} catch (err) {
    throw 'Page connected';
}
}
</code>```

If I can get this to work, I'm sure I can figure out the rest. However, even though the log shows me I get a HTTP response of 200, it never throws the error 'Page connected'.

If someone can guide me on:

1) Is this the correct method to achieve what I want, or is Try/Catch for something else?
 2) The correct syntax.

I would be very grateful.

答:
You can use option muteHttpExceptions to handle the exception yourself.

According to docs:

muteHttpExceptions: If true the fetch doesn't throw an exception if
the response code indicates failure, and instead returns the
HTTPResponse. The default is false.

Of course, here is the example code:

```<code>function DoSomething(url)
{
  var options =
  {
  'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() == 200)
  {
    //Do anything with url data...
    return "Success!!!";
  }
  else
  {
    console.log("Response Code: " + response.getResponseCode());
    console.log("Content Text:\n" + response.getContentText());
    return "Failed :(";
  }

}
</code>```

Body:
I'm still new to JavaScript and Google apps script, and this is the first time I'm trying to use a 'Try/Catch' statement.

I'm running a script that connects to a page. It connects most of the time without issue, but occasionally it won't respond and throw a http error (Or, the response will be empty). I want to try/catch this response to have it run a second time if I get an error code, but I'm not 100% sure I understand the syntax, because no matter how I format it, It either never throws the exception, or always throws it.

Here is some sample code I've been experimenting with:

function myFunction() {
  var response =  UrlFetchApp.fetch("google.com");
  Logger.log('Response Code: ' + response.getResponseCode());

try {if(response.getResponseCode() === 200);
} catch (err) {
    throw 'Page connected';
}
}

If I can get this to work, I'm sure I can figure out the rest. However, even though the log shows me I get a HTTP response of 200, it never throws the error 'Page connected'.

If someone can guide me on:

1) Is this the correct method to achieve what I want, or is Try/Catch for something else?
 2) The correct syntax.

I would be very grateful.

Body:
You can use option muteHttpExceptions to handle the exception yourself.

According to docs:

muteHttpExceptions: If true the fetch doesn't throw an exception if
the response code indicates failure, and instead returns the
HTTPResponse. The default is false.

Of course, here is the example code:

function DoSomething(url)
{
  var options =
  {
  'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() == 200)
  {
    //Do anything with url data...
    return "Success!!!";
  }
  else
  {
    console.log("Response Code: " + response.getResponseCode());
    console.log("Content Text:\n" + response.getContentText());
    return "Failed :(";
  }

}