问:
How protect API request made from Flutter Web app?
I have an API developed in PHP for my Flutter web app. I am using this API to fetch all the data. But, I can see all the requests made to the server.

Is there any way to hide/restrict any unauthorized person to use my API? I am using HTTP library to make calls from my flutter app to API. I just want to hide those calls to web API. I have seen some websites do that. Since the server code and website code in those websites are in the same directory it can be accessed directly without having to make a request to the webserver.

答:
Two problems I see are

You are able to see all the request made to backend server from your web page and you want to hide them.

The answer to this is No you cant. I say this based on my search in google and some posts in SO like this

You may think about disabling the developers tools. The answer is No and maybe with unknown side effects.

Is there any way to hide/restrict any unauthorized person to use my API?

The answer to this question is yes and can be done in many approaches. Like you said token based authorization has its own issue with keys being leaked and thats why there is always validity associated with it and should be considered. There are mechanisms such as refresh tokens to renew tokens etc.

The first and foremost thing I would do is enable CORS mechanism in your sever where the server will only allow request from very specific domains to be processed. More details available here


来源: stackexchange

问:
Index of vector of strings in c++
I have a vector of string including :- chemistry physics maths.
I want to access first character of each word ie c of chemistry p of physics and m of maths. How to do that? </p>

答:
You can output the first index element through this process.

I have made a 2D vector and applied a for loop so each row of the vector's first element is printed.

```<code>#include <iostream>
#include <vector>

int main()
{
    std::vector<std::string> vec = {"chemistry", "maths", "physics"};

    for(int i=0;i<vec.size();i++)
    {

         std::cout << vec[i][0];
    }
    return EXIT_SUCCESS;
}

</code>```

You can also use a range based for loop

```<code>for (auto &i : vec)
    std::cout << i[0] << " ";
</code>```

The output will be

```<code>c m p
</code>```

ContentLicense: CC BY-SA 4.0

Title: Index of vector of strings in c++

Body:
You can output the first index element through this process.

I have made a 2D vector and applied a for loop so each row of the vector's first element is printed.

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::string> vec = {"chemistry", "maths", "physics"};

    for(int i=0;i<vec.size();i++)
    {

         std::cout << vec[i][0];
    }
    return EXIT_SUCCESS;
}

You can also use a range based for loop

for (auto &i : vec)
    std::cout << i[0] << " ";

The output will be

c m p


问:
Throw HttpException in nestJs async function
Im new to nestJs, however my recent problem which im going to elaborate, is more of an async exception handling issue. i have a http post function which is responsible for inserting a user in mongodb in case of not finding any other user with that id. Since the findOne function is async, i can not throw exception when a duplicate user exists.
here is my controller:

```<code>  @Post('/register')
    async register(@Body() createUserDto: User): Promise<String> {
       return await this.sejamService.registerUser(createUserDto);

    }
</code>```

my userService:

```<code>  try {
                this.findOne(userProfile.nationalCode).then(res => {
                    if (res === undefined) {
                        var user = new User(userProfile.nationalCode, userProfile.email, userProfile.password, userProfile.firstName,
                            userProfile.surname, userProfile.fatherName, userProfile.birthCertNumber, userProfile.phoneNumber);
                        //const createdUser = new this.userModel(userProfile);
                        this.usersRepository.save(user);
                    } else {
                        throw new HttpException({
                    status: HttpStatus.BAD_REQUEST,
                    error: 'some error',
                }, HttpStatus.CONFLICT);
                    }

                });
            } catch (e) {
                console.log('error');
                throw new HttpException({
                    status: HttpStatus.BAD_REQUEST,
                    error: 'some error',
                }, HttpStatus.CONFLICT);
            }
</code>```

答:
Since I'm not able to test this code, I'll try to sketch a possible solution.

First, I'll start by stating that in my opinion, throwing http exceptions from within services is not the best practice, since ideally, services should not be aware of that context. There are obviously exceptions, your's doesn't seems like one of them (again - this is my opinion).

As for the "solution" itself, you can take advantages of Promises, for instance:

userService (this is just a piece of the code):

```<code>return new Promise((resolve, reject) => {
    this.findOne(userProfile.nationalCode).then(() => {
    if (res === undefined) {
        const user = new User(userProfile.nationalCode, userProfile.email, userProfile.password, userProfile.firstName,
                    userProfile.surname, userProfile.fatherName, userProfile.birthCertNumber, userProfile.phoneNumber);
        //const createdUser = new this.userModel(userProfile);
        this.usersRepository.save(user);
        resolve();
    } else {
        reject('some error');
    }
})
   ...
</code>```

With that code in your hand, you would be able to do something like this in your controller:

```<code>@Post('/register')
async register(@Body() createUserDto: User): Promise<String> {
  try {
     await this.sejamService.registerUser(createUserDto);
  } catch(e) {
     throw new HttpException(....)
  }
}
</code>```

Again, the above code is just an example. Do whatever you need to do to make it more fit.

Body:
Im new to nestJs, however my recent problem which im going to elaborate, is more of an async exception handling issue. i have a http post function which is responsible for inserting a user in mongodb in case of not finding any other user with that id. Since the findOne function is async, i can not throw exception when a duplicate user exists.
here is my controller:

  @Post('/register')
    async register(@Body() createUserDto: User): Promise<String> {
       return await this.sejamService.registerUser(createUserDto);

    }

my userService:

  try {
                this.findOne(userProfile.nationalCode).then(res => {
                    if (res === undefined) {
                        var user = new User(userProfile.nationalCode, userProfile.email, userProfile.password, userProfile.firstName,
                            userProfile.surname, userProfile.fatherName, userProfile.birthCertNumber, userProfile.phoneNumber);
                        //const createdUser = new this.userModel(userProfile);
                        this.usersRepository.save(user);
                    } else {
                        throw new HttpException({
                    status: HttpStatus.BAD_REQUEST,
                    error: 'some error',
                }, HttpStatus.CONFLICT);
                    }

                });
            } catch (e) {
                console.log('error');
                throw new HttpException({
                    status: HttpStatus.BAD_REQUEST,
                    error: 'some error',
                }, HttpStatus.CONFLICT);
            }

Body:
Since I'm not able to test this code, I'll try to sketch a possible solution.

First, I'll start by stating that in my opinion, throwing http exceptions from within services is not the best practice, since ideally, services should not be aware of that context. There are obviously exceptions, your's doesn't seems like one of them (again - this is my opinion).

As for the "solution" itself, you can take advantages of Promises, for instance:

userService (this is just a piece of the code):

return new Promise((resolve, reject) => {
    this.findOne(userProfile.nationalCode).then(() => {
    if (res === undefined) {
        const user = new User(userProfile.nationalCode, userProfile.email, userProfile.password, userProfile.firstName,
                    userProfile.surname, userProfile.fatherName, userProfile.birthCertNumber, userProfile.phoneNumber);
        //const createdUser = new this.userModel(userProfile);
        this.usersRepository.save(user);
        resolve();
    } else {
        reject('some error');
    }
})
   ...

With that code in your hand, you would be able to do something like this in your controller:

@Post('/register')
async register(@Body() createUserDto: User): Promise<String> {
  try {
     await this.sejamService.registerUser(createUserDto);
  } catch(e) {
     throw new HttpException(....)
  }
}

Again, the above code is just an example. Do whatever you need to do to make it more fit.


问:
Laravel PHPUnit error mysql fulltext index
Just got an error while running PHPUnit in Laravel after add FULLTEXT index

```<code>Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000]: General error: 1 near "name": syntax error
</code>```

After investigating, the error caused by migration that I've added

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddFulltextIndexToProductName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement('ALTER TABLE products ADD FULLTEXT fulltext_index(name)');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('DROP INDEX `fulltext_index`');
    }
}

</code>```

If I remove that migration code, the test running gracefully

Has anyone experienced this problem?

答:
Usually Laravel tests are using in memory sqlite database and this statement in your migration will not work.
You can check how to create sqlite full text index here: https://www.sqlitetutorial.net/sqlite-full-text-search/

Since Laravel doesn't support full text search out of the box I assume you have written custom function which probably also will not work in tests.

To overcome the issue you can:

use mysql for test (not recommended since it is slow)

use repositories pattern

skip the migration when in tests (if you are not
testing the search - you don't need it). You can check with
if(env('APP_ENV') === 'testing')

use laravel scout for search

Body:
Just got an error while running PHPUnit in Laravel after add FULLTEXT index

Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000]: General error: 1 near "name": syntax error

After investigating, the error caused by migration that I've added

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddFulltextIndexToProductName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement('ALTER TABLE products ADD FULLTEXT fulltext_index(name)');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('DROP INDEX `fulltext_index`');
    }
}

If I remove that migration code, the test running gracefully

Has anyone experienced this problem?


问:
Why -1 causes key error in pandas dataframe post resetting its index and how to make it work
Lets say I have a pandas dataframe and the -1 indexing does not work post resetting its index. How do I make it work as it was earlier and why it doesn't work in this case?:

答:
You might consider using the df.loc() or df.iloc() property.
In your case that might be
(see the documentation).

data.rerset_index()['Date'].iloc(-1)
```

Instead of resetting the index, you also could simply write data.index[-1].

Body:
You might consider using the df.loc() or df.iloc() property.
In your case that might be
(see the documentation).

data.rerset_index()['Date'].iloc(-1)

Instead of resetting the index, you also could simply write data.index[-1].


问:
Raw notation doesn't give the desired outcome
I'm trying to use Python's raw notation to find a pattern that includes special characters with no success.

