问:
nodejs with docker and postgress: Error: getaddrinfo ENOTFOUND
Hello I don't know what else to do to resolve this error:

```<code>    ci-api    | Error: getaddrinfo ENOTFOUND ${DB_HOST}
    ci-api    |     at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
    ci-api    |   errno: 'ENOTFOUND',
    ci-api    |   code: 'ENOTFOUND',
    ci-api    |   syscall: 'getaddrinfo',
    ci-api    |   hostname: '${DB_HOST}'
    ci-api    | }
</code>```

I have a .env file with the following variables:

.env file:

```<code>    SERVER_PORT=4000
    DB_HOST=db-pg
    DB_PORT=5432
    DB_USER=spirit
    DB_PASS=api
    DB_NAME=emasa_ci
</code>```

DockerFile:

```<code>    #building code
    FROM node:lts-alpine

    ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.7.3/wait /wait
    RUN chmod +x /wait

    RUN mkdir -p /home/node/api && chown -R node:node /home/node/api

    WORKDIR /home/node/api

    COPY ormconfig.json .env package.json yarn.* ./

    USER node

    RUN yarn

    COPY --chown=node:node . .
    EXPOSE 4000

**My `docker-compose`:**

    version: '3.7'
    services:
      db-pg:
        image: postgres:12
        container_name: db-pg
        ports:
          - '${DB_PORT}:5432'
        environment:
          ALLOW_EMPTY_PASSWORD: 'no'
          POSTGRES_USER: ${DB_USER}
          POSTGRES_PASSWORD: ${DB_PASS}
          POSTGRES_DB: ${DB_NAME}
        volumes:
          - ci-postgres-data:/data

      ci-api:
        build: .
        container_name: ci-api
        volumes:
          - .:/home/node/api
        ports:
          - '${SERVER_PORT}:${SERVER_PORT}'
        depends_on:
          - db-pg
        command: sh -c "/wait && yarn dev"
        environment:
          WAIT_HOSTS: db-pg:5432
        logging:
          driver: 'json-file'
          options:
            max-size: '10m'
            max-file: '5'

    volumes:
      ci-postgres-data:
</code>```

And, this is my ORM CONFIG:

```<code>    {
      "type": "postgres",
      "host": "${DB_HOST}",
      "port": "${DB_PORT}",
      "username": "${DB_USER}",
      "password": "${DB_PASS}",
      "database": "${DB_NAME}",
      "synchronize": true,
      "logging": false,
      "entities": ["dist/src/entity/**/*.js"],
      "migrations": ["dist/src/migration/**/*.js"],
      "subscribers": ["dist/src/subscriber/**/*.js"],
      "cli": {
        "entitiesDir": "dist/src/entity",
        "migrationsDir": "dist/src/migration",
        "subscribersDir": "dist/src/subscriber"
      }
    }
</code>```

I can't imagine the reason for this error, I basically added a script for the node to start after the start of my Postgres where db-pg is my Postgres image name.

I can't imagine what went wrong, could someone help me with this?

P.S.: I use typescript/typeorm

答:
```<code>{
  "type": "postgres",
  "host": "db-pg",
  "port": 5432,
  "username": "spirit",
  "password": "api",
  "database": "emasa_ci",
  "synchronize": true,
  "logging": false,
  "entities": ["dist/src/entity/**/*.js"],
  "migrations": ["dist/src/migration/**/*.js"],
  "subscribers": ["dist/src/subscriber/**/*.js"],
  "cli": {
    "entitiesDir": "dist/src/entity",
    "migrationsDir": "dist/src/migration",
    "subscribersDir": "dist/src/subscriber"
  }
}
</code>```

the problem was in my
ormconfig.json (was using .env)

Body:
Hello I don't know what else to do to resolve this error:

    ci-api    | Error: getaddrinfo ENOTFOUND ${DB_HOST}
    ci-api    |     at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) {
    ci-api    |   errno: 'ENOTFOUND',
    ci-api    |   code: 'ENOTFOUND',
    ci-api    |   syscall: 'getaddrinfo',
    ci-api    |   hostname: '${DB_HOST}'
    ci-api    | }

I have a .env file with the following variables:

.env file:

    SERVER_PORT=4000
    DB_HOST=db-pg
    DB_PORT=5432
    DB_USER=spirit
    DB_PASS=api
    DB_NAME=emasa_ci

DockerFile:

    #building code
    FROM node:lts-alpine

    ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.7.3/wait /wait
    RUN chmod +x /wait

    RUN mkdir -p /home/node/api && chown -R node:node /home/node/api

    WORKDIR /home/node/api

    COPY ormconfig.json .env package.json yarn.* ./

    USER node

    RUN yarn

    COPY --chown=node:node . .
    EXPOSE 4000

**My `docker-compose`:**

    version: '3.7'
    services:
      db-pg:
        image: postgres:12
        container_name: db-pg
        ports:
          - '${DB_PORT}:5432'
        environment:
          ALLOW_EMPTY_PASSWORD: 'no'
          POSTGRES_USER: ${DB_USER}
          POSTGRES_PASSWORD: ${DB_PASS}
          POSTGRES_DB: ${DB_NAME}
        volumes:
          - ci-postgres-data:/data

      ci-api:
        build: .
        container_name: ci-api
        volumes:
          - .:/home/node/api
        ports:
          - '${SERVER_PORT}:${SERVER_PORT}'
        depends_on:
          - db-pg
        command: sh -c "/wait && yarn dev"
        environment:
          WAIT_HOSTS: db-pg:5432
        logging:
          driver: 'json-file'
          options:
            max-size: '10m'
            max-file: '5'

    volumes:
      ci-postgres-data:

And, this is my ORM CONFIG:

    {
      "type": "postgres",
      "host": "${DB_HOST}",
      "port": "${DB_PORT}",
      "username": "${DB_USER}",
      "password": "${DB_PASS}",
      "database": "${DB_NAME}",
      "synchronize": true,
      "logging": false,
      "entities": ["dist/src/entity/**/*.js"],
      "migrations": ["dist/src/migration/**/*.js"],
      "subscribers": ["dist/src/subscriber/**/*.js"],
      "cli": {
        "entitiesDir": "dist/src/entity",
        "migrationsDir": "dist/src/migration",
        "subscribersDir": "dist/src/subscriber"
      }
    }

I can't imagine the reason for this error, I basically added a script for the node to start after the start of my Postgres where db-pg is my Postgres image name.

I can't imagine what went wrong, could someone help me with this?

P.S.: I use typescript/typeorm

Body:
{
  "type": "postgres",
  "host": "db-pg",
  "port": 5432,
  "username": "spirit",
  "password": "api",
  "database": "emasa_ci",
  "synchronize": true,
  "logging": false,
  "entities": ["dist/src/entity/**/*.js"],
  "migrations": ["dist/src/migration/**/*.js"],
  "subscribers": ["dist/src/subscriber/**/*.js"],
  "cli": {
    "entitiesDir": "dist/src/entity",
    "migrationsDir": "dist/src/migration",
    "subscribersDir": "dist/src/subscriber"
  }
}

the problem was in my
ormconfig.json (was using .env)


来源: stackexchange

问:
React when pass data to child throw props data duplicate
I'm create Activities function component  and call child function  component called Categories  when i send categories list to Categories function  component and log "props" data send twice first one is empty and second has data as follow

Activies

```<code>function Activities() {
 const [category, setCategory] = useState([]);

  function handelChange({ target }) {
    setCategory({
      ...category,
      [target.name]: target.value,
    });
  }

  useEffect(() => {
    getCategories().then((_categories) => setCategory(_categories));
  }, []);

 return (<Categories category={category} onChange={handelChange} />)

}
</code>```

and categories component

```<code>function Categories(props) {
 console.log(props);

return (<div></div>)
}
</code>```

i'm trying to log props in useEffect but problem still exist

答:
This is happening because of how the life cycle in React works. This is correct and expected behavior. Before you load the categories, it is a blank array on the initial render. Then it gets the categories, updates the state, and re-renders, this time with categories.

renders with the initial state(empty)

goes and fetches categories

re-renders with the categories

This is entirely expected. That double log is the initial render and then the updated state render. Remember React is a heavily async library. The useEffect doesn't happen during render, it happens after render. Every state update will also cause an update and thus another log. It might be helpful to research what will cause a React render and how the life cycle behaves.

ContentLicense: CC BY-SA 4.0

Body:
I'm create Activities function component  and call child function  component called Categories  when i send categories list to Categories function  component and log "props" data send twice first one is empty and second has data as follow

Activies

function Activities() {
 const [category, setCategory] = useState([]);

  function handelChange({ target }) {
    setCategory({
      ...category,
      [target.name]: target.value,
    });
  }

  useEffect(() => {
    getCategories().then((_categories) => setCategory(_categories));
  }, []);

 return (<Categories category={category} onChange={handelChange} />)

}

and categories component

function Categories(props) {
 console.log(props);

return (

)
}

i'm trying to log props in useEffect but problem still exist


问:
Add rows in a gridview c#
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code: </p>

```<code>DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();
</code>```

答:
Hey Just check this. This might help u</p>

```<code>DataTable dataTable = new DataTable();

int columnsCount = // Set the number of the table's columns here.

for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
    DataColumn dataColumn = new DataColumn();
    // Assign dataColumn properties' values here ..
    dataTable.Columns.Add(dataColumn);
}

int rowsCount = // Set the number of the table's rows here.

for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
    DataRow dataRow = new DataRow();
    dataRow["ColumnName"] = // Set the value here ..
    dataTable.Rows.Add(dataRow);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add rows in a gridview c#

Body:
Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code:

DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");

DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();

gvQnA.DataSource = dt;
gvQnA.DataBind();

Body:
Hey Just check this. This might help u

DataTable dataTable = new DataTable();

int columnsCount = // Set the number of the table's columns here.

for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
    DataColumn dataColumn = new DataColumn();
    // Assign dataColumn properties' values here ..
    dataTable.Columns.Add(dataColumn);
}

int rowsCount = // Set the number of the table's rows here.

for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
    DataRow dataRow = new DataRow();
    dataRow["ColumnName"] = // Set the value here ..
    dataTable.Rows.Add(dataRow);
}


问:
C ncurses KEY_BACKSPACE not working
Im trying to work this code using the the nurses library. I'm trying to make it print the letter i whenever I press the backspace key, but it doesn't seem to be working. It seem pretty simple. It should be working but it isn't. am I missing something? Thanks in advance</p>

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

int main () {

  short ch;
  initscr();
  keypad(stdscr, TRUE);
  clear();
  noecho();
  ch = getch();

  while(ch != '\n') {
    if(ch == KEY_BACKSPACE) {
      mvaddch(90, 90, 'i');
    }
    ch = getch();
  }

  endwin();
}
</code>```

