问:
Index column size too large. The maximum column size is 767 bytes. on import existing database in Laravel (Read carefully not duplicate)
Please read carefully. This is not a duplicate on the topic:
#1071 - Specified key was too long; max key length is 767 bytes and  How to fix 1709 - Index column size too large. The maximum column size is 767 bytes. in mysql in XAMPP

I already have an existing base. And I get this error. My question is how to correct it and I tried everything.

First I set in my database.php this code

```<code>        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
</code>```

After I set:

```<code>         Schema::defaultStringLength(191);
</code>```

Always i got error message:

Index column size too large. The maximum column size is 767 bytes.

The first time my import burst here:

```<code> CREATE TABLE `admins` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `password` varchar(60) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `created_at` timestamp NULL DEFAULT NULL,
   `updated_at` timestamp NULL DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `admins_email_unique` (`email`)
 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4
 COLLATE=utf8mb4_unicode_ci
</code>```

This is 5 tables in a row, I have 40 more. For that reason I can't change existing table.

The question, how to fix this? I use mariaDB and xampp.
The difference between my question and those above is that I import an existing table and I can not change the data. I also work in Laravel

答:
You can chenge the innodb_large_prefix in your config file to ON. That will set your  index key prefixes up to 3072 bytes as the mysql doc says.</p>

```<code>[mysqld]
innodb_large_prefix = 1
</code>```

Body:
Please read carefully. This is not a duplicate on the topic:
#1071 - Specified key was too long; max key length is 767 bytes and  How to fix 1709 - Index column size too large. The maximum column size is 767 bytes. in mysql in XAMPP

I already have an existing base. And I get this error. My question is how to correct it and I tried everything.

First I set in my database.php this code

        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',

After I set:

         Schema::defaultStringLength(191);

Always i got error message:

Index column size too large. The maximum column size is 767 bytes.

The first time my import burst here:

 CREATE TABLE `admins` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `password` varchar(60) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
   `created_at` timestamp NULL DEFAULT NULL,
   `updated_at` timestamp NULL DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `admins_email_unique` (`email`)
 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4
 COLLATE=utf8mb4_unicode_ci

This is 5 tables in a row, I have 40 more. For that reason I can't change existing table.

The question, how to fix this? I use mariaDB and xampp.
The difference between my question and those above is that I import an existing table and I can not change the data. I also work in Laravel

Body:
You can chenge the innodb_large_prefix in your config file to ON. That will set your  index key prefixes up to 3072 bytes as the mysql doc says.

[mysqld]
innodb_large_prefix = 1


来源: stackexchange

问:
Unable to access react environment variables using process.env
In my React App, I use a .env file to keep some API keys. However when I tried to access those variables using process.env the values seem to be undefined.

I start the app using below command.

```<code>yarn build; cd dist; static-server --index ./login/index.html -p 1234
</code>```

I tried restarting server, removing dist folder and rebuilding but didn't work.

This is where I access the variables.
In constants.js

```<code>const MY_API_KEY = process.env.REACT_APP_MY_API_KEY;
// some more consts here

module.exports = {MY_API_KEY};
</code>```

However when I did console.log(process.env.REACT_APP_MY_API_KEY) in constants.js file, it printed the key to console and MY_API_KEY was initialized to correct value.

What could have gone wrong here ?

答:
Accessing environment variables in React is a bit different from how you would do it when working in a Node environment.

You need to configure Webpack to handle environment variables and also install an NPM library for loading these variables.

First install node-env-file, this allows you to load your environment variables.

Then for the Webpack part, you need to do this:

```<code>plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: '"production"',
      REACT_APP_MY_API_KEY: JSON.stringify(process.env.REACT_APP_MY_API_KEY)
    }
  }),
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my React App, I use a .env file to keep some API keys. However when I tried to access those variables using process.env the values seem to be undefined.

I start the app using below command.

yarn build; cd dist; static-server --index ./login/index.html -p 1234

I tried restarting server, removing dist folder and rebuilding but didn't work.

This is where I access the variables.
In constants.js

const MY_API_KEY = process.env.REACT_APP_MY_API_KEY;
// some more consts here

module.exports = {MY_API_KEY};

However when I did console.log(process.env.REACT_APP_MY_API_KEY) in constants.js file, it printed the key to console and MY_API_KEY was initialized to correct value.

What could have gone wrong here ?

Body:
Accessing environment variables in React is a bit different from how you would do it when working in a Node environment.

You need to configure Webpack to handle environment variables and also install an NPM library for loading these variables.

First install node-env-file, this allows you to load your environment variables.

Then for the Webpack part, you need to do this:

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: '"production"',
      REACT_APP_MY_API_KEY: JSON.stringify(process.env.REACT_APP_MY_API_KEY)
    }
  }),
]


问:
Why does multimap allow duplicate key-value pairs?
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

```<code>#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}
</code>```

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?

答:
The values are allowed to be duplicates because they are not required to be comparable to each other. The container cannot do anything with the values besides copy them in. This enables types like multimap< int, my_class >.

If duplicate key-value pairs are undesirable, then use set< pair< T, U > > and use lower_bound to find the first match to a given key.

ContentLicense: CC BY-SA 3.0

Body:
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?


问:
Uncaught ReferenceError: require is not defined (electron)
I am having trouble with my Electron app. I had it working about 9 months ago, but now the custom minimise and maximise buttons I made are not functioning properly.

Here is my file structure

```<code>node_modules
    ...
web
    css
        main.css
    html
        index.html
    images
        ...
    js
        index.js
    themes
        ...
main.js
package.json
package-lock.json
require.js
</code>```

And here is the contents of index.html

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="../css/main.css">
        <style type="text/css">* {visibility: hidden;}</style>
        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700" rel="stylesheet">
        <link rel="icon" href="../images/favicon-32x32.png" />
    </head>
    <body>
        <div id="wrapper">
            <div id="title-bar">
                <div id="title-bar-btns">
                    <button id="min-btn" onclick="window_minimise()">—</button>
                    <button id="close-btn" onclick="window_close()">✕</button>
                </div>
            </div>
        ...
        </div>
        <script>
            // You can also require other files to run in this process
            require('../../renderer.js')
        </script>
        <script src="../js/index.js" type="text/javascript"></script>
    </body>
</html>
</code>```

And index.js

```<code>...
const {BrowserWindow} = require('electron').remote;

  function window_minimise(){
      let window = BrowserWindow.getCurrentWindow();
      window.minimize();
  }

  function window_close(){
      let window = BrowserWindow.getCurrentWindow();
      window.close();
  }
...
</code>```

And here is my main.js file

```<code>const {app, BrowserWindow} = require('electron')

let mainWindow

function createWindow () {

  let mainWindow = new BrowserWindow({
      width: 1200,
      height: 748,
      icon:'web/images/favicon-32x32.png',
      resizable: false,
      frame: false,
      show: false,
      backgroundColor: '#171717',
      webPreferences: {
          nodeIntegration: true
      }
  })

  mainWindow.once('ready-to-show', () => {
  mainWindow.show()
})
  mainWindow.setMenu(null);

  mainWindow.loadURL('http://localhost:8000/html/index.html')

  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) createWindow()
})

</code>```

When I click minimise or maximise, nothing happens. So I went to http://localhost:8000/html/index.html and checked the console, and I saw these errors

Uncaught ReferenceError: require is not defined at index.html:137

Uncaught ReferenceError: require is not defined at index.js:110

I am using electron version 5.0.2 by the way.

If someone could help me resolve this, that would be wonderful.

Thanks.

EDIT: The errors I mentioned above are shown when the page loads, and this error is shown when I click minimise

Uncaught ReferenceError: Cannot access 'BrowserWindow' before
  initialization at window_minimise (index.js:113) at
  HTMLButtonElement.onclick (index.html:18)

EDIT2: I think the issue is that eel (the code that allows me to interface python with my electron app) requires the webpage to be run on localhost, and thus node features such as require do not work. I go into a bit more detail in a GitHub issue here: github.com/ChrisKnott/Eel/issues/147

答:
Change your index.js file as follows. Then use nodeRequire instead of require keyword.

```<code>  initNodeRequire();
  const {BrowserWindow} = nodeRequire('electron').remote;

  function window_minimise(){
      let window = BrowserWindow.getCurrentWindow();
      window.minimize();
  }

  function window_close(){
      let window = BrowserWindow.getCurrentWindow();
      window.close();
  }

  function initNodeRequire(){
       window.nodeRequire = require;
       delete window.require;
       delete window.exports;
       delete window.module;
  }
</code>```

Body:
I am having trouble with my Electron app. I had it working about 9 months ago, but now the custom minimise and maximise buttons I made are not functioning properly.

Here is my file structure

node_modules
    ...
web
    css
        main.css
    html
        index.html
    images
        ...
    js
        index.js
    themes
        ...
main.js
package.json
package-lock.json
require.js

And here is the contents of index.html

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="../css/main.css">

        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700" rel="stylesheet">
        <link rel="icon" href="../images/favicon-32x32.png" />

                    <button id="min-btn" onclick="window_minimise()">—</button>
                    <button id="close-btn" onclick="window_close()">✕</button>

        ...

And index.js

...
const {BrowserWindow} = require('electron').remote;

  function window_minimise(){
      let window = BrowserWindow.getCurrentWindow();
      window.minimize();
  }

  function window_close(){
      let window = BrowserWindow.getCurrentWindow();
      window.close();
  }
...

And here is my main.js file

const {app, BrowserWindow} = require('electron')

let mainWindow

function createWindow () {

  let mainWindow = new BrowserWindow({
      width: 1200,
      height: 748,
      icon:'web/images/favicon-32x32.png',
      resizable: false,
      frame: false,
      show: false,
      backgroundColor: '#171717',
      webPreferences: {
          nodeIntegration: true
      }
  })

  mainWindow.once('ready-to-show', () => {
  mainWindow.show()
})
  mainWindow.setMenu(null);

  mainWindow.loadURL('http://localhost:8000/html/index.html')

  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (mainWindow === null) createWindow()
})