When using the 'r' notation to ignore the special characters nothing is found - see the example below:

Problematic Code

```<code>import re
pattern = re.compile(r"testing+101@gmail.com")
sentence = '___dsdtesting+101@gmail.comaaa___'

result = re.search(pattern, sentence).group()

print(result)
</code>```

The above code will not find the pattern and return

AttributeError: 'NoneType' object has no attribute 'group'

Working Code

When escaping the '+' with '\' it works as expected:

```<code>import re
pattern = re.compile("testing\+101@gmail.com")
sentence = '___dsdtesting+101@gmail.comaaa___'

result = re.search(pattern, sentence).group()

print(result)
</code>```

The above code will return the desired outcome of "testing+101@gmail.com".

Am I using the raw notation wrong? What's going on?

TO CLARIFY: I am not interested in escaping with the '\', rather I want to use the raw notation.

答:
There are two levels of special characters here — those that are special to Python’s string syntax, and those that are special in regular expressions. Using raw strings takes care of the first group, but not the second group.

The plus sign is special in regexes, so to match the string a+ you need the regex a\+. Because the backslash is special to Python strings, if you do not use raw strings you need to type this as 'a\\+'. Using raw strings lets you type r'a\+'.

(Because the sequence \+ does not mean anything special to Python, and Python leaves such sequences unchanged, you could actually get away with just 'a\+'.)

Body:
I'm trying to use Python's raw notation to find a pattern that includes special characters with no success.

When using the 'r' notation to ignore the special characters nothing is found - see the example below:

Problematic Code

import re
pattern = re.compile(r"testing+101@gmail.com")
sentence = '___dsdtesting+101@gmail.comaaa___'

result = re.search(pattern, sentence).group()

print(result)

The above code will not find the pattern and return

AttributeError: 'NoneType' object has no attribute 'group'

Working Code

When escaping the '+' with '\' it works as expected:

import re
pattern = re.compile("testing\+101@gmail.com")
sentence = '___dsdtesting+101@gmail.comaaa___'

result = re.search(pattern, sentence).group()

print(result)

The above code will return the desired outcome of "testing+101@gmail.com".

Am I using the raw notation wrong? What's going on?

TO CLARIFY: I am not interested in escaping with the '\', rather I want to use the raw notation.


问:
Ajax data not passing to controller
I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.

Here my function:

```<code>    function functionA() {
        $.ajax({
            url: URLToApi,
            method: 'POST',
            headers: {
                sessionStorage.getItem('token')
            },
            data: {
                access_token: sessionStorage.getItem('pageToken'),
                message: $('#comment').val(),
                id: sessionStorage.getItem('pageId')
            },
            success: function () {
                $('#success').text('It has been added!"');
            },
        });
    }
</code>```

答:
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows: </p>

```<code>   function functionA() {
    $.ajax({
        url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
        method: 'POST',
        headers: {
            sessionStorage.getItem('token')
        },
        success: function () {
            $('#success').text('It has been added!"');
        },
    });
}
</code>```

Title: Ajax data not passing to controller

Body:
I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.

Here my function:

    function functionA() {
        $.ajax({
            url: URLToApi,
            method: 'POST',
            headers: {
                sessionStorage.getItem('token')
            },
            data: {
                access_token: sessionStorage.getItem('pageToken'),
                message: $('#comment').val(),
                id: sessionStorage.getItem('pageId')
            },
            success: function () {
                $('#success').text('It has been added!"');
            },
        });
    }

Body:
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:

   function functionA() {
    $.ajax({
        url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
        method: 'POST',
        headers: {
            sessionStorage.getItem('token')
        },
        success: function () {
            $('#success').text('It has been added!"');
        },
    });
}


问:
Facing "Unexpected end of JSON input" problem in npm install command
```<code>1555 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...pes/node":"^12.6.9","'

1555 verbose stack     at JSON.parse (<anonymous>)

1555 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)

1555 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50

1555 verbose stack     at runMicrotasks (<anonymous>)

1555 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)

1556 verbose cwd E:\Dubey\Projects\simplefolio

1557 verbose Windows_NT 10.0.18363

1558 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"

1559 verbose node v12.16.3

1560 verbose npm  v6.14.4

1561 error Unexpected end of JSON input while parsing near '...pes/node":"^12.6.9","'

1562 verbose exit [ 1, true ]
</code>```

<p>This error log I am getting every time I run npm install  </p>

答:
try this

```<code>npm cache clean --force
</code>```

and then run your command

Body:
1555 verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...pes/node":"^12.6.9","'

1555 verbose stack     at JSON.parse (<anonymous>)

1555 verbose stack     at parseJson (C:\Program Files\nodejs\node_modules\npm\node_modules\json-parse-better-errors\index.js:7:17)

1555 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\body.js:96:50

1555 verbose stack     at runMicrotasks (<anonymous>)

1555 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:97:5)

1556 verbose cwd E:\Dubey\Projects\simplefolio

1557 verbose Windows_NT 10.0.18363

1558 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"

1559 verbose node v12.16.3

1560 verbose npm  v6.14.4

1561 error Unexpected end of JSON input while parsing near '...pes/node":"^12.6.9","'

1562 verbose exit [ 1, true ]

This error log I am getting every time I run npm install

Body:
try this

npm cache clean --force

and then run your command


问:
Makefile problems
I want compile makefile in linux.
This Is my makefile

```<code>FFMPEG_LIBS=    libavdevice                        \
libavformat                        \
libavfilter                        \
libavcodec                         \
libswresample                      \
libswscale                         \
libavutil                          \

LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS))
LIBS = -lstdc++fs
PROJECT_ROOT    =   $(shell pwd)

CXX        = g++
CXXFLAGS   = -c -Wall
STRIP      = strip
LDFLAGS    =
OBJS       = main.o chekfiletoconcat.o
DEPS       = chekfiletoconcat.h
EXECUTABLE = concat

.PHONY: all
all: $(EXECUTABLE) $(LIBS)

$(EXECUTABLE): $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS)
    $(STRIP) $(EXECUTABLE)

%.o: %.cpp $(DEPS)
    $(CXX) $(CXXFLAGS) $<

.PHONY: clean
clean:
    rm -f $(OBJS) $(EXECUTABLE)
</code>```

But I recive error ** make: * No rule to make target '-lstdc++fs', needed by 'all'.  Stop.

答:
```<code>.PHONY: all
all: $(EXECUTABLE) $(LIBS)
</code>```

It makes no sense to have dependencies to your libs as long you do not build it by yourself. In your case, $(LIBS) did not contain the name of the library files, which is necessary to make a build rule from it and make it possible to make them a prerequisite, but directly have the "-lxyz" command line option for the linker. You can't use this format for deps in Makefile. In your case, I would simply remove the $(LIBS) from your rule.

```<code>all: $(EXECUTABLE)
</code>```

Title: Makefile problems

Body:
I want compile makefile in linux.
This Is my makefile

FFMPEG_LIBS=    libavdevice                        \
libavformat                        \
libavfilter                        \
libavcodec                         \
libswresample                      \
libswscale                         \
libavutil                          \

LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS))
LIBS = -lstdc++fs
PROJECT_ROOT    =   $(shell pwd)

CXX        = g++
CXXFLAGS   = -c -Wall
STRIP      = strip
LDFLAGS    =
OBJS       = main.o chekfiletoconcat.o
DEPS       = chekfiletoconcat.h
EXECUTABLE = concat

.PHONY: all
all: $(EXECUTABLE) $(LIBS)

$(EXECUTABLE): $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS)
    $(STRIP) $(EXECUTABLE)

%.o: %.cpp $(DEPS)
    $(CXX) $(CXXFLAGS) $<

.PHONY: clean
clean:
    rm -f $(OBJS) $(EXECUTABLE)

But I recive error ** make: * No rule to make target '-lstdc++fs', needed by 'all'.  Stop.

Body:
.PHONY: all
all: $(EXECUTABLE) $(LIBS)

It makes no sense to have dependencies to your libs as long you do not build it by yourself. In your case, $(LIBS) did not contain the name of the library files, which is necessary to make a build rule from it and make it possible to make them a prerequisite, but directly have the "-lxyz" command line option for the linker. You can't use this format for deps in Makefile. In your case, I would simply remove the $(LIBS) from your rule.

all: $(EXECUTABLE)


问:
objective c leaking NSNumber being retained
My application uses GPS and assigns an NSNumber instance variable every time the GPS is updated and in my last bit of testing before release, I've discovered that it leaks a lot. I'm fairly certain I know which lines are contributing to the leak, but I can't figure how to solve it.

```<code>latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];
</code>```

This line is in my GPS update method and is run regularly. Latitude is an instance variable, and when I remove the retain, I can no longer access the variable in the other methods I need. I have the variable released in the dealloc method, but that doesn't seem to do anything.

I understand the alloc-release paradigm, but I'm still not sure how to fix this.

答:
Before setting it, you must release the previously retained value. Otherwise, when you assign the new pointer, the previous object which is released has nothing referencing it and it can never be released.

To do this easily, I recommend setting it as a @property and using self.latitude = [NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]];. Notice that the retain is no longer used in the assignment. This is assuming your property is set up with the retain flag, and retains it for you.

I.e.

@property (nonatomic, retain) NSNumber *latitude

ContentLicense: CC BY-SA 3.0

Body:
My application uses GPS and assigns an NSNumber instance variable every time the GPS is updated and in my last bit of testing before release, I've discovered that it leaks a lot. I'm fairly certain I know which lines are contributing to the leak, but I can't figure how to solve it.

