问:
Zappa: No module named '_cffi_backend'
I recently uploaded an Django application with the use off Zappa, which was running perfectly fine.

Now, I wanted to update this application, and It suddenly gives me this error:
(The changes I made wasn't really that much, removed a blank=True in my models.py)

```<code>ModuleNotFoundError: No module named '_cffi_backend'
Traceback (most recent call last):
  File "/var/task/handler.py", line 657, in lambda_handler
    return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 251, in lambda_handler
    handler = cls()
  File "/var/task/handler.py", line 160, in __init__
    wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS)
  File "/var/task/zappa/ext/django_zappa.py", line 21, in get_django_wsgi
    return get_wsgi_application()
  File "/tmp/mysite/django/core/wsgi.py", line 12, in get_wsgi_application
    django.setup(set_prefix=False)
  File "/tmp/mysite/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/tmp/mysite/django/apps/registry.py", line 122, in populate
    app_config.ready()
  File "/tmp/mysite/core/apps.py", line 8, in ready
    from core import signals
  File "/tmp/mysite/core/signals.py", line 1, in <module>
    import cairosvg
  File "/tmp/mysite/cairosvg/__init__.py", line 26, in <module>
    from . import surface  # noqa isort:skip
  File "/tmp/mysite/cairosvg/surface.py", line 9, in <module>
    import cairocffi as cairo
  File "/tmp/mysite/cairocffi/__init__.py", line 17, in <module>
    from ._generated.ffi import ffi
  File "/tmp/mysite/cairocffi/_generated/ffi.py", line 2, in <module>
    import _cffi_backend
</code>```

I use a package CairoSVG and when disabling this, my application works again.
The weird thing is that I was using this package in previous version aswell without any problems.

when updating with zappa update dev it shows me this:

```<code>Calling update for stage dev..
Downloading and installing dependencies..
 - reportlab==3.6.6: Using locally cached manylinux wheel
 - pyproj==3.3.0: Using locally cached manylinux wheel
 - psycopg2-binary==2.9.3: Using locally cached manylinux wheel
'releases'
Packaging project as gzipped tarball.
</code>```

I've noticed that on previous updates, there was a 4th dependency called "cffi" but is gone now.

I have no idea how it's gone and from where those dependenties come from because I have much more in my requirements.txt

答:
Don't exactly know what went wrong but I got it fixed by:

completly removing my virtual environment

creating a new one.

installing packages with pip install -r requirements.txt --no-cache-dir

the --no-cache-dir was really important adding.

Title: Zappa: No module named '_cffi_backend'

Body:
I recently uploaded an Django application with the use off Zappa, which was running perfectly fine.

Now, I wanted to update this application, and It suddenly gives me this error:
(The changes I made wasn't really that much, removed a blank=True in my models.py)

ModuleNotFoundError: No module named '_cffi_backend'
Traceback (most recent call last):
  File "/var/task/handler.py", line 657, in lambda_handler
    return LambdaHandler.lambda_handler(event, context)
  File "/var/task/handler.py", line 251, in lambda_handler
    handler = cls()
  File "/var/task/handler.py", line 160, in __init__
    wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS)
  File "/var/task/zappa/ext/django_zappa.py", line 21, in get_django_wsgi
    return get_wsgi_application()
  File "/tmp/mysite/django/core/wsgi.py", line 12, in get_wsgi_application
    django.setup(set_prefix=False)
  File "/tmp/mysite/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/tmp/mysite/django/apps/registry.py", line 122, in populate
    app_config.ready()
  File "/tmp/mysite/core/apps.py", line 8, in ready
    from core import signals
  File "/tmp/mysite/core/signals.py", line 1, in <module>
    import cairosvg
  File "/tmp/mysite/cairosvg/__init__.py", line 26, in <module>
    from . import surface  # noqa isort:skip
  File "/tmp/mysite/cairosvg/surface.py", line 9, in <module>
    import cairocffi as cairo
  File "/tmp/mysite/cairocffi/__init__.py", line 17, in <module>
    from ._generated.ffi import ffi
  File "/tmp/mysite/cairocffi/_generated/ffi.py", line 2, in <module>
    import _cffi_backend

I use a package CairoSVG and when disabling this, my application works again.
The weird thing is that I was using this package in previous version aswell without any problems.

when updating with zappa update dev it shows me this:

Calling update for stage dev..
Downloading and installing dependencies..
 - reportlab==3.6.6: Using locally cached manylinux wheel
 - pyproj==3.3.0: Using locally cached manylinux wheel
 - psycopg2-binary==2.9.3: Using locally cached manylinux wheel
'releases'
Packaging project as gzipped tarball.

I've noticed that on previous updates, there was a 4th dependency called "cffi" but is gone now.

I have no idea how it's gone and from where those dependenties come from because I have much more in my requirements.txt


来源: stackexchange

问:
Pyjs not working with Tkinter
I am trying to use pyjamas (http://pyjs.org/) to compile some python that I wrote into javascript. My python program works the way I want it to.  I installed via the installation guide on the website.

```<code>pyjsbuild -I --library_dir=/usr/lib/python2.7/lib-tk/ deployme.py
</code>```

When I attempt to open the html that is generated I get (displayed in firefox):

deployme ImportError: No module named Tkinter., Tkinter. in context null

I did a lot of searching and it appears that Tkinter and pyjs don't get along.
http://mail.python.org/pipermail/tutor/2012-May/089463.html

1 - I just wanted to see if anyone has had any success with using pyjs with Tkinter.  I have only provided 1 link of evidence that it might not and can't understand what is so special about Tkinter that I can't just tell pyjs where the additional libraries are and have it include them.

2 - Would it be easier for me to just learn some javascript and code my user interface (that I had made with Tkinter) in js?

3 - Is there another way I can accomplish running my python program on a website?

答: You may not use Tkinter in Pyjamas. Better use Brython. But it doesn't as well</p>

ContentLicense: CC BY-SA 3.0

Title: Pyjs not working with Tkinter

Body:
I am trying to use pyjamas (http://pyjs.org/) to compile some python that I wrote into javascript. My python program works the way I want it to.  I installed via the installation guide on the website.

pyjsbuild -I --library_dir=/usr/lib/python2.7/lib-tk/ deployme.py

When I attempt to open the html that is generated I get (displayed in firefox):

deployme ImportError: No module named Tkinter., Tkinter. in context null

I did a lot of searching and it appears that Tkinter and pyjs don't get along.
http://mail.python.org/pipermail/tutor/2012-May/089463.html

1 - I just wanted to see if anyone has had any success with using pyjs with Tkinter.  I have only provided 1 link of evidence that it might not and can't understand what is so special about Tkinter that I can't just tell pyjs where the additional libraries are and have it include them.

2 - Would it be easier for me to just learn some javascript and code my user interface (that I had made with Tkinter) in js?

3 - Is there another way I can accomplish running my python program on a website?

ContentLicense: CC BY-SA 4.0


问:
Typescript react-redux configuring store error
This is my code:

```<code>interface IState {
  userData: {
    name: string
    age: number
  }
  // companyData: {},
  // websiteData: {}
}
export const initialState: IState = {
  userData: {
    name: "Mark",
    age: 30
  }
  // companyData: {},
  // websiteData: {},
}

const mainReducer = combineReducers({
  userData: userReducer
  // companyData: companyDataReducer,
  // websiteData: websiteDataReducer,
});

const configureStore = () =>
  createStore(
    mainReducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunk))
  );

export default configureStore;

</code>```

it generates this error which I do not understand:

Argument of type 'IState' is not assignable to parameter of type '{ userData?: { userData: any; } | undefined; }'.
Types of property 'userData' are incompatible.
Property 'userData' is missing in type '{ name: string; age: number; }' but required in type '{ userData: any; }'.

答: I had issues with my reducers, I was returning whole state instead of a slice of the state and that was messing everything up.</p>

Body:
This is my code:

interface IState {
  userData: {
    name: string
    age: number
  }
  // companyData: {},
  // websiteData: {}
}
export const initialState: IState = {
  userData: {
    name: "Mark",
    age: 30
  }
  // companyData: {},
  // websiteData: {},
}

const mainReducer = combineReducers({
  userData: userReducer
  // companyData: companyDataReducer,
  // websiteData: websiteDataReducer,
});

const configureStore = () =>
  createStore(
    mainReducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunk))
  );

export default configureStore;

it generates this error which I do not understand:

Argument of type 'IState' is not assignable to parameter of type '{ userData?: { userData: any; } | undefined; }'.
Types of property 'userData' are incompatible.
Property 'userData' is missing in type '{ name: string; age: number; }' but required in type '{ userData: any; }'.


问:
How Create RSA Encryption key pairs using python that is comaptible with C# or vice versa?
Actually, i have started work on creating a web service in Python and C#(.NET 3.5 framework) as client. All requests are on POST so i decided to send my data in encrypted form using public key on C# side and decrypt data in Python, Again from python Encrypt data using Private Key & decrypt using public key in C# side..

But the problem here is that keys i hav generated in C# side that is in ... xml format that is not support in python.
I have also tried from python to generate key pair, that are not working C# side..

I have searched on web, found some solutions but nothing works...

Can Any tell me how to generate key pairs that work on both side...?
Also tell me the format of key generated on both sides..
If you have any related info or KB regarding RSA encryption please share here with me..

答:
Please take a look at PyOpenSSL and may be it will be better to use standard HTTPS for your service. You can use self-signed SSL certificates with PyCurl and urllib.urlopen and other python web clients.

Urllib and validation of server certificate
one of the examples.


问:
Add permissions base on roles of group in keycloak
I first set my application base on Auth0, with roles and permissions setup. Result user are linked with x roles, and Auth0 inject to the token claim an array of linked permissions. Now my app need to become also compatible to use KeyCloak.

How to inject into the token the permissions array, like with Auth0?

答:
To match same beaver of Auth0, on keycloak all the auth0-roles are set as group. And all auth0-permission as roles.

Now to allow to inject into the token the related roles of groups linked with a user, I created a Script Mapper in the client like this:

```<code>var ArrayList = Java.type("java.util.ArrayList");
var permissions = new ArrayList();
user.getGroups().forEach(function(groupModel) {
    groupModel.getRoleMappings().forEach(function(roleModel) {
        var roleName = roleModel.getName();
        if(!permissions.contains(roleName)) {
            permissions.add(roleName);
        }
    });
});
token.setOtherClaims("permissions", permissions);
</code>```

Take me time to find the best way to make it working. But if you know a better solution. Thank you for sharing ;-)

Body:
To match same beaver of Auth0, on keycloak all the auth0-roles are set as group. And all auth0-permission as roles.

Now to allow to inject into the token the related roles of groups linked with a user, I created a Script Mapper in the client like this:

var ArrayList = Java.type("java.util.ArrayList");
var permissions = new ArrayList();
user.getGroups().forEach(function(groupModel) {
    groupModel.getRoleMappings().forEach(function(roleModel) {
        var roleName = roleModel.getName();
        if(!permissions.contains(roleName)) {
            permissions.add(roleName);
        }
    });
});
token.setOtherClaims("permissions", permissions);

Take me time to find the best way to make it working. But if you know a better solution. Thank you for sharing ;-)


问:
how can I use a state as an array of objects
I have recently started learning React TypeScript, and I am trying to make a Bowling Score application. I thought about state (I don't know much about states, just started learning it)  so I can put an array of object inside the state and use it which will make the values in each frame changes when I press the roll buttons. This is my code :

```<code>  type frame = {
    leftScore: any;
    rightScore: any;
    lastFrameScore: any;
    totalScore: any;
}
const game = new Game();
const [score , setScore] = useState<frame[]>([]);

function App() {
    setScore({score : game.score}); // got error here

    return (

        <div className='container'>
            <div className="RollsContainer">
                <h1>hi </h1>
                {[...Array(11)].map((e , i) =>
                    <button key={i} onClick={() => handleRolls(i)}>{i}</button>
                )
                }
            </div>
            <div className="frameContainer">

                {[...Array(10)].map((e , i) =>

                    <Frame
                        framenbr={i + 1}
                        leftbox={score[i + 1].leftScore}
                        rightbox={game.score[i].rightScore}
                        lastbox={game.score[i].lastFrameScore}
                        totalScore={game.score[i].totalScore}
                        key={i + 1}/>)
                }

            </div>

        </div>
    )

}
</code>```

this is game class:

```<code>export class Game {
    curentFrame: number;
    roll: any;
    score: frame[] = [];

    constructor() {
        this.curentFrame = 0;

        for (let i = 0; i <= 10; i++) {
            this.score[i] = {
                leftScore : '' ,
                rightScore : '' ,
                lastFrameScore : '' ,
                totalScore : '' ,
            };
        }

    }
}
</code>```

I got this error

```<code>Error:(15, 15) TS2345: Argument of type '{ score: frame[]; }' is not assignable to parameter of type 'SetStateAction<frame[]>'.
  Object literal may only specify known properties, and 'score' does not exist in type 'SetStateAction<frame[]>'.
</code>```

I don't know if this is right or wrong I tried so many solutions but did not work

答:
You are setting score like this.setState instead useState hook, so change your setScore like below and also try putting intial object array with frame type instead of empty array.</p>
```<code>...
const initialObj = {
                     leftScore : '' ,
                     rightScore : '' ,
                     lastFrameScore : '' ,
                     totalScore : '' ,
                   }
const [score , setScore] = useState<frame[]>([initialObj]);
...
setScore(prev => [...prev, game.score]);
</code>```

Body:
I have recently started learning React TypeScript, and I am trying to make a Bowling Score application. I thought about state (I don't know much about states, just started learning it)  so I can put an array of object inside the state and use it which will make the values in each frame changes when I press the roll buttons. This is my code :

  type frame = {
    leftScore: any;
    rightScore: any;
    lastFrameScore: any;
    totalScore: any;
}
const game = new Game();
const [score , setScore] = useState<frame[]>([]);

function App() {
    setScore({score : game.score}); // got error here

    return (

hi

                {[...Array(11)].map((e , i) =>
                    <button key={i} onClick={() => handleRolls(i)}>{i}</button>
                )
                }

                {[...Array(10)].map((e , i) =>

                    <Frame
                        framenbr={i + 1}
                        leftbox={score[i + 1].leftScore}
                        rightbox={game.score[i].rightScore}
                        lastbox={game.score[i].lastFrameScore}
                        totalScore={game.score[i].totalScore}
                        key={i + 1}/>)
                }

    )

}

this is game class:

export class Game {
    curentFrame: number;
    roll: any;
    score: frame[] = [];

    constructor() {
        this.curentFrame = 0;

        for (let i = 0; i <= 10; i++) {
            this.score[i] = {
                leftScore : '' ,
                rightScore : '' ,
                lastFrameScore : '' ,
                totalScore : '' ,
            };
        }

    }
}

I got this error

Error:(15, 15) TS2345: Argument of type '{ score: frame[]; }' is not assignable to parameter of type 'SetStateAction<frame[]>'.
  Object literal may only specify known properties, and 'score' does not exist in type 'SetStateAction<frame[]>'.

I don't know if this is right or wrong I tried so many solutions but did not work

Body:
You are setting score like this.setState instead useState hook, so change your setScore like below and also try putting intial object array with frame type instead of empty array.

...
const initialObj = {
                     leftScore : '' ,
                     rightScore : '' ,
                     lastFrameScore : '' ,
                     totalScore : '' ,
                   }
const [score , setScore] = useState<frame[]>([initialObj]);
...
setScore(prev => [...prev, game.score]);


问:
a single script in node to get authToken from some xyz oath2 /token end point and call the following api. I have coded something like this below
// getToken.mjs

```<code>import axios from 'axios';
import qs from 'qs';
var data = qs.stringify({
  'client_id': 'xxxx-xxx',
  'client_secret':  'xxxx-xxx',
  'scope': 'https://graph.microsoft.com/.default',
  'grant_type': 'client_credentials'
});
const config = {
  method: 'get',
  url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',   },
  data : data
};

export let accessToken = axios(config)
.then(function (response) {
  console.log((response.data.access_token));
})
.catch(function (error) {
  console.log(error);
});
</code>```

--------- Calling the API in the second script -----

//get response.js

```<code>import axios from "axios";
import { accessToken } from "./getToken.mjs";
const config = {
  method: 'get',
  url: 'https://graph.microsoft.com/v1.0/me/',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': `Bearer ${accessToken}`,
  }
};

export let data000 = axios(config).then(function (response) {
  console.log(JSON.stringify(response.data));
}).catch(function (error) {
  console.log(error);
});

console.log(data000);
</code>```

On executing the > node response.js ...  returns 401, client secret, and id is correct. However, I feel the accessToken is not getting imported and hence the error. How do I fix this?

答:
Try to use POST method to get accessToken.

```<code>const config = {
  method: 'post',
  url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',   },
  data : data
};
</code>```

Body:
// getToken.mjs

import axios from 'axios';
import qs from 'qs';
var data = qs.stringify({
  'client_id': 'xxxx-xxx',
  'client_secret':  'xxxx-xxx',
  'scope': 'https://graph.microsoft.com/.default',
  'grant_type': 'client_credentials'
});
const config = {
  method: 'get',
  url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',   },
  data : data
};

export let accessToken = axios(config)
.then(function (response) {
  console.log((response.data.access_token));
})
.catch(function (error) {
  console.log(error);
});

--------- Calling the API in the second script -----

//get response.js

import axios from "axios";
import { accessToken } from "./getToken.mjs";
const config = {
  method: 'get',
  url: 'https://graph.microsoft.com/v1.0/me/',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': `Bearer ${accessToken}`,
  }
};

export let data000 = axios(config).then(function (response) {
  console.log(JSON.stringify(response.data));
}).catch(function (error) {
  console.log(error);
});

console.log(data000);

On executing the > node response.js ...  returns 401, client secret, and id is correct. However, I feel the accessToken is not getting imported and hence the error. How do I fix this?

Body:
Try to use POST method to get accessToken.

const config = {
  method: 'post',
  url: 'https://login.microsoftonline.com/${tenant_id}/oauth2/v2.0/token',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',   },
  data : data
};


问:
What is the best way of converting a large folder of bmp files to jpeg?
I have a large folder of BMP files and I want to write a script that will loop through all the files in the folder and convert all BMP files into jpeg. I want it to continuously run as it will be used on a production line where new BMP images will be uploaded regularly.</p>

答:
A single run of this code will give you the expected output.

```<code>from PIL import Image
from os import listdir,path

file_path = '.'
file_format = '.jpeg'
for file in listdir(file_path):
    file_name, file_type = path.splitext(file)
    try:
        if file_type not in [file_format, '.py','.png']:
            im = Image.open(file_name + file_type)
            im.save(file_name + file_format)
    except (IOError, OSError):
        print('Error: {} Conversion'.format(file))
</code>```

Body:
A single run of this code will give you the expected output.

from PIL import Image
from os import listdir,path

file_path = '.'
file_format = '.jpeg'
for file in listdir(file_path):
    file_name, file_type = path.splitext(file)
    try:
        if file_type not in [file_format, '.py','.png']:
            im = Image.open(file_name + file_type)
            im.save(file_name + file_format)
    except (IOError, OSError):
        print('Error: {} Conversion'.format(file))


问:
Using the DISTINCT keyword causes this error: not a SELECTed expression
I have a query that looks something like this:

```<code>SELECT DISTINCT share.rooms
FROM Shares share
  left join share.rooms.buildingAdditions.buildings.buildingInfoses as bi
... //where clause omitted
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
</code>```

Which results in the following exception:

```<code>Caused by: org.hibernate.exception.SQLGrammarException: ORA-01791: not a SELECTed expression
</code>```

If I remove the DISTINCT keyword, the query runs without issue.  If I remove the order by clause, the query runs without issue.  Unfortunately, I can't seem to get the ordered result set without duplicates.

答:
When using DISTINCT in a query that has an ORDER BY you must select all the columns you've used in the ORDER BY statement:

```<code>SELECT DISTINCT share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
...
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
</code>```

Body:
I have a query that looks something like this:

SELECT DISTINCT share.rooms
FROM Shares share
  left join share.rooms.buildingAdditions.buildings.buildingInfoses as bi
... //where clause omitted
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent

Which results in the following exception:

Caused by: org.hibernate.exception.SQLGrammarException: ORA-01791: not a SELECTed expression

If I remove the DISTINCT keyword, the query runs without issue.  If I remove the order by clause, the query runs without issue.  Unfortunately, I can't seem to get the ordered result set without duplicates.

Body:
When using DISTINCT in a query that has an ORDER BY you must select all the columns you've used in the ORDER BY statement:

SELECT DISTINCT share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
...
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
         share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent


问:
What will happen if I put project1's SECRET_KEY to project2
Sorry to bother you guys but I have a question about Django's SECRET_KEY.

So I know these SECRET_KEY's are unique for every project.

So I think what will happen if I change this SCECRET_KEY.

Suppose I have created project1 and copied SECRET_KEY then paste it to project2's SECRET_KEY and after that I deleted project1.

So what will happen? I searched a lot but I didn't get any clear answer about it.

Thanks!!!

答:
User experience directly impacted by a change of value are: sessions, the data decode will break, that is valid for any session backend (cookies, database, file-based or cache). The password reset token already sent won't work, users will have to ask for a new one.

Same will happen for both projects.

Key is used in various things, mainly used in session cookies.
CSRF key will probably change too.

Many things will be affected that use the SECRET_KEY

You can read more here - https://docs.gitguardian.com/secrets-detection/detectors/specifics/django_secret_key


问:
How to assign or return generic T that is constrained by union?
In other words, how do I implement type-specific solutions for different types in a union type set?

Given the following code...

type FieldType interface {
    string | int
}

type Field[T FieldType] struct {
    name         string
    defaultValue T
}

func NewField[T FieldType](name string, defaultValue T) *Field[T] {
    return &Field[T]{
        name:         name,
        defaultValue: defaultValue,
    }
}

func (f *Field[T]) Name() string {
    return f.name
}

func (f *Field[T]) Get() (T, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}
```
<p>the compiler shows the error:</p>
```field.go:37:9: cannot use value (variable of type string) as type T in return statement
```
<p>Is there a way to provide implementations for all possible <code>FieldType</code>s?</p>
<p>Like...</p>
<pre class="lang-golang prettyprint-override"><code>func (f *Field[string]) Get() (string, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}

func (f *Field[int]) Get() (int, error) {
    raw, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    value, err := strconv.ParseInt(raw, 10, 64)
    if err != nil {
        return *new(T), err
    }
    return int(value), nil
}
</code>```

Any hint would be welcome.

答:
Ok, the type switch works if reflections are used.

func (f *Field[T]) Get() (T, error) {
    raw, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }

    v := reflect.ValueOf(new(T))

    switch v.Type().Elem().Kind() {
    case reflect.String:
        v.Elem().Set(reflect.ValueOf(raw))

    case reflect.Int:
        value, err := strconv.ParseInt(raw, 10, 64)
        if err != nil {
            return f.defaultValue, err
        }
        v.Elem().Set(reflect.ValueOf(int(value)))
    }

    return v.Elem().Interface().(T), nil
}
```

But better solutions are very welcome ;-)

Body:
In other words, how do I implement type-specific solutions for different types in a union type set?

Given the following code...

type FieldType interface {
    string | int
}

type Field[T FieldType] struct {
    name         string
    defaultValue T
}

func NewField[T FieldType](name string, defaultValue T) *Field[T] {
    return &Field[T]{
        name:         name,
        defaultValue: defaultValue,
    }
}

func (f *Field[T]) Name() string {
    return f.name
}

func (f *Field[T]) Get() (T, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}

the compiler shows the error:

field.go:37:9: cannot use value (variable of type string) as type T in return statement

Is there a way to provide implementations for all possible FieldTypes?

Like...

func (f *Field[string]) Get() (string, error) {
    value, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    return value, nil
}

func (f *Field[int]) Get() (int, error) {
    raw, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }
    value, err := strconv.ParseInt(raw, 10, 64)
    if err != nil {
        return *new(T), err
    }
    return int(value), nil
}

Any hint would be welcome.

Body:
Ok, the type switch works if reflections are used.

func (f *Field[T]) Get() (T, error) {
    raw, ok := os.LookupEnv(f.name)
    if !ok {
        return f.defaultValue, nil
    }

    v := reflect.ValueOf(new(T))

    switch v.Type().Elem().Kind() {
    case reflect.String:
        v.Elem().Set(reflect.ValueOf(raw))

    case reflect.Int:
        value, err := strconv.ParseInt(raw, 10, 64)
        if err != nil {
            return f.defaultValue, err
        }
        v.Elem().Set(reflect.ValueOf(int(value)))
    }

    return v.Elem().Interface().(T), nil
}

But better solutions are very welcome ;-)


问:
How to recover from routef command on rhel?
By mistake I have executed routef command on linux machine. Please help me recover it before my manager blasts at me. </p>

答:
```<code>systemctl restart network && yum update
</code>```

Body: systemctl restart network && yum update


问:
Class doesn't get added on first click
I add a classname with Jquery, and it works, but only starts working AFTER my first click.
The code only addes the 'class' attribute the first time, but without the value.
Can anyone see what I do wrong?
(the class just add's a top margin in CSS)

```<code>(function(){
    $(document).ready(Setup)

    function Setup(){
        $("#navBarBehandeling").on('click',CheckDropDown);
    }
    $("#navBarBehandeling").on('click',CheckDropDown);
    function CheckDropDown(){
        var t = $(this);
        if(t.attr('aria-expanded')=='false'){
           $('main').addClass("mt-9");

        }
        else{
            $('main').removeClass("mt-9");
        }

    }
}()
</code>```

And here's my css:

```<code>.mt-9{
    margin-top: 9rem;
}
</code>```

and here's my html:

```<code><head>
   CDN's for Jquery and bootstrap
</head>
<body>
    <header>
        <div id="navBarBehandeling"> navbar with dropdown here></div>
    </header>
    <main>
        <p> blablabla </p>
    </main>
</body>
</code>```

答:
Use document ready like this:</p>
```<code>$(document).ready(function () {
      $("#navBarBehandeling").on("click", CheckDropDown);
      function CheckDropDown() {
        var t = $(this);
        if (t.attr("aria-expanded") == "false") {
          $("main").addClass("mt-9");
        } else {
          $("main").removeClass("mt-9");
        }
      }
    });
</code>```

Title: Class doesn't get added on first click

Body:
I add a classname with Jquery, and it works, but only starts working AFTER my first click.
The code only addes the 'class' attribute the first time, but without the value.
Can anyone see what I do wrong?
(the class just add's a top margin in CSS)

(function(){
    $(document).ready(Setup)

    function Setup(){
        $("#navBarBehandeling").on('click',CheckDropDown);
    }
    $("#navBarBehandeling").on('click',CheckDropDown);
    function CheckDropDown(){
        var t = $(this);
        if(t.attr('aria-expanded')=='false'){
           $('main').addClass("mt-9");

        }
        else{
            $('main').removeClass("mt-9");
        }

    }
}()

And here's my css:

.mt-9{
    margin-top: 9rem;
}

and here's my html:

   CDN's for Jquery and bootstrap

 navbar with dropdown here>

 blablabla

Body:
Use document ready like this:

$(document).ready(function () {
      $("#navBarBehandeling").on("click", CheckDropDown);
      function CheckDropDown() {
        var t = $(this);
        if (t.attr("aria-expanded") == "false") {
          $("main").addClass("mt-9");
        } else {
          $("main").removeClass("mt-9");
        }
      }
    });


问:
Entity framework query returns the same row multiple times
This is my first time using the Entity Framework and I'm getting some confusing results. I know a particular table contains 3 distinct rows when I run this SQL query:

```<code>SELECT * FROM mytable WHERE service_month = 201012
</code>```

When I run this query against the framework however, I get 3 rows, but they are all copies of the first row (VB syntax).

```<code>Dim temp = _context.mytable.Where(Function(x) x.service_month = 201012)
</code>```

Did I set up something incorrectly? This is how I'd do it with LINQ to SQL so I feel like I'm missing something.

答:
I experienced this in Code First 5.0.13 when I had used a [Key] attribute in the business object that came from the wrong library. It should be</p>
```<code>System.ComponentModel.DataAnnotations.KeyAttribute
</code>```

Body:
This is my first time using the Entity Framework and I'm getting some confusing results. I know a particular table contains 3 distinct rows when I run this SQL query:

SELECT * FROM mytable WHERE service_month = 201012

When I run this query against the framework however, I get 3 rows, but they are all copies of the first row (VB syntax).

Dim temp = _context.mytable.Where(Function(x) x.service_month = 201012)

Did I set up something incorrectly? This is how I'd do it with LINQ to SQL so I feel like I'm missing something.

Body:
I experienced this in Code First 5.0.13 when I had used a [Key] attribute in the business object that came from the wrong library. It should be

System.ComponentModel.DataAnnotations.KeyAttribute


问:
Can't install scikit-learn on mac
I am trying to install scikit-learn and scipy packages in Python. I've already installed NumPy and Pandas successfully. Then I used following command:

```<code>pip install scikit-learn
</code>```

and I received following error:

```<code>File "/private/tmp/pip-build-env-w7wmv28v/overlay/lib/python3.9/site-packages/wheel/bdist_wheel.py", line 278, in get_tag
                      assert tag in supported_tags, "would build wheel with unsupported tag {}".format(tag)
                  AssertionError: would build wheel with unsupported tag ('cp39', 'cp39', 'macosx_11_0_universal2')
                  [end of output]

              note: This error originates from a subprocess, and is likely not a problem with pip.
              ERROR: Failed building wheel for numpy
            Failed to build numpy
            ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
      error: subprocess-exited-with-error

      × pip subprocess to install build dependencies did not run successfully.
      │ exit code: 1
      ╰─> See above for output.

      note: This error originates from a subprocess, and is likely not a problem with pip.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.
</code>```

I am using python 3.9.10, and a mac computer. What should I do?

答:
Have you tried this?:</p>
```<code>pip install sklearn
</code>```

Title: Can't install scikit-learn on mac

Body:
I am trying to install scikit-learn and scipy packages in Python. I've already installed NumPy and Pandas successfully. Then I used following command:

pip install scikit-learn

and I received following error:

File "/private/tmp/pip-build-env-w7wmv28v/overlay/lib/python3.9/site-packages/wheel/bdist_wheel.py", line 278, in get_tag
                      assert tag in supported_tags, "would build wheel with unsupported tag {}".format(tag)
                  AssertionError: would build wheel with unsupported tag ('cp39', 'cp39', 'macosx_11_0_universal2')
                  [end of output]

              note: This error originates from a subprocess, and is likely not a problem with pip.
              ERROR: Failed building wheel for numpy
            Failed to build numpy
            ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
      error: subprocess-exited-with-error

      × pip subprocess to install build dependencies did not run successfully.
      │ exit code: 1
      ╰─> See above for output.

      note: This error originates from a subprocess, and is likely not a problem with pip.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

I am using python 3.9.10, and a mac computer. What should I do?

Body:
Have you tried this?:

pip install sklearn


问:
What is the difference between == and ===?
What is the difference between equality:

```<code>==
</code>```

and strict equality?

```<code>===
</code>```

答:
This is the answer given by the creators of actionscript itself
== tests two expressions for equality.
whereas, === tests two expressions for equality, but does not perform automatic data conversion.</p>

ContentLicense: CC BY-SA 2.5

Body:
What is the difference between equality:

==

and strict equality?

===


问:
Average time for approval of iPhone application on Appstore
Any idea on what is the average time that Appstore usually takes to approve/dis-approve a submitted application ?</p>

答:
There are also sites like http://148apps.biz/app-store-metrics/?mpage=approval that try to measure what the current average approval time is.

Also note the "max delay" column...


答:
I implemented a code like this, but as far as I can say, it is not the most efficient way to solve this problem. Just for now, you can see the solution below. I will work on how to improve it.</p>
```<code>import copy

l= [45, 22, 11, 5, 2, 1, 20, 10, 5, 2, 1, 40, 20, 10, 5, 2, 1, 26, 13, 6, 3, 1, 32, 16, 8, 4, 2, 1]

e=1

result_l = list()

while l != []:
    res = [i for i in l[:l.index(e)+1]]
    result_l.append(copy.deepcopy(res))

    index = l.index(e)+1
    for _ in range(index):
        del l[0]
    res=None

print(result_l)
</code>```

Title: How to group list till the specific element occurs in python?

Body:
How to group list till the specific element occurs

l= [45, 22, 11, 5, 2, 1, 20, 10, 5, 2, 1, 40, 20, 10, 5, 2, 1, 26, 13, 6, 3, 1, 32, 16, 8, 4, 2, 1]

e=1

My code:

l=[45, 22, 11, 5, 2, 1, 20, 10, 5, 2, 1, 40, 20, 10, 5, 2, 1, 26, 13, 6, 3, 1, 32, 16, 8, 4, 2, 1]
e=1

l=[l[i:l.index(e)+1] for i in range(0,len(l))]
print(l)

My output:

[[45, 22, 11, 5, 2, 1], [22, 11, 5, 2, 1], [11, 5, 2, 1], [5, 2, 1], [2, 1], [1], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]

Needed output:

[[45, 22, 11, 5, 2, 1], [20, 10, 5, 2, 1], [40, 20, 10, 5, 2, 1], [26, 13, 6, 3, 1], [32, 16, 8, 4, 2, 1]]

What mistake i made?

Body:
I implemented a code like this, but as far as I can say, it is not the most efficient way to solve this problem. Just for now, you can see the solution below. I will work on how to improve it.

import copy

l= [45, 22, 11, 5, 2, 1, 20, 10, 5, 2, 1, 40, 20, 10, 5, 2, 1, 26, 13, 6, 3, 1, 32, 16, 8, 4, 2, 1]

e=1

result_l = list()

while l != []:
    res = [i for i in l[:l.index(e)+1]]
    result_l.append(copy.deepcopy(res))

    index = l.index(e)+1
    for _ in range(index):
        del l[0]
    res=None

print(result_l)


问:
How to fix "command not found: mysql" in Zsh
I want to use MySQL with my Rails application.

After successfully installing the package and seeing the option to start and stop the server from the Preference Pane, if I execute

```<code>mysql --version
</code>```

I get an error from zsh:

```<code>zsh: command not found: mysql
</code>```

I understand that this has something to do with my $PATH variable and if I display my $PATH I get:

```<code>/Library/Frameworks/Python.framework/Versions/3.4/bin:/Users/aniruddhabarapatre1/.rvm/gems/ruby-2.2.1/bin:/Users/aniruddhabarapatre1/.rvm/gems/ruby-2.2.1@global/bin:/Users/aniruddhabarapatre1/.rvm/rubies/ruby-2.2.1/bin:/usr/local/bin:/Users/aniruddhabarapatre1/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/opt/ImageMagick/bin:/usr/local/MacGPG2/bin:/Users/aniruddhabarapatre1/.rvm/bin
</code>```

How do I resolve this error to get Mysql up and running?

答:
In the terminal run:

```<code>export PATH=/usr/local/Cellar/mysql/8.0.26/bin:$PATH
</code>```

Then, if you run:

```<code>mysql
</code>```

It should return:

```<code>Access denied for user 'user'@'localhost' (using password: NO)
</code>```

Run:

```<code>mysql -u root -p
</code>```

It should ask for your password and then be good to go.

Body:
I want to use MySQL with my Rails application.

After successfully installing the package and seeing the option to start and stop the server from the Preference Pane, if I execute

mysql --version

I get an error from zsh:

zsh: command not found: mysql

I understand that this has something to do with my $PATH variable and if I display my $PATH I get:

/Library/Frameworks/Python.framework/Versions/3.4/bin:/Users/aniruddhabarapatre1/.rvm/gems/ruby-2.2.1/bin:/Users/aniruddhabarapatre1/.rvm/gems/ruby-2.2.1@global/bin:/Users/aniruddhabarapatre1/.rvm/rubies/ruby-2.2.1/bin:/usr/local/bin:/Users/aniruddhabarapatre1/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/opt/ImageMagick/bin:/usr/local/MacGPG2/bin:/Users/aniruddhabarapatre1/.rvm/bin

How do I resolve this error to get Mysql up and running?

Body:
In the terminal run:

export PATH=/usr/local/Cellar/mysql/8.0.26/bin:$PATH

Then, if you run:

mysql

It should return:

Access denied for user 'user'@'localhost' (using password: NO)

Run:

mysql -u root -p

It should ask for your password and then be good to go.


问:
In ggplot2 on log10 scale, can axis label accuracy vary?
I'm drawing a plot with a log10 x-axis, with limits from 0.01 to 100. By default, the axis is displayed in scientific notation.

If I define the label using comma_format(), it the ticks mark 0.01, 0.10, 1.00, 10.00 and 100.00.

However, I want the labels to be 0.01, 0.1, 1, 10, 100.

Is there any way to vary with accuracy?

答:
You can use gsub() with a regex pattern to remove trailing zeroes and optionally a separator.

The expression below has the following meaning:

0+$ one or more zeroes at the end of the string.

\\.? possibly a period (the dashes indicate literal periods instead of the regex wildcard). By placing this before the zeroes, we only seek to remove periods followed by zeroes, which excludes e.g. 0.01.

library(scales)
library(ggplot2)

df <- data.frame(x = 10^seq(-2, 2, length.out = 10))

ggplot(df, aes(x, x)) +
  geom_point() +
  scale_y_log10(
    labels = ~ gsub("\\.?0+$", "", comma(.x))
  )
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
You can use gsub() with a regex pattern to remove trailing zeroes and optionally a separator.

The expression below has the following meaning:

0+$ one or more zeroes at the end of the string.

\\.? possibly a period (the dashes indicate literal periods instead of the regex wildcard). By placing this before the zeroes, we only seek to remove periods followed by zeroes, which excludes e.g. 0.01.

library(scales)
library(ggplot2)

df <- data.frame(x = 10^seq(-2, 2, length.out = 10))

ggplot(df, aes(x, x)) +
  geom_point() +
  scale_y_log10(
    labels = ~ gsub("\\.?0+$", "", comma(.x))
  )

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
Integrate Github commits to gitlab repository
Is this a possibility to integrate github repository in gitlab.
My basic need is to commit in github and flow it all in gitlab.
I am not sure if this can be done!
Is this a classical case of CI?

Thanks!

答: I think you want to do some mirroring of your project. I guess (but not tested) that if the repository have a .gitlab-ci.yml file, pipelines will be launched when commits are mirrored.


问:
How can i join two prefetch related in Django query
i have to do a django filter with complex form query and i don't have experience with select_related and prefetch_related methods.

models.py:

```<code>class User(models.Model):

class Park(models.Model):

class Plot(models.Model):
  owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, null=True, related_name='plots')
  park = models.ForeignKey('Park', verbose_name=_('Park'), on_delete=models.SET_NULL, null=True, related_name='plots')

