问:
How to create a new string list from a list of strings excluding one variable?
I have a list of strings and I'm trying to iterate through it and create each iteration a new list without one of the strings.
I tried the following:

```<code>tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)
</code>```

But each iteration the new list is empty.

答:
The statement:

```<code>tx_list_copy = tx_list
</code>```

does not copy the list but it refers to the same memory object: tx_list and tx_list_copy are different references to the same memory object list. This means that if you edit the first one, the second one will be edited too.

Instead, in order to copy the original list, you should use the .copy() method:

```<code>for txid in tx_list:
    tx_list_copy = tx_list.copy()     # copy the original list
    tx_list_copy.remove(txid)         # remove the txid element, this is already the list without the txid element
</code>```

Then, to remove the txid element from tx_list_copy, you could use the .remove() method, which removes the element in the tx_list_copy, so this is already the list you need.

Body:
I have a list of strings and I'm trying to iterate through it and create each iteration a new list without one of the strings.
I tried the following:

tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)

But each iteration the new list is empty.

Body:
The statement:

tx_list_copy = tx_list

does not copy the list but it refers to the same memory object: tx_list and tx_list_copy are different references to the same memory object list. This means that if you edit the first one, the second one will be edited too.

Instead, in order to copy the original list, you should use the .copy() method:

for txid in tx_list:
    tx_list_copy = tx_list.copy()     # copy the original list
    tx_list_copy.remove(txid)         # remove the txid element, this is already the list without the txid element

Then, to remove the txid element from tx_list_copy, you could use the .remove() method, which removes the element in the tx_list_copy, so this is already the list you need.


来源: stackexchange

问:
Align Button To The center Of the window using pysimplegui
In my application am trying to place my button,text and input at the center of the window.I am using PySimpleGUI for designing buttons.For aligning to the center i used justification='center' attribute on my code.But still it is not fitting to the center of the window.

The code am working with is

```<code>import PySimpleGUI as sg
from tkinter import *
sg.theme('DarkAmber')
layout = [
        [sg.Text('Enter the value',justification='center')],
        [sg.Input(justification='center')],
        [sg.Button('Enter','center')]
     ]

  window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True)

 while True:
event, values = window.read()   # Read the event that happened and the values dictionary
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':     # If user closed window with X or if user clicked "Exit" button then exit
    break
if event == 'Button':
  print('You pressed the button')
window.close()
</code>```

The above code outputs

How can i make the text,button and input to the center of the window?

答:
this code make the text, button and input to the center of the window.</p>
```<code>import PySimpleGUI as sg
sg.theme('DarkAmber')
layout = [
        [sg.Text('Enter the value',justification='center',size=(100,1))],
        [sg.Input(justification='center',size=(100,1))],
        [sg.Button('Enter','center',size=(100,1))]
     ]

window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True)

while True:
    event, values = window.read()   # Read the event that happened and the values dictionary
    print(event, values)
    if event == None or event == 'Exit':     # If user closed window with X or if user clicked "Exit" button then exit
        break
    if event == 'Button':
      print('You pressed the button')
    window.close()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my application am trying to place my button,text and input at the center of the window.I am using PySimpleGUI for designing buttons.For aligning to the center i used justification='center' attribute on my code.But still it is not fitting to the center of the window.

The code am working with is

import PySimpleGUI as sg
from tkinter import *
sg.theme('DarkAmber')
layout = [
        [sg.Text('Enter the value',justification='center')],
        [sg.Input(justification='center')],
        [sg.Button('Enter','center')]
     ]

  window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True)

 while True:
event, values = window.read()   # Read the event that happened and the values dictionary
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':     # If user closed window with X or if user clicked "Exit" button then exit
    break
if event == 'Button':
  print('You pressed the button')
window.close()

The above code outputs

How can i make the text,button and input to the center of the window?

Body:
this code make the text, button and input to the center of the window.

import PySimpleGUI as sg
sg.theme('DarkAmber')
layout = [
        [sg.Text('Enter the value',justification='center',size=(100,1))],
        [sg.Input(justification='center',size=(100,1))],
        [sg.Button('Enter','center',size=(100,1))]
     ]

window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True)

while True:
    event, values = window.read()   # Read the event that happened and the values dictionary
    print(event, values)
    if event == None or event == 'Exit':     # If user closed window with X or if user clicked "Exit" button then exit
        break
    if event == 'Button':
      print('You pressed the button')
    window.close()


问:
Make API calls to model deployed on GCP
We have trained a Nasnet model on GCP, and deployed it so that API calls can be made.

The model takes an image as input (numpy array), and returns an array of predictions. However, when we try to make API calls to the model sending a numpy array, an error occurs (Request payload size exceeds the limit). Another commonly accepted format is base64, however our model is only configured to take in a numpy array as input.

Is there any way to fix this issue so that predictions can be made with API calls? Would creating a serverless function help? Thanks

EDIT: Here is the code I'm using the make a request to the GCP model:

```<code>import googleapiclient.discovery
import numpy as np
import requests

# x is an image encoded as a numpy array
def generate_custom_tags(x):

    project_id = "MY_PROJECT_ID"
    model_id = "MY_MODEL_NAME"
    model_path = "projects/{}/models/{}".format(project_id, model_id)
    ml_resource = googleapiclient.discovery.build("ml","v1").projects()
    instances = { 'input_2': x.tolist() }

    input_data_json = {"signature_name": "serving_default", "instances": instances}
    request = ml_resource.predict(name=model_path, body = input_data_json)

    response = request.execute()
    if "error" in response:
        raise RuntimeError(response["error"])
    return np.array([pred["dense"] for pred in response["predictions"]])
</code>```

答:
The “Request payload size exceeds the limit” error is due to a hard limit for the Cloud Machine Learning Engine API. There's a feature request to increase this limit which you can follow for updates here [1]. In the meantime, try using the following solution as it is similar to your case [2].

[1] https://issuetracker.google.com/123314535

[2] gcloud ml-engine returns error on large files

Title: Make API calls to model deployed on GCP

Body:
We have trained a Nasnet model on GCP, and deployed it so that API calls can be made.

The model takes an image as input (numpy array), and returns an array of predictions. However, when we try to make API calls to the model sending a numpy array, an error occurs (Request payload size exceeds the limit). Another commonly accepted format is base64, however our model is only configured to take in a numpy array as input.

Is there any way to fix this issue so that predictions can be made with API calls? Would creating a serverless function help? Thanks

EDIT: Here is the code I'm using the make a request to the GCP model:

import googleapiclient.discovery
import numpy as np
import requests

# x is an image encoded as a numpy array
def generate_custom_tags(x):

    project_id = "MY_PROJECT_ID"
    model_id = "MY_MODEL_NAME"
    model_path = "projects/{}/models/{}".format(project_id, model_id)
    ml_resource = googleapiclient.discovery.build("ml","v1").projects()
    instances = { 'input_2': x.tolist() }

    input_data_json = {"signature_name": "serving_default", "instances": instances}
    request = ml_resource.predict(name=model_path, body = input_data_json)

    response = request.execute()
    if "error" in response:
        raise RuntimeError(response["error"])
    return np.array([pred["dense"] for pred in response["predictions"]])


问:
Rotation of Oculus Touch Controller in A-Frame / Three.js
Does anyone know how to find the current rotation of an Oculus Touch Controller? - in A-Frame, or more likely combination of A-Frame and Three.js.
I want the current rotation to use it to control other objects.
Thanks!</p>

答:
Getting the controller position and rotation is the same as any other entity via DOM:

```<code> el.getAttribute('rotation');
</code>```

or THREE.js:

```<code> el.object3D.rotation
</code>```

Example logging rotation in console

Body:
Getting the controller position and rotation is the same as any other entity via DOM:

 el.getAttribute('rotation');

or THREE.js:

 el.object3D.rotation

Example logging rotation in console


问:
Generate SHA-1 for Flutter/React-Native/Android-Native app
I'm trying to generate a SHA-1 for a Flutter app, for Android studio to support Google Sign in, but I don't know how to do that, I saw some posts that indicate to run a command, but there I need a jks file I guess, and flutter doesn't create that.

Could someone help me?

答:
for linux:

if you are using vscode you can right-click on gradlew->copypath (in my case: /home/alif/Documents/project/flutter/fit_app/android/gradlew)

open your terminal and paste it, don't forget to delete /gradlew

type .../android gradlew signinReport and hit enter

good luck!


问:
Scispacy for biomedical named entitiy recognition(NER)
How to label entities using scispacy?

When I tried to perform NER using scispacy, it identified the biomedical entities by labeling them as Entity but failed to label them as gene/protein, etc.. So how do I do that using scispacy? Or is scispacy not capable of labeling data? The image is attached for reference:
jupyter notebook snippet

答:
You can filter the label by 'GENE_OR_GENE_PRODUCT' to get all gene names.</p>

```<code>import spacy
import scispacy
import en_ner_bionlp13cg_md

document = "We aimed to prospectively compare the risk of early progression according to circulating ESR1 mutations, CA-15.3, and circulating cell-free DNA in MBC patients treated with a first-line aromatase inhibitor (AI)"

nlp = spacy.load("en_ner_bionlp13cg_md")
for X in nlp(document).ents:
    if X.label_=='GENE_OR_GENE_PRODUCT':
        print(X.text)
</code>```

Body:
You can filter the label by 'GENE_OR_GENE_PRODUCT' to get all gene names.

import spacy
import scispacy
import en_ner_bionlp13cg_md

document = "We aimed to prospectively compare the risk of early progression according to circulating ESR1 mutations, CA-15.3, and circulating cell-free DNA in MBC patients treated with a first-line aromatase inhibitor (AI)"

nlp = spacy.load("en_ner_bionlp13cg_md")
for X in nlp(document).ents:
    if X.label_=='GENE_OR_GENE_PRODUCT':
        print(X.text)


答:
You can use cumulative window functions and aggregation:

```<code>select source, min(updated_date), max(closed_date)
from (select t.*,
             count(closed_date) over (partition by source order by updated_date desc) as grp
      from t
     ) t