latitude = [[NSNumber numberWithFloat:[[coordinates objectAtIndex:0] floatValue]] retain];

This line is in my GPS update method and is run regularly. Latitude is an instance variable, and when I remove the retain, I can no longer access the variable in the other methods I need. I have the variable released in the dealloc method, but that doesn't seem to do anything.

I understand the alloc-release paradigm, but I'm still not sure how to fix this.


答:
This line, the rule for all:

```<code>all: $(EXECUTABLE) $(LIBS)
</code>```

translates into:

```<code>all: concat -lstdc++fs
</code>```

and that's what's causing the error, since make doesn't know how to build -lstdc++fs - it is, after all, a compiler/linker argument rather than a file.

I don't think the $(LIBS) should be there, it makes much more sense to have:

```<code>all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS) $(LIBS)
    $(STRIP) $(EXECUTABLE)
</code>```

In other words, use $(LIBS) flags to compile the executable, but not as a dependency.

Title: Makefile problems

Body:
This line, the rule for all:

all: $(EXECUTABLE) $(LIBS)

translates into:

all: concat -lstdc++fs

and that's what's causing the error, since make doesn't know how to build -lstdc++fs - it is, after all, a compiler/linker argument rather than a file.

I don't think the $(LIBS) should be there, it makes much more sense to have:

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@ $(LDLIBS) $(LIBS)
    $(STRIP) $(EXECUTABLE)

In other words, use $(LIBS) flags to compile the executable, but not as a dependency.


问:
Python doesn't run properly on Visual Studio Code
I downloaded Visual Studio Code and installed Python following the instructions at https://code.visualstudio.com/docs/python/python-tutorial.

As I chose the Python extension in Visual Studio Code, an installation started, but it told me afterwards that the system install is not supported. Therefore I installed it with Homebrew.

First of all, I seem do not have the green 'run'-button displayed in the installation tutorial above. There I only can run code with right click and 'Run Selection/Line in Python Terminal'.

A simple print('Hello, World!') seems to run properly, but when I try to run a program with more than one line (i.e., more than one instruction) I get multiple error messages that I did not get while using Anaconda before.

For context: I am currently learning to program using Python and follow the book 'Automate the boring stuff with Python'.

The code I try to run is:

```<code>#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)
</code>```

For clarification:
Traceback (most recent call last): File "/Users/XXX/Desktop/Python Projects/Ex.py", line 7, in <module> import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip'
is the error I get.

I just want to use Visual Studio Code properly and I am really not sure why it isn't working or what I did wrong while installing it. (For example, why am I missing the green 'run'-button?!)

答: There is one syntax error in your code on line 10. sys.exit() should be on the next line. Once that was fixed, it ran fine for me in my Visual Studio Code.</p>

Body:
I downloaded Visual Studio Code and installed Python following the instructions at https://code.visualstudio.com/docs/python/python-tutorial.

As I chose the Python extension in Visual Studio Code, an installation started, but it told me afterwards that the system install is not supported. Therefore I installed it with Homebrew.

First of all, I seem do not have the green 'run'-button displayed in the installation tutorial above. There I only can run code with right click and 'Run Selection/Line in Python Terminal'.

A simple print('Hello, World!') seems to run properly, but when I try to run a program with more than one line (i.e., more than one instruction) I get multiple error messages that I did not get while using Anaconda before.

For context: I am currently learning to program using Python and follow the book 'Automate the boring stuff with Python'.

The code I try to run is:

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

For clarification:
Traceback (most recent call last): File "/Users/XXX/Desktop/Python Projects/Ex.py", line 7, in <module> import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip'
is the error I get.

I just want to use Visual Studio Code properly and I am really not sure why it isn't working or what I did wrong while installing it. (For example, why am I missing the green 'run'-button?!)


问:
Android Studio doesn't see genymotion
I updated  0.5 to 0.8.14 version of android studio ,  but now  studio doesn't see genymotion , what I must do now ? Thanks for all . </p>

<p>Edit :I solved the problem by updating genymotion too </p>

答:
Go to Genymotion → Setting → ADB → Use Custom Android SDK tools
(C:\Users\{username}\AppData\Local\Android\Sdk).

Go to Android Studio → Search for "Genymotion Device Manager" → Specific the part for Genymotion (C:\Program Files\Genymobile\Genymotion).

Go to Android Studio → View → Appearent → Toolbar.

Title: Android Studio doesn't see genymotion

Body:
I updated  0.5 to 0.8.14 version of android studio ,  but now  studio doesn't see genymotion , what I must do now ? Thanks for all .

Edit :I solved the problem by updating genymotion too


问:
Why Subject subscribe is not working in Angular 9
I have a Subject defined in the authentication service. When I want to move user information to another component, subscribe doesn't work and it doesn't work. I tried to use it in different hooks, but again it was useless. I also used BehaviorSubject, but null returns.

Does anyone know what the problem is?

auth.service.ts

```<code>import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {AuthModel} from '../Infrastructure/Models/authModel';
import {RegisterUserDeviceModel} from '../Infrastructure/Models/RegisterUserDeviceModel';
import {ResponseModel} from '../Infrastructure/Models/responseModel';
import {RegisterUserDeviceResponseModel} from '../Infrastructure/Models/registerUserDeviceResponseModel';
import {LoginResponseModel} from '../Infrastructure/Models/LoginResponseModel';
import {RegisterDeviceDataMosel} from '../app.component';
import {BehaviorSubject, Subject, throwError} from 'rxjs';
import {UserDataModel} from '../Infrastructure/Models/UserDataModel';
import {catchError, tap} from 'rxjs/operators';
import {RoleEnum} from '../Infrastructure/Enums/RoleEnum';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    devicecode: string = (<RegisterDeviceDataMosel> JSON.parse(localStorage.getItem('RegisterDeviceData'))).devicecode;
    user = new Subject<UserDataModel>();

constructor(private _http: HttpClient) {
}

Signin(data: AuthModel) {
    let _headers = new HttpHeaders();
    _headers = _headers.append('Content-Type', 'application/json');
    _headers = _headers.append('Access-Control-Allow-Origin', '*');
    _headers = _headers.append('X-Skip-Interceptor', '');
    _headers = _headers.append('device_code', this.devicecode);
    const _options = {headers: _headers};

    return this._http.post<ResponseModel<LoginResponseModel>>('http://localhost:5000/account/login', data, _options)
        .pipe( catchError(this.handelError) , tap(resData => {
            this.handleAuth(data.username, resData.response.access_token, resData.response.refresh_token
                , resData.response.role, resData.response.expires_in);
        }));
}

AutoLoading(): boolean {
    debugger;
    const userData: {
        username: string,
        access_token: string,
        refresh_token: string,
        role: RoleEnum,
        _tokenexpirationDate: string
    } = JSON.parse(localStorage.getItem('userData'));
    if (!userData) {
        return false;
    }
    const loadUser = new UserDataModel(userData.username, userData.access_token, userData.refresh_token
        , userData.role, new Date(userData._tokenexpirationDate));
    if (loadUser.token) {
        this.user.next(loadUser);
        return true;
    }
}

private handleAuth(username, token, refresh_token, role, expiresin) {
    const expirationDate = new Date(new Date().getTime() + +expiresin * 60000);
    const user = new UserDataModel(username, token, refresh_token
        , role, expirationDate);
    debugger;
    this.user.next(user);
    localStorage.setItem('userData', JSON.stringify(user));
}

private handelError(errorResponse: HttpErrorResponse){
    return throwError(errorResponse);
}
}
</code>```

component

```<code>import {AfterViewChecked, AfterViewInit, Component, OnDestroy, OnInit} from '@angular/core';
import * as momenthijri from 'moment-hijri';
import {AuthService} from '../../auth/auth.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-footer',
  styleUrls: ['./footer.component.scss'],
  templateUrl: './footer.component.html',
  providers: [AuthService]
})
export class FooterComponent implements OnInit , OnDestroy {
  private userSub: Subscription ;
  nowDate = new Date();
  hijri;
  public userName;
  public role;

  constructor(private authService: AuthService) {
  }

  ngOnInit(): void {
    this.hijri = momenthijri(this.nowDate.toString()).format('iYYYY/iM/iD');
    this.userSub = this.authService.user.subscribe( res =>{
      debugger;
      this.userName = res.username ;
      this.role = res.role;
    });
  }

  ngOnDestroy(): void {
    this.userSub.unsubscribe();
  }
}
</code>```

Thank you all for your help

答:
It happens because Subject doesn't store the data inside and you have to subscribe before providing the data in your subject. Also, you can use BehaviorSubject that stores the data inside, and all the time you subscribe to it you will receive this data, but you have to provide an initial value.

On the other hand, you can simulate BehaviorSubject without initial value by user = new ReplaySubject<UserDataModel>(1) which will store the last data and return it every time you subscribe. Hope, my explanations is clear :)

Body:
I have a Subject defined in the authentication service. When I want to move user information to another component, subscribe doesn't work and it doesn't work. I tried to use it in different hooks, but again it was useless. I also used BehaviorSubject, but null returns.

Does anyone know what the problem is?

auth.service.ts