class Building(models.Model):
  plot = models.ForeignKey('Plot', verbose_name=_('Plot'), on_delete=models.SET_NULL, blank=True, null=True, related_name='plot_buildings')
  owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, blank=True, null=True, related_name='owner_buildings')
  tenant = models.ForeignKey(get_user_model(), verbose_name=_('Tenant'), on_delete=models.SET_NULL, blank=True, null=True, related_name='tenant_buildings')
</code>```

I need to get all de user that are owner of a plot or a building or tenant of a building.

i have this for now...

filters.py:

```<code>class UserApiFilter(filters.FilterSet):
  park_id = filters.CharFilter(method='filter_by_park')

  def filter_by_park(self, queryset, name, value):
    params = {name: value}
    result = queryset.prefetch_related(Prefetch('plots', queryset=app_models.Plot.objects.filter(**params)))
</code>```

Anybody could help me please?
Thanks in advance.

答:
For now i have this solution:</p>
```<code>params = {'park__id': value}
plots = app_models.Plot.objects.filter(**params)
users_plots = list(map(lambda x: x.owner, plots))
params = {'plot__park__id': value}
buildings = app_models.Building.objects.filter(**params)
users_buildings_owners = list(map(lambda x: x.owner, buildings))
users_buildings_tenats = list(map(lambda x: x.tenant, buildings))
result = list(map(lambda x: x.id, set(users_plots + users_buildings_owners + users_buildings_tenats)))
return queryset.filter(id__in=result)
</code>```

Body:
i have to do a django filter with complex form query and i don't have experience with select_related and prefetch_related methods.

models.py:

class User(models.Model):

class Park(models.Model):

class Plot(models.Model):
  owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, null=True, related_name='plots')
  park = models.ForeignKey('Park', verbose_name=_('Park'), on_delete=models.SET_NULL, null=True, related_name='plots')

class Building(models.Model):
  plot = models.ForeignKey('Plot', verbose_name=_('Plot'), on_delete=models.SET_NULL, blank=True, null=True, related_name='plot_buildings')
  owner = models.ForeignKey(get_user_model(), verbose_name=_('Owner'), on_delete=models.SET_NULL, blank=True, null=True, related_name='owner_buildings')
  tenant = models.ForeignKey(get_user_model(), verbose_name=_('Tenant'), on_delete=models.SET_NULL, blank=True, null=True, related_name='tenant_buildings')

I need to get all de user that are owner of a plot or a building or tenant of a building.

i have this for now...

filters.py:

class UserApiFilter(filters.FilterSet):
  park_id = filters.CharFilter(method='filter_by_park')

  def filter_by_park(self, queryset, name, value):
    params = {name: value}
    result = queryset.prefetch_related(Prefetch('plots', queryset=app_models.Plot.objects.filter(**params)))

Anybody could help me please?
Thanks in advance.

Body:
For now i have this solution:

params = {'park__id': value}
plots = app_models.Plot.objects.filter(**params)
users_plots = list(map(lambda x: x.owner, plots))
params = {'plot__park__id': value}
buildings = app_models.Building.objects.filter(**params)
users_buildings_owners = list(map(lambda x: x.owner, buildings))
users_buildings_tenats = list(map(lambda x: x.tenant, buildings))
result = list(map(lambda x: x.id, set(users_plots + users_buildings_owners + users_buildings_tenats)))
return queryset.filter(id__in=result)


问:
Date trunc and partition by subject
I have a db with column name containing different companies names, and column date, where each company has all days of the year ( so date= 1/3/2007 appear for name=x and also for name=y).

I need to calculate monthly profit separately for each company.

I am able to do this for a single company:

```<code>    WITH BS AS (
    SELECT DISTINCT ON(date_trunc('month', date)) date_trunc('month', date), date_num, name, profit as c
    FROM history
    WHERE name IN ('X', 'Y') //companies
    ),
    LG AS (
    SELECT date_num, name, c, LAG(c,1) OVER (PARTITION BY name ORDER BY date_num) o
    FROM BS
    )

    SELECT date_num, name, c, o,  100 * ( (c - o)/o )  as trends
    FROM LG
    ORDER BY date_num  DESC