group by source, grp;
</code>```

The idea is a reverse count of updated_date to assign a group to the rows.  Then aggregate based on that group.

Title: How to match a table with 3 columns, returning the first ocurrence of the second column with the first non-value of the third one?

Body:
I'm strugling to make this work. I have a table with this structure:

enter code here
|---------------------|------------------|------------------|
|      source         |   updated_date   |   closed_date    |
|---------------------|------------------|------------------|
|        RMD          |   2019-01-01     |       NULL       |
|---------------------|------------------|------------------|
|        RMD          |   2019-01-25     |       NULL       |
|---------------------|------------------|------------------|
|        RMD          |   2019-01-29     |    2019-02-05    |
|---------------------|------------------|------------------|
|        SRC          |   2019-02-15     |       NULL       |
|---------------------|------------------|------------------|
|        SRC          |   2019-02-19     |    2019-02-21    |
|---------------------|------------------|------------------|
|        SRC          |   2019-02-20     |       NULL       |
|---------------------|------------------|------------------|
|        SRC          |   2019-02-27     |    2019-02-28    |
|---------------------|------------------|------------------|

I need to return the first updated date and the respective first non-null closed_date.

Example, based on the above's data, I would like to returng this:

|---------------------|------------------|------------------|
|      source         |   updated_date   |   closed_date    |
|---------------------|------------------|------------------|
|        RMD          |   2019-01-01     |    2019-02-05    |
|---------------------|------------------|------------------|
|        SRC          |   2019-02-15     |    2019-02-21    |
|---------------------|------------------|------------------|
|        SRC          |   2019-02-20     |    2019-02-28    |
|---------------------|------------------|------------------|

This is quite challenging for me and I'm cracking my head on getting this work. The closest I could get was using self-relationship but I couldn't manage to make this work as I just can't get the first value to match with the second one, and I also tried COALESCE but either it does not work for this example or I didn't used well.

Any good soul to give me a light?

Body:
You can use cumulative window functions and aggregation:

select source, min(updated_date), max(closed_date)
from (select t.*,
             count(closed_date) over (partition by source order by updated_date desc) as grp
      from t
     ) t
group by source, grp;

The idea is a reverse count of updated_date to assign a group to the rows.  Then aggregate based on that group.


问:
How do I count the number of occurrence of an item in a list? - Dart
I would like to know how many occurrences of a single item consists in a list in dart. As far as I know, the contains method checks only up to the first occurrence and returns a bool. </p>

答:
Following counts how many "1"s are in list:

[1, 2, 1].where((item) => item == 1).length
```


问:
React/Node app in Heroku, serving index.html/index.js with server running
I'm pretty sure that this issue is localized to my start scripts. When looking online people will post differing start scripts.

Some have "start": "node index.js" -> (this won't start my server), gives an H10 error in heroku logs

Others have "start": "nodemon server.js" -> (this runs the server, serves the index.html, but it won't include the index.js file), no error given but not desired behavior

I used create-react-app, it works locally when i can do concurrent 'react-scripts start' and 'nodemon server', and my port is also set to the environment var.
let me know if I can provide extra info, and any help would be appreciated

Index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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

Server.js

```<code>require('dotenv').config();

var express = require("express");
var app = express();
const cookieParser = require('cookie-parser');
var withAuth = require('./middleware');
const path = require('path');
var PORT = process.env.PORT || 4090;

const {
    receivePublicToken,
    getTransactions,
    getBalance,
    putCat,
    getCat,
    logIn,
    isUser
} = require("../src/controllers/controller");

app.use(express.json());
app.use(cookieParser());

// Get the public token and exchange it for an access token
app.post("/auth/public_token", withAuth, receivePublicToken);// Get Transactions
app.get("/transactions", getTransactions);
app.get("/accounts/balance/get", getBalance);
app.post("/users/login", logIn);
app.post("/categories/post", putCat);
app.get("/categories/get", getCat);
app.get("/auth", withAuth, isUser);
app.get("/logout", (req, res) => {
    res.clearCookie('token').sendStatus(200);
})
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'))
});

app.listen(PORT, () => {
    console.log(`Server running on ${PORT}`);
});
</code>```

start script in package.json

```<code>"scripts": {
  "dev": "concurrently \"npm run start\" \"npm run start-client\"",
  "start-client": "react-scripts start"
  "start": "nodemon server/server.js",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject",
  "postinstall": "npm run build"
  }
</code>```

directory structure

答: I think your start script must be node server/server.js

Body:
I'm pretty sure that this issue is localized to my start scripts. When looking online people will post differing start scripts.

Some have "start": "node index.js" -> (this won't start my server), gives an H10 error in heroku logs

Others have "start": "nodemon server.js" -> (this runs the server, serves the index.html, but it won't include the index.js file), no error given but not desired behavior

I used create-react-app, it works locally when i can do concurrent 'react-scripts start' and 'nodemon server', and my port is also set to the environment var.
let me know if I can provide extra info, and any help would be appreciated

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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

Server.js

require('dotenv').config();

var express = require("express");
var app = express();
const cookieParser = require('cookie-parser');
var withAuth = require('./middleware');
const path = require('path');
var PORT = process.env.PORT || 4090;

const {
    receivePublicToken,
    getTransactions,
    getBalance,
    putCat,
    getCat,
    logIn,
    isUser
} = require("../src/controllers/controller");

app.use(express.json());
app.use(cookieParser());

// Get the public token and exchange it for an access token
app.post("/auth/public_token", withAuth, receivePublicToken);// Get Transactions
app.get("/transactions", getTransactions);
app.get("/accounts/balance/get", getBalance);
app.post("/users/login", logIn);
app.post("/categories/post", putCat);
app.get("/categories/get", getCat);
app.get("/auth", withAuth, isUser);
app.get("/logout", (req, res) => {
    res.clearCookie('token').sendStatus(200);
})
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'))
});

app.listen(PORT, () => {
    console.log(`Server running on ${PORT}`);
});

start script in package.json

"scripts": {
  "dev": "concurrently \"npm run start\" \"npm run start-client\"",
  "start-client": "react-scripts start"
  "start": "nodemon server/server.js",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject",
  "postinstall": "npm run build"
  }

directory structure


问:
Firebase security rules: "ruleset uses old version", what is current version?
firebase --version 8.4.1

with Firebase init I created some files.

Now firebase deploy is complaining about firebase.storage.  The error message is:

Ruleset uses old version (version [1]). Please update to the latest version (version [2]).

What is wrong with it?

```<code>firebase deploy
deploying database, storage, firestore, functions, hosting
database:   checking rules syntax...
database: rules syntax for database $db is valid
firebase.storage: checking storage.rules for compilation errors...
undefined:undefined - Ruleset uses old version (version
   [1]). Please update to the latest version (version [2]).
firebase.storage: rules file storage.rules compiled successfully

cat storage.rules

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth!=null;
    }
  }
}
</code>```

答:
You should be using security rules version 2 going forward. Note the first line:</p>

```<code>rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth!=null;
    }
  }
}
</code>```

Body:
firebase --version 8.4.1

with Firebase init I created some files.

Now firebase deploy is complaining about firebase.storage.  The error message is:

Ruleset uses old version (version [1]). Please update to the latest version (version [2]).

What is wrong with it?

firebase deploy
deploying database, storage, firestore, functions, hosting
database:   checking rules syntax...
database: rules syntax for database $db is valid
firebase.storage: checking storage.rules for compilation errors...
undefined:undefined - Ruleset uses old version (version
   [1]). Please update to the latest version (version [2]).
firebase.storage: rules file storage.rules compiled successfully

cat storage.rules

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth!=null;
    }
  }
}

Body:
You should be using security rules version 2 going forward. Note the first line:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth!=null;
    }
  }
}


问:
How to use "mysql2" gem in Rails 3 application on Windows 7?
I try to install the mysql2 gem on Windows 7 32-bit.

I run:

```<code>gem install mysql2
</code>```

and I get the following error:

```<code>ERROR:  Error installing mysql2:
        The 'mysql2' native gem requires installed build tools.

Please update your PATH to include build tools or download the DevKit
from 'http://rubyinstaller.org/downloads' and follow the instructions
at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
</code>```

Any ideas what could cause this error, and how to solve this ?

UPDATE

I did everything as described here, but I can't figure out the last step:

```<code>gem install mysql2 --
     '--with-mysql-lib="c:\Program Files\MySQL\MySQL Server 5.1\lib\opt"
      --with-mysql-include="c:\Program Files\MySQL\MySQL Server 5.1\include"'
</code>```

I understand that I should change the paths to the correct paths in my system, but I can't find the lib\opt and the include directories in my WAMP MySQL installation. I use WAMP 2.1.

Please advise.

答:
Try XAMPP from apachefriends.org, be sure to download the full version and you will find "lib", "bin", "include" and other MySQL directories. For further details, refer to -

http://rorguide.blogspot.com/2011/03/installing-mysql2-gem-on-ruby-192-and.html

ContentLicense: CC BY-SA 3.0

Body:
I try to install the mysql2 gem on Windows 7 32-bit.

I run:

gem install mysql2

and I get the following error:

ERROR:  Error installing mysql2:
        The 'mysql2' native gem requires installed build tools.

Please update your PATH to include build tools or download the DevKit
from 'http://rubyinstaller.org/downloads' and follow the instructions
at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'

Any ideas what could cause this error, and how to solve this ?

UPDATE

I did everything as described here, but I can't figure out the last step:

gem install mysql2 --
     '--with-mysql-lib="c:\Program Files\MySQL\MySQL Server 5.1\lib\opt"
      --with-mysql-include="c:\Program Files\MySQL\MySQL Server 5.1\include"'

I understand that I should change the paths to the correct paths in my system, but I can't find the lib\opt and the include directories in my WAMP MySQL installation. I use WAMP 2.1.

Please advise.


问:
How to get the desired outpout from the following list?
Suppose the is a list with following values

```<code>A=[1,2,3,4,5,6,7]
</code>```

The Required Output is

print

```<code>1
1+2
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7
</code>```

Please help me to get the above answer..

Body:
Suppose the is a list with following values

A=[1,2,3,4,5,6,7]

The Required Output is