When I click minimise or maximise, nothing happens. So I went to http://localhost:8000/html/index.html and checked the console, and I saw these errors

Uncaught ReferenceError: require is not defined at index.html:137

Uncaught ReferenceError: require is not defined at index.js:110

I am using electron version 5.0.2 by the way.

If someone could help me resolve this, that would be wonderful.

Thanks.

EDIT: The errors I mentioned above are shown when the page loads, and this error is shown when I click minimise

Uncaught ReferenceError: Cannot access 'BrowserWindow' before
  initialization at window_minimise (index.js:113) at
  HTMLButtonElement.onclick (index.html:18)

EDIT2: I think the issue is that eel (the code that allows me to interface python with my electron app) requires the webpage to be run on localhost, and thus node features such as require do not work. I go into a bit more detail in a GitHub issue here: github.com/ChrisKnott/Eel/issues/147

Body:
Change your index.js file as follows. Then use nodeRequire instead of require keyword.

  initNodeRequire();
  const {BrowserWindow} = nodeRequire('electron').remote;

  function window_minimise(){
      let window = BrowserWindow.getCurrentWindow();
      window.minimize();
  }

  function window_close(){
      let window = BrowserWindow.getCurrentWindow();
      window.close();
  }

  function initNodeRequire(){
       window.nodeRequire = require;
       delete window.require;
       delete window.exports;
       delete window.module;
  }


问:
Whether 'var' allocates new memory when re-accessed or overwrites it?
```<code>function Foo(){
  var someObj = {
    s: 'string'
  }

  console.log(someObj.s);
}

Foo(); // first call
Foo(); // second call
</code>```

Will the memory where the someObj points to are overwritten or will a new one be allocated? If new memory will be allocated, what happens with someObj created at first call, will garbage collector erase it? And should I make a definition of someObj outside the function to reduce the number of memory operations?

答:
As far as I'm concerned that's nothing I would really care when writing js. It's up to the compiler (V8 or whatever is compiling your code) to do necessary optimisations.

But:

Will the memory where the someObj points to are overwritten or will a new one be allocated?

I says it's allocated every time function is called. Or, in other words, you can treat it as new variable all the time.

what happens with someObj created at first call, will garbage collector erase it

Yes, when function is called and exits, this reference is marked as trash, which should be cleaned up by GC when GC kicks in.

And should I make a definition of someObj outside the function to reduce the number of memory operations?

From my knowledge about V8 and similar, as longs as the type is always the same, there are some built-in techniques that would make this optimisation.

However, in general I cannot imagine how often this would have to be called, that you'd need any optimisation in this kind of code.

This question sounds like either some academic problem (which I probably can't help much) or some attempt of premature optimisations.

As a side note. Code is primarily for other humans. It should be readable for them first.

Body:
function Foo(){
  var someObj = {
    s: 'string'
  }

  console.log(someObj.s);
}

Foo(); // first call
Foo(); // second call

Will the memory where the someObj points to are overwritten or will a new one be allocated? If new memory will be allocated, what happens with someObj created at first call, will garbage collector erase it? And should I make a definition of someObj outside the function to reduce the number of memory operations?


问:
Displaying text with SDL TTF with SDL2 and OpenGL
I'm trying to display text using SDL2 TTF and OpenGL. A weird texture appears in the window, it's got the right size and the right position but you can't see any letters.

I've tried using the SDL_CreateRGBSurface() thinking that it might be a cleaner way to recuperate the pixels, but it didn't work either. My surface is never NULL and always passes the validation test.

I use the get_front() function before the while() loop, and the displayMoney() function inside it, right after using glClear(GL_COLOR_BUFFER_BIT).

SDL, TTF and OpenGL are initialized properly and I have created an OpenGL context. Here's the problematic code:

```<code>SDL_Surface* get_font()
{
    TTF_Font *font;
    font = TTF_OpenFont("lib/ariali.ttf", 35);
    if (!font) cout << "problem loading font" << endl;
    SDL_Color white = {150,200,200};
    SDL_Color black = {0,100,0};
    SDL_Surface* text = TTF_RenderText_Shaded(font, "MO", white, black);
    if (!text) cout << "text not loaded" << endl;

    return text;
}

void displayMoney(SDL_Surface* surface)
{
    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    glEnable(GL_TEXTURE_2D);
    GLuint TextureID = 0;
    glGenTextures(1, &TextureID);
    glBindTexture(GL_TEXTURE_2D, TextureID);
        int Mode = GL_RGB;
        if(surface->format->BytesPerPixel == 4) {
            Mode = GL_RGBA;
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, Mode, 128, 64, 0, Mode, GL_UNSIGNED_BYTE, surface->pixels);

        glPushMatrix();
            glTranslated(100,100,0);
            glScalef(100,100,0);
            glBegin(GL_QUADS);
                glTexCoord2f(0, 1); glVertex2f(-0.5f, -0.5f);
                glTexCoord2f(1, 1); glVertex2f(0.5f, -0.5f);
                glTexCoord2f(1, 0); glVertex2f(0.5f, 0.5f);
                glTexCoord2f(0, 0); glVertex2f(-0.5f, 0.5f);
            glEnd();
        glPopMatrix();
    glBindTexture(GL_TEXTURE_2D, 0);
}
</code>```

```<code>
#include <SDL2/SDL.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#include <GL/gl.h>
#include <GL/glu.h>
#include <stb_image/stb_image.h>
#include <SDL2_ttf/SDL_ttf.h>
#include "init.h"

int main(int argc, char **argv) {

    SDL_Window* window = init();
    if (window == nullptr) {
        cout << "Error window init" << endl;
    }

    if (TTF_Init() < 0) {
        cout << "Error TTF init" << endl;
    }

    SDL_Surface* text = get_font();

    while (loop) {

        glClear(GL_COLOR_BUFFER_BIT);

        displayMoney(text);

...

       SDL_GL_SwapWindow(window);

</code>```

There aren't any error messages. Also, instead of using my surface, I tested my code with an image by using the stbi_load function and it worked perfectly well. The issue therefore seems to be with the SDL part.

EDIT : I've recently found out the surface I get from my text has the following properties: Rmask=Gmask=Bmask=Amask = 0. This is obviously a problem but I've no idea how to fix it...

答:
As stated in SDL_ttf documentation at https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC42 ,

Shaded: Create an 8-bit palettized surface and render the given text at high quality with the given font and colors. The 0 pixel value is background, while other pixels have varying degrees of the foreground color from the background color.

So your resulting surface is indexed with 8-bit palette, not an RGBA (also indicated by missing colour masks in surface format, as you've noted). RGBA surface with alpha channel is produced by e.g. TTF_RenderText_Blended, or use different texture format, or perform format conversion. You need to pass surface width/height to glTexImage2D instead of 128/64 constants as surface size may vary.

You also have several resource leaks in question's code: creating new texture on each draw and never deleting it (which is also unnecessary if text isn't changing), and never closing font with TTF_CloseFont.

Body:
I'm trying to display text using SDL2 TTF and OpenGL. A weird texture appears in the window, it's got the right size and the right position but you can't see any letters.

I've tried using the SDL_CreateRGBSurface() thinking that it might be a cleaner way to recuperate the pixels, but it didn't work either. My surface is never NULL and always passes the validation test.

I use the get_front() function before the while() loop, and the displayMoney() function inside it, right after using glClear(GL_COLOR_BUFFER_BIT).

SDL, TTF and OpenGL are initialized properly and I have created an OpenGL context. Here's the problematic code:

SDL_Surface* get_font()
{
    TTF_Font *font;
    font = TTF_OpenFont("lib/ariali.ttf", 35);
    if (!font) cout << "problem loading font" << endl;
    SDL_Color white = {150,200,200};
    SDL_Color black = {0,100,0};
    SDL_Surface* text = TTF_RenderText_Shaded(font, "MO", white, black);
    if (!text) cout << "text not loaded" << endl;

    return text;
}

void displayMoney(SDL_Surface* surface)
{
    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    glEnable(GL_TEXTURE_2D);
    GLuint TextureID = 0;
    glGenTextures(1, &TextureID);
    glBindTexture(GL_TEXTURE_2D, TextureID);
        int Mode = GL_RGB;
        if(surface->format->BytesPerPixel == 4) {
            Mode = GL_RGBA;
        }

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, Mode, 128, 64, 0, Mode, GL_UNSIGNED_BYTE, surface->pixels);

        glPushMatrix();
            glTranslated(100,100,0);
            glScalef(100,100,0);
            glBegin(GL_QUADS);
                glTexCoord2f(0, 1); glVertex2f(-0.5f, -0.5f);
                glTexCoord2f(1, 1); glVertex2f(0.5f, -0.5f);
                glTexCoord2f(1, 0); glVertex2f(0.5f, 0.5f);
                glTexCoord2f(0, 0); glVertex2f(-0.5f, 0.5f);
            glEnd();
        glPopMatrix();
    glBindTexture(GL_TEXTURE_2D, 0);
}

#include <SDL2/SDL.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#include <GL/gl.h>
#include <GL/glu.h>
#include <stb_image/stb_image.h>
#include <SDL2_ttf/SDL_ttf.h>
#include "init.h"

