问:
How do I move an element on a canvas around with an animation?
I have been looking for a while on how to move a certain square around on a canvas with JavaScript, and haven't found much. I have done one where it removes itself and replaces itself every frame, but I want it to be smoother and animated. This is my code:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas>

<button onclick="#">Move Up</button>

```

So far the button does nothing, is there a function I could add that would move the square around? (in this case up)

答:
To make smooth animations, check about the requestAnimationFrame function (https://developer.mozilla.org/fr/docs/Web/API/Window/requestAnimationFrame).

Here an example with your code:

canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');

var squareY = 60;
var isButtonPressed = false;

ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);

function moveUp() {
  window.requestAnimationFrame(moveUp);

  if (isButtonPressed) {
    squareY -= 10 / 16;
  }

  squareY = Math.max(squareY, 5);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(20, squareY, 20, 20);
}

function onMouseUp() {
  isButtonPressed = false;
}

function onMouseDown() {
  isButtonPressed = true;
}
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');

var squareY = 60;
var isButtonPressed = false;

ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);

function moveUp() {
  window.requestAnimationFrame(moveUp);

  if (isButtonPressed) {
    squareY -= 10 / 16;
  }

  squareY = Math.max(squareY, 5);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(20, squareY, 20, 20);
}

function onMouseUp() {
  isButtonPressed = false;
}

function onMouseDown() {
  isButtonPressed = true;
}

window.addEventListener('keydown', function (e) {
  if (e.key == 'ArrowUp') {
    // if the arrow key is pressed
    squareY -= 10 / 16;
  }
});

moveUp();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onmousedown="onMouseDown()" onmouseup="onMouseUp()">Move Up</button>
<script>
</script></code>```

Body:
I have been looking for a while on how to move a certain square around on a canvas with JavaScript, and haven't found much. I have done one where it removes itself and replaces itself every frame, but I want it to be smoother and animated. This is my code:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas>

<button onclick="#">Move Up</button>

So far the button does nothing, is there a function I could add that would move the square around? (in this case up)

Body:
To make smooth animations, check about the requestAnimationFrame function (https://developer.mozilla.org/fr/docs/Web/API/Window/requestAnimationFrame).

Here an example with your code:

canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');

var squareY = 60;
var isButtonPressed = false;

ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);

function moveUp() {
  window.requestAnimationFrame(moveUp);

  if (isButtonPressed) {
    squareY -= 10 / 16;
  }

  squareY = Math.max(squareY, 5);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(20, squareY, 20, 20);
}

function onMouseUp() {
  isButtonPressed = false;
}

function onMouseDown() {
  isButtonPressed = true;
}
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');

var squareY = 60;
var isButtonPressed = false;

ctx.fillStyle = '#FF0000';
ctx.fillRect(20, squareY, 20, 20);

function moveUp() {
  window.requestAnimationFrame(moveUp);

  if (isButtonPressed) {
    squareY -= 10 / 16;
  }

  squareY = Math.max(squareY, 5);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(20, squareY, 20, 20);
}

function onMouseUp() {
  isButtonPressed = false;
}

function onMouseDown() {
  isButtonPressed = true;
}

window.addEventListener('keydown', function (e) {
  if (e.key == 'ArrowUp') {
    // if the arrow key is pressed
    squareY -= 10 / 16;
  }
});

moveUp();

<canvas id="myCanvas" width="200" height="100" style="border:1px solid grey;"></canvas><br />
<button onmousedown="onMouseDown()" onmouseup="onMouseUp()">Move Up</button>
<script>
</script>


来源: stackexchange

问:
Getting null pointer exception while run my code with TestNG and Cucumber?
Getting "Null pointer Exception" while Run my code.

Runner class

Main Class

答: The driver instance initialized in your TestRunner class inside the @BeforeSuite method is not retrieved inside SignIn class automatically. You should create a getter method to get the driver object from TestRunner to SignIn class or use the inheritance concept to get the driver. This is the reason why you are getting a NullPointerException. You are trying to access a driver object that is not initialized in SignIn class.</p>

ContentLicense: CC BY-SA 4.0


问:
How to reload Flask-based webpage after receiving data
I have a simple web project which gets data from, processes it and needs to output result on the page. After the spider works, the data is written to sqlite, but not displayed on the page. How to refresh page after writing data in sqlite?

button

```<code><button id="scrape" class="btn btn-success mr-2">Scrape</button>
</code>```

js

```<code>$.post('/wellness', {'specialty': specialty, 'state': state, 'city': city}, (res) => {
});
</code>```

flask

```<code>@app.route('/<page_id>', methods=['GET', 'POST'])
def page(page_id):
file_html = f"{page_id}.html"
file_py = f"{page_id}.py"
file_db = f"{page_id}.db"

specialty = request.form.getlist('specialty[]')
state = request.form.getlist('state[]')
city = request.form.getlist('city[]')

settings = ''
with open('settings.json', 'r') as f:
    for line in f.read():
        settings += line

settings = json.loads(settings)
settings['specialty'] = specialty
settings['state'] = state
settings['city'] = city

with open('settings.json', 'w') as f:
    f.write(json.dumps(settings, indent=4))

process = subprocess.Popen('python e:/Python/sqlite/spiders/' + file_py, shell=True)
process.wait()

try:
    db = sqlite3.connect(file_db)
    cursor = db.cursor()

    cursor.execute('SELECT * FROM wellness ORDER BY id DESC')
    cards = cursor.fetchall()

    db.close()
    return render_template(file_html, cards = cards)
except:
    return render_template(file_html)
</code>```

答:
solution:</p>

```<code>$.post('/wellness', {'specialty': specialty, 'state': state, 'city': city}, (res) => {
  $(location).attr('href', 'http://127.0.0.1:5000/wellness')
});
</code>```

Body:
I have a simple web project which gets data from, processes it and needs to output result on the page. After the spider works, the data is written to sqlite, but not displayed on the page. How to refresh page after writing data in sqlite?

button

<button id="scrape" class="btn btn-success mr-2">Scrape</button>

js

$.post('/wellness', {'specialty': specialty, 'state': state, 'city': city}, (res) => {
});

flask

@app.route('/<page_id>', methods=['GET', 'POST'])
def page(page_id):
file_html = f"{page_id}.html"
file_py = f"{page_id}.py"
file_db = f"{page_id}.db"

specialty = request.form.getlist('specialty[]')
state = request.form.getlist('state[]')
city = request.form.getlist('city[]')

settings = ''
with open('settings.json', 'r') as f:
    for line in f.read():
        settings += line

settings = json.loads(settings)
settings['specialty'] = specialty
settings['state'] = state
settings['city'] = city

with open('settings.json', 'w') as f:
    f.write(json.dumps(settings, indent=4))

process = subprocess.Popen('python e:/Python/sqlite/spiders/' + file_py, shell=True)
process.wait()

try:
    db = sqlite3.connect(file_db)
    cursor = db.cursor()

    cursor.execute('SELECT * FROM wellness ORDER BY id DESC')
    cards = cursor.fetchall()

    db.close()
    return render_template(file_html, cards = cards)
except:
    return render_template(file_html)

Body:
solution:

$.post('/wellness', {'specialty': specialty, 'state': state, 'city': city}, (res) => {
  $(location).attr('href', 'http://127.0.0.1:5000/wellness')
});


问:
How to initialize an entity passing in an object using typeorm
I have an entity "List" and i want to create a new list by passing in an object into the constructor.

List.ts

```<code>import {Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from "typeorm";

@Entity()
export class List {

    @PrimaryColumn()
    id: string;

    @Column({type: "varchar", nullable: true})
    dtype: string;

    @Column({type: "varchar", nullable: true})
    title: string;

    @Column({type: "varchar"})
    user_id: string;

    @Column({type: "varchar", nullable: true})
    brand_id: string;

    @CreateDateColumn({type: "timestamp", nullable: true})
    created_at: string;

    @UpdateDateColumn({type: "timestamp", nullable: true})
    updated_at: string;

    @DeleteDateColumn({type: "timestamp", nullable: true})
    deleted_at: string;

}
</code>```

list.test

```<code>import "reflect-metadata";
import {createConnection, getRepository} from "typeorm";
import {List} from "./../../src/entity/lists/List";

describe("List", () => {

    let connection
    beforeAll( async () => {
        connection = await createConnection();
        console.log(connection);
    });

    it("should insert a list into database", async () => {

        const listRepository = getRepository(List);

        const list = new List({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

    })

})
</code>```

Right now i get the following

Expected 0 arguments, but got 1.ts(2554)