print

1
1+2
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7

Please help me to get the above answer..

Body:
a = [1,2,3,4,5,6,7]
for i in range(len(a)+1):
    for j in range(i):
        if(j+1==i):
            print(a[j],end='')
        else:
            print(a[j],'+ ',end='')
    print(('\r'))


问:
Laravel Shared Hosting .htaccess
I am trying to deploy a Laravel project onto a share hosting, I've managed to get most of the hard work done but I cannot strip off the /public directory without a Forbidden issue.

The website works and shows same pages for these links

www.mywebsite.com/test/index.php

www.mywebsite.com/test/public/

But without the /index.php It returns ->

```<code>Forbidden

You don't have permission to access /test/ on this server.
</code>```

Currently my .htaccess looks like the following.

```<code><IfModule mod_rewrite.c>

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ public/index.php [L]

</IfModule>
</code>```

Any ideas?

答:
this is the magic script i use (add to the .htaccess in public_html)

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
</code>```

Title: Laravel Shared Hosting .htaccess

Body:
I am trying to deploy a Laravel project onto a share hosting, I've managed to get most of the hard work done but I cannot strip off the /public directory without a Forbidden issue.

The website works and shows same pages for these links

www.mywebsite.com/test/index.php

www.mywebsite.com/test/public/

But without the /index.php It returns ->

Forbidden

You don't have permission to access /test/ on this server.

Currently my .htaccess looks like the following.

<IfModule mod_rewrite.c>

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ public/index.php [L]

</IfModule>

Any ideas?

Body:
this is the magic script i use (add to the .htaccess in public_html)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>


问:
How to save pdf file in node js with express and multer
I'm using a multer api, and I'm saving files in memory, because I need to upload images and pdf, and I need to process the images.

I can upload images, but I can't upload pdfs files.

Thanks

答:
this might help you </p>

```<code>// Set storage engine
const storage = multer.diskStorage({
  destination: "./uploads",
  filename: function(req, file, cb) {
    // null as first argument means no error
    cb(null, Date.now() + "-" + file.originalname);
  },
});

  let encode_file = null;
  let fileName = "";
  if (req.file) {
    fileName = req.file.originalname;
    var filepath = path.join(__dirname, req.file.path);
    console.log(filepath);
    var stream = fs.readFileSync(filepath);
    encode_file = stream.toString("base64");
  }
</code>```

Body:
this might help you

// Set storage engine
const storage = multer.diskStorage({
  destination: "./uploads",
  filename: function(req, file, cb) {
    // null as first argument means no error
    cb(null, Date.now() + "-" + file.originalname);
  },
});

  let encode_file = null;
  let fileName = "";
  if (req.file) {
    fileName = req.file.originalname;
    var filepath = path.join(__dirname, req.file.path);
    console.log(filepath);
    var stream = fs.readFileSync(filepath);
    encode_file = stream.toString("base64");
  }


问:
ElementNotInteractableException: element not interactable: element has zero size appears since upgrade to chromedriver 83
I use the following docker image to run my cucumber tests:

https://hub.docker.com/r/selenium/standalone-chrome/

Unfortunately, starting from today it seems that whenever I run my tests I get the errors below. They appear at the start of each test. It does not matter what I do on the page.

**13:38:26      [exec] org.openqa.selenium.ElementNotInteractableException: element not interactable: element has zero size

13:38:26      [exec]   (Session info: chrome=83.0.4103.61)**

I did some digging and I noticed the chromedriver version was updated from 81 to 83. I managed to fix this issue by using an older docker image from that docker hub link which has chromedriver 81. But if I attempt to use chromedriver 83 again it will not work.

Has anyone else encountered this? Is there a new chrome option I need to add because of the update?

答:
The root cause of that issue is that Chrome doesn't scroll to the element outside of the viewport. Instead of it, Chrome tries to click on it outside of the viewing area. That's why the issue appears. It is definitely an issue with Chrome 83 because I didn't face it on Chrome 81.

Moreover, I have no such issue on Windows machine, it reproduced only on Linux (I'm using selenoid docker images).

Solution with a click via JS is not the best option, because via JS you can click anywhere even for unclickable elements (e.g. overlapped by other objects). It's an unsafe operation.

Instead of this, I would suggest scrolling to the element before click and after native click(); it will work just perfectly.

```<code>JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView(true);", element);
element.click();
</code>```

Body:
The root cause of that issue is that Chrome doesn't scroll to the element outside of the viewport. Instead of it, Chrome tries to click on it outside of the viewing area. That's why the issue appears. It is definitely an issue with Chrome 83 because I didn't face it on Chrome 81.

Moreover, I have no such issue on Windows machine, it reproduced only on Linux (I'm using selenoid docker images).

Solution with a click via JS is not the best option, because via JS you can click anywhere even for unclickable elements (e.g. overlapped by other objects). It's an unsafe operation.

Instead of this, I would suggest scrolling to the element before click and after native click(); it will work just perfectly.

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView(true);", element);
element.click();


问:
Where to put a utility function in Angular
This is just an example working with Angular, let say I need to use a function in the component, in this case the getDay() function will be called by an event.

```<code>getDay()  {
  switch (new Date().getDay()) {
    case 0:
      day = "Sunday";
      break;
    case 1:
      day = "Monday";
      break;
    case 2:
       day = "Tuesday";
       break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
  }
}
</code>```

Since I'm using Typescript, should I just create a shared folder inside components directory and inside it:

Create a component e.g: formatDate.component.ts with export class FormateDateComponent and just add my function there and import where I want?

What would be the best practice.

答:
There are two ways :-

create a static method in a class:-

    export Class DateHelper {
       static getDay()  {
        switch (new Date().getDay()) {
             case 0:
             day = "Sunday";
             break;
             case 1:
             day = "Monday";
             break;
             case 2:
             day = "Tuesday";
             break;
             case 3:
             day = "Wednesday";
             break;
             case 4:
             day = "Thursday";
             break;
             case 5:
             day = "Friday";
             break;
             case 6:
             day = "Saturday";
           }
        }
      }```
</div>
</div>
</p>

<p>and can use it like DateHelper.getDay() directly.</p>

<ol start="2">
<li>way create a class and inherit it in component Foreg:-</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    export class AppComponent extends DateHelper {
       constructor(){
         super();
       }
       this.getDay();
    } </code>```

For normal methods like you have i would go with first approach.

Body:
This is just an example working with Angular, let say I need to use a function in the component, in this case the getDay() function will be called by an event.

getDay()  {
  switch (new Date().getDay()) {
    case 0:
      day = "Sunday";
      break;
    case 1:
      day = "Monday";
      break;
    case 2:
       day = "Tuesday";
       break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
  }
}

Since I'm using Typescript, should I just create a shared folder inside components directory and inside it:

Create a component e.g: formatDate.component.ts with export class FormateDateComponent and just add my function there and import where I want?

What would be the best practice.

Body:
There are two ways :-

create a static method in a class:-

    export Class DateHelper {
       static getDay()  {
        switch (new Date().getDay()) {
             case 0:
             day = "Sunday";
             break;
             case 1:
             day = "Monday";
             break;
             case 2:
             day = "Tuesday";
             break;
             case 3:
             day = "Wednesday";
             break;
             case 4:
             day = "Thursday";
             break;
             case 5:
             day = "Friday";
             break;
             case 6:
             day = "Saturday";
           }
        }
      }

and can use it like DateHelper.getDay() directly.

way create a class and inherit it in component Foreg:-

    export class AppComponent extends DateHelper {
       constructor(){
         super();
       }
       this.getDay();
    }

For normal methods like you have i would go with first approach.


问:
Does deleting venv delete installed modules?
Does deleting a python virtual environment (venv) directory delete the modules installed in it?

I see the installed modules both in the venv directory and also under Python3.7/Scripts directory. I can access the installed modules even when I am outside the venv. If I delete the venv directory will I not be able to do so?

答:
When you delete the venv directory the modules installed in it are deleted.

Where as you have those modules in your Python3.7/Scripts directory also.

So, you can access them even if you delete venv directory.


问:
Task :app:createReleaseExpoManifest FAILED
I am trying to produce apk in a project I created with create-react-native-app. But an error like xxxx occurs. I would appreciate if anyone with knowledge helps.

Task :app:createReleaseExpoManifest FAILED
Error: Failed to connect to the packager server. If you did not start this build by running 'react-native run-android', you can start the packager manually by running 'react-native start' in the project directory. (Error: connect ECONNREFUSED 127.0.0.1:8081)

enter image description here
enter image description here

答:
See the error message:

Task :app:createReleaseExpoManifest FAILED
  Error: Failed to connect to the packager server. If you did not start this build by running 'react-native run-android', you can start the packager manually by running 'react-native start' in the project directory. (Error: connect ECONNREFUSED 127.0.0.1:8081)

So, run react-native start and then build your app.


问:
Trying to combine a list of lists in python
I have a list of lists containing tuples of x and y coordinates such as
[ [(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)] ] and I want to combine them in such a way where the output contains all the x coordinates together and all the y coordinates together. Essentially I'm trying to make the output be [(1,3,5,7,0), (2,4,6,8,5)] so that it is a 2xN matrix. I tried to do list(zip(*b) where b = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]] (the original list), but that has not given me the correct output.

答:
The shortest possible solution, though perhaps not as intuitive.</p>

```<code>list(zip(*sum(b,[])))
</code>```

Body:
The shortest possible solution, though perhaps not as intuitive.

list(zip(*sum(b,[])))


问:
Issue with adding independent filters search to multiple parameters in SSRS
I have been trying to create a report with multiple parameters. My requirement is to keep those parameters separate from each other while searching the report. in this picture we have four input values but they are codependent which each other and the requirement says the client should be able to see the data with one filter input Can anyone can help me how to separate these individual searchers. </p>

答:
all these values are coming from the same table, we had to do it this way because we needed the distinct values from the table. I tried this query and report still not giving any result when I select only one parameter. SELECT *
      FROM  data_table_name ax
      WHERE (
    (region IN (@region) or @region IS NULL)
    AND
    (cocode IN (@cocode) or @cocode IS NULL)
    AND
    (prodcode IN (@prodcode) or @prodcode IS NULL)
    AND
    (CONVERT(VARCHAR(10), datetimestamp, 110) IN (@datetimestamp) or        @datetimestamp IS NULL)
    ) This is how i structured my report</p>


问:
Count half of rest of a partition by from position
I'm trying to achieve the following results:

now, the group comes from

```<code> SUM(CASE WHEN seqnum <= (0.5 * seqnum_rev) THEN i.[P&L] END) OVER(PARTITION BY i.bracket_label ORDER BY i.event_id) AS [P&L 50%],
</code>```

I need that in each iteration it counts the total of rows from the end till position (seq_inv) and sum the amounts in P&L only for the half of it from that position.

for example, when

```<code>seq = 2
</code>```

seq_inv will be = 13, half of it is 6 so I need to sum the following 6 positions from seq = 2.

when seq = 4  there are 11 positions till the end (seq_inv = 11), so half is 5, so I want to count 5 positions from seq = 4.

I hope this makes sense, I'm trying to come up with a rule that will be able to adapt to the case I have, since the partition by is what gives me the numbers that need to be summed.

I was also thinking if there was something to do with a partition by top 50% or something like that, but I guess that doesn't exist.

答:
I have the advantage that I've helped him before and have a little extra context.

That context is that this is just the later stage of a very long chain of common table expressions.  That means self-joins and/or correlated sub-queries are unfortunately expensive.

Preferably, this should be answerable using window functions, as the data set is already available in the appropriate ordering and partitioning.

My reading is this...

The SUM(5:9) (meaning the sum of rows 5 to row 9, inclusive) is equal to SUM(5:end) - SUM(10:end)

That leads me to this...

```<code>WITH
  cumulative AS
