问:
Python distributed zip with all dependencies
I am trying to create a simple project with dependencies such as requests and to create a distributed zip file with the following command : python3.6 setup.py bdist --format=zip. In the dist zip file there should be also package.zip created with the following bash script:

```<code>#!/bin/bash
pip install -r requirements.txt --target ./packages
if [[ -d packages ]]; then
    cd packages
    find . -name "*.pyc" -delete
    find . -name "*.egg-info" | xargs rm -rf
    zip -9mrv packages.zip .
    mv packages.zip ..
    cd ..
    rm -rf packages
fi
</code>```

The final zip file contain the following files:

```<code>
Archive:  dist/test_python_zip-1.0.linux-x86_64.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2019-05-27 12:37   src/
        0  2019-05-27 12:37   __pycache__/
        0  2019-05-27 12:37   commands/
      187  2019-05-27 12:37   test_python_zip-1.0-py3.6.egg-info
        0  2019-05-22 19:18   __init__.py
      222  2019-05-27 12:34   __main__.py
        0  2019-05-27 12:37   src/commands/
        0  2019-05-27 12:37   src/commands/__pycache__/
       28  2019-05-22 17:47   src/commands/buy.py
       18  2019-05-22 19:02   src/commands/__init__.py
      246  2019-05-22 18:39   src/commands/hello.py
       30  2019-05-22 17:47   src/commands/start.py
      125  2019-05-27 12:37   src/commands/__pycache__/__init__.cpython-36.pyc
      337  2019-05-27 12:37   src/commands/__pycache__/hello.cpython-36.pyc
      214  2019-05-27 12:37   src/commands/__pycache__/start.cpython-36.pyc
      210  2019-05-27 12:37   src/commands/__pycache__/buy.cpython-36.pyc
       95  2019-05-27 12:37   __pycache__/__init__.cpython-36.pyc
      403  2019-05-27 12:37   __pycache__/__main__.cpython-36.pyc
        0  2019-05-27 12:37   commands/__pycache__/
       28  2019-05-22 17:47   commands/buy.py
       18  2019-05-22 19:02   commands/__init__.py
      246  2019-05-22 18:39   commands/hello.py
       30  2019-05-22 17:47   commands/start.py
      121  2019-05-27 12:37   commands/__pycache__/__init__.cpython-36.pyc
      333  2019-05-27 12:37   commands/__pycache__/hello.cpython-36.pyc
      210  2019-05-27 12:37   commands/__pycache__/start.cpython-36.pyc
      206  2019-05-27 12:37   commands/__pycache__/buy.cpython-36.pyc
---------                     -------
     3307                     27 files
</code>```

The setup.py file content is:

```<code>from distutils.command.bdist_dumb import bdist_dumb
from distutils.core import setup

class custom_bdist_dumb(bdist_dumb):

    def reinitialize_command(self, name, **kw):
        cmd = bdist_dumb.reinitialize_command(self, name, **kw)
        if name == 'install':
            cmd.install_lib = '/'
        return cmd

if __name__ == '__main__':
    setup(
        # our custom class override
        cmdclass={'bdist_dumb': custom_bdist_dumb},
        name='test_python_zip',
        version="1.0",
        py_modules=['__main__'],
        packages=['lib', 'src/commands'])

</code>```

The project tree is the following:

```<code>
.
├── build
│   ├── bdist.linux-x86_64
│   ├── lib
│   │   ├── commands
│   │   │   ├── buy.py
│   │   │   ├── hello.py
│   │   │   ├── __init__.py
│   │   │   └── start.py
│   │   ├── __init__.py
│   │   ├── __main__.py
│   │   └── src
│   │       └── commands
│   │           ├── buy.py
│   │           ├── hello.py
│   │           ├── __init__.py
│   │           └── start.py
│   └── lib.linux-x86_64-2.7
│       └── commands
│           ├── buy.py
│           ├── hello.py
│           ├── __init__.py
│           └── start.py
├── dist
│   └── test_python_zip-1.0.linux-x86_64.zip
├── __main__.py
├── packages.sh
├── packages.zip
├── __pycache__
├── requirements.txt
├── setup.py
├── src
│   ├── commands
│   │   ├── buy.py
│   │   ├── hello.py
│   │   ├── hello.pyc
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── __pycache__
│   │   └── start.py
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── packages.zip
│   └── test_python_zip.egg-info
│       ├── dependency_links.txt
│       ├── PKG-INFO
│       ├── SOURCES.txt
│       └── top_level.txt
└── test_python_zip.egg-info
    ├── dependency_links.txt
    ├── PKG-INFO
    ├── SOURCES.txt
    └── top_level.txt

</code>```

Finally the main.py file content is:

```<code>import sys

if not ('packages.zip' in sys.path):
    sys.path.insert(0, 'packages.zip')
print(sys.version)
print("\n \n")
print(sys.path)
from src.commands import hello

def main():
    hello.call()

if __name__ == '__main__':
    main()

</code>```

The problem here is that the requirements dependency is not loaded from the package.zip file and if it is not installed I got the following error:

```<code>3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0]

['lib', 'dist/test_python_zip-1.0.linux-x86_64.zip', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/yborisov/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']
Traceback (most recent call last):
  File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "dist/test_python_zip-1.0.linux-x86_64.zip/__main__.py", line 8, in <module>
  File "dist/test_python_zip-1.0.linux-x86_64.zip/src/commands/hello.py", line 1, in <module>
ModuleNotFoundError: No module named 'requests'
</code>```

What should be the problem and how I can resolved it?

答:
Instead of using package.zip in the final zip I used the package folder which I moved under src package. I added a MANIFEST.in with content

```<code>include  packages __main__.py
recursive-include  src/commands *
</code>```

The setup.py was changed to

```<code>from distutils.command.bdist_dumb import bdist_dumb
from distutils.core import setup

from setuptools import find_packages

class CustomBdistDumb(bdist_dumb):

    def reinitialize_command(self, name, **kw):
        cmd = bdist_dumb.reinitialize_command(self, name, **kw)
        if name == 'install':
            cmd.install_lib = '/'
        return cmd

setup(
    # our custom class override
    cmdclass={'bdist_dumb': CustomBdistDumb},
    name='test_python_zip',
    version="1.0",
    package_data={
        '': ['packages']
    },
    py_modules=['__main__'],
    packages=find_packages(),
)
</code>```

and the request module is loaded directly from the packages folder:

```<code>from src.packages import requests

URL = "https://api.ipify.org/?format=json"

def call():
    # sending get request and saving the response as response object
    r = requests.get(url=URL)

    # extracting data in json format
    data = r.json()
    print(data)
</code>```

Body:
I am trying to create a simple project with dependencies such as requests and to create a distributed zip file with the following command : python3.6 setup.py bdist --format=zip. In the dist zip file there should be also package.zip created with the following bash script:

#!/bin/bash
pip install -r requirements.txt --target ./packages
if [[ -d packages ]]; then
    cd packages
    find . -name "*.pyc" -delete
    find . -name "*.egg-info" | xargs rm -rf
    zip -9mrv packages.zip .
    mv packages.zip ..
    cd ..
    rm -rf packages
fi

The final zip file contain the following files:

Archive:  dist/test_python_zip-1.0.linux-x86_64.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2019-05-27 12:37   src/
        0  2019-05-27 12:37   __pycache__/
        0  2019-05-27 12:37   commands/
      187  2019-05-27 12:37   test_python_zip-1.0-py3.6.egg-info
        0  2019-05-22 19:18   __init__.py
      222  2019-05-27 12:34   __main__.py
        0  2019-05-27 12:37   src/commands/
        0  2019-05-27 12:37   src/commands/__pycache__/
       28  2019-05-22 17:47   src/commands/buy.py
       18  2019-05-22 19:02   src/commands/__init__.py
      246  2019-05-22 18:39   src/commands/hello.py
       30  2019-05-22 17:47   src/commands/start.py
      125  2019-05-27 12:37   src/commands/__pycache__/__init__.cpython-36.pyc
      337  2019-05-27 12:37   src/commands/__pycache__/hello.cpython-36.pyc
      214  2019-05-27 12:37   src/commands/__pycache__/start.cpython-36.pyc
      210  2019-05-27 12:37   src/commands/__pycache__/buy.cpython-36.pyc
       95  2019-05-27 12:37   __pycache__/__init__.cpython-36.pyc
      403  2019-05-27 12:37   __pycache__/__main__.cpython-36.pyc
        0  2019-05-27 12:37   commands/__pycache__/
       28  2019-05-22 17:47   commands/buy.py
       18  2019-05-22 19:02   commands/__init__.py
      246  2019-05-22 18:39   commands/hello.py
       30  2019-05-22 17:47   commands/start.py
      121  2019-05-27 12:37   commands/__pycache__/__init__.cpython-36.pyc
      333  2019-05-27 12:37   commands/__pycache__/hello.cpython-36.pyc
      210  2019-05-27 12:37   commands/__pycache__/start.cpython-36.pyc
      206  2019-05-27 12:37   commands/__pycache__/buy.cpython-36.pyc
---------                     -------
     3307                     27 files

The setup.py file content is:

from distutils.command.bdist_dumb import bdist_dumb
from distutils.core import setup

class custom_bdist_dumb(bdist_dumb):

    def reinitialize_command(self, name, **kw):
        cmd = bdist_dumb.reinitialize_command(self, name, **kw)
        if name == 'install':
            cmd.install_lib = '/'
        return cmd

if __name__ == '__main__':
    setup(
        # our custom class override
        cmdclass={'bdist_dumb': custom_bdist_dumb},
        name='test_python_zip',
        version="1.0",
        py_modules=['__main__'],
        packages=['lib', 'src/commands'])

The project tree is the following:

.
├── build
│   ├── bdist.linux-x86_64
│   ├── lib
│   │   ├── commands
│   │   │   ├── buy.py
│   │   │   ├── hello.py
│   │   │   ├── __init__.py
│   │   │   └── start.py
│   │   ├── __init__.py
│   │   ├── __main__.py
│   │   └── src
│   │       └── commands
│   │           ├── buy.py
│   │           ├── hello.py
│   │           ├── __init__.py
│   │           └── start.py
│   └── lib.linux-x86_64-2.7
│       └── commands
│           ├── buy.py
│           ├── hello.py
│           ├── __init__.py
│           └── start.py
├── dist
│   └── test_python_zip-1.0.linux-x86_64.zip
├── __main__.py
├── packages.sh
├── packages.zip
├── __pycache__
├── requirements.txt
├── setup.py
├── src
│   ├── commands
│   │   ├── buy.py
│   │   ├── hello.py
│   │   ├── hello.pyc
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── __pycache__
│   │   └── start.py
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── packages.zip
│   └── test_python_zip.egg-info
│       ├── dependency_links.txt
│       ├── PKG-INFO
│       ├── SOURCES.txt
│       └── top_level.txt
└── test_python_zip.egg-info
    ├── dependency_links.txt
    ├── PKG-INFO
    ├── SOURCES.txt
    └── top_level.txt