Is there a way typeorm can automatically handles this?

答:
There are two ways to solve this, the first is to declare your own constructor in the List class and assign the values but it gets messy.

The preferred method is by using repository.create to create an instance of the entity from an object. https://github.com/typeorm/typeorm/blob/master/docs/repository-api.md

```<code>        const listRepository = connection.getRepository(List);

        const list = listRepository.create({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

        const newList = await listRepository.save(list);
</code>```

Body:
I have an entity "List" and i want to create a new list by passing in an object into the constructor.

List.ts

import {Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from "typeorm";

@Entity()
export class List {

    @PrimaryColumn()
    id: string;

    @Column({type: "varchar", nullable: true})
    dtype: string;

    @Column({type: "varchar", nullable: true})
    title: string;

    @Column({type: "varchar"})
    user_id: string;

    @Column({type: "varchar", nullable: true})
    brand_id: string;

    @CreateDateColumn({type: "timestamp", nullable: true})
    created_at: string;

    @UpdateDateColumn({type: "timestamp", nullable: true})
    updated_at: string;

    @DeleteDateColumn({type: "timestamp", nullable: true})
    deleted_at: string;

}

list.test

import "reflect-metadata";
import {createConnection, getRepository} from "typeorm";
import {List} from "./../../src/entity/lists/List";

describe("List", () => {

    let connection
    beforeAll( async () => {
        connection = await createConnection();
        console.log(connection);
    });

    it("should insert a list into database", async () => {

        const listRepository = getRepository(List);

        const list = new List({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

    })

})

Right now i get the following

Expected 0 arguments, but got 1.ts(2554)

Is there a way typeorm can automatically handles this?

Body:
There are two ways to solve this, the first is to declare your own constructor in the List class and assign the values but it gets messy.

The preferred method is by using repository.create to create an instance of the entity from an object. https://github.com/typeorm/typeorm/blob/master/docs/repository-api.md

        const listRepository = connection.getRepository(List);

        const list = listRepository.create({
            id: "7e60c4ef",
            dtype: "brandlist",
            title: "OnePlus",
            user_id: "3aecd1b0-c34d-4427-9abd-fdacef00eaa5",
            brand_id: "7e60c4ef-0e6f-46c9-948b-a97d555bf4e4",
        });

        const newList = await listRepository.save(list);


问:
org.xml.sax.SAXParseException: Premature end of file
I have this piece of code which gives to SAXParseError i.e., it is not getting the content, but the same thing when i use in my test pg it works correctly. Here i am providing my original code piece, can any1 figure out what is the problem

This is the part where I fetch a xml and append a node to it but it seems that i am not able to get the file itself

```<code>String atemp=readFileAsString("../webapps/abc/include/xml/data.xml")

        log.info("ok thats good")

        String[] splitString=res.split(",")

        log.info(atemp)

        try
        {
            def root = new XmlSlurper().parseText(atemp)
        }
        catch(Exception e)
        {
            log.debug("parse errror: "+e)
        }
        root.appendNode {
          row {
            name(splitString[1])
            host(splitString[2])
            desc(splitString[3])
            product(splitString[4])
            type(splitString[5])
            time(splitString[6])
            by(splitString[7])
          }
        }

        def outputBuilder = new StreamingMarkupBuilder()
        String temp = outputBuilder.bind{ mkp.yield root }

        File file = new File("../webapps/abc/include/xml/data.xml");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(temp);
        output.close();
        log.info(temp)
</code>```

my readFileAsString function

```<code>private String readFileAsString(String filePath) {
    try
    {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        log.info(reader==null);
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            log.info(readData)
        }
        reader.close();
        log.info("File Content\n"+fileData.toString());
        return fileData.toString();
    }
    catch (Exception e)
    {
        log.info(e);
    }
}
</code>```

Output

```<code>INFO http-5050-Processor24 com.abc.helper.WriteXml - false
INFO http-5050-Processor24 com.abc.helper.WriteXml - File Content
INFO http-5050-Processor24 com.abc.helper.WriteXml - ok thats good
</code>```

Note: I am able to open the file in my test program with the same path

答:
Assuming this is in Groovy, I believe you can replace all of your code with:

```<code>File f = new File( '../webapps/abc/include/xml/data.xml' )
def root = new XmlSlurper().parse( f )
String[] splitString = res.split( ',' )
root.appendNode {
  row {
    name(splitString[1])
    host(splitString[2])
    desc(splitString[3])
    product(splitString[4])
    type(splitString[5])
    time(splitString[6])
    by(splitString[7])
  }
}
def outputBuilder = new StreamingMarkupBuilder()
String newXml = outputBuilder.bind{ mkp.yield root }
f.text = newXml
</code>```

But I repeat, doing this inside a web application is probably a bad idea as if two threads call this code at the same time, the file is going to be unpredictable (and get more unpredictable as it gets larger)

Also, you might want to change:

```<code>File f = new File( '../webapps/abc/include/xml/data.xml' )
</code>```

to

```<code>File f = new File( "${System.properties['catalina.base']}/webapps/abc/include/xml/data.xml" )
</code>```

As suggested to you in a previous question of yours

ContentLicense: CC BY-SA 3.0

Body:
I have this piece of code which gives to SAXParseError i.e., it is not getting the content, but the same thing when i use in my test pg it works correctly. Here i am providing my original code piece, can any1 figure out what is the problem

This is the part where I fetch a xml and append a node to it but it seems that i am not able to get the file itself

String atemp=readFileAsString("../webapps/abc/include/xml/data.xml")

        log.info("ok thats good")

        String[] splitString=res.split(",")

        log.info(atemp)

        try
        {
            def root = new XmlSlurper().parseText(atemp)
        }
        catch(Exception e)
        {
            log.debug("parse errror: "+e)
        }
        root.appendNode {
          row {
            name(splitString[1])
            host(splitString[2])
            desc(splitString[3])
            product(splitString[4])
            type(splitString[5])
            time(splitString[6])
            by(splitString[7])
          }
        }

        def outputBuilder = new StreamingMarkupBuilder()
        String temp = outputBuilder.bind{ mkp.yield root }

        File file = new File("../webapps/abc/include/xml/data.xml");
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(temp);
        output.close();
        log.info(temp)

my readFileAsString function

private String readFileAsString(String filePath) {
    try
    {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        log.info(reader==null);
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            log.info(readData)
        }
        reader.close();
        log.info("File Content\n"+fileData.toString());
        return fileData.toString();
    }
    catch (Exception e)
    {
        log.info(e);
    }
}

Output

INFO http-5050-Processor24 com.abc.helper.WriteXml - false
INFO http-5050-Processor24 com.abc.helper.WriteXml - File Content
INFO http-5050-Processor24 com.abc.helper.WriteXml - ok thats good

Note: I am able to open the file in my test program with the same path

Body:
Assuming this is in Groovy, I believe you can replace all of your code with:

File f = new File( '../webapps/abc/include/xml/data.xml' )
def root = new XmlSlurper().parse( f )
String[] splitString = res.split( ',' )
root.appendNode {
  row {
    name(splitString[1])
    host(splitString[2])
    desc(splitString[3])
    product(splitString[4])
    type(splitString[5])
    time(splitString[6])
    by(splitString[7])
  }
}
def outputBuilder = new StreamingMarkupBuilder()
String newXml = outputBuilder.bind{ mkp.yield root }
f.text = newXml

But I repeat, doing this inside a web application is probably a bad idea as if two threads call this code at the same time, the file is going to be unpredictable (and get more unpredictable as it gets larger)

Also, you might want to change:

File f = new File( '../webapps/abc/include/xml/data.xml' )

to

File f = new File( "${System.properties['catalina.base']}/webapps/abc/include/xml/data.xml" )

As suggested to you in a previous question of yours


问:
autocomplete="off" force in browser
I have a login form and I NEED to force autocomplete to off.
i have tried

jquery: $('#login').attr("autocomplete", "off");

HTML: <input ... autocomplete="off">

Javascript: document.getElementById('myInputId').autocomplete = 'off';

When I click the login input box a drop down appears
across all browsers
FF, Chrome, IE..

N.B. this applies to users who have previously saved password information They need to forced to enter login details

答: Enclose "form-group" class in form tag  and add onSubmit handler with event.preventDefault() method called inside the handler. </p>

Title: autocomplete="off" force in browser


问:
Referencing index from a column and adding count
Following my project below, I would like to python to be able to show which date a trade is made. Currently I have done a backtest that shows if price is above average or below average. Is there a way where I can specify in the result on which date is the trade (buy and sell) is done? For example "Buying now at 5.86999 on 2019-5-20". Also is it possible to add count to the trades that I have done?

```<code>### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy
## Below is to import the relevant code and set pandas option
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'
pd.set_option('display.max_rows', None)

## Identifying which ticker, start date, end date, defining MACD calcs and appending them into dataframe
stock = "FRO" #Input stock ticker
Start_date = '2019-1-1' #Input Start date for analysis
End_date = dt.datetime.today()
Quick_EMA = 12
Slow_EMA = 26
Signal_EMA = 9
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
df['Signal_Line'] = df['MACDLine'].ewm(span = Signal_EMA, min_periods = Signal_EMA).mean()

##setting rules for backtest, main strategy - MACD Line crossover signal to buy/sell and risk tolerance on 1% bss Adj CLose
pos = 0
realized_pnl = []
buytrades = 0
selltrades = 0
percentchange = []
cut_loss_percent = 0.96
for i in df.index:
    closing_price = df['Close'][i]
    emin = df['MACDLine'][i]
    emax = df['Signal_Line'][i]
    openprice = df['Open'][i]
    if (emin>emax):
        print('MACD higher than Signal')
        if pos == 0:
            bp = closing_price
            pos = 1
            buytrades =+1
            cut_loss = cut_loss_percent*bp
            print('Buying now at ' + str(bp))
            print('Will cut loss at ' + str (cut_loss))

    elif (closing_price<cut_loss):
            if pos == 1:
               print('Cut Loss at ' + str(cut_loss))
               pos = 0
               selltrades =+1
               print(cut_loss - bp)
               pc = (cut_loss - bp)
               realized_pnl.append(pc)
               return_onper = pc/bp
               percentchange.append(return_onper)

    elif (emax>emin):
        print('MACD is lower than Signal')
        if pos == 1:
            cp = closing_price
            pos = 0
            selltrades =+1
            print('Selling now at ' + str(cp))
            print(cp-bp)
            pc = (cp - bp)
            realized_pnl.append(pc)
            return_onper = pc/bp
            percentchange.append(return_onper)

if pos == 1:
    print('Still has position in place')
    mtm = (closing_price - bp)
    mtmgainloss = mtm/bp
    percentchange.append(mtmgainloss)

total_realizedpnl = sum(realized_pnl)
print('Realized Pnl '+ str(total_realizedpnl))
All_pnl = total_realizedpnl + mtm
print('Sum of total Pnl ' + str(All_pnl))
sum(percentchange)
</code>```

Below is a snipet of the results

```<code>MACD higher than Signal
Buying now at 5.869999885559082
Will cut loss at 5.635199890136718
MACD higher than Signal
...
MACD higher than Signal
Still has position in place
Realized Pnl 4.460401210784912
Sum of total Pnl 5.5204016304016115
Out[21]:
0.6354297951321523
</code>```

答:
Managed to find a workaround this, it might be quite idiocracy but somehow i works :D</p>

```<code>### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy
## Below is to import the relevant code and set pandas option
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'
pd.set_option('display.max_rows', None)

## Identifying which ticker, start date, end date, defining MACD calcs and appending them into dataframe
stock = "FRO" #Input stock ticker
Start_date = '2019-1-1' #Input Start date for analysis
End_date = dt.datetime.today()
Quick_EMA = 12 #Amend as you like
Slow_EMA = 26 #Amend as you like
Signal_EMA = 9 #Amend as you like
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
df['Signal_Line'] = df['MACDLine'].ewm(span = Signal_EMA, min_periods = Signal_EMA).mean()
df['MACD_Sig_diff'] = df['MACDLine'] - df['Signal_Line']
df['MACD_Sig_diff_10MA'] = df['MACD_Sig_diff'].ewm(span = 10, min_periods = 10).mean()
df['Date'] = df.index

##setting rules for backtest, main strategy - MACD Line crossover signal to buy/sell and risk tolerance on 4% bss Adj CLose
pos = 0
realized_pnl = []
buytrades = []
selltrades = []
percentchange = []
cut_loss_percent = 0.96 #Stop loss level, if its 5% it will be 100% - 5% = 0.95
for i in df.index:
    closing_price = df['Close'][i]
    emin = df['MACDLine'][i]
    emax = df['Signal_Line'][i]
    openprice = df['Open'][i]
    tradedate = df['Date'][i]
    if (emin>emax):
        print('MACD higher than Signal')
        if pos == 0:
            bp = closing_price
            pos = 1
            buytrades.append(1)
            cut_loss = cut_loss_percent*bp
            print('Buying now at ' + str(bp) +' at ' + str(tradedate))
            print('Will cut loss at ' + str (cut_loss))

    elif (closing_price<cut_loss):
            if pos == 1:
               print('Cut Loss at ' + str(cut_loss)+' at ' + str(tradedate))
               pos = 0
               selltrades.append(1)
               print('Pnl is ' + str(cut_loss - bp))
               pc = (cut_loss - bp)
               realized_pnl.append(pc)
               return_onper = pc/bp
               percentchange.append(return_onper)

    elif (emax>emin):
        print('MACD is lower than Signal')
        if pos == 1:
            cp = closing_price
            pos = 0
            selltrades.append(1)
            print('Selling now at ' + str(cp)+' at ' + str(tradedate))
            print('Pnl is '+ str(cp-bp))
            pc = (cp - bp)
            realized_pnl.append(pc)
            return_onper = pc/bp
            percentchange.append(return_onper)

if pos == 1:
    print('Still has position in place')
    mtm = (closing_price - bp)
    mtmgainloss = mtm/bp
    percentchange.append(mtmgainloss)

print('Realized Pnl '+ str(sum(realized_pnl)))
All_pnl = realized_pnl + mtm
print('Sum of total Pnl ' + str(sum(All_pnl)))
print('Pnl in % ' +str(sum(percentchange*100)))
print('The number of buy trades are ' + str(sum(buytrades)))
print('The number of sell trades are '+ str(sum(selltrades)))

</code>```

Body:
Following my project below, I would like to python to be able to show which date a trade is made. Currently I have done a backtest that shows if price is above average or below average. Is there a way where I can specify in the result on which date is the trade (buy and sell) is done? For example "Buying now at 5.86999 on 2019-5-20". Also is it possible to add count to the trades that I have done?

### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy
## Below is to import the relevant code and set pandas option
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'
pd.set_option('display.max_rows', None)

## Identifying which ticker, start date, end date, defining MACD calcs and appending them into dataframe
stock = "FRO" #Input stock ticker
Start_date = '2019-1-1' #Input Start date for analysis
End_date = dt.datetime.today()
Quick_EMA = 12
Slow_EMA = 26
Signal_EMA = 9
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
df['Signal_Line'] = df['MACDLine'].ewm(span = Signal_EMA, min_periods = Signal_EMA).mean()

##setting rules for backtest, main strategy - MACD Line crossover signal to buy/sell and risk tolerance on 1% bss Adj CLose
pos = 0
realized_pnl = []
buytrades = 0
selltrades = 0
percentchange = []
cut_loss_percent = 0.96
for i in df.index:
    closing_price = df['Close'][i]
    emin = df['MACDLine'][i]
    emax = df['Signal_Line'][i]
    openprice = df['Open'][i]
    if (emin>emax):
        print('MACD higher than Signal')
        if pos == 0:
            bp = closing_price
            pos = 1
            buytrades =+1
            cut_loss = cut_loss_percent*bp
            print('Buying now at ' + str(bp))
            print('Will cut loss at ' + str (cut_loss))

    elif (closing_price<cut_loss):
            if pos == 1:
               print('Cut Loss at ' + str(cut_loss))
               pos = 0
               selltrades =+1
               print(cut_loss - bp)
               pc = (cut_loss - bp)
               realized_pnl.append(pc)
               return_onper = pc/bp
               percentchange.append(return_onper)

    elif (emax>emin):
        print('MACD is lower than Signal')
        if pos == 1:
            cp = closing_price
            pos = 0
            selltrades =+1
            print('Selling now at ' + str(cp))
            print(cp-bp)
            pc = (cp - bp)
            realized_pnl.append(pc)
            return_onper = pc/bp
            percentchange.append(return_onper)

if pos == 1:
    print('Still has position in place')
    mtm = (closing_price - bp)
    mtmgainloss = mtm/bp
    percentchange.append(mtmgainloss)

total_realizedpnl = sum(realized_pnl)
print('Realized Pnl '+ str(total_realizedpnl))
All_pnl = total_realizedpnl + mtm
print('Sum of total Pnl ' + str(All_pnl))
sum(percentchange)

Below is a snipet of the results

MACD higher than Signal
Buying now at 5.869999885559082
Will cut loss at 5.635199890136718
MACD higher than Signal
...
MACD higher than Signal
Still has position in place
Realized Pnl 4.460401210784912
Sum of total Pnl 5.5204016304016115
Out[21]:
0.6354297951321523

Body:
Managed to find a workaround this, it might be quite idiocracy but somehow i works :D

### Purpose of this code is to backtest MACD strategy using 12,26,9. This is a long only strategy
## Below is to import the relevant code and set pandas option
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'
pd.set_option('display.max_rows', None)

## Identifying which ticker, start date, end date, defining MACD calcs and appending them into dataframe
stock = "FRO" #Input stock ticker
Start_date = '2019-1-1' #Input Start date for analysis
End_date = dt.datetime.today()
Quick_EMA = 12 #Amend as you like
Slow_EMA = 26 #Amend as you like
Signal_EMA = 9 #Amend as you like
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
df['Signal_Line'] = df['MACDLine'].ewm(span = Signal_EMA, min_periods = Signal_EMA).mean()
df['MACD_Sig_diff'] = df['MACDLine'] - df['Signal_Line']
df['MACD_Sig_diff_10MA'] = df['MACD_Sig_diff'].ewm(span = 10, min_periods = 10).mean()
df['Date'] = df.index

##setting rules for backtest, main strategy - MACD Line crossover signal to buy/sell and risk tolerance on 4% bss Adj CLose
pos = 0
realized_pnl = []
buytrades = []
selltrades = []
percentchange = []
cut_loss_percent = 0.96 #Stop loss level, if its 5% it will be 100% - 5% = 0.95
for i in df.index:
    closing_price = df['Close'][i]
    emin = df['MACDLine'][i]
    emax = df['Signal_Line'][i]
    openprice = df['Open'][i]
    tradedate = df['Date'][i]
    if (emin>emax):
        print('MACD higher than Signal')
        if pos == 0:
            bp = closing_price
            pos = 1
            buytrades.append(1)
            cut_loss = cut_loss_percent*bp
            print('Buying now at ' + str(bp) +' at ' + str(tradedate))
            print('Will cut loss at ' + str (cut_loss))

    elif (closing_price<cut_loss):
            if pos == 1:
               print('Cut Loss at ' + str(cut_loss)+' at ' + str(tradedate))
               pos = 0
               selltrades.append(1)
               print('Pnl is ' + str(cut_loss - bp))
               pc = (cut_loss - bp)
               realized_pnl.append(pc)
               return_onper = pc/bp
               percentchange.append(return_onper)

    elif (emax>emin):
        print('MACD is lower than Signal')
        if pos == 1:
            cp = closing_price
            pos = 0
            selltrades.append(1)
            print('Selling now at ' + str(cp)+' at ' + str(tradedate))
            print('Pnl is '+ str(cp-bp))
            pc = (cp - bp)
            realized_pnl.append(pc)
            return_onper = pc/bp
            percentchange.append(return_onper)

if pos == 1:
    print('Still has position in place')
    mtm = (closing_price - bp)
    mtmgainloss = mtm/bp
    percentchange.append(mtmgainloss)

print('Realized Pnl '+ str(sum(realized_pnl)))
All_pnl = realized_pnl + mtm
print('Sum of total Pnl ' + str(sum(All_pnl)))
print('Pnl in % ' +str(sum(percentchange*100)))
print('The number of buy trades are ' + str(sum(buytrades)))
print('The number of sell trades are '+ str(sum(selltrades)))


问:
Merge this if statement with the enclosing one in sonar
Why Sonar showing below code having Major issue and its saying Marge this if statement with enclosing one

If i do that there will be functional issue will come .How can i solve this problem

code

```<code>    if (Optional.ofNullable(baseOffersRequest.getCreditClass()).isPresent()) {
            if (!baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("High")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Low")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Medium")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Unknown")) {
                errors.add(new Error("EPO_CATALOG_ERR_04", "Invalid Credit Class in the Request."));
            }
        }
</code>```

答:
What Sonar is suggesting here is to do something like this:

```<code>if (Optional.ofNullable(baseOffersRequest.getCreditClass()).isPresent()) && (!baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("High")
                && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Low")
                && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Medium")
                && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Unknown")) {
            errors.add(new Error("EPO_CATALOG_ERR_04", "Invalid Credit Class in the Request."));

}
</code>```

No functional issue here, as it does the same without an extra if statement.

Body:
Why Sonar showing below code having Major issue and its saying Marge this if statement with enclosing one

If i do that there will be functional issue will come .How can i solve this problem

code

    if (Optional.ofNullable(baseOffersRequest.getCreditClass()).isPresent()) {
            if (!baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("High")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Low")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Medium")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Unknown")) {
                errors.add(new Error("EPO_CATALOG_ERR_04", "Invalid Credit Class in the Request."));
            }
        }

Body:
What Sonar is suggesting here is to do something like this:

if (Optional.ofNullable(baseOffersRequest.getCreditClass()).isPresent()) && (!baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("High")
                && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Low")
                && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Medium")
                && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Unknown")) {
            errors.add(new Error("EPO_CATALOG_ERR_04", "Invalid Credit Class in the Request."));

}

No functional issue here, as it does the same without an extra if statement.


问:
Adding Text beneath each column 4X4 using CSS GRID
I am very new to CSS Grid and am trying to create a 2 X 2 grid. I am able to create the four image divs ( 2 on each row and 2 on each column) but I want the text to appear underneath each one. I have tried to use the grid-template-areas property but all the text just appears under one div all overlapped.

Any help would be appreciated, please.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-template-areas: "image image " "text text";
}