(
  SELECT
    *,
    SUM([P&L]) OVER (PARTITION BY bracket_label ORDER BY event_id DESC)  AS cumulative_p_and_l
  FROM
    data
)
SELECT
  *,
  cum_val - LEAD(cumulative_p_and_l, seq_inv/2, 0) OVER (PARTITION BY bracket_label ORDER BY event_id)  AS p_and_l_50_perc,
  cum_val - LEAD(cumulative_p_and_l, seq_inv/4, 0) OVER (PARTITION BY bracket_label ORDER BY event_id)  AS p_and_l_25_perc,
FROM
  cumulative
</code>```

NOTE: Using , &, % in column names is horrendous, don't do it ;)

EDIT: Corrected the ORDER BY in the cumulative sum.

Body:
I'm trying to achieve the following results:

now, the group comes from

 SUM(CASE WHEN seqnum <= (0.5 * seqnum_rev) THEN i.[P&L] END) OVER(PARTITION BY i.bracket_label ORDER BY i.event_id) AS [P&L 50%],

I need that in each iteration it counts the total of rows from the end till position (seq_inv) and sum the amounts in P&L only for the half of it from that position.

for example, when

seq = 2

seq_inv will be = 13, half of it is 6 so I need to sum the following 6 positions from seq = 2.

when seq = 4  there are 11 positions till the end (seq_inv = 11), so half is 5, so I want to count 5 positions from seq = 4.

I hope this makes sense, I'm trying to come up with a rule that will be able to adapt to the case I have, since the partition by is what gives me the numbers that need to be summed.

I was also thinking if there was something to do with a partition by top 50% or something like that, but I guess that doesn't exist.

Body:
I have the advantage that I've helped him before and have a little extra context.

That context is that this is just the later stage of a very long chain of common table expressions.  That means self-joins and/or correlated sub-queries are unfortunately expensive.

Preferably, this should be answerable using window functions, as the data set is already available in the appropriate ordering and partitioning.

My reading is this...

The SUM(5:9) (meaning the sum of rows 5 to row 9, inclusive) is equal to SUM(5:end) - SUM(10:end)

That leads me to this...

WITH
  cumulative AS
(
  SELECT
    *,
    SUM([P&L]) OVER (PARTITION BY bracket_label ORDER BY event_id DESC)  AS cumulative_p_and_l
  FROM
    data
)
SELECT
  *,
  cum_val - LEAD(cumulative_p_and_l, seq_inv/2, 0) OVER (PARTITION BY bracket_label ORDER BY event_id)  AS p_and_l_50_perc,
  cum_val - LEAD(cumulative_p_and_l, seq_inv/4, 0) OVER (PARTITION BY bracket_label ORDER BY event_id)  AS p_and_l_25_perc,
FROM
  cumulative

NOTE: Using , &, % in column names is horrendous, don't do it ;)

EDIT: Corrected the ORDER BY in the cumulative sum.


问:
Java: ClassNotFound Classpath issues
Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.

However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.

I've been reading that you can change the path that JVM uses when searching for class files.

so I tried:

set CLASSPATH=$CLASSPATH=~/../../BackEnd

but that didn't do anything..

Here is my main file..

```<code>import java.util.Scanner;
import java.io.File;
class BackEnd
{
    public static void main(String args[]) throws java.io.FileNotFoundException
    {

        Tree.ServiceTree providers = new Tree.ServiceTree();
        String path = "./providers.txt";
        Scanner read = new Scanner (new File(path));
        read.useDelimiter(",");
        String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
        try
        {
            while(read.hasNext())
            {
                for(int i = 0; i < 5; ++i)
                {
                    information[i] = read.nextLine();//read in all the info into the array
                }

                Services.Service newService;//used as dynamic reference to be passed to tree
                Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor

                switch(information[0])//check type to initalize appropriate object
                {
                    case "Dogwalk":
                        newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
                    case "Groceries":
                        newService = new Services.Groceries(serviceInfo, information[2], information[3]);
                    case "Housework":
                        newService = new Services.Housework(serviceInfo, information[2], information[3]);
                }
                providers.insert(information[4], newService);
            }
            read.close();
            throw new java.io.FileNotFoundException("File not found...");
        }
        catch(java.io.FileNotFoundException exception)
        {
            System.out.println("File not found");
        }
        //providers.display();
    }
}
</code>```

答:
Figured it out. Error had nothing to do with compilation or class path and was due
to uninitialized variable newService

Title: Java: ClassNotFound Classpath issues

Body:
Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.

However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.

I've been reading that you can change the path that JVM uses when searching for class files.

so I tried:

set CLASSPATH=$CLASSPATH=~/../../BackEnd

but that didn't do anything..

Here is my main file..

import java.util.Scanner;
import java.io.File;
class BackEnd
{
    public static void main(String args[]) throws java.io.FileNotFoundException
    {

        Tree.ServiceTree providers = new Tree.ServiceTree();
        String path = "./providers.txt";
        Scanner read = new Scanner (new File(path));
        read.useDelimiter(",");
        String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
        try
        {
            while(read.hasNext())
            {
                for(int i = 0; i < 5; ++i)
                {
                    information[i] = read.nextLine();//read in all the info into the array
                }

                Services.Service newService;//used as dynamic reference to be passed to tree
                Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor

                switch(information[0])//check type to initalize appropriate object
                {
                    case "Dogwalk":
                        newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
                    case "Groceries":
                        newService = new Services.Groceries(serviceInfo, information[2], information[3]);
                    case "Housework":
                        newService = new Services.Housework(serviceInfo, information[2], information[3]);
                }
                providers.insert(information[4], newService);
            }
            read.close();
            throw new java.io.FileNotFoundException("File not found...");
        }
        catch(java.io.FileNotFoundException exception)
        {
            System.out.println("File not found");
        }
        //providers.display();
    }
}


问:
Typescript groupBy "Cannot be used to index type '{}'" when trying to add key to reduce object
I'm trying to get the following function to compile without TS erros:

```<code>function groupBy<Item>(items: Item[], key: keyof Item) {
  return items.reduce((acc, item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {});
}
</code>```

But assigning to acc results in Type 'Item[keyof Item]' cannot be used to index type '{}'.

I've tried a lot of other things like playing with Extract and Record but just results in more errors e.g.

```<code>export function groupBy<Item extends Record<string, object>, K extends Extract<keyof Item, string>>(
  items: Item[],
  key: K
) {
  return items.reduce((acc: Record<K, Item[]>, item: Item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {});
}
</code>```

P.S the functionality is like lodash groupBy e.g.

```<code>groupBy(['one', 'two', 'three'], 'length');
// Result: { '3': ['one', 'two'], '5': ['three'] }
</code>```

How can I fix that? Thanks

答:
I'd type it like this:

```<code>function groupBy<T extends Record<K, PropertyKey>, K extends keyof T>(
  items: readonly T[],
  key: K
) {
  return items.reduce((acc, item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {} as Record<T[K], T[]>);
}
</code>```

The important bits are: mutually constraining K and T so that K is a key of T where the property T[K] is itself suitable to be a key of an object; and asserting that the accumulator will eventually be of type Record<T[K], T[]>, an object whose keys are the same as T[K] and whose values are an array of T.

Then you can test that it works:

```<code>const g = groupBy(['one', 'two', 'three'], 'length');
// const g: Record<number, string[]>

console.log(
  Object.keys(g).map(k => k + ": " + g[+k].join(", ")).join("; ")
); // 3: one, two; 5: three
</code>```

The type of g is inferred as {[k: number]: string[]}, an object with a numeric index signature whose properties are string arrays.  As another example, to make sure it works:

```<code>interface Shirt {
  size: "S" | "M" | "L"
  color: string;
}
const shirts: Shirt[] = [
  { size: "S", color: "red" },
  { size: "M", color: "blue" },
  { size: "L", color: "green" },
  { size: "S", color: "orange" }];

const h = groupBy(shirts, "size");
// const h: Record<"S" | "M" | "L", Shirt[]>

console.log(JSON.stringify(h));
//{"S":[{"size":"S","color":"red"},{"size":"S","color":"orange"}],"M":[{"size":"M","color":"blue"}],"L":[{"size":"L","color":"green"}]}
</code>```

Here we see that a Shirt has a size property from a limited selection of string literals, and groupBy(shirts, "size") returns a value inferred to be of type {S: Shirt[], M: Shirt[], L: Shirt[]}.

Okay, hope that helps; good luck!

Playground link to code

Body:
I'm trying to get the following function to compile without TS erros:

function groupBy<Item>(items: Item[], key: keyof Item) {
  return items.reduce((acc, item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {});
}

But assigning to acc results in Type 'Item[keyof Item]' cannot be used to index type '{}'.

I've tried a lot of other things like playing with Extract and Record but just results in more errors e.g.

export function groupBy<Item extends Record<string, object>, K extends Extract<keyof Item, string>>(
  items: Item[],
  key: K
) {
  return items.reduce((acc: Record<K, Item[]>, item: Item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {});
}

P.S the functionality is like lodash groupBy e.g.

groupBy(['one', 'two', 'three'], 'length');
// Result: { '3': ['one', 'two'], '5': ['three'] }

How can I fix that? Thanks

Body:
I'd type it like this:

function groupBy<T extends Record<K, PropertyKey>, K extends keyof T>(
  items: readonly T[],
  key: K
) {
  return items.reduce((acc, item) => {
    (acc[item[key]] = acc[item[key]] || []).push(item);
    return acc;
  }, {} as Record<T[K], T[]>);
}

The important bits are: mutually constraining K and T so that K is a key of T where the property T[K] is itself suitable to be a key of an object; and asserting that the accumulator will eventually be of type Record<T[K], T[]>, an object whose keys are the same as T[K] and whose values are an array of T.

Then you can test that it works:

const g = groupBy(['one', 'two', 'three'], 'length');
// const g: Record<number, string[]>

console.log(
  Object.keys(g).map(k => k + ": " + g[+k].join(", ")).join("; ")
); // 3: one, two; 5: three

The type of g is inferred as {[k: number]: string[]}, an object with a numeric index signature whose properties are string arrays.  As another example, to make sure it works:

interface Shirt {
  size: "S" | "M" | "L"
  color: string;
}
const shirts: Shirt[] = [
  { size: "S", color: "red" },
  { size: "M", color: "blue" },
  { size: "L", color: "green" },
  { size: "S", color: "orange" }];

const h = groupBy(shirts, "size");
// const h: Record<"S" | "M" | "L", Shirt[]>

console.log(JSON.stringify(h));
//{"S":[{"size":"S","color":"red"},{"size":"S","color":"orange"}],"M":[{"size":"M","color":"blue"}],"L":[{"size":"L","color":"green"}]}

Here we see that a Shirt has a size property from a limited selection of string literals, and groupBy(shirts, "size") returns a value inferred to be of type {S: Shirt[], M: Shirt[], L: Shirt[]}.

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABAcwE5xABwEIE8A8AKogKYAeUJYAJgM6IBKJEcq1+A0gDSIAK6mEqii4OJXAD4eHUhSp1EAa3FxgiQhIAUAKESIYlALa0AXIlQkAhtQQAbXOoDaAXS66l4sx20BKRAG93CygQVCQDEmMAOgtqEAgSTU1LCAgeCMM-AF4JAPc9ZNTHDMdlXGdnRCzEFIhio1LxCsQAHxbEFx8ozBBaAAtNDJ8AbnzzEhCwmtTRvQBfHn85mvomFjYiRw5XJ2cJEe057W0WMFooFCqUdCw8TUcAcgQSB54HqAB3OFfEd76LF47B62KjIKB9B4HAD0UMQp3OKDMa1Y7DAIEMACMhDxzqgYGBkC4JMd4XAQVFbHBkDo9AB5DEAK2YUCiZVommQXUMlkwmkUVVy-IA1IgAERmUWIEWEoWKZxRBlwfGaUU8UU+LqK5Wi4Ziny+XUwxAAZjMzx4nzguoArGZwQDjvjKKhgCkSIgAMp9GDCPJ6WgwABeJAlHsl7VFAFlw2KADKi9wsSmoMy4-HIUZHeEXfo+qCmT3e4QuK6Odz+RAB4Oh1VwsmsCWxSULcuVoMhsXRnhJhtijG2EAkZs8VtVjui+Pd+spsVoEhUYej9s1qfJiWsSwEoeIObOUYnBAIvpXNAYHC4TS54S0NVj9WjI3ZxB9JHMFH4UVh1qdmMT2tevMiRJQ8yRICkqU0AApD1aQAOSiNMCRgYALz6DUHyhfxP3FRwsLvExsK4UUe1QcVRSbBY8PbMiwyIkiyI3LdRV3IjoxMXDRXwqNVWI6cyP7QdmNcP92Ko4MyMnXjkzIucF13I5tCAA" rel="nofollow noreferrer">Playground link to code


问:
Show SKU on cart and checkout pages in Woocommerce 3
I would like to display SKU on cart (Under product column ) and checkout page.

I searched SO, but all answers are for old versions of WooCommerce and non of them is for 3.x.

How can I show SKU on cart and checkout pages in Woocommerce 3?

答:
You can do it with this way:</p>

```<code>/**
 * @snippet       Show SKU @ WooCommerce Cart
 * @author        Khalid Almallahi
 */

add_action( 'woocommerce_after_cart_item_name', 'abukotsh_sku_below_cart_item_name', 11, 2 );

function abukotsh_sku_below_cart_item_name( $cart_item, $cart_item_key ) {
    $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
    $sku = $_product->get_sku();
    if ( ! $sku ) return;
    echo '<p><small>SKU: ' . $sku . '</small></p>';
}
</code>```

Body:
You can do it with this way:

/**
 * @snippet       Show SKU @ WooCommerce Cart
 * @author        Khalid Almallahi
 */

add_action( 'woocommerce_after_cart_item_name', 'abukotsh_sku_below_cart_item_name', 11, 2 );

function abukotsh_sku_below_cart_item_name( $cart_item, $cart_item_key ) {
    $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
    $sku = $_product->get_sku();
    if ( ! $sku ) return;
    echo '<p><small>SKU: ' . $sku . '</small></p>';
}


问:
COBOL DB2 Bind Process
What is the difference between pre-compile and bind for a COBOL DB2 program.

How does syntax check differ in both the processes.

If we give the wrong column name in our code, then in which process it will fail.

答:
It seems you need to do some study in the Db2 Knowledge Centre.

A pre-compile action creates a bindfile, containing the static SQL present in the source code (i.e the sections of code with EXEC SQL statements in your COBOL), in addition to a compilable form of the source code that contains the non-SQL logic and data (your PROCEDURE DIVISION and DATA DIVISION etc).

A bind action uses both the bindfile and the database to create a package inside the database which is the executable form of the bindfile contents. The package contains sections corresponding your your EXEC SQL blocks for static SQL.

Later, when the built (i.e. compiled and linked) application executes, and wants to use the database, this will cause sections of the package to be loaded from the database catalog (or read from cache) and executed by the database manager to deliver the required actions.

As each command (precompile, vs bind) serves a different purpose, the syntax varies , and also can vary with the Db2-server platform (Z/OS , i-series, Linux/Unix/Windows) and version.

Refer to the free Db2 Knowledge Center for your version of Db2 and your Db2-server platform (separate different documentation Knowledge Center websites exist for Db2-for-Z/OS,  Db2 for i-series,  Db2-for-Linux/Unix/Windows ).

Title: COBOL DB2 Bind Process


问:
Determine the time complexity using master theorem
How would I determine the time complexity using the Master Theorem for the given problem?

```<code>T(n) = aT(n/b) + O(n^d)
</code>```

```<code>T(n) = 4 T(n/2) + n*log(n)
a = 4, b = 2, d = 1
</code>```

```<code>1. O(n^d)       if d > logb(a)
2. O(n^d logn)  if d = logb(a)
3. O(n^logb(a)) if d < logb(a)
</code>```

In my case:

```<code>log2(4) = 2  --> d < log2(4)
</code>```

```<code>T(n) = O(n^logb(a))
     = O(n^2)
</code>```

Is this correct?

edit:

I have made an different approach now, resulting in the same as before though, and following my professors instruction.

```<code>T(n) = a*T(n/b) + f(n)

T(n) = 4 T(n/2) + n*log(n)

         1. Ө(n^(logba))       , if --> f(n) є O(n^(logba-ε)),
T(n) = { 2. Ө(n^(logba) log2n) , if --> f(n) є Ө(n^(logba))
         3. Ө(f(n))            , if --> f(n) є Ω(n^(logba+ε))
</code>```

First I look at the 2nd case

```<code>f(n)  = n*log(n)
logb^a = log2^4 = 2
n^log24 = n^2
</code>```

The second case does not apply because:

```<code>n*log(n) ∉ Θ(n^logba) —> the runtime of f(n) is smaller, because n*log(n) < n^2
</code>```

Look at the first case if the runtime of f(n) is smaller than n^2

```<code>1. Ө(n^(logba)) , if --> f(n) є O(n^(logba-ε))

O(n^(logba-ε)) = O(n^(log24-ε))= O(n^2-ε)
n*log(n) ∈ O(n^(log24-ε)) --> works
</code>```

f(n) has O(n^2-ε) as upper limit for worst case scenario,

case of Master—Theorems applies:

```<code>T(n) = Θ(n^log24) = Θ(n^2)
T(n) = Θ(n^2)
</code>```

答:
The version of the master theorem that you've stated here specifically assumes that the additive term has the form O(nd). In this case, the additive term is of the form n log n, which is not O(n1). This means that you cannot apply the master theorem as you have above.

A useful technique when working with recurrences like these is to sandwich the recurrence between two others. Notice, for example, that T(n) is bounded by these recurrences:

S(n) = 4S(n / 2) + n

R(n) = 4T(n / 2) + n1+ε, where ε is some small positive number.

Try solving each of these recurrences using the master theorem and see what you get, keeping in mind that your recurrence solves to a value sandwiched between them.

Hope this helps!

Body:
How would I determine the time complexity using the Master Theorem for the given problem?

T(n) = aT(n/b) + O(n^d)

T(n) = 4 T(n/2) + n*log(n)
a = 4, b = 2, d = 1

1. O(n^d)       if d > logb(a)
2. O(n^d logn)  if d = logb(a)
3. O(n^logb(a)) if d < logb(a)

In my case:

log2(4) = 2  --> d < log2(4)

T(n) = O(n^logb(a))
     = O(n^2)

Is this correct?

edit:

I have made an different approach now, resulting in the same as before though, and following my professors instruction.

T(n) = a*T(n/b) + f(n)

T(n) = 4 T(n/2) + n*log(n)

         1. Ө(n^(logba))       , if --> f(n) є O(n^(logba-ε)),
T(n) = { 2. Ө(n^(logba) log2n) , if --> f(n) є Ө(n^(logba))
         3. Ө(f(n))            , if --> f(n) є Ω(n^(logba+ε))

First I look at the 2nd case

f(n)  = n*log(n)
logb^a = log2^4 = 2
n^log24 = n^2

The second case does not apply because:

n*log(n) ∉ Θ(n^logba) —> the runtime of f(n) is smaller, because n*log(n) < n^2

Look at the first case if the runtime of f(n) is smaller than n^2

1. Ө(n^(logba)) , if --> f(n) є O(n^(logba-ε))

O(n^(logba-ε)) = O(n^(log24-ε))= O(n^2-ε)
n*log(n) ∈ O(n^(log24-ε)) --> works

f(n) has O(n^2-ε) as upper limit for worst case scenario,

case of Master—Theorems applies:

T(n) = Θ(n^log24) = Θ(n^2)
T(n) = Θ(n^2)


问:
Convert negative index to positive index in an array (Trinomial Triangle)
I am trying to find trinomial coefficients and I want to avoid using negative index in my array. There will be instances whereby i or j will become negative and will return array out of bounds error. Is there anyway I can mirror the array contained in the negative indexes to a positive index?

Here’s the recursive formula: Recursion Formula

I recognize that T(0, -1) = T(0, 1) but how do I implement it?

example:

```<code>row 0: T(0, 0) = 1 , T(0, 1) = 0 ...

row 1: T(1, 0) = T(0, -1) + T(0, 0) + T(0, 1) , T(2, 0) ...
</code>```

The trinomial coefficient T(n,k) is the coefficient of x^(n+k) in the expansion of (1+x+x^2)^n.

Trinomial triangle (middle index is 0, negative on the left of 0, positive on the right of 0):

Note: The code below iterates through the array from middle index 0 to the right.

public class ClassNameHere {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int k = Integer.parseInt(args[1]);
        long[][] DP = new long[n + 1][k + 1];
        DP[0][0] = 1;
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= Math.min(i, k); j++) {
                if (i == j || ((j == 0) && i < 2)) DP[i][j] = 1;
                else if (j < -i) {
                    DP[i][j] = 0;
                } else DP[i][j] = DP[i - 1][j];
            }
        }
        System.out.println(DP[n][k]);
    }
}
```

Now I am able to get the terms from T(0, 0) to T(1, 0) with my code but unable to continue past T(2, 0) onwards by adding T(1,0) + T(1, 1) + T(1, 2). When I tried to implement DP[i][j] = DP[i - 1][j - 1] + DP[i - 1][j] + DP[i - 1][j + 1], it returns ArrayIndexOutOfBoundsException again.. I think that something is wrong with the implementation of the above statement ^. Any suggestions on how to go on with this?

答:
I have found the cause.

It can be done by initializing the correct length in the 2D array.

```<code>long[][] tri = new long[n + 1][k + n + 1];
</code>```

and using Math.abs() to handle instances where j index will flow to negative indices.

```<code>tri[i][j] = tri[i - 1][Math.abs(j - 1)] + tri[i - 1][j] + tri[i - 1][j + 1];
</code>```

Body:
I am trying to find trinomial coefficients and I want to avoid using negative index in my array. There will be instances whereby i or j will become negative and will return array out of bounds error. Is there anyway I can mirror the array contained in the negative indexes to a positive index?

Here’s the recursive formula: Recursion Formula

I recognize that T(0, -1) = T(0, 1) but how do I implement it?

example:

row 0: T(0, 0) = 1 , T(0, 1) = 0 ...

row 1: T(1, 0) = T(0, -1) + T(0, 0) + T(0, 1) , T(2, 0) ...

The trinomial coefficient T(n,k) is the coefficient of x^(n+k) in the expansion of (1+x+x^2)^n.

Trinomial triangle (middle index is 0, negative on the left of 0, positive on the right of 0):

Note: The code below iterates through the array from middle index 0 to the right.

public class ClassNameHere {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int k = Integer.parseInt(args[1]);
        long[][] DP = new long[n + 1][k + 1];
        DP[0][0] = 1;
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= Math.min(i, k); j++) {
                if (i == j || ((j == 0) && i < 2)) DP[i][j] = 1;
                else if (j < -i) {
                    DP[i][j] = 0;
                } else DP[i][j] = DP[i - 1][j];
            }
        }
        System.out.println(DP[n][k]);
    }
}

Now I am able to get the terms from T(0, 0) to T(1, 0) with my code but unable to continue past T(2, 0) onwards by adding T(1,0) + T(1, 1) + T(1, 2). When I tried to implement DP[i][j] = DP[i - 1][j - 1] + DP[i - 1][j] + DP[i - 1][j + 1], it returns ArrayIndexOutOfBoundsException again.. I think that something is wrong with the implementation of the above statement ^. Any suggestions on how to go on with this?

Body:
I have found the cause.

It can be done by initializing the correct length in the 2D array.

long[][] tri = new long[n + 1][k + n + 1];

and using Math.abs() to handle instances where j index will flow to negative indices.

tri[i][j] = tri[i - 1][Math.abs(j - 1)] + tri[i - 1][j] + tri[i - 1][j + 1];


问:
Automatically Start Microsoft Reporting Services after a Restart
I have a VM running on a server, and, among other things, I have Microsoft Reporting Services running on it, as is used by one of my websites.

The thing is, there are times when the server restarts, and when it does, MRS does not automatically start running again; I have to manually start the service. Is there a way to configure MRS to start automatically after restarting the machine?

答: Go to Services in Control Panel, and find Microsoft Reporting Services.  Right click it, and go to Properties.  In the dialog that will appear, you'll see Startup Type.  Ensure that it is set to Automatic.


问:
Onclick show div overlapping/hiding others
I'm trying to achieve 3 clickable
 that expand and hide/overlap others on click, while showing what's inside each clicked
. I only have JQuery as of right now.

My initial question is, what should I use? (Flexbox? CSS animation? React?)
Is it possible in vanilla html+css+js stack without having a bonky transition ?
I made an image to illustrate what I'm trying to say:

答:
It is possible just by using pure Javascript, all you need to do is add a click event to each div, and when one is clicked you issue yourDivName.setAttribute("style", "display: block"); and issue yourDivName.setAttribute("style", "display: none"); to the other two. Then just repeat this process for each one. Obviously enclosing each one in a function yourFunctionName(){
    //Enter logic here
}

Your process should be first getting each div and putting it in a variable, then doing the above code according to what you wish to do to the div. I hope this helps let me know if you'd like me to do the Javascript for you :)


问:
How to access sub-collections across multiple documents within a single collection in firestore?
I have a database structure as follows (simplified for purposes of this question):

```<code>Collection: registrations
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_AA = {type: "Q1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "Q2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_AC = {type: "Q1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "Q1", address: {pincode: "333333", city:"Paris"}
            ...
</code>```

What I want to do:
Obtain a list of all the orders across all users within the collection "registrations".
(please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection)

In more words...
Query FireStore to find all the available documents (users) within the collection "registrations", and for each of these documents (users) find all the orders in their sub-collection named "orders".

How can I do this in the shortest steps (fewest queries)?

Also, is it essential for me to add a "dummy" field within each "user" document? I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields. Even after adding a dummy field, I was unable to get it to work.

My most recent effort has been:

```<code>let ordersList = [];
await firestore()
    .collection("registrations")
    .get()
    .then((collectionRef) => {
        collectionRef.forEach((userDoc) => {
            console.log("==", userDoc.id);
            if(userDoc.id.startsWith("user")) {
                userDoc.collections("orders")
                    .get()
                    .then((ordersSnapshot) => {
                        ordersSnapshot.forEach((orderDoc) => {
                            ordersList.push(orderDoc.data());
                        });
                    });
            }
        });
    })
    .catch(error => {
        console.log("Error in retrieving data!");
        console.log('Error: ', error);
    })
</code>```

I get the error:

Error:  [TypeError: userDoc.collections is not a function. (In
  'userDoc.collections("orders")', 'userDoc.collections' is undefined)]

答: You should definitely use the collectionGroup() method as described there.

Body:
I have a database structure as follows (simplified for purposes of this question):

Collection: registrations
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_AA = {type: "Q1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "Q2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_AC = {type: "Q1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "Q1", address: {pincode: "333333", city:"Paris"}
            ...

What I want to do:
Obtain a list of all the orders across all users within the collection "registrations".
(please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection)

In more words...
Query FireStore to find all the available documents (users) within the collection "registrations", and for each of these documents (users) find all the orders in their sub-collection named "orders".

How can I do this in the shortest steps (fewest queries)?

Also, is it essential for me to add a "dummy" field within each "user" document? I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields. Even after adding a dummy field, I was unable to get it to work.

My most recent effort has been:

let ordersList = [];
await firestore()
    .collection("registrations")
    .get()
    .then((collectionRef) => {
        collectionRef.forEach((userDoc) => {
            console.log("==", userDoc.id);
            if(userDoc.id.startsWith("user")) {
                userDoc.collections("orders")
                    .get()
                    .then((ordersSnapshot) => {
                        ordersSnapshot.forEach((orderDoc) => {
                            ordersList.push(orderDoc.data());
                        });
                    });
            }
        });
    })
    .catch(error => {
        console.log("Error in retrieving data!");
        console.log('Error: ', error);
    })

I get the error:

Error:  [TypeError: userDoc.collections is not a function. (In
  'userDoc.collections("orders")', 'userDoc.collections' is undefined)]


问:
UICollectionViewCell zero spacing not working
I did create a custom calendar based on UICollectionView.

One UICollectionViewCell - one date in the calendar. I want to delete spacing between cells.
CollectionView layout settings -

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.width / 7), height: collectionView.frame.width / 7)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}
</code>```

In different screen sizes, unless iPhone X, we will see the spacing between cells.

How to fix it?

答:
This is occurring because of the rounding-off of decimal places when your providing collectionView.frame.width / 7 just as matt has said in his answer. Seems you are trying to avoid this because you don't want users to see that bit of gap between the cells. Mostly you would only see this on a simulator an not on a real device due to the pixel density. You can overcome this fault either by replacing the UICollectionViewFlowLayout with a UICollectionViewCompositionalLayout which is available only from iOS 12. A simple fix would be to create a custom background view for the cell that extends the UICollectionViewCell by just 1 pixel. Here is an example of how I tried to achieve this:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    cell.backgroundColor = .purple
    let view = UIView()
    view.backgroundColor = .brown
    cell.addSubview(view) // Comment this line and you can see the gap
    view.frame = cell.bounds
    view.frame.size = CGSize(width: view.frame.size.width + 1, height: view.frame.size.height + 1)
    return cell
}
```