import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {AuthModel} from '../Infrastructure/Models/authModel';
import {RegisterUserDeviceModel} from '../Infrastructure/Models/RegisterUserDeviceModel';
import {ResponseModel} from '../Infrastructure/Models/responseModel';
import {RegisterUserDeviceResponseModel} from '../Infrastructure/Models/registerUserDeviceResponseModel';
import {LoginResponseModel} from '../Infrastructure/Models/LoginResponseModel';
import {RegisterDeviceDataMosel} from '../app.component';
import {BehaviorSubject, Subject, throwError} from 'rxjs';
import {UserDataModel} from '../Infrastructure/Models/UserDataModel';
import {catchError, tap} from 'rxjs/operators';
import {RoleEnum} from '../Infrastructure/Enums/RoleEnum';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    devicecode: string = (<RegisterDeviceDataMosel> JSON.parse(localStorage.getItem('RegisterDeviceData'))).devicecode;
    user = new Subject<UserDataModel>();

constructor(private _http: HttpClient) {
}

Signin(data: AuthModel) {
    let _headers = new HttpHeaders();
    _headers = _headers.append('Content-Type', 'application/json');
    _headers = _headers.append('Access-Control-Allow-Origin', '*');
    _headers = _headers.append('X-Skip-Interceptor', '');
    _headers = _headers.append('device_code', this.devicecode);
    const _options = {headers: _headers};

    return this._http.post<ResponseModel<LoginResponseModel>>('http://localhost:5000/account/login', data, _options)
        .pipe( catchError(this.handelError) , tap(resData => {
            this.handleAuth(data.username, resData.response.access_token, resData.response.refresh_token
                , resData.response.role, resData.response.expires_in);
        }));
}

AutoLoading(): boolean {
    debugger;
    const userData: {
        username: string,
        access_token: string,
        refresh_token: string,
        role: RoleEnum,
        _tokenexpirationDate: string
    } = JSON.parse(localStorage.getItem('userData'));
    if (!userData) {
        return false;
    }
    const loadUser = new UserDataModel(userData.username, userData.access_token, userData.refresh_token
        , userData.role, new Date(userData._tokenexpirationDate));
    if (loadUser.token) {
        this.user.next(loadUser);
        return true;
    }
}

private handleAuth(username, token, refresh_token, role, expiresin) {
    const expirationDate = new Date(new Date().getTime() + +expiresin * 60000);
    const user = new UserDataModel(username, token, refresh_token
        , role, expirationDate);
    debugger;
    this.user.next(user);
    localStorage.setItem('userData', JSON.stringify(user));
}

private handelError(errorResponse: HttpErrorResponse){
    return throwError(errorResponse);
}
}

component

import {AfterViewChecked, AfterViewInit, Component, OnDestroy, OnInit} from '@angular/core';
import * as momenthijri from 'moment-hijri';
import {AuthService} from '../../auth/auth.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-footer',
  styleUrls: ['./footer.component.scss'],
  templateUrl: './footer.component.html',
  providers: [AuthService]
})
export class FooterComponent implements OnInit , OnDestroy {
  private userSub: Subscription ;
  nowDate = new Date();
  hijri;
  public userName;
  public role;

  constructor(private authService: AuthService) {
  }

  ngOnInit(): void {
    this.hijri = momenthijri(this.nowDate.toString()).format('iYYYY/iM/iD');
    this.userSub = this.authService.user.subscribe( res =>{
      debugger;
      this.userName = res.username ;
      this.role = res.role;
    });
  }

  ngOnDestroy(): void {
    this.userSub.unsubscribe();
  }
}

Thank you all for your help


问:
How do I bypass undefined JavaScript errors when doing a web scrape with a HttpWebRequest
I am trying to do a HttpWebRequest to scrape a login page's HTML and post data to that web page's username and password controls to 'auto logon' the client essentially. The problem I am running into, is the URI I am using when parsed has JavaScript within and a XML .config file that is not getting downloaded and only available to the actual hosted site it appears.

When I read the response, execution breakes in VS.NET and I get a "Microsoft JScript Runtime error: 'VerticalMenuConfig is undefined"

Looking at the script tags where debugging has stopped I see the reference to "scripts/VerticalMenuConfig.xml".

If I hit continue, the page is all messed up when written to the response of my page, and I still unsuccessfully write to any of the input text boxes. I am using an example like the following that writes to the "Search" text box automatically on Amazon; it is exactly what I need to do: http://www.worldofasp.net/tut/WebRequest/Working_with_HttpWebRequest_and_HttpWebResponse_in_ASPNET_114.aspx

Here is the code that breaks:

```<code><script language="javascript" src="scripts/VerticalMenu.js"></script>
<script>
var vm = new VerticalMenu("tdVertMenu", "scripts/VerticalMenuConfig.xml", "");
vm.openSubMenu("clientLogin");
</code>```

It breaks on the line: var vm = new VerticalMenu...

Is there a better way to do this?

答: You're describing a webpage that is already broken, you can't browse webpages that are broken, regardless of using an HttpClient or Chrome.</p>


问:
Client Side React JS post request
I am trying to execute a post request to a server running on the same machine, from client rendered react application but I am getting a bunch of errors.

I have enabled a browser plugin that can mitigate the CORS issue, I have also put a temporary filter on the server-side to pass the header Access-Control-Allow-Origin : *.

I have no issue with GET requests on that matter. I am able to query the API just fine.

Unfortunately, this is not the case with POST (Please excuse my ignorance if the answer is obvious - is it even possible to make client-side post requests?)

bellow is the function that does the request and expects the result on the console.

    const postAddCategory = () => {

        const myHeaders = {host: "localhost:3000"};

        const body = {"productCategoryName": categoryName, "enabled": enabled};

        const config = {
            headers: myHeaders
        };
        axios.post("http://localhost:8080/products/categories/category/add", body, config)
            .then(r => console.log(r.data))
    }
```

<p>The errors:
<img src="https://i.stack.imgur.com/PD5KF.png" alt="enter image description here"></p>

<p>The interesting fact is that the request is not reaching the API at all.</p>

<p>I have tried several variations on the call with different headers, excluding the host header, since it is complaining about that as well. I have tried with the fetch API. No luck. </p>

<p>Any help would be greatly appreciated.</p>

<p>Thanks</p>

<p><strong>edit</strong></p>

<p>Even though the call is <strong>not</strong> reaching the API,</p>

<p>the API is build in Java (Spring Boot)
and the filter is the following:</p>

<pre class="lang-java prettyprint-override"><code>@Component
public class ForDevelopmentOnlyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        res.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        chain.doFilter(req, res);
    }
}
</code>```

The above works because the GET request were complaining with CORS related errors before its addition.

答:
Root cause of the problem is shown by the error -

Content-type is not allowed by Access-control-allow-headers

This problem can be fixed by explicitly adding the following header to the server:

'access-control-allow-headers : content-type' on the server.

Reference:

AJAX requests from browser follow these 3 step process:

Step 1:  (Pre-flight request)

Browsers asks the server for permission, using the 'HTTP OPTIONS' request. This is also called the 'pre-flight' request.

Step 2: (Server tells the options)
Server responds to pre-flight request and indicates to the browser what is allowed.

This response contains following information:

Allowed origins (Example: xyz.com, * )

Allowed methods (Example: get, post, delete, put ...)

Allowed headers (Example: authorization, content-type, *)

Step 3:
Browser checks the options provided by the server and makes the actual AJAX request, only if the options provided by the server allow it.

More information:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

Title: Client Side React JS post request

Body:
I am trying to execute a post request to a server running on the same machine, from client rendered react application but I am getting a bunch of errors.

I have enabled a browser plugin that can mitigate the CORS issue, I have also put a temporary filter on the server-side to pass the header Access-Control-Allow-Origin : *.

I have no issue with GET requests on that matter. I am able to query the API just fine.

Unfortunately, this is not the case with POST (Please excuse my ignorance if the answer is obvious - is it even possible to make client-side post requests?)

bellow is the function that does the request and expects the result on the console.

    const postAddCategory = () => {

        const myHeaders = {host: "localhost:3000"};

        const body = {"productCategoryName": categoryName, "enabled": enabled};

        const config = {
            headers: myHeaders
        };
        axios.post("http://localhost:8080/products/categories/category/add", body, config)
            .then(r => console.log(r.data))
    }

The errors:

The interesting fact is that the request is not reaching the API at all.

I have tried several variations on the call with different headers, excluding the host header, since it is complaining about that as well. I have tried with the fetch API. No luck.

Any help would be greatly appreciated.

Thanks

edit

Even though the call is not reaching the API,

the API is build in Java (Spring Boot)
and the filter is the following:

@Component
public class ForDevelopmentOnlyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        res.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        chain.doFilter(req, res);
    }
}

The above works because the GET request were complaining with CORS related errors before its addition.


问:
Issue with geography library in Python
I want to use geography library to extract the details of the places. I am unable to install it. I installed pillow, newspaper, lxml, beautifulsoup4 and all the nltk Corpas. While installing newspaper it was giving me an error in the distribute-0.6.21 library so I installed it and after that, I am facing a below error for every module I am trying to install:

```<code>$ conda install newspaper

Traceback (most recent call last):
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 626, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/cli/main.py", line 85, in _main
    from ..base.context import context
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/base/context.py", line 18, in <module>
    from .._vendor.auxlib.path import expand
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/_vendor/auxlib/path.py", line 8, in <module>
    import pkg_resources
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/pkg_resources.py", line 45
    def _bypass_ensure_directory(name, mode=0777):
                                               ^
SyntaxError: invalid token

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/palakagrawal/anaconda/bin/conda", line 6, in <module>
    sys.exit(conda.cli.main())
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/cli/main.py", line 162, in main
    return conda_exception_handler(_main, *args)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 630, in conda_exception_handler
    return handle_exception(e)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 620, in handle_exception
    print_unexpected_error_message(e)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 561, in print_unexpected_error_message
    from conda.base.context import context
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/base/context.py", line 18, in <module>
    from .._vendor.auxlib.path import expand
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/_vendor/auxlib/path.py", line 8, in <module>
    import pkg_resources
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/pkg_resources.py", line 45
    def _bypass_ensure_directory(name, mode=0777):
                                               ^
SyntaxError: invalid token
</code>```