Finally the main.py file content is:

import sys

if not ('packages.zip' in sys.path):
    sys.path.insert(0, 'packages.zip')
print(sys.version)
print("\n \n")
print(sys.path)
from src.commands import hello

def main():
    hello.call()

if __name__ == '__main__':
    main()

The problem here is that the requirements dependency is not loaded from the package.zip file and if it is not installed I got the following error:

3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0]

['lib', 'dist/test_python_zip-1.0.linux-x86_64.zip', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/yborisov/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']
Traceback (most recent call last):
  File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "dist/test_python_zip-1.0.linux-x86_64.zip/__main__.py", line 8, in <module>
  File "dist/test_python_zip-1.0.linux-x86_64.zip/src/commands/hello.py", line 1, in <module>
ModuleNotFoundError: No module named 'requests'

What should be the problem and how I can resolved it?

Body:
Instead of using package.zip in the final zip I used the package folder which I moved under src package. I added a MANIFEST.in with content

include  packages __main__.py
recursive-include  src/commands *

The setup.py was changed to

from distutils.command.bdist_dumb import bdist_dumb
from distutils.core import setup

from setuptools import find_packages

class CustomBdistDumb(bdist_dumb):

    def reinitialize_command(self, name, **kw):
        cmd = bdist_dumb.reinitialize_command(self, name, **kw)
        if name == 'install':
            cmd.install_lib = '/'
        return cmd

setup(
    # our custom class override
    cmdclass={'bdist_dumb': CustomBdistDumb},
    name='test_python_zip',
    version="1.0",
    package_data={
        '': ['packages']
    },
    py_modules=['__main__'],
    packages=find_packages(),
)

and the request module is loaded directly from the packages folder:

from src.packages import requests

URL = "https://api.ipify.org/?format=json"

def call():
    # sending get request and saving the response as response object
    r = requests.get(url=URL)

    # extracting data in json format
    data = r.json()
    print(data)


来源: stackexchange

问:
How to make an image of a <ImageBackground> tag darker (React Native)
I'm trying to create an image with a text on it, and in order for the the text to be clearly seen I need to make the image darker.
Also (don't sure if it matters or not) I need the background image to be touchable.
This question was asked several times here and I've seen some answers, but none of them worked for me, so I'm wondering if I'm missing something more crucial here.

My code is the following:

```<code><View style={postStyles.container}>
<TouchableOpacity onPress={() =>
this.props.navigation.navigate('AnotherWindow')}>
    <ImageBackground source={require('../../assets/images/my_img.jpg')}
     style={{width: '100%', height: 150}}>
            <Text style={postStyles.title} numberOfLines={2}>
                My text
             </Text>
    </ImageBackground></TouchableOpacity>
</code>```

From looking around here, I've tried the following solutions:

Tried to wrap the text element inside the imagebackground tag inside a
 View element that has a style property of "backgroundColor" with value of 'rgba(255,0,0,0.5)' (also tried different values),

Tried to add this backgroundColor property to the styles of both the container itself, the TouchableOpacity element

Tried to above two solutions with the "elevation" property instead of backgroundColor (I work in Android).

None of the above solutions worked, in a sense that the background image didn't change at all, so I'm wondering if I'm missing something more crucial.

Thanks!

答:
If anyone still having problems with the ImageBackground component, this is how i solved it, basically i set a view inside the image background which has the backgroundColor that darkens the image.</p>

```<code> <ImageBackground
      source={Images.background}
      style={styles.imageBackground}
    >
      <View style={styles.innerContainer}>
      {content}
      </View>
 </ImageBackground>

const styles = StyleSheet.create({
      imageBackground: {
        height: '100%',
        width: '100%'
      },
      innerContainer: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0, 0.60)'
      },
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create an image with a text on it, and in order for the the text to be clearly seen I need to make the image darker.
Also (don't sure if it matters or not) I need the background image to be touchable.
This question was asked several times here and I've seen some answers, but none of them worked for me, so I'm wondering if I'm missing something more crucial here.

My code is the following:

<View style={postStyles.container}>
<TouchableOpacity onPress={() =>
this.props.navigation.navigate('AnotherWindow')}>
    <ImageBackground source={require('../../assets/images/my_img.jpg')}
     style={{width: '100%', height: 150}}>
            <Text style={postStyles.title} numberOfLines={2}>
                My text
             </Text>
    </ImageBackground></TouchableOpacity>

From looking around here, I've tried the following solutions:

Tried to wrap the text element inside the imagebackground tag inside a
 View element that has a style property of "backgroundColor" with value of 'rgba(255,0,0,0.5)' (also tried different values),

Tried to add this backgroundColor property to the styles of both the container itself, the TouchableOpacity element

Tried to above two solutions with the "elevation" property instead of backgroundColor (I work in Android).

None of the above solutions worked, in a sense that the background image didn't change at all, so I'm wondering if I'm missing something more crucial.

Thanks!

Body:
If anyone still having problems with the ImageBackground component, this is how i solved it, basically i set a view inside the image background which has the backgroundColor that darkens the image.

 <ImageBackground
      source={Images.background}
      style={styles.imageBackground}
    >
      <View style={styles.innerContainer}>
      {content}
      </View>
 </ImageBackground>

const styles = StyleSheet.create({
      imageBackground: {
        height: '100%',
        width: '100%'
      },
      innerContainer: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0, 0.60)'
      },
});


问:
What to do when android doesn't detect my .css and .js files when I run index.html?
I wrote a .html file that uses css(style.css) and javascript(app.js).
When I transferred the folder containing the index.html,style.css and app.js over to my android internal memory,the browser runs the html file but my .css and .js files are not detected.

```<code>            <!DOCTYPE html>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <head>
            <link href="style.css" rel="stylesheet" >
            </head>
            <body>
             ....
            </body>
            <script src="app.js" charset="utf-8"></script>
</code>```

I have tried using "/style.css" and "./style.css".
But none of them are helping in detecting the files.

Inline styles in the index.html file work fine and show up in my browser.

Using Chrome on Android 8.1.0 (MIUI 10.1|Stable)

答:
You can load your files somewhere in your device like this :

file:///storage/emulated/0/MyDirectory/index.html

file:///storage/emulated/0/MyDirectory/style.css

file:///storage/emulated/0/MyDirectory/app.js

And then try to address thoes in src and href.

For testing purposes you can also use applications that let you run local servers on your device, like this one: https://play.google.com/store/apps/details?id=com.esminis.server.apache

Body:
I wrote a .html file that uses css(style.css) and javascript(app.js).
When I transferred the folder containing the index.html,style.css and app.js over to my android internal memory,the browser runs the html file but my .css and .js files are not detected.

            <!DOCTYPE html>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">

            <link href="style.css" rel="stylesheet" >

             ....

I have tried using "/style.css" and "./style.css".
But none of them are helping in detecting the files.

Inline styles in the index.html file work fine and show up in my browser.

Using Chrome on Android 8.1.0 (MIUI 10.1|Stable)


问:
NestJS: Adding verification options to AuthGuard with JWT
I am trying to make use of the AuthGuard decorator, and the passport JWT strategy, following the documentation.

Everything in the documentation works great. But I now want to protect a route with a scope contained in the JWT. So here is a basic jwt payload generated by my application:

{
  "user": {
    "id": "20189c4f-1183-4216-8b48-333ddb825de8",
    "username": "user.test@gmail.com"
  },
  "scope": [
    "manage_server"
  ],
  "iat": 1534766258,
  "exp": 1534771258,
  "iss": "15f2463d-8810-44f9-a908-801872ded159",
  "sub": "20189c4f-1183-4216-8b48-333ddb825de8",
  "jti": "078047bc-fc1f-4c35-8abe-72834f7bcc44"
}
```

<p>Here is the basic protected route being guarded by the <code>AuthGuard</code> decorator:</p>

<pre class="lang-js prettyprint-override"><code>@Get('protected')
@UseGuards(AuthGuard('jwt'))
async protected(): Promise<string> {
    return 'Hello Protected World';
}
</code>```

I would like to add options and restrict the access of that route to the people having the manager_server scope into their JWT. So after reading a little bit of the AuthGuard code, I thought that I was able to write something like:

@Get('protected')
@UseGuards(AuthGuard('jwt', {
    scope: 'manage_server'
}))
async protected(): Promise<string> {
    return 'Hello Protected World';
}
```

<p><strong>However, I can't see in the documentation where I could make use of this option.</strong> </p>

<p>I thought that adding an option argument to the <code>validate</code> function of the <code>JWTStrategy</code> could make the trick, but it does not. Here is my <code>validate</code> function (contained in the <code>jwt.strategy.ts</code> file):</p>

<pre class="lang-js prettyprint-override"><code>async validate(payload: JwtPayload, done: ((err: any, value: any) => void)) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
        return done(new UnauthorizedException(), false);
    }
    done(null, user);
}
</code>```

Thank you very much for your help and don't hesitate to ask me for more informations in the comments if you need so.

答:
I tried a slightly different approach, by extending the AuthGuard guard. I wanted to maintain the ability to use different Passport Strategies, so I included a mixin. Feedback is appreciated.

In your Jwt strategy you could simply return the JwtPaylozd so that the user has a scopes attribute. Then the custom AuthGuard looks like this:

```<code>import { UnauthorizedException, mixin } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

export function AuthScopes(scopes: string[], type?: string | string[]) {
    return mixin(class ScopesAuth extends AuthGuard(type) {
        protected readonly scopes = scopes;
        handleRequest(err, user, info, context) {
        if (err || !user) {
            throw err || new UnauthorizedException();
        }

        if(!this.scopes.some(s => user.scopes.split(' ').includes(s)))
        {
            throw new UnauthorizedException(`JWT does not possess one of the required scopes (${this.scopes.join(',')})`);
        }
        return user;
        }
    });
  }