</code>```

This works for a single company, but if I have multiple (X+Y) how can I separate the DISTINCT date selection for each name ?

desired output (assuming each name as all possible dates of the year):

```<code>name  date      trend

X     1.2.2020.   3
X     1.3.2020.   4
X     1.4.2020.   7
Y     1.2.2020.   9
Y     1.3.2020.   2
Y     1.4.2020.   5
</code>```

Original data :

```<code>name  date      profit  date_num

X     1.2.2020.   2     1638316800 (EPOCH DATES)
X     2.2.2020.   1     ....
X     3.2.2020.   6     ..
Y     1.2.2020.   5
Y     2.2.2020.   4
Y     3.2.2020.   2
</code>```

答:
Using DISTINCT ON requires a proper ORDER BY to return the correct rows.

```<code>WITH BS AS (
   SELECT DISTINCT ON(date_trunc('month', date), name) date, name, date_num, profit c
   FROM history
   WHERE name IN ('X', 'Y')
   ORDER BY date_trunc('month', date), name, date_num
), LG AS (
      SELECT date_num, name, c, LAG(c,1) OVER(PARTITION BY name ORDER BY date_num) o
      FROM BS
)
SELECT date_num, name, c, o,  100.0 * ( (c - o)/o )  as trends
FROM LG
ORDER BY date_num DESC
</code>```

db<>fiddle

Title: Date trunc and partition by subject

Body:
I have a db with column name containing different companies names, and column date, where each company has all days of the year ( so date= 1/3/2007 appear for name=x and also for name=y).

I need to calculate monthly profit separately for each company.

I am able to do this for a single company:

    WITH BS AS (
    SELECT DISTINCT ON(date_trunc('month', date)) date_trunc('month', date), date_num, name, profit as c
    FROM history
    WHERE name IN ('X', 'Y') //companies
    ),
    LG AS (
    SELECT date_num, name, c, LAG(c,1) OVER (PARTITION BY name ORDER BY date_num) o
    FROM BS
    )

    SELECT date_num, name, c, o,  100 * ( (c - o)/o )  as trends
    FROM LG
    ORDER BY date_num  DESC

This works for a single company, but if I have multiple (X+Y) how can I separate the DISTINCT date selection for each name ?

desired output (assuming each name as all possible dates of the year):

name  date      trend

X     1.2.2020.   3
X     1.3.2020.   4
X     1.4.2020.   7
Y     1.2.2020.   9
Y     1.3.2020.   2
Y     1.4.2020.   5

Original data :

name  date      profit  date_num

X     1.2.2020.   2     1638316800 (EPOCH DATES)
X     2.2.2020.   1     ....
X     3.2.2020.   6     ..
Y     1.2.2020.   5
Y     2.2.2020.   4
Y     3.2.2020.   2

Body:
Using DISTINCT ON requires a proper ORDER BY to return the correct rows.

WITH BS AS (
   SELECT DISTINCT ON(date_trunc('month', date), name) date, name, date_num, profit c
   FROM history
   WHERE name IN ('X', 'Y')
   ORDER BY date_trunc('month', date), name, date_num
), LG AS (
      SELECT date_num, name, c, LAG(c,1) OVER(PARTITION BY name ORDER BY date_num) o
      FROM BS
)
SELECT date_num, name, c, o,  100.0 * ( (c - o)/o )  as trends
FROM LG
ORDER BY date_num DESC

db<>fiddle


问:
How to read commands from a text file to serial port
I need to write commands to a USB serial port to configure multiple devices, the commands are always the same so I type the same list of commands over and over again which is inefficient. I do this using PuTTY.

Is there a program similar to PuTTY which allows you to read commands from a text file or another method which I can send the same series of commands quickly?

答:
PuTTY comes with console tool called Plink that's (contrary to PuTTY) intended for automation.

See this question for details how to use Plink to execute commands over serial connection:

Execute a command on device over serial connection with Plink


问:
Can't login to Apple ID on Xcode, `Unexpected nil property at path: 'Provider/attributes/developerTeamId'`

Problem

In Xcode (Version 13.2.1 (13C100) and the latest beta, Version 13.3 beta (13E5086k)), trying to login to my Apple ID results in the error, Unexpected nil property at path: 'Provider/attributes/developerTeamId'. Has anyone got a solution to this?

Observations

this happens on multiple computers. So don't bother resetting your system. I am trying to use an older version of Xcode now. However, this might be an API issue (data sent back from Apple servers) which isn't structured well for Xcode.

this affects accounts with multiple teams.

 accounts section" />

答:
After writing to feedbackasistant the problem was fixed for me.

Xcode Version 13.2.1 (13C100)


问:
os.getenv from systemd adds another backslash \\n to \n
Loading the .env file in /etc/systemd/system/p-app.service:

```<code>[Service]
...

