问:
HashMap Serializability
HashMap implements the Serializable interface; so it can be serialized. I have looked at the implementation of HashMap and the Entry[] table is marked as transient. Since the Entry[] table is the one that stores the entire contents of the Map and if it cannot be serialized, how is the Map constructed back during de-serialization</p>

答:
If you look at the source you will see that it does not rely on the default serialization mechanism, but manually writes out all the entries (as an alternating stream of keys and values):

```<code>/**
  * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
  * serialize it)
  *
  * @serialData The <i>capacity</i> of the HashMap (the length of the
  *             bucket array) is emitted (int), followed by the
  *             <i>size</i> (an int, the number of key-value
  *             mappings), followed by the key (Object) and value (Object)
  *             for each key-value mapping.  The key-value mappings are
  *             emitted in no particular order.
  */
      private void writeObject(java.io.ObjectOutputStream s)
             throws IOException
         {
             Iterator<Map.Entry<K,V>> i =
                 (size > 0) ? entrySet0().iterator() : null;

            // Write out the threshold, loadfactor, and any hidden stuff
            s.defaultWriteObject();

            // Write out number of buckets
            s.writeInt(table.length);

            // Write out size (number of Mappings)
            s.writeInt(size);

            // Write out keys and values (alternating)
            if (i != null) {
                while (i.hasNext()) {
                    Map.Entry<K,V> e = i.next();
                    s.writeObject(e.getKey());
                    s.writeObject(e.getValue());
                }
            }
        }
</code>```

This is more compact than the array, which can contain many empty entries and link chains and overhead for Map$Entry wrappers.

Note that it still invokes defaultWriteObject for the "easy" fields. In order for that to work, it has to mark everything else as transient.

Title: HashMap Serializability

Body:
If you look at the source you will see that it does not rely on the default serialization mechanism, but manually writes out all the entries (as an alternating stream of keys and values):

/**
  * Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
  * serialize it)
  *
  * @serialData The <i>capacity</i> of the HashMap (the length of the
  *             bucket array) is emitted (int), followed by the
  *             <i>size</i> (an int, the number of key-value
  *             mappings), followed by the key (Object) and value (Object)
  *             for each key-value mapping.  The key-value mappings are
  *             emitted in no particular order.
  */
      private void writeObject(java.io.ObjectOutputStream s)
             throws IOException
         {
             Iterator<Map.Entry<K,V>> i =
                 (size > 0) ? entrySet0().iterator() : null;

            // Write out the threshold, loadfactor, and any hidden stuff
            s.defaultWriteObject();

            // Write out number of buckets
            s.writeInt(table.length);

            // Write out size (number of Mappings)
            s.writeInt(size);

            // Write out keys and values (alternating)
            if (i != null) {
                while (i.hasNext()) {
                    Map.Entry<K,V> e = i.next();
                    s.writeObject(e.getKey());
                    s.writeObject(e.getValue());
                }
            }
        }

This is more compact than the array, which can contain many empty entries and link chains and overhead for Map$Entry wrappers.

Note that it still invokes defaultWriteObject for the "easy" fields. In order for that to work, it has to mark everything else as transient.


来源: stackexchange

问:
Python requests returns 404 error status from today on amazon "sold by" page
There

https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link

I just can access on browser as well, but python requests returns 404 error status.

Until yesterday, this page worked as well with python requests. but from today, it does not work for me and it returns 404 error status.

import requests

headers = {
    'Connection': 'keep-alive',
    'rtt': '300',
    'downlink': '0.4',
    'ect': '3g',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8',
}

response = requests.get(
    'https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link',
    headers=headers
)
print(response.status_code) # 404
```

I really will appreciate if I can get any help from you.

Regards.

答:
It works just fine to me. Maybe you can try changing your user agent.</p>
```<code>import requests
from fake_useragent import UserAgent # fake user agent library

# random user-agent
ua = UserAgent()
user_agent = ua.random

headers = {
    'Connection': 'keep-alive',
    'rtt': '300',
    'downlink': '0.4',
    'ect': '3g',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': user_agent,
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8',
}

response = requests.get(
    'https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link',
     headers=headers
 )

print(response.status_code)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There

https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link

I just can access on browser as well, but python requests returns 404 error status.

Until yesterday, this page worked as well with python requests. but from today, it does not work for me and it returns 404 error status.

import requests

headers = {
    'Connection': 'keep-alive',
    'rtt': '300',
    'downlink': '0.4',
    'ect': '3g',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8',
}

response = requests.get(
    'https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link',
    headers=headers
)
print(response.status_code) # 404

I really will appreciate if I can get any help from you.

Regards.

Body:
It works just fine to me. Maybe you can try changing your user agent.

import requests
from fake_useragent import UserAgent # fake user agent library

# random user-agent
ua = UserAgent()
user_agent = ua.random

headers = {
    'Connection': 'keep-alive',
    'rtt': '300',
    'downlink': '0.4',
    'ect': '3g',
    'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': user_agent,
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Language': 'en-US,en;q=0.9,ko;q=0.8',
}

response = requests.get(
    'https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link',
     headers=headers
 )

print(response.status_code)


问:
Pine-Script - Input actual time as Default
i´m trying to fill a Date input with a default value, the default value should be the actual date.

The original code:

end_time = input.time(defval=timestamp('01 Aug 2021 00:00 +0000'), title='End Time')

I would like to have the actual date as defval.

i tried several things, like timestamp(timenow) but i get always the same error-message:

An argument of 'series int' type was used but a 'const string' is expected

I understand that i bring a int to a string, but how can i convert the actual date/time to fit in the code above?

Thanx for your brains,

答:
The input.*() function defval= argument requires a value known at the compilation time and could not be dynamic.

As a workaround, you can use the interactive feature (confirm= argument) to select the last bar on the chart with a mouse-click:

```<code>//@version=5
indicator("My script")
end_time = input.time(defval=timestamp('01 Aug 2021 00:00 +0000'), title='End Time', confirm = true)
bgcolor(time == end_time ? color.red : na)
</code>```

Body:
The input.*() function defval= argument requires a value known at the compilation time and could not be dynamic.

As a workaround, you can use the interactive feature (confirm= argument) to select the last bar on the chart with a mouse-click:

//@version=5
indicator("My script")
end_time = input.time(defval=timestamp('01 Aug 2021 00:00 +0000'), title='End Time', confirm = true)
bgcolor(time == end_time ? color.red : na)


问:
i created a react native project in windows system but when i want to run in ios OS using npx react-native run-ios it gives me permission denied erro
AppCoderiOS1:ios appcoderios1$ npx react-native start
sh: /Users/appcoderios1/Downloads/ProjectName/node_modules/.bin/react-native: Permission denied
gives me the error when an existing project created in windows OS want to run in ios OS</p>

答:
This happened because you can't run iOS project in machine with Windows.
You can run project in iOS emulator only if you have MacOS.</p>


问:
How to navigate through the mat-vertical-stepper in same component
i am building a website,
In registration form i am using mat-vertical stepper it has 5 mat-steps
1)personal Info
2)Investment profile
3)account Info
4)setup Funding
5)sign in and submit

In sign in and submit all the information from the previous mat-step labels are retrieved with their corresponding mat-step-Labels.

My problem here is each mat-Step-Label has an edit icon when user clicks on it it should go to particular mat-step and edit the content .

答:
This is mat-stepper's default behavior, just follow the official document
https://material.angular.io/components/stepper/overview#stepper-variants

and here is a stack blitz site for your reference
https://stackblitz.com/edit/material-angular-stepper?embed=1&file=src/app/app.component.html


问:
Find the n largest occurrences of duplicate values in a column
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

```<code>"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"
</code>```

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

```<code>"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times
</code>```

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

```<code>"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times
</code>```

答:
Using any sort+awk+head:</p>
```<code>$ sort -t, -k5,5 file |
    awk '
        BEGIN { FS=OFS="," }
        $5 != p5 { if (NR>1) print p0, cnt; p5=$5; p0=$0; cnt=0 }
        { cnt++ }
        END { print p0, cnt }' |
    sort -t, -k6,6rn |
    head -2
"instance id","src IP","destination ip","63812","389",4
"instance id","src IP","destination ip","12489","49194",2
</code>```

Body:
I have a 7GB csv file from which I need to find the first n values which occurred mostly in the 5th column. The format of my file is as:

"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","389","65311"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","88","49194"
"instance id","src IP","destination ip","12489","49194"
"instance id","src IP","destination ip","63812","389"
"instance id","src IP","destination ip","63812","389"

Using the following command
awk -F , ' !count[$5]++ {save[$5] = $0; next} count[$5] > 0 { print save[$5] " is " count[$5] " times"} ' example.csv
able to find the following output

"instance id","src IP","destination ip","63812","389" is 1 times
"instance id","src IP","destination ip","389","65311" is 1 times
"instance id","src IP","destination ip","63812","389" is 2 times
"instance id","src IP","destination ip","88","49194" is 1 times
"instance id","src IP","destination ip","12489","49194" is 2 times
"instance id","src IP","destination ip","63812","389" is 3 times
"instance id","src IP","destination ip","63812","389" is 4 times

but not able to understand how to get the top 50 rows in which the 5th column entry duplicated most of the time.

Let's suppose if n=2, then my output should be like following:

"instance id","src IP","destination ip","63812","389" is 4 times
"instance id","src IP","destination ip","12489","49194" is 2 times

Body:
Using any sort+awk+head:

$ sort -t, -k5,5 file |
    awk '
        BEGIN { FS=OFS="," }
        $5 != p5 { if (NR>1) print p0, cnt; p5=$5; p0=$0; cnt=0 }
        { cnt++ }
        END { print p0, cnt }' |
    sort -t, -k6,6rn |
    head -2
"instance id","src IP","destination ip","63812","389",4
"instance id","src IP","destination ip","12489","49194",2


问:
grapql@16 dropped long-deprecated support for positional arguments, please pass an object instead
```<code>    const { ApolloServer, gql } = require('apollo-server');

    // A schema is a collection of type definitions (hence "typeDefs")
    // that together define the "shape" of queries that are executed against
    // your data.
    const typeDefs = gql`
      # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

      # This "Book" type defines the queryable fields for every book in our data source.
      type Book {
        title: String
        author: String
      }

      # The "Query" type is special: it lists all of the available queries that
      # clients can execute, along with the return type for each. In this
      # case, the "books" query returns an array of zero or more Books (defined above).
      type Query {
        books: [Book]
      }
    `;
const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
];

// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
  Query: {
    books: () => books,
  },
};

// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });

// The `listen` method launches a web server.
server.listen().then(({ url }) => {
  console.log(`  Server ready at ${url}`);
});
</code>```

So this is the code I copied from official Apollo GraphQL site. I use graphql 16.3 and apollo-server 2.25.3.
I don't know what the message told me what to fix. Help me please. Thank you guys so much!

答:
From their documentation it seems that apollo-server 2 don't support graphql >15

https://www.apollographql.com/docs/apollo-server/migration/

I would either migrate to apollo-server 3 or downgrade graphql to version 15.

Body:
    const { ApolloServer, gql } = require('apollo-server');

    // A schema is a collection of type definitions (hence "typeDefs")
    // that together define the "shape" of queries that are executed against
    // your data.
    const typeDefs = gql`
      # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

      # This "Book" type defines the queryable fields for every book in our data source.
      type Book {
        title: String
        author: String
      }

      # The "Query" type is special: it lists all of the available queries that
      # clients can execute, along with the return type for each. In this
      # case, the "books" query returns an array of zero or more Books (defined above).
      type Query {
        books: [Book]
      }
    `;
const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
];

// Resolvers define the technique for fetching the types defined in the
// schema. This resolver retrieves books from the "books" array above.
const resolvers = {
  Query: {
    books: () => books,
  },
};

// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });

// The `listen` method launches a web server.
server.listen().then(({ url }) => {
  console.log(`  Server ready at ${url}`);
});

So this is the code I copied from official Apollo GraphQL site. I use graphql 16.3 and apollo-server 2.25.3.
I don't know what the message told me what to fix. Help me please. Thank you guys so much!


问:
Interoperability between OpenCV Python interface and a ctypes library
I'm using the Python interface from OpenCV 2.3. I have a library written in C that expects, as arguments, OpenCV objects such as IplImage. Like this:

```<code>void MyFunction(IplImage* image);
</code>```

I wish, from my Python code, to call this function. I've tried:

```<code>library.MyFunction(image)
</code>```

But it gives me an error:

```<code>ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
</code>```

I've also tried to use byref but it still doesn't works:

```<code>TypeError: byref() argument must be a ctypes instance, not 'cv.iplimage'
</code>```

How do I do this?

答:
cv.iplimage is a CPython object defined by iplimage_t. It wraps the IplImage pointer that you need. There are a few ways to get at this pointer. I'll use the fact that CPython id returns the object base address.

```<code>import cv, cv2
from ctypes import *
</code>```

You could use c_void_p instead of defining IplImage. I define it below in order to demonstrate that the pointer is correct.

```<code>class IplROI(Structure):
    pass

class IplTileInfo(Structure):
    pass

class IplImage(Structure):
    pass

IplImage._fields_ = [
    ('nSize', c_int),
    ('ID', c_int),
    ('nChannels', c_int),
    ('alphaChannel', c_int),
    ('depth', c_int),
    ('colorModel', c_char * 4),
    ('channelSeq', c_char * 4),
    ('dataOrder', c_int),
    ('origin', c_int),
    ('align', c_int),
    ('width', c_int),
    ('height', c_int),
    ('roi', POINTER(IplROI)),
    ('maskROI', POINTER(IplImage)),
    ('imageId', c_void_p),
    ('tileInfo', POINTER(IplTileInfo)),
    ('imageSize', c_int),
    ('imageData', c_char_p),
    ('widthStep', c_int),
    ('BorderMode', c_int * 4),
    ('BorderConst', c_int * 4),
    ('imageDataOrigin', c_char_p)]
</code>```

The CPython object:

```<code>class iplimage_t(Structure):
    _fields_ = [('ob_refcnt', c_ssize_t),
                ('ob_type',  py_object),
                ('a', POINTER(IplImage)),
                ('data', py_object),
                ('offset', c_size_t)]
</code>```

Load an example as an iplimage:

```<code>data = cv2.imread('lena.jpg')  # 512 x 512
step = data.dtype.itemsize * 3 * data.shape[1]
size = data.shape[1], data.shape[0]
img = cv.CreateImageHeader(size, cv.IPL_DEPTH_8U, 3)
cv.SetData(img, data, step)
</code>```

In CPython the id of img is its base address. Using ctypes you have direct access to the a field of this object, i.e. the IplImage * that you need.

```<code>>>> ipl = iplimage_t.from_address(id(img))
>>> a = ipl.a.contents
>>> a.nChannels
3
>>> a.depth
8
>>> a.colorModel
'RGB'
>>> a.width
512
>>> a.height
512
>>> a.imageSize
786432
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Python interface from OpenCV 2.3. I have a library written in C that expects, as arguments, OpenCV objects such as IplImage. Like this:

void MyFunction(IplImage* image);

I wish, from my Python code, to call this function. I've tried:

library.MyFunction(image)

But it gives me an error:

ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1

I've also tried to use byref but it still doesn't works:

TypeError: byref() argument must be a ctypes instance, not 'cv.iplimage'

How do I do this?

Body:
cv.iplimage is a CPython object defined by iplimage_t. It wraps the IplImage pointer that you need. There are a few ways to get at this pointer. I'll use the fact that CPython id returns the object base address.

import cv, cv2
from ctypes import *

You could use c_void_p instead of defining IplImage. I define it below in order to demonstrate that the pointer is correct.

class IplROI(Structure):
    pass

class IplTileInfo(Structure):
    pass

class IplImage(Structure):
    pass

IplImage._fields_ = [
    ('nSize', c_int),
    ('ID', c_int),
    ('nChannels', c_int),
    ('alphaChannel', c_int),
    ('depth', c_int),
    ('colorModel', c_char * 4),
    ('channelSeq', c_char * 4),
    ('dataOrder', c_int),
    ('origin', c_int),
    ('align', c_int),
    ('width', c_int),
    ('height', c_int),
    ('roi', POINTER(IplROI)),
    ('maskROI', POINTER(IplImage)),
    ('imageId', c_void_p),
    ('tileInfo', POINTER(IplTileInfo)),
    ('imageSize', c_int),
    ('imageData', c_char_p),
    ('widthStep', c_int),
    ('BorderMode', c_int * 4),
    ('BorderConst', c_int * 4),
    ('imageDataOrigin', c_char_p)]

The CPython object:

class iplimage_t(Structure):
    _fields_ = [('ob_refcnt', c_ssize_t),
                ('ob_type',  py_object),
                ('a', POINTER(IplImage)),
                ('data', py_object),
                ('offset', c_size_t)]

Load an example as an iplimage:

data = cv2.imread('lena.jpg')  # 512 x 512
step = data.dtype.itemsize * 3 * data.shape[1]
size = data.shape[1], data.shape[0]
img = cv.CreateImageHeader(size, cv.IPL_DEPTH_8U, 3)
cv.SetData(img, data, step)

In CPython the id of img is its base address. Using ctypes you have direct access to the a field of this object, i.e. the IplImage * that you need.

>>> ipl = iplimage_t.from_address(id(img))
>>> a = ipl.a.contents
>>> a.nChannels
3
>>> a.depth
8
>>> a.colorModel
'RGB'
>>> a.width
512
>>> a.height
512
>>> a.imageSize
786432


问:
How to draw outside sprites boundaries with Unity's shaders?
I'm learning how to make shader in Unity and I have a question about shaders applied on sprites.

I made a shader which modifies a sprite to create a distortion effect:

But, as you can see on the picture linked above, my sprite is cut on the boundaries of the sprite.

Is there any way to avoid this cut and draw the missing part ?

My shader :

```<code>Shader "Shader101/testShader"
{
    Properties
    {
        _MainTex( "Texture", 2D ) = "white" {}
        _DisplaceTex( "Displacement Texture", 2D ) = "white" {}
        _Power("Power", Range(-0.4, 0.4)) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
        }

        Pass
        {
            Blend SrcAlpha OneMinusSrcAlpha

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = mul( UNITY_MATRIX_MVP, v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _DisplaceTex;
            float _Power;

            fixed4 frag (v2f i) : SV_Target
            {
                float2 distuv = float2( 0, i.uv.y + _Time.x * 2 );

                float2 wave = tex2D( _DisplaceTex, distuv * 5  ).xy;
                wave = (( wave * 2 ) - 1) * _Power - 0.25;

                float4 color = tex2D( _MainTex, i.uv + float2(wave.y, 0) );
                return color;
            }
            ENDCG
        }
    }
}
</code>```

Sorry for my poor english :|

Thank you

答:
This is still a high search result without a satisfactory answer.
Two settings may help:

Extrude edges - Adds padding around the sprite

Full Rect - Required if you manually add extra space around a sprite, causes the wireframe to use all the empty space, instead of just the opaque areas.

Body:
I'm learning how to make shader in Unity and I have a question about shaders applied on sprites.

I made a shader which modifies a sprite to create a distortion effect:

But, as you can see on the picture linked above, my sprite is cut on the boundaries of the sprite.

Is there any way to avoid this cut and draw the missing part ?

My shader :

Shader "Shader101/testShader"
{
    Properties
    {
        _MainTex( "Texture", 2D ) = "white" {}
        _DisplaceTex( "Displacement Texture", 2D ) = "white" {}
        _Power("Power", Range(-0.4, 0.4)) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
        }

        Pass
        {
            Blend SrcAlpha OneMinusSrcAlpha

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = mul( UNITY_MATRIX_MVP, v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _DisplaceTex;
            float _Power;

            fixed4 frag (v2f i) : SV_Target
            {
                float2 distuv = float2( 0, i.uv.y + _Time.x * 2 );

                float2 wave = tex2D( _DisplaceTex, distuv * 5  ).xy;
                wave = (( wave * 2 ) - 1) * _Power - 0.25;

                float4 color = tex2D( _MainTex, i.uv + float2(wave.y, 0) );
                return color;
            }
            ENDCG
        }
    }
}

Sorry for my poor english :|

Thank you


问:
Node js path file
My csv file is in drive 'E' folder 'awais' and i am new to coding i cant access the file anybody can help me with relative path absolute path concept and how can i access this file

i am getting this error : "Unhandled rejection Error: File does not exist. Check to make sure the file path to your csv is correct."

```<code>const fs = require('fs')
const path = require('path')