</code>```

You can then use this guard like so:

```<code>@Get('protected')
@UseGuards(AuthScopes(['secret:read'], 'jwt'))
async protected(): Promise<string> {
    return 'Hello Protected World';
}
</code>```

'jwt' represents the strategy.

Body:
I am trying to make use of the AuthGuard decorator, and the passport JWT strategy, following the documentation.

Everything in the documentation works great. But I now want to protect a route with a scope contained in the JWT. So here is a basic jwt payload generated by my application:

{
  "user": {
    "id": "20189c4f-1183-4216-8b48-333ddb825de8",
    "username": "user.test@gmail.com"
  },
  "scope": [
    "manage_server"
  ],
  "iat": 1534766258,
  "exp": 1534771258,
  "iss": "15f2463d-8810-44f9-a908-801872ded159",
  "sub": "20189c4f-1183-4216-8b48-333ddb825de8",
  "jti": "078047bc-fc1f-4c35-8abe-72834f7bcc44"
}

Here is the basic protected route being guarded by the AuthGuard decorator:

@Get('protected')
@UseGuards(AuthGuard('jwt'))
async protected(): Promise<string> {
    return 'Hello Protected World';
}

I would like to add options and restrict the access of that route to the people having the manager_server scope into their JWT. So after reading a little bit of the AuthGuard code, I thought that I was able to write something like:

@Get('protected')
@UseGuards(AuthGuard('jwt', {
    scope: 'manage_server'
}))
async protected(): Promise<string> {
    return 'Hello Protected World';
}

However, I can't see in the documentation where I could make use of this option.

I thought that adding an option argument to the validate function of the JWTStrategy could make the trick, but it does not. Here is my validate function (contained in the jwt.strategy.ts file):

async validate(payload: JwtPayload, done: ((err: any, value: any) => void)) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
        return done(new UnauthorizedException(), false);
    }
    done(null, user);
}

Thank you very much for your help and don't hesitate to ask me for more informations in the comments if you need so.

Body:
I tried a slightly different approach, by extending the AuthGuard guard. I wanted to maintain the ability to use different Passport Strategies, so I included a mixin. Feedback is appreciated.

In your Jwt strategy you could simply return the JwtPaylozd so that the user has a scopes attribute. Then the custom AuthGuard looks like this:

import { UnauthorizedException, mixin } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

export function AuthScopes(scopes: string[], type?: string | string[]) {
    return mixin(class ScopesAuth extends AuthGuard(type) {
        protected readonly scopes = scopes;
        handleRequest(err, user, info, context) {
        if (err || !user) {
            throw err || new UnauthorizedException();
        }

        if(!this.scopes.some(s => user.scopes.split(' ').includes(s)))
        {
            throw new UnauthorizedException(`JWT does not possess one of the required scopes (${this.scopes.join(',')})`);
        }
        return user;
        }
    });
  }

You can then use this guard like so:

@Get('protected')
@UseGuards(AuthScopes(['secret:read'], 'jwt'))
async protected(): Promise<string> {
    return 'Hello Protected World';
}

'jwt' represents the strategy.


问:
Handle UnicodeEncodeError in python2.7
I have the following code :

```<code>    for index, row in df_out.iterrows():
        yield {
               'CustomerName': str(row['CustomerName'])
              }
</code>```

and I get the the UnicodeEncodeError:

```<code>RuntimeError: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)
</code>```

How can I handle this part in order to avoid that error?

```<code>str(row['CustomerName'])
</code>```

答:
If you are potentially dealing with non-ASCII text in python2, then doing

```<code>str(some_text)
</code>```

is usually bad idea, because you will get a UnicodeEncodeError if some_text contains non-ASCII characters. The correct code would be

```<code>unicode(some_text)
</code>```

as unicode() will not try to encode your text as ASCII.

However given this code

```<code>for index, row in df_out.iterrows():
    yield {
           'CustomerName': str(row['CustomerName'])
          }
</code>```

it's very likely that row['CustomerName'] is already  a unicode object, so calling unicode on it would be redundant.  This will probably work:

```<code>for index, row in df_out.iterrows():
    yield {
           'CustomerName': row['CustomerName']
          }
</code>```

To summarise: remove the str call.  If that doesn't work, try replacing str with unicode.

Title: Handle UnicodeEncodeError in python2.7

Body:
I have the following code :

    for index, row in df_out.iterrows():
        yield {
               'CustomerName': str(row['CustomerName'])
              }

and I get the the UnicodeEncodeError:

RuntimeError: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)

How can I handle this part in order to avoid that error?

str(row['CustomerName'])

Body:
If you are potentially dealing with non-ASCII text in python2, then doing

str(some_text)

is usually bad idea, because you will get a UnicodeEncodeError if some_text contains non-ASCII characters. The correct code would be

unicode(some_text)

as unicode() will not try to encode your text as ASCII.

However given this code

for index, row in df_out.iterrows():
    yield {
           'CustomerName': str(row['CustomerName'])
          }

it's very likely that row['CustomerName'] is already  a unicode object, so calling unicode on it would be redundant.  This will probably work:

for index, row in df_out.iterrows():
    yield {
           'CustomerName': row['CustomerName']
          }

To summarise: remove the str call.  If that doesn't work, try replacing str with unicode.


问:
How to set default values for fields in records in Clojure?
I am creating records in Clojure and would like to set some fields up with a default value. How can I do this?</p>

答:
Use a constructor function.

```<code>(defrecord Foo [a b c])

(defn make-foo
  [& {:keys [a b c] :or {a 5 c 7}}]
  (Foo. a b c))

(make-foo :b 6)
(make-foo :b 6 :a 8)
</code>```

Of course there are various variations. You could for example require certain fields to be non-optional and without a default.

```<code>(defn make-foo
  [b & {:keys [a c] :or {a 5 c 7}}]
  (Foo. a b c))

(make-foo 6)
(make-foo 6 :a 8)
</code>```

YMMV.

ContentLicense: CC BY-SA 3.0

Body:
Use a constructor function.

(defrecord Foo [a b c])

(defn make-foo
  [& {:keys [a b c] :or {a 5 c 7}}]
  (Foo. a b c))

(make-foo :b 6)
(make-foo :b 6 :a 8)

Of course there are various variations. You could for example require certain fields to be non-optional and without a default.

(defn make-foo
  [b & {:keys [a c] :or {a 5 c 7}}]
  (Foo. a b c))

(make-foo 6)
(make-foo 6 :a 8)

YMMV.


问:
Color row of Datatable using a SQL query in ASP.NET C#
I need to color rows of my asp.net c# table.
To show the table, Im using one ASP:Repeater with html:

```<code><div class="panel-body">
<div class="table-responsive">
    <table class="table table-striped table-bordered table-hover" id="dataTables-MaquinasCaidas" >
        <thead>
            <tr>
                <th>Hora Reportada</th>
                <th>Máquina</th>
            </tr>
        </thead>
        <tbody>
            <asp:Repeater ID="repeaterMaquinaCaida" runat="server">
                <ItemTemplate>

                    <tr>
                        <td>
                            <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />
                        </td>
                        <td>
                            <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />
                        </td>
                    </tr>

                </ItemTemplate>
            </asp:Repeater>
        </tbody>
    </table>
