问:
React native error while creating bottom navigation
I am trying to create Bottom Navigation in react native project. I am getting this error

Invariant violation: Element type is invalid: expected string (for built-in components) or a class/function (for a composite components) but got undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

But I did export to all my files and I didn't mixed with any default or named imports.

Index.js

```<code>import React from 'react';
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './src/redux/reducers/rootReducer'
import { NavigationContainer } from '@react-navigation/native'

const store = createStore(rootReducer)

const Root = () => (
    <Provider store={store}>
        <NavigationContainer>
            <App />
        </NavigationContainer>
    </Provider>
)

AppRegistry.registerComponent(appName, () => Root);
</code>```

App.js

```<code>import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { MaterialCommunityIcons } from 'react-native-vector-icons';

import Accounts from './src/components/Accounts';
import Categories from './src/components/Categories';
import Transactions from './src/components/Transactions';
import Budget from './src/components/Budget';
import Overview from './src/components/Overview';

const Tab = createMaterialBottomTabNavigator();

export default App = () => {
  return (
    <Tab.Navigator
      initialRouteName="Accounts"
      activeColor="#e91e63"
      labelStyle={{ fontSize: 12 }}
      style={{ backgroundColor: 'tomato' }}
    >
      <Tab.Screen
        name="Accounts"
        component={Accounts}
        options={{
          tabBarLabel: 'Home',
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="home" color={color} size={size} />
          ),
        }}
      />
      <Tab.Screen ... />
<Tab.Screen ... />
    </Tab.Navigator>
  );
}
</code>```

What is the error in my coding? I have gone through previous questions but all the solutions are changing default to named and vice versa.

答:
Adding export default solved my problem</p>

```<code>Code :

//Import library to help create component
import React from 'react';
import { AppRegistry } from 'react-native';
import Header from './src/components/header';

//Create a Component
const App = () => (
  <Header />
);

//Export App - This line solved my issue
export default App;

//Render it to the device
AppRegistry.registerComponent('albums', () => App);
//albums is project name that we use while creating RN App
</code>```

Body:
I am trying to create Bottom Navigation in react native project. I am getting this error

Invariant violation: Element type is invalid: expected string (for built-in components) or a class/function (for a composite components) but got undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

But I did export to all my files and I didn't mixed with any default or named imports.

Index.js

import React from 'react';
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './src/redux/reducers/rootReducer'
import { NavigationContainer } from '@react-navigation/native'

const store = createStore(rootReducer)

const Root = () => (
    <Provider store={store}>
        <NavigationContainer>
            <App />
        </NavigationContainer>
    </Provider>
)

AppRegistry.registerComponent(appName, () => Root);

App.js

import React from 'react';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { MaterialCommunityIcons } from 'react-native-vector-icons';

import Accounts from './src/components/Accounts';
import Categories from './src/components/Categories';
import Transactions from './src/components/Transactions';
import Budget from './src/components/Budget';
import Overview from './src/components/Overview';

const Tab = createMaterialBottomTabNavigator();

export default App = () => {
  return (
    <Tab.Navigator
      initialRouteName="Accounts"
      activeColor="#e91e63"
      labelStyle={{ fontSize: 12 }}
      style={{ backgroundColor: 'tomato' }}
    >
      <Tab.Screen
        name="Accounts"
        component={Accounts}
        options={{
          tabBarLabel: 'Home',
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="home" color={color} size={size} />
          ),
        }}
      />
      <Tab.Screen ... />
<Tab.Screen ... />
    </Tab.Navigator>
  );
}

What is the error in my coding? I have gone through previous questions but all the solutions are changing default to named and vice versa.

Body:
Adding export default solved my problem

Code :

//Import library to help create component
import React from 'react';
import { AppRegistry } from 'react-native';
import Header from './src/components/header';

//Create a Component
const App = () => (
  <Header />
);

//Export App - This line solved my issue
export default App;

//Render it to the device
AppRegistry.registerComponent('albums', () => App);
//albums is project name that we use while creating RN App


来源: stackexchange

问:
Windows 7 OpenLDAP Curl DLL Dependency Hell
I really hope someone can be of help to me because this problem has me totally stuck and frustrated.

Yesterday I installed a fresh and shiney new Windows 7 x64 onto a development box.

I got VS2008 installed, Tortoise SVN, did a checkout, compiled my currently project, all fine and dandy.

But when I go to run (either F5 in VS or just running the exe from the shell) I get a dialog box that looks like this:

(source: aliparr.net)

So I fiddle around and can't see an obvious problem. I bust out depends.exe, thinking maybe there's a dll missing, and I get this:

(source: aliparr.net)

So I play, finding different versions of gpsvc.dll and ishims.dll and putting them in with the .exe, No luck.

If I do a profile in depends (which follows the Output window of vs), I get this:

```<code>..
Loaded "c:\windows\syswow64\ADVAPI32.DLL" at address 0x75F20000 by thread 1.  Successfully hooked module.

Loaded "c:\windows\syswow64\LPK.DLL" at address 0x76B20000 by thread 1.  Successfully hooked module.

Loaded "c:\windows\syswow64\USP10.DLL" at address 0x761C0000 by thread 1.  Successfully hooked module.

Loaded "c:\windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_508ed732bcbc0e5a\MSVCR90.DLL" at address 0x70570000 by thread 1.  Successfully hooked module.

Loaded "c:\users\ali\desktop\repository\development\trunk\spree\bin\debug\OPENLDAP.DLL" at address 0x001E0000 by thread 1.  Successfully hooked module.

Exited "c:\users\ali\desktop\repository\development\trunk\spree\bin\debug\SPREE.EXE" (process 0x5D4) with code -1073741701 (0xC000007B) by thread 1.
</code>```

So it seems openldap.dll is the last thing to get loaded before it all goes wrong. I require this dll because I use cURL within the application to do a little JSON communicating...

I've tried playing with moving files and trying differing dlls, but honestly I'm acting a little blind here. Can someone please help or point me in the right direction?

It should be noted these dlls and setup work fine in Windows Vista x64 and x86 - is this a Windows 7 thing?

Massive thanks in advance, I might still have some hair left after this is done.

Edit

I've now realised curl.exe dies in exactly the same way with openldap.dll - I guess some windows 7 issue?
Can you/does anyone have a curl without the dependency on openldap? Is there another lightweight C/C++ library out there that'll let me fetch a document over http and do the odd http POST ?

Thanks

答: I've also found that mine is trying to load a 64 bit version of LIBSASL.DLL - the one that came with my 64 bit Tortoise distribution.  I also only need curl for pulling a bit of JSON data.  I think the best solution is going to be to rebuild libcurl from source and exclude the LDAP since I don't need it anyway.</p>

ContentLicense: CC BY-SA 4.0

Body:
I really hope someone can be of help to me because this problem has me totally stuck and frustrated.

Yesterday I installed a fresh and shiney new Windows 7 x64 onto a development box.

I got VS2008 installed, Tortoise SVN, did a checkout, compiled my currently project, all fine and dandy.

But when I go to run (either F5 in VS or just running the exe from the shell) I get a dialog box that looks like this:

(source: aliparr.net)

So I fiddle around and can't see an obvious problem. I bust out depends.exe, thinking maybe there's a dll missing, and I get this:

(source: aliparr.net)

So I play, finding different versions of gpsvc.dll and ishims.dll and putting them in with the .exe, No luck.

If I do a profile in depends (which follows the Output window of vs), I get this:

..
Loaded "c:\windows\syswow64\ADVAPI32.DLL" at address 0x75F20000 by thread 1.  Successfully hooked module.

Loaded "c:\windows\syswow64\LPK.DLL" at address 0x76B20000 by thread 1.  Successfully hooked module.

Loaded "c:\windows\syswow64\USP10.DLL" at address 0x761C0000 by thread 1.  Successfully hooked module.

Loaded "c:\windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_508ed732bcbc0e5a\MSVCR90.DLL" at address 0x70570000 by thread 1.  Successfully hooked module.

Loaded "c:\users\ali\desktop\repository\development\trunk\spree\bin\debug\OPENLDAP.DLL" at address 0x001E0000 by thread 1.  Successfully hooked module.

Exited "c:\users\ali\desktop\repository\development\trunk\spree\bin\debug\SPREE.EXE" (process 0x5D4) with code -1073741701 (0xC000007B) by thread 1.

So it seems openldap.dll is the last thing to get loaded before it all goes wrong. I require this dll because I use cURL within the application to do a little JSON communicating...

I've tried playing with moving files and trying differing dlls, but honestly I'm acting a little blind here. Can someone please help or point me in the right direction?

It should be noted these dlls and setup work fine in Windows Vista x64 and x86 - is this a Windows 7 thing?

Massive thanks in advance, I might still have some hair left after this is done.

Edit

I've now realised curl.exe dies in exactly the same way with openldap.dll - I guess some windows 7 issue?
Can you/does anyone have a curl without the dependency on openldap? Is there another lightweight C/C++ library out there that'll let me fetch a document over http and do the odd http POST ?

Thanks

ContentLicense: CC BY-SA 3.0


问:
Pandas DataFrame to Dict with (Row, Column) tuple as keys and int value at those location as values
I am trying to make the following DataFrame

```<code>       A      B      C      D      E
A      0   7324  11765   6937  10424
B   7324      0  17791   3532   5902
C  11765  17791      0  17184  20608
D   6937   3532  17184      0   6550
E  10424   5902  20608   6550      0
</code>```

to look something like this:

```<code>{
    ('A','A'): 0,
    ('A','B'): 7324,
    ('A','C'): 11765,
    .
    .
    .
    ('E','C'): 20608,
    ('E','D'): 6550,
    ('E','E'): 0,
}
</code>```

Simply put, the output is a dictionary with 2-tuples as keys of rows and columns and values at those locations as dictionary's values. Thank you!

Body:
I am trying to make the following DataFrame

       A      B      C      D      E
A      0   7324  11765   6937  10424
B   7324      0  17791   3532   5902
C  11765  17791      0  17184  20608
D   6937   3532  17184      0   6550
E  10424   5902  20608   6550      0

to look something like this:

{
    ('A','A'): 0,
    ('A','B'): 7324,
    ('A','C'): 11765,
    .
    .
    .
    ('E','C'): 20608,
    ('E','D'): 6550,
    ('E','E'): 0,
}