const csv = require('csvtojson');

const csvFile = ('/E/Awais/customer-data.csv');

csv()
.fromFile(csvFile).then ( (jsonObj) =>{
    console.log(jsonObj)
    fs.writeFile(path.join(__dirname,'customer-data.json'),JSON.stringify(jsonObj,null,1),()=>{
        console.log(jsonObj)
});
})
```

```

答:
You might wanna try:

const csvFile = ('E:/Awais/customer-data.csv');
```
<p>That would be an absolute path. If you want to use a relative path (meaning that the csv is located in a folder relative to where your code file is stored) you would need to let us know in which folder your code resides. Alternatively (since you already imported path) you could also do:</p>
<pre class="lang-js prettyprint-override"><code>const csvFile = path.normalize('E:\\Awais\\customer-data.csv');
</code>```

Title: Node js path file

Body:
My csv file is in drive 'E' folder 'awais' and i am new to coding i cant access the file anybody can help me with relative path absolute path concept and how can i access this file

i am getting this error : "Unhandled rejection Error: File does not exist. Check to make sure the file path to your csv is correct."

const fs = require('fs')
const path = require('path')

const csv = require('csvtojson');

const csvFile = ('/E/Awais/customer-data.csv');

csv()
.fromFile(csvFile).then ( (jsonObj) =>{
    console.log(jsonObj)
    fs.writeFile(path.join(__dirname,'customer-data.json'),JSON.stringify(jsonObj,null,1),()=>{
        console.log(jsonObj)
});
})
```

Body:
You might wanna try:

const csvFile = ('E:/Awais/customer-data.csv');

That would be an absolute path. If you want to use a relative path (meaning that the csv is located in a folder relative to where your code file is stored) you would need to let us know in which folder your code resides. Alternatively (since you already imported path) you could also do:

const csvFile = path.normalize('E:\\Awais\\customer-data.csv');


问:
Git Describe NPM not providing Tag information
I am trying Git-Describe npm package to retrieve hash information and tag to append to my application later.

I have following the instruction that are provided in the Git describe npm page. The script worked well but the tag information is retrieved as null here. Also I have added few tags in the local and my remote git.

I am able to retrieve all the tag information using git tag -l

The below is the script that I was trying to run.

```<code>const {gitDescribe, gitDescribeSync} = require('git-describe');

// Another example: working directory, use 16 character commit hash abbreviation
const gitInfo = gitDescribeSync({
    customArguments: ['--abbrev=16']
});

// Asynchronous with promise
gitDescribe(__dirname)
    .then((gitInfo) => console.dir(gitInfo))
    .catch((err) => console.error(err));

// Asynchronous with node-style callback
gitDescribe(__dirname, (err, gitInfo) => {
    if (err)
        return console.error(err);
    console.dir(gitInfo);
});
</code>```

node version.js

Output is:

```<code>{
  dirty: true,
  raw: 'f8f7e57e-dirty',
  hash: 'f8f7e57e',
  distance: null,
  tag: null,
  semver: null,
  suffix: 'f8f7e57e-dirty',
  semverString: null,
  toString: [Function]
}
</code>```

Here the tag info are coming with null. But the hash string is correct. (Git log output).

```<code>commit **f8f7e57e**713b71b0f9d3181c0d19ffd (HEAD -> PF223095_US1834348_ui_gitcommit, tag: r9.0.6, origin/PF223095_US1834348_ui_gitcommit, mastere)
</code>```

答:
As @zxiiro said, the default behaviour is to look for tags starting with v followed by a digit (v0.9, v2.3-dev).

You can specify your own regex with the match option, this example will match tags starting with a digit (0.9, 2.3-dev, 99-luft-balloons)

```<code>const gitInfo = gitDescribeSync({match: '[0-9]*'});
</code>```

Body:
I am trying Git-Describe npm package to retrieve hash information and tag to append to my application later.

I have following the instruction that are provided in the Git describe npm page. The script worked well but the tag information is retrieved as null here. Also I have added few tags in the local and my remote git.

I am able to retrieve all the tag information using git tag -l

The below is the script that I was trying to run.

const {gitDescribe, gitDescribeSync} = require('git-describe');

// Another example: working directory, use 16 character commit hash abbreviation
const gitInfo = gitDescribeSync({
    customArguments: ['--abbrev=16']
});

// Asynchronous with promise
gitDescribe(__dirname)
    .then((gitInfo) => console.dir(gitInfo))
    .catch((err) => console.error(err));

// Asynchronous with node-style callback
gitDescribe(__dirname, (err, gitInfo) => {
    if (err)
        return console.error(err);
    console.dir(gitInfo);
});

node version.js

Output is:

{
  dirty: true,
  raw: 'f8f7e57e-dirty',
  hash: 'f8f7e57e',
  distance: null,
  tag: null,
  semver: null,
  suffix: 'f8f7e57e-dirty',
  semverString: null,
  toString: [Function]
}

Here the tag info are coming with null. But the hash string is correct. (Git log output).

commit **f8f7e57e**713b71b0f9d3181c0d19ffd (HEAD -> PF223095_US1834348_ui_gitcommit, tag: r9.0.6, origin/PF223095_US1834348_ui_gitcommit, mastere)

Body:
As @zxiiro said, the default behaviour is to look for tags starting with v followed by a digit (v0.9, v2.3-dev).

You can specify your own regex with the match option, this example will match tags starting with a digit (0.9, 2.3-dev, 99-luft-balloons)

const gitInfo = gitDescribeSync({match: '[0-9]*'});


问:
What is the time complexity of for loop in which the counter starts from 1?
May i know for the outer loop the time complexity is n+1-2? So its n-1

Example

```<code>for(int a=3; a<=n; a++){
  System.out.println(a);
}
</code>```

So i have another question, assume that a < n , so the time complexity would be n-2? Thanks

答:
Your loop

```<code>for(int a=3; a<=n; a++){
    System.out.println(a);
}
</code>```

is running n-2 times, and if you compare it like a < n, the loop stops before 'a' reaches 'n', so n-3 times.

Since per definition for the Big-O-Notation constants don't matter the complexity of your loop is:

O(n-2) = O(n-3) = O(n).

Body:
May i know for the outer loop the time complexity is n+1-2? So its n-1

Example

for(int a=3; a<=n; a++){
  System.out.println(a);
}

So i have another question, assume that a < n , so the time complexity would be n-2? Thanks

Body:
Your loop

for(int a=3; a<=n; a++){
    System.out.println(a);
}

is running n-2 times, and if you compare it like a < n, the loop stops before 'a' reaches 'n', so n-3 times.

Since per definition for the Big-O-Notation constants don't matter the complexity of your loop is:

O(n-2) = O(n-3) = O(n).


问:
Django - Template tags inside css file
I'm trying to modify the css of a page based on the PageSetting model that I'm using. I'm allowing the user the ability to change how the theme of a page looks like based on some of the PageSetting attributes.

```<code>class PageSettings(SingletonModel):
    theme = models.IntegerField(choices=THEMES,
                                verbose_name=_("Theme"),
                                default=0)
    base_color = RGBColorField(blank=False,
                               verbose_name=_("Base color"),
                               default="bc0000")

    ...
</code>```

What I would like to do is change some values in my css depending on base_color. Pretty much something like this:

```<code># inside my_theme.css
.side-bar {
  background: {{ pagesetting.base_color }};
  float:left;
  width: {{ pagesetting.sidebar_width}}%

  ...

}
</code>```

is this acheivble in Django? I know I can do

but this makes my html ugly and harder to debug.

答:
Had the same issue, for me I had to use style tag inside base.html</p>
```<code><style>
@font-face {
    font-family: "Booter - Zero Zero";
    src: url('../static/fonts/Booter\ -\ Zero\ Zero.woff') format('woff'), url('../static/fonts/Booter\ -\ Zero\ Zero.woff2') format('woff2');

    font-weight: normal;
    font-style: normal;
}