</div>
</code>```

in .cs page, to fill the table:

```<code>public void fillTable()
    {
        string query = "SELECT * FROM MaquinaCaida order by HoraReportada asc";
        DataTable tableResponse = SqlComm.SqlDataTable(query);
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        if (!IsPostBack)
        {
            repeaterMaquinaCaida.DataSource = tableResponse;
            repeaterMaquinaCaida.DataBind();
        }
</code>```

I just need to color some rows based on condition, like:

```<code>SELECT * FROM Table WHERE Column = "something";
</code>```

And then change the color of the row to red, for example.

Is there a way to perform this action??

答:
You can tap into the ItemDataBound event, check the row data source for a certain condition, and then alter the row class.

```<code><asp:Repeater ID="repeaterMaquinaCaida" runat="server" OnItemDataBound="ItemDataBound"

void ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
  // Execute the following logic for Items and Alternating Items.
  if (e.Item.ItemType == ListItemType.Item ||
      e.Item.ItemType == ListItemType.AlternatingItem)
  {
    if (((Evaluation)e.Item.DataItem).Rating == "Good") //check your logic here
    {
      ((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>"; //change row here
    }
  }
}
</code>```

https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater.itemdatabound?redirectedfrom=MSDN&view=netframework-4.8

Body:
I need to color rows of my asp.net c# table.
To show the table, Im using one ASP:Repeater with html:

                Hora Reportada
                Máquina

            <asp:Repeater ID="repeaterMaquinaCaida" runat="server">
                <ItemTemplate>

                            <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />

                            <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />

                </ItemTemplate>
            </asp:Repeater>

in .cs page, to fill the table:

public void fillTable()
    {
        string query = "SELECT * FROM MaquinaCaida order by HoraReportada asc";
        DataTable tableResponse = SqlComm.SqlDataTable(query);
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        if (!IsPostBack)
        {
            repeaterMaquinaCaida.DataSource = tableResponse;
            repeaterMaquinaCaida.DataBind();
        }

I just need to color some rows based on condition, like:

SELECT * FROM Table WHERE Column = "something";

And then change the color of the row to red, for example.

Is there a way to perform this action??

Body:
You can tap into the ItemDataBound event, check the row data source for a certain condition, and then alter the row class.

<asp:Repeater ID="repeaterMaquinaCaida" runat="server" OnItemDataBound="ItemDataBound"

void ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
  // Execute the following logic for Items and Alternating Items.
  if (e.Item.ItemType == ListItemType.Item ||
      e.Item.ItemType == ListItemType.AlternatingItem)
  {
    if (((Evaluation)e.Item.DataItem).Rating == "Good") //check your logic here
    {
      ((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>"; //change row here
    }
  }
}

https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater.itemdatabound?redirectedfrom=MSDN&view=netframework-4.8


问:
Exactly-once semantics in spring Kafka
I need to apply transactions in a system that comprises of below components:

A Kafka producer, this is some external application which would publish messages on a kafka topic.

A Kafka consumer, this is a spring boot application where I have configured the kafka listener and after processing the message, it needs to be saved to a NoSQL database.

I have gone through several blogs like this & this, and all of them talks about the transactions in context of streaming application, where the messages would be read-processed-written back to a Kafka topic.

I don't see any clear example or blog around achieving transactionality in the use case similar to mine i.e. producing-processing-writing to a DB in a single atomic transaction. I believe it to be very common scenario & there must be some support for it as well.

Can someone please guide me on how to achieve this? Any relevant code snippet would be greatly appreciated.

答:
I'm guessing you're trying to solve the scenario where your consumer goes down after writing to the database but before committing the offsets, or other similar problems.  Unfortunately this means you have to build your own fault-tolerance.

In the case of the problem I mentioned above, this means you would have to manage the consumer offsets in your end-output database, updating them in the same database transaction that you're writing the output of your consumer application to.

Title: Exactly-once semantics in spring Kafka


问:
Private inheritance: name lookup error
I have the following code example that doesn't compile:

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

namespace my
{
    class base1
    { // line 6
    };

    class base2: private base1
    {
    };

    class derived: private base2
    {
    public:
        // The following function just wants to print a pointer, nothing else!
        void print(base1* pointer) {printf("%p\n", pointer);}
    };
}
</code>```

The error that gcc prints is:

test.cpp:6: error: `class my::base1'
  is inaccessible

test.cpp:17: error: within this
  context

Now, i can guess what the problem is: when looking at the declaration of print, the compiler sees base1 and thinks: base1 is the base-class subobject of derived* this, but you don't have access to it! While i intend that base1 should be just a type name.

How can i see in the C++ Standard that this is a correct behavior, and not a bug in the compiler (i am sure it's not a bug; all compilers i checked behaved so)?

How should i fix this error? All the following fixes work, but which one should i choose?

void print(class base1* pointer) {}

void print(::my:: base1* pointer) {}

class base1;
  void print(base1* pointer) {}

Edit:

```<code>int main()
{
    my::base1 object1;
    my::derived object3;
    object3.print(&object1);
}
</code>```

答:
The section you're looking for is 11.1. It suggests using ::my::base1* to work around this:

[ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. — end note ]

```<code>[ Example:
class A { };
class B : private A { };
class C : public B {
A *p;
// error: injected-class-name A is inaccessible
:: A * q ;
// OK
};
</code>```

Title: Private inheritance: name lookup error

Body:
I have the following code example that doesn't compile:

#include <stdio.h>

namespace my
{
    class base1
    { // line 6
    };

    class base2: private base1
    {
    };

    class derived: private base2
    {
    public:
        // The following function just wants to print a pointer, nothing else!
        void print(base1* pointer) {printf("%p\n", pointer);}
    };
}

The error that gcc prints is:

test.cpp:6: error: `class my::base1'
  is inaccessible

test.cpp:17: error: within this
  context

Now, i can guess what the problem is: when looking at the declaration of print, the compiler sees base1 and thinks: base1 is the base-class subobject of derived* this, but you don't have access to it! While i intend that base1 should be just a type name.

How can i see in the C++ Standard that this is a correct behavior, and not a bug in the compiler (i am sure it's not a bug; all compilers i checked behaved so)?

How should i fix this error? All the following fixes work, but which one should i choose?

void print(class base1* pointer) {}

void print(::my:: base1* pointer) {}

class base1;
  void print(base1* pointer) {}

Edit:

int main()
{
    my::base1 object1;
    my::derived object3;
    object3.print(&object1);
}

Body:
The section you're looking for is 11.1. It suggests using ::my::base1* to work around this:

[ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. — end note ]

[ Example:
class A { };
class B : private A { };
class C : public B {
A *p;
// error: injected-class-name A is inaccessible
:: A * q ;
// OK
};


问:
Can't install gems using asdf
So I'm switching to a project that is using ruby. They use asdf as a package manager

I’m having trouble installing the gems, I’m using zsh and I’m thinking there might be an issue with the paths

Running gem install bundler outputs: You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

ruby -v
outputs: ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]

which ruby
output: /usr/bin/ruby

And I tried setting a global version for ruby with asdf global ruby 2.5.3 but that doesn’t seem to change the version

This is my gem environment:

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.5.2.3
  - RUBY VERSION: 2.3.7 (2018-03-28 patchlevel 456) [universal.x86_64-darwin18]
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/2.3.0
  - USER INSTALLATION DIRECTORY: /Users/carlos.grijalva/.gem/ruby/2.3.0
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - SPEC CACHE DIRECTORY: /Users/carlos.grijalva/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Library/Ruby/Site
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-18
  - GEM PATHS:
     - /Library/Ruby/Gems/2.3.0
     - /Users/carlos.grijalva/.gem/ruby/2.3.0
     - /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/gems/2.3.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/carlos.grijalva/.asdf/shims
     - /Users/carlos.grijalva/.asdf/bin
     - /Users/carlos.grijalva/bin
     - /usr/local/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
</code>```

答:
It sounds like you may need to add the relevant lines to your .zshrc so asdf shims get recognized. You can find the instructions here

For macOS & zsh the correct lines to append to .zshrc are:

```<code>echo -e '\n. $HOME/.asdf/asdf.sh' >> ~/.zshrc
echo -e '\n. $HOME/.asdf/completions/asdf.bash' >> ~/.zshrc
</code>```

After doing so, either source ~/.zshrc or restart your terminal

Title: Can't install gems using asdf

Body:
So I'm switching to a project that is using ruby. They use asdf as a package manager

I’m having trouble installing the gems, I’m using zsh and I’m thinking there might be an issue with the paths

Running gem install bundler outputs: You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory.

ruby -v
outputs: ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18]

which ruby
output: /usr/bin/ruby

And I tried setting a global version for ruby with asdf global ruby 2.5.3 but that doesn’t seem to change the version

This is my gem environment:

RubyGems Environment:
  - RUBYGEMS VERSION: 2.5.2.3
  - RUBY VERSION: 2.3.7 (2018-03-28 patchlevel 456) [universal.x86_64-darwin18]
  - INSTALLATION DIRECTORY: /Library/Ruby/Gems/2.3.0
  - USER INSTALLATION DIRECTORY: /Users/carlos.grijalva/.gem/ruby/2.3.0
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - SPEC CACHE DIRECTORY: /Users/carlos.grijalva/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Library/Ruby/Site
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-18
  - GEM PATHS:
     - /Library/Ruby/Gems/2.3.0
     - /Users/carlos.grijalva/.gem/ruby/2.3.0
     - /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/gems/2.3.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/carlos.grijalva/.asdf/shims
     - /Users/carlos.grijalva/.asdf/bin
     - /Users/carlos.grijalva/bin
     - /usr/local/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin

Body:
It sounds like you may need to add the relevant lines to your .zshrc so asdf shims get recognized. You can find the instructions here

For macOS & zsh the correct lines to append to .zshrc are:

echo -e '\n. $HOME/.asdf/asdf.sh' >> ~/.zshrc
echo -e '\n. $HOME/.asdf/completions/asdf.bash' >> ~/.zshrc

After doing so, either source ~/.zshrc or restart your terminal


问:
why transparent drawbox does not work on some video sources?
It works on smptebars, smptehdbars, testsrc and testsrc2 but not other sources.

```<code>ffplay -loglevel trace -f lavfi -i testsrc=r=1:d=1:size=800x600 -vf "drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"
</code>```

When I try this I can see the transparent box. But if I use color, and rgbtestsrc sources it does not work.

```<code>ffplay -loglevel trace -f lavfi -i rgbtestsrc=r=1:d=1:size=800x600 -vf "drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"
ffplay -loglevel trace -f lavfi -i color=c=red:r=1:d=1:size=800x600 -vf "drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"
</code>```

after looking at the trace output, it seems the transparency only works on rgb24 and yuv formats (yuv444p, yuv420p, etc.), this is surprising since we normally assume the rgba source can work with alpha channel.

The following command change the pix_fmt to rgb24, then it works:

```<code>ffplay -loglevel trace -f lavfi -i rgbtestsrc=r=1:d=1:size=800x600 -vf "format=pix_fmts=rgb24,drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"
</code>```

The following command change the pix_fmt to rgba, then it does not work:

```<code>ffplay -loglevel trace -f lavfi -i rgbtestsrc=r=1:d=1:size=800x600 -vf "format=pix_fmts=rgba,drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"
</code>```

Why is that? and how can I fix this?

答: Can't reproduce here. You're using an old build of ffmpeg. There was a bug in drawbox to do with transparency, but it was fixed in Dec 2017.</p>

Body:
It works on smptebars, smptehdbars, testsrc and testsrc2 but not other sources.

ffplay -loglevel trace -f lavfi -i testsrc=r=1:d=1:size=800x600 -vf "drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"

When I try this I can see the transparent box. But if I use color, and rgbtestsrc sources it does not work.

ffplay -loglevel trace -f lavfi -i rgbtestsrc=r=1:d=1:size=800x600 -vf "drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"
ffplay -loglevel trace -f lavfi -i color=c=red:r=1:d=1:size=800x600 -vf "drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"

after looking at the trace output, it seems the transparency only works on rgb24 and yuv formats (yuv444p, yuv420p, etc.), this is surprising since we normally assume the rgba source can work with alpha channel.

The following command change the pix_fmt to rgb24, then it works:

ffplay -loglevel trace -f lavfi -i rgbtestsrc=r=1:d=1:size=800x600 -vf "format=pix_fmts=rgb24,drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"

The following command change the pix_fmt to rgba, then it does not work:

ffplay -loglevel trace -f lavfi -i rgbtestsrc=r=1:d=1:size=800x600 -vf "format=pix_fmts=rgba,drawbox=x=0:y=0:w='iw/2':h='ih/2':t=max:c=white@0.5"

Why is that? and how can I fix this?


问:
adobe flex extreme components
In my project, we are using Adobe flex extreme components to show grids. i see the grid as below in my jsp( with filters)

```<code>    <ec:table items="searchResults"
    var="searchResults"
    imagePath="${pageContext.request.contextPath}/static/images/table/*.gif"
    view="buttonsOnBottom"
    retrieveRowsCallback="limit"
    filterRowsCallback="limit"
    sortRowsCallback="limit"
    ...    >
 ..
</code>```

what is the function of these three: retrieveRowsCallback,filterRowsCallback,sortRowsCallback.

 What I want is this:

 When the grid loads, show a prefiltered list(e.g. only records with status = 'Active'). The server side can easily return the filtered list, but on the grid , the filter value is shown as 'blank' instead of 'Active'.

Thank you.

答: "Adobe flex extreme components" doesn't exist, or so says google.  This is a 3rd party library and not standard Flex component. You should look up the 3rd party documentation to see what those do.</p>

Title: adobe flex extreme components

Body:
In my project, we are using Adobe flex extreme components to show grids. i see the grid as below in my jsp( with filters)

    <ec:table items="searchResults"
    var="searchResults"
    imagePath="${pageContext.request.contextPath}/static/images/table/*.gif"
    view="buttonsOnBottom"
    retrieveRowsCallback="limit"
    filterRowsCallback="limit"
    sortRowsCallback="limit"
    ...    >
 ..

what is the function of these three: retrieveRowsCallback,filterRowsCallback,sortRowsCallback.

 What I want is this:

 When the grid loads, show a prefiltered list(e.g. only records with status = 'Active'). The server side can easily return the filtered list, but on the grid , the filter value is shown as 'blank' instead of 'Active'.

Thank you.


问:
Mutate only applies to the value of the first column
I'm trying to remove a substring from the values of a column, my data looks something like this:

```<code>LBL       Var1      Var2
name1       1        12
name1_A     1        13
name1_B     2        10
name2       1        11
name2_A     2        10
name2_B     3        9
</code>```

I have already created a function that works on a single string, but when I try to mutate the data frame it shows the result of the first row and does not apply on the rest of the rows. What am I doing wrong?

This is the function that I have created so far:

```<code>remExt <- function(x){
  y <- str_split_fixed(x,"_",2)
  return(y[1])
}
</code>```

I have tried the function with a single string and it works perfectly:

```<code>string1 <- "Yes_No"

res <- remExt(string1)
print(res)

</code>```

[1] "Yes"

I try the mutate with the following instruction:

```<code>df %>% mutate(newLBL = remExt(df$LBL))
</code>```

And I get the following result:

```<code>LBL       Var1      Var2   newLBL
name1       1        12    name1
name1_A     1        13    name1
name1_B     2        10    name1
name2       1        11    name1
name2_A     2        10    name1
name2_B     3        9     name1
</code>```

My expected result is:

```<code>LBL       Var1      Var2   newLBL
name1       1        12    name1
name1_A     1        13    name1
name1_B     2        10    name1
name2       1        11    name2
name2_A     2        10    name2
name2_B     3        9     name2
</code>```

But just can't seem to get it to work, any ideas?

答:
You're only taking the first element from y, you want the first column with y[,1]:

```<code>remExt <- function(x){
  y <- str_split_fixed(x,"_",2)
  return(y[,1])
}

df %>% mutate(newLBL = remExt(LBL))
      LBL Var1 Var2 newLBL
1   name1    1   12  name1
2 name1_A    1   13  name1
3 name1_B    2   10  name1
4   name2    1   11  name2
5 name2_A    2   10  name2
6 name2_B    3    9  name2
</code>```

Also note with mutate you don't need to extract the column with $

EDIT:

A simpler implementation would be to use str_remove or str_replace. Both the following are equivalent:

```<code>df %>% mutate(newLBL = str_replace(LBL,"\\_.",""))

df %>% mutate(newLBL = str_remove(LBL,"\\_."))
</code>```

Body:
I'm trying to remove a substring from the values of a column, my data looks something like this:

LBL       Var1      Var2
name1       1        12
name1_A     1        13
name1_B     2        10
name2       1        11
name2_A     2        10
name2_B     3        9

I have already created a function that works on a single string, but when I try to mutate the data frame it shows the result of the first row and does not apply on the rest of the rows. What am I doing wrong?

This is the function that I have created so far:

remExt <- function(x){
  y <- str_split_fixed(x,"_",2)
  return(y[1])
}

I have tried the function with a single string and it works perfectly:

string1 <- "Yes_No"

res <- remExt(string1)
print(res)

[1] "Yes"

I try the mutate with the following instruction:

df %>% mutate(newLBL = remExt(df$LBL))

And I get the following result:

LBL       Var1      Var2   newLBL
name1       1        12    name1
name1_A     1        13    name1
name1_B     2        10    name1
name2       1        11    name1
name2_A     2        10    name1
name2_B     3        9     name1

My expected result is:

LBL       Var1      Var2   newLBL
name1       1        12    name1
name1_A     1        13    name1
name1_B     2        10    name1
name2       1        11    name2
name2_A     2        10    name2
name2_B     3        9     name2

But just can't seem to get it to work, any ideas?

Body:
You're only taking the first element from y, you want the first column with y[,1]:

remExt <- function(x){
  y <- str_split_fixed(x,"_",2)
  return(y[,1])
}

df %>% mutate(newLBL = remExt(LBL))
      LBL Var1 Var2 newLBL
1   name1    1   12  name1
2 name1_A    1   13  name1
3 name1_B    2   10  name1
4   name2    1   11  name2
5 name2_A    2   10  name2
6 name2_B    3    9  name2

Also note with mutate you don't need to extract the column with $

EDIT:

A simpler implementation would be to use str_remove or str_replace. Both the following are equivalent:

df %>% mutate(newLBL = str_replace(LBL,"\\_.",""))

df %>% mutate(newLBL = str_remove(LBL,"\\_."))


问:
Is there a better way to count string format placeholders in a string in C#?
I have a template string and an array of parameters that come from different sources but need to be matched up to create a new "filled-in" string:

```<code>string templateString = GetTemplate();   // e.g. "Mr {0} has a {1}"
string[] dataItems = GetDataItems();     // e.g. ["Jones", "ceiling cat"}

string resultingString = String.Format(templateString, dataItems);
// e.g. "Mr Jones has a ceiling cat"
</code>```

With this code, I'm assuming that the number of string format placeholders in the template will equal the number of data items.  It's generally a fair assumption in my case, but I want to be able to produce a resultingString without failing even if the assumption is wrong.  I don't mind if there are empty spaces for missing data.

If there are too many items in dataItems, the String.Format method handles it fine.  If there aren't enough, I get an Exception.

To overcome this, I'm counting the number of placeholders and adding new items to the dataItems array if there aren't enough.

To count the placeholders, the code I'm working with at the moment is:

```<code>private static int CountOccurrences(string haystack)
{
    // Loop through all instances of the string "}".
    int count = 0;
    int i = 0;
    while ((i = text.IndexOf("}", i)) != -1)
    {
        i++;
        count++;
    }
    return count;
}
</code>```

Obviously this makes the assumption that there aren't any closing curly braces that aren't being used for format placeholders.  It also just feels wrong. :)

Is there a better way to count the string format placeholders in a string?

A number of people have correctly pointed out that the answer I marked as correct won't work in many circumstances.  The main reasons are:

Regexes that count the number of placeholders doesn't account for literal braces ( {{0}} )

Counting placeholders doesn't account for repeated or skipped placeholders (e.g. "{0} has a {1} which also has a {1}")

答:
You could "abuse" the ICustomFormatter to gather the placeholders and return them to the caller. This simply reuses the built-in parsing algorithm, instead of trying to reimplement it (and possibly deviate from the built-in algorithm).

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace FormatPlaceholders {

    class Program {

        class FormatSnooper : IFormatProvider, ICustomFormatter {

            public object GetFormat(Type formatType) {
                return this;
            }

            public string Format(string format, object arg, IFormatProvider formatProvider) {
                Placeholders.Add(((int)arg, format));
                return null;
            }

            internal readonly List<(int index, string format)> Placeholders = new List<(int index, string format)>();

        }

        public static IEnumerable<(int index, string format)> GetFormatPlaceholders(string format, int max_count = 100) {

            var snooper = new FormatSnooper();

            string.Format(
                snooper,
                format,
                Enumerable.Range(0, max_count).Cast<object>().ToArray()
            );

            return snooper.Placeholders;

        }

        static void Main(string[] args) {
            foreach (var (index, format) in GetFormatPlaceholders("{1:foo}{4:bar}{1:baz}"))
                Console.WriteLine($"{index}: {format}");
        }

    }

}
</code>```

Which prints:

```<code>1: foo
4: bar
1: baz
</code>```

You can then easily find the max of index, count, find "holes" etc...

I realize I'm (years) late to the party, but I had the need for something similar to what OP asked, so I share the solution I came up with here, in case someone finds it useful...

ContentLicense: CC BY-SA 2.5

Body:
I have a template string and an array of parameters that come from different sources but need to be matched up to create a new "filled-in" string:

string templateString = GetTemplate();   // e.g. "Mr {0} has a {1}"
string[] dataItems = GetDataItems();     // e.g. ["Jones", "ceiling cat"}

string resultingString = String.Format(templateString, dataItems);
// e.g. "Mr Jones has a ceiling cat"

With this code, I'm assuming that the number of string format placeholders in the template will equal the number of data items.  It's generally a fair assumption in my case, but I want to be able to produce a resultingString without failing even if the assumption is wrong.  I don't mind if there are empty spaces for missing data.

If there are too many items in dataItems, the String.Format method handles it fine.  If there aren't enough, I get an Exception.

To overcome this, I'm counting the number of placeholders and adding new items to the dataItems array if there aren't enough.

To count the placeholders, the code I'm working with at the moment is:

private static int CountOccurrences(string haystack)
{
    // Loop through all instances of the string "}".
    int count = 0;
    int i = 0;
    while ((i = text.IndexOf("}", i)) != -1)
    {
        i++;
        count++;
    }
    return count;
}

Obviously this makes the assumption that there aren't any closing curly braces that aren't being used for format placeholders.  It also just feels wrong. :)

Is there a better way to count the string format placeholders in a string?

A number of people have correctly pointed out that the answer I marked as correct won't work in many circumstances.  The main reasons are:

Regexes that count the number of placeholders doesn't account for literal braces ( {{0}} )

Counting placeholders doesn't account for repeated or skipped placeholders (e.g. "{0} has a {1} which also has a {1}")

Body:
You could "abuse" the ICustomFormatter to gather the placeholders and return them to the caller. This simply reuses the built-in parsing algorithm, instead of trying to reimplement it (and possibly deviate from the built-in algorithm).

using System;
using System.Collections.Generic;
using System.Linq;

namespace FormatPlaceholders {

    class Program {

        class FormatSnooper : IFormatProvider, ICustomFormatter {

            public object GetFormat(Type formatType) {
                return this;
            }

            public string Format(string format, object arg, IFormatProvider formatProvider) {
                Placeholders.Add(((int)arg, format));
                return null;
            }

            internal readonly List<(int index, string format)> Placeholders = new List<(int index, string format)>();

        }

        public static IEnumerable<(int index, string format)> GetFormatPlaceholders(string format, int max_count = 100) {

            var snooper = new FormatSnooper();

            string.Format(
                snooper,
                format,
                Enumerable.Range(0, max_count).Cast<object>().ToArray()
            );

            return snooper.Placeholders;

        }

        static void Main(string[] args) {
            foreach (var (index, format) in GetFormatPlaceholders("{1:foo}{4:bar}{1:baz}"))
                Console.WriteLine($"{index}: {format}");
        }

    }

}

Which prints:

1: foo
4: bar
1: baz

You can then easily find the max of index, count, find "holes" etc...

I realize I'm (years) late to the party, but I had the need for something similar to what OP asked, so I share the solution I came up with here, in case someone finds it useful...


问:
How do I do something LIKE in mysql in javascript?
I wanted to check the user's expertise and display their network graph. The reason I wanted to use LIKE is because in mysql database the expertise attribute is included also with their workplace. For example: Data Analyst at Petronas. So I wanted to check if their expertise is data analyst and display their network graph.

This is the code that I've tried:

```<code><?php
if (isset($_GET['id'])) {

    $id = $_GET['id'];
    $sql = "SELECT * FROM professional, job, location WHERE PROFESSIONAL_ID LIKE '%$id%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);

    $row = mysqli_fetch_assoc($result);

    echo "
                <div class='card'>
                <img src='../images/img.png' style='width:100%'>
                <h2>".$row['PROFESSIONAL_NAME']."</h2>
                <p class='title'><i class='fa fa-briefcase' aria-hidden='true'></i> ".$row['JOB_NAME']."</p>
                <p class='marker'><i class='fa fa-map-marker' aria-hidden='true'></i> ".$row['LOCATION_NAME']."</p>
                <a href=".$row['PROFESSIONAL_URL']."><p><button>Contact</button></p></a>
              </div>

              <div class='network'>
              <h2> Filter Network</h2>
              </div>

              <div class='filter'>
        <input type='radio' value='Expertise' unchecked name='radioBtn' onclick='checkexpertise(".$row['JOB_NAME'].")'> <label> Expertise</label><br>
        <input type='radio' value='Location' unchecked name='radioBtn' onclick='checklocation(".$row['LOCATION_NAME'].")'> <label> Location</label><br>
        <input type='radio' value='Workplace' unchecked name='radioBtn' onclick='checkworkplace()'> <label> Workplace </label><br>
        <input type='radio' value='Past Workplace' unchecked name='radioBtn' onclick='checkpast()'> <label>Past Workplace</label><br>

      </div>";

}

?>
<script>
      function CheckExpertise (Expertise) {
        if Expertise LIKE %Data Analyst% OR %data analyst%
        {
          window.location.replace("expertise.html");
          }
      }
      </script>
</code>```

答:
You can use includes and I'd recommend converted the string to all lowercase and then checking so you only have to do one check.

```<code>function CheckExpertise (Expertise) {
    if (Expertise.toLowerCase.includes("data analyst") {
        window.location.replace("expertise.html");
    }
}
</code>```

Body:
I wanted to check the user's expertise and display their network graph. The reason I wanted to use LIKE is because in mysql database the expertise attribute is included also with their workplace. For example: Data Analyst at Petronas. So I wanted to check if their expertise is data analyst and display their network graph.

This is the code that I've tried:

<?php
if (isset($_GET['id'])) {

    $id = $_GET['id'];
    $sql = "SELECT * FROM professional, job, location WHERE PROFESSIONAL_ID LIKE '%$id%' AND PROFESSIONAL_ID=JOB_ID AND JOB_ID = LOCATION_ID " ;
    $result = mysqli_query($conn, $sql);

    $row = mysqli_fetch_assoc($result);

    echo "

".$row['PROFESSIONAL_NAME']."

 ".$row['JOB_NAME']."

 ".$row['LOCATION_NAME']."

<button>Contact</button>

 Filter Network

        <input type='radio' value='Expertise' unchecked name='radioBtn' onclick='checkexpertise(".$row['JOB_NAME'].")'>  Expertise

        <input type='radio' value='Location' unchecked name='radioBtn' onclick='checklocation(".$row['LOCATION_NAME'].")'>  Location

        <input type='radio' value='Workplace' unchecked name='radioBtn' onclick='checkworkplace()'>  Workplace

        <input type='radio' value='Past Workplace' unchecked name='radioBtn' onclick='checkpast()'> Past Workplace

";

}

?>

Body:
You can use includes and I'd recommend converted the string to all lowercase and then checking so you only have to do one check.

function CheckExpertise (Expertise) {
    if (Expertise.toLowerCase.includes("data analyst") {
        window.location.replace("expertise.html");
    }
}


问:
'IConfiguration' does not contain a definition for 'Get'
Originally, I had the code in 1.0.0-rc1-beta6.

 public static IConfiguration Configuration { get; set; }

 public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        // Setup configuration sources.
        var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
        Configuration = builder.Build();
        var test = Configuration.Get("ASPNET_ENV");
    }
```
<p>Now I want to use 1.0.0-rc1-update, the code is:</p>
<pre class="lang-cs prettyprint-override"><code> public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        // Setup configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
        Configuration = builder.Build();
        var test = Configuration.Get("ASPNET_ENV");
    }
</code>```

"ASP.NET_ENV" is from launchSettings.json file.

"profiles": {
"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "environmentVariables": {
    "ASPNET_ENV": "Development"
  },
  "sdkVersion": "dnx-clr-win-x64.1.0.0-beta6"
},
```
<p>But I still get the error on the last line.</p>
<blockquote>
<p>'IConfiguration' does not contain a definition for 'Get' and the best extension method overload 'SessionExtensions.Get(ISession, string)' requires a receiver of type 'ISession'.</p>
</blockquote>
<p>Also get the error here.</p>
<pre class="lang-cs prettyprint-override"><code>   public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC services to the services container.
        services.AddMvc(); //error
    }
</code>```

My project.json file

    {
  "webroot": "wwwroot",
  "version": "1.0.0-*",
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta7",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
    "Microsoft.Framework.Logging": "1.0.0-beta8",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "EntityFramework": "6.1.3",
    "jqGridWebApi": "1.1.4",
    "EnyimMemcached": "2.13.0",
    "xunit": "2.2.0-beta1-build3239",
    "Moq": "4.2.1510.2205",
    "NLog": "2.1.0",
    "CryptSharpOfficial": "2.1.0",
    "System.Linq.Dynamic": "1.0.4"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001",
    "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5005"
  },
  "frameworks": {
    "dnx451": {
      "frameworkAssemblies": {
        "System.configuration": "4.0.0.0",
        "System.Data": "4.0.0.0"
      }
    }
  },
  "exclude": [
    "wwwroot",
    "node_modules",
    "bower_components"
  ],
  "publishExclude": [
    "node_modules",
    "bower_components",
    "**.xproj",
    "**.user",
    "**.vspscc"
  ],
  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  },
  "configurations": {
    "Staging": { }
  }
}
```

答:
Install the NuGet package:

Microsoft.Extensions.Configuration.Binder

Duplicate: Bind an IConfigurationSection to a complex object without ASP.NET Core

Body:
Originally, I had the code in 1.0.0-rc1-beta6.

 public static IConfiguration Configuration { get; set; }

 public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        // Setup configuration sources.
        var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
        Configuration = builder.Build();
        var test = Configuration.Get("ASPNET_ENV");
    }

Now I want to use 1.0.0-rc1-update, the code is:

 public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        // Setup configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();
        Configuration = builder.Build();
        var test = Configuration.Get("ASPNET_ENV");
    }

"ASP.NET_ENV" is from launchSettings.json file.

"profiles": {
"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "environmentVariables": {
    "ASPNET_ENV": "Development"
  },
  "sdkVersion": "dnx-clr-win-x64.1.0.0-beta6"
},

But I still get the error on the last line.

'IConfiguration' does not contain a definition for 'Get' and the best extension method overload 'SessionExtensions.Get(ISession, string)' requires a receiver of type 'ISession'.

Also get the error here.

   public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC services to the services container.
        services.AddMvc(); //error
    }

My project.json file

    {
  "webroot": "wwwroot",
  "version": "1.0.0-*",
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta7",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
    "Microsoft.Framework.Logging": "1.0.0-beta8",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "EntityFramework": "6.1.3",
    "jqGridWebApi": "1.1.4",
    "EnyimMemcached": "2.13.0",
    "xunit": "2.2.0-beta1-build3239",
    "Moq": "4.2.1510.2205",
    "NLog": "2.1.0",
    "CryptSharpOfficial": "2.1.0",
    "System.Linq.Dynamic": "1.0.4"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001",
    "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5005"
  },
  "frameworks": {
    "dnx451": {
      "frameworkAssemblies": {
        "System.configuration": "4.0.0.0",
        "System.Data": "4.0.0.0"
      }
    }
  },
  "exclude": [
    "wwwroot",
    "node_modules",
    "bower_components"
  ],
  "publishExclude": [
    "node_modules",
    "bower_components",
    "**.xproj",
    "**.user",
    "**.vspscc"
  ],
  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  },
  "configurations": {
    "Staging": { }
  }
}


问:
Convert Audio sampleBuffer to NSData in wav format (without saving to file)
I am using

```<code>- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
</code>```

To capture audio.

Is it possible to convert sampleBuffer to NSData in wav format (without saving to file)

答:
Try to use this solution to convert your CMSampleBufferRef into NSData.

this:
https://stackoverflow.com/a/4997105/4218954

or this:
https://stackoverflow.com/a/29311174/4218954

Body:
I am using

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection

To capture audio.

Is it possible to convert sampleBuffer to NSData in wav format (without saving to file)


问:
How to enable profiler in symfony 4
Solved:

I re-install it all over again and now it contains the web_profiler.yalm inside. Thanks to all.

The original question was:

I´m just starting to learn Symfony so I downloaded the free videos at KnpUniversity to get started. When I reached the video "Web Debug Toolbar & the Profiler!" I excecuted the next command:

```<code>> composer require profiler --dev
</code>```

it installed OK.

Then, when I opened my app in the browser the "(...)slick black bar at the bottom..." didn't show up.

I read somewhere that maybe is due to I haven't installed symfony/debug but look at my composer.json:

```<code>"require-dev": {
        "sensiolabs/security-checker": "^4.1",
        "symfony/debug": "^4.0",
        "symfony/dotenv": "^4.0",
        "symfony/profiler-pack": "^1.0",
        "symfony/web-server-bundle": "^4.0"
    },