This was a nice little hack I found a while back. Hope this helps you too.

Body:
I did create a custom calendar based on UICollectionView.

One UICollectionViewCell - one date in the calendar. I want to delete spacing between cells.
CollectionView layout settings -

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.width / 7), height: collectionView.frame.width / 7)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

In different screen sizes, unless iPhone X, we will see the spacing between cells.

How to fix it?

Body:
This is occurring because of the rounding-off of decimal places when your providing collectionView.frame.width / 7 just as matt has said in his answer. Seems you are trying to avoid this because you don't want users to see that bit of gap between the cells. Mostly you would only see this on a simulator an not on a real device due to the pixel density. You can overcome this fault either by replacing the UICollectionViewFlowLayout with a UICollectionViewCompositionalLayout which is available only from iOS 12. A simple fix would be to create a custom background view for the cell that extends the UICollectionViewCell by just 1 pixel. Here is an example of how I tried to achieve this:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    cell.backgroundColor = .purple
    let view = UIView()
    view.backgroundColor = .brown
    cell.addSubview(view) // Comment this line and you can see the gap
    view.frame = cell.bounds
    view.frame.size = CGSize(width: view.frame.size.width + 1, height: view.frame.size.height + 1)
    return cell
}

This was a nice little hack I found a while back. Hope this helps you too.