.main-header {
    background-color: rgba(0, 0, 0, .6);
    background-image: url(static/images/header_background.jpg);
    background-blend-mode: multiply;
    background-size: cover;
    padding-bottom: 30px;
}
</code>```

Title: Django - Template tags inside css file

Body:
I'm trying to modify the css of a page based on the PageSetting model that I'm using. I'm allowing the user the ability to change how the theme of a page looks like based on some of the PageSetting attributes.

class PageSettings(SingletonModel):
    theme = models.IntegerField(choices=THEMES,
                                verbose_name=_("Theme"),
                                default=0)
    base_color = RGBColorField(blank=False,
                               verbose_name=_("Base color"),
                               default="bc0000")

    ...

What I would like to do is change some values in my css depending on base_color. Pretty much something like this:

# inside my_theme.css
.side-bar {
  background: {{ pagesetting.base_color }};
  float:left;
  width: {{ pagesetting.sidebar_width}}%

  ...

}

is this acheivble in Django? I know I can do

but this makes my html ugly and harder to debug.

Body:
Had the same issue, for me I had to use style tag inside base.html

<style>
@font-face {
    font-family: "Booter - Zero Zero";
    src: url('../static/fonts/Booter\ -\ Zero\ Zero.woff') format('woff'), url('../static/fonts/Booter\ -\ Zero\ Zero.woff2') format('woff2');

    font-weight: normal;
    font-style: normal;
}

.main-header {
    background-color: rgba(0, 0, 0, .6);
    background-image: url(static/images/header_background.jpg);
    background-blend-mode: multiply;
    background-size: cover;
    padding-bottom: 30px;
}


问:
TempDir is null
I want to copy some files into a temporary directory. But the File I annotate with @TempDir does not seem to get injected.

```<code>import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.File;

public class MyTempFileTest {

    @TempDir
    public File tempFolder;

    @Test
    public void testTempFolder() {
        Assertions.assertNotNull(tempFolder);
    }
 }
</code>```

the result is org.opentest4j.AssertionFailedError: expected: not <null>

I would instead expect it to be a random temporary directory, as was the case with @Rule TemporaryFolder tmpSudokus = new TemporaryFolder() in Junit4.

And according to the docs I can annotate a Java.io.File.

If I try to pass the tempDir as a directory

```<code>    @Test
    public void testTempFolderParam(@TempDir File tempFolder) {
        Assertions.assertNotNull(tempFolder);
    }
</code>```

I get org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.io.File tempFolder] in executable [public void my.package.MyTempFileTest.testTempFolderParam(java.io.File)].

The test is part of an android project, my dependencies are:

```<code>dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.2'
}
</code>```

答:
According to documentation Junit5 Docs

The temporary directory is only created if a field in a test class or a parameter in a lifecycle method or test method is annotated with @TempDir. If the field type or parameter type is neither Path nor File or if the temporary directory cannot be created, an ExtensionConfigurationException or a ParameterResolutionException will be thrown as appropriate. In addition, a ParameterResolutionException will be thrown for a constructor parameter annotated with @TempDir.

As I see in your example, you did use java.io.File so I guess your problem is in the creation part of the temporary folder.

I copied your example and it did work, the tempDir was not null

Dependencies :

junit-jupiter:5.7.2

junit-jupiter-engine:5.7.2

junit-jupiter-params:5.7.2

Title: TempDir is null

Body:
I want to copy some files into a temporary directory. But the File I annotate with @TempDir does not seem to get injected.

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.File;

public class MyTempFileTest {

    @TempDir
    public File tempFolder;

    @Test
    public void testTempFolder() {
        Assertions.assertNotNull(tempFolder);
    }
 }

the result is org.opentest4j.AssertionFailedError: expected: not <null>

I would instead expect it to be a random temporary directory, as was the case with @Rule TemporaryFolder tmpSudokus = new TemporaryFolder() in Junit4.

And according to the docs I can annotate a Java.io.File.

If I try to pass the tempDir as a directory

    @Test
    public void testTempFolderParam(@TempDir File tempFolder) {
        Assertions.assertNotNull(tempFolder);
    }

I get org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [java.io.File tempFolder] in executable [public void my.package.MyTempFileTest.testTempFolderParam(java.io.File)].

The test is part of an android project, my dependencies are:

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.2'
    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.7.2'
}


问:
Can we use Boto to deploy Yaml templates?
I am using boto to deploy json templates in AWS. My question is Can i use the same boto library to deploy Templates in Yaml as well.When i tried i got the error no json could be decoded.

If there is a way then please share an example
Thanks.

答:
You can now use a YAML file directly from Boto3:</p>
```<code>try:
    with open(template_file_location, 'r') as content_file:
        content = content_file.read()
except OSError as e:
  # error handling in case error reading file
...
boto3_client.validate_template(TemplateBody=content)
</code>```

Body:
You can now use a YAML file directly from Boto3:

try:
    with open(template_file_location, 'r') as content_file:
        content = content_file.read()
except OSError as e:
  # error handling in case error reading file
...
boto3_client.validate_template(TemplateBody=content)


问:
Optimizing Left Join With Group By and Order By (MariaDb)
I am attempting to optimize a query in MariaDb that is really bogged down by its ORDER BY clause. I can run it in under a tenth of a second without the ORDER BY clause, but it takes over 25 seconds with it. Here is the gist of the query:

```<code>SELECT u.id, u.display_name, u.cell_phone, u.email,
uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM users u
LEFT JOIN user_vehicles uv ON uv.user_id = u.id AND uv.current_owner=1
WHERE u.is_deleted = 0
GROUP BY u.id
ORDER BY u.display_name
LIMIT 0, 10;
</code>```

I need it to be a left join because I want to include users that aren't linked to a vehicle.

I need the group by because I want only 1 result per user (and display_name is not guaranteed to be unique).

users table has about 130K rows, while user_vehicles has about 230K rows.

Here is the EXPLAIN of the query:

```<code>id  select_type table   type    possible_keys   key      key_len  ref           rows    Extra
1   SIMPLE      u       index   dms_cust_idx    PRIMARY  4        null          124825  Using where; Using temporary; Using filesort
1   SIMPLE      uv      ref     user_idx        user_idx 4        awscheduler.u.id  1   Using where

</code>```

I have tried these two indices to speed things up, but they don't seem to do much.

```<code>CREATE INDEX idx_display_speedy ON users(display_name);

CREATE INDEX idx_display_speedy2 ON users(id, display_name, is_deleted, dms_cust_id);
</code>```

I am looking for ideas on how to speed this up. I attempted using nested queries, but since the order by is the bottleneck & order within the nested query is ignored, I believe that attempt was in vain.

答:
how about:

```<code>WITH a AS (
   SELECT u.id, u.display_name, u.cell_phone, u.email
   FROM users u
   WHERE u.is_deleted = 0
   GROUP BY u.id
   LIMIT 0, 10
)
SELECT a.id, a.display_name, a.cell_phone, a.email,
       uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM a LEFT JOIN user_vehicles uv ON uv.user_id = a.id AND uv.current_owner=1
ORDER BY a.display_name;
</code>```

The intention is we take a subset of users before joining it with user_vehicles.
Disclaimer: I haven't verified if its faster or not, but have similar experience in the past where this helps.

Body:
I am attempting to optimize a query in MariaDb that is really bogged down by its ORDER BY clause. I can run it in under a tenth of a second without the ORDER BY clause, but it takes over 25 seconds with it. Here is the gist of the query:

SELECT u.id, u.display_name, u.cell_phone, u.email,
uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM users u
LEFT JOIN user_vehicles uv ON uv.user_id = u.id AND uv.current_owner=1
WHERE u.is_deleted = 0
GROUP BY u.id
ORDER BY u.display_name
LIMIT 0, 10;

I need it to be a left join because I want to include users that aren't linked to a vehicle.

I need the group by because I want only 1 result per user (and display_name is not guaranteed to be unique).

users table has about 130K rows, while user_vehicles has about 230K rows.

Here is the EXPLAIN of the query:

id  select_type table   type    possible_keys   key      key_len  ref           rows    Extra
1   SIMPLE      u       index   dms_cust_idx    PRIMARY  4        null          124825  Using where; Using temporary; Using filesort
1   SIMPLE      uv      ref     user_idx        user_idx 4        awscheduler.u.id  1   Using where

I have tried these two indices to speed things up, but they don't seem to do much.

CREATE INDEX idx_display_speedy ON users(display_name);

CREATE INDEX idx_display_speedy2 ON users(id, display_name, is_deleted, dms_cust_id);

I am looking for ideas on how to speed this up. I attempted using nested queries, but since the order by is the bottleneck & order within the nested query is ignored, I believe that attempt was in vain.

Body:
how about:

WITH a AS (
   SELECT u.id, u.display_name, u.cell_phone, u.email
   FROM users u
   WHERE u.is_deleted = 0
   GROUP BY u.id
   LIMIT 0, 10
)
SELECT a.id, a.display_name, a.cell_phone, a.email,
       uv.year, uv.make, uv.model, uv.id AS user_vehicle_id
FROM a LEFT JOIN user_vehicles uv ON uv.user_id = a.id AND uv.current_owner=1
ORDER BY a.display_name;

The intention is we take a subset of users before joining it with user_vehicles.
Disclaimer: I haven't verified if its faster or not, but have similar experience in the past where this helps.


问:
Importing files outside my App.js - React Native
I'm new to React Native and I'm currently trying to create a cookbook application with Expo. And I'm looking for a solution to shorten my importing in my App.js since they're all in the same folder. Here it looks like:

```<code>import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
import BananaQue from "./recipes/BananaQue";
import Bibingka from "./recipes/Bibingka";
import BukoPie from "./recipes/BukoPie";
</code>```

And this is how I use these all I imported:

```<code><NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BananaQue"
            component={BananaQue}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="Bibingka"
            component={Bibingka}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BukoPie"
            component={BukoPie}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