</code>```

so I have it installed.

I excecuted the following command which give me the profiler configuration in my project:

```<code>> php bin/console debug:config web_profiler

Current configuration for extension with alias "web_profiler"
=============================================================

web_profiler:
    toolbar: false
    intercept_redirects: false
    excluded_ajax_paths: '^/((index|app(_[\w]+)?)\.php/)?_wdt'
</code>```

As you see above, the toolbar is set to false, How can I activate it? or How can I get the profiler bar showed up?

I'm using:

Composer version 1.6.5,

Symfony 4.1.1 and

PHP 7.2.7

Thanks in advance.

Solution:

I created a new project and it worked, it appears to be an error when composer was downloading the packages.

答:
Please be aware, that you have to attach web_profiler routes.

in:

config/routes/dev/web_profiler.yaml

```<code>web_profiler_wdt:
resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
prefix: /_wdt

web_profiler_profiler:
resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
prefix: /_profiler
</code>```

Title: How to enable profiler in symfony 4

Body:
Solved:

I re-install it all over again and now it contains the web_profiler.yalm inside. Thanks to all.

The original question was:

I´m just starting to learn Symfony so I downloaded the free videos at KnpUniversity to get started. When I reached the video "Web Debug Toolbar & the Profiler!" I excecuted the next command:

> composer require profiler --dev

it installed OK.

Then, when I opened my app in the browser the "(...)slick black bar at the bottom..." didn't show up.

I read somewhere that maybe is due to I haven't installed symfony/debug but look at my composer.json:

"require-dev": {
        "sensiolabs/security-checker": "^4.1",
        "symfony/debug": "^4.0",
        "symfony/dotenv": "^4.0",
        "symfony/profiler-pack": "^1.0",
        "symfony/web-server-bundle": "^4.0"
    },

so I have it installed.

I excecuted the following command which give me the profiler configuration in my project:

> php bin/console debug:config web_profiler

Current configuration for extension with alias "web_profiler"
=============================================================

web_profiler:
    toolbar: false
    intercept_redirects: false
    excluded_ajax_paths: '^/((index|app(_[\w]+)?)\.php/)?_wdt'

As you see above, the toolbar is set to false, How can I activate it? or How can I get the profiler bar showed up?

I'm using:

Composer version 1.6.5,

Symfony 4.1.1 and

PHP 7.2.7

Thanks in advance.

Solution:

I created a new project and it worked, it appears to be an error when composer was downloading the packages.

Body:
Please be aware, that you have to attach web_profiler routes.

in:

config/routes/dev/web_profiler.yaml

web_profiler_wdt:
resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
prefix: /_wdt

web_profiler_profiler:
resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
prefix: /_profiler


问:
How to print only the last match using itertools in python?
I have the following code:

```<code>p = ['a','b','c','d']
q = ['a','a','x','y','z']