.text {
  grid-area: text;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">
        TEXT 2
      </p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner --></code>```

答:
Manage placement without template areas using nth-of-type and flow via columns.

.image {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-auto-flow: column;
}

p:nth-of-type(odd),
.image:nth-of-type(odd) {
  grid-column: 1;
}

p:nth-of-type(even),
.image:nth-of-type(even) {
  grid-column: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">
        TEXT 2
      </p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner --></code>```

Body:
I am very new to CSS Grid and am trying to create a 2 X 2 grid. I am able to create the four image divs ( 2 on each row and 2 on each column) but I want the text to appear underneath each one. I have tried to use the grid-template-areas property but all the text just appears under one div all overlapped.

Any help would be appreciated, please.

.image {
  width: 526px;
  height: 360px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-template-areas: "image image " "text text";
}

.text {
  grid-area: text;
}

TEXT 1

        TEXT 2

TEXT 3

TEXT 4

Body:
Manage placement without template areas using nth-of-type and flow via columns.

.image {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  border-radius: 10px;
  margin-top: 35px;
  margin-bottom: 35px;
}

.grid-container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 1fr 1fr;
  column-gap: 10px;
  row-gap: 1em;
  grid-auto-flow: column;
}

p:nth-of-type(odd),
.image:nth-of-type(odd) {
  grid-column: 1;
}