问:
Getting a "head: error reading 'path': is a directory" error
I'm trying to get the first line of a file, but for some reason, the head command seems to be called on the parent directory, which obviously won't work.

I have a variable productPath which contains the path to the file that I want to analyze. From executing an echo on that variable, I determined that the variable does indeed contain the correct path to the file I want to read. However, when I execute the following:

```<code>line = $(head -n 1 $productPath)
</code>```

I get the following error:

```<code>head: error reading 'src/test/resources/features/Env_First': Is a directory
</code>```

The file is actually inside the Env_First directory. I tried executing head on a few other files, and all of them seem to be doing the same thing (always trying to read the parent directory, instead of the actual file). What would be the correct usage of head to get the first line of the file?

EDIT:
As per @bhristov's request, here is a minimal reproducible snippet. Here, I'm reading a file called readableFile.feature in the directory src/test/environments.

```<code>for productPath in $(find src/test/environments -maxdepth 1)
do
      echo "$productPath" #this outputs src/test/environments/readableFile.feature
      line=$(head -n 1 $productPath) #this produces the error mentioned earlier
done
</code>```

答:
The find command will return the directory as the first result, which is why the error.

I suggest replacing that find with this:

```<code>for productPath in src/test/environments/*
do
      echo "$productPath"
      line=$(head -n 1 $productPath)
done
</code>```