for (p, q) in itertools.product(p, q):
    if p == q:
        print(q)
</code>```

it prints:

```<code>a
a
</code>```

After adding some additional logs it seems that the first item of p is compared with the first item of q, then first item of p with second item of q, first item of p with third item of q etc.

How can I modify this code so that it will only print the last match? So I only want the output a once (because of the comparison of the first item of p and the second item in q in this case)

答:
Why not simply use a set to find common characters between the two lists

```<code>p = ['a','b','c','d']
q = ['a','a','x','y','z']

print(set(p).intersection(set(q)))
</code>```

The output will be {'a'}

Or if you cannot use a set, collect all matches into a list and print the last element

```<code>import itertools

p = ['a','b','c','d']
q = ['a','a','x','y','z']

items = []
for (p, q) in itertools.product(p, q):
    #Collect all matches in a list
    if p == q:
        items.append((p,q))

#Print the last item
print(items[-1])
</code>```

The output will be ('a', 'a')

Body:
I have the following code:

p = ['a','b','c','d']
q = ['a','a','x','y','z']

for (p, q) in itertools.product(p, q):
    if p == q:
        print(q)

it prints:

a
a

After adding some additional logs it seems that the first item of p is compared with the first item of q, then first item of p with second item of q, first item of p with third item of q etc.

How can I modify this code so that it will only print the last match? So I only want the output a once (because of the comparison of the first item of p and the second item in q in this case)

Body:
Why not simply use a set to find common characters between the two lists

p = ['a','b','c','d']
q = ['a','a','x','y','z']

print(set(p).intersection(set(q)))

The output will be {'a'}

Or if you cannot use a set, collect all matches into a list and print the last element

import itertools

p = ['a','b','c','d']
q = ['a','a','x','y','z']

items = []
for (p, q) in itertools.product(p, q):
    #Collect all matches in a list
    if p == q:
        items.append((p,q))

#Print the last item
print(items[-1])

The output will be ('a', 'a')


问:
Special characters in character class
I would like to match below patterns and replace them with sql keywords around them.

The files are on Linux server with SQL code in them. I tried to match with some regular expressions. Ideally, I would like to match Any number of special characters, alphabets and ignore case for col_4 to find first strings that contain col4 in the query.

I tried working with below expression and also with the help of community's response from another question.

```<code>[A-Za-z_#]*\.\)\{0,\}col4
</code>```

Source text:

```<code>SELECT
col1 as col1,
[&"tab.sch"].tabl_nm.col2 as col2,
col3,
[&"tab.sch"].tabl_nm.col_4 as col_4,
\#tab.sch#.tab_nm.COL_4 col_4,
col5
FROM yada yada
</code>```

I want to be able to wrap upper around first instance of col_4 fields ignoring case

Expected result

```<code>SELECT
col1 as col1,
[&"tab.sch"].tabl_nm.col2 as col2,
col3,
upper([&"tab.sch"].tabl_nm.col_4) as col_4,
upper(#tab.sch#.tab_nm.COL_4) col_4,
col5
FROM yada yada
</code>```

答:
Thanks for the feedback. I was able to solve this with below code

```<code>sed '/SELECT/,/FROM/ {s/[Aa][Ss] [Cc][oO][lL]_4 *//;s/\([[:punct:]A-Za-z0-9]*\.\)\{0,\}[Cc][oO][lL]_4 /SUBSTR(&,1,30) as col4/;}'
</code>```

Title: Special characters in character class

Body:
I would like to match below patterns and replace them with sql keywords around them.

The files are on Linux server with SQL code in them. I tried to match with some regular expressions. Ideally, I would like to match Any number of special characters, alphabets and ignore case for col_4 to find first strings that contain col4 in the query.

I tried working with below expression and also with the help of community's response from another question.

[A-Za-z_#]*\.\)\{0,\}col4

Source text:

SELECT
col1 as col1,
[&"tab.sch"].tabl_nm.col2 as col2,
col3,
[&"tab.sch"].tabl_nm.col_4 as col_4,
\#tab.sch#.tab_nm.COL_4 col_4,
col5
FROM yada yada

I want to be able to wrap upper around first instance of col_4 fields ignoring case

Expected result

SELECT
col1 as col1,
[&"tab.sch"].tabl_nm.col2 as col2,
col3,
upper([&"tab.sch"].tabl_nm.col_4) as col_4,
upper(#tab.sch#.tab_nm.COL_4) col_4,
col5
FROM yada yada

Body:
Thanks for the feedback. I was able to solve this with below code

sed '/SELECT/,/FROM/ {s/[Aa][Ss] [Cc][oO][lL]_4 *//;s/\([[:punct:]A-Za-z0-9]*\.\)\{0,\}[Cc][oO][lL]_4 /SUBSTR(&,1,30) as col4/;}'


问:
ORACLE SQL Range of hours
i have a problem, i have a table with 3 columns

```<code>- date - varchar2   - varchar2 -
| date | start_hour | end_hour |
</code>```

I need to make a validation to not overlap hour ranges.

For example:

```<code>| date  | start_hour | end_hour |
| date1 | 09:00AM    | 09:30AM  |
| date1 | 10:30AM    | 11:30AM  |
| date1 | 01:00PM    | 03:00PM  |
</code>```

Assuming the date is the same for the 3 rows.

What i need is, to no overlap these ranges

I cant insert a ranges like this

 start_hour =  08:00AM and end_hour = 09:20AM, because, a range between 09:00AM and 09:30AM already exist, so, the new range clashes with the range who exist in the table.
I tried so many querys, with not between, the end_hour i insert need to be less than the start_hour from a table.
Anyone have an idea how to do it?

答:
i already found the solution to my problem, as a recomendation from a comment in my question, when i changed the format of the hours, and the format of the new hours, it worked perfectly.
Here is the code for someone who have this same issue in the future.

```<code>DECLARE
  l_count NUMBER(1) := 0;
BEGIN

  SELECT COUNT(*)
  INTO   l_count
  FROM   table
  WHERE  start_hour <= :new_start_hour
  AND    end_hour   >= :new_end_hour
  AND    date = :date
  AND    ROWNUM     = 1;
  dbms_output.put_line(l_count);

END;
/
</code>```

Thanks for all our help.

Title: ORACLE SQL Range of hours

Body:
i have a problem, i have a table with 3 columns

- date - varchar2   - varchar2 -
| date | start_hour | end_hour |

I need to make a validation to not overlap hour ranges.

For example:

| date  | start_hour | end_hour |
| date1 | 09:00AM    | 09:30AM  |
| date1 | 10:30AM    | 11:30AM  |
| date1 | 01:00PM    | 03:00PM  |

Assuming the date is the same for the 3 rows.

What i need is, to no overlap these ranges

I cant insert a ranges like this

 start_hour =  08:00AM and end_hour = 09:20AM, because, a range between 09:00AM and 09:30AM already exist, so, the new range clashes with the range who exist in the table.
I tried so many querys, with not between, the end_hour i insert need to be less than the start_hour from a table.
Anyone have an idea how to do it?

Body:
i already found the solution to my problem, as a recomendation from a comment in my question, when i changed the format of the hours, and the format of the new hours, it worked perfectly.
Here is the code for someone who have this same issue in the future.

DECLARE
  l_count NUMBER(1) := 0;
BEGIN

  SELECT COUNT(*)
  INTO   l_count
  FROM   table
  WHERE  start_hour <= :new_start_hour
  AND    end_hour   >= :new_end_hour
  AND    date = :date
  AND    ROWNUM     = 1;
  dbms_output.put_line(l_count);

END;
/

Thanks for all our help.


问:
How to dynamically create column names for dataframe based on shape
I am creating a dataframe from a list of lists where some "rows" have 3 "columns" and some have 20, for example. I don't know because this is parsing a text file to generate the list. The data is all strings.

I have tried the following code:

```<code>df = pd.DataFrame(data=myArray)
df_xrefs.columns(['Column A', 'Column B'] + ['DynamicColumn_{}'+format(x) for x in range(1, int(df.shape[1])-1)])
</code>```

I expect the columns to be:

```<code> 'Column A', 'Column B', 'DynamicColumn_1, DynamicColumn_2' ... 'DynamicColumn_n'
</code>```

```<code>TypeError: 'RangeIndex' object is not callable
</code>```

With my current test data, the output of the following is 5

```<code>df = pd.DataFrame(data=myArray)
print(df.shape[1])
</code>```

答:
you are missing the reassignment of columns with equals.</p>

```<code>df_xrefs.columns = (['Column A', 'Column B'] + ['DynamicColumn_{}'.format(x) for x in range(1, int(df_xrefs.shape[1])-1)])
</code>```

Body:
I am creating a dataframe from a list of lists where some "rows" have 3 "columns" and some have 20, for example. I don't know because this is parsing a text file to generate the list. The data is all strings.

I have tried the following code:

df = pd.DataFrame(data=myArray)
df_xrefs.columns(['Column A', 'Column B'] + ['DynamicColumn_{}'+format(x) for x in range(1, int(df.shape[1])-1)])

I expect the columns to be:

 'Column A', 'Column B', 'DynamicColumn_1, DynamicColumn_2' ... 'DynamicColumn_n'

TypeError: 'RangeIndex' object is not callable

With my current test data, the output of the following is 5

df = pd.DataFrame(data=myArray)
print(df.shape[1])

Body:
you are missing the reassignment of columns with equals.

df_xrefs.columns = (['Column A', 'Column B'] + ['DynamicColumn_{}'.format(x) for x in range(1, int(df_xrefs.shape[1])-1)])


问:
Xamarin Android cannot re-access shared files
TL;DR...

How do I re-access files which have been shared to my Xamarin Android app, which worked on first sharing, but I get permission exceptions when I try and access them again later on?

I'm writing my first Xamarin Android (not Forms) app, which I want to be able to "share" photos well as "add" photos.

By "share" I mean you open Gallery, select one or more photos, and share them to my app via Intent.ActionSend and Intent.ActionSendMultiple.

And by "add" I mean you click on a button within the app, which allows you to add a photo via the Intent.ActionOpenDocument.

I've been able to set "Persistable Permissions" on images that I have added via the ActionOpenDocument using the following (taken from this answer)...

```<code>protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if ((requestCode == c_addPhoto) && (resultCode == Result.Ok) && (data != null))
    {
        Uri uri = data.Data;
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            ContentResolver.TakePersistableUriPermission(uri, ActivityFlags.GrantReadUriPermission);
        AddToList(uri);
    }
}
</code>```

This works, and when I re-open the application the images are accessed using Uri values such as...

```<code> content://com.android.providers.media.documents/document/image%3A2122
</code>```

My issue is being able to access images that have been shared via the Intent.ActionSend and Intent.ActionSendMultiple where the Uri that is passed through the Intent.ClipData.Item is in the following format...

```<code> content://media/external/images/media/1998
</code>```

If I try and run the TakePersistableUriPermission on the Uri after it is passed to my app, I get the following exception...

Java.Lang.SecurityException: No persistable permission grants found for UID 10254 and Uri content://media/external/images/media/1998 [user 0]

And if I try and access the Uri I get the following exception...

Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/1998 from pid=4042, uid=10254 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

But I do have the following in my AndroidManifest.xml file...

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

How do I grant the file permission for access in the future?

Or do I need to translate the Uri from the content://media... to content://com.android... format, and if so, how?

答:
Have you gone through the File/Content Provider implementation in your Android solution?
This is one that I answered for Xamarin Forms app though it should be same for Xamarin Android since everything you need to do for File Provider you will do in Android platform specific project:
File Download in Xamarin forms

Android defined the File/Content Provider since Api version 22 which means if your app runs on or above that versions you must define the File Provider for your app to be able to Share the files.

Here's the official page https://developer.android.com/reference/android/support/v4/content/FileProvider

Body:
TL;DR...

How do I re-access files which have been shared to my Xamarin Android app, which worked on first sharing, but I get permission exceptions when I try and access them again later on?

I'm writing my first Xamarin Android (not Forms) app, which I want to be able to "share" photos well as "add" photos.

By "share" I mean you open Gallery, select one or more photos, and share them to my app via Intent.ActionSend and Intent.ActionSendMultiple.

And by "add" I mean you click on a button within the app, which allows you to add a photo via the Intent.ActionOpenDocument.

I've been able to set "Persistable Permissions" on images that I have added via the ActionOpenDocument using the following (taken from this answer)...

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    if ((requestCode == c_addPhoto) && (resultCode == Result.Ok) && (data != null))
    {
        Uri uri = data.Data;
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            ContentResolver.TakePersistableUriPermission(uri, ActivityFlags.GrantReadUriPermission);
        AddToList(uri);
    }
}

This works, and when I re-open the application the images are accessed using Uri values such as...

 content://com.android.providers.media.documents/document/image%3A2122

My issue is being able to access images that have been shared via the Intent.ActionSend and Intent.ActionSendMultiple where the Uri that is passed through the Intent.ClipData.Item is in the following format...

 content://media/external/images/media/1998

If I try and run the TakePersistableUriPermission on the Uri after it is passed to my app, I get the following exception...

Java.Lang.SecurityException: No persistable permission grants found for UID 10254 and Uri content://media/external/images/media/1998 [user 0]

And if I try and access the Uri I get the following exception...

Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/1998 from pid=4042, uid=10254 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

But I do have the following in my AndroidManifest.xml file...

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

How do I grant the file permission for access in the future?

Or do I need to translate the Uri from the content://media... to content://com.android... format, and if so, how?


问:
Exception Unhandled while trying to initialize dynamic array
I'm allocating dynamic memory in my class as a private: variable

Then in the constructor I'm trying to initialize the array.

```<code>public
Display(int Width, int Height) {
    nScreenHeight = Height;
    nScreenWidth = Width;
    DWORD dwBytesWritten = 0;
    for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
    SetConsoleActiveScreenBuffer(hConsole);
}

private:
    int nScreenWidth;
    int nScreenHeight;
    wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];