</code>```

答:
You can import many components using Curley brackets {}</p>
```<code>import { a, b, c, d } from '../your file name'
</code>```

Body:
I'm new to React Native and I'm currently trying to create a cookbook application with Expo. And I'm looking for a solution to shorten my importing in my App.js since they're all in the same folder. Here it looks like:

import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
import BananaQue from "./recipes/BananaQue";
import Bibingka from "./recipes/Bibingka";
import BukoPie from "./recipes/BukoPie";

And this is how I use these all I imported:

<NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BananaQue"
            component={BananaQue}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="Bibingka"
            component={Bibingka}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BukoPie"
            component={BukoPie}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>

Body:
You can import many components using Curley brackets {}

import { a, b, c, d } from '../your file name'


问:
Is there a way to use eval() and a dictionary if input could be None?
I have some code with a lot of stacked if statements that I'm trying to make more pythonic. One of the segments of code boils down to three separate "values".

```<code>0.9 if 10<x>=20
0.75 if x>20
1 if x<10 or x is None
</code>```

I tried sticking this in a dictionary to run through a function I made for a less complex (integers only) dictionary but am not sure how to handle None inputs.

```<code>def wallrat(val, table):
    try:
        # Create true/false list based on input value
        chks = [eval(v.replace('x',str(val))) for v in table.values()]
        # Find which value is true and verify that there's only one true value
        if True in chks and chks.count(True) == 1:
            # find the key that's true
            v = chks.index(True)
            table_list = list(table)
            # Loop through keys and values in dictionary
            return table_list[v]

age_dict = {0.9: '10< x >=20', 0.75: 'x > 20', 1:'x<10 or x is None'}
</code>```

The above code obviously errors since if x == None, it can't do the other evaluations of 10< None >=20. I'm not sure how to pythonically handle this situation. Is it even possible to have a dictionary that tests both None and ints/floats? Or am I stuck having to use only x < 10 and use a separate segment of code to output the value of 1 if the input is None?

EDIT: I don't want to delete the question, but ended up just utilizing an If ... is not 'None' and an else statement to capture the 'None' = 1 assignment.

Comments and answers may provide helpful reconsideration to others utilizing eval(). In my specific use-case, there is no way for the input to contain malicious strings due to what the input data is (GIS feature class tables with integer fields or a coded int variable based on input date fields). Regardless though, I wasn't aware of the concerns about using eval() and the comments provide good information IMO.

答:
You can use a list of lambdas that contain the logic you need instead of eval as it is a potential security risk and almost always not needed.

```<code>checks = [lambda x: .75 if x > 20 else ..., lambda x: 1 if x is None or x < 10 else ...]
</code>```

Body:
I have some code with a lot of stacked if statements that I'm trying to make more pythonic. One of the segments of code boils down to three separate "values".

0.9 if 10<x>=20
0.75 if x>20
1 if x<10 or x is None

I tried sticking this in a dictionary to run through a function I made for a less complex (integers only) dictionary but am not sure how to handle None inputs.

def wallrat(val, table):
    try:
        # Create true/false list based on input value
        chks = [eval(v.replace('x',str(val))) for v in table.values()]
        # Find which value is true and verify that there's only one true value
        if True in chks and chks.count(True) == 1:
            # find the key that's true
            v = chks.index(True)
            table_list = list(table)
            # Loop through keys and values in dictionary
            return table_list[v]

age_dict = {0.9: '10< x >=20', 0.75: 'x > 20', 1:'x<10 or x is None'}

The above code obviously errors since if x == None, it can't do the other evaluations of 10< None >=20. I'm not sure how to pythonically handle this situation. Is it even possible to have a dictionary that tests both None and ints/floats? Or am I stuck having to use only x < 10 and use a separate segment of code to output the value of 1 if the input is None?

EDIT: I don't want to delete the question, but ended up just utilizing an If ... is not 'None' and an else statement to capture the 'None' = 1 assignment.

Comments and answers may provide helpful reconsideration to others utilizing eval(). In my specific use-case, there is no way for the input to contain malicious strings due to what the input data is (GIS feature class tables with integer fields or a coded int variable based on input date fields). Regardless though, I wasn't aware of the concerns about using eval() and the comments provide good information IMO.

Body:
You can use a list of lambdas that contain the logic you need instead of eval as it is a potential security risk and almost always not needed.

checks = [lambda x: .75 if x > 20 else ..., lambda x: 1 if x is None or x < 10 else ...]


问:
Laravel Jetstream problem with Bazar vendor package
i am using Laravel 8.3, and i already have installed Jetstream with Fortify package for login on frontend, it's work i can login, but i needit to install package Bazar: https://github.com/conedevelopment/bazar
In that docs of bazar, it's say to install breeze, i want to stay on jetstream to don't make code to big.
When i am logged in, in try to access url with /bazar, but say 403 This action is unauthorized.
I tried to install clean bazar, and work with breeze, what i am doing wrong ?

This is composer.json:

```<code>    "require": {
    "php": "^7.3|^8.0",
    "conedevelopment/bazar": "^0.9.1",
    "donatello-za/rake-php-plus": "^1.0",
    "fideloper/proxy": "^4.4",
    "fruitcake/laravel-cors": "^2.0",
    "guzzlehttp/guzzle": "^7.0.1",
    "intervention/image": "^2.6",
    "laravel/framework": "^8.40",
    "laravel/jetstream": "^2.3",
    "laravel/sanctum": "^2.6",
    "laravel/socialite": "^5.2",
    "laravel/tinker": "^2.5",
    "laravel/ui": "^3.3",
    "laravelcollective/html": "^6.2",
    "livewire/livewire": "^2.5",
    "yoeunes/toastr": "^1.2"
},
</code>```

Doc image:

答:
The problem was not the login method Breeze or Jetstream, both use laravel auth, problem was Bazar, in config/bazar.php, you have a key

```<code>'admins' => [
        'xx@m.com',
    ],
</code>```

There you need to add email to have permision to view the backend of Bazar

Body:
i am using Laravel 8.3, and i already have installed Jetstream with Fortify package for login on frontend, it's work i can login, but i needit to install package Bazar: https://github.com/conedevelopment/bazar
In that docs of bazar, it's say to install breeze, i want to stay on jetstream to don't make code to big.
When i am logged in, in try to access url with /bazar, but say 403 This action is unauthorized.
I tried to install clean bazar, and work with breeze, what i am doing wrong ?

This is composer.json:

    "require": {
    "php": "^7.3|^8.0",
    "conedevelopment/bazar": "^0.9.1",
    "donatello-za/rake-php-plus": "^1.0",
    "fideloper/proxy": "^4.4",
    "fruitcake/laravel-cors": "^2.0",
    "guzzlehttp/guzzle": "^7.0.1",
    "intervention/image": "^2.6",
    "laravel/framework": "^8.40",
    "laravel/jetstream": "^2.3",
    "laravel/sanctum": "^2.6",
    "laravel/socialite": "^5.2",
    "laravel/tinker": "^2.5",
    "laravel/ui": "^3.3",
    "laravelcollective/html": "^6.2",
    "livewire/livewire": "^2.5",
    "yoeunes/toastr": "^1.2"
},

Doc image:

Body:
The problem was not the login method Breeze or Jetstream, both use laravel auth, problem was Bazar, in config/bazar.php, you have a key

'admins' => [
        'xx@m.com',
    ],

There you need to add email to have permision to view the backend of Bazar


问:
Vue.js vuetifyjs Calendar not dispaying day events
I have a working calendar that can change based on the type property. I am able  to display information in the calendar header but day events seem to be a problem.

My vue.js vuetify calendar does not display day events. It is set to display as type 'week'. I am working from the following example.

export default {
  data: () => ({
    todayDate: new Date().toISOString().substr(0, 10) /*'YYYY-MM-DD'*/ ,
    type: 'week',
    events: [{
        title: 'Weekly Meeting',
        date: '2019-02-26',
        time: '09:00',
        duration: 45
      },
      {
        title: 'Mash Potatoes',
        date: '2019-02-28',
        time: '12:30',
        duration: 180
      }
    ]
  }),

  computed: {
    eventsMap() {
      const map = {};
      this.events.forEach(e => (map[e.date] = map[e.date] || []).push(e));
      return map
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></script>
<v-calendar ref="calendar" :type="type" v-model="todayDate" :now="todayDate" :value="todayDate" color="primary">

  <template slot="dayBody" slot-scope="{ date, timeToY, minutesToPixels }">
              <template v-for="event in eventsMap[date]">
                <div
                  v-if="event.time"
                  :key="event.title"
                  v-html="event.title"
                ></div>
              </template>
  </template>

</v-calendar></code>```

答:
One of the reason could be Events are not displaying because you are missing color property in Events objects. Without color property, Events are present but not visible because by default color is white.</p>
```<code>{
    color: 'indigo',
    name: 'Weekly Meeting',
    date: '2019-02-26',
    time: '09:00',
    duration: 45
},
</code>```

Body:
I have a working calendar that can change based on the type property. I am able  to display information in the calendar header but day events seem to be a problem.