答:
Actually, getch() returns int, but not short or char. Try using int instead of char, as KEY_BACKSPACE consists of more then 1 byte.

Also, why not, consider using wgetch(window) instead of getch():

```<code>int ch;
ch = wgetch(<here put your window handler>)
</code>```

Also use int or uint32_t for ch instead of short int in this case, as BACKSPACE key code (KEY_BACKSPACE) returned by wgetch() also can use up to 4 bytes.

Title: C ncurses KEY_BACKSPACE not working

Body:
Im trying to work this code using the the nurses library. I'm trying to make it print the letter i whenever I press the backspace key, but it doesn't seem to be working. It seem pretty simple. It should be working but it isn't. am I missing something? Thanks in advance

#include <ncurses.h>
#include <stdio.h>

int main () {

  short ch;
  initscr();
  keypad(stdscr, TRUE);
  clear();
  noecho();
  ch = getch();

  while(ch != '\n') {
    if(ch == KEY_BACKSPACE) {
      mvaddch(90, 90, 'i');
    }
    ch = getch();
  }

  endwin();
}

Body:
Actually, getch() returns int, but not short or char. Try using int instead of char, as KEY_BACKSPACE consists of more then 1 byte.

Also, why not, consider using wgetch(window) instead of getch():

int ch;
ch = wgetch(<here put your window handler>)

Also use int or uint32_t for ch instead of short int in this case, as BACKSPACE key code (KEY_BACKSPACE) returned by wgetch() also can use up to 4 bytes.


问:
restart console on Minecraft Server
Please excuse me for my inexperience, I am very new to this.
I set up a server on Digital Ocean for Minecraft earlier today. I ran the command to create the world with java -Xmx1024M -Xms1024M -jar minecraft_server.1.15.2.jar nogui, and created a screen.
It gave me access to the console where I could type like /op  and other commands. Later on, I shut down, and now when I try to rejoin, I'm not sure how to get back to that console. I have more than 1 person on the server, who is on the console right now - I don't know if that should cause it any issue. When I retry to open the console with the command java -jar minecraft_server.jar It says there is already a server running (which there is) but I just want to get back to the console. </p>

<p>Thank you in advance. </p>

答:
If this is a linux vserver or root server, you can use the "screen" tool to access the minecraft console again.

Create a new startup script (start.sh) in the server directory to launch the JAR:

```<code> #!/bin/sh

screen -d -m -S "minecraft_screen" java -Xmx1024M -Xms1024M -jar minecraft_server.1.15.2.jar nogui
</code>```

Open your terminal and execute the following in the directory:

```<code>chmod +x start.sh
</code>```

Run your start up script:

```<code>./start.sh
</code>```

To access the minecraft screen use the command "screen -r".

To leave the minecraft screen press Ctrl + A + D

Title: restart console on Minecraft Server

Body:
Please excuse me for my inexperience, I am very new to this.
I set up a server on Digital Ocean for Minecraft earlier today. I ran the command to create the world with java -Xmx1024M -Xms1024M -jar minecraft_server.1.15.2.jar nogui, and created a screen.
It gave me access to the console where I could type like /op  and other commands. Later on, I shut down, and now when I try to rejoin, I'm not sure how to get back to that console. I have more than 1 person on the server, who is on the console right now - I don't know if that should cause it any issue. When I retry to open the console with the command java -jar minecraft_server.jar It says there is already a server running (which there is) but I just want to get back to the console.

Thank you in advance.

Body:
If this is a linux vserver or root server, you can use the "screen" tool to access the minecraft console again.

Create a new startup script (start.sh) in the server directory to launch the JAR:

 #!/bin/sh

screen -d -m -S "minecraft_screen" java -Xmx1024M -Xms1024M -jar minecraft_server.1.15.2.jar nogui

Open your terminal and execute the following in the directory:

chmod +x start.sh

Run your start up script:

./start.sh

To access the minecraft screen use the command "screen -r".

To leave the minecraft screen press Ctrl + A + D


问:
Laravel websocket cant connect to pusher ERR_CERT_AUTHORITY_INVALID
I have a laravel application with websockets. I already setup all the needs for the websocket and pusher config. But whenever I test my broadcast channel I got

app.js:58283 WebSocket connection to 'wss://127.0.0.1/app/644a4ac1988060882370?protocol=7&client=js&version=6.0.2&flash=false' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID

When i do some reload. sometimes i get
app.js:55791 WebSocket connection to 'wss://127.0.0.1/app/644a4ac1988060882370?protocol=7&client=js&version=6.0.2&flash=false' failed: WebSocket is closed before the connection is established.

Here are my configs.

broadcasting.php

```<code>   'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => true,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http',
            ],
        ],
</code>```

websockets.php

```<code>  'apps' => [
        [
            'id' => env('PUSHER_APP_ID'),
            'name' => env('APP_NAME'),
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'path' => env('PUSHER_APP_PATH'),
            'capacity' => null,
            'enable_client_messages' => false,
            'enable_statistics' => true,
            'verify_peer' => false,
        ],
    ],
</code>```

bootstrap.js

```<code>import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxxxxxx',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    // enabledTransports: ['ws', 'wss']
});

window.Echo.channel('Inventory').listen('InventoryEvent',(e)=>{
    console.log(e)
})
</code>```

web.php

```<code>Route::get('/', function () {
    broadcast(new InventoryEvent('somedata'));
    return view('welcome');
});
</code>```

InventoryEvent

```<code>namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class InventoryEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $somedata;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($somedata)
    {
        $this->somedata = $somedata;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('Inventory');
    }
}
</code>```

package.json

```<code>    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.0.0",
        "cross-env": "^7.0",
        "jquery": "^3.2",
        "laravel-mix": "^5.0.1",
        "lodash": "^4.17.13",
        "popper.js": "^1.12",
        "resolve-url-loader": "2.3.1",
        "sass": "^1.20.1",
        "sass-loader": "7.*",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    },
    "dependencies": {
        "admin-lte": "^3.0.4",
        "fusioncharts": "^3.15.1-sr.1",
        "laravel-echo": "^1.7.0",
        "pusher-js": "^6.0.2",
        "sweetalert2": "^9.10.9",
        "vue-fusioncharts": "^3.0.4",
        "vue-moment": "^4.1.0",
        "vue-router": "^3.1.6",
        "vue-select": "^3.9.5"
    }
</code>```

I already setup the env for my pusher credentials. Do i need to config something in my pusher in order for this to work? I got another project with the same setup but it works but this one is not.

答:
in your bootstrap.js file, try changing:

```<code>import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxxxxxx',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    forceTLS: false, //<<<<=====CHANGE THIS
    // enabledTransports: ['ws', 'wss']
});

window.Echo.channel('Inventory').listen('InventoryEvent',(e)=>{
    console.log(e)
})
</code>```

the default value of the forceTLS option is true, which forces listening on wss instead of ws.

Body:
I have a laravel application with websockets. I already setup all the needs for the websocket and pusher config. But whenever I test my broadcast channel I got

app.js:58283 WebSocket connection to 'wss://127.0.0.1/app/644a4ac1988060882370?protocol=7&client=js&version=6.0.2&flash=false' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID

When i do some reload. sometimes i get
app.js:55791 WebSocket connection to 'wss://127.0.0.1/app/644a4ac1988060882370?protocol=7&client=js&version=6.0.2&flash=false' failed: WebSocket is closed before the connection is established.

Here are my configs.

broadcasting.php

   'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => true,
                'host' => '127.0.0.1',
                'port' => 6001,
                'scheme' => 'http',
            ],
        ],

websockets.php

  'apps' => [
        [
            'id' => env('PUSHER_APP_ID'),
            'name' => env('APP_NAME'),
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'path' => env('PUSHER_APP_PATH'),
            'capacity' => null,
            'enable_client_messages' => false,
            'enable_statistics' => true,
            'verify_peer' => false,
        ],
    ],

bootstrap.js

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxxxxxx',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    // enabledTransports: ['ws', 'wss']
});

window.Echo.channel('Inventory').listen('InventoryEvent',(e)=>{
    console.log(e)
})

web.php

Route::get('/', function () {
    broadcast(new InventoryEvent('somedata'));
    return view('welcome');
});

InventoryEvent

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class InventoryEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $somedata;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($somedata)
    {
        $this->somedata = $somedata;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('Inventory');
    }
}

package.json

    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.0.0",
        "cross-env": "^7.0",
        "jquery": "^3.2",
        "laravel-mix": "^5.0.1",
        "lodash": "^4.17.13",
        "popper.js": "^1.12",
        "resolve-url-loader": "2.3.1",
        "sass": "^1.20.1",
        "sass-loader": "7.*",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    },
    "dependencies": {
        "admin-lte": "^3.0.4",
        "fusioncharts": "^3.15.1-sr.1",
        "laravel-echo": "^1.7.0",
        "pusher-js": "^6.0.2",
        "sweetalert2": "^9.10.9",
        "vue-fusioncharts": "^3.0.4",
        "vue-moment": "^4.1.0",
        "vue-router": "^3.1.6",
        "vue-select": "^3.9.5"
    }

I already setup the env for my pusher credentials. Do i need to config something in my pusher in order for this to work? I got another project with the same setup but it works but this one is not.

Body:
in your bootstrap.js file, try changing:

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxxxxxx',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
    forceTLS: false, //<<<<=====CHANGE THIS
    // enabledTransports: ['ws', 'wss']
});

window.Echo.channel('Inventory').listen('InventoryEvent',(e)=>{
    console.log(e)
})

the default value of the forceTLS option is true, which forces listening on wss instead of ws.


问:
json schema to objective c - model classes generation
Hi stack overflow people

i am writing an iphone app thats connects to a web service, through REST with JSON.
I would like to generate my model classes in objective c from a json schema provided by my web service, a bit like i d do with wsdl2objc with asoap, xml and wsdl combination.

It looks like there s not much out there on this subject

i tried something called jsonschema2objc.rb from http://code.google.com/p/bkjsonschema/ but it s giving me errors even on the simplest json schema, the one found here: http://en.wikipedia.org/wiki/JSON#Schema

i get this error:

Using temporary file /var/folders/rN/rNw33pkyHVeNG+-IesdU+k+++TI/-Tmp-/jsonschema2objc.8WRkBSQo
!!! Object definition at index Product has unknown type

so here are my 2 questions:

do you guys know any good tool to acheive jsonchema => objective c classes ?

do you know what this error means in my ./jsonschema2objc.rb

Thx!

答: It's not free, but perhaps Objectify would do what you want? It seems very slick.</p>

ContentLicense: CC BY-SA 2.5


问:
Inserting records into postgreSQL database in Python

When I run this command in python,

```<code>command=("""INSERT INTO perms(role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES
(%s,%s,%s,%s,%s,%s,%s)""")
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))
</code>```