</code>```

If I try run the program an Exception Unhanded in thrown.

Unhandled exception thrown: write access violation.
this->screen was 0x2096112.

While trying to initialize the buffer screen with L' '

答:
Memebers are initialized in the order they appear in the class declaration before the body of the constructor is executed. So what happens is:

nScreenWidth is default initialized (see here)

nScreenHeight is default initialized

screen is initialized with new wchar_t[nScreenWidth*nScreenHeight]

only now the constructor runs and you assign values to nScreenWidth and nScreenHeight

Use the initializer list for all members to avoid confusion:

```<code>Display(int Width, int Height) :
   nScreenWidth(Width), nScreenHeight(Height), screen(new wchar_t[nScreenWidth*nScreenHeight])
{
    DWORD dwBytesWritten = 0;
    for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
    SetConsoleActiveScreenBuffer(hConsole);
}
</code>```

Even better would be to use a std::vector<wchar_t>, the constructor would be

```<code>Display(int Width, int Height) :
       nScreenWidth(Width), nScreenHeight(Height), screen(Width*Height)
{
    ...
</code>```

and instead of bothering about the rule of three/five you can rely on the rule of zero.

Body:
I'm allocating dynamic memory in my class as a private: variable

Then in the constructor I'm trying to initialize the array.

public
Display(int Width, int Height) {
    nScreenHeight = Height;
    nScreenWidth = Width;
    DWORD dwBytesWritten = 0;
    for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
    SetConsoleActiveScreenBuffer(hConsole);
}

private:
    int nScreenWidth;
    int nScreenHeight;
    wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];

If I try run the program an Exception Unhanded in thrown.

Unhandled exception thrown: write access violation.
this->screen was 0x2096112.

While trying to initialize the buffer screen with L' '

Body:
Memebers are initialized in the order they appear in the class declaration before the body of the constructor is executed. So what happens is:

nScreenWidth is default initialized (see here)

nScreenHeight is default initialized

screen is initialized with new wchar_t[nScreenWidth*nScreenHeight]

only now the constructor runs and you assign values to nScreenWidth and nScreenHeight

Use the initializer list for all members to avoid confusion:

Display(int Width, int Height) :
   nScreenWidth(Width), nScreenHeight(Height), screen(new wchar_t[nScreenWidth*nScreenHeight])
{
    DWORD dwBytesWritten = 0;
    for (int i = 0; i < (nScreenWidth*nScreenHeight); i++) screen[i] = L'';
    SetConsoleActiveScreenBuffer(hConsole);
}

Even better would be to use a std::vector<wchar_t>, the constructor would be

Display(int Width, int Height) :
       nScreenWidth(Width), nScreenHeight(Height), screen(Width*Height)
{
    ...

and instead of bothering about the rule of three/five you can rely on the rule of zero.


问:
Color row of Datatable using a SQL query in ASP.NET C#
I need to color rows of my asp.net c# table.
To show the table, Im using one ASP:Repeater with html:

```<code><div class="panel-body">
<div class="table-responsive">
    <table class="table table-striped table-bordered table-hover" id="dataTables-MaquinasCaidas" >
        <thead>
            <tr>
                <th>Hora Reportada</th>
                <th>Máquina</th>
            </tr>
        </thead>
        <tbody>
            <asp:Repeater ID="repeaterMaquinaCaida" runat="server">
                <ItemTemplate>

                    <tr>
                        <td>
                            <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />
                        </td>
                        <td>
                            <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />
                        </td>
                    </tr>

                </ItemTemplate>
            </asp:Repeater>
        </tbody>
    </table>
</div>
</code>```

in .cs page, to fill the table:

```<code>public void fillTable()
    {
        string query = "SELECT * FROM MaquinaCaida order by HoraReportada asc";
        DataTable tableResponse = SqlComm.SqlDataTable(query);
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        if (!IsPostBack)
        {
            repeaterMaquinaCaida.DataSource = tableResponse;
            repeaterMaquinaCaida.DataBind();
        }
</code>```

I just need to color some rows based on condition, like:

```<code>SELECT * FROM Table WHERE Column = "something";
</code>```

And then change the color of the row to red, for example.

Is there a way to perform this action??

答:
You can do it in your Repeater. Something like this.

```<code>    <ItemTemplate>

        <tr runat="server" class='<%#(string)Eval("column") == "condition ? "redAlert" : "" %>'>
            <td>
                <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />
            </td>
            <td>
                <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />
            </td>
        </tr>

    </ItemTemplate>
</code>```

Body:
I need to color rows of my asp.net c# table.
To show the table, Im using one ASP:Repeater with html:

                Hora Reportada
                Máquina

            <asp:Repeater ID="repeaterMaquinaCaida" runat="server">
                <ItemTemplate>

                            <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />

                            <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />

                </ItemTemplate>
            </asp:Repeater>

in .cs page, to fill the table:

public void fillTable()
    {
        string query = "SELECT * FROM MaquinaCaida order by HoraReportada asc";
        DataTable tableResponse = SqlComm.SqlDataTable(query);
        TableRow row = new TableRow();
        TableCell cell = new TableCell();
        if (!IsPostBack)
        {
            repeaterMaquinaCaida.DataSource = tableResponse;
            repeaterMaquinaCaida.DataBind();
        }

I just need to color some rows based on condition, like:

SELECT * FROM Table WHERE Column = "something";

And then change the color of the row to red, for example.

Is there a way to perform this action??

Body:
You can do it in your Repeater. Something like this.

    <ItemTemplate>

        <tr runat="server" class='<%#(string)Eval("column") == "condition ? "redAlert" : "" %>'>
            <td>
                <asp:Label ID="lblHoraReportada" runat="server" Text='<%# Eval("HoraReportada") %>' />
            </td>
            <td>
                <asp:Label ID="lblNoMaquina" runat="server" Text='<%# Eval("NoMaquina") %>' />
            </td>
        </tr>

    </ItemTemplate>