int main(int argc, char **argv) {

    SDL_Window* window = init();
    if (window == nullptr) {
        cout << "Error window init" << endl;
    }

    if (TTF_Init() < 0) {
        cout << "Error TTF init" << endl;
    }

    SDL_Surface* text = get_font();

    while (loop) {

        glClear(GL_COLOR_BUFFER_BIT);

        displayMoney(text);

...

       SDL_GL_SwapWindow(window);

There aren't any error messages. Also, instead of using my surface, I tested my code with an image by using the stbi_load function and it worked perfectly well. The issue therefore seems to be with the SDL part.

EDIT : I've recently found out the surface I get from my text has the following properties: Rmask=Gmask=Bmask=Amask = 0. This is obviously a problem but I've no idea how to fix it...


问:
messages file is not picking single quote
In Play Framework, the messages file is used for localisation. I have added the following key-value in it but the single quote in the value is not getting picked.

```<code>error.incorrectTag = The specified tag doesn't exist in the system
</code>```

When I print the above message using the following code

```<code>println(s"${messagesApi("error.incorrectTag")(langs.availables(0))}")
</code>```

I see The specified tag doesnt exist in the system (single quote is not there)

How can I print the single quote?

答:
You need to escape the single quote ' by using a double single quote '' like this:

```<code>error.incorrectTag = The specified tag doesn''t exist in the system
</code>```

Body:
In Play Framework, the messages file is used for localisation. I have added the following key-value in it but the single quote in the value is not getting picked.

error.incorrectTag = The specified tag doesn't exist in the system

When I print the above message using the following code

println(s"${messagesApi("error.incorrectTag")(langs.availables(0))}")

I see The specified tag doesnt exist in the system (single quote is not there)

How can I print the single quote?

Body:
You need to escape the single quote ' by using a double single quote '' like this:

error.incorrectTag = The specified tag doesn''t exist in the system


问:
Unable to start Peers in Hyperledger Fabric?
Problem:

I created crypto material and channel artifacts for a network using Hyperledger Fabric. Then I Up the network but it only up the cli container. Then I look for the logs in the containers. In all peers, it shows me like this.

```<code>Cannot run peer because error when setting up MSP of type bccsp from directory /etc/hyperledger/fabric/msp: could not load a valid signer certificate from directory /etc/hyperledger/fabric/msp/signcerts: stat /etc/hyperledger/fabric/msp/signcerts: no such file or directory
</code>```

In orderer container,

```<code>Failed to initialize local MSP: could not load a valid signer certificate from directory /var/hyperledger/orderer/msp/signcerts: stat /var/hyperledger/orderer/msp/signcerts: no such file or directory
</code>```

I tried and searched a lot to find a solution to this problem. But I was unable to find any reason for this problem. Yesterday It was working fine without any errors but today when I restarted the network it leaves me with these errors. Can someone help me solve this problem?. Thank you!

答:
I had the same problem.

Try using 'Teardown Fabric Runtime' and start it again.

The problem was that the first time I started fabric on Windows 10, I haven't enabled C drive sharing in Docker and got error:

C: drive is not shared. Please share it in Docker for Windows Settings.

Then I turned C drive sharing on and it resolved drive sharing error, however I started getting the error you mentioned. All I did was teared down fabric and started it again. I guess it's related to false start of fabric docker containers and all it needs is a fresh start.

Body:
Problem:

I created crypto material and channel artifacts for a network using Hyperledger Fabric. Then I Up the network but it only up the cli container. Then I look for the logs in the containers. In all peers, it shows me like this.

Cannot run peer because error when setting up MSP of type bccsp from directory /etc/hyperledger/fabric/msp: could not load a valid signer certificate from directory /etc/hyperledger/fabric/msp/signcerts: stat /etc/hyperledger/fabric/msp/signcerts: no such file or directory

In orderer container,

Failed to initialize local MSP: could not load a valid signer certificate from directory /var/hyperledger/orderer/msp/signcerts: stat /var/hyperledger/orderer/msp/signcerts: no such file or directory

I tried and searched a lot to find a solution to this problem. But I was unable to find any reason for this problem. Yesterday It was working fine without any errors but today when I restarted the network it leaves me with these errors. Can someone help me solve this problem?. Thank you!


问:
Which event is triggered when v model value is changing
I'm new to Vuejs and my requirement is to write a single functional globally to trigger whenever v-model value of my form elements are set. I tried to write this for element.onchnage but this is not working.

Can some one tell me which HTML event is triggered when the v-model value is set in vuejs ?

答:
Hey Linu and welcome to SO.

Check out the docs for Form input bindings:
https://v2.vuejs.org/v2/guide/forms.html

There it says:

v-model internally uses different properties and emits different
events for different input elements:

text and textarea elements use value property and input event

checkboxes and radiobuttons use checked property and change event;

select fields use value as a prop and change as an event.

So instead of v-model you can do the following for inputs

```<code><input :value="dataProperty" @input="dataProperty = $event.target.value" />
</code>```

Body:
Hey Linu and welcome to SO.

Check out the docs for Form input bindings:
https://v2.vuejs.org/v2/guide/forms.html

There it says:

v-model internally uses different properties and emits different
events for different input elements:

text and textarea elements use value property and input event

checkboxes and radiobuttons use checked property and change event;

select fields use value as a prop and change as an event.

So instead of v-model you can do the following for inputs

<input :value="dataProperty" @input="dataProperty = $event.target.value" />


问:
Not able to create border dynmaically using ngstyle in angularjs
I have applied this condition on element but it is not showing any border also it is not showing any error in parsing html:

```<code><h1 ng-style="'{border:' + f()+'px' + 'solid red'+'}'">{{a}}</h1>
</code>```

Here is the code from my controller:

```<code>$scope.a = "dynamic border";
$scope.f = function() {
  return 1;
};
</code>```

答:
Your code is mostly correct, only small issues with placement of '. Try the following please.

```<code><h1 ng-style="{'border': f() + 'px solid red'}">{{a}}</h1>
</code>```

Demo

Body:
I have applied this condition on element but it is not showing any border also it is not showing any error in parsing html:

{{a}}

Here is the code from my controller:

$scope.a = "dynamic border";
$scope.f = function() {
  return 1;
};

Body:
Your code is mostly correct, only small issues with placement of '. Try the following please.

<h1 ng-style="{'border': f() + 'px solid red'}">{{a}}</h1>

Demo


问:
Excel Formula: COUNTIFS() return value is wrong
I'm using COUNTIFS() formula in Excel to count number of dates in a list,corresponding to a particular name. The output values are not accurate

Formula used:

= COUNTIFS($G$31:$G$37,B32,$F$31:$F$37,"")

COUNTIFS(range1 -text, comparison value, range2-date, check for value in range 2 )

The formula first compares a list range1 (G column) with a given text comparison, then it compares the range2 (F column) list to check for a date/blank space.

I've also tried this version of formula:

= COUNTIFS($G$31:$G$37,B32,$F$31:$F$37,"?????????")

and it returns a '0' every time

Am I using this function the right way?Data Image

答:
Looking at your provided sample data try:

```<code>=COUNTIFS($G$31:$G$37,B32,$F$31:$F$37,"<>")
</code>```

In cel C32 and drag down...

It was the "<>" (anything other then empty) you were looking for I assume.

Body:
Looking at your provided sample data try:

=COUNTIFS($G$31:$G$37,B32,$F$31:$F$37,"<>")

In cel C32 and drag down...

It was the "<>" (anything other then empty) you were looking for I assume.


问:
How to set inspection profile for the editor in IntelliJ?
I'm suddenly missing a lot of in-editor warnings and errors. When I manually run my inspections, the things I'm missing show up just fine, but how do I get them to show in the editor window again?

For example, if I put an incorrect package statement in my class, it will show up when I run Analyze -> Inspect Code..., but not the editor window won't complain or offer a quick fix.

答:
Here you can access all settings of intellij code inspection

When you run "Analyze -> Inspect Code" the IDE will effectively not do any highlight. Be sure that in the code inspection, the highlight level is on "inspections" or at least on "syntax" as Matthew mentioned


问:
How to find the number of times a string occurs in a text file?
I'm trying to count the number of times a string occurs in a file of strings.

```<code>data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)
</code>```

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?

答:
So after a bit of experimenting, I came across the following:

file = open("xyz.txt", 'r')
count = 0
inline = []
toFind = input("What should I find? > ")
toFind2 = toFind + '\n'
for line in file.readlines():
    line = line.split(' ')
    if toFind in line:
        count += 1
        inline.append("".join(line))
    if toFind2 in line:
        count += 1
        inline.append("".join(line))

print("This was found: " + str(count) + " times.")
```

This should do the trick. =]

Body:
I'm trying to count the number of times a string occurs in a file of strings.

data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?

Body:
So after a bit of experimenting, I came across the following:

file = open("xyz.txt", 'r')
count = 0
inline = []
toFind = input("What should I find? > ")
toFind2 = toFind + '\n'
for line in file.readlines():
    line = line.split(' ')
    if toFind in line:
        count += 1
        inline.append("".join(line))
    if toFind2 in line:
        count += 1
        inline.append("".join(line))

print("This was found: " + str(count) + " times.")

This should do the trick. =]


问:
Forecast multiple features in Time Series Data (using key)
I have a data set of multiple users activity for the last 2 years.
My problem is to forecast for a given person is likely to do what kind of activity in the near future.

For example:

```<code>Today is 2019-05-27
Input should be user_id (ex: 1)
</code>```

Then it has to produce something like below:

User with user_id 1 is likely to climb a mountain on 2019-05-30

User with user_id 1 is likely to go to trip on 2019-06-02

All this should be forecasted using users activity history. (Frequency of each activity can be different)

How do solve this problem using machine learning on python?

What algorithm is best for this kind of problem?

答:
any (time series analysis) tsa algorithm will work for your problem statement but first

1. you need to clean the data & bring it in the format that algorithm can learn from.

2. you can create a pandas dataframe having two or more columns, first will be the index having all the dates,time & second column will have a vector/number which represents the activities from your dataset from third column onwards you can keep values for different users in different column

|---------------------|------------------|
|      index          |   data_user1     |
|---------------------|------------------|
|      date           |   activity_label |
|---------------------|------------------|

3. For converting your activity to a vector/number you can use label encoder

4. Impute the missing timestamps in your dataset.

5. Use any tsa algorithm either sliding window approach with LSTM/NN or the pre-implemented algos from statsmodels.tsa

I'll suggest you to use ARIMA/SARIMA, if you have date in the right form it's as simple as writing just these 3 lines.

```<code>model=statsmodels.api.tsa.SARIMAX(train_df,order=(1,0,1),seasonal_order=(1,1,0,24))
model = model.fit()
model.predict()
</code>```

Body:
I have a data set of multiple users activity for the last 2 years.
My problem is to forecast for a given person is likely to do what kind of activity in the near future.

For example:

Today is 2019-05-27
Input should be user_id (ex: 1)

Then it has to produce something like below:

User with user_id 1 is likely to climb a mountain on 2019-05-30

User with user_id 1 is likely to go to trip on 2019-06-02

All this should be forecasted using users activity history. (Frequency of each activity can be different)

How do solve this problem using machine learning on python?

What algorithm is best for this kind of problem?

Body:
any (time series analysis) tsa algorithm will work for your problem statement but first

1. you need to clean the data & bring it in the format that algorithm can learn from.

2. you can create a pandas dataframe having two or more columns, first will be the index having all the dates,time & second column will have a vector/number which represents the activities from your dataset from third column onwards you can keep values for different users in different column

|---------------------|------------------|
|      index          |   data_user1     |
|---------------------|------------------|
|      date           |   activity_label |
|---------------------|------------------|

3. For converting your activity to a vector/number you can use label encoder

4. Impute the missing timestamps in your dataset.

5. Use any tsa algorithm either sliding window approach with LSTM/NN or the pre-implemented algos from statsmodels.tsa

I'll suggest you to use ARIMA/SARIMA, if you have date in the right form it's as simple as writing just these 3 lines.

model=statsmodels.api.tsa.SARIMAX(train_df,order=(1,0,1),seasonal_order=(1,1,0,24))
model = model.fit()
model.predict()


问:
Why select returns only the first value?
There are two values in function. Input and select, everything works normally except that the select returns the first value (px). Where did I get it wrong?</p>

```<code><input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>
</code>```

```<code>function Width(){
var x = document.getElementById("width").value;
var y = document.getElementById("widthpixselpercentage").value;
        document.getElementById(someDiv).style.width = x + y;

}
</code>```

答:
You may refer to the following sample code:

function Width(vv)
{
 alert(vv.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="width" onchange="Width(this)" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width(this)" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div></code>```

Body:
There are two values in function. Input and select, everything works normally except that the select returns the first value (px). Where did I get it wrong?

<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

function Width(){
var x = document.getElementById("width").value;
var y = document.getElementById("widthpixselpercentage").value;
        document.getElementById(someDiv).style.width = x + y;

}

Body:
You may refer to the following sample code:

function Width(vv)
{
 alert(vv.value);
}

<input id="width" onchange="Width(this)" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width(this)" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>


问:
Where does PHP store the error log? (PHP 5, Apache, FastCGI, and cPanel)
I am on shared hosting and have cPanel, Apache, and PHP is run by FastCGI.  Where does PHP store the error log?

Is there another way I can find the error log on a shared hosting environment instead of having to go through entire site structure to look for error_log files?

I have access to the php.ini file (I am using PHP version 5.2.16).

答:
You are on a shared environment and cannot find error log. Always check if cPanel has option Errors in your cPanel dashboard. If you are not being able to find the error log, then you can find it there.

In the cPanel search bar, search Error, it will show Error Pages which are basically lists of different HTTP error pages and other Error is where the error logs are displayed.

Other places to look in a shared environment:

/home/yourusername/logs

/home/yourusername/public_html/error_log


问:
iPad programming, any way to invert color programmatically?
You know how the iPad can invert colors? For the app I'm working on we wanted to have a button that would invert the colors for one of the views the same way.  Does the sdk have any kind of support for something like that already? </p>

答:
I don't think that there is an easy way at the moment. CALayer has a compositingFilter property which is described as

A CoreImage filter used to composite
  the receiver’s contents with the
  background. Animatable.

It's available since iOS 2.0 but it also says:

While the CALayer class exposes this
  property, Core Image is not available
  in iOS. Currently the filters
  available for this property are
  undefined.

Core Image would have been ideal for that purpose, it does provide a filter (CIColorInvert) to invert colors.

Another apporach would be: Change the color properties of the UI controls you are using, though I doubt that everything will look they way you expect, as there may be gradients and such. You have to implement your own small algorithm to invert a given color.

I see only the hard way: You have to draw your controls manually with drawRect and invert the colors with your own algorithm there.

ContentLicense: CC BY-SA 2.5


问:
How to update children rows of an object that has OneToMany association
I am working on a Java project, and I got stuck while trying to update an object with a oneToMany association, here are my classes :

Team.class

```<code>    @Entity
    @Table(name = "TEAM", schema = SchemaRef.NOM_SCHEMA_REF)
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = CacheRegion.CACHE_TEAM)
    public class TEAM extends TeamPrincipal {

        /**
         * long serialVersionUID.
         */
        private static final long serialVersionUID = -7697301560938121726L;

        /** The players . */
        @OneToMany(mappedBy = "tm", cascade = CascadeType.ALL, orphanRemoval = false)
        @Fetch(FetchMode.SUBSELECT)
        @LazyCollection(LazyCollectionOption.FALSE)
        @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = CacheRegion.CACHE_TEAM)
        private Set<Player> listPlayers;

//Getters & Setters

    }
</code>```

Player.class

```<code>@Entity
@Table(name = "PLAYER", schema = SchemaReferentiel.NOM_SCHEMA_REF)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = CacheRegion.CACHE_TEAM)
public class Player extends DomainObject {

    /**
     * long serialVersionUID.
     */
    private static final long serialVersionUID = -7697301560938121726L;

    /** The id. */
    @Id
    @SequenceGenerator(
                       name = "SequenceIdGenerator",
                       sequenceName = SchemaReferentiel.NOM_SCHEMA_REF + ".SEQUENCE_PLAYER",
                       allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceIdGenerator")
    @Column(name = "PLAYER_ID")
    private long id;

    /** The Player. */
    @ManyToOne
    @JoinColumn(name = "lTeam_Player", referencedColumnName = "id", nullable = false)
    @ForeignKey(name = "C_FK_PlTeam_Player")
    private Team team;

//getters and setter
}
</code>```

The calling DAO method is TeamDao.java:

```<code>sessionFactory.getCurrentSession().saveOrUpdate(toSave);
</code>```

The problem I am facing with this mapping is when I try to update the Team by changing the list of players it updates the Team attributes but the Players are always the same as when it was added.

The creation is done correctly, in debug mode while trying to update, the team contains the new list of players to update, after the call of DAO method, the parent(TEAM) is updated but the children (Players) are not

答:
As this is a bi-directional mapping, make sure that you set the players for a team and set the team for each of the players:</p>

```<code>team.setPlayers(players);

for(Player player: players){
   player.setTeam(team);
}

sessionFactory.getCurrentSession().saveOrUpdate(team);
</code>```

Body:
I am working on a Java project, and I got stuck while trying to update an object with a oneToMany association, here are my classes :

Team.class

    @Entity
    @Table(name = "TEAM", schema = SchemaRef.NOM_SCHEMA_REF)
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = CacheRegion.CACHE_TEAM)
    public class TEAM extends TeamPrincipal {

        /**
         * long serialVersionUID.
         */
        private static final long serialVersionUID = -7697301560938121726L;

        /** The players . */
        @OneToMany(mappedBy = "tm", cascade = CascadeType.ALL, orphanRemoval = false)
        @Fetch(FetchMode.SUBSELECT)
        @LazyCollection(LazyCollectionOption.FALSE)
        @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = CacheRegion.CACHE_TEAM)
        private Set<Player> listPlayers;

//Getters & Setters

    }