My vue.js vuetify calendar does not display day events. It is set to display as type 'week'. I am working from the following example.

export default {
  data: () => ({
    todayDate: new Date().toISOString().substr(0, 10) /*'YYYY-MM-DD'*/ ,
    type: 'week',
    events: [{
        title: 'Weekly Meeting',
        date: '2019-02-26',
        time: '09:00',
        duration: 45
      },
      {
        title: 'Mash Potatoes',
        date: '2019-02-28',
        time: '12:30',
        duration: 180
      }
    ]
  }),

  computed: {
    eventsMap() {
      const map = {};
      this.events.forEach(e => (map[e.date] = map[e.date] || []).push(e));
      return map
    }
  }
}

</script>
<v-calendar ref="calendar" :type="type" v-model="todayDate" :now="todayDate" :value="todayDate" color="primary">

  <template slot="dayBody" slot-scope="{ date, timeToY, minutesToPixels }">
              <template v-for="event in eventsMap[date]">

              </template>
  </template>

</v-calendar>

Body:
One of the reason could be Events are not displaying because you are missing color property in Events objects. Without color property, Events are present but not visible because by default color is white.

{
    color: 'indigo',
    name: 'Weekly Meeting',
    date: '2019-02-26',
    time: '09:00',
    duration: 45
},


问:
Mongoose how to auto add _id to objects in array within collection item?
i have a mongo collection that looks like this:

```<code>{
    name: string
    _id: (auto set)
    items: array[
        name: string
        url: string
        items: array[
            {
                name: string,
                url: string,
                items: []
            }
        ]
    ]
}
</code>```

I'm using findByIdAndUpdate (with mongoose) to add an item into the items array:

```<code>Menu.findByIdAndUpdate(
    req.body.parentid,
    {
        $push: {
            items: {
                name: req.body.item.name,
                url: req.body.item.url,
                items: []
            }
        }
    },
    {
        safe: true,
        upsert: true,
        new: true
    },
    function(err, model) {
        if (err !== null) {
            console.log(err);
        }
    }
);
</code>```

This works fine, but it does not add an _id to each object inserted into the items array. And i really need an id for each one.

I'm guessing it comes from the method used, findByIdAndUpdate as it looks more like an update rather than an insert. If my thinking is correct.

Using mongodb 3.2.10 and mongoose 4.7.6.

Any help would be really appreciated.
Thanks.

EDIT: the _id: (auto set) is not real, it's being automatically added via mongo. But just at the top level objects.

答:
if you don't define _id in Schema, mongoose automatically add a _id to array item.
for example:

```<code>const countrySchema = new Schema({
  name: {
    type: String
  },
  cities: [
    {
      // don't define _id here.
      name: String
    }
  ],
});
</code>```

now when you insert a row, the result is something like this:

{name : 'Iran', cities : [{_id : 6202902b45f0d858ac141537,name :
'Tabriz'}]}

Body:
i have a mongo collection that looks like this:

{
    name: string
    _id: (auto set)
    items: array[
        name: string
        url: string
        items: array[
            {
                name: string,
                url: string,
                items: []
            }
        ]
    ]
}

I'm using findByIdAndUpdate (with mongoose) to add an item into the items array:

Menu.findByIdAndUpdate(
    req.body.parentid,
    {
        $push: {
            items: {
                name: req.body.item.name,
                url: req.body.item.url,
                items: []
            }
        }
    },
    {
        safe: true,
        upsert: true,
        new: true
    },
    function(err, model) {
        if (err !== null) {
            console.log(err);
        }
    }
);

This works fine, but it does not add an _id to each object inserted into the items array. And i really need an id for each one.

I'm guessing it comes from the method used, findByIdAndUpdate as it looks more like an update rather than an insert. If my thinking is correct.

Using mongodb 3.2.10 and mongoose 4.7.6.

Any help would be really appreciated.
Thanks.

EDIT: the _id: (auto set) is not real, it's being automatically added via mongo. But just at the top level objects.

Body:
if you don't define _id in Schema, mongoose automatically add a _id to array item.
for example:

const countrySchema = new Schema({
  name: {
    type: String
  },
  cities: [
    {
      // don't define _id here.
      name: String
    }
  ],
});

now when you insert a row, the result is something like this:

{name : 'Iran', cities : [{_id : 6202902b45f0d858ac141537,name :
'Tabriz'}]}


问:
AZURE: Can I host NuGet.Server in Azure?
I want to host a nuget.server to share private nuget packages with my dev team.

This link:
https://learn.microsoft.com/en-us/nuget/hosting-packages/nuget-server

shows me how to build a nuget.server, but it says that it needs to run under IIS.

Can I deploy a nuget.server application to azure instead of running it under IIS?

It looks like Azure artifacts requires using a CI/CD pipeline, but my dev team is not up to using pipelines yet.  For now, all applications are manually deployed to production from Visual Studio.

Any suggestions?

答:
It looks like Azure artifacts requires using a CI/CD pipeline

That's not correct. Anything that can authenticate to Azure Artifacts can push packages to it, including doing it from your own machine. Similarly, if you want to have a private feed, that's a simple configuration, whereas hosting your own NuGet server means you'll need to implement authentication yourself.

I strongly recommend you use Azure Artifacts instead of hosting your own server, if you already have access to Azure DevOps. They handle scalability/performance, whereas I believe that NuGet.Server has performance problems when there are a large number of packages. Azure DevOps also handles authentication, as previously discussed. I wouldn't be surprised if Azure Artifacts is also cheaper than Azure App Service, although this depends on a lot of things so will depend on your specific usage, making it impossible to make a blanket statement.

If you really want to host your own nuget feed, I can't find docs explicitly saying it, but Azure App Service on a Windows host is IIS. ASP.NET (before Core) only run in IIS, and here are Azure App Service's docs for running ASP.NET (not Core) apps: https://learn.microsoft.com/en-us/azure/app-service/configure-language-dotnet-framework


问:
Simple Question: How to split date (08-17-2011) into month, day, year? PHP
I have a variable called $orderdate and it is set to a date format like this mm-dd-yyyy.

In PHP how would I split this variable into $month, $day, $year?

Thanks for your help.

答:
If you are not certain about the input format you can also do the following:

```<code>$time  = strtotime($input);
$day   = date('d',$time);
$month = date('m',$time);
$year  = date('Y',$time);
</code>```

Body:
If you are not certain about the input format you can also do the following:

$time  = strtotime($input);
$day   = date('d',$time);
$month = date('m',$time);
$year  = date('Y',$time);


答:
Since you want to replace all the / with -'s, gsub is the way to go:

```<code>jq 'map(gsub("\/"; "-"))'
</code>```

Will produce

[
  "1934-08-20",
  "1961-01-10",
  "1952-01-25",
  "1967-07-24"
]
```

As you can test in this online demo

Title: jq: replache slash by dash chracter

Body:
I need to replace slash character by "-".

I mean:

[
  "1934/08/20",
  "1961/01/10",
  "1952/01/25",
  "1967/07/24"
]

I need:

[
  "1934-0820",
  "1961-01-10",
  "1952-01-25",
  "1967-07-24"
]

Is there anyway to get it?

Body:
Since you want to replace all the / with -'s, gsub is the way to go:

jq 'map(gsub("\/"; "-"))'

Will produce

[
  "1934-08-20",
  "1961-01-10",
  "1952-01-25",
  "1967-07-24"
]

As you can test in this online demo


问:
Error occurred in "OPSS Processing" phase execution
I am trying to install oracle database 19c client in the windows server 2016. However I am encountered with the following error</p>
```<code>CFGFWK-64254: Error occurred in "OPSS Processing" phase execution