I get the following error

```<code>Traceback (most recent call last):
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))
psycopg2.ProgrammingError: can't adapt type 'numpy.int64'
bash: parse_git_branch: command not found
</code>```

Additional info:
RoleArray contains 792 records & looks like this
[102, 102, 102, 102, 102, 102, 103, 103, 105, 105, 106, 106, 106, 106, 106, 106, 106,...etc]

reasourceArrray contains 792 records & looks like this
[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,...etc]

data[2],data[3],data[4],data[5],data[6] all contain 792 records & are boolean fields.

Any feedback on how to resolve the error?

UPDATE ----
  Thank you everyone for the feedback! In addition to the answer I upvoted
  check out this solution

```<code>for i, x, y in zip(RoleArray, resourceArray, range (0,len(data[2]))):
  data2Value=data[2][y]
  data3Value=data[3][y]
  data4Value=data[4][y]
  data5Value=data[5][y]
  data6Value=data[6][y]

  cur.execute("INSERT INTO perms (role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES('"
  +(i)+"','"+(x)+"','"+(str(data2Value))+"','"
  (str(data3Value))+"','"+(str(data4Value))+"','"
  (str(data5Value))+"','"+(str(data6Value))+"')")
  con.commit()
</code>```

答: The problem comes from %s expecting a string and you are passing a numpy array. Instead what you should consider doing is iterating over the records and inserting them one by one with a for loop. You will probably need to cast the values in the two numpy arrays to string by using: str(value).</p>

Body:
When I run this command in python,

command=("""INSERT INTO perms(role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES
(%s,%s,%s,%s,%s,%s,%s)""")
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))

I get the following error

Traceback (most recent call last):
cur.execute(command(roleArray,reasourceArrray,data[2],data[3],data[4],data[5],data[6]))
psycopg2.ProgrammingError: can't adapt type 'numpy.int64'
bash: parse_git_branch: command not found

Additional info:
RoleArray contains 792 records & looks like this
[102, 102, 102, 102, 102, 102, 103, 103, 105, 105, 106, 106, 106, 106, 106, 106, 106,...etc]

reasourceArrray contains 792 records & looks like this
[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,...etc]

data[2],data[3],data[4],data[5],data[6] all contain 792 records & are boolean fields.

Any feedback on how to resolve the error?

UPDATE ----
  Thank you everyone for the feedback! In addition to the answer I upvoted
  check out this solution

for i, x, y in zip(RoleArray, resourceArray, range (0,len(data[2]))):
  data2Value=data[2][y]
  data3Value=data[3][y]
  data4Value=data[4][y]
  data5Value=data[5][y]
  data6Value=data[6][y]

  cur.execute("INSERT INTO perms (role_id,resource_id,p_create,p_read,p_update,p_delete,p_execute) VALUES('"
  +(i)+"','"+(x)+"','"+(str(data2Value))+"','"
  (str(data3Value))+"','"+(str(data4Value))+"','"
  (str(data5Value))+"','"+(str(data6Value))+"')")
  con.commit()


问:
Absolute layout uasage
Is that ok to use absolute layout in my application if i know exactly the x,y that i'll draw the widget at or it'll affect the application appearance on the device ?

I'm asking this question as I've read that it's deprecated

答:
It is a very bad practice to use absolute layout coordinates.

Don't use it.

Title: Absolute layout uasage


问:
Text manipulation within a dataframe: words extraction
I would like to check the word next to a number.
For example, I have this column in my dataframe:
    Recipes

```<code>Halve the clementine and place into the cavity along with the bay leaves. Transfer the duck to a medium roasting tray and roast for around 1 hour 20 minutes.
Add the stock, then bring to the boil and reduce to a simmer for around 15 minutes.
2 heaped teaspoons Chinese five-spice
100 ml Marsala
1 litre organic chicken stock
</code>```

I would like to get a new column where I extract them:

```<code>New Column
[1 hour, 20 minutes]
15 minutes
2 heaped
100 ml
1 litre
</code>```

as I need to compare to a list of values:

```<code>to_compare= ["1 hour", "20 litres", "100 ml", "2", "15 minutes", "20 minutes"]
</code>```

to see how many elements per each row are in common.
Thank you for your help.

答:
You can use regex to build the pattern that can extract the number and the following word, then apply this function to the whole column of your dataframe

```<code>import pandas as pd
import re
df = pd.DataFrame({'text':["Halve the clementine and place into the cavity along with the bay leaves. Transfer the duck to a medium roasting tray and roast for around 1 hour 20 minutes.",
           "Add the stock, then bring to the boil and reduce to a simmer for around 15 minutes.",
           "2 heaped teaspoons Chinese five-spice",
           "100 ml Marsala",
           "1 litre organic chicken stock"]})

def extract_qty(txt):
  return re.findall('\d+ \w+',txt)

df['extracted_qty'] = df['text'].apply(extract_qty)

df
#   text                                                extracted_qty
#0  Halve the clementine and place into the cavity...   [1 hour, 20 minutes]
#1  Add the stock, then bring to the boil and redu...   [15 minutes]
#2  2 heaped teaspoons Chinese five-spice               [2 heaped]
#3  100 ml Marsala                                      [100 ml]
#4  1 litre organic chicken stock                       [1 litre]
</code>```

Extract common values with to_compare and a list comprehension:

```<code>to_compare= ["1 hour", "20 litres", "100 ml", "2", "15 minutes", "20 minutes"]

df['common'] = df['extracted_qty'].apply(lambda x: [el for el in x if el in to_compare])

#   text                        extracted_qty           common
#0  Halve the clementine ...    [1 hour, 20 minutes]    [1 hour, 20 minutes]
#1  Add the stock, then  ...    [15 minutes]            [15 minutes]
#2  2 heaped teaspoons ...      [2 heaped]              []
#3  100 ml Marsala              [100 ml]                [100 ml]
#4  1 litre organic chicken...  [1 litre]               []
</code>```

Body:
I would like to check the word next to a number.
For example, I have this column in my dataframe:
    Recipes

Halve the clementine and place into the cavity along with the bay leaves. Transfer the duck to a medium roasting tray and roast for around 1 hour 20 minutes.
Add the stock, then bring to the boil and reduce to a simmer for around 15 minutes.
2 heaped teaspoons Chinese five-spice
100 ml Marsala
1 litre organic chicken stock

I would like to get a new column where I extract them:

New Column
[1 hour, 20 minutes]
15 minutes
2 heaped
100 ml
1 litre

as I need to compare to a list of values:

to_compare= ["1 hour", "20 litres", "100 ml", "2", "15 minutes", "20 minutes"]

to see how many elements per each row are in common.
Thank you for your help.

Body:
You can use regex to build the pattern that can extract the number and the following word, then apply this function to the whole column of your dataframe

import pandas as pd
import re
df = pd.DataFrame({'text':["Halve the clementine and place into the cavity along with the bay leaves. Transfer the duck to a medium roasting tray and roast for around 1 hour 20 minutes.",
           "Add the stock, then bring to the boil and reduce to a simmer for around 15 minutes.",
           "2 heaped teaspoons Chinese five-spice",
           "100 ml Marsala",
           "1 litre organic chicken stock"]})

def extract_qty(txt):
  return re.findall('\d+ \w+',txt)

df['extracted_qty'] = df['text'].apply(extract_qty)

df
#   text                                                extracted_qty
#0  Halve the clementine and place into the cavity...   [1 hour, 20 minutes]
#1  Add the stock, then bring to the boil and redu...   [15 minutes]
#2  2 heaped teaspoons Chinese five-spice               [2 heaped]
#3  100 ml Marsala                                      [100 ml]
#4  1 litre organic chicken stock                       [1 litre]

Extract common values with to_compare and a list comprehension:

to_compare= ["1 hour", "20 litres", "100 ml", "2", "15 minutes", "20 minutes"]

df['common'] = df['extracted_qty'].apply(lambda x: [el for el in x if el in to_compare])

#   text                        extracted_qty           common
#0  Halve the clementine ...    [1 hour, 20 minutes]    [1 hour, 20 minutes]
#1  Add the stock, then  ...    [15 minutes]            [15 minutes]
#2  2 heaped teaspoons ...      [2 heaped]              []
#3  100 ml Marsala              [100 ml]                [100 ml]
#4  1 litre organic chicken...  [1 litre]               []


答:
We use Series.str.extractall with the pattern numbers - space - letter. Then we check which matches are in to_compare, and finally we use GroupBy.sum to get how many matches we have

```<code>matches = df['Col'].str.extractall('(\d+\s\w+)')
df['matches'] = matches[0].isin(to_compare).groupby(level=0).sum()

                                                 Col  matches
0  Halve the clementine and place into the cavity...      2.0
1  Add the stock, then bring to the boil and redu...      1.0
2              2 heaped teaspoons Chinese five-spice      0.0
3                                     100 ml Marsala      1.0
4                      1 litre organic chicken stock      0.0
</code>```

Also, matches returns:

```<code>                  0
  match
0 0          1 hour
  1      20 minutes
1 0      15 minutes
2 0        2 heaped
3 0          100 ml
4 0         1 litre
</code>```

To get these in a list, use:

```<code>matches.groupby(level=0).agg(list)

                      0
0  [1 hour, 20 minutes]
1          [15 minutes]
2            [2 heaped]
3              [100 ml]
4             [1 litre]
</code>```

Title: Text manipulation within a dataframe: words extraction

Body:
We use Series.str.extractall with the pattern numbers - space - letter. Then we check which matches are in to_compare, and finally we use GroupBy.sum to get how many matches we have

matches = df['Col'].str.extractall('(\d+\s\w+)')
df['matches'] = matches[0].isin(to_compare).groupby(level=0).sum()

                                                 Col  matches
0  Halve the clementine and place into the cavity...      2.0
1  Add the stock, then bring to the boil and redu...      1.0
2              2 heaped teaspoons Chinese five-spice      0.0
3                                     100 ml Marsala      1.0
4                      1 litre organic chicken stock      0.0

Also, matches returns:

                  0
  match
0 0          1 hour
  1      20 minutes
1 0      15 minutes
2 0        2 heaped
3 0          100 ml
4 0         1 litre

To get these in a list, use:

matches.groupby(level=0).agg(list)

                      0
0  [1 hour, 20 minutes]
1          [15 minutes]
2            [2 heaped]
3              [100 ml]
4             [1 litre]


问:
Adjusting centered text font size based on image size. How?
With some research, I have created the following piece of code to generate a simple image with a text string right on the center showing the resolution of this image. The challenge is, when you change X & Y dimensions to larger or smaller values, the font size remains the same.

My question is, what would be a good way to "grow" or "shrink" the font size as the user chooses between image sizes?