Player.class

@Entity
@Table(name = "PLAYER", schema = SchemaReferentiel.NOM_SCHEMA_REF)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = CacheRegion.CACHE_TEAM)
public class Player extends DomainObject {

    /**
     * long serialVersionUID.
     */
    private static final long serialVersionUID = -7697301560938121726L;

    /** The id. */
    @Id
    @SequenceGenerator(
                       name = "SequenceIdGenerator",
                       sequenceName = SchemaReferentiel.NOM_SCHEMA_REF + ".SEQUENCE_PLAYER",
                       allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceIdGenerator")
    @Column(name = "PLAYER_ID")
    private long id;

    /** The Player. */
    @ManyToOne
    @JoinColumn(name = "lTeam_Player", referencedColumnName = "id", nullable = false)
    @ForeignKey(name = "C_FK_PlTeam_Player")
    private Team team;

//getters and setter
}

The calling DAO method is TeamDao.java:

sessionFactory.getCurrentSession().saveOrUpdate(toSave);

The problem I am facing with this mapping is when I try to update the Team by changing the list of players it updates the Team attributes but the Players are always the same as when it was added.

The creation is done correctly, in debug mode while trying to update, the team contains the new list of players to update, after the call of DAO method, the parent(TEAM) is updated but the children (Players) are not

Body:
As this is a bi-directional mapping, make sure that you set the players for a team and set the team for each of the players:

team.setPlayers(players);

for(Player player: players){
   player.setTeam(team);
}

sessionFactory.getCurrentSession().saveOrUpdate(team);


问:
Precedence of 'or' and 'and' operators in C
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance.</p>

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

int main(){
    int a,b,c,d;
    a =1;
    b = c = 10;
    d = a|| --b&&--c;
    printf("%d\n",c);
    printf("%d\n",a);
    printf("%d\n",d);
    return 0;
}
</code>```

答:
Precedence and order of evaluation are two different things. From Logical OR
 documentation (emphasis mine):

There is a sequence point after the evaluation of lhs. If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation).

In case of exp1 || exp2, exp1 is always evaluated first as there is a sequence point after it and if exp1 is non-zero then exp2 is not evaluated.

Body:
In the following code, I am getting 10 | 1 | 1 as a result. But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || (--b)&&(--c) since 'and' has higher precedence. ( or shortcutting breaks precedence rules ?)Thanks in advance.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a,b,c,d;
    a =1;
    b = c = 10;
    d = a|| --b&&--c;
    printf("%d\n",c);
    printf("%d\n",a);
    printf("%d\n",d);
    return 0;
}


问:
Trouble moving files in PowerShell using forfiles to a folder whose name has more than one word
I'm new to PowerShell, and am trying to move a few excel spreadsheets into a folder titled "old folder" using the forfiles command. PowerShell says that the files have been moved, but when I check the folder they're not there. They aren't in their original location either.

```<code>forfiles /P C:\Users\NewUser\Desktop /M *.xlsx /D +27/05/2019 /C 'cmd /c move @file C:\Users\NewUser\Desktop\"old folder"\'
</code>```

I tried changing the folder name to a single word "oldfolder" and it worked just fine. What am I doing wrong?

答:
As forfiles has it's idiosyncrasies even in cmd, I wouldn't drag that along to PowerShell.

IIUR that translates to:

```<code>Get-ChildItem 'C:\Users\NewUser\Desktop\*.xlsx' -File |
    Where-Object LastWriteTime -ge [DateTime]::Today |
        Move-Item -Destination 'C:\Users\NewUser\Desktop\old folder\'
</code>```

Not sure if you meant that to be /D -27/05/2019 => -lt or -le instead of -ge

Body:
I'm new to PowerShell, and am trying to move a few excel spreadsheets into a folder titled "old folder" using the forfiles command. PowerShell says that the files have been moved, but when I check the folder they're not there. They aren't in their original location either.

forfiles /P C:\Users\NewUser\Desktop /M *.xlsx /D +27/05/2019 /C 'cmd /c move @file C:\Users\NewUser\Desktop\"old folder"\'

I tried changing the folder name to a single word "oldfolder" and it worked just fine. What am I doing wrong?

Body:
As forfiles has it's idiosyncrasies even in cmd, I wouldn't drag that along to PowerShell.

IIUR that translates to:

Get-ChildItem 'C:\Users\NewUser\Desktop\*.xlsx' -File |
    Where-Object LastWriteTime -ge [DateTime]::Today |
        Move-Item -Destination 'C:\Users\NewUser\Desktop\old folder\'

Not sure if you meant that to be /D -27/05/2019 => -lt or -le instead of -ge


问:
setTimeOut() solution on Twitter
I was reading John resig's blogpost: http://ejohn.org/blog/learning-from-twitter/ and I did not understand the problem with setTimeOut()  there.

Question 1:

Johh shared this code:

```<code>var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);
</code>```

Where is caching used here? I assume when didScroll is true, then outerPane variable will be used instead of re-searching the DOM, am I right?

Question 2:

In the comment section Michael shared a code:

```<code>var timer = 0;