</code>```

答: Oracle database 19c client installation might failed because of the operating system's password policy. The provided password for the "oracle" user does not comply the password policy of the Operating System. Please provide a password for the "oracle" user that meets the password policy requirements as per your operating system.</p>

Body:
I am trying to install oracle database 19c client in the windows server 2016. However I am encountered with the following error

CFGFWK-64254: Error occurred in "OPSS Processing" phase execution


问:
Print result of query in a table in laravel
I have an index method in a controller that returns a collection(https://laravel.com/docs/8.x/collections) to a view

```<code>public function index()
{
    $categoriePdf = new CategorieDocumenti;
    $categoriePdf = DB::table('categorie_documenti')
    ->select('id','descrizione','per_veicolo')
    ->get();
    return view('elenca_categoria_pdf', ['campi' => $categoriePdf]);
}
</code>```

In the view I want to print the result of the query in an adminlte table.

I got the tamplate from here https://github.com/jeroennoten/Laravel-AdminLTE/wiki
and the table i want to setup is this https://github.com/jeroennoten/Laravel-AdminLTE/wiki/Tool-Components#datatables

Here is the screenshot of how it should be

I want the same thing but not with static data as the example does but with the content of the collection

I tried for hours but I cant understand how to put all the rows of the collection in $config['data'] array as the example does with static data:

```<code>$config = [
'data' => [
    [22, 'John Bender', '+02 (123) 123456789', '<nobr>'.$btnEdit.$btnDelete.$btnDetails.'</nobr>'],
    [19, 'Sophia Clemens', '+99 (987) 987654321', '<nobr>'.$btnEdit.$btnDelete.$btnDetails.'</nobr>'],
    [3, 'Peter Sousa', '+69 (555) 12367345243', '<nobr>'.$btnEdit.$btnDelete.$btnDetails.'</nobr>'],
],
</code>```

答:
change your controller to

```<code>public function index()
{
    $categoriePdf = new CategorieDocumenti;
    $categoriePdf = DB::table('categorie_documenti')
    ->select('id','descrizione','per_veicolo')
    ->get();
    return view('elenca_categoria_pdf',compact('categoriePdf'));
}
</code>```

then in your view blade file do something like this

```<code> <thead>
 <th>{{ __('id') }}</th>
<th>{{ __('Name') }}</th>
<th>{{ __('Actions') }}</th>
</thead>
<body>
@foreach($categoriePdf as $categoriePdfs)
<tr>
<td>{{$categoriePdfs->id}}</td>
<td>{{$categoriePdfs->name}}</td>
<td><input type="button" class="btn btn-success" value="add"/></td>
</tr>
@endforeach
 </tbody>
 </table>
</code>```

Body:
I have an index method in a controller that returns a collection(https://laravel.com/docs/8.x/collections) to a view

public function index()
{
    $categoriePdf = new CategorieDocumenti;
    $categoriePdf = DB::table('categorie_documenti')
    ->select('id','descrizione','per_veicolo')
    ->get();
    return view('elenca_categoria_pdf', ['campi' => $categoriePdf]);
}

In the view I want to print the result of the query in an adminlte table.

I got the tamplate from here https://github.com/jeroennoten/Laravel-AdminLTE/wiki
and the table i want to setup is this https://github.com/jeroennoten/Laravel-AdminLTE/wiki/Tool-Components#datatables

Here is the screenshot of how it should be

I want the same thing but not with static data as the example does but with the content of the collection

I tried for hours but I cant understand how to put all the rows of the collection in $config['data'] array as the example does with static data:

$config = [
'data' => [
    [22, 'John Bender', '+02 (123) 123456789', '<nobr>'.$btnEdit.$btnDelete.$btnDetails.'</nobr>'],
    [19, 'Sophia Clemens', '+99 (987) 987654321', '<nobr>'.$btnEdit.$btnDelete.$btnDetails.'</nobr>'],
    [3, 'Peter Sousa', '+69 (555) 12367345243', '<nobr>'.$btnEdit.$btnDelete.$btnDetails.'</nobr>'],
],

Body:
change your controller to

public function index()
{
    $categoriePdf = new CategorieDocumenti;
    $categoriePdf = DB::table('categorie_documenti')
    ->select('id','descrizione','per_veicolo')
    ->get();
    return view('elenca_categoria_pdf',compact('categoriePdf'));
}

then in your view blade file do something like this

 <thead>
 <th>{{ __('id') }}</th>
<th>{{ __('Name') }}</th>
<th>{{ __('Actions') }}</th>
</thead>
<body>
@foreach($categoriePdf as $categoriePdfs)
<tr>
<td>{{$categoriePdfs->id}}</td>
<td>{{$categoriePdfs->name}}</td>
<td><input type="button" class="btn btn-success" value="add"/></td>
</tr>
@endforeach
 </tbody>
 </table>


问:
How to limit the amount of simultaneously running jobs of a certain "type"?
I would like to be able to limit the amount of jobs of a given "type" that run at the same time (maybe based on their label, e.g. no more than N jobs with label mylabel may run at the same time).

I have a long running computation that requires a license key to run.  I have N license keys and I would like to limit the amount of simultaneously running jobs to N. Here's how I imagine it working: I label the jobs with some special tag.  Then, I schedule N + K jobs, then at most N jobs may be in state "running" and K jobs should be in the queue and may only transition to "running" state when the total number of running jobs labeled mytag is less or equal to N.

[UPDATE]

The jobs are independent of each other.

The execution order is not important, although I would like them to be FIFO (time wise).

The jobs are scheduled on user requests. That is, there is no fixed amount of work known in advance that needs to be processed, the requests to run a job with some set of parameters (configuration file) come sporadically in time.

答: You can ‘parallelism’ attribuate of the job, but K8s won’t spin any jobs till the current active be less than parallel threshild</p>


问:
How to replace only the leading zeros with NA?
How can I replace leading zeros with NAs? suppose I have the following example:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})
</code>```

the goal is to have the following result:

```<code> c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0
</code>```

but doing the following will not work since it will replace all and not just the leading zeros:

```<code>df[np.abs(df) < 1e-50] = np.nan
</code>```

答:
You could use cummax to fill the non-trailing zeros, and mask those that remain:

```<code>df.mask(df.cummax().eq(0))
</code>```

Or to handle all non zero values with limited precision:

```<code>df.mask(df.gt(1e-50).cummax().lt(1e-50))
</code>```

output:

```<code>    c1   c2
0  NaN  1.0
1  NaN  1.0
2  1.0  1.0
3  0.0  0.0
</code>```

Body:
How can I replace leading zeros with NAs? suppose I have the following example:

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})

the goal is to have the following result:

 c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0

but doing the following will not work since it will replace all and not just the leading zeros:

df[np.abs(df) < 1e-50] = np.nan

Body:
You could use cummax to fill the non-trailing zeros, and mask those that remain:

df.mask(df.cummax().eq(0))

Or to handle all non zero values with limited precision:

df.mask(df.gt(1e-50).cummax().lt(1e-50))

output:

    c1   c2
0  NaN  1.0
1  NaN  1.0
2  1.0  1.0
3  0.0  0.0


问:
PHP curl not getting the intended page content, Firefox does. Possible causes?
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

```<code>// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);
</code>```

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

```<code># Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK
</code>```

答:
You should take a look at cookies generated by the website, or even some CSRF tokens that would be inserted to keep you away from doing some parsing job.
When I inspect the webpage at first load, I can find this:

```<code>Set-Cookie:cookie2=b1d92ddac8aa82350a6ff5e892a8637d;Domain=.taobao.com;Path=/;HttpOnly
_tb_token_=fde3979ee6b13;Domain=.taobao.com;Path=/;Expires=Sat, 17-Sep-2011 07:09:40     GMT;HttpOnly
t=91f29eb410a21a04bf36025823c4b2ad; Domain=.taobao.com; Expires=Wed, 16-Nov-2011 07:09:40 GMT; Path=/
uc1=cookie14=UoLdHCDBHbn1eg%3D%3D; Domain=.taobao.com; Path=/
</code>```

Maybe these cookies are used to identify you while navigating through categories.

Searching for "token" in the DOM made some results too.

Body:
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK

Body:
You should take a look at cookies generated by the website, or even some CSRF tokens that would be inserted to keep you away from doing some parsing job.
When I inspect the webpage at first load, I can find this:

Set-Cookie:cookie2=b1d92ddac8aa82350a6ff5e892a8637d;Domain=.taobao.com;Path=/;HttpOnly
_tb_token_=fde3979ee6b13;Domain=.taobao.com;Path=/;Expires=Sat, 17-Sep-2011 07:09:40     GMT;HttpOnly
t=91f29eb410a21a04bf36025823c4b2ad; Domain=.taobao.com; Expires=Wed, 16-Nov-2011 07:09:40 GMT; Path=/
uc1=cookie14=UoLdHCDBHbn1eg%3D%3D; Domain=.taobao.com; Path=/

Maybe these cookies are used to identify you while navigating through categories.

Searching for "token" in the DOM made some results too.


问:
Facebook scraper using 302 redirect and accessing old site same domain name
Developed a site whose domain was pointing to an external host.
On finishing the development I pointed the nameservers back to where the domain is hosted.
Everything changed over smoothly, I did not have to use any redirects.

Sharing any page on Facebook however, gives me this:

There is a 302 redirect. The Debugger is scraping the old URL for some reason

答: Changing DNS servers can take up to 48 hour to take in effect. If it was done recently try to wait a bit, otherwise you could contact the support of facebook,</p>


问:
Can't see raise messages in DBeaver or PgAdmin
When i execute the function below (in the picture), i can't find the raise message anywhere even in execution logs: is there anyway to make it appear.

script:

```<code> SELECT helloworld('myname');

    CREATE OR REPLACE FUNCTION helloWorld(name text) RETURNS void AS $helloWorld$
    DECLARE
    BEGIN
        RAISE LOG 'Hello, %', name;
    END;

$helloWorld$ LANGUAGE plpgsql;
</code>```

答: also dont do a basic mistake like me that to see the raise notice messages inside function, you first have to call that function by select public.helloworld()

Body:
When i execute the function below (in the picture), i can't find the raise message anywhere even in execution logs: is there anyway to make it appear.

script:

 SELECT helloworld('myname');

    CREATE OR REPLACE FUNCTION helloWorld(name text) RETURNS void AS $helloWorld$
    DECLARE
    BEGIN
        RAISE LOG 'Hello, %', name;
    END;

$helloWorld$ LANGUAGE plpgsql;


问:
How add group for custom user in django?
I created custom model of user using this official docs customizing authentication in Django
But how can add groups and premissions? My django is version 1.9</p>

答:
As a complement to @ajinzrathod answer: I applied the solution and got error because I missed some trailing commas. The working code in admin.py is as following:

class UserAdminConfig(UserAdmin):
    model = CustomUser
    fieldsets = (
        # Other fieldsets

        ('Group Permissions', {
            'fields': ('groups', 'user_permissions', )
        }),
    )