EnvironmentFile=/u/p/app.env
</code>```

How the keys are stored in /u/p/app.env:

```<code>AUTH_JWT_PRIVATE="-----BEGIN EC PRIVATE KEY-----\nM...5f/KL...49\nA...wN/VT...VE/KW...yQ\nM...mA==\n-----END EC PRIVATE KEY-----"

AUTH_JWT_PUBLIC="-----BEGIN PUBLIC KEY-----\nM...wN/VT...VE/KW...mA==\n-----END PUBLIC KEY-----"
</code>```

Retrieval Python:

```<code>def get_envar(name):
    if name in os.environ:
        try:
            payload = os.getenv(name)
            print(f'Environment variable {name} loaded.')
        except Exception as error:
            sys.exit(
                'Failed importing {} from environment variable. Error: {}'.format(name, error))
        else:
            return payload
    else:
        sys.exit('Failed importing environment variable {} was not found!'.format(name))

AUTHORIZE_JWT_KEY_PRIVATE = get_envar('AUTH_JWT_PRIVATE').encode('ascii')
AUTHORIZE_JWT_KEY_PUBLIC = get_envar('AUTH_JWT_PUBLIC').encode('ascii')
</code>```

And when I print these variables I get this:

```<code>b'-----BEGIN EC PRIVATE KEY-----\\nM...5f/KL...49\\nA...wN/VT...VE/KW...yQ\nM...mA==\\n-----END EC PRIVATE KEY-----'
</code>```

With double backslash \\n.

And therefore I am getting an error

```<code>ValueError: Could not deserialize key data. The data may be in an incorrect format or it may be encrypted with an unsupported algorithm.
</code>```

at return jwt.encode(payload=payload, key=private, algorithm=algorithm)

Am I doing something wrong?

答:
Solved the issue like by storing the keys in /u/p/app.env like this:</p>
```<code>AUTH_JWT_PRIVATE="-----BEGIN EC PRIVATE KEY-----
M...5f/KL...49
A...wN/VT...VE/KW...yQ
M...mA==
-----END EC PRIVATE KEY-----"

AUTH_JWT_PUBLIC="-----BEGIN PUBLIC KEY-----
M...wN/VT...VE/KW...mA==
-----END PUBLIC KEY-----"
</code>```

Body:
Loading the .env file in /etc/systemd/system/p-app.service:

[Service]
...

EnvironmentFile=/u/p/app.env

How the keys are stored in /u/p/app.env:

AUTH_JWT_PRIVATE="-----BEGIN EC PRIVATE KEY-----\nM...5f/KL...49\nA...wN/VT...VE/KW...yQ\nM...mA==\n-----END EC PRIVATE KEY-----"

AUTH_JWT_PUBLIC="-----BEGIN PUBLIC KEY-----\nM...wN/VT...VE/KW...mA==\n-----END PUBLIC KEY-----"

Retrieval Python:

def get_envar(name):
    if name in os.environ:
        try:
            payload = os.getenv(name)
            print(f'Environment variable {name} loaded.')
        except Exception as error:
            sys.exit(
                'Failed importing {} from environment variable. Error: {}'.format(name, error))
        else:
            return payload
    else:
        sys.exit('Failed importing environment variable {} was not found!'.format(name))

AUTHORIZE_JWT_KEY_PRIVATE = get_envar('AUTH_JWT_PRIVATE').encode('ascii')
AUTHORIZE_JWT_KEY_PUBLIC = get_envar('AUTH_JWT_PUBLIC').encode('ascii')

And when I print these variables I get this:

b'-----BEGIN EC PRIVATE KEY-----\\nM...5f/KL...49\\nA...wN/VT...VE/KW...yQ\nM...mA==\\n-----END EC PRIVATE KEY-----'

With double backslash \\n.

And therefore I am getting an error

ValueError: Could not deserialize key data. The data may be in an incorrect format or it may be encrypted with an unsupported algorithm.

at return jwt.encode(payload=payload, key=private, algorithm=algorithm)

Am I doing something wrong?

Body:
Solved the issue like by storing the keys in /u/p/app.env like this:

AUTH_JWT_PRIVATE="-----BEGIN EC PRIVATE KEY-----
M...5f/KL...49
A...wN/VT...VE/KW...yQ
M...mA==
-----END EC PRIVATE KEY-----"

AUTH_JWT_PUBLIC="-----BEGIN PUBLIC KEY-----
M...wN/VT...VE/KW...mA==
-----END PUBLIC KEY-----"


问:
Force to scroll overflowing item in flexbox
Im making a container with 3 cards. Each card (brown-ish color in example) has a header with title (sand-buiscuit color) and content (blue one).

What I want to acheive is when the cards are closed (click on header in example), the content (blue) is transitioning to height 0, and so the only visible part is header.

Also when the card is open I want to show the available content but only then, when there is enough available space in container (green).

When 3 cards are open, they have the same height (expand evenly in container), and remaining content (blue) is scrolled.

Is it possible to make?
I prepared a demo codesandbox

答:
I made a small code example using styled-components (just because i like it), you can easily change it to regular react components with css, but this demonstrates the idea.

I created 3 boxes, each box has a default height(40px) and after clicking (which opens it) its height is set to: 100%.

Wrapping all of this boxes with flex container does the trick.

import styled from 'styled-components';
import React, { useState } from 'react';

const MyComponent = () => {
  return (
    <Container>
      <BoxContainer height={100} number={1} />
      <BoxContainer height={100} number={2} />
      <BoxContainer number={3} />
    </Container>
  );
};

export default MyComponent;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 200px;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  background-color: blue;
`;

const BoxContainer = ({ number, height = '100' }) => {
  const [open, setOpen] = useState(false);

  return (
    <Box style={{ height: open ? '100%' : '40px' }} onClick={() => setOpen(!open)}>
      Box: {number}
      {open &&
Content
}
    </Box>
  );
};

const Box = styled.div`
  width: 100%;
  overflow: scroll;
  background-color: #00b8a2;
  border: 1px solid red;
`;```

sandbox example here: https://codesandbox.io/s/boxes-fill-container-evenly-when-opened-btlvb

Body:
I made a small code example using styled-components (just because i like it), you can easily change it to regular react components with css, but this demonstrates the idea.

I created 3 boxes, each box has a default height(40px) and after clicking (which opens it) its height is set to: 100%.

Wrapping all of this boxes with flex container does the trick.

import styled from 'styled-components';
import React, { useState } from 'react';

const MyComponent = () => {
  return (
    <Container>
      <BoxContainer height={100} number={1} />
      <BoxContainer height={100} number={2} />
      <BoxContainer number={3} />
    </Container>
  );
};

export default MyComponent;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: 200px;
  height: 400px;
  overflow: hidden;
  border: 1px solid black;
  background-color: blue;
`;