$(window).scroll(function () {
if (timer) {
clearTimeout(timer);
}

// Use a buffer so we don't call myCallback too often.
timer = setTimeout(myCallback, 100);
});
</code>```

and said: "Instead of setting up an interval, the callback is only ever fired when it needs to be. Saves a few extra calls to the callback, and any overhead from the extra logic inside the scroll handler should be fairly minimal."

My question is: setTimeOut() will return a timerID which will be used by clearTimeOut to clear. Now with this setTimeout(myCallback, 100) function after every 100 mili second myCallBack function will be used, isn't it? Moreover, when the scroll event will fire the timer will be cleared and never set again, so what is the purpose of using it?

Sorry for my confusions. Have a nice day.

答:
@ Question 2:

The code if (timer) { clearTimeout(timer); } is easy to missunderstand, because the used syntax, in my humble opinion, is wrong. I think the code must be as follows below:

```<code>if (timer != null) { clearTimeout(timer); }
</code>```

because after a clearTimeout, the variable 'timer' will be cleaned. You can try it if you would made an alert(timer); after 'clearTimeout()'.

Title: setTimeOut() solution on Twitter

Body:
I was reading John resig's blogpost: http://ejohn.org/blog/learning-from-twitter/ and I did not understand the problem with setTimeOut()  there.

Question 1:

Johh shared this code:

var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);

Where is caching used here? I assume when didScroll is true, then outerPane variable will be used instead of re-searching the DOM, am I right?

Question 2:

In the comment section Michael shared a code:

var timer = 0;

$(window).scroll(function () {
if (timer) {
clearTimeout(timer);
}

// Use a buffer so we don't call myCallback too often.
timer = setTimeout(myCallback, 100);
});

and said: "Instead of setting up an interval, the callback is only ever fired when it needs to be. Saves a few extra calls to the callback, and any overhead from the extra logic inside the scroll handler should be fairly minimal."

My question is: setTimeOut() will return a timerID which will be used by clearTimeOut to clear. Now with this setTimeout(myCallback, 100) function after every 100 mili second myCallBack function will be used, isn't it? Moreover, when the scroll event will fire the timer will be cleared and never set again, so what is the purpose of using it?

Sorry for my confusions. Have a nice day.

Body:
@ Question 2:

The code if (timer) { clearTimeout(timer); } is easy to missunderstand, because the used syntax, in my humble opinion, is wrong. I think the code must be as follows below:

if (timer != null) { clearTimeout(timer); }

because after a clearTimeout, the variable 'timer' will be cleaned. You can try it if you would made an alert(timer); after 'clearTimeout()'.


问:
Cognos Report Studio / Concur Reporting - multiple rows into one
first off, i am new not only to cognos report studio, but to working with databases/tables and queries in general. I am tasked with building reports using sap concur's implementation of IBM Cognos report studio (v10.2.1). That means the data model is defined by the concur people.

I am using 5 queries joined together in 4 Joins and now have all the columns and values the way i want them in the report (through more trial and error than i am comfortable with, to be honest), except for one thing:
Adding the column "Comments" generates duplicate rows, one for each comment. There can be no comments, 1 comment or multiple comments per item.
So what i want to achieve is concatenating all comments (if there are any) into the same row.

I tried using a repeater doing the following steps:

adding the repeater from the toolbox giving it the same query as the
list

"unlocking" the report to be able to make changes to the layout

placing the data item from the comment column into the repeater

placing the repeater containing the data item back into the column

Unfortunately this doesn't change anything. Any help would be much appreciated.

PS: Of course i used the available training resources (manuals & recorded training sessions) provided by concur concerning their reporting solution. However, these are rather low level and very light on the issue of joining multiple queries.

答:
The steps assume you have already got Associate in Nursing existing list with the columns, aside from comment, that you simply want:

Move as well as create a new list object to the end of the initial
list and choose from the conversation that came up the correct query.

You can see the outer list's last column containing its own
unoccupied list.

Push and locate the comment section in the inside list

Choose the object from the list inside. it either click on the three
red dots in the list's top left corner or select them from the
various properties dialog.

Click the property of Master Detail Relationships.

Click the New Link button at the top and try to select the right and
left columns and click ok again


问:
Reading a json file from s3 bucket
"I have a File on amazon s3 bucket with the url,the file is in json format,i want to read the file and store it in list in flutter"</p>

```<code>HttpClient().getUrl(Uri.parse("mobile_app_air_ports.json"))
.then((HttpClientRequest request)=> request.close())
.then((HttpClientResponse response){
Future<List<String>>
test=response.transform(Utf8Decoder()).toList();
});
</code>```

答:
You need to create your data model, then parse your JSON:</p>

```<code>import 'dart:convert';

class YourDataModel {
  final String yourData;

  Post({this.yourData});

  YourDataModel.fromJson(Map<String, dynamic> json) {
    return YourDataModel(
      yourData: json['yourData'],
    );
  }
}
</code>```

```<code>Future<List<String>> fetchData() async {
  final response =
      await http.get('mobile_app_air_ports');

  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return (json.decode(response.body) as List<dynamic>)
        .map<YourDataModel>((item) => YourDataModel.fromMap(item))
        .toList();

  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}