Another option is to add a check before doing whatever you want to do with if to see if productPath is a file.

Body:
I'm trying to get the first line of a file, but for some reason, the head command seems to be called on the parent directory, which obviously won't work.

I have a variable productPath which contains the path to the file that I want to analyze. From executing an echo on that variable, I determined that the variable does indeed contain the correct path to the file I want to read. However, when I execute the following:

line = $(head -n 1 $productPath)

I get the following error:

head: error reading 'src/test/resources/features/Env_First': Is a directory

The file is actually inside the Env_First directory. I tried executing head on a few other files, and all of them seem to be doing the same thing (always trying to read the parent directory, instead of the actual file). What would be the correct usage of head to get the first line of the file?

EDIT:
As per @bhristov's request, here is a minimal reproducible snippet. Here, I'm reading a file called readableFile.feature in the directory src/test/environments.

for productPath in $(find src/test/environments -maxdepth 1)
do
      echo "$productPath" #this outputs src/test/environments/readableFile.feature
      line=$(head -n 1 $productPath) #this produces the error mentioned earlier
done

Body:
The find command will return the directory as the first result, which is why the error.

I suggest replacing that find with this:

for productPath in src/test/environments/*
do
      echo "$productPath"
      line=$(head -n 1 $productPath)
done

Another option is to add a check before doing whatever you want to do with if to see if productPath is a file.


问:
How to count expiry date when we enter month in odoo 13
Requirement is when we enter purchase Date (like 06/01/2020) and month (like 14).

It will count expire date from purchase date, so the warranty_expires_on Date (like 07/31/2021).

I have added field in version 13 which is

```<code>purchase_date=fields.Date(string="Purchase Date")

warranty_period=fields.Integer(string="Warranty Period")

warranty_expires_on=fields.Date(string="Warranty Expires on",compute="_get_date",store=True)

unit_of_time = fields.Selection([

        (YEARLY, 'Years'),
        (MONTHLY, 'Months'),
        (WEEKLY, 'Weeks')])
count = fields.Integer(string="Number of ranges to generate", required=True,default=1)

@api.depends('purchase_date','warranty_period')

def _get_date(self):
    for rec in self:
        vals = rrule(freq=rec.unit_of_time,
                    interval=rec.warranty_period,
                    dtstart=rec.purchase_date,
                    count=rec.count+1)
        vals = list(vals)
        for idx, dt_start in enumerate(vals[:-1]):
            purchase_date = dt_start.date()
            warranty_expires_on = vals[idx+1].date() - relativedelta(days=1)
            rec.update({'warranty_expires_on':warranty_expires_on})
</code>```

from xml side...

```<code>            <xpath expr="//field[@name='warranty_period']" position="after">
                <field name="unit_of_time"/>
            </xpath>

            <xpath expr="//field[@name='unit_of_time']" position="after">
                <field name="count" invisible='1'/>
            </xpath>
</code>```

But i am facing below error.

```<code>Odoo Server Error

Traceback (most recent call last):

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 619, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 309, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])

  File "/home/yash/Workspace/odoo_13/odoo/tools/pycompat.py", line 14, in reraise
    raise value

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 664, in dispatch
    result = self._call_function(**self.params)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 345, in _call_function
    return checked_call(self.db, *args, **kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/service/model.py", line 93, in wrapper
    return f(dbname, *args, **kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 338, in checked_call
    result = self.endpoint(*a, **kw)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 909, in __call__
    return self.method(*args, **kw)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 510, in response_wrap
    response = f(*args, **kw)

  File "/home/yash/Workspace/odoo_13/addons/web/controllers/main.py", line 1319, in call_kw
    return self._call_kw(model, method, args, kwargs)

  File "/home/yash/Workspace/odoo_13/addons/web/controllers/main.py", line 1311, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/api.py", line 395, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/api.py", line 382, in _call_kw_multi
    result = method(recs, *args, **kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 6062, in onchange
    for name in nametree

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 6063, in <listcomp>
    if name not in done and snapshot0.has_changed(name)

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 5930, in has_changed
    return self[name] != record[name]

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 5589, in __getitem__
    return self._fields[key].__get__(self, type(self))

  File "/home/yash/Workspace/odoo_13/odoo/fields.py", line 973, in __get__
    self.compute_value(recs)

  File "/home/yash/Workspace/odoo_13/odoo/fields.py", line 1087, in compute_value
    records._compute_field_value(self)

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 3905, in _compute_field_value
    getattr(self, field.compute)()

  File "/home/yash/Workspace/project13/equipment_allocations_app/models/maintenance.py", line 68, in _get_date
    count=rec.count+1)

  File "/usr/local/lib/python3.6/dist-packages/dateutil/rrule.py", line 619, in __init__

    if freq < HOURLY:

TypeError: '<' not supported between instances of 'str' and 'int'
</code>```

答:
rrule freq argument must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY.

```<code>(YEARLY,
 MONTHLY,
 WEEKLY,
 DAILY,
 HOURLY,
 MINUTELY,
 SECONDLY) = list(range(7))
</code>```

freq must  be in list(range(7))

```<code>>>> from dateutil.rrule import MONTHLY
>>> MONTHLY
1
</code>```

Odoo will raise an error if you try to use values in selection of type different from str,

```<code>AssertionError: Field purchase.order.unit_of_time with non-str value in selection - - -
</code>```

Get the integer freq using the selection value

Example

```<code>from dateutil.rrule import rrule, YEARLY, MONTHLY, WEEKLY

unit_of_time = fields.Selection([

    (str(YEARLY), 'Years'),
    (str(MONTHLY), 'Months'),
    (str(WEEKLY), 'Weeks')])
</code>```

Convert unit_of_time to int when calling rrule

```<code>freq=int(rec.unit_of_time)
</code>```

Body:
Requirement is when we enter purchase Date (like 06/01/2020) and month (like 14).

It will count expire date from purchase date, so the warranty_expires_on Date (like 07/31/2021).

I have added field in version 13 which is

purchase_date=fields.Date(string="Purchase Date")

warranty_period=fields.Integer(string="Warranty Period")

warranty_expires_on=fields.Date(string="Warranty Expires on",compute="_get_date",store=True)

unit_of_time = fields.Selection([

        (YEARLY, 'Years'),
        (MONTHLY, 'Months'),
        (WEEKLY, 'Weeks')])
count = fields.Integer(string="Number of ranges to generate", required=True,default=1)

@api.depends('purchase_date','warranty_period')

def _get_date(self):
    for rec in self:
        vals = rrule(freq=rec.unit_of_time,
                    interval=rec.warranty_period,
                    dtstart=rec.purchase_date,
                    count=rec.count+1)
        vals = list(vals)
        for idx, dt_start in enumerate(vals[:-1]):
            purchase_date = dt_start.date()
            warranty_expires_on = vals[idx+1].date() - relativedelta(days=1)
            rec.update({'warranty_expires_on':warranty_expires_on})

from xml side...

            <xpath expr="//field[@name='warranty_period']" position="after">
                <field name="unit_of_time"/>
            </xpath>

            <xpath expr="//field[@name='unit_of_time']" position="after">
                <field name="count" invisible='1'/>
            </xpath>

But i am facing below error.

Odoo Server Error

Traceback (most recent call last):

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 619, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 309, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])

  File "/home/yash/Workspace/odoo_13/odoo/tools/pycompat.py", line 14, in reraise
    raise value

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 664, in dispatch
    result = self._call_function(**self.params)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 345, in _call_function
    return checked_call(self.db, *args, **kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/service/model.py", line 93, in wrapper
    return f(dbname, *args, **kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 338, in checked_call
    result = self.endpoint(*a, **kw)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 909, in __call__
    return self.method(*args, **kw)

  File "/home/yash/Workspace/odoo_13/odoo/http.py", line 510, in response_wrap
    response = f(*args, **kw)

  File "/home/yash/Workspace/odoo_13/addons/web/controllers/main.py", line 1319, in call_kw
    return self._call_kw(model, method, args, kwargs)

  File "/home/yash/Workspace/odoo_13/addons/web/controllers/main.py", line 1311, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/api.py", line 395, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/api.py", line 382, in _call_kw_multi
    result = method(recs, *args, **kwargs)

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 6062, in onchange
    for name in nametree

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 6063, in <listcomp>
    if name not in done and snapshot0.has_changed(name)

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 5930, in has_changed
    return self[name] != record[name]

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 5589, in __getitem__
    return self._fields[key].__get__(self, type(self))

  File "/home/yash/Workspace/odoo_13/odoo/fields.py", line 973, in __get__
    self.compute_value(recs)

  File "/home/yash/Workspace/odoo_13/odoo/fields.py", line 1087, in compute_value
    records._compute_field_value(self)

  File "/home/yash/Workspace/odoo_13/odoo/models.py", line 3905, in _compute_field_value
    getattr(self, field.compute)()

  File "/home/yash/Workspace/project13/equipment_allocations_app/models/maintenance.py", line 68, in _get_date
    count=rec.count+1)

  File "/usr/local/lib/python3.6/dist-packages/dateutil/rrule.py", line 619, in __init__

    if freq < HOURLY:

TypeError: '<' not supported between instances of 'str' and 'int'

Body:
rrule freq argument must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY.

(YEARLY,
 MONTHLY,
 WEEKLY,
 DAILY,
 HOURLY,
 MINUTELY,
 SECONDLY) = list(range(7))

freq must  be in list(range(7))

>>> from dateutil.rrule import MONTHLY
>>> MONTHLY
1

Odoo will raise an error if you try to use values in selection of type different from str,

AssertionError: Field purchase.order.unit_of_time with non-str value in selection - - -

Get the integer freq using the selection value

Example

from dateutil.rrule import rrule, YEARLY, MONTHLY, WEEKLY

unit_of_time = fields.Selection([

    (str(YEARLY), 'Years'),
    (str(MONTHLY), 'Months'),
    (str(WEEKLY), 'Weeks')])

Convert unit_of_time to int when calling rrule

freq=int(rec.unit_of_time)


问:
why is my call to a mock api not parsing the data as expected?
I'm trying to debug and find a reason why this isn't working and how to get it to work.

MainActivity.kt

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

        ...

    fetchJson()
}
</code>```

so this just calls my function fetchJson

this is the function:

```<code>fun fetchJson() {
    println("Attempting to Fetch JSON")

    val url = "https://www.mocky.io/v2/5ed340ab340000650001f28c"

    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: okhttp3.Callback {
        override fun onFailure(call: okhttp3.Call, e: IOException) {
            println("Failed to execute request")
        }

        override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
            val body = response?.body?.string()
            println(body)
            println("success")
            val gson = GsonBuilder().create()

            val homeFeed = gson.fromJson(body, note::class.java)

           /* runOnUiThread {
                recycler_view.adapter = MainAdapter(homeFeed)
            }*/
        }

    })