Please help me with above error and suggest me the way to install geography module

答:
if you are using python3 use:
pip3 install geograpy3</p>

Title: Issue with geography library in Python

Body:
I want to use geography library to extract the details of the places. I am unable to install it. I installed pillow, newspaper, lxml, beautifulsoup4 and all the nltk Corpas. While installing newspaper it was giving me an error in the distribute-0.6.21 library so I installed it and after that, I am facing a below error for every module I am trying to install:

$ conda install newspaper

Traceback (most recent call last):
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 626, in conda_exception_handler
    return_value = func(*args, **kwargs)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/cli/main.py", line 85, in _main
    from ..base.context import context
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/base/context.py", line 18, in <module>
    from .._vendor.auxlib.path import expand
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/_vendor/auxlib/path.py", line 8, in <module>
    import pkg_resources
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/pkg_resources.py", line 45
    def _bypass_ensure_directory(name, mode=0777):
                                               ^
SyntaxError: invalid token

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/palakagrawal/anaconda/bin/conda", line 6, in <module>
    sys.exit(conda.cli.main())
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/cli/main.py", line 162, in main
    return conda_exception_handler(_main, *args)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 630, in conda_exception_handler
    return handle_exception(e)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 620, in handle_exception
    print_unexpected_error_message(e)
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/exceptions.py", line 561, in print_unexpected_error_message
    from conda.base.context import context
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/base/context.py", line 18, in <module>
    from .._vendor.auxlib.path import expand
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/conda/_vendor/auxlib/path.py", line 8, in <module>
    import pkg_resources
  File "/Users/palakagrawal/anaconda/lib/python3.5/site-packages/pkg_resources.py", line 45
    def _bypass_ensure_directory(name, mode=0777):
                                               ^
SyntaxError: invalid token

Please help me with above error and suggest me the way to install geography module


问:
Create a dict from a list of tuples by summing values for the same keys
I have this list:

```<code>[(2018, '2', '172767270', '202', 'gege', 'French'),
 (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),
 (2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),
 ...
]
</code>```

I want the output to be a dictionary based on the key in the last column and the sum of values in the 3rd column.

E.g. for (172767270, French) and (1374767888, French) with their sum  172767270 + 1374767888 = 1547535158 the dictionary would have the following key-value pair:

```<code>dic = {'French': 1547535158, ...}
</code>```

and the final result would be something like:

```<code>dic = {'French': 324213424, 'Latin': 34234242, ...}
</code>```

答:
```<code>list = []  #define list here
dict_out = {} #output dictionary

def get_sum(name):
    summed = 0
    for value in list:
        if value[-1] == name:
            summed += int(value[2])
    return summed

for value in list:
    if value[-1] not in dict_out:
        dict_out[value[-1]] = get_sum(value[-1])[:4]

</code>```

Body:
I have this list:

[(2018, '2', '172767270', '202', 'gege', 'French'),
 (2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),
 (2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),
 ...
]

I want the output to be a dictionary based on the key in the last column and the sum of values in the 3rd column.

E.g. for (172767270, French) and (1374767888, French) with their sum  172767270 + 1374767888 = 1547535158 the dictionary would have the following key-value pair:

dic = {'French': 1547535158, ...}

and the final result would be something like:

dic = {'French': 324213424, 'Latin': 34234242, ...}


问:
Can't change divs ID of first element from <tempate>
I have this HTML template:

```<code><template id="single_feed">

    <div class="ibox" id="FIRST_DIV">
        <div class="ibox-title">
            <h5 id="naslov"></h5>
         </div>
        <div class="ibox-content">
            <form method="get" _lpchecked="1">
                 <div class="form-group  row"><label class="col-sm-2 col-form-label">Naziv</label>
            </form>
        </div>
    </div>
</template>
</code>```

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

```<code>    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});
</code>```

P.S:
I removed unnecessary parts to make code more readable.

答:
Hope this will helps,

const template = (document.getElementsByTagName("template")[0]).content.cloneNode(true);
const firstDiv = template.querySelector("div");
firstDiv.id = "new id";
document.body.querySelector('#kolona_1').appendChild(firstDiv);

Body:
I have this HTML template:

<template id="single_feed">

            <form method="get" _lpchecked="1">

Naziv
            </form>

</template>

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});

P.S:
I removed unnecessary parts to make code more readable.


问:
Index of vector of strings in c++
I have a vector of string including :- chemistry physics maths.
I want to access first character of each word ie c of chemistry p of physics and m of maths. How to do that? </p>

答:
I think this code should do the trick. If not then the Compiler is being a racist and doesn't like you that much. In that case you can just go-to your old buddy cpp.sh :D

String is a char Array and you can access it's contents from indexes like so

```<code>std::string str = "Hello";
std::cout << "First Index: " << str[0];
</code>```

Output:-

```<code>H
</code>```

Same goes for the vector as well

```<code>std::vector <char> str = "World!";
std::cout << "First Index: " << str[0];
</code>```

Output:-

```<code>W
</code>```

Now if you combine those two, it makes it a 2D Array so you have to access it like you access data from a 2D Array/Matrix.

```<code>std::vector <std::string> str = {"Hello", "World", "!"};
std::cout << "First Index Of Element 1: " << str[0][0] << std::endl
          << "First Index Of Element 2: " << str[1][0] << std::endl
          << "First Index Of Element 3: " << str[2][0] << std::endl;
</code>```

Output:-

```<code>H
W
!
</code>```

Program:-

```<code>#include <iostream>
#include <vector>

int main() {
    std::vector <std::string> vec = {"chemistry", "physics", "math"};
    for (int i=0; i < vec.size(); i++) {  //-- size(); Function gives the size of a vector
         std::cout << vec[i][0] << std::endl;
    }
    return 0;
}
</code>```

Output:-

```<code>c
p
m
Press any key to continue...
</code>```

Title: Index of vector of strings in c++

Body:
I think this code should do the trick. If not then the Compiler is being a racist and doesn't like you that much. In that case you can just go-to your old buddy cpp.sh :D

String is a char Array and you can access it's contents from indexes like so

std::string str = "Hello";
std::cout << "First Index: " << str[0];

Output:-

H

Same goes for the vector as well

std::vector <char> str = "World!";
std::cout << "First Index: " << str[0];

Output:-

W

Now if you combine those two, it makes it a 2D Array so you have to access it like you access data from a 2D Array/Matrix.

std::vector <std::string> str = {"Hello", "World", "!"};
std::cout << "First Index Of Element 1: " << str[0][0] << std::endl
          << "First Index Of Element 2: " << str[1][0] << std::endl
          << "First Index Of Element 3: " << str[2][0] << std::endl;

Output:-

H
W
!

Program:-

#include <iostream>
#include <vector>

int main() {
    std::vector <std::string> vec = {"chemistry", "physics", "math"};
    for (int i=0; i < vec.size(); i++) {  //-- size(); Function gives the size of a vector
         std::cout << vec[i][0] << std::endl;
    }
    return 0;
}

Output:-

c
p
m
Press any key to continue...


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
You have defined the factorial () function inside main function. This is not allowed. You need to put the entire function out of the main.

You have done f(x) = f(x - 1) + 2;. Here you have a function on the left side of the assignment which is incorrect. Also i could  not understant what was the cause of such an attempt.

The code which you require to computer the recursive function is:

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

int main (void)
{
  int x, y;
  printf ("\nEnter x: ");
  scanf ("%d", &x);
  y = f (x);
  printf ("\n%d\n", y);
  return 0;
}

int f (int x)
{
  if (x <= 0)
  {
   return 0;
  }
  else
  {
    return f (x - 1) + 2;
  }
}
</code>```

I could not understand why did the factorial function came into your way. May be probably you wanted to modify it and implement the given problem.

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}

Body:
You have defined the factorial () function inside main function. This is not allowed. You need to put the entire function out of the main.

You have done f(x) = f(x - 1) + 2;. Here you have a function on the left side of the assignment which is incorrect. Also i could  not understant what was the cause of such an attempt.

The code which you require to computer the recursive function is:

#include <stdio.h>

int main (void)
{
  int x, y;
  printf ("\nEnter x: ");
  scanf ("%d", &x);
  y = f (x);
  printf ("\n%d\n", y);
  return 0;
}

int f (int x)
{
  if (x <= 0)
  {
   return 0;
  }
  else
  {
    return f (x - 1) + 2;
  }
}

I could not understand why did the factorial function came into your way. May be probably you wanted to modify it and implement the given problem.


问:
TypeError when parsing Blogger API response: Cannot read property 'url' of undefined
I'm parsing JSON feed from the blogger API but its throwing following error:

37:59 Uncaught TypeError: Cannot read property 'url' of undefined

Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.

Javascript Code:

```

JsFiddle: https://jsfiddle.net/645pg9rz/

答:
Updated:  the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)

there are no pictures in the object that came to you. It's the only icon that comes. I put them.

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>Document</title>