p:nth-of-type(even),
.image:nth-of-type(even) {
  grid-column: 2;
}

<div class="banner">
  <div class="wrapper">
    <div class="grid-container">
      <div class="image"></div>
      <p class="text">TEXT 1</p>
      <div class="image"></div>
      <p class="text">
        TEXT 2
      </p>
      <div class="image"></div>
      <p class="text">TEXT 3</p>
      <div class="image"></div>
      <p class="text">TEXT 4</p>
    </div>
  </div>
  <!-- wrapper -->

</div>
<!-- banner -->


答:
I tried Partitioning the Running Balance, but could not get it right.

I kept trying and finally got it right.

I changed my Running Balance Script to this and it worked:

```<code>select
*
,   round(case SubAccount when 'zzClosing Balance' then 0 else sum(Amount) over(partition by MasterAccount order by Sort rows unbounded preceding ) end,2) RunningBalance
from    @tbl
</code>```

Thanks for you help either way.

Title: Running Balance per Account Number

Body:
I require to have a running balance per Account Number.

I tried developing a function, but keep getting the wrong values.

See below Sample Data and how I currently calculate the Running Balance:

declare @tbl table (id int primary key identity, Sort varchar(100), MasterAccount varchar(50), SubAccount varchar(50), Amount float)
insert into @tbl (Sort,MasterAccount,SubAccount,Amount)
values
('1000_1','1000','aaOpening Balance',78137.58)
,('1000_2_13699','1000','1000',35516.34)
,('1000_2_14379','1000','1000',16675)
,('1000_2_15141','1000','1000',9252.21)
,('1000_2_15151','1000','1000',8167.3)
,('1000_2_15161','1000','1000',5729.3)
,('1000_2_15166','1000','1000',8898.7)
,('1000_2_15623','1000','1000',3335)
,('1000_2_15633','1000','1000',2620.85)
,('1000_2_15638','1000','1000',3425.39)
,('1000_2_17582','1000','1000',7281.55)
,('1000_2_18756','1000','1000',2126)
,('1000_2_19698','1000','1000',8000)
,('1000_2_19713','1000','1000',8000)
,('1000_2_19718','1000','1000',8000)
,('1000_2_19847','1000','1000',8000)
,('1000_2_20055','1000','1000',3933.1)
,('1000_2_20060','1000','1000',5304.37)
,('1000_2_20099','1000','1000',0.00000000123)
,('1000_2_20104','1000','1000',-0.00000000123)
,('1000_2_20330','1000','1000',8000)
,('1000_2_20340','1000','1000',8000)
,('1000_2_20360','1000','1000',8000)
,('1000_2_20390','1000','1000',8000)
,('1000_2_20416','1000','1000',8000)
,('1000_2_20576','1000','1000',8000)
,('1000_2_21033','1000','1000',8000)
,('1000_3','1000','zzClosing Balance',278402.69)
,('2000_1','2000','aaOpening Balance',128023.65)
,('2000_2_14381','2000','2000',15174.5)
,('2000_2_15143','2000','2000',10534.92)
,('2000_2_15153','2000','2000',9299.6)
,('2000_2_15163','2000','2000',6523.6)
,('2000_2_15168','2000','2000',10132.4)
,('2000_2_15625','2000','2000',3084.28)
,('2000_2_15635','2000','2000',2652.48)
,('2000_2_15640','2000','2000',3466.73)
,('2000_2_17584','2000','2000',8489.38)
,('2000_2_18758','2000','2000',2132.41)
,('2000_2_20057','2000','2000',3944.96)
,('2000_2_20062','2000','2000',5320.37)
,('2000_3','2000','zzClosing Balance',208779.28)