Simply put, the output is a dictionary with 2-tuples as keys of rows and columns and values at those locations as dictionary's values. Thank you!

Body:
stack and then convert to dict:

df.stack().to_dict()

{('A', 'A'): 0,
('A', 'B'): 7324,
 ('A', 'C'): 11765,
 ('A', 'D'): 6937,
 ('A', 'E'): 10424,
 ('B', 'A'): 7324,
 ('B', 'B'): 0,
 ('B', 'C'): 17791,
 ('B', 'D'): 3532,
 ('B', 'E'): 5902,
 ('C', 'A'): 11765,
 ('C', 'B'): 17791,
 ('C', 'C'): 0,
 ('C', 'D'): 17184,
 ('C', 'E'): 20608,
 ('D', 'A'): 6937,
 ('D', 'B'): 3532,
 ('D', 'C'): 17184,
 ('D', 'D'): 0,
 ('D', 'E'): 6550,
 ('E', 'A'): 10424,
 ('E', 'B'): 5902,
 ('E', 'C'): 20608,
 ('E', 'D'): 6550,
 ('E', 'E'): 0}


问:
Why threads doesn't accept this input?
I was doing a project that uses threads to sum some matrix but at the time of creating the threads and adding the params it always shows up the same error. Any ideas?

```<code>void sum(std::vector <double>& matrix, std::vector <double>& other) {
    for (auto i = 0; i < 15; i++) {
        matrix[i] += other[i];
    }
}

</code>```

here it is the operation that threads should do.

```<code>std::vector <double>* mat1 = new std::vector <double>[15];
std::vector <double>* mat2 = new std::vector <double>[15];
std::vector <std::thread*> threads;

for (int j = 0; j < 15; j++) {
    sum(mat1[j], mat2[j]);                                          //this works;
    threads.push_back(new std::thread(sum,mat1[j],mat2[j]));        //this dont why?;
}
</code>```

Thanks in advance

答:
To get it to compile, change:

```<code>std::thread(sum,mat1[j],mat2[j])
</code>```

to:

```<code>std::thread(sum, std::ref(mat1[j]), std::ref(mat2[j]))
</code>```

Example: https://godbolt.org/z/Ek-cnm

But there are multiple problems with your question and code besides just getting it to compile, please listen to what other have said in the comments.

Title: Why threads doesn't accept this input?

Body:
I was doing a project that uses threads to sum some matrix but at the time of creating the threads and adding the params it always shows up the same error. Any ideas?

void sum(std::vector <double>& matrix, std::vector <double>& other) {
    for (auto i = 0; i < 15; i++) {
        matrix[i] += other[i];
    }
}

here it is the operation that threads should do.

std::vector <double>* mat1 = new std::vector <double>[15];
std::vector <double>* mat2 = new std::vector <double>[15];
std::vector <std::thread*> threads;

for (int j = 0; j < 15; j++) {
    sum(mat1[j], mat2[j]);                                          //this works;
    threads.push_back(new std::thread(sum,mat1[j],mat2[j]));        //this dont why?;
}

Thanks in advance

Body:
To get it to compile, change:

std::thread(sum,mat1[j],mat2[j])

to:

std::thread(sum, std::ref(mat1[j]), std::ref(mat2[j]))

Example: https://godbolt.org/z/Ek-cnm

But there are multiple problems with your question and code besides just getting it to compile, please listen to what other have said in the comments.


问:
Accessibility: How to use multiple LABEL elements for one INPUT item correctly (via ARIA, etc.)?
I have a two-sided mobile menu drawer that relies on a hidden checkbox for switching/toggling between its two sides.

There are two LABEL elements, one on each side of the menu drawer. Each LABEL, via its FOR attribute, references the ID of the hidden INPUT checkbox. Clicking a displayed LABEL thus checks the INPUT checkbox and causes the menu to switch sides (via CSS). A distillation of the HTML is:

```<code><ul class=main-menu>
    <li>
        <input id=toggle-drawer type=checkbox title="hidden checkbox">
        <label for=toggle-drawer>See Sub Menu</label>
        <ul class=sub-menu>
            <li>
                <label for=toggle-drawer>See Main Menu</label>
            </li>
            <li>Sub-menu item 1</li>
            <li>Sub-menu item 2</li>
            <li>Sub-menu item 3</li>
        </ul>
    </li>
    <li>Main Menu item 1</li>
    <li>Main Menu item 2</li>
    <li>Main Menu item 3</li>
</ul>
</code>```

It is, in fact, perfectly valid HTML to have multiple labels that reference the same input item.

See https://www.w3.org/TR/html401/interact/forms.html#h-17.9.1 :

"More than one LABEL may be associated with the same control by
  creating multiple references via the for attribute."

However, the WebAIM WAVE (Web Accessibility Evaluation Tool) browser extension flags the two labels as an error, stating,

"A form control should have at most one associated label element. If
  more than one label element is associated to the control, assistive
  technology may not read the appropriate label."

As a remedy, it goes on to state:

"If multiple form labels are necessary, use aria-labelledby."

aria-labelledby seems not to apply to my case, as it would be put on an INPUT item that is referenced by a DIV, etc.

Is there an ARIA or similar mark-up method I can use to satisfy this accessibility audit? I do not wish to alter my HTML structure.

答:
Although it is perfectly valid HTML, having two labels will cause issues with NVDA and possibly other screen readers where it will only read one label.

This is why WAVE suggests you use aria-labelledby as that is designed to take multiple elements and can combine them (in the order you list them).

It is perfectly valid to use this on an input, also note that aria-labelledby will override any associated  elements using for="id"

One thing you could do is use the less often used aria-describedby to associate the second label and ensure that the reading order is correct.

In the example below it would read 'See Main Menu, See Sub Menu' as it will read the  first and then use the aria-describedby="toggle-drawer-label" to add additional information.

The only down side is that it may read the input information in between the  and the describedby label.

```<code><ul class=main-menu>
    <li>
        <input id="toggle-drawer" aria-describedby="toggle-drawer-label" type=checkbox title="hidden checkbox">
        <label id="toggle-drawer-label">See Sub Menu</label>
        <ul class=sub-menu>
            <li>
                <label for="toggle-drawer">See Main Menu</label>
            </li>
            <li>Sub-menu item 1</li>
            <li>Sub-menu item 2</li>
            <li>Sub-menu item 3</li>
        </ul>
    </li>
    <li>Main Menu item 1</li>
    <li>Main Menu item 2</li>
    <li>Main Menu item 3</li>
</ul>
</code>```

The recommended way

I would recommend simply using aria-labelledby="label1 label2" as that is the accepted method and will result in the most consistent results, obviously it means you need to add id attributes to both labels so that is the trade off.

Note that using aria-labelledby="label1 label2" and associating the fields with for="toggle-drawer" on both labels has the added benefit of correctly linking the labels so that you can click on either label and it will focus the <input>.

Body:
I have a two-sided mobile menu drawer that relies on a hidden checkbox for switching/toggling between its two sides.

There are two LABEL elements, one on each side of the menu drawer. Each LABEL, via its FOR attribute, references the ID of the hidden INPUT checkbox. Clicking a displayed LABEL thus checks the INPUT checkbox and causes the menu to switch sides (via CSS). A distillation of the HTML is:

        <input id=toggle-drawer type=checkbox title="hidden checkbox">
        See Sub Menu

                See Main Menu

Sub-menu item 1

Sub-menu item 2

Sub-menu item 3

Main Menu item 1

Main Menu item 2

Main Menu item 3

It is, in fact, perfectly valid HTML to have multiple labels that reference the same input item.

See https://www.w3.org/TR/html401/interact/forms.html#h-17.9.1 :

"More than one LABEL may be associated with the same control by
  creating multiple references via the for attribute."

However, the WebAIM WAVE (Web Accessibility Evaluation Tool) browser extension flags the two labels as an error, stating,

"A form control should have at most one associated label element. If
  more than one label element is associated to the control, assistive
  technology may not read the appropriate label."

As a remedy, it goes on to state:

"If multiple form labels are necessary, use aria-labelledby."

aria-labelledby seems not to apply to my case, as it would be put on an INPUT item that is referenced by a DIV, etc.

Is there an ARIA or similar mark-up method I can use to satisfy this accessibility audit? I do not wish to alter my HTML structure.

Body:
Although it is perfectly valid HTML, having two labels will cause issues with NVDA and possibly other screen readers where it will only read one label.

This is why WAVE suggests you use aria-labelledby as that is designed to take multiple elements and can combine them (in the order you list them).

It is perfectly valid to use this on an input, also note that aria-labelledby will override any associated <label> elements using for="id"

One thing you could do is use the less often used aria-describedby to associate the second label and ensure that the reading order is correct.

In the example below it would read 'See Main Menu, See Sub Menu' as it will read the <label  for="toggle-drawer"> first and then use the aria-describedby="toggle-drawer-label" to add additional information.

The only down side is that it may read the input information in between the <label> and the describedby label.

<ul class=main-menu>
    <li>
        <input id="toggle-drawer" aria-describedby="toggle-drawer-label" type=checkbox title="hidden checkbox">
        <label id="toggle-drawer-label">See Sub Menu</label>
        <ul class=sub-menu>
            <li>
                <label for="toggle-drawer">See Main Menu</label>
            </li>
            <li>Sub-menu item 1</li>
            <li>Sub-menu item 2</li>
            <li>Sub-menu item 3</li>
        </ul>
    </li>
    <li>Main Menu item 1</li>
    <li>Main Menu item 2</li>
    <li>Main Menu item 3</li>
</ul>

The recommended way

I would recommend simply using aria-labelledby="label1 label2" as that is the accepted method and will result in the most consistent results, obviously it means you need to add id attributes to both labels so that is the trade off.

Note that using aria-labelledby="label1 label2" and associating the fields with for="toggle-drawer" on both labels has the added benefit of correctly linking the labels so that you can click on either label and it will focus the <input>.


问:
How to login as admin without social login on remark42 commenting system
I choose remark42 as my commenting system, I only offer anonymous access to leave messages, this is my docker compose config file