```

Body:
I'm parsing JSON feed from the blogger API but its throwing following error:

37:59 Uncaught TypeError: Cannot read property 'url' of undefined

Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.

Javascript Code:

JsFiddle: https://jsfiddle.net/645pg9rz/

Body:
Updated:  the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)

there are no pictures in the object that came to you. It's the only icon that comes. I put them.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <title>Document</title>

  <style>

  </style>
</head>

<body>

  <div class="row" id="news"></div>

  <script>
    function mycallback(json) {
      console.log(json)
      for (var i = 0; i < json.feed.entry.length; i++) {
        for (var j = 0; j < json.feed.entry[i].link.length; j++) {
          if (json.feed.entry[i].link[j].rel == 'alternate') {
            var postUrl = json.feed.entry[i].link[j].href;
            break;
          }
        }
        var postTitle = json.feed.entry[i].title.$t;
        var postAuthor = json.feed.entry[i].author[0].name.$t;
        var postSummary = json.feed.entry[i].summary.$t;
        var entryShort = postSummary.substring(0, 400);
        var entryEnd = entryShort.lastIndexOf(" ");
        var postContent = entryShort.substring(0, entryEnd) + '...';
        var postImage = json.feed.entry[i].author[0].gd$image.src;
        var postTimestamp = json.feed.entry[i].published.$t;
        console.log(postImage)
        var item = '<div class="col-md-3 mb-4 blogpost-main">';
        var item = item + '<div class="card h-100">';
        var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
        var item = item + '<div class="card-body">';
        var item = item + '<a href=' + postUrl + '><h6 class="card-title">' + postTitle + '</h6></a>';
        var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= ' + postTimestamp + '>' + postTimestamp + '</time></p>';
        var item = item + '</div>';
        var item = item + '</div>';
        var item = item + '</div>';

        document.getElementById("news").innerHTML += item;

      }
    }
  </script>
  <script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>

</body>

</html>


答:
It's the indentation error:

```<code>if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()
</code>```

sys.exit() should be on the next line.

Title: Python doesn't run properly on Visual Studio Code

Body:
It's the indentation error:

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

sys.exit() should be on the next line.


问:
Camera does not return to main activity after taking picture
When the main activity starts it directly starts the intent for MediaStore.ACTION_IMAGE_CAPTURE
I implemented the onActivityResult method, but when I take a picture it does not return back to the main activity, rather it remains in the camera app

This is the code:

```<code>final int REQUEST_TAKE_IMAGE = 1;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_TAKE_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_TAKE_IMAGE){
            if(resultCode == RESULT_OK){
                assert data != null;
                Bundle extras = data.getExtras();
                assert extras != null;
                Bitmap bitmap = (Bitmap) extras.get("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }
</code>```

答: Try shifting the intent launch to a button click listener, my guess what is happening is whenever your activity starts, it takes the person back to the camera app as intent is launched on start and activity uses this callback every time you try to bring it to the foreground,i.e, taking a pick and expecting it to bring you back to the activity.</p>

Body:
When the main activity starts it directly starts the intent for MediaStore.ACTION_IMAGE_CAPTURE
I implemented the onActivityResult method, but when I take a picture it does not return back to the main activity, rather it remains in the camera app

This is the code:

final int REQUEST_TAKE_IMAGE = 1;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_TAKE_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_TAKE_IMAGE){
            if(resultCode == RESULT_OK){
                assert data != null;
                Bundle extras = data.getExtras();
                assert extras != null;
                Bitmap bitmap = (Bitmap) extras.get("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }


问:
Cannot zoom in and out of nib in the new Interface Builder
Have I missed something obvious or is it not possible to zoom freely in and out of an open nib file, within the integrated Interface Builder of Xcode 4?</p>

答:
EDIT: This is not an answer but a suggestion to at least zoom in and have better pixel level control.

I am unaware of a way to zoom in/out within xcode but with a mac, you can zoom in using the accessibility controls. On my MacBook, I hold command and scroll with two fingers on the touchpad to enable this feature.


问:
How to implement Role based access control in API using WSO2 stack
We are using WSO2IS as IAM server  , roles  and Users are managed in WSO2IS. WSO2EI WILL be integration server , exposing private APIs

What would be the right way to implement role based access control using , like some set of APIs only to be accessed by users with specific groups. How can I implement this most simplest way ? Is there a requirement of WSO2AM here ?

Thanks

答:
EI is not the ideal way to exposing private oauth secured APIs. Even though you can achieve it with EI, that would be an excessive effort when integrating.

Use API Manager to expose the APIs to your crowd. Configure Identity Server as the Key Manager (Token Manager) of the APIM server. APIM server knows how to talk to the Identity Server to generate and validate access tokens. So there's no explicit effort to integrate the resource server(APIM Gateway) with the authorization server(IAM).

Share the user store between both the servers. (IS and APIM)

Configure IS as the Key Manager of the API server.

Register your API in the publisher/developer portal.

When publishing, you can define role based access restrictions to your API resources from the Publisher portal. (Roe : Scope mapping)

Once you define, IS will always check your roles upon providing an access token for you.

As you've already defined a role : scope mapping, scopes you request in your token generation request, will only be accepted if you (requester) has the expected roles. Therefore, the scope of your token will only be as good as the roles you've got assigned to yourself. Now, as the API resources you've published require a defined set of scopes, not all the access tokens will be accepted when trying to access the APIs. Only the ones with the expected scopes.

Configure IS-KM with APIM

Role based scopes


Title: Create a dict from a list of tuples by summing values for the same keys

Body:
If you want to have the sum of the third column based on language, then:

d = defaultdict(int)
l = [(2018, '2', '172767270', '202', 'gege', 'French'),(2018, '2', '172763270', '202', 'gege', 'English'),(2018, '2', '17167270', '202', 'gege', 'Spanish'),
(2012, '212', '56007072', '200', 'cdadcadc', 'Minangkabou'),(2018, '2', '1727672', '202', 'gege', 'Arabic'),(2013, 'J21', '186144990', '200', 'sacacs', 'Latin'),(2017, '2', '1374767888', '202', 'gege', 'French')]

for elem in l:
    d[elem[5]]+= int(elem[2])

d

Output:

defaultdict(int,
            {'Arabic': 1727672,
             'English': 172763270,
             'French': 1547535158,
             'Latin': 186144990,
             'Minangkabou': 56007072,
             'Spanish': 17167270})

After that, if you just want the top 5, you can do the following:

dict(sorted(list(d.items()),key= lambda x:x[1],reverse=True)[:5])

Output:

 {'English': 172763270,
 'French': 1547535158,
 'Latin': 186144990,
 'Minangkabou': 56007072,
 'Spanish': 17167270}


问:
Adding python script to views.py in django and firing with button click
Total novice here.

Trying to make a web app that generates and displays a random video when a button
is clicked on a django page.

I have a python script that generates the video.

I have a django project with templates/home.html, views.py, urls.py, and
my python script videogenfull.py in it. For now it looks like this..

```<code>
views.py:

from django.http import HttpResponse
from django.shortcuts import render

def home_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    return render(request, "home.html", {})

</code>```

```<code>
urls.py:

from django.contrib import admin
from django.urls import path

from pages.views import home_view

urlpatterns = [
    path('', home_view, name='home'),
    path('admin/', admin.site.urls)
]

</code>```

videogenfull.py -  pulls random videos from web, edits them and exports them out as one (very small) video. I have setup a static folder where the generated video will go to and put in some html code in home.html for the video to play.

The html page successfully shows up in my browser - text header and temp video for now.

Next I know that I need to:

make a html/ajax/jquery button in my html file

write some code in views.py to get videogenfull.py in there so it fires when the button is clicked

I've been at this last part for a good while and can't figure out how to do it.
Is this broadly what I need to do?

```<code>home.html:

<button id="myClickButton" type="button">Click</button>
<div id="myOutput"></div>

$("#myClickButton").click(function() {
    $.get("/output/", function(data) {
        $("#myOutput").html(data);
    }, "html");
});

</code>```

```<code>views.py:

def index(request):
    return render(request, 'yourapp/index.html')

</code>```

Thanks!

答:
First create function in views.py

```<code>from django.http import HttpResponse
from django.shortcuts import render

def home_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    return render(request, "home.html")

def output_view(request):
    return HttpResponse("<h1>Hello World</h1>")
</code>```

Next you have to assign it to url output/ in urls.py

```<code>from django.contrib import admin
from django.urls import path

from pages.views import home_view, output_view

urlpatterns = [
    path('', home_view, name='home'),
    path('output/', output_view, name='output'),
    path('admin/', admin.site.urls),
]
</code>```

And you have to use

<button id="myClickButton" type="button">Click</button>

<script>
  $("#myClickButton").click(function() {
    $.get("/output/", function(data) {
      $("#myOutput").html(data);
    }, "html");
  });
</script>
```

<p>If it works then you can try to use <code>videogenfull.py</code> in function <code>output()</code>. But it may need more work so I can only show ideas how to use it.</p>

<p>You can run it as subprocess</p>

```import subprocess

def output_view(requests):
    subprocess.run(["python", "videogenfull.py"])
    return HttpResponse("
Hello World
")
```

<p>or you can use it as module - if you have code in function(s) - ie.</p>

```import videogenfull

def output_view(requests):
    filename = videogenfull.some_function()
    return HttpResponse(f'
Hello World
<video src="{filename}"/>')
```

Body:
Total novice here.

Trying to make a web app that generates and displays a random video when a button
is clicked on a django page.

I have a python script that generates the video.

I have a django project with templates/home.html, views.py, urls.py, and
my python script videogenfull.py in it. For now it looks like this..

views.py:

from django.http import HttpResponse
from django.shortcuts import render

def home_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    return render(request, "home.html", {})

urls.py:

from django.contrib import admin
from django.urls import path

from pages.views import home_view

urlpatterns = [
    path('', home_view, name='home'),
    path('admin/', admin.site.urls)
]

videogenfull.py -  pulls random videos from web, edits them and exports them out as one (very small) video. I have setup a static folder where the generated video will go to and put in some html code in home.html for the video to play.

The html page successfully shows up in my browser - text header and temp video for now.

Next I know that I need to:

make a html/ajax/jquery button in my html file

write some code in views.py to get videogenfull.py in there so it fires when the button is clicked

I've been at this last part for a good while and can't figure out how to do it.
Is this broadly what I need to do?

home.html:

<button id="myClickButton" type="button">Click</button>

$("#myClickButton").click(function() {
    $.get("/output/", function(data) {
        $("#myOutput").html(data);
    }, "html");
});

views.py:

def index(request):
    return render(request, 'yourapp/index.html')

Thanks!

Body:
First create function in views.py

from django.http import HttpResponse
from django.shortcuts import render

def home_view(request, *args, **kwargs):
    print(args, kwargs)
    print(request.user)
    return render(request, "home.html")

def output_view(request):
    return HttpResponse("<h1>Hello World</h1>")

Next you have to assign it to url output/ in urls.py

from django.contrib import admin
from django.urls import path

from pages.views import home_view, output_view

urlpatterns = [
    path('', home_view, name='home'),
    path('output/', output_view, name='output'),
    path('admin/', admin.site.urls),
]

And you have to use <script> in home.html

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<button id="myClickButton" type="button">Click</button>

<div id="myOutput"></div>

<script>
  $("#myClickButton").click(function() {
    $.get("/output/", function(data) {
      $("#myOutput").html(data);
    }, "html");
  });
</script>

If it works then you can try to use videogenfull.py in function output(). But it may need more work so I can only show ideas how to use it.

You can run it as subprocess

import subprocess

def output_view(requests):
    subprocess.run(["python", "videogenfull.py"])
    return HttpResponse("<h1>Hello World</h1>")

or you can use it as module - if you have code in function(s) - ie.

import videogenfull

def output_view(requests):
    filename = videogenfull.some_function()
    return HttpResponse(f'<h1>Hello World</h1><video src="{filename}"/>')


问:
How to prevent form submitting on other button is clicked rather than submit button in JavaScript
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.</p>

```<code><form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />
  <div class="mt-2">
    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>
  </div>
</form>
<script>
  const add_list_form = document.querySelector('#add_list_form');
  add_list_form.addEventListener('submit',(e)=>{ e.preventDefault();
  console.log('form is submitted..') })
<script>
</code>```

答: You can use in js method preventDefault() to not to have a default submit or reload by default </p>

Body:
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.

<form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />

    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>

</form>


问:
Permission failure cloning in Git in Windows
When I clone from GitHub using CMD or PowerShell with ssh-agent on Windows 10 v.1909, the following shows:

```<code>git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
</code>```

However, I ran ssh -vT git@github.com and the key does work

```<code>debug1: Offering public key: {My key}
</code>```

And

```<code>Hi {My username}! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

But with Git bash I can clone just fine.

This also happen with GitLab.

I tried

```<code>Host *
 ForwardAgent yes
</code>```

in .ssh/config and it doesn't work.

I also tried every solution from GitHub Support Page and GitHub Community Forum and still doesn't work.

PS. I prefer Windows cmd.

答:
It turns out that git doesn't use native OpenSSH. Here what's I did

```<code>git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"
</code>```

Reference here

Body:
When I clone from GitHub using CMD or PowerShell with ssh-agent on Windows 10 v.1909, the following shows:

git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

However, I ran ssh -vT git@github.com and the key does work

debug1: Offering public key: {My key}

And

Hi {My username}! You've successfully authenticated, but GitHub does not provide shell access.

But with Git bash I can clone just fine.

This also happen with GitLab.

I tried

Host *
 ForwardAgent yes

in .ssh/config and it doesn't work.

I also tried every solution from GitHub Support Page and GitHub Community Forum and still doesn't work.

PS. I prefer Windows cmd.

Body:
It turns out that git doesn't use native OpenSSH. Here what's I did

git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"

Reference here


问:
Why -1 causes key error in pandas dataframe post resetting its index and how to make it work
Lets say I have a pandas dataframe and the -1 indexing does not work post resetting its index. How do I make it work as it was earlier and why it doesn't work in this case?:

答:
Try this:

```<code>list(data.reset_index()['Date'])[-1]
</code>```

I dont think reset_index() as anything to do with it. Choosing a specific column from a dataframe returns a series. We may need to cast it to a list to access via negative index position.

This is a small example I tried on a sample dummy df:

```<code>'''
year    key val
2019    a   3
2019    a   4
2019    b   3
2019    c   5
2020    d   6
2020    e   1
2020    f   2
'''

import pandas as pd

df = pd.read_clipboard()

print(df)
</code>```

Source df:

```<code>   year  key  val
0  2019  a      3
1  2019  a      4
2  2019  b      3
3  2019  c      5
4  2020  d      6
5  2020  e      1
6  2020  f      2
</code>```

Both of these throw key error:

```<code>mask = df['year'][-1]
print(mask)
</code>```

or

```<code>mask = df.reset_index()['year'][-1]
print(mask)
</code>```

Output:

```<code>KeyError: -1
</code>```

Both of these work:

```<code>mask = list(df.reset_index()['year'])[-1]
</code>```

or

```<code>mask = list(df['year'])[-1]
</code>```

Output:

```<code>2020
</code>```

Body:
Try this:

list(data.reset_index()['Date'])[-1]

I dont think reset_index() as anything to do with it. Choosing a specific column from a dataframe returns a series. We may need to cast it to a list to access via negative index position.

This is a small example I tried on a sample dummy df:

'''
year    key val
2019    a   3
2019    a   4
2019    b   3
2019    c   5
2020    d   6
2020    e   1
2020    f   2
'''

import pandas as pd

df = pd.read_clipboard()

print(df)

Source df:

   year  key  val
0  2019  a      3
1  2019  a      4
2  2019  b      3
3  2019  c      5
4  2020  d      6
5  2020  e      1
6  2020  f      2

Both of these throw key error:

mask = df['year'][-1]
print(mask)

or

mask = df.reset_index()['year'][-1]
print(mask)

Output:

KeyError: -1

Both of these work:

mask = list(df.reset_index()['year'])[-1]

or

mask = list(df['year'])[-1]

Output:

2020


问:
Faster web scraping with R
I need help to speed up a web scraping with R.
I need to scrape some data from about 23.000 web pages but I need to do it faster than 2 hours (!) and I don't know how to improve my script to reach the goal (I'm new with R!).
Here's an example of the page: https://"sample"/46351 and every page is characterized by a code at the end of the url. In Codes$id there are all codes.
Can anyone give me any advice?
Are there any functions to speed up all?
Here attached the code.
Thanks a lot for the help!

```<code>> cr <- c()
> pr <- c()
> vig <- c()
> ges <- c()
> tabellafinale <- NULL
> tabellafinale <- data.table(ges,cr, pr, vig,stringsAsFactors = FALSE)
> imp <- Codes$id
> str1 <- "https://"sample"/"
> for (p in 1:length(imp)) {
+
+   try(
+     {
+       str2 <- imp[p]
+       str3 <- paste(str1,str2,sep="")
+       page<-read_html(str3)
+       carr<-html_text(html_nodes(page,".span3"))
+       prez<-html_text(html_nodes(page,".carbFormat"))
+       viag<-html_text(html_nodes(page,".span5"))
+       gest <- str2
+       carr<-gsub("\n","",carr)
+       via<-gsub("\n","",via)
+       pre<-gsub("\n","",pre)
+       carr<-gsub("\r","",carr)
+       via<-gsub("\r","",via)
+       pre<-gsub("\r","",pre)
+       carr<-gsub("\t","",carr)
+       via<-gsub("\t","",via)
+       pre<-gsub("\t","",pre)
+       car <- data.table(carr)
+       n <- length(carr)
+       carb <- carr[7:n]
+       cr <- data.table(carb)
+       prezzi <- data.table(pre)
+       vigore <- data.table(via)
+       ges <- data.table(gest)
+       oss <- data.table(ges,cr, pr, vig, stringsAsFactors = FALSE)
+       tabellafinale <- rbind(tabellafinale, oss)
+     }
+     , silent=T
+   )
+   closeAllConnections()
+ }
</code>```

答:
You can try :

```<code>library(rvest)

tabellafinale <- do.call(rbind, lapply(Codes$id, function(str2) {
  try({
    str3 <- paste0(str1,str2)
    page<-read_html(str3)
    carr<-html_text(html_nodes(page,".span3"))
    prez<-html_text(html_nodes(page,".carbFormat"))
    viag<-html_text(html_nodes(page,".span5"))
    carr<- gsub("[\n\r\t]","",carr)
    prez<- gsub("[\n\r\t]","",prez)
    viag<- gsub("[\n\r\t]","",viag)
    carb <- carr[7:length(carr)]
    data.frame(str2,carb, prez, viag, stringsAsFactors = FALSE)
  }, silent = TRUE)
}))
</code>```

You can replace do.call rbind + lapply to map_df from purrr.

```<code>tabellafinale <- map_df(Codes$id, function(str2) {
   .....rest of the code
   .....as it is
})
</code>```

Title: Faster web scraping with R

Body:
I need help to speed up a web scraping with R.
I need to scrape some data from about 23.000 web pages but I need to do it faster than 2 hours (!) and I don't know how to improve my script to reach the goal (I'm new with R!).
Here's an example of the page: https://"sample"/46351 and every page is characterized by a code at the end of the url. In Codes$id there are all codes.
Can anyone give me any advice?
Are there any functions to speed up all?
Here attached the code.
Thanks a lot for the help!

> cr <- c()
> pr <- c()
> vig <- c()
> ges <- c()
> tabellafinale <- NULL
> tabellafinale <- data.table(ges,cr, pr, vig,stringsAsFactors = FALSE)
> imp <- Codes$id
> str1 <- "https://"sample"/"
> for (p in 1:length(imp)) {
+
+   try(
+     {
+       str2 <- imp[p]
+       str3 <- paste(str1,str2,sep="")
+       page<-read_html(str3)
+       carr<-html_text(html_nodes(page,".span3"))
+       prez<-html_text(html_nodes(page,".carbFormat"))
+       viag<-html_text(html_nodes(page,".span5"))
+       gest <- str2
+       carr<-gsub("\n","",carr)
+       via<-gsub("\n","",via)
+       pre<-gsub("\n","",pre)
+       carr<-gsub("\r","",carr)
+       via<-gsub("\r","",via)
+       pre<-gsub("\r","",pre)
+       carr<-gsub("\t","",carr)
+       via<-gsub("\t","",via)
+       pre<-gsub("\t","",pre)
+       car <- data.table(carr)
+       n <- length(carr)
+       carb <- carr[7:n]
+       cr <- data.table(carb)
+       prezzi <- data.table(pre)
+       vigore <- data.table(via)
+       ges <- data.table(gest)
+       oss <- data.table(ges,cr, pr, vig, stringsAsFactors = FALSE)
+       tabellafinale <- rbind(tabellafinale, oss)
+     }
+     , silent=T
+   )
+   closeAllConnections()
+ }

Body:
You can try :

library(rvest)

tabellafinale <- do.call(rbind, lapply(Codes$id, function(str2) {
  try({
    str3 <- paste0(str1,str2)
    page<-read_html(str3)
    carr<-html_text(html_nodes(page,".span3"))
    prez<-html_text(html_nodes(page,".carbFormat"))
    viag<-html_text(html_nodes(page,".span5"))
    carr<- gsub("[\n\r\t]","",carr)
    prez<- gsub("[\n\r\t]","",prez)
    viag<- gsub("[\n\r\t]","",viag)
    carb <- carr[7:length(carr)]
    data.frame(str2,carb, prez, viag, stringsAsFactors = FALSE)
  }, silent = TRUE)
}))

You can replace do.call rbind + lapply to map_df from purrr.

tabellafinale <- map_df(Codes$id, function(str2) {
   .....rest of the code
   .....as it is
})


问:
Django inline formset will always create new object instead of update them
I've 2 model First and Second with a FK from Second to First. I created a form for the 2 class and a inline formset for Second. On template I manually designed my form and with jQuery I'm able to add dynamic forms of Second.

On UpdateView the form is correctly populated, but when I submit the form, all Second instances are created again with new ids instead of updating them. I double checked that on HTML there are name=PREFIX-FORM_COUNT-id with correct ids, but seems that Django ignores it.

I'm using Django 2.2.12 & Python 3.6

Here what I made:

models.py

class First(models.Model):
    name = models.CharField(max_length=100, null=False)

class Second(models.Model):
    first= models.ForeignKey(First, null=False, on_delete=models.CASCADE)
    number= models.FloatField(null=False, default=0)
```

<p><strong>form.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class FirstForm(forms.ModelForm):

    class Meta:
        model = First
        fields = "__all__"

class SecondForm(forms.ModelForm):
    class Meta:
        model = Second
        fields = "__all__"

SecondsFormset = inlineformset_factory(First, Second, SecondForm)
</code>```

view.py

class FirstUpdateView(UpdateView):
    template_name = "first.html"
    model = First
    form_class = FirstForm
    context_object_name = "first_obj"

    def get_success_url(self):
        return reverse(...)

    def forms_valid(self, first, seconds):
        try:
            first.save()
            seconds.save()
            messages.success(self.request, "OK!")

        except DatabaseError as err:
            print(err)
            messages.error(self.request, "Ooops!")
        return HttpResponseRedirect(self.get_success_url())

    def post(self, request, *args, **kwargs):
        first_form = FirstForm(request.POST, instance=self.get_object())
        second_forms = SecondsFormset(request.POST, instance=self.get_object(), prefix="second")
        if first_form .is_valid() and second_forms.is_valid():
            return self.forms_valid(first_form , second_forms)
        ...
```

<p><strong>.html</strong> <em>(putted only essential tags)</em></p>

<pre class="lang-html prettyprint-override"><code><form method="post">
    {% csrf_token %}
    <input type="text" id="name" value="{{ first_obj.name }}" name="name" required>
    <input type="hidden" name="second-TOTAL_FORMS" value="0" id="second-TOTAL_FORMS">
    <input type="hidden" name="second-INITIAL_FORMS" value="0" id="second-INITIAL_FORMS">
    <input type="hidden" name="second-MIN_NUM_FORMS" value="0" id="second-MIN_NUM_FORMS">
    <div id="seconds_container">
        {% for s in first_obj.second_set.all %}
            <input type="hidden"  name="second-{{forloop.counter0}}-id" value="{{s.pk}}">
            <input type="hidden"  name="second-{{forloop.counter0}}-first" value="{{first_obj.pk}}">
            <input type="number" min="0" max="10" step="1" value="{{s.number}}" name="second-{{forloop.counter0}}-number" required>
        {% endfor %}
    </div>
    <button class="btn btn-success" type="submit">Update</button>
</form>
</code>```

I checked how Django creates forms and it will only add DELETE checkbox on it, but all other infos are correctly stored into the formset. When I do .save() it will create new Second element on db instead of change them.
What am I missing?

答:
I solved this!
I setted TOTAL_FORMS and INITIAL_FORMS with wrong values. From Django's docs:

total_form_count returns the total number of forms in this formset. initial_form_count returns the number of forms in the formset that were pre-filled, and is also used to determine how many forms are required. You will probably never need to override either of these methods, so please be sure you understand what they do before doing so.

So the correct way to use it is:

In views:

Generate FormSets with extra=0

In HTML:

Set TOTAL_FORMS with number of rows you are POSTing and change it dinamically if dinamically add/remove rows;

Set INITIAL_FORMSwith number of alredy filled rows (editing/deleting) and never change this;

To delete a pre-filled row use DELETE checkbox instead of removing entire row;

Body:
I've 2 model First and Second with a FK from Second to First. I created a form for the 2 class and a inline formset for Second. On template I manually designed my form and with jQuery I'm able to add dynamic forms of Second.

On UpdateView the form is correctly populated, but when I submit the form, all Second instances are created again with new ids instead of updating them. I double checked that on HTML there are name=PREFIX-FORM_COUNT-id with correct ids, but seems that Django ignores it.

I'm using Django 2.2.12 & Python 3.6

Here what I made:

models.py

class First(models.Model):
    name = models.CharField(max_length=100, null=False)

class Second(models.Model):
    first= models.ForeignKey(First, null=False, on_delete=models.CASCADE)
    number= models.FloatField(null=False, default=0)

form.py

class FirstForm(forms.ModelForm):

    class Meta:
        model = First
        fields = "__all__"

class SecondForm(forms.ModelForm):
    class Meta:
        model = Second
        fields = "__all__"

SecondsFormset = inlineformset_factory(First, Second, SecondForm)

view.py

class FirstUpdateView(UpdateView):
    template_name = "first.html"
    model = First
    form_class = FirstForm
    context_object_name = "first_obj"

    def get_success_url(self):
        return reverse(...)

    def forms_valid(self, first, seconds):
        try:
            first.save()
            seconds.save()
            messages.success(self.request, "OK!")

        except DatabaseError as err:
            print(err)
            messages.error(self.request, "Ooops!")
        return HttpResponseRedirect(self.get_success_url())

    def post(self, request, *args, **kwargs):
        first_form = FirstForm(request.POST, instance=self.get_object())
        second_forms = SecondsFormset(request.POST, instance=self.get_object(), prefix="second")
        if first_form .is_valid() and second_forms.is_valid():
            return self.forms_valid(first_form , second_forms)
        ...

.html (putted only essential tags)

<form method="post">
    {% csrf_token %}
    <input type="text" id="name" value="{{ first_obj.name }}" name="name" required>
    <input type="hidden" name="second-TOTAL_FORMS" value="0" id="second-TOTAL_FORMS">
    <input type="hidden" name="second-INITIAL_FORMS" value="0" id="second-INITIAL_FORMS">
    <input type="hidden" name="second-MIN_NUM_FORMS" value="0" id="second-MIN_NUM_FORMS">

        {% for s in first_obj.second_set.all %}
            <input type="hidden"  name="second-{{forloop.counter0}}-id" value="{{s.pk}}">
            <input type="hidden"  name="second-{{forloop.counter0}}-first" value="{{first_obj.pk}}">
            <input type="number" min="0" max="10" step="1" value="{{s.number}}" name="second-{{forloop.counter0}}-number" required>
        {% endfor %}

    <button class="btn btn-success" type="submit">Update</button>
</form>

I checked how Django creates forms and it will only add DELETE checkbox on it, but all other infos are correctly stored into the formset. When I do .save() it will create new Second element on db instead of change them.
What am I missing?