</code>```

the idea behind this is that you take JSON data and fit it into adapter classes and display them in a card view.

my problem isn't with the adapters or the card view but the rest API. It doesn't want to work with my mock rest API, but it will work with other rest API's. I'm not sure why though?

I've tried to add a network security exception, I've had to remove my adapter class just to get it to say success. I still can't find the JSON body in the console when I get the onresponse call, and because I don't get errors in the debug console I don't know what is going on.

I have no clue what isn't working here. Is it GSON converters?, the rest API, my code? is a problem with my emulator?...etc?

the classes the body should print to the console:

```<code>class note(val noteis: List<Mlist>)

class Mlist(val text1: String, val text2: String, val text3: String)
</code>```

答:
There are two problems I can see:

No stacktrace in onFailure method. Let's add it:

```<code>println("Failed to execute request, $e")
</code>```

Running this now returns
PKIX path building failed: (...) unable to find valid certification path to requested target
This fails because Java does not trust the certificate from www.mocky.io. You can add it or ignore it by changing the configuration of OkHttpClient, but for now let's simply change the url from https:// to http://.

With that change you should be getting response body printed out, if not your error is beyond provided code.

Response class does not match the json data.

JSON data from the link looks like this:

```<code>{
    "Mlist": {
        "text1": "text1a",
        "text2": "text2a",
        "text3": "text3a"
    }
}
</code>```

So it is not a list of Mlist objects, but a single object in a field named Mlist.
To match this we can:

a) change the name of the field in the note class

```<code>class note(val Mlist: Mlist)
</code>```

b) use @SerializedName annotation

```<code>    @SerializedName("Mlist")
    val notes: Mlist
</code>```

Btw. you can change note and Mlist to data class to be able to see its content with print* methods.

Body:
I'm trying to debug and find a reason why this isn't working and how to get it to work.

MainActivity.kt

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

        ...

    fetchJson()
}

so this just calls my function fetchJson

this is the function:

fun fetchJson() {
    println("Attempting to Fetch JSON")

    val url = "https://www.mocky.io/v2/5ed340ab340000650001f28c"

    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: okhttp3.Callback {
        override fun onFailure(call: okhttp3.Call, e: IOException) {
            println("Failed to execute request")
        }

        override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
            val body = response?.body?.string()
            println(body)
            println("success")
            val gson = GsonBuilder().create()

            val homeFeed = gson.fromJson(body, note::class.java)

           /* runOnUiThread {
                recycler_view.adapter = MainAdapter(homeFeed)
            }*/
        }

    })

the idea behind this is that you take JSON data and fit it into adapter classes and display them in a card view.

my problem isn't with the adapters or the card view but the rest API. It doesn't want to work with my mock rest API, but it will work with other rest API's. I'm not sure why though?

I've tried to add a network security exception, I've had to remove my adapter class just to get it to say success. I still can't find the JSON body in the console when I get the onresponse call, and because I don't get errors in the debug console I don't know what is going on.

I have no clue what isn't working here. Is it GSON converters?, the rest API, my code? is a problem with my emulator?...etc?

the classes the body should print to the console:

class note(val noteis: List<Mlist>)

class Mlist(val text1: String, val text2: String, val text3: String)

Body:
There are two problems I can see:

No stacktrace in onFailure method. Let's add it:

println("Failed to execute request, $e")

Running this now returns
PKIX path building failed: (...) unable to find valid certification path to requested target
This fails because Java does not trust the certificate from www.mocky.io. You can add it or ignore it by changing the configuration of OkHttpClient, but for now let's simply change the url from https:// to http://.

With that change you should be getting response body printed out, if not your error is beyond provided code.

Response class does not match the json data.

JSON data from the link looks like this:

{
    "Mlist": {
        "text1": "text1a",
        "text2": "text2a",
        "text3": "text3a"
    }
}

So it is not a list of Mlist objects, but a single object in a field named Mlist.
To match this we can:

a) change the name of the field in the note class

class note(val Mlist: Mlist)

b) use @SerializedName annotation

    @SerializedName("Mlist")
    val notes: Mlist

Btw. you can change note and Mlist to data class to be able to see its content with print* methods.


问:
SQL - INSERT and catch the id auto-increment value
What is the best way to get the auto-id value in the same SQL with a SELECT?

A forum said adding this "; has Return Scope_Identity()"

in the end of the SQL works in ASP.

Is there a corresponding way in PHP?

答:
In php: mysql_insert_id()
http://us3.php.net/mysql_insert_id

or

If you wanted to genterate the number from your mySql select query, you could use this
EDIT:

```<code>SELECT LAST_INSERT_ID(`1`) + 1 FROM table
</code>```

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milan Babuškov

Body:
In php: mysql_insert_id()
http://us3.php.net/mysql_insert_id

or

If you wanted to genterate the number from your mySql select query, you could use this
EDIT:

SELECT LAST_INSERT_ID(`1`) + 1 FROM table

OwnerDisplayName: superUntitled

LastEditorDisplayName: superUntitled


问:
Is it safe to store Tweet IDs as BIGINTs?
Moving forwards, am I going to have a problem at some point if I store Tweet IDs from the Twitter API as an unsigned BIGINT in MySQL?

Am I better off using a CHAR(25) or something? The Tweet IDs are only going to get bigger and bigger over time.

答:
an unsigned bigint can hold a value in the range of 0 to 18446744073709551615 (a really big number)

if there are say approx. 52 billion tweets per year then:

```<code>18446744073709551615 / 52000000000 = 354745078 years worth of tweets
</code>```

so I think you'd be safe :P

Body:
an unsigned bigint can hold a value in the range of 0 to 18446744073709551615 (a really big number)

if there are say approx. 52 billion tweets per year then:

18446744073709551615 / 52000000000 = 354745078 years worth of tweets

so I think you'd be safe :P