One idea I had would be to calculate predetermined areas, add them to an array of key value pairs where the value is the hard-coded font size for a given range of areas.

Perhaps you have a simpler idea?

PS: The font I am using can be downloaded from Google fonts here:

Montserrat-SemiBold

The output looks like this:

And the code:

```<code><?php

  // We Declare our canvas width & height dimensions
  $myCanvasWidth  = 256;
  $myCanvasHeight = 256;

  // We Create an empty and dark canvas from these dimensions above
  $myCanvas = imagecreate($myCanvasWidth, $myCanvasHeight) or die("Can't create image!");
  // We Allocate a color to be used as the canvas background
  $colorIndigo = imagecolorallocate($myCanvas, 0x3F, 0x51, 0xB5);
  // We Apply color as canvas background
  imagefill($myCanvas, 0, 0, $colorIndigo);

  // We Allocate a color to be used with the canvas text
  $colorWhite = imagecolorallocate($myCanvas, 0xFF, 0xFF, 0xFF);

  // We Declare our TTF font path in Windows 10...
  $myFont = 'J:\Montserrat-SemiBold.ttf';
  // We set the font size
  $myFontSize = 16;
  // We set the text angle
  $myTextAngle = 0;

  // We Declare the text string to be drawn on canvas...
  $myText = $myCanvasWidth . ' x ' . $myCanvasHeight;

  // We Calculate and return the bounding box in pixels for the text string to be drawn on canvas...
  $myTextBoundingBox = imageftbbox($myFontSize, $myTextAngle, $myFont, $myText);

  // Get the text upper, lower, left and right corner bounds of our text bounding box...
  $lower_left_x  = $myTextBoundingBox[0];
  $lower_left_y  = $myTextBoundingBox[1];
  $lower_right_x = $myTextBoundingBox[2];
  $lower_right_y = $myTextBoundingBox[3];
  $upper_right_x = $myTextBoundingBox[4];
  $upper_right_y = $myTextBoundingBox[5];
  $upper_left_x  = $myTextBoundingBox[6];
  $upper_left_y  = $myTextBoundingBox[7];

  // Get Text Width and Height
  $myTextWidth  =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
  $myTextHeight = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

  //Get the starting position for centering
  $start_x_offset = ($myCanvasWidth - $myTextWidth) / 2;
  $start_y_offset = (($myCanvasHeight - $myTextHeight) + $myFontSize * 2) / 2;

  // Write text to the image using TrueType fonts
  imagettftext($myCanvas, $myFontSize, $myTextAngle, $start_x_offset, $start_y_offset, $colorWhite, $myFont, $myText);

  // Draw a horizontal dashed line for reference only
  imagedashedline($myCanvas, 0, $myCanvasHeight/2, $myCanvasWidth, $myCanvasHeight/2, $colorWhite);
  // Draw a vertical dashed line for reference only
  imagedashedline($myCanvas, $myCanvasWidth/2, 0, $myCanvasWidth/2, $myCanvasHeight, $colorWhite);

  // We se the correct http header for png images...
  header('Content-Type: image/png');

  // We Output a PNG image to either the browser or a file
  imagepng($myCanvas);
  // Free any memory associated with myCanvas; image.
  imagedestroy($myCanvas);

?>
</code>```

答:
Here is the comment above implemented as an answer. Interestingly enough, even though the lines and the font don't appear to align, they are indeed actually centered.

The "x" at the center creates the illusion of nonalignment; a possible side effect of NOT using mono-spaced fonts in order to achieve a more unnecessarily precise alignment..?!

Then again.. mono-spaced fonts are not that good looking...

Sample resize outputs:

```<code><?php

  // We Declare our canvas width & height dimensions
  $myCanvasWidth  = 640;
  $myCanvasHeight = 360;

  // We Create an empty and dark canvas from these dimensions above
  $myCanvas = imagecreate($myCanvasWidth, $myCanvasHeight) or die("Can't create image!");
  // We Allocate a color to be used as the canvas background
  $colorIndigo = imagecolorallocate($myCanvas, 0x3F, 0x51, 0xB5);
  // We Apply color as canvas background
  imagefill($myCanvas, 0, 0, $colorIndigo);

  // We Allocate a color to be used with the canvas text
  $colorWhite = imagecolorallocate($myCanvas, 0xFF, 0xFF, 0xFF);

  // We Declare our TTF font path in Windows 10...
  $myFont = 'J:\Montserrat-SemiBold.ttf';

  // Static font seed value...
  $fontSize = 16;
  // We set the dynamic font size
  $myFontSize = $myCanvasWidth / $fontSize;
  // We set the text angle
  $myTextAngle = 0;

  // We Declare the text string to be drawn on canvas...
  $myText = $myCanvasWidth . ' x ' . $myCanvasHeight;

  // We Calculate and return the bounding box in pixels for the text string to be drawn on canvas...
  $myTextBoundingBox = imageftbbox($myFontSize, $myTextAngle, $myFont, $myText);

  // Get the text upper, lower, left and right corner bounds of our text bounding box...
  $lower_left_x  = $myTextBoundingBox[0];
  $lower_left_y  = $myTextBoundingBox[1];
  $lower_right_x = $myTextBoundingBox[2];
  $lower_right_y = $myTextBoundingBox[3];
  $upper_right_x = $myTextBoundingBox[4];
  $upper_right_y = $myTextBoundingBox[5];
  $upper_left_x  = $myTextBoundingBox[6];
  $upper_left_y  = $myTextBoundingBox[7];

  // Get Text Width and Height
  $myTextWidth  =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
  $myTextHeight = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

  //Get the starting position for centering
  $start_x_offset = ($myCanvasWidth - $myTextWidth) / 2;
  $start_y_offset = (($myCanvasHeight - $myTextHeight) + $myFontSize * 2) / 2;

  // Write text to the image using TrueType fonts
  imagettftext($myCanvas, $myFontSize, $myTextAngle, $start_x_offset, $start_y_offset, $colorWhite, $myFont, $myText);

  // Draw a horizontal dashed line for reference only
  imagedashedline($myCanvas, 0, $myCanvasHeight/2, $myCanvasWidth, $myCanvasHeight/2, $colorWhite);
  // Draw a vertical dashed line for reference only
  imagedashedline($myCanvas, $myCanvasWidth/2, 0, $myCanvasWidth/2, $myCanvasHeight, $colorWhite);

  // We set the correct http header for png images...
  header('Content-Type: image/png');

  // We Output a PNG image to either the browser or a file
  imagepng($myCanvas);
  // Finally, we free any memory associated with myCanvas; the image.
  imagedestroy($myCanvas);

?>
</code>```

The imageftbbox() function illustrated.

The imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:

Body:
With some research, I have created the following piece of code to generate a simple image with a text string right on the center showing the resolution of this image. The challenge is, when you change X & Y dimensions to larger or smaller values, the font size remains the same.

My question is, what would be a good way to "grow" or "shrink" the font size as the user chooses between image sizes?

One idea I had would be to calculate predetermined areas, add them to an array of key value pairs where the value is the hard-coded font size for a given range of areas.

Perhaps you have a simpler idea?

PS: The font I am using can be downloaded from Google fonts here:

Montserrat-SemiBold

The output looks like this:

And the code:

<?php

  // We Declare our canvas width & height dimensions
  $myCanvasWidth  = 256;
  $myCanvasHeight = 256;

  // We Create an empty and dark canvas from these dimensions above
  $myCanvas = imagecreate($myCanvasWidth, $myCanvasHeight) or die("Can't create image!");
  // We Allocate a color to be used as the canvas background
  $colorIndigo = imagecolorallocate($myCanvas, 0x3F, 0x51, 0xB5);
  // We Apply color as canvas background
  imagefill($myCanvas, 0, 0, $colorIndigo);

  // We Allocate a color to be used with the canvas text
  $colorWhite = imagecolorallocate($myCanvas, 0xFF, 0xFF, 0xFF);

  // We Declare our TTF font path in Windows 10...
  $myFont = 'J:\Montserrat-SemiBold.ttf';
  // We set the font size
  $myFontSize = 16;
  // We set the text angle
  $myTextAngle = 0;

  // We Declare the text string to be drawn on canvas...
  $myText = $myCanvasWidth . ' x ' . $myCanvasHeight;

  // We Calculate and return the bounding box in pixels for the text string to be drawn on canvas...
  $myTextBoundingBox = imageftbbox($myFontSize, $myTextAngle, $myFont, $myText);

  // Get the text upper, lower, left and right corner bounds of our text bounding box...
  $lower_left_x  = $myTextBoundingBox[0];
  $lower_left_y  = $myTextBoundingBox[1];
  $lower_right_x = $myTextBoundingBox[2];
  $lower_right_y = $myTextBoundingBox[3];
  $upper_right_x = $myTextBoundingBox[4];
  $upper_right_y = $myTextBoundingBox[5];
  $upper_left_x  = $myTextBoundingBox[6];
  $upper_left_y  = $myTextBoundingBox[7];

  // Get Text Width and Height
  $myTextWidth  =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
  $myTextHeight = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

  //Get the starting position for centering
  $start_x_offset = ($myCanvasWidth - $myTextWidth) / 2;
  $start_y_offset = (($myCanvasHeight - $myTextHeight) + $myFontSize * 2) / 2;

  // Write text to the image using TrueType fonts
  imagettftext($myCanvas, $myFontSize, $myTextAngle, $start_x_offset, $start_y_offset, $colorWhite, $myFont, $myText);

  // Draw a horizontal dashed line for reference only
  imagedashedline($myCanvas, 0, $myCanvasHeight/2, $myCanvasWidth, $myCanvasHeight/2, $colorWhite);
  // Draw a vertical dashed line for reference only
  imagedashedline($myCanvas, $myCanvasWidth/2, 0, $myCanvasWidth/2, $myCanvasHeight, $colorWhite);

  // We se the correct http header for png images...
  header('Content-Type: image/png');

  // We Output a PNG image to either the browser or a file
  imagepng($myCanvas);
  // Free any memory associated with myCanvas; image.
  imagedestroy($myCanvas);

?>

Body:
Here is the comment above implemented as an answer. Interestingly enough, even though the lines and the font don't appear to align, they are indeed actually centered.

The "x" at the center creates the illusion of nonalignment; a possible side effect of NOT using mono-spaced fonts in order to achieve a more unnecessarily precise alignment..?!

Then again.. mono-spaced fonts are not that good looking...

Sample resize outputs:

<?php

  // We Declare our canvas width & height dimensions
  $myCanvasWidth  = 640;
  $myCanvasHeight = 360;

  // We Create an empty and dark canvas from these dimensions above
  $myCanvas = imagecreate($myCanvasWidth, $myCanvasHeight) or die("Can't create image!");
  // We Allocate a color to be used as the canvas background
  $colorIndigo = imagecolorallocate($myCanvas, 0x3F, 0x51, 0xB5);
  // We Apply color as canvas background
  imagefill($myCanvas, 0, 0, $colorIndigo);

  // We Allocate a color to be used with the canvas text
  $colorWhite = imagecolorallocate($myCanvas, 0xFF, 0xFF, 0xFF);

  // We Declare our TTF font path in Windows 10...
  $myFont = 'J:\Montserrat-SemiBold.ttf';

  // Static font seed value...
  $fontSize = 16;
  // We set the dynamic font size
  $myFontSize = $myCanvasWidth / $fontSize;
  // We set the text angle
  $myTextAngle = 0;

  // We Declare the text string to be drawn on canvas...
  $myText = $myCanvasWidth . ' x ' . $myCanvasHeight;

  // We Calculate and return the bounding box in pixels for the text string to be drawn on canvas...
  $myTextBoundingBox = imageftbbox($myFontSize, $myTextAngle, $myFont, $myText);

  // Get the text upper, lower, left and right corner bounds of our text bounding box...
  $lower_left_x  = $myTextBoundingBox[0];
  $lower_left_y  = $myTextBoundingBox[1];
  $lower_right_x = $myTextBoundingBox[2];
  $lower_right_y = $myTextBoundingBox[3];
  $upper_right_x = $myTextBoundingBox[4];
  $upper_right_y = $myTextBoundingBox[5];
  $upper_left_x  = $myTextBoundingBox[6];
  $upper_left_y  = $myTextBoundingBox[7];

  // Get Text Width and Height
  $myTextWidth  =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
  $myTextHeight = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

  //Get the starting position for centering
  $start_x_offset = ($myCanvasWidth - $myTextWidth) / 2;
  $start_y_offset = (($myCanvasHeight - $myTextHeight) + $myFontSize * 2) / 2;

  // Write text to the image using TrueType fonts
  imagettftext($myCanvas, $myFontSize, $myTextAngle, $start_x_offset, $start_y_offset, $colorWhite, $myFont, $myText);

  // Draw a horizontal dashed line for reference only
  imagedashedline($myCanvas, 0, $myCanvasHeight/2, $myCanvasWidth, $myCanvasHeight/2, $colorWhite);
  // Draw a vertical dashed line for reference only
  imagedashedline($myCanvas, $myCanvasWidth/2, 0, $myCanvasWidth/2, $myCanvasHeight, $colorWhite);

  // We set the correct http header for png images...
  header('Content-Type: image/png');

  // We Output a PNG image to either the browser or a file
  imagepng($myCanvas);
  // Finally, we free any memory associated with myCanvas; the image.
  imagedestroy($myCanvas);

?>

The imageftbbox() function illustrated.

The imageftbbox() returns an array with 8 elements representing four points making the bounding box of the text:


问:
Need NSIS example script with all necessary files for script to run
I am very new to NSIS, and i was wondering if there is a way to change the splash screen with modern UI, on the first and last pages:

Installer Closing Page

Installer Opening Page

答:
```<code>!define MUI_WELCOMEFINISHPAGE_BITMAP "c:\myfiles\wizard.bmp"
!include MUI2.nsh
...
</code>```

<p>This is of course documented in the Readme. </p>

Body:
!define MUI_WELCOMEFINISHPAGE_BITMAP "c:\myfiles\wizard.bmp"
!include MUI2.nsh
...

This is of course documented in the Readme.


问:
Rise up circle using negative margin only and not using position?
How can I rise up the circle by using negative margin only? I don't want to use position.

```<code>.task6 {
  margin-top: 5px;
  border: 1px solid red;
}

.task6_row {
  margin: 20px 0;
  width: 100%;
  background-color: lightgray;
  padding: 10px 0;
  border: 1px solid green;
}

.feature_item {
  width: 32%;
  background-color: white;
  padding: 0;
  margin: 5px;
  border-bottom: 1px solid blue;
  text-align: center;
  position: relative;
}

.feature_number {
  width: 50px;
  height: 50px;
  line-height: 50px;
  display: inline-block;
  /* position: absolute; */
  border-radius: 50%;
  background-color: blue;
  color: white;
  text-align: center;
  margin-top: -12px;
  font-family: Arial, Tahoma;
}

.feature_name {}

.feature_desc {
  color: lightgray;
}

.example {
  display: inline-block;
  margin: 10px 0;
  padding: 10px;
  background-color: blue;
  color: white;
  border-radius: 8px;
}
</code>```

1

        cheap price

        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Placeat, ratione?

      see example

```

答:
The position of the circle is dependable on its container, which has a margin of 5px. If you reset the margin-top of the container you will also move the circle.

ADD:

```<code>   .feature_item { margin:5px; margin-top:0px; }
   .feature_number { margin-top: -12px; }
</code>```

Body:
How can I rise up the circle by using negative margin only? I don't want to use position.

.task6 {
  margin-top: 5px;
  border: 1px solid red;
}

.task6_row {
  margin: 20px 0;
  width: 100%;
  background-color: lightgray;
  padding: 10px 0;
  border: 1px solid green;
}

.feature_item {
  width: 32%;
  background-color: white;
  padding: 0;
  margin: 5px;
  border-bottom: 1px solid blue;
  text-align: center;
  position: relative;
}

.feature_number {
  width: 50px;
  height: 50px;
  line-height: 50px;
  display: inline-block;
  /* position: absolute; */
  border-radius: 50%;
  background-color: blue;
  color: white;
  text-align: center;
  margin-top: -12px;
  font-family: Arial, Tahoma;
}

.feature_name {}

.feature_desc {
  color: lightgray;
}

.example {
  display: inline-block;
  margin: 10px 0;
  padding: 10px;
  background-color: blue;
  color: white;
  border-radius: 8px;
}

1

        cheap price

        Lorem ipsum dolor sit, amet consectetur adipisicing elit. Placeat, ratione?

      see example

Body:
The position of the circle is dependable on its container, which has a margin of 5px. If you reset the margin-top of the container you will also move the circle.

ADD:

   .feature_item { margin:5px; margin-top:0px; }
   .feature_number { margin-top: -12px; }


问:
How to reduce bounding box of speech CSS generated bubble to visible part?
I've written coded some speech bubble for displaying hints on what to do in a smartphone app. It shall be responsive, hence I chose to use CSS ... However, there are some issues with it. The "pointing" part of the speech bubble (which is added with a ::before or ::after) has a little gap, when it's animated. And the invisible region of the pointing part is also quite huge. Since this is on top of the elements to be clicked/touched on, it prevents the action, if the user touches exactly where  the pointer points to.

This is issue #1 (Gap between rounded box and triangle/pointing part; only during animation.. because both parts seem to be moved separately):

This is issue #2 (Too large invisible bounding box, that overlays the button; Yellow region in the following image, this prevents the button to be clicked if the user touches that invisible region):

I mainly need to reduce this invisible region (Issue #2).

My current solution can be found at: https://jsfiddle.net/1mw0g79a/ or just below. Please keep the usage of "vh", "vw" and "%" for size related measures in the CSS, as this is how I ensure a similar look of the app on different devices... This is also the reason why I cannot simply use 'any' open source solution for speech bubbles out there.

The HTML:

```<code><html><head><title>...</title></head><body>
  <div id="button" class="button">Button</div>
  <div id="hint" class="bubble downwards">
    Hello! I'm a hint message...
  </div>
</body></html>
</code>```

And the CSS:

```<code>.bubble {
  position: fixed;
  top: 33.5vh;
  left: 3vw;
  max-width: 90vw;
  width: 90vw;
  z-index: 10000;

  background-color: #00000088;
  color: white;
  font-size: 2.3vh;
  padding: 2vh 2vw;
  border-radius: 2vh;
  box-shadow:   0 1vh 1vw rgba(0, 0, 0, .3), 0 0.1vh 0.2vw rgba(0, 0, 0, .2);

  display: flex;
  align-content: center;

  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-name: bounce;
  animation-timing-function: ease;
}
.bubble.downwards::after {
  content: '';
  position: absolute;
  width: 0;
  height: 3vh;
  bottom: -9vh;
  border-top: none;
  left: 40vw;
  border: 3vh solid transparent;
    z-index: 10001;

  border-top-color: #00000066;
  filter: drop-shadow(0 1vh 1vw rgba(0, 0, 0, .3)), drop-shadow(0 0.1vh 0.2vw rgba(0, 0, 0, .2));
}
@keyframes bounce {
    0%   { margin-top: -0vh; }
    50%  { margin-top: -1vh; }
    100% { margin-top: 0vh; }
}
.button {
  border-radius: 0.5vh;
  background-color: #aaa;
  font-size: 2.3vh;
  padding: 1vh;
  text-align: center;
}

#button {
  position: absolute;
  top: 40vh;
  width: 20vw;
  left: auto;
  right: auto;
}

#hint {
  top: 30vh;
  left: 3vw;
}
#hint::after {
  left: 5vw;
}
</code>```

答:
I used transform because I wanted it to be smoot when using animation. And that's how you can make triangle. It will also be responsive and will be positioned in the middle for each dimension.  Triangle will now take up just as much space as its own and will not have a negative impact on the button.

.bubble {
    position: fixed;
    top: 33.5vh;
    left: 3vw;
    max-width: 90vw;
    width: 90vw;
    z-index: 10000;

    background-color: #00000088;
    color: white;
    font-size: 2.3vh;
    padding: 2vh 2vw;
    border-radius: 2vh;
    box-shadow:   0 1vh 1vw rgba(0, 0, 0, .3), 0 0.1vh 0.2vw rgba(0, 0, 0, .2);

    display: flex;
    align-content: center;

    animation-duration: 2s;
    animation-iteration-count: infinite;
    animation-name: bounce;
    animation-timing-function: linear; /* changed  */

  }

  @keyframes bounce { /* created  */

    0%   { transform: translateY(0) }
    50%  { transform: translateY(-20px) }
    100% { transform: translateY(0) }
}

  .bubble.downwards::after { /* created */
    content: '';
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 30px 30px 0 30px; /* you can adjust it for any size you want*/
    border-color: gray transparent transparent transparent;
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
  };

  .button {
    border-radius: 0.5vh;
    background-color: #aaa;
    font-size: 2.3vh;
    padding: 1vh;
    text-align: center;
  }
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="button" class="button">Button</div>
  <div id="hint" class="bubble downwards">
    Hello! I'm a hint message...
  </div></code>```

Body:
I've written coded some speech bubble for displaying hints on what to do in a smartphone app. It shall be responsive, hence I chose to use CSS ... However, there are some issues with it. The "pointing" part of the speech bubble (which is added with a ::before or ::after) has a little gap, when it's animated. And the invisible region of the pointing part is also quite huge. Since this is on top of the elements to be clicked/touched on, it prevents the action, if the user touches exactly where  the pointer points to.