const BoxContainer = ({ number, height = '100' }) => {
  const [open, setOpen] = useState(false);

  return (
    <Box style={{ height: open ? '100%' : '40px' }} onClick={() => setOpen(!open)}>
      Box: {number}
      {open && <p>Content</p>}
    </Box>
  );
};

const Box = styled.div`
  width: 100%;
  overflow: scroll;
  background-color: #00b8a2;
  border: 1px solid red;
`;

sandbox example here: https://codesandbox.io/s/boxes-fill-container-evenly-when-opened-btlvb


问:
Retrieving values from multidimensional arrays
I have an array something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };
</code>```

if I want to retrieve 1 and 2 and feed them into this:

```<code>int a;
int b;
</code>```

How do I do it?

Is it something like this:

```<code>multiDimensionalArray2[0,0]
</code>```

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

```<code>   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };
</code>```

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

答:
You´re close, to retrieve the first numbers try this

```<code>        var a = multiDimensionalArray2[0, 0]; // x == 1
        var b = multiDimensionalArray2[0, 1]; // x == 2
</code>```

Did you give it a try and it didn´t work? You´ll notice that SO users will encourage you to try-and-error first. Come back when you hit a wall :)

Body:
I have an array something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } };

if I want to retrieve 1 and 2 and feed them into this:

int a;
int b;

How do I do it?

Is it something like this:

multiDimensionalArray2[0,0]

What if I wanted to put more numbers in the same form  e.g. { { 2, 1 }, { 4, 1 } };, in the same form as above. Would it be something like this:

   int[,] multiDimensionalArray2 = { { 1, 2 }, { 4, 5 } },{ { 2, 1 }, { 4, 1 } };

To retrieve the second set would I do this, multiDimensionalArray2[1,1]

Body:
You´re close, to retrieve the first numbers try this

        var a = multiDimensionalArray2[0, 0]; // x == 1
        var b = multiDimensionalArray2[0, 1]; // x == 2

Did you give it a try and it didn´t work? You´ll notice that SO users will encourage you to try-and-error first. Come back when you hit a wall :)


问:
Unable to get input data value in console in NestJS
I am making an post request where I am posting phone number via Postman request.In Postman I have set Content-Type:application/json but I am getting empty obbject {} in console.Below is my Postman screenshot of setting header and posting value.

Below is my code:

subscriber.controller.ts

```<code>@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

    @Post('location')
    async getLocation(@Body() phoneNumber:String){

    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc;
   }
}
</code>```

subscriber.service.ts

```<code>@Injectable()
export class SubscribeService {
constructor(private httpService: HttpService){}

      async getLocation(phoneNumber:String){

      return console.log(phoneNumber);
    }
}
</code>```

Someone let me know why its showing empty object in console.

答:
Update: return console.log(phoneNumber); in your service returns undefined, which you return in controller. If I'm not mistaken by default nest will change it to empty object in such case.
One more bug: @Body() phoneNumber:String in controller is incorrect, as you send JSON object.

Outdated: You've set x-www-form-urlencoded type for body on screen 2. Use raw type and provide correct JSON

Body:
I am making an post request where I am posting phone number via Postman request.In Postman I have set Content-Type:application/json but I am getting empty obbject {} in console.Below is my Postman screenshot of setting header and posting value.

Below is my code:

subscriber.controller.ts

@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

    @Post('location')
    async getLocation(@Body() phoneNumber:String){

    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc;
   }
}

subscriber.service.ts

@Injectable()
export class SubscribeService {
constructor(private httpService: HttpService){}

      async getLocation(phoneNumber:String){

      return console.log(phoneNumber);
    }
}

Someone let me know why its showing empty object in console.


问:
How to convert between 1200 and 1200/75 baud devices? socat?
Is it possible to get a program that uses symmetrical 1200 baud to communicate over serial to a device running at 1200/75? I've tried putting socet in between to create a virtual serial device running at 1200 and set the USB serial to 1200/75 but the far end still gets garbled text:</p>
```<code>socat -d -d pty,link=/dev/ttyvirt,raw,nonblock,echo=0,perm=0777,b1200 open:/dev/ttyUSB0,raw,nonblock,echo=0,ospeed=b1200,ispeed=b75
</code>```

答: The ispeed and ospeed options take integer numbers as argument, so try without the 'b' prefixes!</p>

Body:
Is it possible to get a program that uses symmetrical 1200 baud to communicate over serial to a device running at 1200/75? I've tried putting socet in between to create a virtual serial device running at 1200 and set the USB serial to 1200/75 but the far end still gets garbled text:

socat -d -d pty,link=/dev/ttyvirt,raw,nonblock,echo=0,perm=0777,b1200 open:/dev/ttyUSB0,raw,nonblock,echo=0,ospeed=b1200,ispeed=b75


问:
Autocorrelation of a wave file
I'm playing around with audio signal processing.
For that purpose, I'm using a single channel wave file from here.

My first experiment was to look at the auto-correlation of the signal as done by the following code.

from scipy.io import wavfile
from scipy import signal
import numpy as np

sample_rate_a, data_a = wavfile.read('sounds/CantinaBand3.wav')

corr = signal.correlate(data_a, data_a)
lags = signal.correlation_lags(len(data_a), len(data_a))
corr = corr / np.max(corr)

lag = lags[np.argmax(corr)]
print(lag, np.max(corr))
```

Given that it is an auto-correlation, I would have expected to see a peak of 1.0 at lag 0 (since I normalize the correlation matrix).

However, the program outputs a peak of 1.0 at lag -36141.
At lag 0, the correlation is -0.3526826588536898.

Currently, I do not have any explanation for this behavior.
Is there an error in my calculation of the correlation or the lags?

答:
When you read your wav file data_a is an int16 array. The correlation will be calculated using int16 data type as well, this will cause a lot of overflow. To get a meaningful result you can convert it to a floating point array.

from scipy.io import wavfile
from scipy import signal
import numpy as np

_, data_a = wavfile.read('./CantinaBand3.wav')
data_a = np.float32(data_a)
corr = signal.correlate(data_a, data_a)
lags = signal.correlation_lags(len(data_a), len(data_a))
corr = corr / np.max(corr)