select
*
,   round(case SubAccount when 'zzClosing Balance' then 0 else sum(Amount) over(order by [Sort] rows unbounded preceding) end,2) RunningBalance
from    @tbl

The results look as following:

The problem I am facing is the balance for the second Account Number (in this case Acc Number "2000") is calculated wrong.

I require the Running Balance to Start with the value 128,023.65 and end with 208,779.28.

To give you a better idea, my expected results would look like this:

How would I get the Expected results?

Your assistance is greatly appreciated!

Body:
I tried Partitioning the Running Balance, but could not get it right.

I kept trying and finally got it right.

I changed my Running Balance Script to this and it worked:

select
*
,   round(case SubAccount when 'zzClosing Balance' then 0 else sum(Amount) over(partition by MasterAccount order by Sort rows unbounded preceding ) end,2) RunningBalance
from    @tbl

Thanks for you help either way.


问:
AS3 performance difference between function and events
I working on a game project in Flash AS3.

I need to pass data from one class (Game) to other class objects (Ships) on EnterFrame and performance is starting to be a issue.
I was wondering is there a difference in performance between calling to the Ship a direct function or dispatching an event which the Ship can listen.

another question is where should I put the enterframe function. Is it better to use only one enterframe function and call the methods \ dispatch events from there, or it will be wiser to put the enterframe in the different objects (Ships)? note: some Ships are inactive most of the time.

Hope I managed to explain myself.

Thanks,

Vivo

答:
It's definitely cheaper to call functions directly rather than having to go through the event dispatch / listen chain.

It's tricky how many EnterFrames you should have, generally speaking it's better to have as few as possible, but if you have to dispatch tons of events you're better off having a few more – that being said if you can do it with direct method calls from one central EnterFrame loop that's the best.

Also if your Ships are inactive most of the time then you shouldn't have an EnterFrame running on each.


问:
Is it possible to run the gcloud command using work load identity?
We are in a situation where only our k8s pods have been given the permission to access Datastore. No other user account or service account has the necessary permissions to modify datastore.

I am required to create indexes on datastore. Since I do not have the necessary permissions to do so, I was wondering if there is a mechanism to run gcloud datastore indexes create indexes.yaml from the authorized pods.

答:
There is no difference between a simple Compute engine + gcloud and a Workload identity + gcloud

You can see this description here

Workload Identity intercepts calls to the Compute Engine metadata server to exchange workload identity pool credentials for credentials from the associated GSAs

Thereby, the default authentication mechanism of Gcloud, based on metadata server, is exactly the same.


问:
React passed data from child to parent not logging in parent
I tried to pass data from a child component to it's parent but it isn't showing in the parent component.
In parent component I want to display the duration of a service that is selected in the child component.
In the child component I can log the selected service but it isn't passing to its parent:

Parent component:

```<code>class CalenderModal extends React.Component {
  state={selectedService:[]}

// handover of child data to parent
  handleServiceSelect = (selectedServiceObj) => {
    this.setState({selectedService: selectedServiceObj});
    console.log('inside CalendarModal:', this.state.selectedService)
}

  handleRemove = () => {
    this.props.onRemove();
  }

  handleSave = () => {
    const fullname = this.fullname.value;
    const phone = this.phone.value;
    this.props.onSave({
      fullname,
      phone,
    });
  }

  render() {

    return (
      <div className="customModal">
        <div>Choose service you want to schedule:</div>
        /// child component
        <ServiceSearch onServiceSelect={()=> this.handleServiceSelect}/>
        <div>{this.state.selectedService.duration} hours</div>

        <button className="customModal__button customModal__button_example" onClick={this.handleSave}>{action}</button>
      </div>
    );
  }
}

export default CalenderModal;

</code>```

Child component:

```<code>class ServiceList extends Component {
    constructor(props) {
        super(props);
      }
    servicesToRender=[]

    handleServiceSelect = (event) => {
        var selectedServiceId =  event.target.value;
        var selectedService = this.servicesToRender.find(({id})=> id === selectedServiceId )
                console.log("inside Service search:",selectedService)
        this.props.onServiceSelect(selectedService);
    }
    render() {
        const FEED_QUERY = gql`
     {
         servicefeed {
          id
          name
          cost
          duration

     }
    }
   `
        return (
            <Query query={FEED_QUERY} >
                {({ loading, error, data }) => {
                    if (loading) return <div>Fetching</div>
                    if (error) return <div>Error</div>
                     this.servicesToRender= data.servicefeed
                    //  const servicesToRender = data.servicefeed
                    return (
                        <React.Fragment>
                            <label class="my-1 mr-2" for="inlineFormCustomSelectPref">choose service:</label>
                            <select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref"  onChange={this.handleServiceSelect}>
                                {this.servicesToRender.map(service => <ServiceSearchOption key={service.id} service={service}  />)}
                            </select>
                        </React.Fragment>
                    )
                }}
            </Query>
        )
    }
}

export default ServiceList
</code>```

I'm not sure what I'm missing here.

答:
You haven't called the function in parent when passing it as props and using arrow function inline. The correct ways is below

```<code><ServiceSearch onServiceSelect={()=> this.handleServiceSelect()}/>
</code>```

However, you could have simply passed the function reference without an arrow function since the handleServiceSelect is already and arrow function and will have function binding

```<code><ServiceSearch onServiceSelect={this.handleServiceSelect}/>
</code>```

Body:
I tried to pass data from a child component to it's parent but it isn't showing in the parent component.
In parent component I want to display the duration of a service that is selected in the child component.
In the child component I can log the selected service but it isn't passing to its parent:

Parent component:

class CalenderModal extends React.Component {
  state={selectedService:[]}

// handover of child data to parent
  handleServiceSelect = (selectedServiceObj) => {
    this.setState({selectedService: selectedServiceObj});
    console.log('inside CalendarModal:', this.state.selectedService)
}

  handleRemove = () => {
    this.props.onRemove();
  }

  handleSave = () => {
    const fullname = this.fullname.value;
    const phone = this.phone.value;
    this.props.onSave({
      fullname,
      phone,
    });
  }

  render() {

    return (

Choose service you want to schedule:

        /// child component
        <ServiceSearch onServiceSelect={()=> this.handleServiceSelect}/>

{this.state.selectedService.duration} hours

        <button className="customModal__button customModal__button_example" onClick={this.handleSave}>{action}</button>

    );
  }
}

export default CalenderModal;