This is issue #1 (Gap between rounded box and triangle/pointing part; only during animation.. because both parts seem to be moved separately):

This is issue #2 (Too large invisible bounding box, that overlays the button; Yellow region in the following image, this prevents the button to be clicked if the user touches that invisible region):

I mainly need to reduce this invisible region (Issue #2).

My current solution can be found at: https://jsfiddle.net/1mw0g79a/ or just below. Please keep the usage of "vh", "vw" and "%" for size related measures in the CSS, as this is how I ensure a similar look of the app on different devices... This is also the reason why I cannot simply use 'any' open source solution for speech bubbles out there.

The HTML:

<title>...</title>

Button

    Hello! I'm a hint message...

And the CSS:

.bubble {
  position: fixed;
  top: 33.5vh;
  left: 3vw;
  max-width: 90vw;
  width: 90vw;
  z-index: 10000;

  background-color: #00000088;
  color: white;
  font-size: 2.3vh;
  padding: 2vh 2vw;
  border-radius: 2vh;
  box-shadow:   0 1vh 1vw rgba(0, 0, 0, .3), 0 0.1vh 0.2vw rgba(0, 0, 0, .2);

  display: flex;
  align-content: center;

  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-name: bounce;
  animation-timing-function: ease;
}
.bubble.downwards::after {
  content: '';
  position: absolute;
  width: 0;
  height: 3vh;
  bottom: -9vh;
  border-top: none;
  left: 40vw;
  border: 3vh solid transparent;
    z-index: 10001;

  border-top-color: #00000066;
  filter: drop-shadow(0 1vh 1vw rgba(0, 0, 0, .3)), drop-shadow(0 0.1vh 0.2vw rgba(0, 0, 0, .2));
}
@keyframes bounce {
    0%   { margin-top: -0vh; }
    50%  { margin-top: -1vh; }
    100% { margin-top: 0vh; }
}
.button {
  border-radius: 0.5vh;
  background-color: #aaa;
  font-size: 2.3vh;
  padding: 1vh;
  text-align: center;
}

#button {
  position: absolute;
  top: 40vh;
  width: 20vw;
  left: auto;
  right: auto;
}

#hint {
  top: 30vh;
  left: 3vw;
}
#hint::after {
  left: 5vw;
}

Body:
I used transform because I wanted it to be smoot when using animation. And that's how you can make triangle. It will also be responsive and will be positioned in the middle for each dimension.  Triangle will now take up just as much space as its own and will not have a negative impact on the button.

.bubble {
    position: fixed;
    top: 33.5vh;
    left: 3vw;
    max-width: 90vw;
    width: 90vw;
    z-index: 10000;

    background-color: #00000088;
    color: white;
    font-size: 2.3vh;
    padding: 2vh 2vw;
    border-radius: 2vh;
    box-shadow:   0 1vh 1vw rgba(0, 0, 0, .3), 0 0.1vh 0.2vw rgba(0, 0, 0, .2);

    display: flex;
    align-content: center;

    animation-duration: 2s;
    animation-iteration-count: infinite;
    animation-name: bounce;
    animation-timing-function: linear; /* changed  */

  }

  @keyframes bounce { /* created  */

    0%   { transform: translateY(0) }
    50%  { transform: translateY(-20px) }
    100% { transform: translateY(0) }
}

  .bubble.downwards::after { /* created */
    content: '';
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 30px 30px 0 30px; /* you can adjust it for any size you want*/
    border-color: gray transparent transparent transparent;
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
  };

  .button {
    border-radius: 0.5vh;
    background-color: #aaa;
    font-size: 2.3vh;
    padding: 1vh;
    text-align: center;
  }

<div id="button" class="button">Button</div>
  <div id="hint" class="bubble downwards">
    Hello! I'm a hint message...
  </div>


问:
Error creating a BLOB_STORAGE type external data source in Azure SQL Data Warehouse
Here's the T-SQL I try to run:

```<code>CREATE EXTERNAL DATA SOURCE mySource WITH
(TYPE = BLOB_STORAGE, LOCATION = 'https://myContainer.blob.core.windows.net', CREDENTIAL = myCredential)
</code>```

Here's the error I get:

```<code>Msg 105057, Level 16, State 1, Line 6
CREATE EXTERNAL DATA SOURCE statement failed because the value for the 'TYPE' option is invalid. Change the value for the 'TYPE' option and try again.
</code>```

I've Googled for "Msg 105057" and I get nothing. My goal is to use the OPENROWSET function to bulk insert a JSON file from my Azure Storage account into my Azure Data Warehouse.

答:
The problem is that Azure SQL Data Warehouse (aka Azure Synapse Analytics) does not support the BLOB_STORAGE type or the OPENROWSET function. This seems counter-intuitive, but it's not the 1st time Azure has disappointed me.

https://learn.microsoft.com/en-us/sql/t-sql/functions/openrowset-transact-sql?view=sql-server-ver15#syntax
https://learn.microsoft.com/en-us/sql/relational-databases/import-export/examples-of-bulk-access-to-data-in-azure-blob-storage?view=sql-server-ver15

Note that 'Azure Synapse Analytics (SQL DW)' is not marked as 'Applies to" in these documents.

Body:
Here's the T-SQL I try to run:

CREATE EXTERNAL DATA SOURCE mySource WITH
(TYPE = BLOB_STORAGE, LOCATION = 'https://myContainer.blob.core.windows.net', CREDENTIAL = myCredential)

Here's the error I get:

Msg 105057, Level 16, State 1, Line 6
CREATE EXTERNAL DATA SOURCE statement failed because the value for the 'TYPE' option is invalid. Change the value for the 'TYPE' option and try again.

I've Googled for "Msg 105057" and I get nothing. My goal is to use the OPENROWSET function to bulk insert a JSON file from my Azure Storage account into my Azure Data Warehouse.


问:
Displaying random 10 elements from a list flutter
I have a list fetched from a rest Api and stored it as above.

Then in my listview. builder where I display all items in the list, But I want to display 10 items at a go and they should be random such that whenever i refresh my page ill display a new list of items. I do not want to display along list simply because i want the users to click a see all button to view all the items in the list in a different page.My quetion is how can i go about it as what have managed to do is displaying only one item randomly,and make them random

答:
Please check the below example. You can assign the response of API to data here.

import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: Color.fromARGB(255, 18, 32, 47)),
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _random = new Random();
  var data = [
    'T 0',
    'T 1',
    'T 2',
    'T 3',
    'T 4',
    'T 5',
    'T 6',
    'T 7',
    'T 8',
    'T 9',
    'T 10',
    'T 11',
    'T 12',
    'T 13',
    'T 14',
    'T 15',
    'T 16',
    'T 17',
    'T 18',
    'T 19',
  ];

  var listToShow = [];
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      bottomNavigationBar: BottomAppBar(
        shape: CircularNotchedRectangle(),
        child: Container(
          height: 75,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(
                iconSize: 30.0,
                padding: EdgeInsets.only(left: 28.0),
                icon: Icon(Icons.refresh),
                onPressed: () {
                  setState(() {
                    updateDataInList();
                  });
                },
              ),
              IconButton(
                iconSize: 30.0,
                padding: EdgeInsets.only(right: 28.0),
                icon: Icon(Icons.all_inclusive),
                onPressed: () {
                  setState(() {
                    showAllData();
                  });
                },
              ),

            ],
          ),
        ),
      ),
      body: ListView.builder(
        itemCount: listToShow.length,
        itemBuilder: (context, i) {
          return Ink(
            color: Colors.blueGrey,
            child: ListTile(
              title: Text(listToShow[i].toString()),
            ),
          );
        },
      ),
    );
  }

  void updateDataInList() {
    listToShow = new List.generate(10, (_) => data[_random.nextInt(data.length)]);
  }

  void showAllData(){
    listToShow = data;
  }
}
```


问:
How can you get how many contributions a user did today with the GitHub API
I am making a very simple chrome extension that displays the number of contributions you did today on GitHub. How can i get that number?</p>

答:
You could use Github GraphQL API to request contributionsCollection with a date range :

query {
  viewer {
    contributionsCollection(from:"2020-05-05T00:00:00Z", to:"2020-05-05T00:00:00Z") {
      contributionCalendar{
        totalContributions
      }
    }
  }
}
```

<p>For a specific user: </p>

<pre class="lang-graphql prettyprint-override"><code>query {
  user(login:"krissemicolon") {
    contributionsCollection(from:"2020-06-01T00:00:00Z", to:"2020-06-01T00:00:00Z") {
      contributionCalendar{
        totalContributions
      }
    }
  }
}
</code>```

If using graphql API is not an option you could also parse the calendar svg, checkout this

Body:
You could use Github GraphQL API to request contributionsCollection with a date range :

query {
  viewer {
    contributionsCollection(from:"2020-05-05T00:00:00Z", to:"2020-05-05T00:00:00Z") {
      contributionCalendar{
        totalContributions
      }
    }
  }
}

For a specific user:

query {
  user(login:"krissemicolon") {
    contributionsCollection(from:"2020-06-01T00:00:00Z", to:"2020-06-01T00:00:00Z") {
      contributionCalendar{
        totalContributions
      }
    }
  }
}

If using graphql API is not an option you could also parse the calendar svg, checkout this


答:
numpy integers are not the same as regular Python integers. You can do a simple check on that:

```<code>import numpy as np

arr = np.array([1, 2, 3])
print(type(arr[0]))

arr_1 = arr.tolist()
print(type(arr_1[0]))
</code>```

The psycopg2 library (and I think most others, but I can't make an exhaustive list) won't accept the numpy integer type; you need to call numpy.tolist() to convert them back.

That said, there are other issues. The error you've given me in the comments shows that you have a pandas.DataFrame. There are several ways to approach this:

Insert the extra numpy arrays (RoleArray, resourceArray) into the df and then use df.to_sql`

Grab the values from the df as a 2D numpy array, insert the columns, and then do the upload

In the example below, I've chosen the latter for "reasons" i.e. no particular reason :)

Since you are inserting multiple rows, you would normally use executemany in SQL to avoid multiple transactions. However, it doesn't work as expected in psycopg2. Therefore, we're going to use execute_batch

Putting it all together:

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

from psycopg2.extras import execute_batch

# Create a fake DataFrame so that we can do some slicing
df = pd.DataFrame()
for x in range(10):
    df[x] = np.random.randint(0, 100, 10)

# Create the additional arrays with values in different ranges
RoleArray = np.random.randint(100, 200, 10)
resourceArray = np.random.randint(200, 300, 10)

# Take a slice of the df to get the relevant columns, and get the numpy array
# using .values
data = df.iloc[:, 2:7].values

# Add the extra columns to the "front" of the array
data = np.hstack((np.array([RoleArray, resourceArray]).reshape(-1, 2), data))