</code>```

Title: Reading a json file from s3 bucket

Body:
"I have a File on amazon s3 bucket with the url,the file is in json format,i want to read the file and store it in list in flutter"

HttpClient().getUrl(Uri.parse("mobile_app_air_ports.json"))
.then((HttpClientRequest request)=> request.close())
.then((HttpClientResponse response){
Future<List<String>>
test=response.transform(Utf8Decoder()).toList();
});

Body:
You need to create your data model, then parse your JSON:

import 'dart:convert';

class YourDataModel {
  final String yourData;

  Post({this.yourData});

  YourDataModel.fromJson(Map<String, dynamic> json) {
    return YourDataModel(
      yourData: json['yourData'],
    );
  }
}

Future<List<String>> fetchData() async {
  final response =
      await http.get('mobile_app_air_ports');

  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return (json.decode(response.body) as List<dynamic>)
        .map<YourDataModel>((item) => YourDataModel.fromMap(item))
        .toList();

  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}


问:
Creating Windows 10 Transparency effects in c# form
How do you create the transparency effects that you see in windows 10? Something like this:

I have no clue how to approach this in c#. Logically thinking I would take a snapshot of the desktop every time the form comes into focus. Then blur it and place it at 0, 0(screen to client coordinates). That doesn't seem very effective. Any help? Again. not an experienced C# programmer, so a detailed explanation would be much appreciated

Edit: I saw some the answers referring me to a page for alpha blending. This is not what I am looking for. I wanted to know how to create the blur that you see in the image, the rest I can figure out at my own pace

答:
You can get that by using some algorithms

I don't know will it work or not. When I see your post I just think and got this concept.

Get entire windows desktop wallpaper image by using copyscreen method

Draw that image into a new bitmap where bitmap width = screen resolution.width and bitmap height = screen resolution.height eg: Bitmap bm = new Bitmap (1920, 1080)

Learn how to blur a bitmap image in c#. There is many of blogs teaching how to blur a bitmap programmatically.

Make blur of captured desktop wallpaper image

Put a picture of inside the form and draw the blurred bitmap into picturebox

You can make FormBorderStyle.None to get rid of old borders

You should keep picturebox picture style = normal in order to get full blurred image


问:
How to use gyro data with RBPF SLAM?
I'm using CMetricMapBuilderRBPF in MRPT to do SLAM, but after the robot makes sharp turns, subsequent LIDAR observations are not correctly aligned with the rest of the map. The robot has a very accurate DSP-3000 gyro, and I'd like to use this orientation data to improve the performance of the SLAM process. What is the best approach to using this gyro data for SLAM within MRPT? Thank you.</p>

答:
There's at present no straight-forward way to do what you want...
You could "improve" the odometry readings by using the heading from the gyro, for example.

Or you could just increase the uncertainty of rotations in the noise model of odometry.

Title: How to use gyro data with RBPF SLAM?


问:
Why filter not working on list of strings
I am trying to write code to read a text file and to filter out those lines which have both search items:

```<code>import std.stdio;
import std.string;
import std.file : readText;
import std.algorithm;

void main(){
    string[] srchitems = ["second", "pen"];  // to search file text for lines which have both these;
    auto alltext = readText("testing.txt");
    auto alllist = alltext.split("\n");
    foreach(str; srchitems){
        alllist = alllist.filter!(a => a.indexOf(str) >= 0);    // not working ;
    }
    writeln(alllist);
}
</code>```

However, it is not working and giving this error:

```<code>$ rdmd soq_filter.d
soq_filter.d(11): Error: cannot implicitly convert expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_filter.d", "-I."]
</code>```

Following line with cast also does not work:

```<code>    alllist = cast(string[]) alllist.filter!(a => a.indexOf(str) >= 0);     // not working ;
</code>```

Error:

```<code>Error: cannot cast expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
</code>```

Where is the problem and how can it be solved? Thanks.

答:
As you have figured out, the return value from filter isn't an array, but a custom range. filter's return value is in fact a lazy range, so that if you only use the first few items only those items will be calculated. To convert a lazy range into an array, you will need to use std.array.array:

```<code>import std.array : array;
alllist = alllist.filter!(a => a.indexOf(str) >= 0).array;
</code>```

In your case, that seems to work well. However, by slightly restructuring your code, there is a more idiomatic solution:

```<code>import std.stdio;
import std.string;
import std.file : readText;
import std.algorithm;
import std.array;