Child component:

class ServiceList extends Component {
    constructor(props) {
        super(props);
      }
    servicesToRender=[]

    handleServiceSelect = (event) => {
        var selectedServiceId =  event.target.value;
        var selectedService = this.servicesToRender.find(({id})=> id === selectedServiceId )
                console.log("inside Service search:",selectedService)
        this.props.onServiceSelect(selectedService);
    }
    render() {
        const FEED_QUERY = gql`
     {
         servicefeed {
          id
          name
          cost
          duration

     }
    }
   `
        return (
            <Query query={FEED_QUERY} >
                {({ loading, error, data }) => {
                    if (loading) return
Fetching

                    if (error) return
Error

                     this.servicesToRender= data.servicefeed
                    //  const servicesToRender = data.servicefeed
                    return (
                        <React.Fragment>
                            choose service:
                            <select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref"  onChange={this.handleServiceSelect}>
                                {this.servicesToRender.map(service => <ServiceSearchOption key={service.id} service={service}  />)}
                            </select>
                        </React.Fragment>
                    )
                }}
            </Query>
        )
    }
}

export default ServiceList

I'm not sure what I'm missing here.

Body:
You haven't called the function in parent when passing it as props and using arrow function inline. The correct ways is below

<ServiceSearch onServiceSelect={()=> this.handleServiceSelect()}/>

However, you could have simply passed the function reference without an arrow function since the handleServiceSelect is already and arrow function and will have function binding

<ServiceSearch onServiceSelect={this.handleServiceSelect}/>


问:
How to log all files inside a folder
I want to navigate into a specific folder and then print all the files inside that specified folder using Google Apps Script:

function listFilesinSpecFolder(){
    var files = DriveApp.getFolderById("specific folder id placed here");
    while (files.hasNext()) {
      var file = files.next();
      Logger.log(file.getName());
    }
}
```
<p>When I tried to log this it gives me an error saying that hasNext() function is not a function.
But when I run the below code it gives me no errors...</p>
<pre class="lang-js prettyprint-override"><code>function folder(){
    var folders = DriveApp.getFolders();
    while (folders.hasNext()) {
      var folder = folders.next();
      Logger.log(folder.getName());
    }
}
</code>```

答:
The following script will help you 'to navigate into a specific folder and then print all the files inside that specified folder'

CODE:

```<code>function listFilesinSpecFolder() {

  var folder = DriveApp.getFolderById('FOLDER ID GOES HERE');
  var file;
  var contents = folder.getFiles();
  while(contents.hasNext()) {
    file = contents.next();
    Logger.log(file.getName());
  }
}
</code>```

Title: How to log all files inside a folder

Body:
I want to navigate into a specific folder and then print all the files inside that specified folder using Google Apps Script:

function listFilesinSpecFolder(){
    var files = DriveApp.getFolderById("specific folder id placed here");
    while (files.hasNext()) {
      var file = files.next();
      Logger.log(file.getName());
    }
}

When I tried to log this it gives me an error saying that hasNext() function is not a function.
But when I run the below code it gives me no errors...

function folder(){
    var folders = DriveApp.getFolders();
    while (folders.hasNext()) {
      var folder = folders.next();
      Logger.log(folder.getName());
    }
}

Body:
The following script will help you 'to navigate into a specific folder and then print all the files inside that specified folder'

CODE:

function listFilesinSpecFolder() {

  var folder = DriveApp.getFolderById('FOLDER ID GOES HERE');
  var file;
  var contents = folder.getFiles();
  while(contents.hasNext()) {
    file = contents.next();
    Logger.log(file.getName());
  }
}


问:
Problem integrating a toolbar into an recyclerview
I have a problem and I need your help. I have created a RecyclerView and it was okay. Now I want to have a toolbar at the top with a black background and red text. The RecyclerView, which is basically a list of items, should start under the toolbar. I inserted a toolbar but unfortunately it is not displayed at all, altough in the blueprint of Android Studio it can be seen. However, on the normal layout screen you can't see it and also on the editor you can't see it. Here I have some screenshots:

Here is the XML layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyDrinks">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="432dp"
        android:layout_height="135dp"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp"
            android:text="Test Toolbar" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="4dp"
        android:scrollbars="vertical"
        android:background="@android:color/white"
        ></androidx.recyclerview.widget.RecyclerView>

</RelativeLayout>
</code>```

Does anyone know what the problem might be? So basically the toolbar is not displayed at all and secondly the recyclerview list starts at the very top which I do not want. I'd appreciate every feedback.

答:
you can use LinearLayout or RelativeLayout

LinearLayout means you can align views one by one (vertically or horizontally).

RelativeLayout means based on relation of views from its parents and other views.

LinearLayout :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:gravity="center"
            android:text="Test Toolbar"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:padding="4dp"
        android:scrollbars="vertical" />
</LinearLayout>
</code>```

or RelativeLayout:

```<code>  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:gravity="center"
            android:text="Test Toolbar"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar_mainActivity"
        android:background="@android:color/white"
        android:padding="4dp"
        android:scrollbars="vertical" />
</RelativeLayout>
</code>```

ConstraintLayout :

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/black"
        android:clipToPadding="true"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark"
        tools:ignore="MissingConstraints">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:gravity="center"
            android:text="Test Toolbar"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp" />
    </androidx.appcompat.widget.Toolbar>

    <ImageButton
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar_mainActivity"
        android:padding="4dp"
        android:scrollbars="vertical"
        app:layout_constraintTop_toBottomOf="@id/toolbar_mainActivity" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Could I help you?

Body:
I have a problem and I need your help. I have created a RecyclerView and it was okay. Now I want to have a toolbar at the top with a black background and red text. The RecyclerView, which is basically a list of items, should start under the toolbar. I inserted a toolbar but unfortunately it is not displayed at all, altough in the blueprint of Android Studio it can be seen. However, on the normal layout screen you can't see it and also on the editor you can't see it. Here I have some screenshots:

Here is the XML layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyDrinks">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="432dp"
        android:layout_height="135dp"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp"
            android:text="Test Toolbar" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="4dp"
        android:scrollbars="vertical"
        android:background="@android:color/white"
        ></androidx.recyclerview.widget.RecyclerView>

</RelativeLayout>

Does anyone know what the problem might be? So basically the toolbar is not displayed at all and secondly the recyclerview list starts at the very top which I do not want. I'd appreciate every feedback.

Body:
you can use LinearLayout or RelativeLayout

LinearLayout means you can align views one by one (vertically or horizontally).

RelativeLayout means based on relation of views from its parents and other views.

LinearLayout :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:gravity="center"
            android:text="Test Toolbar"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:padding="4dp"
        android:scrollbars="vertical" />
</LinearLayout>

or RelativeLayout:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/black"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:gravity="center"
            android:text="Test Toolbar"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp" />
    </androidx.appcompat.widget.Toolbar>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toolbar_mainActivity"
        android:background="@android:color/white"
        android:padding="4dp"
        android:scrollbars="vertical" />
</RelativeLayout>

ConstraintLayout :

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/black"
        android:clipToPadding="true"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextColor="@android:color/holo_red_dark"
        tools:ignore="MissingConstraints">

        <TextView
            android:id="@+id/textView_ToolBar_ActivityTest"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:gravity="center"
            android:text="Test Toolbar"
            android:textColor="@android:color/holo_red_dark"
            android:textSize="24sp" />
    </androidx.appcompat.widget.Toolbar>

    <ImageButton
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar_mainActivity"
        android:padding="4dp"
        android:scrollbars="vertical"
        app:layout_constraintTop_toBottomOf="@id/toolbar_mainActivity" />
</androidx.constraintlayout.widget.ConstraintLayout>

Could I help you?


答:
If you write an else case for the if inside the isPresent() loop, it wouldn't throw such an error. As there is only one case inside that isPresent() loop, it is suggesting you to add that single condition check in one if loop.

I think it is suggesting you to write in this way according to the code you have written:

```<code> if (Optional.ofNullable(baseOffersRequest.getCreditClass()).isPresent()
            && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("High")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Low")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Medium")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Unknown")) {
                errors.add(new Error("EPO_CATALOG_ERR_04", "Invalid Credit Class in the Request."));
            }
</code>```

Title: Merge this if statement with the enclosing one in sonar

Body:
If you write an else case for the if inside the isPresent() loop, it wouldn't throw such an error. As there is only one case inside that isPresent() loop, it is suggesting you to add that single condition check in one if loop.