# Convert into Python integer types
data = data.tolist()

# Now bulk up-load
command=("""
         INSERT INTO perms(role_id,
                           resource_id,
                           p_create,
                           p_read,
                           p_update,
                           p_delete,
                           p_execute)
         VALUES (%s,%s,%s,%s,%s,%s,%s)
         """)

execute_batch(cur,
              command,
              data)

# Don't forget a conn.commit() (or equivalent) here
</code>```

Title: Inserting records into postgreSQL database in Python

Body:
numpy integers are not the same as regular Python integers. You can do a simple check on that:

import numpy as np

arr = np.array([1, 2, 3])
print(type(arr[0]))

arr_1 = arr.tolist()
print(type(arr_1[0]))

The psycopg2 library (and I think most others, but I can't make an exhaustive list) won't accept the numpy integer type; you need to call numpy.tolist() to convert them back.

That said, there are other issues. The error you've given me in the comments shows that you have a pandas.DataFrame. There are several ways to approach this:

Insert the extra numpy arrays (RoleArray, resourceArray) into the df and then use df.to_sql`

Grab the values from the df as a 2D numpy array, insert the columns, and then do the upload

In the example below, I've chosen the latter for "reasons" i.e. no particular reason :)

Since you are inserting multiple rows, you would normally use executemany in SQL to avoid multiple transactions. However, it doesn't work as expected in psycopg2. Therefore, we're going to use execute_batch

Putting it all together:

import numpy as np
import pandas as pd

from psycopg2.extras import execute_batch

# Create a fake DataFrame so that we can do some slicing
df = pd.DataFrame()
for x in range(10):
    df[x] = np.random.randint(0, 100, 10)

# Create the additional arrays with values in different ranges
RoleArray = np.random.randint(100, 200, 10)
resourceArray = np.random.randint(200, 300, 10)

# Take a slice of the df to get the relevant columns, and get the numpy array
# using .values
data = df.iloc[:, 2:7].values

# Add the extra columns to the "front" of the array
data = np.hstack((np.array([RoleArray, resourceArray]).reshape(-1, 2), data))

# Convert into Python integer types
data = data.tolist()

# Now bulk up-load
command=("""
         INSERT INTO perms(role_id,
                           resource_id,
                           p_create,
                           p_read,
                           p_update,
                           p_delete,
                           p_execute)
         VALUES (%s,%s,%s,%s,%s,%s,%s)
         """)

execute_batch(cur,
              command,
              data)

# Don't forget a conn.commit() (or equivalent) here


问:
ie "webpage has expired" on back button PHP session problem
On IE when user hits back button they get the classic IE "webpage has expired" message.

I have found that setting the following in my php.ini has solved this.

```<code>'session.cache_limiter=private'
</code>```

However my problem now is when I send forms I include a PHP session value ($_SESSION['token']) in a hidden field. I then check this on the following page to see if token values match

```<code>echo "<form ......<input type='hidden' name='token' value='".$_SESSION['token']."' />";

/*on recieving page*/
if($_POST['token']==$_SESSION['token']){/*ok matched*/}
else{/*THIS IS WHERE THE ERROR OCCURS*/}
</code>```

My problem is since adding this setting to my php.ini file I noticed when sending forms I get my custom page error as for some reason the $_SESSION['token'] value appears to change on the page receiving the form data thus making the if() statement return false? It's happening in all browsers now?