lag = lags[np.argmax(corr)]
print(lag, np.max(corr))
```

Title: Autocorrelation of a wave file

Body:
I'm playing around with audio signal processing.
For that purpose, I'm using a single channel wave file from here.

My first experiment was to look at the auto-correlation of the signal as done by the following code.

from scipy.io import wavfile
from scipy import signal
import numpy as np

sample_rate_a, data_a = wavfile.read('sounds/CantinaBand3.wav')

corr = signal.correlate(data_a, data_a)
lags = signal.correlation_lags(len(data_a), len(data_a))
corr = corr / np.max(corr)

lag = lags[np.argmax(corr)]
print(lag, np.max(corr))

Given that it is an auto-correlation, I would have expected to see a peak of 1.0 at lag 0 (since I normalize the correlation matrix).

However, the program outputs a peak of 1.0 at lag -36141.
At lag 0, the correlation is -0.3526826588536898.

Currently, I do not have any explanation for this behavior.
Is there an error in my calculation of the correlation or the lags?


问:
Can you make an objects that deletes itself in Django?
So I made model VerificationToken

```<code>class VerificationToken(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    code = models.CharField(max_length=4)
    date_created = models.DateTimeField(auto_now_add=True)

    @property
    def expiration(self):

        lifetime = timedelta(minutes=10)

        expire = self.date_created + lifetime

        return expire
</code>```

and this model have an expiration property. Is there a way to make this model delete itself after it expires?

答:
Just make a filter that prevents retrieving expired VerificationTokens:

```<code>from datetime import timedelta
from django.db.models.functions import Now

VerificationToken.objects.filter(
    <strong>date_created__gte=Now()-timedelta(minutes=10)</strong>
)</code>```

You can also make a manager such that VerificationToken.objects is a manager that only contains non-expired tokens:

```<code>from datetime import timedelta
from django.conf import settings
from django.db.models.functions import Now

class <strong>VerificationTokenManager</strong>(models.Manager):

    def get_queryset(self):
        return super().get_querset().filter(
            date_created__gte=Now()-timedelta(minutes=10)
        )

class VerificationToken(models.Model):
    user = models.ForeignKey(
        <strong>settings.AUTH_USER_MODEL</strong>,
        on_delete=models.CASCADE
    )
    code = models.CharField(max_length=4)
    date_created = models.DateTimeField(auto_now_add=True<strong>, db_index=True</strong>)
    objects = <strong>VerificationTokenManager()</strong></code>```

you can then make a management command [Django-doc] that you for example run through cron, or some other scheduling task that removes expired VerificationTokens with:

```<code># app_name/management/commands/remove_expired_tokens.py

from datetime import timedelta
from django.core.management.base import BaseCommand
from django.db.models.functions import Now
from <em>app_name</em>.models import VerificationToken

class Command(BaseCommand):
    help = 'Remove expired verification tokens'

    def handle(self, *args, **options):
        VerificationToken._base_manager.filter(
            <strong>date_created__lt=Now()-timedelta(minutes=10)</strong>
        )<strong>.delete()</strong></code>```

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Body:
So I made model VerificationToken

class VerificationToken(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    code = models.CharField(max_length=4)
    date_created = models.DateTimeField(auto_now_add=True)

    @property
    def expiration(self):

        lifetime = timedelta(minutes=10)

        expire = self.date_created + lifetime

        return expire

and this model have an expiration property. Is there a way to make this model delete itself after it expires?

Body:
Just make a filter that prevents retrieving expired VerificationTokens:

from datetime import timedelta
from django.db.models.functions import Now

VerificationToken.objects.filter(
    date_created__gte=Now()-timedelta(minutes=10)
)

You can also make a manager such that VerificationToken.objects is a manager that only contains non-expired tokens:

from datetime import timedelta
from django.conf import settings
from django.db.models.functions import Now

class VerificationTokenManager(models.Manager):

    def get_queryset(self):
        return super().get_querset().filter(
            date_created__gte=Now()-timedelta(minutes=10)
        )

class VerificationToken(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    code = models.CharField(max_length=4)
    date_created = models.DateTimeField(auto_now_add=True, db_index=True)
    objects = VerificationTokenManager()

you can then make a management command [Django-doc] that you for example run through cron, or some other scheduling task that removes expired VerificationTokens with:

# app_name/management/commands/remove_expired_tokens.py

from datetime import timedelta
from django.core.management.base import BaseCommand
from django.db.models.functions import Now
from app_name.models import VerificationToken

class Command(BaseCommand):
    help = 'Remove expired verification tokens'

    def handle(self, *args, **options):
        VerificationToken._base_manager.filter(
            date_created__lt=Now()-timedelta(minutes=10)
        ).delete()

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


问:
how do i close firefox browsers window using javascript?
```<code>  function CloseWindow()
  {
        window.close();
  }
</code>```

The above code is working fine for IE but Firefox does not allows to close browsers window
any solution???

答:
Try to use self object</p>

```<code><a href="javascript:self.close()">Close Window</a>
</code>```

Body:
  function CloseWindow()
  {
        window.close();
  }

The above code is working fine for IE but Firefox does not allows to close browsers window
any solution???

Body:
Try to use self object

<a href="javascript:self.close()">Close Window</a>


问:
How to Push NPM Package to Azure Artifact Feed?
By mistake, I have deleted an NPM Package from Azure Artifact Feed and then deleted it from Recyclebin also. Now while trying to push the NPM package back to Azure Artifact Feed, I am getting the below error message. How do I push the same package again to Artifact Feed?</p>
```<code>> npm --registry https://pkgs.dev.azure.com/maryodavid0305/Platform/_packaging/test/npm/registry/ publish jdmessenger-1.0.0.tgz
npm notice
npm notice package: @jd-libs/jdmessenger@1.0.0
npm notice === Tarball Contents ===
npm notice 2.1kB dist/cjs/events.js
npm notice 938B  dist/esm/events.js
npm notice 5.2kB dist/cjs/executor.js
npm notice 4.0kB dist/esm/executor.js
npm notice 712B  dist/cjs/index.js
npm notice 87B   dist/esm/index.js
npm notice 1.9kB package.json
npm notice 1.0kB dist/cjs/events.js.map
npm notice 975B  dist/esm/events.js.map
npm notice 3.4kB dist/cjs/executor.js.map
npm notice 3.4kB dist/esm/executor.js.map
npm notice 141B  dist/cjs/index.js.map
npm notice 145B  dist/esm/index.js.map
npm notice 602B  README.md
npm notice 1.0kB dist/cjs/events.d.ts
npm notice 1.0kB dist/esm/events.d.ts
npm notice 1.9kB src/tests/events.spec.ts
npm notice 1.7kB src/events.ts
npm notice 1.3kB dist/cjs/executor.d.ts
npm notice 1.3kB dist/esm/executor.d.ts
npm notice 5.2kB src/tests/executor.spec.ts
npm notice 5.8kB src/executor.ts
npm notice 54B   dist/cjs/index.d.ts
npm notice 54B   dist/esm/index.d.ts
npm notice 54B   src/index.ts
npm notice === Tarball Details ===
npm notice name:          @jd-libs/jdmessenger
npm notice version:       1.0.0
npm notice package size:  8.8 kB
npm notice unpacked size: 44.1 kB
npm notice shasum:        294b8c616c6a846d1b5ef72fca3df4412c1830d4
npm notice integrity:     sha512-3Q3rsjeOMUms7[...]NVf6QC56tHDyw==
npm notice total files:   25
npm notice
npm ERR! code E403
npm ERR! 403 403 Forbidden - The version 1.0.0 of @jd-libs/jdmessenger has been deleted. It cannot be restored or pushed. (DevOps Activity ID: 54385895-A886-4BB4-A948-AF65CEE0F8A7) - PUT https://pkgs.dev.azure.com/maryodavid0305/Platform/_packaging/test/npm/registry/@jd-libs%2fjdmessenger - The version 1.0.0 of @jd-libs/jdmessenger has been deleted. It cannot be restored or pushed.
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\maryo\AppData\Roaming\npm-cache\_logs\2022-02-09T09_50_24_857Z-debug.log
</code>```

答:
The only way to do this, as I know, is pushing another version.

If possible, upgrade version number, i.e. 1.0.1, and push it.

Body:
By mistake, I have deleted an NPM Package from Azure Artifact Feed and then deleted it from Recyclebin also. Now while trying to push the NPM package back to Azure Artifact Feed, I am getting the below error message. How do I push the same package again to Artifact Feed?

> npm --registry https://pkgs.dev.azure.com/maryodavid0305/Platform/_packaging/test/npm/registry/ publish jdmessenger-1.0.0.tgz
npm notice
npm notice package: @jd-libs/jdmessenger@1.0.0
npm notice === Tarball Contents ===
npm notice 2.1kB dist/cjs/events.js
npm notice 938B  dist/esm/events.js
npm notice 5.2kB dist/cjs/executor.js
npm notice 4.0kB dist/esm/executor.js
npm notice 712B  dist/cjs/index.js
npm notice 87B   dist/esm/index.js
npm notice 1.9kB package.json
npm notice 1.0kB dist/cjs/events.js.map
npm notice 975B  dist/esm/events.js.map
npm notice 3.4kB dist/cjs/executor.js.map
npm notice 3.4kB dist/esm/executor.js.map
npm notice 141B  dist/cjs/index.js.map
npm notice 145B  dist/esm/index.js.map
npm notice 602B  README.md
npm notice 1.0kB dist/cjs/events.d.ts
npm notice 1.0kB dist/esm/events.d.ts
npm notice 1.9kB src/tests/events.spec.ts
npm notice 1.7kB src/events.ts
npm notice 1.3kB dist/cjs/executor.d.ts
npm notice 1.3kB dist/esm/executor.d.ts
npm notice 5.2kB src/tests/executor.spec.ts
npm notice 5.8kB src/executor.ts
npm notice 54B   dist/cjs/index.d.ts
npm notice 54B   dist/esm/index.d.ts
npm notice 54B   src/index.ts
npm notice === Tarball Details ===
npm notice name:          @jd-libs/jdmessenger
npm notice version:       1.0.0
npm notice package size:  8.8 kB
npm notice unpacked size: 44.1 kB
npm notice shasum:        294b8c616c6a846d1b5ef72fca3df4412c1830d4
npm notice integrity:     sha512-3Q3rsjeOMUms7[...]NVf6QC56tHDyw==
npm notice total files:   25
npm notice
npm ERR! code E403
npm ERR! 403 403 Forbidden - The version 1.0.0 of @jd-libs/jdmessenger has been deleted. It cannot be restored or pushed. (DevOps Activity ID: 54385895-A886-4BB4-A948-AF65CEE0F8A7) - PUT https://pkgs.dev.azure.com/maryodavid0305/Platform/_packaging/test/npm/registry/@jd-libs%2fjdmessenger - The version 1.0.0 of @jd-libs/jdmessenger has been deleted. It cannot be restored or pushed.
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\maryo\AppData\Roaming\npm-cache\_logs\2022-02-09T09_50_24_857Z-debug.log


问:
upgrade to spring boot by keeping the old xml config gives error : Attribute 'local' is not allowed to appear in element 'ref'
I was upgrading a project to spring boot, which is in an old version of spring now.

There is a dependency in this project (I don't have control in it) which is still in old spring.
This dependency provides a context xml config file , which is imported in the application context file of the project I am upgrading, as shown below.

```<code><import resource="classpath:applicationContext-accesscontrol.xml" />
</code>```

But, in this imported xml file local ref is used which is not allowed in new spring.

```<code><list>
                <ref local="bean1" />
                <ref local="bean2" />
            </list>
</code>```

When I run the application I am getting below error in the log:

Caused by: org.xml.sax.SAXParseException; lineNumber: 82;
columnNumber: 39; cvc-complex-type.3.2.2: Attribute 'local' is not
allowed to appear in element 'ref'.   at
java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
at
java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:135)
at
java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)

How can I make it work when I don't have control in this old versioned dependency?

答:
As mentioned in

When to use <ref bean> and when to use <ref local> in Spring?

local is not supported. So use bean instead of local in applicationContext-accesscontrol.xml :

```<code>            <list>
                <ref bean="bean1" />
                <ref bean="bean2" />
            </list>
</code>```

Body:
I was upgrading a project to spring boot, which is in an old version of spring now.

There is a dependency in this project (I don't have control in it) which is still in old spring.
This dependency provides a context xml config file , which is imported in the application context file of the project I am upgrading, as shown below.

<import resource="classpath:applicationContext-accesscontrol.xml" />

But, in this imported xml file local ref is used which is not allowed in new spring.

<list>
                <ref local="bean1" />
                <ref local="bean2" />
            </list>

When I run the application I am getting below error in the log:

Caused by: org.xml.sax.SAXParseException; lineNumber: 82;
columnNumber: 39; cvc-complex-type.3.2.2: Attribute 'local' is not
allowed to appear in element 'ref'.   at
java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
at
java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:135)
at
java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)

How can I make it work when I don't have control in this old versioned dependency?

Body:
As mentioned in

When to use <ref bean> and when to use <ref local> in Spring?

local is not supported. So use bean instead of local in applicationContext-accesscontrol.xml :

            <list>
                <ref bean="bean1" />
                <ref bean="bean2" />
            </list>


问:
randomized data trasnformation in pytorch
I want to rotate all the images in my Dataset with a random degree between [0,180]. If I compose a transformation function and pass my images to this function in the __getitem__ function of my Dataset class. Does this mean:

every single image is randomly rotated?

images in each batch get rotated with an identical degree but this degree randomly changes across batches (calls)?

I would appreciate it if you could clarify this for me.

答:
In mapped datasets, __getitem__ is used to select a single element from the dataset.

The way random transformations work in PyTorch/Torchvision is they apply a unique random transformation each time the transform is called. This means:

Every single image in your dataset is indeed randomly rotated but not by the same amount.

Additionally images in a batch get different transformations. In other words, elements in the batch won't share the same transformation parameters.

Here is a minimal example with a dummy dataset:

```<code>class D(Dataset):
    def __init__(self, n):
        super().__init__()
        self.n = n
        self.transforms = T.Lambda(lambda x: x*randint(0,10))

    def __len__(self):
        return self.n

    def __getitem__(self, index):
        x = self.transforms(index)
        return x
</code>```

Here you can see the random transformer inter and intra batches:

```<code>>>> dl = DataLoader(D(10), batch_size=2)

>>> for i, x  in enumerate(dl):
...     print(f'batch {i}: elements {2*i} and {2*i+1} = {x.tolist()}')
batch 0: elements 0 and 1 = [0, 2]
batch 1: elements 2 and 3 = [14, 27]
batch 2: elements 4 and 5 = [32, 40]
batch 3: elements 6 and 7 = [60, 0]
batch 4: elements 8 and 9 = [80, 27]
</code>```

Body:
In mapped datasets, __getitem__ is used to select a single element from the dataset.

The way random transformations work in PyTorch/Torchvision is they apply a unique random transformation each time the transform is called. This means:

Every single image in your dataset is indeed randomly rotated but not by the same amount.

Additionally images in a batch get different transformations. In other words, elements in the batch won't share the same transformation parameters.

Here is a minimal example with a dummy dataset:

class D(Dataset):
    def __init__(self, n):
        super().__init__()
        self.n = n
        self.transforms = T.Lambda(lambda x: x*randint(0,10))

    def __len__(self):
        return self.n

    def __getitem__(self, index):
        x = self.transforms(index)
        return x

Here you can see the random transformer inter and intra batches:

>>> dl = DataLoader(D(10), batch_size=2)

>>> for i, x  in enumerate(dl):
...     print(f'batch {i}: elements {2*i} and {2*i+1} = {x.tolist()}')
batch 0: elements 0 and 1 = [0, 2]
batch 1: elements 2 and 3 = [14, 27]
batch 2: elements 4 and 5 = [32, 40]
batch 3: elements 6 and 7 = [60, 0]
batch 4: elements 8 and 9 = [80, 27]


问:
:confirm in rails not working
I just started coding in ruby on rails and I've been following a guide which is using a more outdated version of rails than I am using.  I am using 3.2.12

This is my code:

```<code><%= button_to 'Destroy', product, :method => "delete", :confirm => 'Are you sure?'  %>
</code>```

From what I understand, these are symbols that are passed to rails, which is then converted to either an html or javascript action that then pops up the message box and deletes the object if applicable.  The above code destroys the object, but it does not pop up the confirm box.  Why is this?   Also, I had the above as the following at first:

```<code><%= link_to 'Destroy', product, :method => "delete", :confirm => 'Are you sure?'  %>
</code>```

The confirm box is not popping up under any circumstance, using link_to or button_to.  Below is the html rendered when inspected using Chrome's inspector.  jquery and jquery-ujs are loaded into the  as well, so I'm not sure where to go from here.

```<code><input name="_method" type="hidden" value="delete">
<input data-confirm="Are you sureeee?" type="submit" value="Destroy">
<input name="authenticity_token" type="hidden" value="Q2xicqELHYHtrwarbtPBe5PT2bZgWV5C+JdcReJI8ig=">
</code>```

Thanks!

答:
If you want to delete something with confirmation box in rails 7, you may try this one:

With button_to (more prefered IMHO):

```<code><%= button_to 'Destroy', product, method: :delete,
  form: {data: {turbo_confirm: 'Are you sure?'}} %>
</code>```

This will render an HTML form tag which sends a POST request on submit (after confirmation) but with a hidden _method attribute with 'delete' value. So that rails will treat this request as if it has a DELETE method.

It will be routed to products#destroy (or whatever your routes are saying).

With link_to:

```<code><%= link_to 'Destroy', product,
  data: {turbo_method: :delete, turbo_confirm: 'Sure?'} %>
</code>```

This will render a simple a tag with data-turbo-method and data-turbo-confirm attributes. Clicking this link will trigger a confirmation box and if "OK" is chosed, a real DELETE request will be sent.

If you want to end destroy action in your controller with a redirect_to, some browsers will redirect to a new location with DELETE method (causing errors), so make sure to add status: :see_other parameter, like the guides suggests.

Title: :confirm in rails not working

Body:
I just started coding in ruby on rails and I've been following a guide which is using a more outdated version of rails than I am using.  I am using 3.2.12

This is my code:

<%= button_to 'Destroy', product, :method => "delete", :confirm => 'Are you sure?'  %>

From what I understand, these are symbols that are passed to rails, which is then converted to either an html or javascript action that then pops up the message box and deletes the object if applicable.  The above code destroys the object, but it does not pop up the confirm box.  Why is this?   Also, I had the above as the following at first:

<%= link_to 'Destroy', product, :method => "delete", :confirm => 'Are you sure?'  %>

The confirm box is not popping up under any circumstance, using link_to or button_to.  Below is the html rendered when inspected using Chrome's inspector.  jquery and jquery-ujs are loaded into the  as well, so I'm not sure where to go from here.

<input name="_method" type="hidden" value="delete">
<input data-confirm="Are you sureeee?" type="submit" value="Destroy">
<input name="authenticity_token" type="hidden" value="Q2xicqELHYHtrwarbtPBe5PT2bZgWV5C+JdcReJI8ig=">

Thanks!

Body:
If you want to delete something with confirmation box in rails 7, you may try this one:

With button_to (more prefered IMHO):

<%= button_to 'Destroy', product, method: :delete,
  form: {data: {turbo_confirm: 'Are you sure?'}} %>

This will render an HTML form tag which sends a POST request on submit (after confirmation) but with a hidden _method attribute with 'delete' value. So that rails will treat this request as if it has a DELETE method.

It will be routed to products#destroy (or whatever your routes are saying).

With link_to:

<%= link_to 'Destroy', product,
  data: {turbo_method: :delete, turbo_confirm: 'Sure?'} %>

This will render a simple a tag with data-turbo-method and data-turbo-confirm attributes. Clicking this link will trigger a confirmation box and if "OK" is chosed, a real DELETE request will be sent.

If you want to end destroy action in your controller with a redirect_to, some browsers will redirect to a new location with DELETE method (causing errors), so make sure to add status: :see_other parameter, like the guides suggests.


问:
How to combine hierarchical lists into one while respecting the hierarchy of each one of them using networkx and python?
For a medical application I want to combine several lists into one list. The items in each list represent actions to be taken for a specific disease.
For instance the list Malaria would look like that:

'Give Malaria medication'

'Give antibiotics'

'Tell patient to come back tomorrow'

'Give a warm lemon tea'

A second list for Bacterial sore throat would be this:

'Give antibiotics'

'Give paracetamol'

'Give a warm lemon tea'

'Warm the patient'

The actions in each list are hierarchical. That means that the more important tasks are mentioned first.

The lists themselves have a hierarchy as well, so Malaria is higher than Bacterial sore throat.

I need to combine those lists into a global one, that has the items sorted in a way that both hierarchies are preserved. This would be the case that a patient has both Malaria AND Bacterial sore throat and receives treatment according to the importance of each action.

For this case I would want this list:

'Give Malaria medication' (from Malaria list because it is higher than sore throat)

'Give antibiotics' (covers an action from both lists)

'Tell patient to come back tomorrow' (from Malaria list)

'Give Paracetamol' (more important than warm tea as seen in sore throat)

'Give a warm lemon tea' (covers an action from both lists)

'Warm the patient'

Currently this sorting is done by hand, but it becomes too complex with 50+ diseases.
I have looked into networkx trying to do a topological sort but I guess this is not the right approach.

It becomes more complex when sorting is not possible and the actions are in reverse order.
For instance in Diarrhoea there are

make the patient drink

give treatment

while in Severe Diarrhoea these are in reverse order

give treatment

make the patient drink

In this case I want the solution to double an item in the global list to

give treatment

make the patient drink

give treatment

Is there a way to solve at least one of those steps?

答:
I agree with @Corralien that once you have a DAG, topological sort is still the way to go. You just have to break the ties between elements that are at the same hierarchy level correctly. This can be done with nx.lexicographical_topological_sort.

```<code>import networkx as nx

malaria = ['give malaria medication', 'give antibiotics', 'tell patient to come back tomorrow', 'give warm lemon tea']
bacterial_sore_throat = ['give antibiotics', 'give paracetamol', 'give warm lemon tea', 'warm patient']

edges = list(zip(malaria[:-1], malaria[1:])) + list(zip(bacterial_sore_throat[:-1], bacterial_sore_throat[1:]))
graph = nx.from_edgelist(edges, nx.DiGraph)

def sort_function(item):
    if item in malaria:
        return '01'
    elif item in bacterial_sore_throat:
        return '02'
    else:
        raise ValueError

print(list(nx.lexicographical_topological_sort(graph, sort_function)))

# ['give malaria medication', 'give antibiotics', 'tell patient to come back tomorrow', 'give paracetamol', 'give warm lemon tea', 'warm patient']
</code>```

Body:
I agree with @Corralien that once you have a DAG, topological sort is still the way to go. You just have to break the ties between elements that are at the same hierarchy level correctly. This can be done with nx.lexicographical_topological_sort.

import networkx as nx

malaria = ['give malaria medication', 'give antibiotics', 'tell patient to come back tomorrow', 'give warm lemon tea']
bacterial_sore_throat = ['give antibiotics', 'give paracetamol', 'give warm lemon tea', 'warm patient']

edges = list(zip(malaria[:-1], malaria[1:])) + list(zip(bacterial_sore_throat[:-1], bacterial_sore_throat[1:]))
graph = nx.from_edgelist(edges, nx.DiGraph)

def sort_function(item):
    if item in malaria:
        return '01'
    elif item in bacterial_sore_throat:
        return '02'
    else:
        raise ValueError

print(list(nx.lexicographical_topological_sort(graph, sort_function)))

# ['give malaria medication', 'give antibiotics', 'tell patient to come back tomorrow', 'give paracetamol', 'give warm lemon tea', 'warm patient']


问:
Drop duplicates horizontal in pandas python
Sorry I cant figure out how to drop duplicate values but horizontal. The function drop_duplicate does not have a index parameter.

So i have one dataframe

contact
phone1
phone2
phone3
phone4

1
1234

1234

2

12345

12345

And I want to have the following dataframe:

contact
phone1
phone2
phone3
phone4

1
1234

2

12345

答:
Option 1: Can use stack and reindex

```<code>df.stack().drop_duplicates().unstack().reindex(columns=df.columns).fillna('')

  contact  phone1   phone2 phone3 phone4
0      1.0  1234.0
1      2.0          12345.0
</code>```

Option2:To replace duplicates row wise, please try first NaN with 0 (a value that does not exist in the df). Mask the duplicates and fill them with '', then replace 0 with NaN to restore the df

```<code>df.fillna(0).mask(df.apply(lambda x: x.duplicated(), axis=1)).fillna('').replace(0,np.nan)

  contact  phone1   phone2   phone3 phone4
0        1  1234.0      NaN
1        2     NaN  12345.0
</code>```

Option 3:

To achieve your outcome as put. We can  just:

```<code>df.mask(df.apply(lambda x: x.duplicated(), axis=1)).fillna('')

contact  phone1   phone2 phone3 phone4
0      1.0  1234.0
1      2.0          12345.0
</code>```

Body:
Option 1: Can use stack and reindex

df.stack().drop_duplicates().unstack().reindex(columns=df.columns).fillna('')

  contact  phone1   phone2 phone3 phone4
0      1.0  1234.0
1      2.0          12345.0

Option2:To replace duplicates row wise, please try first NaN with 0 (a value that does not exist in the df). Mask the duplicates and fill them with '', then replace 0 with NaN to restore the df

df.fillna(0).mask(df.apply(lambda x: x.duplicated(), axis=1)).fillna('').replace(0,np.nan)

  contact  phone1   phone2   phone3 phone4
0        1  1234.0      NaN
1        2     NaN  12345.0

Option 3:

To achieve your outcome as put. We can  just:

df.mask(df.apply(lambda x: x.duplicated(), axis=1)).fillna('')

contact  phone1   phone2 phone3 phone4
0      1.0  1234.0
1      2.0          12345.0