admin.site.register(CustomUser, UserAdminConfig)
```


问:
Using Express.js and Puppeteer with multiple URL at the same time
I am having trouble using express.Router() and Puppeteer. When I tried to send data (which is the URL) to the Node.JS instance that was running on PM2 at the same time, they are returning the same value.

Visual Sample:

Browser: Google Chrome 64Bit Windows

Tab 1: https://api.domain.com/wp/01

Tab 2: https://api.domain.com/wp/02

Enter key was pressed at the same time to send the request

Node Instance:

```<code>app.get("/:id/:video", function (req, res) {

  var id = req.params.id;
  var episode = req.params.episode;
  url = `www.domain2.com/${id}/${video}`;

  rs(url, (err, resp, html) => {

    (async () => {
      const browser = await puppeteer.launch({
        args: ["--no-sandbox"],
      });

      const page = await browser.newPage();

      await page.on("response", async (response) => {
        if (response.url().includes("api.php?id=")) {
          var data = JSON.parse(JSON.stringify(await response.json()));

          var sourceOne = data.source.filter(function (el) {
            return el.label == "devVideo";
          });

            if (one != "") {
              return res.status(200).json({
                link: sourceOne[0].file,
              });
            }
          }
        }
      });

      // console.log(object.response);
      await page.goto(url, {
        waitUntil: "networkidle0",
        // Remove the timeout
        timeout: 0,
      });

      await page.close();
      await browser.close();
    })();
  });
});
</code>```

The url that has been sent from browser to nodejs was processed

Result

Expected Results:

Tab 1: https://domain2.com/1.mp4
Tab 2: https://domain2.com/2.mp4

Got Results:

Tab 1: https://domain2.com/1.mp4
Tab 2: https://domain2.com/1.mp4

As you can see on the 'Got Results', the results are the same. Now I'm confused...

答:
Got it work. It was error on my side , I moved the

```<code>
    var id = req.params.id;
    var episode = req.params.video;
    url = `www.domain2.com/${id}/${video}`;
    // console.log(object.response);

</code>```

near the await page.goto(url, {

Body:
I am having trouble using express.Router() and Puppeteer. When I tried to send data (which is the URL) to the Node.JS instance that was running on PM2 at the same time, they are returning the same value.

Visual Sample:

Browser: Google Chrome 64Bit Windows

Tab 1: https://api.domain.com/wp/01

Tab 2: https://api.domain.com/wp/02

Enter key was pressed at the same time to send the request

Node Instance:

app.get("/:id/:video", function (req, res) {

  var id = req.params.id;
  var episode = req.params.episode;
  url = `www.domain2.com/${id}/${video}`;

  rs(url, (err, resp, html) => {

    (async () => {
      const browser = await puppeteer.launch({
        args: ["--no-sandbox"],
      });

      const page = await browser.newPage();

      await page.on("response", async (response) => {
        if (response.url().includes("api.php?id=")) {
          var data = JSON.parse(JSON.stringify(await response.json()));

          var sourceOne = data.source.filter(function (el) {
            return el.label == "devVideo";
          });

            if (one != "") {
              return res.status(200).json({
                link: sourceOne[0].file,
              });
            }
          }
        }
      });

      // console.log(object.response);
      await page.goto(url, {
        waitUntil: "networkidle0",
        // Remove the timeout
        timeout: 0,
      });

      await page.close();
      await browser.close();
    })();
  });
});

The url that has been sent from browser to nodejs was processed

Result

Expected Results:

Tab 1: https://domain2.com/1.mp4
Tab 2: https://domain2.com/2.mp4

Got Results:

Tab 1: https://domain2.com/1.mp4
Tab 2: https://domain2.com/1.mp4

As you can see on the 'Got Results', the results are the same. Now I'm confused...

Body:
Got it work. It was error on my side , I moved the

    var id = req.params.id;
    var episode = req.params.video;
    url = `www.domain2.com/${id}/${video}`;
    // console.log(object.response);

near the await page.goto(url, {


问:
Python Dataframe rename column compared to value
With Pandas I'm trying to rename unnamed columns in dataframe with values on the first ligne of data.

My dataframe:

id
store
unnamed: 1
unnamed: 2
windows
unnamed: 3
unnamed: 4

0
B1
B2
B3
B1
B2
B3

1
2
c
12
15
15
14

2
4
d
35
14
14
87

My wanted result:

id
store_B1
store_B3
store_B2
windows_B1
windows_B2
windows_B3

0
B1
B2
B3
B1
B2
B3

1
2
c
12
15
15
14

2
4
d
35
14
14
87

I don't know how I can match the column name with the value in my data. Thanks for your help. Regards

答:
You can use df.columns.where to make unnamed: columns NaN, then convert it to a Series and use ffill:

```<code>df.columns = pd.Series(df.columns.where(~df.columns.str.startswith('unnamed:'))).ffill() + np.where(~df.columns.isin(['id','col2']), ('_' + df.iloc[0].astype(str)).tolist(), '')
</code>```

Output:

```<code>>>> df
   id store_B1 store_B2 store_B3 windows_B1 windows_B2 windows_B3
0   0       B1       B2       B3         B1         B2         B3
1   1        2        c       12         15         15         14
2   2        4        d       35         14         14         87
</code>```

Body:
You can use df.columns.where to make unnamed: columns NaN, then convert it to a Series and use ffill:

df.columns = pd.Series(df.columns.where(~df.columns.str.startswith('unnamed:'))).ffill() + np.where(~df.columns.isin(['id','col2']), ('_' + df.iloc[0].astype(str)).tolist(), '')

Output:

>>> df
   id store_B1 store_B2 store_B3 windows_B1 windows_B2 windows_B3
0   0       B1       B2       B3         B1         B2         B3
1   1        2        c       12         15         15         14
2   2        4        d       35         14         14         87


问:
How to make my reducer reusable using Redux toolkit?
How can I make my reducer be reusable in other slices?

For example, I have this reducer in my signinSlice and I want this also to be used in my signupSlice without copying and pasting it to it.

```<code>    reducers: {
        RESET_INITIAL_STATE: (state) => {
      state.status = "idle";
    },
  },
</code>```

The reason why I'm asking this is I want to reduce or prevent the duplicated code all over in my other slices. By the way, I'm using redux-toolkit

答:
IMHO, You should not factorize your reducer but you can just declare a function anywhere

```<code>export const resetInitialState = (state) => state.status = "idle"
</code>```

and in both slices:

```<code>import { resetInitialState } from '...'

reducers: {
  RESET_INITIAL_STATE: resetInitialState
}
</code>```

Body:
How can I make my reducer be reusable in other slices?

For example, I have this reducer in my signinSlice and I want this also to be used in my signupSlice without copying and pasting it to it.

    reducers: {
        RESET_INITIAL_STATE: (state) => {
      state.status = "idle";
    },
  },

The reason why I'm asking this is I want to reduce or prevent the duplicated code all over in my other slices. By the way, I'm using redux-toolkit

Body:
IMHO, You should not factorize your reducer but you can just declare a function anywhere

export const resetInitialState = (state) => state.status = "idle"

and in both slices:

import { resetInitialState } from '...'

reducers: {
  RESET_INITIAL_STATE: resetInitialState
}


问:
Uploading AAB Bundle to AppCenter downloads an APK File?
I am converting my Android app from APK to AAB. However, when I uploaded the bundle.aab to AppCenter, the download was an APK? Shouldn't the download be a .AAB file?</p>

答:
The Android OS can only install APKs. If you upload Android App Bundles to the Google Play Store, the Play Store then generates optimized APKs for your end users.

Microsoft's App Center on the other hand generates an unoptimized universal APK.

"When you distribute Android Application Bundle (AAB), App Center generates a universal APK, signs it with a generated signing key, and distributes it to a device."

Source: https://learn.microsoft.com/en-us/appcenter/distribution/uploading


问:
HashMap Serializability
HashMap implements the Serializable interface; so it can be serialized. I have looked at the implementation of HashMap and the Entry[] table is marked as transient. Since the Entry[] table is the one that stores the entire contents of the Map and if it cannot be serialized, how is the Map constructed back during de-serialization</p>

答: HashMap takes care of its own serialization through the use of the writeObject and readObject methods.

Title: HashMap Serializability


问:
Error when redeclaring class in Firefox console but not in Chrome console
```<code>class Picture {
    constructor(icon) {
        this.icon = icon

    }
}
</code>```

When I run this code twice in the Chrome console it doesn't throw any errors.
But when I try running it twice in the Firefox console it says Uncaught SyntaxError: redeclaration of let Picture. Why do the browsers behave differently?

答:
A class can't be redefined. It is actually a block scoped variable.

If you're experimenting with code in a web browser, such as the Firefox Web Console (Tools > Web Developer > Web Console) and you 'Run' a definition of a class with the same name twice, you'll get a SyntaxError: redeclaration of let ClassName;

MDN docs

Redeclaration of let/const is allowed in chrome console. Run the below statement twice:

```<code>let x = 2;
</code>```

Check this SO answer and this link from Chrome blog

Redeclaration within the same console line is not allowed though.

Body:
class Picture {
    constructor(icon) {
        this.icon = icon

    }
}

When I run this code twice in the Chrome console it doesn't throw any errors.
But when I try running it twice in the Firefox console it says Uncaught SyntaxError: redeclaration of let Picture. Why do the browsers behave differently?

Body:
A class can't be redefined. It is actually a block scoped variable.

If you're experimenting with code in a web browser, such as the Firefox Web Console (Tools > Web Developer > Web Console) and you 'Run' a definition of a class with the same name twice, you'll get a SyntaxError: redeclaration of let ClassName;

MDN docs

Redeclaration of let/const is allowed in chrome console. Run the below statement twice:

let x = 2;

Check this SO answer and this link from Chrome blog

Redeclaration within the same console line is not allowed though.