I think it is suggesting you to write in this way according to the code you have written:

 if (Optional.ofNullable(baseOffersRequest.getCreditClass()).isPresent()
            && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("High")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Low")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Medium")
                    && !baseOffersRequest.getCreditClass().trim().equalsIgnoreCase("Unknown")) {
                errors.add(new Error("EPO_CATALOG_ERR_04", "Invalid Credit Class in the Request."));
            }


答:
Introduce a variable and check it inside one if statement :

```<code>String creditClass = baseOffersRequest.getCreditClass();
if (Optional.ofNullable(creditClass ).isPresent()) &&
        !creditClass.trim().equalsIgnoreCase("High")
        ...
</code>```

Or even remove null check

```<code>String optionalCreditClass = baseOffersRequest.getCreditClass();
String creditClass =optionalCreditClass == null ? "" : optionalCreditClass.trim();
if (!"High".equalsIgnoreCase(creditClass) &&
...
</code>```

Body:
Introduce a variable and check it inside one if statement :

String creditClass = baseOffersRequest.getCreditClass();
if (Optional.ofNullable(creditClass ).isPresent()) &&
        !creditClass.trim().equalsIgnoreCase("High")
        ...

Or even remove null check

String optionalCreditClass = baseOffersRequest.getCreditClass();
String creditClass =optionalCreditClass == null ? "" : optionalCreditClass.trim();
if (!"High".equalsIgnoreCase(creditClass) &&
...


问:
Creating code first postgres database is failing: No password has been provided but the backend requires one (in MD5)
I'm building a .NET API and am stuck trying to create a postgres database using EFCore and Npgsql.

Targeted frameworks:

.Net Core 3.1

EFCore 3.1.4

Npgsql 3.1.3

I have created the initial migration but then running dotnet ef database update gives me this error:

```<code>Npgsql.NpgsqlException (0x80004005): No password has been provided but the backend requires one (in MD5)
   at Npgsql.NpgsqlConnector.AuthenticateMD5(String username, Byte[] salt, Boolean async)
   at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnection.Open()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
</code>```

I've found a number of other people with the same error but none of the suggested solutions have worked for me, the most common one saying that I need to add Persist Security Info=true; to my connection string as it's a security feature new to .NET Core 3.1.

My current connection string is:

```<code>"ConnectionStrings": {
    "(default)": "Server=localhost; Port=5432; Database=xxxxx; Persist Security Info=true; Pooling=true; CommandTimeout=60;"
  },
</code>```

I've also tried adding Password=xxxxx; to the connection string as well since that has been suggested.

Can anyone help?

答:
```<code>        private static string Host = "mydemoserver.postgres.database.azure.com";
        private static string User = "mylogin@mydemoserver";
        private static string DBname = "mypgsqldb";
        private static string Password = "<server_admin_password>";
        private static string Port = "5432";

        static void Main(string[] args)
        {
            // Build connection string using parameters from portal
            //
            string connString =
                String.Format(
                    "Server={0};Username={1};Database={2};Port={3};Password={4};SSLMode=Prefer",
                    Host,
                    User,
                    DBname,
                    Port,
                    Password);
       }
</code>```

Body:
I'm building a .NET API and am stuck trying to create a postgres database using EFCore and Npgsql.

Targeted frameworks:

.Net Core 3.1

EFCore 3.1.4

Npgsql 3.1.3

I have created the initial migration but then running dotnet ef database update gives me this error:

Npgsql.NpgsqlException (0x80004005): No password has been provided but the backend requires one (in MD5)
   at Npgsql.NpgsqlConnector.AuthenticateMD5(String username, Byte[] salt, Boolean async)
   at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnection.Open()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

I've found a number of other people with the same error but none of the suggested solutions have worked for me, the most common one saying that I need to add Persist Security Info=true; to my connection string as it's a security feature new to .NET Core 3.1.

My current connection string is:

"ConnectionStrings": {
    "(default)": "Server=localhost; Port=5432; Database=xxxxx; Persist Security Info=true; Pooling=true; CommandTimeout=60;"
  },

I've also tried adding Password=xxxxx; to the connection string as well since that has been suggested.

Can anyone help?


问:
Bulma collapsible not working when using CDN
I have included the CSS and JS CDN. I have also tried to use the whole extension CDN and it still wont work. Here is the codepen.

https://codepen.io/firdausai/pen/rNxBLKr?editors=1000

```<code><head>

    <!-- Load bulma CDN -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.2/css/bulma.min.css">

<!-- Load bulma accordion CDN -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma-accordion@2.0.1/dist/css/bulma-accordion.min.css">

    <!-- Load fontawesome CDN -->
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
</head>
<body>
    <div class="card">
    <header class="card-header">
        <p class="card-header-title">
            Card title
        </p>
        <a href="#collapsible-card" data-action="collapse" class="card-header-icon is-hidden-fullscreen" aria-label="more options">
            <span class="icon">
                <i class="fas fa-angle-down" aria-hidden="true"></i>
            </span>
        </a>
    </header>
    <div id="collapsible-card" class="is-collapsible is-active">
        <div class="card-content">
            <p class="title is-4">
                “There are two hard things in computer science: cache invalidation, naming things, and off-by-one
                errors.”
            </p>
            <p class="subtitle is-5">
                Jeff Atwood
            </p>
        </div>
        <footer class="card-footer">
            <p class="card-footer-item">
                <span>
                    View on <a href="https://twitter.com/codinghorror/status/506010907021828096">Twitter</a>
                </span>
            </p>
            <p class="card-footer-item">
                <span>
                    Share on <a href="#">Facebook</a>
                </span>
            </p>
        </footer>
    </div>
</div>
    <script src = "https://cdn.jsdelivr.net/npm/bulma-accordion@2.0.1/dist/js/bulma-accordion.min.js"></script>
</body>
</code>```

any suggestion?

答:
Read the documentation, you have to add this line :

```<code>var accordions = bulmaAccordion.attach(); // accordions now contains an array of all Accordion instances
</code>```

But bulma-accordion has some bugs, and as mentioned in the docs there is a new version with a lot of new functionalities here, I'm using it and I find it better than bulma-accordion.

Body:
I have included the CSS and JS CDN. I have also tried to use the whole extension CDN and it still wont work. Here is the codepen.

https://codepen.io/firdausai/pen/rNxBLKr?editors=1000

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.2/css/bulma.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma-accordion@2.0.1/dist/css/bulma-accordion.min.css">

            Card title

                “There are two hard things in computer science: cache invalidation, naming things, and off-by-one
                errors.”

                Jeff Atwood

                    View on Twitter

                    Share on Facebook

any suggestion?

Body:
Read the documentation, you have to add this line :

var accordions = bulmaAccordion.attach(); // accordions now contains an array of all Accordion instances

But bulma-accordion has some bugs, and as mentioned in the docs there is a new version with a lot of new functionalities here, I'm using it and I find it better than bulma-accordion.


问:
How can i set default answer in Q&A Azure bot
I want change Default Answer in Q&A Maker Azure Framework Bot, but I cant find field that respond this value. I'm reading documentation (but it looks like it uses an older interface), and I'm trying to find this field but with result.

Here's my current configuration screen:

答:
Change the line in qamakerBaseDialog.js as below

var noAnswer = ActivityFactory.DefaultNoAnswer;

Remove ActivityFactory. and rebuild the code.

constructor(knowledgebaseId, authkey, host) {
        //ActivityFactory.
        var noAnswer = DefaultNoAnswer;
        var filters = [];
        super(knowledgebaseId, authkey, host, noAnswer, DefaultThreshold, DefaultCardTitle, DefaultCardNoMatchText,
            DefaultTopN, ActivityFactory.cardNoMatchResponse, filters, QNAMAKER_BASE_DIALOG);
        this.id = QNAMAKER_BASE_DIALOG;
    }```


问:
varA = varA + varB doesn't work in typescript
I'm making a running total calculator method for my angular project in ts,

```<code>Total(){
let t: any;
for (let n = 0; n < this.checkoutItems.length; n++) {
  let key = this.checkoutItems[n].item_id ;
  this.itemsService.getCheckoutItem(key, 2).subscribe((response: any) => {
  this.checkoutItem = response;
  let y = localStorage.getItem(key);
  console.log("y:");
  console.log(y);
  let x=+y;
  console.log("x:");
  console.log(x);
  let a= +this.checkoutItems[n].price;
  console.log("a:");
  console.log(a);
  let b = a*x;
  console.log("b:");
  console.log(b);
   t +=b;
  console.log("t:");
  console.log(t);
  })
}
}
</code>```

Everything works fine upto the console log of b, they print the desired output on my console but for some reason the console log of t returns NaN ? why does that happen? I'm sorry I'm new to typescript.

答:
write like this . You can't add anything to any if you haven't initialize it. So check firstly if undefined or not then use it</p>

```<code>t ? t+=b : t=b;
</code>```

Body:
I'm making a running total calculator method for my angular project in ts,

Total(){
let t: any;
for (let n = 0; n < this.checkoutItems.length; n++) {
  let key = this.checkoutItems[n].item_id ;
  this.itemsService.getCheckoutItem(key, 2).subscribe((response: any) => {
  this.checkoutItem = response;
  let y = localStorage.getItem(key);
  console.log("y:");
  console.log(y);
  let x=+y;
  console.log("x:");
  console.log(x);
  let a= +this.checkoutItems[n].price;
  console.log("a:");
  console.log(a);
  let b = a*x;
  console.log("b:");
  console.log(b);
   t +=b;
  console.log("t:");
  console.log(t);
  })
}
}

Everything works fine upto the console log of b, they print the desired output on my console but for some reason the console log of t returns NaN ? why does that happen? I'm sorry I'm new to typescript.

Body:
write like this . You can't add anything to any if you haven't initialize it. So check firstly if undefined or not then use it

t ? t+=b : t=b;


问:
How to display comments coming from Redux store on individual component
I have created a basic single page app, on initial page there is some dummy data and on click of each item I direct user to individual details page of that item. I wanted to implement comment and delete comment functionality which I successfully did but now when I comment or delete the comment it doesn't only happen at that individual page but in every other page too. Please see the sandbox example for better clarify.

https://codesandbox.io/s/objective-feistel-g62g0?file=/src/components/ProductDetails.js

So once you add some comments in individual page, go back and then click to another products, apparently you will see that the comments you've done in other pages are also available there. What do you think causing this problem ?

答:
I found my own logical solution. You probably might find a better solution but this works pretty well too. I thought of passing another property in the object with the params I get from url and then filter the comments by their url params. So that I could do filtering based on the url parameters and display the comments only made on that specific page.

So ProductDetails.js page should be looking like this:

```<code>import React, { useState, useEffect } from 'react';
import { Input, Button } from 'semantic-ui-react'
import { connect } from 'react-redux';

const ProductDetails = (props) => {

    const [commentObject, setCommentObject] = useState({
        text: "",
        date: "",
        id: ""
    });

    const clickHandler = () => {
        if (!commentObject.text.trim()) {
            return
        }
        props.addNewComment(commentObject)
        setCommentObject({
            ...commentObject,
            text: ""
        })
        console.log(commentObject.id);
    }
    useEffect(() => {

    }, []);

    return (
        <div>
            {props.posts ? props.posts.text : null}

            {props.comments.filter(comment => {
                return comment.postId === props.match.params.slug
            }).map(({ text, id }) => {

                return (<div key={id}>
                    <p>{text}</p>
                    <Button onClick={() => props.deleteComment(id)} >Delete comment</Button></div>)
            })}
            <Input value={commentObject.text}
                onChange={comment => setCommentObject({ text: comment.target.value, date: new Date(), id: Date.now(), postId: props.match.params.slug })}
            />
            <Button onClick={clickHandler} >Add comment</Button>

        </div>
    );
}
const mapStateToProps = (state, ownProps) => {

    let slug = ownProps.match.params.slug;

    return {
        ...state,
        posts: state.posts.find(post => post.slug === slug),

    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        addNewComment: (object) => { dispatch({ type: "ADD_COMMENT", payload: { comment: { text: object.text, date: object.date, id: object.id, postId: object.postId } } }) },
        deleteComment: (id) => { dispatch({ type: "DELETE_COMMENT", id: id }) }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductDetails);

</code>```

Body:
I found my own logical solution. You probably might find a better solution but this works pretty well too. I thought of passing another property in the object with the params I get from url and then filter the comments by their url params. So that I could do filtering based on the url parameters and display the comments only made on that specific page.

So ProductDetails.js page should be looking like this:

import React, { useState, useEffect } from 'react';
import { Input, Button } from 'semantic-ui-react'
import { connect } from 'react-redux';

const ProductDetails = (props) => {

    const [commentObject, setCommentObject] = useState({
        text: "",
        date: "",
        id: ""
    });

    const clickHandler = () => {
        if (!commentObject.text.trim()) {
            return
        }
        props.addNewComment(commentObject)
        setCommentObject({
            ...commentObject,
            text: ""
        })
        console.log(commentObject.id);
    }
    useEffect(() => {

    }, []);

    return (
        <div>
            {props.posts ? props.posts.text : null}

            {props.comments.filter(comment => {
                return comment.postId === props.match.params.slug
            }).map(({ text, id }) => {

                return (<div key={id}>
                    <p>{text}</p>
                    <Button onClick={() => props.deleteComment(id)} >Delete comment</Button></div>)
            })}
            <Input value={commentObject.text}
                onChange={comment => setCommentObject({ text: comment.target.value, date: new Date(), id: Date.now(), postId: props.match.params.slug })}
            />
            <Button onClick={clickHandler} >Add comment</Button>

        </div>
    );
}
const mapStateToProps = (state, ownProps) => {

    let slug = ownProps.match.params.slug;

    return {
        ...state,
        posts: state.posts.find(post => post.slug === slug),

    }
}
const mapDispatchToProps = (dispatch) => {
    return {
        addNewComment: (object) => { dispatch({ type: "ADD_COMMENT", payload: { comment: { text: object.text, date: object.date, id: object.id, postId: object.postId } } }) },
        deleteComment: (id) => { dispatch({ type: "DELETE_COMMENT", id: id }) }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductDetails);


答:
Use a cross join to generate the rows.  Then a left join combine the two tables.  And finally use last_value() to bring in missing values:

```<code>select d.date, i.id,
       last_value(amount, TRUE) over (partition by id order by d.date) as amount
from date d cross join
     (select distinct id from data) i left join
     data t
     on d.date = t.date and i.id = t.id;
</code>```

The last_value() with the second argument ignores NULL values, so it will "go back" to get the most recent non-NULL value.

Title: Repeat previous values by date in hive

Body:
I have 2 tables - Dates and Data with data as follows:
Table: Dates

Date
1/02/2020
2/02/2020
3/02/2020
4/02/2020
5/02/2020
6/02/2020
7/02/2020
8/02/2020
9/02/2020
10/02/2020

Table: Data

Date    Id  Amount
1/02/2020   1   10
3/02/2020   1   30
10/02/2020  1   50
2/02/2020   2   5
6/02/2020   2   10
9/02/2020   2   20

Expected results:

Date    Id  Amount
1/02/2020   1   10
2/02/2020   1   10
3/02/2020   1   30
4/02/2020   1   30
5/02/2020   1   30
6/02/2020   1   30
7/02/2020   1   30
8/02/2020   1   30
9/02/2020   1   30
10/02/2020  1   50
2/02/2020   2   5
3/02/2020   2   5
4/02/2020   2   5
5/02/2020   2   5
6/02/2020   2   10
7/02/2020   2   10
8/02/2020   2   10
9/02/2020   2   20

I have tried using PARTITION OVER but getting duplicate vales and not all dates from Dates table, therefore not getting desired results. Really appreciate if you can help with the code in Hive SQL.

Body:
Use a cross join to generate the rows.  Then a left join combine the two tables.  And finally use last_value() to bring in missing values:

select d.date, i.id,
       last_value(amount, TRUE) over (partition by id order by d.date) as amount
from date d cross join
     (select distinct id from data) i left join
     data t
     on d.date = t.date and i.id = t.id;

The last_value() with the second argument ignores NULL values, so it will "go back" to get the most recent non-NULL value.


问:
What is the easiest way I can create a 'beep' sound from a Ruby program?
I'm making a small ruby command line script and I wanted to know what the simplest way to have the program emit a beep is.</p>

答:
Try printing the audible bell character:</p>

```<code>print "\a"
</code>```

OwnerDisplayName: Daniel X Moore

ContentLicense: CC BY-SA 2.5

Body:
Try printing the audible bell character:

print "\a"

OwnerDisplayName: Jeremy Ruten


问:
x.ToString() is not supported by the entity framework!
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

```<code>public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}
</code>```

Here is my Route entity:

```<code> public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }
</code>```

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?

答: You need to specify which property of Route class you need to compare with searchPattern or prefix. You cannot implicitly do a .ToString() in your scenario.

Body:
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}

Here is my Route entity:

 public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?