Here is my $_SESSION['token'] code (NOTE when sending my form it lands in the else() but value changes of $_SESSION['token'] something to do with cache perhaps not retaining my $_SESSION values?

```<code>session_start()
if(!isset($_SESSION['token']))
{
            $token = md5(uniqid(rand(), TRUE));
            $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
            $_SESSION['token_time'] = time();
}
else
{
            /*if token set ie user press back button on browser*/
            $token_age = time() - $_SESSION['token_time'];
            if ($token_age > 1200)
            {
                        /* More than 20 minutes has passed - regenerate. Do this so more likely wont timeout when user taking long time on <form> and token may not get refreshed before time limit*/
                        $token = md5(uniqid(rand(), TRUE));
                        $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
                        $_SESSION['token_time'] = time();
            }

}
</code>```

If any use heres my other php.ini session settings

```<code>session.cache_limiter=private
session.cookie_secure=1 ;my wholes site is SSL
session.cookie_httponly=1
session.save_path = /tmp ;directory to store sessions
session.save_handler = files
session.cookie_lifetime = 0 ;persistence cookie dies after browser closed
session.use_trans_sid = 0
session.use_only_cookies=1
</code>```

Let me just clear something up guys, the reason this whole problem occurs is using the 'session.cache_limiter=private'. If I take this out theres no problem except I get a message in IE when hitting back button on a form page saying "Webpage expired". Is there any suggestions how to avoid that message occuring in IE when hitting the back button?

Body:
On IE when user hits back button they get the classic IE "webpage has expired" message.

I have found that setting the following in my php.ini has solved this.

'session.cache_limiter=private'

However my problem now is when I send forms I include a PHP session value ($_SESSION['token']) in a hidden field. I then check this on the following page to see if token values match

echo "<form ......<input type='hidden' name='token' value='".$_SESSION['token']."' />";

/*on recieving page*/
if($_POST['token']==$_SESSION['token']){/*ok matched*/}
else{/*THIS IS WHERE THE ERROR OCCURS*/}

My problem is since adding this setting to my php.ini file I noticed when sending forms I get my custom page error as for some reason the $_SESSION['token'] value appears to change on the page receiving the form data thus making the if() statement return false? It's happening in all browsers now?

Here is my $_SESSION['token'] code (NOTE when sending my form it lands in the else() but value changes of $_SESSION['token'] something to do with cache perhaps not retaining my $_SESSION values?

session_start()
if(!isset($_SESSION['token']))
{
            $token = md5(uniqid(rand(), TRUE));
            $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
            $_SESSION['token_time'] = time();
}
else
{
            /*if token set ie user press back button on browser*/
            $token_age = time() - $_SESSION['token_time'];
            if ($token_age > 1200)
            {
                        /* More than 20 minutes has passed - regenerate. Do this so more likely wont timeout when user taking long time on <form> and token may not get refreshed before time limit*/
                        $token = md5(uniqid(rand(), TRUE));
                        $_SESSION['token'] = $token; /*have to put current session token into this variable for hidden field in <form>*/
                        $_SESSION['token_time'] = time();
            }

}

If any use heres my other php.ini session settings

session.cache_limiter=private
session.cookie_secure=1 ;my wholes site is SSL
session.cookie_httponly=1
session.save_path = /tmp ;directory to store sessions
session.save_handler = files
session.cookie_lifetime = 0 ;persistence cookie dies after browser closed
session.use_trans_sid = 0
session.use_only_cookies=1

Let me just clear something up guys, the reason this whole problem occurs is using the 'session.cache_limiter=private'. If I take this out theres no problem except I get a message in IE when hitting back button on a form page saying "Webpage expired". Is there any suggestions how to avoid that message occuring in IE when hitting the back button?

Body: ini_set("session.cache_limiter", "must-revalidate");


问:
NIFI EXECUTESCRIPT Processor failing - No MODULE FOUND
I am trying to import modules into executescript processor in nifi.
As suggested , I. am giving full path into the modules directory.

example:
Module Directory: /var/lib/nifi/Levenshtein --> which contains necessary files for the script.

Furthermore, In the script also I have set the system path pointing to use that module directory
My code Looks something like this

import re
import datetime
import sys
sys.path.append('/var/lib/nifi/Levenshtein')

import Levenshtein
```

When I am running the processor with above code it fails.

ERROR: No Module named Levenshtein in  at line number 3.

答:
If this particular library is a "native module" (compiled C code), Jython (the Python execution engine used by ExecuteScript) will not be able to load it. ExecuteScript in NiFi using Python can only use pure Python code.

The work-around is to use ExecuteProcess or ExecuteStreamCommand and invoke python <my_script.py> on the command-line, which can handle various Python versions, native modules, etc. This execution will occur outside the JVM and use real Python, not Jython.

Body:
I am trying to import modules into executescript processor in nifi.
As suggested , I. am giving full path into the modules directory.

example:
Module Directory: /var/lib/nifi/Levenshtein --> which contains necessary files for the script.

Furthermore, In the script also I have set the system path pointing to use that module directory
My code Looks something like this

import re
import datetime
import sys
sys.path.append('/var/lib/nifi/Levenshtein')

import Levenshtein

When I am running the processor with above code it fails.

ERROR: No Module named Levenshtein in  at line number 3.


问:
How to stop element with first onclick event to be fired when enter key is pressed first time
I was fixing a bug in a jsp page in which even though a function is defined with onkeypress event to click a particular button (actually its an image of button with onclick property associated with it) when the page is opened first time and then enter key is pressed its throwing an error.

When I debugged the code then I find out that actually two calls are made simultaneously.  i.e. the first button with onclick property is also clicked.

Here is just a sample code:

```<code><html>
<head>
</head>
<body>
<div onkeypress =handleEnter()>
name <input  type="text" src='Create.gif' >
</br>
<input  type="image" src='Create.gif' onclick="alert('not done')">
<input  type="image" src='Create.gif' onclick="alert('done')">
</div>
</body>
<script>
function handleEnter()
{
if(window.event.keyCode==13)
{
alert('nothing');
event.cancelBubble=true;
}
}
</script>
</html>
</code>```

on pressing enter key both functions are getting called.

答:
I know this is an old question, but I did not find any other questions/answers for this, and I was having this same issue with buttons.

But for some reason when I look at the "event" that is passed into javascript function, there is no keyCode passed in with it, so I can not distinguish which key was pressed. FYI "event" was only passing in isTrusted property (and nothing else), but that is another question for another time...

My solution was that I just added a button with onclick="return false;" and style="display:none;" in front of all the other elements so that the ENTER key affects this element and is essentially ignored, and is invisible. With onclick='return false;' the form will NOT be submitted. With onclick='return true;' the form WILL be submitted.

```<code><button id='prevent-onclick-on-enter' style='display:none;' onclick='return false;'/>
<input  type="image" src='Create.gif' onclick="alert('not done')">
<input  type="image" src='Create.gif' onclick="alert('done')">
</code>```

SECOND ANSWER
So this is maybe for a slightly different issue that only involves BUTTONS (not INPUTS), but this may be good to know for some people (like me) that did not know this...
When you have a button in a form, it defaults to type "submit" which means the first button in a form will have its onclick event triggered by the ENTER key. To prevent this from happening, simply assigm type="button" to the button, and enter key will no longer affect it.

Body:
I was fixing a bug in a jsp page in which even though a function is defined with onkeypress event to click a particular button (actually its an image of button with onclick property associated with it) when the page is opened first time and then enter key is pressed its throwing an error.

When I debugged the code then I find out that actually two calls are made simultaneously.  i.e. the first button with onclick property is also clicked.

Here is just a sample code:

name <input  type="text" src='Create.gif' >

<input  type="image" src='Create.gif' onclick="alert('not done')">
<input  type="image" src='Create.gif' onclick="alert('done')">

on pressing enter key both functions are getting called.

Body:
I know this is an old question, but I did not find any other questions/answers for this, and I was having this same issue with buttons.

But for some reason when I look at the "event" that is passed into javascript function, there is no keyCode passed in with it, so I can not distinguish which key was pressed. FYI "event" was only passing in isTrusted property (and nothing else), but that is another question for another time...

My solution was that I just added a button with onclick="return false;" and style="display:none;" in front of all the other elements so that the ENTER key affects this element and is essentially ignored, and is invisible. With onclick='return false;' the form will NOT be submitted. With onclick='return true;' the form WILL be submitted.

<button id='prevent-onclick-on-enter' style='display:none;' onclick='return false;'/>
<input  type="image" src='Create.gif' onclick="alert('not done')">
<input  type="image" src='Create.gif' onclick="alert('done')">

SECOND ANSWER
So this is maybe for a slightly different issue that only involves BUTTONS (not INPUTS), but this may be good to know for some people (like me) that did not know this...
When you have a button in a form, it defaults to type "submit" which means the first button in a form will have its onclick event triggered by the ENTER key. To prevent this from happening, simply assigm type="button" to the button, and enter key will no longer affect it.


问:
How to avoid infinite loop when conforming to a protocol with the same variable name in Swift?
Given the following protocol in FooModule:

```<code>protocol Id {
    var id: String { get }
}

protocol Foo {
    var id: Id { get }
}
</code>```

...and some type from ThirdPartyModule that does not conform to it, but that already has a property id:

```<code>struct 3rdPartyId {
   var id: String
}

struct 3rdPartyElement {
    var id: 3rdPartyId
}

</code>```

Now I want to make:

```<code>extension 3rdPartyId: MyModule.Id {
    var id: String { return self.id }
}

extension 3rdPartyElement: MyModule.Element {
    var id: MyModule.Id { return self.id }
}
</code>```

However this results in an infinite loop.

How can I extend 3rdPartyElement to conform to MyModule.Element protocol without having an infinite loop...?

I also tried just declaring it like this:

```<code>extension 3rdPartyElement: MyModule.Element {}
</code>```

... because there is already a property id of a type that should satisfy the protocol. However this does not work either, I get a compiler error telling me to add the property getter that will, of course, make a loop.

答:
Here is what I came up with:

```<code>public enum Bar {
    @frozen
    public struct Id {
        private var _id: String = ""
        public var id: String {
            get { _id }
            set { _id = newValue }
        }
        public init(id: String) {
            _id = id
        }
    }

    @frozen
    public struct Bar {
        public var id: Id
    }
}

// MARK: - Protocols

protocol Id {
    var id: String { get }
}

protocol Foo {
    var id: Id { get }
}

// MARK: - Conformance

// (1) Declare that the type conforms to the protocol
//     (won't compile without the second extension below)
extension Bar.Id: Id {}

// (2) Extend the protocol enough to ensure the compiler
//     knows how the protocol conformance declared in (1)
//     is supposed to actually work.
extension Id where Self == Bar.Id {
    var id: String { self.id }
    init(id: String) {
        self.init(id: id)
    }
}

// (1) Declare that the type conforms to the protocol
//     (won't compile without the second extension below)
extension Bar.Bar: Foo {}

// (2) Extend the protocol enough to ensure the compiler
//     knows how the protocol conformance declared in (1)
//     is supposed to actually work.
extension Foo where Self == Bar.Bar {
    var id: Id { self.id }
}
</code>```

The key is that you need two extensions: one that declares that the type conforms to the protocol, and one that extends the protocol with a where clause and provides the necessary glue to satisfy the compiler that the protocol's requirements are satisfied by the type in question.

This only works because the function bodies / property accessors inside protocol extensions have a special ability that is only true of protocol extensions (but not of extensions on structs/classes).

This special ability of protocol extensions is that the implementation in the extension can access the struct's/class's original implementation of the same variable or function that's declared inside any type that conforms to the protocol that's being extended and that meets the requirements of the where clause.

Due to this special ability of protocol extensions, the following is not an infinite loop:

```<code>extension Foo where Self == Bar.Bar {
    var id: Id { self.id }
}
</code>```

Body:
Given the following protocol in FooModule:

protocol Id {
    var id: String { get }
}

protocol Foo {
    var id: Id { get }
}

...and some type from ThirdPartyModule that does not conform to it, but that already has a property id:

struct 3rdPartyId {
   var id: String
}

struct 3rdPartyElement {
    var id: 3rdPartyId
}

Now I want to make:

extension 3rdPartyId: MyModule.Id {
    var id: String { return self.id }
}

extension 3rdPartyElement: MyModule.Element {
    var id: MyModule.Id { return self.id }
}

However this results in an infinite loop.

How can I extend 3rdPartyElement to conform to MyModule.Element protocol without having an infinite loop...?

I also tried just declaring it like this:

extension 3rdPartyElement: MyModule.Element {}

... because there is already a property id of a type that should satisfy the protocol. However this does not work either, I get a compiler error telling me to add the property getter that will, of course, make a loop.

Body:
Here is what I came up with:

public enum Bar {
    @frozen
    public struct Id {
        private var _id: String = ""
        public var id: String {
            get { _id }
            set { _id = newValue }
        }
        public init(id: String) {
            _id = id
        }
    }

    @frozen
    public struct Bar {
        public var id: Id
    }
}

// MARK: - Protocols

protocol Id {
    var id: String { get }
}

protocol Foo {
    var id: Id { get }
}

// MARK: - Conformance

// (1) Declare that the type conforms to the protocol
//     (won't compile without the second extension below)
extension Bar.Id: Id {}

// (2) Extend the protocol enough to ensure the compiler
//     knows how the protocol conformance declared in (1)
//     is supposed to actually work.
extension Id where Self == Bar.Id {
    var id: String { self.id }
    init(id: String) {
        self.init(id: id)
    }
}

// (1) Declare that the type conforms to the protocol
//     (won't compile without the second extension below)
extension Bar.Bar: Foo {}

// (2) Extend the protocol enough to ensure the compiler
//     knows how the protocol conformance declared in (1)
//     is supposed to actually work.
extension Foo where Self == Bar.Bar {
    var id: Id { self.id }
}

The key is that you need two extensions: one that declares that the type conforms to the protocol, and one that extends the protocol with a where clause and provides the necessary glue to satisfy the compiler that the protocol's requirements are satisfied by the type in question.

This only works because the function bodies / property accessors inside protocol extensions have a special ability that is only true of protocol extensions (but not of extensions on structs/classes).

This special ability of protocol extensions is that the implementation in the extension can access the struct's/class's original implementation of the same variable or function that's declared inside any type that conforms to the protocol that's being extended and that meets the requirements of the where clause.

Due to this special ability of protocol extensions, the following is not an infinite loop:

extension Foo where Self == Bar.Bar {
    var id: Id { self.id }
}


问:
Problem with crypt function in Perl to SHA-512 password
I just started learning Perl and I have a task to compare user input variable with SHA-512 stored hashed password. I made below function to test. I use randomly generated salt to generate digest from real password (p2). Next, I use this digest as salt for my user entered password (p1) to be compared with digest value. This is based on description I have found here.
I use crypt function to generate digest, however I am not able to display or compare it in next if step.
The password should be hashed using SHA-512.
I appreciate your help.</p>

```<code>use strict;
use warnings;

sub HashThis {
    # p1 is userinput and p2 is real password
    my ($p1, $p2) = @_;

    my $salt = join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64];

    # makes digest for real password using our pre defined salt
    my $digest = crypt($p2, '$6$'.$salt);

    # compares if crypt return same digest as using digest as salt for userinput
    if (crypt($p1, $digest) eq $digest) {
        print "*** matching ***\n";
    } else {
        die "*** not matching ***\n";
    }
}

print "Enter a word:\t\t ";
chomp(my $userinput = <STDIN>);

print "Real password:\t\t ";
chomp(my $userpass = <STDIN>);

HashThis($userinput, $userpass);
</code>```

答:
crypt is a thin wrapper around the C crypt function. Its implementation will vary from environment to environment. Here on OS X it does not take a leading $x$ to indicate which algorithm to use, it just uses DES. crypt("foo", '$6$'.$salt); results in $6A86JNndVTdM. Only the first two bytes of the salt are used, $6.

If you want to use SHA-512, use Digest::SHA.

crypt and DES are inappropriate for password hashing. Its short key makes it very easy to defeat, and its salt is just two characters. SHA-512 is also not appropriate for password hashing, it's too fast. Instead, you want a dedicated password hashing function such as bcrypt or PBKDF2 and other key stretching algorithms. Some implementations of crypt can do bcrypt, many can not.

rand is also not cryptographically secure and is inappropriate for generating salts. Instead, use Crypt::Random, Data::Entropy, Math::Random::Secure, or Math::TrulyRandom.

I would recommend using Crypt::PBKDF2, following the instructions in Storing Password in an easy and secure way using Perl, and reading Salted Password Hashing - Doing it Right for the theory.

Body:
I just started learning Perl and I have a task to compare user input variable with SHA-512 stored hashed password. I made below function to test. I use randomly generated salt to generate digest from real password (p2). Next, I use this digest as salt for my user entered password (p1) to be compared with digest value. This is based on description I have found here.
I use crypt function to generate digest, however I am not able to display or compare it in next if step.
The password should be hashed using SHA-512.
I appreciate your help.

use strict;
use warnings;

sub HashThis {
    # p1 is userinput and p2 is real password
    my ($p1, $p2) = @_;

    my $salt = join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64];

    # makes digest for real password using our pre defined salt
    my $digest = crypt($p2, '$6$'.$salt);

    # compares if crypt return same digest as using digest as salt for userinput
    if (crypt($p1, $digest) eq $digest) {
        print "*** matching ***\n";
    } else {
        die "*** not matching ***\n";
    }
}

print "Enter a word:\t\t ";
chomp(my $userinput = <STDIN>);

print "Real password:\t\t ";
chomp(my $userpass = <STDIN>);

HashThis($userinput, $userpass);


问:
is there any way to make Silent installation to my C# program - on Visual-Studio 2008
is there any way to make Silent installation to my C# program -  on Visual-Studio 2008

(i mean that i dont want that when the user install my program he will need to press next->next...)

thanks in advance

答: If you make a normal Visual Studio Deployment Project the msi can be installed silently if you pass the right command line parameters, I believe /passive is the one you are after.