```<code>version: '2'

services:
    remark42:
        image: umputun/remark42:latest
        container_name: "remark42"
        ports:
            - 8080:8080
        environment:
            - AUTH_GITHUB_CID=12345667890           # oauth2 client ID
            - AUTH_GITHUB_CSEC=abcdefg12345678      # oauth2 client secret
            - AUTH_EMAIL_ENABLE=true
            - AUTH_ANON=true
            - REMARK_URL=http://10.10.10.22
            - SITE=remark
            - SECRET=abcd
            - ADMIN_PASSWD=1234
        volumes:
            - ./var:/srv/var
</code>```

according to the Technical details, it mentioned:

Admin authentication (--admin-password set) allows to hit remark42 API
  without social login and with admin privileges. Adds basic-auth for
  username: admin, password: ${ADMIN_PASSWD}

I set my ADMIN_PASSWD to 1234, but can't find a way to login as admin, the only API to login required a social provider

GET /auth/{provider}/login?from=http://url&site=site_id&session=1

lots of apis need admin authorization

答:
According to the documentation (https://github.com/umputun/remark42#admin-users)  you just have to login using the way you want and put the userid in your docker-compose.yml file like this:</p>

```<code>environment:
        - ADMIN_SHARED_ID=github_ef0f706a79cc24b17bbbb374cd234a691a034128,github_dae9983158e9e5e127ef2b87a411ef13c891e9e5
</code>```

Body:
I choose remark42 as my commenting system, I only offer anonymous access to leave messages, this is my docker compose config file

version: '2'

services:
    remark42:
        image: umputun/remark42:latest
        container_name: "remark42"
        ports:
            - 8080:8080
        environment:
            - AUTH_GITHUB_CID=12345667890           # oauth2 client ID
            - AUTH_GITHUB_CSEC=abcdefg12345678      # oauth2 client secret
            - AUTH_EMAIL_ENABLE=true
            - AUTH_ANON=true
            - REMARK_URL=http://10.10.10.22
            - SITE=remark
            - SECRET=abcd
            - ADMIN_PASSWD=1234
        volumes:
            - ./var:/srv/var

according to the Technical details, it mentioned:

Admin authentication (--admin-password set) allows to hit remark42 API
  without social login and with admin privileges. Adds basic-auth for
  username: admin, password: ${ADMIN_PASSWD}

I set my ADMIN_PASSWD to 1234, but can't find a way to login as admin, the only API to login required a social provider

GET /auth/{provider}/login?from=http://url&site=site_id&session=1

lots of apis need admin authorization

Body:
According to the documentation (https://github.com/umputun/remark42#admin-users)  you just have to login using the way you want and put the userid in your docker-compose.yml file like this:

environment:
        - ADMIN_SHARED_ID=github_ef0f706a79cc24b17bbbb374cd234a691a034128,github_dae9983158e9e5e127ef2b87a411ef13c891e9e5


问:
this.array.ForEach dependencies not found with VueCLI
This is my code. I am using VueCLI.

The line that is creating a problem is this.slides.forEach(..

The error that I have is  dependencies not found (full error below).

When I install the dependencies missing npm install --save core-js/modules/es.array.for-each core-js/modules/web.dom-collections.for-each I have a es.array.for-each does not contain a package.json file Error

I then created the package.json file in the location described in the error. I run npm install but I have the same package.json not found error.

Any clue of what is wrong here?

<template>

        <slot>

        </slot>

</template>

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> ERROR  Failed to compile with 2 errors                                                                                10:39:10 AM
These dependencies were not found:

* core-js/modules/es.array.for-each in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Carousel/Carousel.vue?vue&type=script&lang=js&
* core-js/modules/web.dom-collections.for-each in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Carousel/Carousel.vue?vue&type=script&lang=js&

To install them, you can run: npm install --save core-js/modules/es.array.for-each core-js/modules/web.dom-collections.for-each</code>```

npm ERR! code ENOLOCAL
npm ERR! Could not install from "core-js\modules\es.array.for-each" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     User\...\AppData\Roaming\npm-cache\_logs\2020-02-15T15_49_17_958Z-debug.log```

答:
Found the answer.

npm install --save-dev @vue/cli @vue/cli-service-global core-js@3

did the trick! I think there are some issues with core-js@2

Body:
This is my code. I am using VueCLI.

The line that is creating a problem is this.slides.forEach(..

The error that I have is  dependencies not found (full error below).

When I install the dependencies missing npm install --save core-js/modules/es.array.for-each core-js/modules/web.dom-collections.for-each I have a es.array.for-each does not contain a package.json file Error

I then created the package.json file in the location described in the error. I run npm install but I have the same package.json not found error.

Any clue of what is wrong here?

<template>

        <slot>

        </slot>

</template>

 ERROR  Failed to compile with 2 errors                                                                                10:39:10 AM
These dependencies were not found:

* core-js/modules/es.array.for-each in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Carousel/Carousel.vue?vue&type=script&lang=js&
* core-js/modules/web.dom-collections.for-each in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/Carousel/Carousel.vue?vue&type=script&lang=js&

To install them, you can run: npm install --save core-js/modules/es.array.for-each core-js/modules/web.dom-collections.for-each

npm ERR! code ENOLOCAL
npm ERR! Could not install from "core-js\modules\es.array.for-each" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     User\...\AppData\Roaming\npm-cache\_logs\2020-02-15T15_49_17_958Z-debug.log


问:
Clicking button to send info in text box not working
I try to make this: static private long number = (long)Math.Floor(GlobalRandom.NextDouble * 9_000_000_000L) + 1_000_000_000L;   to be returned with this:

```<code>public string MyValtwo
        {
            get { return myValtwo; }
            set { myValtwo = value; }
        }
</code>```

and finally to be sent to this:

```<code>private void button1_Click(object sender, EventArgs e)
        {
            MyValtwo = textBox2.Text;
        }
</code>```

I tried converting: public string MyValtwo = Convert.ToString(number); but nothing returns or the long (number) can't be converted into string.

The main idea is to be generated a number and automatically putted in form 1 text box

答:
You dont need MyValtwo. Change code to below and it will work:

```<code>private void button1_Click(object sender, EventArgs e)
{
    textBox2.Text = number.ToString();
}
</code>```

In case you want to store the value of number as text in MyValtwo then you can add below line in button1_Click function.

```<code>MyValtwo = number.ToString();
</code>```

Body:
I try to make this: static private long number = (long)Math.Floor(GlobalRandom.NextDouble * 9_000_000_000L) + 1_000_000_000L;   to be returned with this:

public string MyValtwo
        {
            get { return myValtwo; }
            set { myValtwo = value; }
        }

and finally to be sent to this:

private void button1_Click(object sender, EventArgs e)
        {
            MyValtwo = textBox2.Text;
        }

I tried converting: public string MyValtwo = Convert.ToString(number); but nothing returns or the long (number) can't be converted into string.

The main idea is to be generated a number and automatically putted in form 1 text box

Body:
You dont need MyValtwo. Change code to below and it will work:

private void button1_Click(object sender, EventArgs e)
{
    textBox2.Text = number.ToString();
}

In case you want to store the value of number as text in MyValtwo then you can add below line in button1_Click function.

MyValtwo = number.ToString();


问:
JavaScript passing argument problem
I have following code

```<code>for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }
</code>```

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

答:
Use a closure to close over the value of i:

```<code>$(el).click( (function(i_){
  return function() {
     that.slider_fn.mini.show(i_, j);
     return false;
  };
})(i));
</code>```

Beforehand, your function was referencing the variable called i, now on each iteration you create a new function that references i_, and this variable is unique to each function and references the value of i when the function was created.

Title: JavaScript passing argument problem

Body:
I have following code

for (var i = 0; i < that.$el.mini.length; i++) {
            var pag = that.$el.mini[i].pagination;
            // Mini-Slider Pagination
            $('li', pag).each( function(j, el) {
                $(el).click( function() {
                    /*
                     * Toggle Mini-Slide
                     */
                    that.slider_fn.mini.show(i, j);
                    return false;
                });
            });
        }

So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.

The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.

How can I make JavaScript (or a function) to memorize that particular number?

Body:
Use a closure to close over the value of i:

$(el).click( (function(i_){
  return function() {
     that.slider_fn.mini.show(i_, j);
     return false;
  };
})(i));

Beforehand, your function was referencing the variable called i, now on each iteration you create a new function that references i_, and this variable is unique to each function and references the value of i when the function was created.


问:
Vue.js - JSON API data doesn't appear on click event
I'm having difficulties with a VueJS project of mine.

I'm trying to get a click event to show additional user data from a JSON API.

The console recognizes the click event, but for some odd reason, none of the additional data that I'm trying to toggle, appears.

I'm suspecting that the method is at fault, or maybe perhaps that the click event isn't configured properly, because the data is there, but nothing shows -- no errors in the console either.

Any suggestions would be greatly appreciated!

<template>

                        Name
                        User name
                        Email

                    {{ user.name }}
                    {{ user.username }}
                    {{ user.email }}

{{ userInfo.name }}

{{ userInfo.username }}

{{ userInfo.adress.street }}

{{ userInfo.address.suite }}

{{ userInfo.address.city }}

{{ userInfo.address.zipcode }}

</template>

```

答:
I was able to reproduce the example without any issue. Maybe it was just a typo ?

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    users: [],
    userInfo: null
  },
  methods: {
    showInfo(userId) {
      for (const user of this.users) {
        if (user.id == userId) {
          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },
  created() {
    // Fetch JSON data
    fetch('https://jsonplaceholder.typicode.com/users/')
      .then(response => response.json())
      .then(json => {
        this.users = json
      })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.middleSection {
  height: 87vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5vh !important;
}</code>```

                Name
                User name
                Email

                {{ user.name }}
                {{ user.username }}
                {{ user.email }}

{{ userInfo.name }}

{{ userInfo.username }}

{{ userInfo.adress.street }}

{{ userInfo.address.suite }}

{{ userInfo.address.city }}

{{ userInfo.address.zipcode }}

```

Body:
I was able to reproduce the example without any issue. Maybe it was just a typo ?

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    users: [],
    userInfo: null
  },
  methods: {
    showInfo(userId) {
      for (const user of this.users) {
        if (user.id == userId) {
          this.userInfo = user
          console.log(this.userInfo)
        }
      }
    }
  },
  created() {
    // Fetch JSON data
    fetch('https://jsonplaceholder.typicode.com/users/')
      .then(response => response.json())
      .then(json => {
        this.users = json
      })
  }
})

.col-12 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.middleSection {
  height: 87vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 5vh !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <section class="middleSection">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <table class="table table-dark">
            <thead>
              <tr>
                <th>Name</th>
                <th>User name</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody v-for="(user, index) in users" :key="index">
              <tr data-toggle="collapse" @click="showInfo(userInfo)">
                <td>{{ user.name }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
              </tr>
            </tbody>
          </table>

          <div v-if="userInfo" class="card card-body">
            <div>{{ userInfo.name }}</div>
            <div>{{ userInfo.username }}</div>
            <div>{{ userInfo.adress.street }}</div>
            <div>{{ userInfo.address.suite }}</div>
            <div>{{ userInfo.address.city }}</div>
            <div>{{ userInfo.address.zipcode }}</div>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>


问:
using poly( function within training model in caret package resulting in dataframe error
Here's the code that I am running:

```<code>library(caret)
library(ISLR)
data('Auto')
cverror <- c()
for(i in 1:5){
  train_control <- trainControl(method='LOOCV')
  models <- train(mpg~poly(horsepower,i), data = Auto, trControl=train_control, method='glm')
  cverror[i] <- (models$results$RMSE)^2
}

cverror
</code>```

What I'm trying to accomplish is to calculate the MSE (mean square error) for different polynomial levels using a loop so I don't have to code line by line. The error message I receive is:

```<code> Error in `[.data.frame`(data, , all.vars(Terms), drop = FALSE) :
  undefined columns selected
</code>```

Why am I receiving this error? My study mates said that this code runs fine on their machine, but it doesn't work on my personal or work computers. I have the latest RStudio and R versions installed with all packages up to date.

The following line of code works just fine:

```<code>train(mpg~poly(horsepower,2), data = Auto, trControl=train_control, method='glm')
</code>```

This is in relation to the tutorial found on page 192/193 of the ISLR text (which I'm expanding upon).

答:
I had a similar issue. Have you tried using the following?</p>

```<code>models <- train(x = poly(Auto$horsepower,i), y = Auto$mpg, data = Auto, trControl=train_control, method='glm')
</code>```

<p>(I have not tested this specific piece of code.) </p>

Body:
Here's the code that I am running:

library(caret)
library(ISLR)
data('Auto')
cverror <- c()
for(i in 1:5){
  train_control <- trainControl(method='LOOCV')
  models <- train(mpg~poly(horsepower,i), data = Auto, trControl=train_control, method='glm')
  cverror[i] <- (models$results$RMSE)^2
}

cverror

What I'm trying to accomplish is to calculate the MSE (mean square error) for different polynomial levels using a loop so I don't have to code line by line. The error message I receive is:

 Error in `[.data.frame`(data, , all.vars(Terms), drop = FALSE) :
  undefined columns selected

Why am I receiving this error? My study mates said that this code runs fine on their machine, but it doesn't work on my personal or work computers. I have the latest RStudio and R versions installed with all packages up to date.

The following line of code works just fine:

train(mpg~poly(horsepower,2), data = Auto, trControl=train_control, method='glm')

This is in relation to the tutorial found on page 192/193 of the ISLR text (which I'm expanding upon).

Body:
I had a similar issue. Have you tried using the following?

models <- train(x = poly(Auto$horsepower,i), y = Auto$mpg, data = Auto, trControl=train_control, method='glm')

(I have not tested this specific piece of code.)


问:
Saml setup with Keycloak as Identity Broker and Okta as Identity provider not working
I am using keycloak (version 8.0.1) as an identity broker in my application. I've setup the saml integration between keycloak/okta as specified in this blog, https://ultimatesecurity.pro/post/okta-saml/

I also have a sample application that I am using to test this integration which is from this blog, https://scalac.io/user-authentication-keycloak-1

I am running into an issue when okta redirects back to keycloak. The response from okta is successful however on receiving the response keycloak looks at the KC_RESTART cookie and tries to find a kid in the JWT which is encoded in that cookie but does not find a match and throws the following exception,

```<code>19:26:00,581 DEBUG [org.keycloak.jose.jws.DefaultTokenManager] (default task-1) Failed to decode token: org.keycloak.common.VerificationException: Key not found
    at org.keycloak.crypto.ServerMacSignatureVerifierContext.getKey(ServerMacSignatureVerifierContext.java:31)
    at org.keycloak.crypto.ServerMacSignatureVerifierContext.<init>(ServerMacSignatureVerifierContext.java:25)
    at org.keycloak.crypto.MacSecretSignatureProvider.verifier(MacSecretSignatureProvider.java:39)
    at org.keycloak.jose.jws.DefaultTokenManager.decode(DefaultTokenManager.java:94)
    at org.keycloak.protocol.RestartLoginCookie.restartSession(RestartLoginCookie.java:146)
    at org.keycloak.services.resources.SessionCodeChecks.restartAuthenticationSessionFromCookie(SessionCodeChecks.java:376)
    at org.keycloak.services.resources.SessionCodeChecks.initialVerifyAuthSession(SessionCodeChecks.java:197)
    at org.keycloak.services.resources.SessionCodeChecks.initialVerify(SessionCodeChecks.java:204)
    at org.keycloak.services.resources.IdentityBrokerService.parseSessionCode(IdentityBrokerService.java:1027)
    at org.keycloak.services.resources.IdentityBrokerService.parseEncodedSessionCode(IdentityBrokerService.java:1016)
    at org.keycloak.services.resources.IdentityBrokerService.authenticated(IdentityBrokerService.java:501)
    at org.keycloak.broker.saml.SAMLEndpoint$Binding.handleLoginResponse(SAMLEndpoint.java:485)
    at org.keycloak.broker.saml.SAMLEndpoint$Binding.handleSamlResponse(SAMLEndpoint.java:524)
</code>```

I have also enabled TRACE logging on keycloak and I see the following error message being printed in the logs,

Before exception,

```<code>19:32:19,019 TRACE [org.keycloak.keys.DefaultKeyManager] (default task-1) Failed to find public key: realm=MyDemo kid=5a148511-021f-477d-a716-2f0f2d425d12 algorithm=HS256 use=SIG
</code>```

After exception

```<code>19:32:19,021 TRACE [org.keycloak.events] (default task-1) type=IDENTITY_PROVIDER_LOGIN_ERROR, realmId=MyDemo, clientId=null, userId=null, ipAddress=127.0.0.1, error=invalid_code, requestUri=http://localhost:8080/auth/realms/MyDemo/broker/samlokta/endpoint, cookies=[io=URgKM5wjPjr8WQdlAAAA, JSESSIONID=57782504027A376E7FD18A7F061B7225, KC_RESTART=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI1YTE0ODUxMS0wMjFmLTQ3N2QtYTcxNi0yZjBmMmQ0MjVkMTIifQ.eyJjaWQiOiJhY2NvdW50IiwicHR5Ijoib3BlbmlkLWNvbm5lY3QiLCJydXJpIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL015RGVtby9hY2NvdW50L2xvZ2luLXJlZGlyZWN0IiwiYWN0IjoiQVVUSEVOVElDQVRFIiwibm90ZXMiOnsic2NvcGUiOiJvcGVuaWQiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvTXlEZW1vIiwicmVzcG9uc2VfdHlwZSI6ImNvZGUiLCJjb2RlX2NoYWxsZW5nZV9tZXRob2QiOiJwbGFpbiIsInJlZGlyZWN0X3VyaSI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MC9hdXRoL3JlYWxtcy9NeURlbW8vYWNjb3VudC9sb2dpbi1yZWRpcmVjdCIsInN0YXRlIjoiMC9mMjBkNTU4ZS00M2I0LTRkMjEtOTFlYy0xOGY0YmQzYmE0OWMifX0.Y0zN-c33soimR_JhvTex-nRKL0rZKquOhRtfdofrF-A, AUTH_SESSION_ID=e549d547-0bd0-413e-986c-361bb35ead4c.moizs-mbp, OAuth_Token_Request_State=6d9150e4-fb5f-45c9-bda5-3a042d964e4c]
</code>```

Looking at the code in DefaultKeyManager.java it appears that the kid which is in the KC_RESTART cookie could not be found in the KeyProvider.

I need help figuring out why not, I'm not sure what step I am missing. Any help would be appreciated.

```<code>        for (KeyProvider p : getProviders(realm)) {
            for (KeyWrapper key : p.getKeys()) {
                if (key.getKid().equals(kid) && key.getStatus().isEnabled() && matches(key, use, algorithm)) {
                    if (logger.isTraceEnabled()) {
                        logger.tracev("Found key: realm={0} kid={1} algorithm={2} use={3}", realm.getName(), key.getKid(), algorithm, use.name());
                    }

                    return key;
                }
            }
        }

</code>```

答:
As it turns out this was a configuration issue. So, basically I am running keycloak on localhost for testing. So I had started it up on localhost and configured the IDP on keycloak. After I configured the IDP I exported the metadata and imported it into Okta. At this point the Audience URI and the Response URI etc. got imported with localhost as the host name. After fiddling around I changed both the URIs to use 127.0.0.1 as host name instead of localhost and that fixed the issue.

I got a clue that this might be a problem when I tried integrating with PingId. PingId rejected the AuthenticationRequest because the entityId - derived from the URI was not matching. I'm not quite sure what the issue with keycloak is but I wanted to post this answer for others who may be stuck with a similar problem.

Body:
I am using keycloak (version 8.0.1) as an identity broker in my application. I've setup the saml integration between keycloak/okta as specified in this blog, https://ultimatesecurity.pro/post/okta-saml/

I also have a sample application that I am using to test this integration which is from this blog, https://scalac.io/user-authentication-keycloak-1

I am running into an issue when okta redirects back to keycloak. The response from okta is successful however on receiving the response keycloak looks at the KC_RESTART cookie and tries to find a kid in the JWT which is encoded in that cookie but does not find a match and throws the following exception,

19:26:00,581 DEBUG [org.keycloak.jose.jws.DefaultTokenManager] (default task-1) Failed to decode token: org.keycloak.common.VerificationException: Key not found
    at org.keycloak.crypto.ServerMacSignatureVerifierContext.getKey(ServerMacSignatureVerifierContext.java:31)
    at org.keycloak.crypto.ServerMacSignatureVerifierContext.<init>(ServerMacSignatureVerifierContext.java:25)
    at org.keycloak.crypto.MacSecretSignatureProvider.verifier(MacSecretSignatureProvider.java:39)
    at org.keycloak.jose.jws.DefaultTokenManager.decode(DefaultTokenManager.java:94)
    at org.keycloak.protocol.RestartLoginCookie.restartSession(RestartLoginCookie.java:146)
    at org.keycloak.services.resources.SessionCodeChecks.restartAuthenticationSessionFromCookie(SessionCodeChecks.java:376)
    at org.keycloak.services.resources.SessionCodeChecks.initialVerifyAuthSession(SessionCodeChecks.java:197)
    at org.keycloak.services.resources.SessionCodeChecks.initialVerify(SessionCodeChecks.java:204)
    at org.keycloak.services.resources.IdentityBrokerService.parseSessionCode(IdentityBrokerService.java:1027)
    at org.keycloak.services.resources.IdentityBrokerService.parseEncodedSessionCode(IdentityBrokerService.java:1016)
    at org.keycloak.services.resources.IdentityBrokerService.authenticated(IdentityBrokerService.java:501)
    at org.keycloak.broker.saml.SAMLEndpoint$Binding.handleLoginResponse(SAMLEndpoint.java:485)
    at org.keycloak.broker.saml.SAMLEndpoint$Binding.handleSamlResponse(SAMLEndpoint.java:524)

I have also enabled TRACE logging on keycloak and I see the following error message being printed in the logs,

Before exception,

19:32:19,019 TRACE [org.keycloak.keys.DefaultKeyManager] (default task-1) Failed to find public key: realm=MyDemo kid=5a148511-021f-477d-a716-2f0f2d425d12 algorithm=HS256 use=SIG

After exception

19:32:19,021 TRACE [org.keycloak.events] (default task-1) type=IDENTITY_PROVIDER_LOGIN_ERROR, realmId=MyDemo, clientId=null, userId=null, ipAddress=127.0.0.1, error=invalid_code, requestUri=http://localhost:8080/auth/realms/MyDemo/broker/samlokta/endpoint, cookies=[io=URgKM5wjPjr8WQdlAAAA, JSESSIONID=57782504027A376E7FD18A7F061B7225, KC_RESTART=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI1YTE0ODUxMS0wMjFmLTQ3N2QtYTcxNi0yZjBmMmQ0MjVkMTIifQ.eyJjaWQiOiJhY2NvdW50IiwicHR5Ijoib3BlbmlkLWNvbm5lY3QiLCJydXJpIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL015RGVtby9hY2NvdW50L2xvZ2luLXJlZGlyZWN0IiwiYWN0IjoiQVVUSEVOVElDQVRFIiwibm90ZXMiOnsic2NvcGUiOiJvcGVuaWQiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvTXlEZW1vIiwicmVzcG9uc2VfdHlwZSI6ImNvZGUiLCJjb2RlX2NoYWxsZW5nZV9tZXRob2QiOiJwbGFpbiIsInJlZGlyZWN0X3VyaSI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MC9hdXRoL3JlYWxtcy9NeURlbW8vYWNjb3VudC9sb2dpbi1yZWRpcmVjdCIsInN0YXRlIjoiMC9mMjBkNTU4ZS00M2I0LTRkMjEtOTFlYy0xOGY0YmQzYmE0OWMifX0.Y0zN-c33soimR_JhvTex-nRKL0rZKquOhRtfdofrF-A, AUTH_SESSION_ID=e549d547-0bd0-413e-986c-361bb35ead4c.moizs-mbp, OAuth_Token_Request_State=6d9150e4-fb5f-45c9-bda5-3a042d964e4c]

Looking at the code in DefaultKeyManager.java it appears that the kid which is in the KC_RESTART cookie could not be found in the KeyProvider.

I need help figuring out why not, I'm not sure what step I am missing. Any help would be appreciated.

        for (KeyProvider p : getProviders(realm)) {
            for (KeyWrapper key : p.getKeys()) {
                if (key.getKid().equals(kid) && key.getStatus().isEnabled() && matches(key, use, algorithm)) {
                    if (logger.isTraceEnabled()) {
                        logger.tracev("Found key: realm={0} kid={1} algorithm={2} use={3}", realm.getName(), key.getKid(), algorithm, use.name());
                    }

                    return key;
                }
            }
        }


问:
How can I display the entire web page in fullscreen and disable f11 and ESC buttons?
I'm doing an online quiz with PHP, HTML and Javascript. When the user clicks the "Start Quiz" button, the page must be shown in fullscreen, and the f11 and ESC buttons must be disabled to prevent users from exiting the fullscreen mode. How can I do that?
Here is the code for the fullscreen mode:</p>

```<code>var elem = document.documentElement;
                function openFullscreen() {
                if (elem.requestFullscreen) {
                    elem.requestFullscreen();
                } else if (elem.mozRequestFullScreen) { /* Firefox */
                    elem.mozRequestFullScreen();
                } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
                    elem.webkitRequestFullscreen();
                } else if (elem.msRequestFullscreen) { /* IE/Edge */
                    elem.msRequestFullscreen();
                }
            }

            function closeFullscreen() {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }
</code>```

答:
In a regular browser setting this is usually not possible due to the security implications.

You can use things like electron though: With electron you can create an application with "kiosk" mode, which basically does that.

Body:
I'm doing an online quiz with PHP, HTML and Javascript. When the user clicks the "Start Quiz" button, the page must be shown in fullscreen, and the f11 and ESC buttons must be disabled to prevent users from exiting the fullscreen mode. How can I do that?
Here is the code for the fullscreen mode:

var elem = document.documentElement;
                function openFullscreen() {
                if (elem.requestFullscreen) {
                    elem.requestFullscreen();
                } else if (elem.mozRequestFullScreen) { /* Firefox */
                    elem.mozRequestFullScreen();
                } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
                    elem.webkitRequestFullscreen();
                } else if (elem.msRequestFullscreen) { /* IE/Edge */
                    elem.msRequestFullscreen();
                }
            }

            function closeFullscreen() {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }


问:
Replace the values of all duplicate rows in Python Pandas
I have a data frame df where some rows are duplicates with respect to a subset of columns:

```<code>df

A       B        C       D
1       Blue     Green   4
2       Red      Green   6
3       Red      Green   2
4       Blue     Pink    6
5       Blue     Orange  9
6       Blue     Orange  8
7       Blue     Red     8
8       Red      Orange  9
</code>```

I would like to replace values for duplicate rows with respect to B and C and replace the whole row by 'ERR', ideally producing:

```<code>A       B        C       D
1       Blue     Green   4
ERR     ERR      ERR     ERR
ERR     ERR      ERR     ERR
4       Blue     Pink    6
ERR     ERR      ERR     ERR
ERR     ERR      ERR     ERR
7       Blue     Red     8
8       Red      Orange  9
</code>```

So brief: If there are duplicate rows for columns B and C, all the values in those rows should be set to 'ERR' (not only the duplicate ones).

Solved! -> thanks to @anky_91

```<code>df = pd.DataFrame({"A": [1,2,3,4,5,6,7,8], "B": ['Blue', 'Red', 'Red', 'Blue', 'Blue', 'Blue', 'Blue', 'Red'], "C": ['Green', 'Green', 'Green', 'Pink', 'Orange', 'Orange', 'Red', 'Orange'], "D": [4,6,2,6,9,8,8,9]})

df = df.mask(df.duplicated(['B','C'], keep=False), 'ERR')
print(df)
</code>```

答:
You can use df.mask here with df.duplicated

```<code>df.mask(df.duplicated(['B','C'],keep=False),'ERR')
</code>```

```<code>     A     B       C    D
0    1  Blue   Green    4
1  ERR   ERR     ERR  ERR
2  ERR   ERR     ERR  ERR
3    4  Blue    Pink    6
4  ERR   ERR     ERR  ERR
5  ERR   ERR     ERR  ERR
6    7  Blue     Red    8
7    8   Red  Orange    9
</code>```

Body:
I have a data frame df where some rows are duplicates with respect to a subset of columns:

df

A       B        C       D
1       Blue     Green   4
2       Red      Green   6
3       Red      Green   2
4       Blue     Pink    6
5       Blue     Orange  9
6       Blue     Orange  8
7       Blue     Red     8
8       Red      Orange  9

I would like to replace values for duplicate rows with respect to B and C and replace the whole row by 'ERR', ideally producing:

A       B        C       D
1       Blue     Green   4
ERR     ERR      ERR     ERR
ERR     ERR      ERR     ERR
4       Blue     Pink    6
ERR     ERR      ERR     ERR
ERR     ERR      ERR     ERR
7       Blue     Red     8
8       Red      Orange  9

So brief: If there are duplicate rows for columns B and C, all the values in those rows should be set to 'ERR' (not only the duplicate ones).

Solved! -> thanks to @anky_91

df = pd.DataFrame({"A": [1,2,3,4,5,6,7,8], "B": ['Blue', 'Red', 'Red', 'Blue', 'Blue', 'Blue', 'Blue', 'Red'], "C": ['Green', 'Green', 'Green', 'Pink', 'Orange', 'Orange', 'Red', 'Orange'], "D": [4,6,2,6,9,8,8,9]})

df = df.mask(df.duplicated(['B','C'], keep=False), 'ERR')
print(df)

Body:
You can use df.mask here with df.duplicated

df.mask(df.duplicated(['B','C'],keep=False),'ERR')

     A     B       C    D
0    1  Blue   Green    4
1  ERR   ERR     ERR  ERR
2  ERR   ERR     ERR  ERR
3    4  Blue    Pink    6
4  ERR   ERR     ERR  ERR
5  ERR   ERR     ERR  ERR
6    7  Blue     Red    8
7    8   Red  Orange    9


问:
Installing Docker + tensorflow on Windows 10
I tried to install tensorflow and docker as followed link https://www.tensorflow.org/install/docker

I downloaded tensorflow image from the tensowflow Hub into the docker and then I tried to test tensorflow python script.
Then I got error message below.
I think it's related with GPU but I just downloaded tensorflow/tensorflow:last and I don't need GPU version.
I thought if I used docker + tensorflow I wouldn't get any error.
Is there anybody who can tell me what's wrong with this..

```<code>2020-02-15 08:24:32.759681: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory
2020-02-15 08:24:32.759786: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory
2020-02-15 08:24:32.759798: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
</code>```

答: As https://www.tensorflow.org/install/docker says, "nvidia-container-runtime is only available for Linux". As for now, there's no way to provide GPU to docker containers if you're using Windows as a host system.</p>

Body:
I tried to install tensorflow and docker as followed link https://www.tensorflow.org/install/docker

I downloaded tensorflow image from the tensowflow Hub into the docker and then I tried to test tensorflow python script.
Then I got error message below.
I think it's related with GPU but I just downloaded tensorflow/tensorflow:last and I don't need GPU version.
I thought if I used docker + tensorflow I wouldn't get any error.
Is there anybody who can tell me what's wrong with this..

2020-02-15 08:24:32.759681: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory
2020-02-15 08:24:32.759786: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory
2020-02-15 08:24:32.759798: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.


问:
Mapstruct, mapping to nested objects from sevral input parameters
Given a set of five objects:

```<code>KeyDto{String id}

ValueDto{String name, String value, String description}

Key{String id, String name}

Value{String value, String description}

Target{Key key, Value value}
</code>```

I would like to create a mapper with two parameters:

```<code> Target dtosToTarget(KeyDto keyDto, ValueDto valueDto);
</code>```

However, just defining helper methods for Key and Value seems not to be enough:

```<code>@Mapping(source = "keyDto.id", target = "id")
@Mapping(source = "valueDto.name", target = "name")
Key keyDtoAndValueDtoToKey(KeyDto keyDto, ValueDto valueDto);

Value valueDtoToValue(ValueDto valueDto);
</code>```

This gives an error on the actual dtosToTarget method:

Error:(17, 19) java: Can't map property "java.lang.String value" to "mapping.Value value". Consider to declare/implement a mapping method: "mapping.Value map(java.lang.String value)".

The only solution I could think of - is defining custom java expressions to call necessary methods, like

```<code>@Mapping(target = "key", expression = "java(keyDtoAndValueDtoToKey(keyDto, valueDto))")
@Mapping(target = "value", expression = "java(valueDtoToValue(valueDto))")
</code>```

Is there a cleaner approach?

答:
The error you are seeing is because by default MapStruct will try to map valueDto.value into Target.value which is String to Value.

However, you can configure this like this:

```<code>@Mapper
public MyMapper {

    @Mapping( target = "key.id", source = "keyDto.id")
    @Mapping( target = "key.name", source = "valueDto.name")
    @Mapping( target = "value", source = "valueDto")
    Target dtosToTarget(KeyDto keyDto, ValueDto valueDto);

    Value valueDtoToValue(ValueDto valueDto);
}
</code>```

Body:
Given a set of five objects:

KeyDto{String id}

ValueDto{String name, String value, String description}

Key{String id, String name}

Value{String value, String description}

Target{Key key, Value value}

I would like to create a mapper with two parameters:

 Target dtosToTarget(KeyDto keyDto, ValueDto valueDto);

However, just defining helper methods for Key and Value seems not to be enough:

@Mapping(source = "keyDto.id", target = "id")
@Mapping(source = "valueDto.name", target = "name")
Key keyDtoAndValueDtoToKey(KeyDto keyDto, ValueDto valueDto);

Value valueDtoToValue(ValueDto valueDto);

This gives an error on the actual dtosToTarget method:

Error:(17, 19) java: Can't map property "java.lang.String value" to "mapping.Value value". Consider to declare/implement a mapping method: "mapping.Value map(java.lang.String value)".

The only solution I could think of - is defining custom java expressions to call necessary methods, like

@Mapping(target = "key", expression = "java(keyDtoAndValueDtoToKey(keyDto, valueDto))")
@Mapping(target = "value", expression = "java(valueDtoToValue(valueDto))")

Is there a cleaner approach?

Body:
The error you are seeing is because by default MapStruct will try to map valueDto.value into Target.value which is String to Value.

However, you can configure this like this:

@Mapper
public MyMapper {

    @Mapping( target = "key.id", source = "keyDto.id")
    @Mapping( target = "key.name", source = "valueDto.name")
    @Mapping( target = "value", source = "valueDto")
    Target dtosToTarget(KeyDto keyDto, ValueDto valueDto);

    Value valueDtoToValue(ValueDto valueDto);
}


问:
How to make kbhit() work in the Spyder environment
Has anyone come across a way to emulate kbhit() in the Spyder environment on Windows? Somehow the development environment gets between the Python program and the keyboard, so any simple way of doing it (i.e. msvcrt.kbhit()) does not work.

答:
Set this configuration in Spyder:

Run > Run Configuration Per File > Execute In An External System Terminal

In my experience "msvcrt.kbhit" only works in CMD.


问:
How to create a new list item with FLOWR and XQuery?
I'm looking to select non-numerical data from an XML file towards shredding it into database columns, or at least an xmltable-like structure.  This FLWOR gives a somewhat useful result:

```<code>xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

<ul>
{
for $foo  in db:open("foo")
return <li>{$foo//text()[not(matches(., '[0-9]'))]}</li>

}
</ul>
</code>```

However, it outputs all results into a single li tag, like:

 a b c d

Preferred output would be of the form:

a

b

Most likely the data is problematic in some way, because a slightly different FLOWR:

```<code>xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

for $foo in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]
</code>```

certainly outputs each non-numerical string on a new line.  How can I output this into a list?

An excerpt of the data:

```<code> <table:table-column table:style-name="co1" table:default-cell-style-name="ce17"/>
  <table:table-row table:style-name="ro1">
    <table:table-cell table:style-name="ce15" office:value-type="string" calcext:value-type="string">
      <text:p>John Smith</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell table:style-name="ce16" office:value-type="string" calcext:value-type="string">
      <text:p>(123) 456-7890</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell office:value-type="string" calcext:value-type="string">
      <text:p>123 Main Street</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell office:value-type="string" calcext:value-type="string">
      <text:p>Anywhere, ZZ 12345-6789</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro1">
    <table:table-cell table:style-name="ce15" office:value-type="string" calcext:value-type="string">
      <text:p>Jane Doe</text:p>
    </table:table-cell>
  </table:table-row>
  <table:table-row table:style-name="ro2">
    <table:table-cell table:style-name="ce16" office:value-type="string" calcext:value-type="string">
      <text:p>(234) 567-8901</text:p>
</code>```

答:
If you want an li for each of the text(), then alter what you are iterating over. Instead of selecting the text() inside of the for loop, iterate over each of the text():

```<code>xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

<ul>
{
for $foo  in db:open("foo")//text()[not(matches(., '[0-9]'))]
return <li>{$foo}</li>
}
</ul>
</code>```

Body:
I'm looking to select non-numerical data from an XML file towards shredding it into database columns, or at least an xmltable-like structure.  This FLWOR gives a somewhat useful result:

xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

{
for $foo  in db:open("foo")
return
{$foo//text()[not(matches(., '[0-9]'))]}

}

However, it outputs all results into a single li tag, like:

 a b c d

Preferred output would be of the form:

a

b

Most likely the data is problematic in some way, because a slightly different FLOWR:

xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

for $foo in db:open("foo")
return $foo//text()[not(matches(., '[0-9]'))]

certainly outputs each non-numerical string on a new line.  How can I output this into a list?

An excerpt of the data:

      <text:p>John Smith</text:p>

      <text:p>(123) 456-7890</text:p>

      <text:p>123 Main Street</text:p>

      <text:p>Anywhere, ZZ 12345-6789</text:p>

      <text:p>Jane Doe</text:p>

      <text:p>(234) 567-8901</text:p>

Body:
If you want an li for each of the text(), then alter what you are iterating over. Instead of selecting the text() inside of the for loop, iterate over each of the text():

xquery version "3.0";
declare namespace office="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

<ul>
{
for $foo  in db:open("foo")//text()[not(matches(., '[0-9]'))]
return <li>{$foo}</li>
}
</ul>


问:
Iterating through dictionary values in python
I have 1000+ text files, each with two columns, one being dates, the other stock prices (at respective date). I have uploaded them and cast them into a dictionary using the following code:

```<code>filelist = os.listdir(r'insertfilepath')
filepath = r'insertfilepath'

dic1 = {}

for file in filelist:
    df = pd.read_csv(filepath + file,sep='\t')
    dic1[file]= df
</code>```

However, when I try to change the column names for each one using the following code:

```<code>for value in dic1:
    for df in value:
        df.rename(columns={df.columns[0]:'Dates',df.columns[1]:'Prices'},inplace=True)
</code>```

I get the following error: 'str' object has no attribute 'rename'.

Interestingly this worked when I casted it to a list, but a I can't analyze the data in a list because I have no way of knowing which stock matches what data.

Any help would be greatly appreciated. I'm new to python so please go easy. Thanks

答:
for value in dic1 loops through the keys, which are file name strings in this case. You want for value in dic1.values()

If you want both keys and values, you use dic1.items() which returns (key, value) tuples

Body:
I have 1000+ text files, each with two columns, one being dates, the other stock prices (at respective date). I have uploaded them and cast them into a dictionary using the following code:

filelist = os.listdir(r'insertfilepath')
filepath = r'insertfilepath'

dic1 = {}

for file in filelist:
    df = pd.read_csv(filepath + file,sep='\t')
    dic1[file]= df

However, when I try to change the column names for each one using the following code:

for value in dic1:
    for df in value:
        df.rename(columns={df.columns[0]:'Dates',df.columns[1]:'Prices'},inplace=True)

I get the following error: 'str' object has no attribute 'rename'.

Interestingly this worked when I casted it to a list, but a I can't analyze the data in a list because I have no way of knowing which stock matches what data.

Any help would be greatly appreciated. I'm new to python so please go easy. Thanks


问:
how do i add links to search suggestions?
I am a fairly new at coding with js and i only have a brief self taught knowledge in html.
any help would be very appreciated, thank you.

This is the javascript for a search box with an autocomplete function. i am asking as to how i can add links for each variables.

```<code><script>
$(document).ready(function(){
    $('input.autocomplete').autocomplete({
        data: {
            "Single Seats": null,
            "Multiple Seats": null,
            "Beds": null,
            "Entertainment": null,
            "Tables": null,
            "Storage": null,
            "Sets": null,
            "Other": null
        }
    });
});
</script>
</code>```

答:
Check the snippet, this will redirect to the link attached to the autocomplete array.
Here the autocomplete array has object with value and url, page will be redirected to appropriate url based on the value selected. For testing all the values are set to google. :)

var $ = jQuery;
$( function() {
    var availableTags = [
      {value:"ActionScript", link:'https://google.com'},
      {value:"AppleScript",link:'https://google.com'},
      {value:"Asp",link:'https://google.com'},
      {value:"BASIC",link:'https://google.com'},
      {value:"C",link:'https://google.com'},
      {value:"C++",link:'https://google.com'},
      {value:"Clojure",link:'https://google.com'},
      {value:"COBOL",link:'https://google.com'},
      {value:"ColdFusion",link:'https://google.com'},
      {value:"Erlang",link:'https://google.com'},
      {value:"Fortran",link:'https://google.com'},
      {value:"Groovy",link:'https://google.com'},
      {value:"Haskell",link:'https://google.com'},
      {value:"Java",link:'https://google.com'},
      {value:"JavaScript",link:'https://google.com'},
      {value:"Lisp",link:'https://google.com'},

    ];
    $( "#tags" ).autocomplete({
      source: availableTags,
      select: function( event, ui ) {
        console.log(ui.item.link);
        window.location.replace(ui.item.link)
      }
    });
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>

  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

</body>
</html></code>```

Body:
Check the snippet, this will redirect to the link attached to the autocomplete array.
Here the autocomplete array has object with value and url, page will be redirected to appropriate url based on the value selected. For testing all the values are set to google. :)

var $ = jQuery;
$( function() {
    var availableTags = [
      {value:"ActionScript", link:'https://google.com'},
      {value:"AppleScript",link:'https://google.com'},
      {value:"Asp",link:'https://google.com'},
      {value:"BASIC",link:'https://google.com'},
      {value:"C",link:'https://google.com'},
      {value:"C++",link:'https://google.com'},
      {value:"Clojure",link:'https://google.com'},
      {value:"COBOL",link:'https://google.com'},
      {value:"ColdFusion",link:'https://google.com'},
      {value:"Erlang",link:'https://google.com'},
      {value:"Fortran",link:'https://google.com'},
      {value:"Groovy",link:'https://google.com'},
      {value:"Haskell",link:'https://google.com'},
      {value:"Java",link:'https://google.com'},
      {value:"JavaScript",link:'https://google.com'},
      {value:"Lisp",link:'https://google.com'},

    ];
    $( "#tags" ).autocomplete({
      source: availableTags,
      select: function( event, ui ) {
        console.log(ui.item.link);
        window.location.replace(ui.item.link)
      }
    });
  } );

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>

  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

</body>
</html>


问:
Issue with a skiping of first row
I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.

File contains: Rabbit, Pig, Dog, Horse, Bird

```<code>try:
    file = open("file.txt")
    line = file.readline()

    animals = []
    for line in file:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    file.close()
</code>```

Output is ['Bird', 'Dog', 'Horse', 'Pig']

答:
The problems is the line variable, it reads a line and it is never used. You should consider using another name for the variable file because it is a keyword. Also it is good practice to open files in this format:

```<code>with open("file.txt") as f:
f.read()

</code>```

This should work.

```<code>try:
    f = open("file.txt")

    animals = []
    for line in f:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    f.close()
</code>```

Title: Issue with a skiping of first row

Body:
I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.

File contains: Rabbit, Pig, Dog, Horse, Bird

try:
    file = open("file.txt")
    line = file.readline()

    animals = []
    for line in file:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    file.close()

Output is ['Bird', 'Dog', 'Horse', 'Pig']

Body:
The problems is the line variable, it reads a line and it is never used. You should consider using another name for the variable file because it is a keyword. Also it is good practice to open files in this format:

with open("file.txt") as f:
f.read()

This should work.

try:
    f = open("file.txt")

    animals = []
    for line in f:
        animals.append(line.rstrip())
    animals.sort()
    print(animals)
finally:
    f.close()


问:
Use JS to add browser version to  or  as class
I'm trying to find a tried and tested script that sniffs the browser version and adds a suitably named class to the  or the  tags... like  or  or .

I don't mind if it's "firefox4" or "ff4" or "firefox_4"... just as long as I can use the class to scope my css.

I could write a script to do this myself but I was wondering if there was a widely used one out there...

Thanks.

答:
```<code>var  rootElement = document.documentElement;
rootElement.className += ' ie7';
</code>```

Title: Use JS to add browser version to <html> or <body> as class


问:
How does wireshark calculate number of short frames
Statistics->Protocol Hierarchy shows various statistics, including short frame counts. How does wireshark count this, and what does it consider as short frames? Is it the same as packets that were intentionally truncated during capturing? (in this case caplen field of struct pcap_pkthdr would be less than len, which is IP payload size).

However, when I implemented simple application (use libpcap) to read pcap, and counted that way (caplen vs. len), my numbers are slightly higher than what wireshark reports.

Wireshark Version 2.2.6, capture contains TLS, i.e. over TCP. Wireshark ProtocolHierarchy menu reports 15240 SSL packets, and 13640 short frames out of these 15240.

答:
How does wireshark count this, and what does it consider as short frames?

When Wireshark catches a BoundsError or ScsiBoundsError exception then it marks the frame as short frame.

From epan/show_exception.c:41

        proto_short = proto_register_protocol("Short Frame", "Short frame", "_ws.short");
```

<p>From epan/show_exception.c:81-104</p>

<pre class="lang-c prettyprint-override"><code>        case BoundsError:
                {
                gboolean display_info = TRUE;

                ....................................

                if (display_info)
                        col_append_str(pinfo->cinfo, COL_INFO, "[Packet size limited during capture]");
                proto_tree_add_protocol_format(tree, proto_short, tvb, 0, 0,
                                "[Packet size limited during capture: %s truncated]", pinfo->current_proto);
                /* Don't record BoundsError exceptions as expert events - they merely
                 * reflect a capture done with a snapshot length too short to capture
                 * all of the packet
                 * (any case where it's caused by something else is a bug). */
        }
</code>```

Is it the same as packets that were intentionally truncated during capturing?

Yes, it should be. But I would say that a small difference is possible as Wireshark does not count the short frames directly as you do in your application but the count depends on exceptions that may not be thrown because of some bugs.

(in this case caplen field of struct pcap_pkthdr would be less than len, which is IP payload size).

Correct.

However, when I implemented simple application (use libpcap) to read pcap, and counted that way (caplen vs. len), my numbers are slightly higher than what wireshark reports.

It's either a bug in Wireshark or in your code. You can use _ws.short filter to view all short frames in Wireshark and then try finding a frame that your app detects as short but Wireshark does not.

Wireshark Version 2.2.6, capture contains TLS, i.e. over TCP

Your version is a bit outdated. The latest version is 3.2.1 so consider upgrading or at least test with both versions.

Body:
How does wireshark count this, and what does it consider as short frames?

When Wireshark catches a BoundsError or ScsiBoundsError exception then it marks the frame as short frame.

From epan/show_exception.c:41

        proto_short = proto_register_protocol("Short Frame", "Short frame", "_ws.short");

From epan/show_exception.c:81-104

        case BoundsError:
                {
                gboolean display_info = TRUE;

                ....................................

                if (display_info)
                        col_append_str(pinfo->cinfo, COL_INFO, "[Packet size limited during capture]");
                proto_tree_add_protocol_format(tree, proto_short, tvb, 0, 0,
                                "[Packet size limited during capture: %s truncated]", pinfo->current_proto);
                /* Don't record BoundsError exceptions as expert events - they merely
                 * reflect a capture done with a snapshot length too short to capture
                 * all of the packet
                 * (any case where it's caused by something else is a bug). */
        }

Is it the same as packets that were intentionally truncated during capturing?

Yes, it should be. But I would say that a small difference is possible as Wireshark does not count the short frames directly as you do in your application but the count depends on exceptions that may not be thrown because of some bugs.

(in this case caplen field of struct pcap_pkthdr would be less than len, which is IP payload size).

Correct.

However, when I implemented simple application (use libpcap) to read pcap, and counted that way (caplen vs. len), my numbers are slightly higher than what wireshark reports.

It's either a bug in Wireshark or in your code. You can use _ws.short filter to view all short frames in Wireshark and then try finding a frame that your app detects as short but Wireshark does not.

Wireshark Version 2.2.6, capture contains TLS, i.e. over TCP

Your version is a bit outdated. The latest version is 3.2.1 so consider upgrading or at least test with both versions.


问:
SQLAlchemy and flask (sqlalchemy.exc.OperationalError:)
I've got this message:

```<code>sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: INSERT INTO user (username, email, password) VALUES (?, ?, ?)]
[parameters: ('test', 'test@test.com', 'password')]
(Background on this error at: http://sqlalche.me/e/e3q8)
</code>```

when I tried: db.session.commit(). I'm following a tutorial and try to personalize the code but with bad results.

What I did so far is:

```<code>>>> from lagerut import db
>>> db.create_all()
>>> from models import User
>>> user_1 = User(username='test', email='test@test.com', password='password')
>>> db.session.add(user_1)
>>> db.session.commit()
</code>```

Here the lagerut.py:

```<code>from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from form import RegistrationForm, LoginForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '2a1de6eea4126191912d6e702c6aa8f9'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///lagerut.db'
db = SQLAlchemy(app)

@app.route('/')
@app.route('/home')
def home():
    return render_template ('home.html')

@app.route('/how-it-works')
def howitworks():
    return render_template ('how-it-works.html', title='How it works')

@app.route('/lager-out')
def lagerout():
    return render_template ('lager-out.html', title='Lager out')

@app.route('/lager-in')
def lagerin():
    return render_template ('lager-in.html', title='Lager in')

@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account created for {form.username.data}!', 'success')
        return redirect(url_for('home'))
    return render_template('register.html', title='Register', form=form)

@app.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == 'admin@blog.com' and form.password.data == 'password':
            flash('You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check username and password', 'danger')
    return render_template('login.html', title='Login', form=form)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

And here the models.py:

```<code>from datetime import datetime
from lagerut import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}')"

class Items(db.Model):
    item_number = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(200), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    department = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return f"Items('{self.product}', '{self.date_posted}', '{self.content}', '{self.department}', '{self.content}')"
</code>```

Should I try to write the code again? I'm just trying to learn how build a little app to my work.

Is a good way to learn programming works also with the shell?

答:
That's because you are not creating the app context while creating the database since you are doing this via python shell you need to add the following line

```<code>with app.app_context():
</code>```

Read more about this here https://flask.palletsprojects.com/en/1.0.x/appcontext/

Body:
I've got this message:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: INSERT INTO user (username, email, password) VALUES (?, ?, ?)]
[parameters: ('test', 'test@test.com', 'password')]
(Background on this error at: http://sqlalche.me/e/e3q8)

when I tried: db.session.commit(). I'm following a tutorial and try to personalize the code but with bad results.

What I did so far is:

>>> from lagerut import db
>>> db.create_all()
>>> from models import User
>>> user_1 = User(username='test', email='test@test.com', password='password')
>>> db.session.add(user_1)
>>> db.session.commit()

Here the lagerut.py:

from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from form import RegistrationForm, LoginForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '2a1de6eea4126191912d6e702c6aa8f9'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///lagerut.db'
db = SQLAlchemy(app)

@app.route('/')
@app.route('/home')
def home():
    return render_template ('home.html')

@app.route('/how-it-works')
def howitworks():
    return render_template ('how-it-works.html', title='How it works')

@app.route('/lager-out')
def lagerout():
    return render_template ('lager-out.html', title='Lager out')

@app.route('/lager-in')
def lagerin():
    return render_template ('lager-in.html', title='Lager in')

@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account created for {form.username.data}!', 'success')
        return redirect(url_for('home'))
    return render_template('register.html', title='Register', form=form)

@app.route("/login", methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == 'admin@blog.com' and form.password.data == 'password':
            flash('You have been logged in!', 'success')
            return redirect(url_for('home'))
        else:
            flash('Login Unsuccessful. Please check username and password', 'danger')
    return render_template('login.html', title='Login', form=form)

if __name__ == '__main__':
    app.run(debug=True)

And here the models.py:

from datetime import datetime
from lagerut import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}')"

class Items(db.Model):
    item_number = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(200), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    department = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)

    def __repr__(self):
        return f"Items('{self.product}', '{self.date_posted}', '{self.content}', '{self.department}', '{self.content}')"

Should I try to write the code again? I'm just trying to learn how build a little app to my work.

Is a good way to learn programming works also with the shell?

Body:
That's because you are not creating the app context while creating the database since you are doing this via python shell you need to add the following line

with app.app_context():

Read more about this here https://flask.palletsprojects.com/en/1.0.x/appcontext/


问:
Translation of BelongsTo in Laravel Nova
I use for translations fields in Nova

```<code>Text::make(__('Name User'), 'name')
</code>```

But I don't understand the manual to make the title of the BelongsTo fields translatable

Title Attributes
  When a BelongsTo field is shown on a resource creation / update screen, a drop-down selection menu or search menu will display the "title" of the resource. For example, a User resource may use the name attribute as its title. Then, when the resource is shown in a BelongsTo selection menu, that attribute will be displayed:

Well... On my code, this fails because translations produces in name of model, not in Label of relation Ship.

```<code>BelongsTo::make(__('User'), 'users')->withMeta([
  'belongsToId' =>  $this->user_id ?? auth()->user()->id
])->hideFromDetail()
</code>```

```<code>local.ERROR: Class 'App\Nova\Usuario' not found {"userId":1,"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Class 'App\\Nova\\Usuario' not found at /home/abkrim/Sites/albaridnova/vendor/laravel/nova/src/Fields/BelongsTo.php:118)
</code>```

Code on Nova\User

```<code>public static $model = 'App\\User';

public static $title = 'email';

public static $search = ['id', 'name', 'email'];

public static function availableForNavigation(Request $request)
{
    return $request->user()->isAdmin();
}

public static function label()
{
    return __('Users');
}

public static function singularLabel()
{
    return __('User');
}
</code>```

When show User resource not problem. Labels translations are done.

But if go to resource Mailbox, field BelongsTo not show translations

答:
This happens because if you don't specify the third argument (resource) on the make method, Nova will think that your resource is called in the same way as the Label (eg: label: User then resourceName: User) and will try to search for that resource class.

Obviously you can override that by passing the resource class as third argument:

// Add the import of your resource if its class
// is not in the same directory as this file
BelongsTo::make(__('User'), 'users', User::class)->withMeta([
  'belongsToId' =>  $this->user_id ?? auth()->user()->id
])->hideFromDetail(),
```

Body:
I use for translations fields in Nova

Text::make(__('Name User'), 'name')

But I don't understand the manual to make the title of the BelongsTo fields translatable

Title Attributes
  When a BelongsTo field is shown on a resource creation / update screen, a drop-down selection menu or search menu will display the "title" of the resource. For example, a User resource may use the name attribute as its title. Then, when the resource is shown in a BelongsTo selection menu, that attribute will be displayed:

Well... On my code, this fails because translations produces in name of model, not in Label of relation Ship.

BelongsTo::make(__('User'), 'users')->withMeta([
  'belongsToId' =>  $this->user_id ?? auth()->user()->id
])->hideFromDetail()

local.ERROR: Class 'App\Nova\Usuario' not found {"userId":1,"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Class 'App\\Nova\\Usuario' not found at /home/abkrim/Sites/albaridnova/vendor/laravel/nova/src/Fields/BelongsTo.php:118)

Code on Nova\User

public static $model = 'App\\User';

public static $title = 'email';

public static $search = ['id', 'name', 'email'];

public static function availableForNavigation(Request $request)
{
    return $request->user()->isAdmin();
}

public static function label()
{
    return __('Users');
}

public static function singularLabel()
{
    return __('User');
}

When show User resource not problem. Labels translations are done.

But if go to resource Mailbox, field BelongsTo not show translations


问:
How can I stack LSTMs with Keras?
This was asked a few times (here and here for instance).

My model is:

```<code>    model = Sequential()
    model.add(LSTM(128, input_shape=(10, VECTOR_SIZE), return_sequences=True))
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
    model.compile(loss='mean_squared_error', optimizer='rmsprop')
</code>```

Which works well.

When I try to stack it:

```<code>    model = Sequential()
    model.add(LSTM(128, input_shape=(10, VECTOR_SIZE), return_sequences=True))
    model.add(LSTM(32))
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
    model.compile(loss='mean_squared_error', optimizer='rmsprop')
</code>```

I get an error:

```<code>Traceback (most recent call last):
  File "train_tf.py", line 112, in <module>
    main()
  File "train_tf.py", line 89, in main
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/engine/sequential.py", line 182, in add
    output_tensor = layer(self.outputs[0])
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 75, in symbolic_fn_wrapper
    return func(*args, **kwargs)
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/engine/base_layer.py", line 463, in __call__
    self.build(unpack_singleton(input_shapes))
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/layers/wrappers.py", line 197, in build
    assert len(input_shape) >= 3
AssertionError
</code>```

The previous answers seem to make it seem so easy, but the reality is different.

答:
You need to set return_sequences=Truefor all recurrent layers in the stack, except the last one, so in your example you should do:

```<code>model = Sequential()
model.add(LSTM(128, input_shape=(10, VECTOR_SIZE), return_sequences=True))
model.add(LSTM(32, return_sequences=True))
model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
</code>```

Title: How can I stack LSTMs with Keras?

Body:
This was asked a few times (here and here for instance).

My model is:

    model = Sequential()
    model.add(LSTM(128, input_shape=(10, VECTOR_SIZE), return_sequences=True))
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
    model.compile(loss='mean_squared_error', optimizer='rmsprop')

Which works well.

When I try to stack it:

    model = Sequential()
    model.add(LSTM(128, input_shape=(10, VECTOR_SIZE), return_sequences=True))
    model.add(LSTM(32))
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
    model.compile(loss='mean_squared_error', optimizer='rmsprop')

I get an error:

Traceback (most recent call last):
  File "train_tf.py", line 112, in <module>
    main()
  File "train_tf.py", line 89, in main
    model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/engine/sequential.py", line 182, in add
    output_tensor = layer(self.outputs[0])
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 75, in symbolic_fn_wrapper
    return func(*args, **kwargs)
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/engine/base_layer.py", line 463, in __call__
    self.build(unpack_singleton(input_shapes))
  File "/Users/shamoon/.local/share/virtualenvs/pytorch-lstm-audio-Pq4zK81J/lib/python3.6/site-packages/keras/layers/wrappers.py", line 197, in build
    assert len(input_shape) >= 3
AssertionError

The previous answers seem to make it seem so easy, but the reality is different.

Body:
You need to set return_sequences=Truefor all recurrent layers in the stack, except the last one, so in your example you should do:

model = Sequential()
model.add(LSTM(128, input_shape=(10, VECTOR_SIZE), return_sequences=True))
model.add(LSTM(32, return_sequences=True))
model.add(TimeDistributed(Dense(VECTOR_SIZE, activation='linear')))


问:
What is Kotlin for C++ push_back() and pop_back() on a string?
In C++ creating and manipulating a mutable stack of characters is rather simple. I use a built-in standard data type (std::string), use a push and pop fuctions that comes with it and can directly print the results. None of this requires creating additional classes or functions.

```<code>#include <iostream>

int main()
{
    std::string path {};
    path.push_back('L');
    path.push_back('R');
    path.pop_back();
    std::cout << path;
}
</code>```

Produces:

```<code>L
</code>```

What is Kotlin for C++ push_back() and pop_back() as a stack of characters?

The question is not how can I implement these as member functions in Kotlin.

C++ Shell code

答:
I'm not really sure if this is what you mean, but Kotlin has a dropLast(param: number of characters to drop) function which returns a string without the number of characters you did want to remove. Link: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/drop-last.html

If you are looking for a stack data structure, you might take a look at the Stack and Deque data structures.
https://chercher.tech/kotlin/deque-kotlin, https://chercher.tech/kotlin/stack-kotlin

Body:
In C++ creating and manipulating a mutable stack of characters is rather simple. I use a built-in standard data type (std::string), use a push and pop fuctions that comes with it and can directly print the results. None of this requires creating additional classes or functions.

#include <iostream>

int main()
{
    std::string path {};
    path.push_back('L');
    path.push_back('R');
    path.pop_back();
    std::cout << path;
}

Produces:

L

What is Kotlin for C++ push_back() and pop_back() as a stack of characters?

The question is not how can I implement these as member functions in Kotlin.

C++ Shell code