void main() {
    string[] srchitems = ["second", "pen"];
    auto alltext = readText("testing.txt");
    auto alllist = alltext.split("\n");
    auto results = alllist.filter!(a => srchitems.any!(b => a.indexOf(b) >= 0));
    writeln(results);
}
</code>```

In the above code, we use the result of filter directly, rather than convert it to an array.

Body:
I am trying to write code to read a text file and to filter out those lines which have both search items:

import std.stdio;
import std.string;
import std.file : readText;
import std.algorithm;

void main(){
    string[] srchitems = ["second", "pen"];  // to search file text for lines which have both these;
    auto alltext = readText("testing.txt");
    auto alllist = alltext.split("\n");
    foreach(str; srchitems){
        alllist = alllist.filter!(a => a.indexOf(str) >= 0);    // not working ;
    }
    writeln(alllist);
}

However, it is not working and giving this error:

$ rdmd soq_filter.d
soq_filter.d(11): Error: cannot implicitly convert expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_filter.d", "-I."]

Following line with cast also does not work:

    alllist = cast(string[]) alllist.filter!(a => a.indexOf(str) >= 0);     // not working ;

Error:

Error: cannot cast expression filter(alllist) of type FilterResult!(__lambda1, string[]) to string[]

Where is the problem and how can it be solved? Thanks.

Body:
As you have figured out, the return value from filter isn't an array, but a custom range. filter's return value is in fact a lazy range, so that if you only use the first few items only those items will be calculated. To convert a lazy range into an array, you will need to use std.array.array:

import std.array : array;
alllist = alllist.filter!(a => a.indexOf(str) >= 0).array;

In your case, that seems to work well. However, by slightly restructuring your code, there is a more idiomatic solution:

import std.stdio;
import std.string;
import std.file : readText;
import std.algorithm;
import std.array;

void main() {
    string[] srchitems = ["second", "pen"];
    auto alltext = readText("testing.txt");
    auto alllist = alltext.split("\n");
    auto results = alllist.filter!(a => srchitems.any!(b => a.indexOf(b) >= 0));
    writeln(results);
}

In the above code, we use the result of filter directly, rather than convert it to an array.


问:
Uses of T extends U?
Lately I encountered a method defined similar to this and I don't exactly understand its usage:

```<code>public static <T, U extends T> T foo(U u) { ... }
</code>```

A sample use could be like this:

```<code>// Baz is just the containing class of foo()
Number n = Baz.foo(1);
</code>```

Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:

```<code>public static <T> T bar(T t) { ... }
</code>```

If I call it like this:

```<code>Number n = Baz.bar(2);
</code>```

The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)

I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.

答:
My first thought was: heck,

```<code>Number n = Baz.bar(2);
</code>```

would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!

Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!

Something like

```<code>class B { }
class C extends B { }
</code>```

now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.

In other words: the U extends T allows you to return instances of B and C. T alone: only C!

But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!

So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.

Title: Uses of T extends U?

Body:
Lately I encountered a method defined similar to this and I don't exactly understand its usage:

public static <T, U extends T> T foo(U u) { ... }

A sample use could be like this:

// Baz is just the containing class of foo()
Number n = Baz.foo(1);

Where T is inferred to Number and U (probably) to Integer. But I can't wrap my head around when this is superior to e.g. this method definition:

public static <T> T bar(T t) { ... }

If I call it like this:

Number n = Baz.bar(2);

The code still works. T is inferred to either Number or Integer (Don't know if the argument type, in this example Integer is preferred over the call site return type Number)

I've read these questions: 1, 2 but I still don't know if the first method with 2 parameters has any advantage over the second method with only one generic.

Body:
My first thought was: heck,

Number n = Baz.bar(2);

would "always" work, as Integer extends Number. So there is no advantage of doing that. But what if you had a super class that wasn't abstract?!

Then the U extends T allows you to return an object that is only of the supertype class, but not of the child class!

Something like

class B { }
class C extends B { }

now that generic method can return an instance of B, too. If there is just a T ... then the method can only return instances of C.

In other words: the U extends T allows you to return instances of B and C. T alone: only C!

But of course, the above makes sense when you look at some specific B and C. But when a method is (in reality) simply returning an instance of B, why would one need generics here in the first place?!

So, I concur with the question: I can't see the practical value of this construct either. Unless one gets into reflection, but even then I don't see a sound design that could only work because of U extends T.


问:
Display used CPU hours with slurm
I have a user account on a super computer where jobs are handled with slurm.

I would like to know the total amount of CPU hours that I have consumed on this super computer. I think that's an understandable question, because there is only a limited number of CPU hours available per project. I'm surprised that an answer is not easy to find.

I know that there are all these commands like sacct, sreport, sshare, etc... but it seems that there is no simple command that displays the used CPU hours.

Can someone help me out?

答:
You can get an overview of the used CPU hours with the following:

sacct -SYYYY-mm-dd -u username -ojobid,start,end,alloccpu,cputime | column -t

You will could calculate the total accounting units (SBU in our system) multiplying CPUTime by AllocCPU which means multiplying the total (sysem+user) CPU time by the amount of CPU used.

An example:

```<code>    JobID         NodeList         State       Start                End                  AllocCPUS   CPUTime
------------  ---------------  ----------  -------------------  -------------------  ----------  ----------
6328552       tcn[595-604]     CANCELLED+  2019-05-21T14:07:57  2019-05-23T16:48:15  240         506-17:12:00
6328552.bat+  tcn595           CANCELLED   2019-05-21T14:07:57  2019-05-23T16:48:16  24          50-16:07:36
6328552.0     tcn[595-604]     FAILED      2019-05-21T14:10:37  2019-05-23T16:48:18  240         506-06:44:00
6332520       tcn[384,386,45+  COMPLETED   2019-05-23T16:06:04  2019-05-24T00:26:36  72          25-00:38:24
6332520.bat+  tcn384           COMPLETED   2019-05-23T16:06:04  2019-05-24T00:26:36  24          8-08:12:48
6332520.0     tcn[384,386,45+  COMPLETED   2019-05-23T16:06:09  2019-05-24T00:26:33  60          20-20:24:00
6332530       tcn[37,41,44,4+  FAILED      2019-05-23T17:11:31  2019-05-25T09:13:34  240         400-08:12:00
6332530.bat+  tcn37            FAILED      2019-05-23T17:11:31  2019-05-25T09:13:34  24          40-00:49:12
6332530.0     tcn[37,41,44,4+  CANCELLED+  2019-05-23T17:11:35  2019-05-25T09:13:34  240         400-07:56:00
</code>```

The fields are shown in the the manpage. They can be shown as -oOPTION (in lower case or in proper POSIX notation --format='Option,AnotherOption...' (a list is in the man).

So far so good. But there is a big caveat here:

What you see here is perfect to get an idea of what you have run or what to expect in terms of CPU / hours. But this will not necessarily reflect your real budget status, as in many cases each node / partition may have an extra parameter, the weight, which is a parameter set for accounting purposes and not part of SLURM. For instance,the GPU nodes may have a weight value of x3, which means that each GPU/hour is measured as 3 SBU instead of 1 for budgetary purposes. What I mean to say is that you can use sacct to gain insight on the CPU times but this will not necessarily reflect how much SBU credits you still have.

Title: Display used CPU hours with slurm

Body:
You can get an overview of the used CPU hours with the following:

sacct -SYYYY-mm-dd -u username -ojobid,start,end,alloccpu,cputime | column -t

You will could calculate the total accounting units (SBU in our system) multiplying CPUTime by AllocCPU which means multiplying the total (sysem+user) CPU time by the amount of CPU used.

An example:

    JobID         NodeList         State       Start                End                  AllocCPUS   CPUTime
------------  ---------------  ----------  -------------------  -------------------  ----------  ----------
6328552       tcn[595-604]     CANCELLED+  2019-05-21T14:07:57  2019-05-23T16:48:15  240         506-17:12:00
6328552.bat+  tcn595           CANCELLED   2019-05-21T14:07:57  2019-05-23T16:48:16  24          50-16:07:36
6328552.0     tcn[595-604]     FAILED      2019-05-21T14:10:37  2019-05-23T16:48:18  240         506-06:44:00
6332520       tcn[384,386,45+  COMPLETED   2019-05-23T16:06:04  2019-05-24T00:26:36  72          25-00:38:24
6332520.bat+  tcn384           COMPLETED   2019-05-23T16:06:04  2019-05-24T00:26:36  24          8-08:12:48
6332520.0     tcn[384,386,45+  COMPLETED   2019-05-23T16:06:09  2019-05-24T00:26:33  60          20-20:24:00
6332530       tcn[37,41,44,4+  FAILED      2019-05-23T17:11:31  2019-05-25T09:13:34  240         400-08:12:00
6332530.bat+  tcn37            FAILED      2019-05-23T17:11:31  2019-05-25T09:13:34  24          40-00:49:12
6332530.0     tcn[37,41,44,4+  CANCELLED+  2019-05-23T17:11:35  2019-05-25T09:13:34  240         400-07:56:00

The fields are shown in the the manpage. They can be shown as -oOPTION (in lower case or in proper POSIX notation --format='Option,AnotherOption...' (a list is in the man).

So far so good. But there is a big caveat here:

What you see here is perfect to get an idea of what you have run or what to expect in terms of CPU / hours. But this will not necessarily reflect your real budget status, as in many cases each node / partition may have an extra parameter, the weight, which is a parameter set for accounting purposes and not part of SLURM. For instance,the GPU nodes may have a weight value of x3, which means that each GPU/hour is measured as 3 SBU instead of 1 for budgetary purposes. What I mean to say is that you can use sacct to gain insight on the CPU times but this will not necessarily reflect how much SBU credits you still have.


问:
How Recursion works in C
I am new to C and I'm reading about recursion, but I am totally confused.

The main part where I'm getting confused is how things get unwind when the exit condition is reached. I would like to know how during recursion values got pushed and popped from stack.

Also can anyone please give me a diagramatic  view of recursion?

Thanks...

答: An alternative answer is that in general you don't know. C as a language doesn't have any stack of heap. Your compiler uses a memory location called the stack to store control flow information such as stack frames, return addresses and registers, but there is nothing in C prohibiting the compiler to store that information elsewhere. For practical aspects the previous answers are correct. This is how C compilers operate today.</p>

Title: How Recursion works in C


问:
Fast way to find number of common items python
I have a large data of 145000 items (a bill of materials) and I want to check the % of shared items between two bill of materials.

Two for loops or other methods always run in similar time periods.

What is the fastest way to do this?

First&secondbill are the lists with components in them:

```<code>for FKid in FirstBill:
      for SKid in SecondBill:
            CommonChild = (CommonChild + 1) if FKid == SKid else CommonChild
    return CommonChilds / len(FirstBill)
</code>```

答:
Kinda optimal to use one set</p>

```<code># Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
    temp = set(lst2)
    lst3 = [value for value in lst1 if value in temp ]
    return lst3

# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
#print(intersection(lst1, lst2))

quantity = len(intersection(lst1, lst2))
</code>```

Body:
I have a large data of 145000 items (a bill of materials) and I want to check the % of shared items between two bill of materials.

Two for loops or other methods always run in similar time periods.

What is the fastest way to do this?

First&secondbill are the lists with components in them:

for FKid in FirstBill:
      for SKid in SecondBill:
            CommonChild = (CommonChild + 1) if FKid == SKid else CommonChild
    return CommonChilds / len(FirstBill)

Body:
Kinda optimal to use one set

# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
    temp = set(lst2)
    lst3 = [value for value in lst1 if value in temp ]
    return lst3

# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
#print(intersection(lst1, lst2))

quantity = len(intersection(lst1, lst2))


问:
TypeError: a bytes-like object is required, not 'str' while using kinit.stdin.write('%s\n' % password)
I am trying to connect to SQL server from Linux machine using python. However facing an issue while trying to get the kerbos ticket. Below is the code i am using.

```<code># Login Credentials
userid = "username"
password = "password"
realm="realm.com"
kinit = '/usr/bin/kinit'

# Get Fresh Kerberos Ticket
kinit_args = [ kinit, '%s@%s' % (userid, realm) ]
kinit = Popen(kinit_args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
kinit.stdin.write('%s\n' % password)
kinit.wait()

Error message displayed :
Traceback (most recent call last):
    File "poc_test1.py", line 25, in <module>
      kinit.stdin.write('%s\n' % password)
TypeError: a bytes-like object is required, not 'str'
</code>```

Thanks in advance.

答:
You need to encode() the write-string as bytes so python knows how to send the correct bytes over the pipe.

Change the line like to look like this:

kinit.stdin.write('{}\n'.format(password).encode('utf-8'))
```

<p>The <code>"".format()</code> is a newer version of the old format string syntax. Afterwards its encoded to bytes assuming UTF-8 encoding for the password string, which should be default.</p>

<p>But I would also suggest replacing the <code>stdin.write</code> and <code>wait</code> with the newer communicate which should look like this:</p>

<pre class="lang-py prettyprint-override"><code>kinit = Popen(kinit_args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
kinit.communicate(input="{}\n".format(password).encode("utf-8"))
</code>```

Body:
I am trying to connect to SQL server from Linux machine using python. However facing an issue while trying to get the kerbos ticket. Below is the code i am using.

# Login Credentials
userid = "username"
password = "password"
realm="realm.com"
kinit = '/usr/bin/kinit'

# Get Fresh Kerberos Ticket
kinit_args = [ kinit, '%s@%s' % (userid, realm) ]
kinit = Popen(kinit_args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
kinit.stdin.write('%s\n' % password)
kinit.wait()

Error message displayed :
Traceback (most recent call last):
    File "poc_test1.py", line 25, in <module>
      kinit.stdin.write('%s\n' % password)
TypeError: a bytes-like object is required, not 'str'

Thanks in advance.

Body:
You need to encode() the write-string as bytes so python knows how to send the correct bytes over the pipe.

Change the line like to look like this:

kinit.stdin.write('{}\n'.format(password).encode('utf-8'))

The "".format() is a newer version of the old format string syntax. Afterwards its encoded to bytes assuming UTF-8 encoding for the password string, which should be default.

But I would also suggest replacing the stdin.write and wait with the newer communicate which should look like this:

kinit = Popen(kinit_args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
kinit.communicate(input="{}\n".format(password).encode("utf-8"))


问:
@Autowired @Service Bean is null although set up properly
I get this error during start of my Spring Boot 2.1.4 based application:

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [test.services.AlmConnectivity]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1295) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 22 common frames omitted
Caused by: java.lang.NullPointerException: null
    at test.services.AlmConnectivity.initProxyBean(AlmConnectivity.java:43) ~[classes/:na]
    at test.services.AlmConnectivity.<init>(AlmConnectivity.java:30) ~[classes/:na]
</code>```

The mentioned line 43 is the one that starts with proxy =:

```<code>@DependsOn({ "config", "cfg" })
private void initProxyBean() {
    System.err.println("Config: " + config);
    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
}
</code>```

System.err prints null too. As you can see I tried to signal dependencies using @DependsOn.

These are the (I guess) other relevant parts of the class:

```<code>@Service
public class AlmConnectivity {
    Logger log = LoggerFactory.getLogger(AlmConnectivity.class);

    @Autowired
    @Qualifier("config")
    Config config;

    private Proxy proxy;

    private OkHttpClient client;

    public AlmConnectivity() {
        initProxyBean();
        initClientBean(proxy);
    }
</code>```

Because I prefer shorter names I used @Qualifier, but even if I skip this and take the bean with its full name config it doesn't work and config stays null.

This is the config class:

```<code>@Component
public class Config {

    @NotNull
    @NotEmpty
    @Value("${proxy.host}")
    private String proxyHost = "i.am.desparate";

    @NotNull
    @NotEmpty
    @Value("${proxy.port}")
    private int proxyPort = 8090;

    public String getProxyHost() {
        return proxyHost;
    }

    public int getProxyPort() {
        return proxyPort;
    }
}
</code>```

My main class carries these annotations:

```<code>@SpringBootApplication
@EnableScheduling
@Configuration
@ComponentScan
@EnableAutoConfiguration
</code>```

(The latter three were added during my attempts to get this running)

答:
Just to add an information on the answer provided above by Smutje:

Bean constructors are meant to create instances of the bean.

Spring first calls the Bean constructor, and only after that, when there is an instance of the bean, calls Autowiring logic (You can read about bean post processors in Spring to understand exactly how they work, its out of scope for this question, though).

After the Autowiring logic is done and all the autowired fields are injected, Spring calls method annotated with @PostConstruct.

This is the place where you can initialize your code.

So one of the possible answers is indeed using the bean post constructor.

Another way is to stop using Field Injection in favor of Constructor Injection:

```<code>@Service
public class AlmConnectivity {

  @Autowired // optional annotation in modern spring if you have a single constructor
  public AlmConnectivity(@Qualifier("config") Config  config) {
       // here config is not null, so you can init proxy
  }
}
</code>```

Body:
I get this error during start of my Spring Boot 2.1.4 based application:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [test.services.AlmConnectivity]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1295) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 22 common frames omitted
Caused by: java.lang.NullPointerException: null
    at test.services.AlmConnectivity.initProxyBean(AlmConnectivity.java:43) ~[classes/:na]
    at test.services.AlmConnectivity.<init>(AlmConnectivity.java:30) ~[classes/:na]

The mentioned line 43 is the one that starts with proxy =:

@DependsOn({ "config", "cfg" })
private void initProxyBean() {
    System.err.println("Config: " + config);
    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyHost(), config.getProxyPort()));
}

System.err prints null too. As you can see I tried to signal dependencies using @DependsOn.

These are the (I guess) other relevant parts of the class:

@Service
public class AlmConnectivity {
    Logger log = LoggerFactory.getLogger(AlmConnectivity.class);

    @Autowired
    @Qualifier("config")
    Config config;

    private Proxy proxy;

    private OkHttpClient client;

    public AlmConnectivity() {
        initProxyBean();
        initClientBean(proxy);
    }

Because I prefer shorter names I used @Qualifier, but even if I skip this and take the bean with its full name config it doesn't work and config stays null.

This is the config class:

@Component
public class Config {

    @NotNull
    @NotEmpty
    @Value("${proxy.host}")
    private String proxyHost = "i.am.desparate";

    @NotNull
    @NotEmpty
    @Value("${proxy.port}")
    private int proxyPort = 8090;

    public String getProxyHost() {
        return proxyHost;
    }

    public int getProxyPort() {
        return proxyPort;
    }
}

My main class carries these annotations:

@SpringBootApplication
@EnableScheduling
@Configuration
@ComponentScan
@EnableAutoConfiguration

(The latter three were added during my attempts to get this running)

Body:
Just to add an information on the answer provided above by Smutje:

Bean constructors are meant to create instances of the bean.

Spring first calls the Bean constructor, and only after that, when there is an instance of the bean, calls Autowiring logic (You can read about bean post processors in Spring to understand exactly how they work, its out of scope for this question, though).

After the Autowiring logic is done and all the autowired fields are injected, Spring calls method annotated with @PostConstruct.

This is the place where you can initialize your code.

So one of the possible answers is indeed using the bean post constructor.

Another way is to stop using Field Injection in favor of Constructor Injection:

@Service
public class AlmConnectivity {

  @Autowired // optional annotation in modern spring if you have a single constructor
  public AlmConnectivity(@Qualifier("config") Config  config) {
       // here config is not null, so you can init proxy
  }
}


问:
Why is a named rvalue reference an lvalue expression?
I know that a named reference is an lvalue:

```<code>int x = 1;
int& ref1 = x;
int&& ref2 = std::move(x);
</code>```

I've read the explanation — that is because we can take the address of those ref1 and ref2.

But when we take the address of a reference we actually take the address of the referenced object, don't we? So this explanation doesn't seem to be correct.

So why a named reference is an lvalue?

答:
That explanation is just a simplification. lvalues aren't defined by being "something you can take the address of", but by a specific set of rules about the value category of expressions. Those rules are carefully constructed so as to result in a self-consistent language in which everything fits together reasonably neatly.

That being said, the explanation does rather fit here, if you consider that by writing ref1, you're not really naming "the reference" but the thing being referred to. That's the magic of references: you're supposed to consider them name aliases rather than entities in their own right.

There are some abstraction leaks surrounding this (particularly, member references), but that's the gist.

You ought to forget about notions like "the reference is an lvalue" and instead think about expressions. Objects have types; expressions have value categories.

Body:
I know that a named reference is an lvalue:

int x = 1;
int& ref1 = x;
int&& ref2 = std::move(x);

I've read the explanation — that is because we can take the address of those ref1 and ref2.

But when we take the address of a reference we actually take the address of the referenced object, don't we? So this explanation doesn't seem to be correct.

So why a named reference is an lvalue?


问:
Postgres closes connection during query after a few hundred seconds when using Psycopg2
I'm running PostgreSQL 9.6 (in Docker, using the postgres:9.6.13 image) and psycopg2 2.8.2.

My PostgreSQL server (local) hosts two databases. My goal is to create materialized views in one of the databases that use data from the other database using Postgres's foreign data wrappers. I do all this from a Python script that uses psycopg2.

This works well as long as creating the materialized view does not take too long (i.e. if the amount of data being imported isn't too large). However, if the process takes longer than roughly ~250 seconds, psycopg2 throws the exception

```<code>psycopg2.OperationalError: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
</code>```

No error message (or any message concerning this whatsoever) can be found in Postgres's logs.

Materialized view creation completes successfully if I do it from an SQL client (Postico).

This code illustrates roughly what I'm doing in the Python script:

db = pg.connect(
    dbname=config.db_name,
    user=config.db_user,
    password=config.db_password,
    host=config.db_host,
    port=config.db_port
)
with db.cursor() as c:
    c.execute("""
        CREATE EXTENSION IF NOT EXISTS postgres_fdw;
        CREATE SERVER fdw FOREIGN DATA WRAPPER postgres_fdw OPTIONS (...);
        CREATE USER MAPPING FOR CURRENT_USER SERVER fdw OPTIONS (...);
        CREATE SCHEMA foreign;
        IMPORT FOREIGN SCHEMA foreign_schema FROM SERVER fdw INTO foreign;
    """)
    c.execute("""
        CREATE MATERIALIZED VIEW IF NOT EXISTS my_view AS (
            SELECT (...)
            FROM foreign.foreign_table
        );
    """)
```

答:
Adding the keepalive parameters to the psycopg2.connect call seems to have solved the problem:

self.db = pg.connect(
            dbname=config.db_name,
            user=config.db_user,
            password=config.db_password,
            host=config.db_host,
            port=config.db_port,
            keepalives=1,
            keepalives_idle=30,
            keepalives_interval=10,
            keepalives_count=5
        )
```

I still don't know why this is necessary. I can't find anyone else who has described having to use the keepalives parameter keywords when using Postgres in Docker just to be able to run queries that take longer than 4-5 minutes, but maybe it's obvious enough that nobody has noted it?

Body:
I'm running PostgreSQL 9.6 (in Docker, using the postgres:9.6.13 image) and psycopg2 2.8.2.

My PostgreSQL server (local) hosts two databases. My goal is to create materialized views in one of the databases that use data from the other database using Postgres's foreign data wrappers. I do all this from a Python script that uses psycopg2.

This works well as long as creating the materialized view does not take too long (i.e. if the amount of data being imported isn't too large). However, if the process takes longer than roughly ~250 seconds, psycopg2 throws the exception

psycopg2.OperationalError: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.

No error message (or any message concerning this whatsoever) can be found in Postgres's logs.

Materialized view creation completes successfully if I do it from an SQL client (Postico).

This code illustrates roughly what I'm doing in the Python script:

db = pg.connect(
    dbname=config.db_name,
    user=config.db_user,
    password=config.db_password,
    host=config.db_host,
    port=config.db_port
)
with db.cursor() as c:
    c.execute("""
        CREATE EXTENSION IF NOT EXISTS postgres_fdw;
        CREATE SERVER fdw FOREIGN DATA WRAPPER postgres_fdw OPTIONS (...);
        CREATE USER MAPPING FOR CURRENT_USER SERVER fdw OPTIONS (...);
        CREATE SCHEMA foreign;
        IMPORT FOREIGN SCHEMA foreign_schema FROM SERVER fdw INTO foreign;
    """)
    c.execute("""
        CREATE MATERIALIZED VIEW IF NOT EXISTS my_view AS (
            SELECT (...)
            FROM foreign.foreign_table
        );
    """)

Body:
Adding the keepalive parameters to the psycopg2.connect call seems to have solved the problem:

self.db = pg.connect(
            dbname=config.db_name,
            user=config.db_user,
            password=config.db_password,
            host=config.db_host,
            port=config.db_port,
            keepalives=1,
            keepalives_idle=30,
            keepalives_interval=10,
            keepalives_count=5
        )

I still don't know why this is necessary. I can't find anyone else who has described having to use the keepalives parameter keywords when using Postgres in Docker just to be able to run queries that take longer than 4-5 minutes, but maybe it's obvious enough that nobody has noted it?


问:
how to find ms word installation path using C#
I am trying to get the installation path of ms word through my code so that I can put its icon in my excel sheet generated through my c# code.

Tried this but no luck.

Here I am trying to get the icon using the whole word installation oath which I know in my device but I want to generalize it.

worksheet.Shapes.AddOLEObject(Filename:
  @"C:\Users\BJS\Desktop\POC\wordFile.docx", Height: 80, Width: 90,
  DisplayAsIcon: true, IconFileName: @"C:\Program Files (x86)\Microsoft
  Office\Office12\WINWORD.EXE", IconIndex: 2, IconLabel: "WordFile",
  Top: _rng.Top, Left: _rng.Left);

Generalize the path which will work for all users

答:
I think you can archieve that with the registryeditor.
Open the key HKEY_Classes_Root\Word.Application\CLSID and save the Key Value.
Search it in HKEY_Classes_Root\WOW6432Node\CLSID\{your_value}\Localserver32 (that's works for x64 systems, for x32 if i remmember right the path is "System" and not "WOW6432Node").

For how to read a registrykey in c# you can follow that SO link

As @Slai Say, that Will work only if you are Talking of server word Path and not browser user path