问:
filtering the keys and reducing into nested structure
I have a below data structure from it i need extract the columns which is an array an i need to build an object with key and actual label name.

Is there any better way to achieve this.

Any help appreciated

    let data = {
      "section1": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test15",
                "label": [
                  {
                    "actualLabel": "Test 15"
                  }
                ]
              },
              {
                "columnName": "test",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      },
      "section2": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test4",
                "label": [
                  {
                    "actualLabel": "Test 4"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test5",
                "label": [
                  {
                    "actualLabel": "Test 5"
                  }
                ]
              },
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      },
      "section3": {
        "forms": [
          {
            "fields": [
              {
                "columnName": "test1",
                "label": [
                  {
                    "actualLabel": "Test 1"
                  }
                ]
              },
              {
                "columnName": "test2",
                "label": [
                  {
                    "actualLabel": "Test 2"
                  }
                ]
              },
              {
                "columnName": "test0",
                "label": [
                  {
                    "actualLabel": "Test 0"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test3",
                "label": [
                  {
                    "actualLabel": "Test 3"
                  }
                ]
              },
              {
                "columnName": "test 4",
                "label": [
                  {
                    "actualLabel": "Test 4"
                  }
                ]
              },
              {
                "columnName": "test10",
                "label": [
                  {
                    "actualLabel": "Test 10"
                  }
                ]
              }
            ]
          },
          {
            "fields": [
              {
                "columnName": "test15",
                "label": [
                  {
                    "actualLabel": "Test 15"
                  }
                ]
              },
              {
                "columnName": "test6",
                "label": [
                  {
                    "actualLabel": "Test 6"
                  }
                ]
              },
              {
                "columnName": "test7",
                "label": [
                  {
                    "actualLabel": "Test 7"
                  }
                ]
              }
            ]
          }
        ]
      }
    }

    let extractColumns = ['test1', 'test2', 'test7', 'test15']

   let result = Object.entries(data).reduce(
          (initial, [key, { forms }]) => {
            forms.forEach(({ fields }) => {
              fields.forEach(
                ({
                  columnName,
                  label: {
                    0: { actualLabel },
                  },
                }) => {
                  if (extractColumns.indexOf(columnName) > -1) {
                    initial[columnName] = {
                      actualLabel,
                    };
                  }
                },
              );
            });
            return initial;
          },
          {},
        );

console.log(result)```

答:
I propose more general solution. Inspired babel.

const data = {
    "section1": {
        "forms": [{
                "fields": [{
                        "columnName": "test1",
                        "label": [{
                            "actualLabel": "Test 1"
                        }]
                    },
                    {
                        "columnName": "test2",
                        "label": [{
                            "actualLabel": "Test 2"
                        }]
                    },
                    {
                        "columnName": "test0",
                        "label": [{
                            "actualLabel": "Test 0"
                        }]
                    }
                ]
            },
            {
                "fields": [{
                        "columnName": "test6",
                        "label": [{
                            "actualLabel": "Test 6"
                        }]
                    },
                    {
                        "columnName": "test3",
                        "label": [{
                            "actualLabel": "Test 3"
                        }]
                    },
                    {
                        "columnName": "test10",
                        "label": [{
                            "actualLabel": "Test 10"
                        }]
                    }
                ]
            },
            {
                "fields": [{
                        "columnName": "test15",
                        "label": [{
                            "actualLabel": "Test 15"
                        }]
                    },
                    {
                        "columnName": "test",
                        "label": [{
                            "actualLabel": "Test 6"
                        }]
                    },
                    {
                        "columnName": "test7",
                        "label": [{
                            "actualLabel": "Test 7"
                        }]
                    }
                ]
            }
        ]
    },
    "section2": {
        "forms": [{
                "fields": [{
                        "columnName": "test1",
                        "label": [{
                            "actualLabel": "Test 1"
                        }]
                    },
                    {
                        "columnName": "test2",
                        "label": [{
                            "actualLabel": "Test 2"
                        }]
                    },
                    {
                        "columnName": "test0",
                        "label": [{
                            "actualLabel": "Test 0"
                        }]
                    }
                ]
            },
            {
                "fields": [{
                        "columnName": "test3",
                        "label": [{
                            "actualLabel": "Test 3"
                        }]
                    },
                    {
                        "columnName": "test4",
                        "label": [{
                            "actualLabel": "Test 4"
                        }]
                    },
                    {
                        "columnName": "test10",
                        "label": [{
                            "actualLabel": "Test 10"
                        }]
                    }
                ]
            },
            {
                "fields": [{
                        "columnName": "test5",
                        "label": [{
                            "actualLabel": "Test 5"
                        }]
                    },
                    {
                        "columnName": "test6",
                        "label": [{
                            "actualLabel": "Test 6"
                        }]
                    },
                    {
                        "columnName": "test7",
                        "label": [{
                            "actualLabel": "Test 7"
                        }]
                    }
                ]
            }
        ]
    },
    "section3": {
        "forms": [{
                "fields": [{
                        "columnName": "test1",
                        "label": [{
                            "actualLabel": "Test 1"
                        }]
                    },
                    {
                        "columnName": "test2",
                        "label": [{
                            "actualLabel": "Test 2"
                        }]
                    },
                    {
                        "columnName": "test0",
                        "label": [{
                            "actualLabel": "Test 0"
                        }]
                    }
                ]
            },
            {
                "fields": [{
                        "columnName": "test3",
                        "label": [{
                            "actualLabel": "Test 3"
                        }]
                    },
                    {
                        "columnName": "test 4",
                        "label": [{
                            "actualLabel": "Test 4"
                        }]
                    },
                    {
                        "columnName": "test10",
                        "label": [{
                            "actualLabel": "Test 10"
                        }]
                    }
                ]
            },
            {
                "fields": [{
                        "columnName": "test15",
                        "label": [{
                            "actualLabel": "Test 15"
                        }]
                    },
                    {
                        "columnName": "test6",
                        "label": [{
                            "actualLabel": "Test 6"
                        }]
                    },
                    {
                        "columnName": "test7",
                        "label": [{
                            "actualLabel": "Test 7"
                        }]
                    }
                ]
            }
        ]
    }
}

function walking(o, callback, result) {
    if (Array.isArray(o)) {
        callback('array', o, result);
        for (let i = 0; i < o.length; i++) {
            walking(o[i], callback, result);
        }
    } else if (typeof o === 'object') {
        callback('object', o, result);
        for (let name in o) {
            walking(o[name], callback, result);
        }
    } else {
        callback('primitive', o, result);
    }
    return result;
}

function handler(type, value, result) {
    const extractColumns = ['test1', 'test2', 'test7', 'test15'];
    if (type == 'object') {
        if ('columnName' in value && 'label' in value) {
            if (extractColumns.indexOf(value.columnName) !== -1) {
                result[value.columnName] = value.label[0];
            }
        }
    }
}

console.log(walking(data, handler, Object.create(null)));```


来源: stackexchange

问:
Attribute error:module 'mysql' has no attribute 'connector'
I'm running MacOS Mojave, trying to connect to MySQL using mysql-python connector, through spyder ide (python3)

But I am getting the error:

File "/Users/admin/Desktop/omgboi.py", line 5, in <module>
    mydb=mysql.connector.connect(host='localhost',user='root',passwd='hariom21feb',database='test')

AttributeError: module 'mysql' has no attribute 'connector'
```

<p>I tried installing and reinstalling mysql-connector and mysql-connector-python through bash but it didn't work. I've also tried changing my file's name but that didn't work as well. This is the code:</p>

<pre class="lang-py prettyprint-override"><code>import mysql.connector
import random
first_names=['Jodee,Marielle,Phillip,Colby,Stephany,Dione,Grover,Napoleon,Nicholas,Alysa,Noma,Leta,Ciera,Donny,Buc,Iren,Renato,Glory,Stacia,Bennie,Soo,Mitzie,Kaci,Peggy,Hilma,Melva,Cindie,Miyoko,Melina,Cammy,Blanche,Rhea,Jill,Kellye,Ailene,Vida,Alva,Sau,Hollis,Oswaldo,Marty']
last_names=['Bula,Bibi,Rolf,Tayna,Ardith,Art,Jeannetta,Patrina,Ronny,Maida,Cleopatra,Sherry,Vincenza,Sheri,Sherlyn,Shayne,Geneva,Javier,Celine,Saran,Shari,Boris,Gwyneth,Summer,Maryellen,Rufina,Essie,Palma,Rafael,Cordell,Jude,Jenine,Manuel,Cleveland,Daphine,Lavina,Candi,Rossie,Brunilda,Gilberte,Nick,Hoyt,Lucius,Ardis,Tyler,Dwain,Caleb,Aide,Mckinley,Margurite']
mydb=mysql.connector.connect(host='localhost',user='root',passwd='hariom21feb',database='test')
mycursor=mydb.cursor()
fkey=random.randint(0,49)
lkey=random.randint(0,49)
nkey=random.randint(0,50)
for i in range(nkey):
    query=('insert into test value(%s,%s,%s,%s,%s)')
    tup=('L5W4NW',first_names(fkey),last_names(lkey),'2970','completed')
    mycursor.execute(query,tup)
mydb.commit()
</code>```

Any ideas about what i'm doing wrong?

答:
How did you installed Connector/Python?

The PyPI package mysql-connector is deprecated, you should use the official mysql-connector-python.

The easiest and recommended way is using pip:

```<code>pip install mysql-connector-python
</code>```

More details about installation here https://dev.mysql.com/doc/dev/connector-python/8.0/installation.html

ContentLicense: CC BY-SA 4.0

Body:
I'm running MacOS Mojave, trying to connect to MySQL using mysql-python connector, through spyder ide (python3)

But I am getting the error:

File "/Users/admin/Desktop/omgboi.py", line 5, in <module>
    mydb=mysql.connector.connect(host='localhost',user='root',passwd='hariom21feb',database='test')

AttributeError: module 'mysql' has no attribute 'connector'

I tried installing and reinstalling mysql-connector and mysql-connector-python through bash but it didn't work. I've also tried changing my file's name but that didn't work as well. This is the code:

import mysql.connector
import random
first_names=['Jodee,Marielle,Phillip,Colby,Stephany,Dione,Grover,Napoleon,Nicholas,Alysa,Noma,Leta,Ciera,Donny,Buc,Iren,Renato,Glory,Stacia,Bennie,Soo,Mitzie,Kaci,Peggy,Hilma,Melva,Cindie,Miyoko,Melina,Cammy,Blanche,Rhea,Jill,Kellye,Ailene,Vida,Alva,Sau,Hollis,Oswaldo,Marty']
last_names=['Bula,Bibi,Rolf,Tayna,Ardith,Art,Jeannetta,Patrina,Ronny,Maida,Cleopatra,Sherry,Vincenza,Sheri,Sherlyn,Shayne,Geneva,Javier,Celine,Saran,Shari,Boris,Gwyneth,Summer,Maryellen,Rufina,Essie,Palma,Rafael,Cordell,Jude,Jenine,Manuel,Cleveland,Daphine,Lavina,Candi,Rossie,Brunilda,Gilberte,Nick,Hoyt,Lucius,Ardis,Tyler,Dwain,Caleb,Aide,Mckinley,Margurite']
mydb=mysql.connector.connect(host='localhost',user='root',passwd='hariom21feb',database='test')
mycursor=mydb.cursor()
fkey=random.randint(0,49)
lkey=random.randint(0,49)
nkey=random.randint(0,50)
for i in range(nkey):
    query=('insert into test value(%s,%s,%s,%s,%s)')
    tup=('L5W4NW',first_names(fkey),last_names(lkey),'2970','completed')
    mycursor.execute(query,tup)
mydb.commit()

Any ideas about what i'm doing wrong?

Body:
How did you installed Connector/Python?

The PyPI package mysql-connector is deprecated, you should use the official mysql-connector-python.

The easiest and recommended way is using pip:

pip install mysql-connector-python

More details about installation here https://dev.mysql.com/doc/dev/connector-python/8.0/installation.html


问:
Login request with JWT response
I have a request '/login' which basically validates the USERNAME and PASSWORD and further on success, return token (JWT).

Now the question is my API is also returning USERNAME and PASSWORD in response with token. Is it the right way or should I remove USERNAME and PASSWORD from response.

REQUEST JSON

```<code>{
"USERNAME": "admin",
"PASSWORD": "123456"
}
</code>```

Response

```<code>{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTk1NTM4NjcsInVzZXJMb2dpbklkIjoiYWRtaW4ifQ.fxaENKTXxPG5wl8hp7_cSORfMzI38ODu_HgNRj3c7UZwohiFNFfZVpou8MYU4kkxEXV87-LP3upctjGCpGV6_Q",
    "PASSWORD": "123456",
    "USERNAME": "admin"
}
</code>```

答: As other people have stated here, your application should not be aware of the password or saving it in any kind of state (memory, database ...) but rather hashing it.</p>

Title: Login request with JWT response

Body:
I have a request '/login' which basically validates the USERNAME and PASSWORD and further on success, return token (JWT).

Now the question is my API is also returning USERNAME and PASSWORD in response with token. Is it the right way or should I remove USERNAME and PASSWORD from response.

REQUEST JSON

{
"USERNAME": "admin",
"PASSWORD": "123456"
}

Response

{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NTk1NTM4NjcsInVzZXJMb2dpbklkIjoiYWRtaW4ifQ.fxaENKTXxPG5wl8hp7_cSORfMzI38ODu_HgNRj3c7UZwohiFNFfZVpou8MYU4kkxEXV87-LP3upctjGCpGV6_Q",
    "PASSWORD": "123456",
    "USERNAME": "admin"
}


问:
Replace preg_replace() e modifier with preg_replace_callback
I'm terrible with regular expressions. I'm trying to replace this:

```<code>public static function camelize($word) {
   return preg_replace('/(^|_)([a-z])/e', 'strtoupper("\\2")', $word);
}
</code>```

with preg_replace_callback with an anonymous function. I don't understand what the \\2 is doing. Or for that matter exactly how preg_replace_callback works.

What would be the correct code for achieving this?

答:
You shouldn't use flag e (or eval in general).

You can also use T-Regx library

```<code>pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm terrible with regular expressions. I'm trying to replace this:

public static function camelize($word) {
   return preg_replace('/(^|_)([a-z])/e', 'strtoupper("\\2")', $word);
}

with preg_replace_callback with an anonymous function. I don't understand what the \\2 is doing. Or for that matter exactly how preg_replace_callback works.

What would be the correct code for achieving this?

Body:
You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');


问:
Effective stdin reading c programming
can anyone help me optimalize code for reading standard input. Here it is what I have now:</p>

```<code>unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}
</code>```

答: Try to read fixed chunks of at least 8192 bytes. Don't use single char input since it's quite slow.</p>

Title: Effective stdin reading c programming

Body:
can anyone help me optimalize code for reading standard input. Here it is what I have now:

unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}


问:
AJAX failed to load server with a status of 500
I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:

jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send @ jquery.min.js:4 ajax @ jquery.min.js:4 (anonymous) @ (index):39 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3

This is the code for controller called SearchController

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index()
    {
        return view('search.search');
    }

    public function search(Request $request)
    {
        if($request->ajax())
        {
            $output="";
            $products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
            if($products)
            {
                foreach ($products as $key => $product) {
                    $output.='<tr>'.
                                '<td>'.$product->id.'</td>'.
                                '<td>'.$product->title.'</td>'.
                                '<td>'.$product->description.'</td>'.
                                '<td>'.$product->price.'</td>'.
                               '</tr>';
                }
                return Response($output);
            }
        }
    }
}
</code>```

Code in web.php

```<code>Route::get('/','SearchController@index');
Route::get('/search','SearchController@search');
</code>```

Code of blade file

```<code><!DOCTYPE html>
<html>
    <head>
        <meta id="token" name="_token" content="{{ csrf_token() }}">
        <title>Live Search</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>
    <body>
        <div class="container">
        <div class="row">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3>Products info </h3>
                </div>
                <div class="panel-body">
                    <div class="form-group">
                        <input type="text" class="form-controller" id="search" name="search"></input>
                    </div>
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Product Name</th>
                                <th>Description</th>
                                <th>Price</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        </div>
        <script type="text/javascript">
            $('#search').on('keyup',function(){
                $value=$(this).val();
                $.ajax({
                    type : 'get',
                    url : '{{URL::to('search')}}',
                    data:{'search':$value},
                    success:function(data){
                        $('tbody').html(data);
                    }
                });
            });
        </script>
        <script type="text/javascript">
        $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
        </script>
    </body>
</html>
</code>```

It should display the record when the key is pressed but it gives error 500 internal server error

Screenshot with GET method
AJAX ERROR WITH GET

Screenshot with POST method
AJAX ERROR WITH POST

答:
Try this

```<code>  <script type="text/javascript">
    $('#search').on('keyup',function(){
    value=$(this).val();
    $.ajaxSetup({
      headers: {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
      }
    });
    $.ajax({
        url : '{{ url('search') }}',
        method : 'POST',
        data:{'search': value},
        success:function(response){
          console.log(response.data)
        }
      });
    })
    </script>
</code>```

your route

```<code>Route::post('/search','SearchController@search');
</code>```

and in your controller, verify

```<code>public function search(Request $request)
{
 $products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
 return response()->json(['data' => $products]);
}
</code>```

Body:
I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:

jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send @ jquery.min.js:4 ajax @ jquery.min.js:4 (anonymous) @ (index):39 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3

This is the code for controller called SearchController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index()
    {
        return view('search.search');
    }

    public function search(Request $request)
    {
        if($request->ajax())
        {
            $output="";
            $products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
            if($products)
            {
                foreach ($products as $key => $product) {
                    $output.='
'.
                                ''.$product->id.'	'.
                                ''.$product->title.'	'.
                                ''.$product->description.'	'.
                                ''.$product->price.'	'.
                               '
';
                }
                return Response($output);
            }
        }
    }
}

Code in web.php

Route::get('/','SearchController@index');
Route::get('/search','SearchController@search');

Code of blade file

<!DOCTYPE html>

        <meta id="token" name="_token" content="{{ csrf_token() }}">
        <title>Live Search</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Products info

                        <input type="text" class="form-controller" id="search" name="search"></input>

                                ID
                                Product Name
                                Description
                                Price

It should display the record when the key is pressed but it gives error 500 internal server error

Screenshot with GET method
AJAX ERROR WITH GET

Screenshot with POST method
AJAX ERROR WITH POST

Body:
Try this

  <script type="text/javascript">
    $('#search').on('keyup',function(){
    value=$(this).val();
    $.ajaxSetup({
      headers: {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
      }
    });
    $.ajax({
        url : '{{ url('search') }}',
        method : 'POST',
        data:{'search': value},
        success:function(response){
          console.log(response.data)
        }
      });
    })
    </script>

your route

Route::post('/search','SearchController@search');

and in your controller, verify

public function search(Request $request)
{
 $products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
 return response()->json(['data' => $products]);
}


问:
LLVM: Why do I get segfaults when building calls?
I'm using LLVM's C API. I think I must be using LLVMBuildCall wrong because most of the calls I make to it segfault. I'm posting a minimal example where this happens below. But I have other examples where I'm using much more complicated LLVMBuildCall calls and it doesn't segfault.

The code is a little long but most of it is boilerplate; maybe go down to the comment // Here's the function type we'll use. It's the call LLVMBuildCall(builder, f, params, PARAM_COUNT, "call") that segfaults. Here's the code:

#include <stdio.h>

#include <llvm-c/Analysis.h>
#include <llvm-c/Core.h>
#include <llvm-c/Target.h>
#include <llvm-c/TargetMachine.h>

int
main() {
    // a lot of setup...
    LLVMInitializeNativeTarget();
    LLVMInitializeNativeAsmPrinter();
    char* triple = LLVMGetDefaultTargetTriple();
    char* error;
    LLVMTargetRef target_ref;
    if (LLVMGetTargetFromTriple(triple, &target_ref, &error)) {
        printf("Error: %s\n", error);
        return 1;
    }
    LLVMTargetMachineRef tm_ref = LLVMCreateTargetMachine(
      target_ref,
      triple,
      "",
      "",
      LLVMCodeGenLevelDefault,
      LLVMRelocStatic,
      LLVMCodeModelJITDefault);
    LLVMDisposeMessage(triple);

    LLVMContextRef context = LLVMContextCreate();
    LLVMModuleRef module = LLVMModuleCreateWithNameInContext("module_name", context);
    LLVMBuilderRef builder = LLVMCreateBuilderInContext(context);

    LLVMTypeRef i64t = LLVMInt64TypeInContext(context);

    const int PARAM_COUNT = 1;

    LLVMTypeRef param_types[PARAM_COUNT] = {
      i64t,
    };

    // Here's the function type we'll use
    LLVMTypeRef func_type = LLVMFunctionType(i64t, param_types, PARAM_COUNT, 0);

    // start building it
    LLVMValueRef func = LLVMAddFunction(module, "func1", func_type);
    LLVMBasicBlockRef entry = LLVMAppendBasicBlockInContext(context, func, "entry");
    LLVMPositionBuilderAtEnd(builder, entry);

    LLVMValueRef c = LLVMConstInt(i64t, 0, 0);

    // If I try to call, I get a seg fault
    LLVMValueRef f = LLVMBuildBitCast(builder, c, func_type, "cast");
    LLVMValueRef params[PARAM_COUNT];
    for (int i = 0; i < PARAM_COUNT; i++) {
        params[i] = LLVMGetParam(f, i);
    }
    LLVMValueRef call = LLVMBuildCall(builder, f, params, PARAM_COUNT, "call");
    LLVMBuildRet(builder, call);

    // but if I comment the above and uncomment this, it works fine
    // LLVMBuildRet(builder, c);

    LLVMVerifyModule(module, LLVMAbortProcessAction, &error);
    LLVMDisposeMessage(error);
}

```

<p>And how I run it:</p>

<pre class="lang-sh prettyprint-override"><code>$ llvm-config --version
8.0.0
$ clang++ trash.cpp `llvm-config --cflags --ldflags` `llvm-config --libs` `llvm-config --system-libs`
$ ./a.out
Segmentation fault: 11
</code>```

FWIW, when I run valgrind's memcheck, I get this (with extra stuff snipped out):

```<code>==58974== Invalid read of size 8
==58974==    at 0x10084DA72: llvm::Use* llvm::copy<llvm::ArrayRef<llvm::Value*>&, llvm::Use*>(llvm::ArrayRef<llvm::Value*>&, llvm::Use*) (in ./a.out)
==58974==    by 0x10084D9E2: llvm::CallInst::init(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, llvm::Twine const&) (in ./a.out)
==58974==    by 0x100814CCA: llvm::CallInst::Create(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, llvm::Twine const&, llvm::Instruction*) (in ./a.out)
==58974==    by 0x1008137FD: llvm::IRBuilder<llvm::ConstantFolder, llvm::IRBuilderDefaultInserter>::CreateCall(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::Twine const&, llvm::MDNode*) (in ./a.out)
==58974==    by 0x1008137B9: LLVMBuildCall (in ./a.out)
==58974==    by 0x10000281A: main (trash.cpp:62)
==58974==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
</code>```

So I guess something is accessing a null pointer.

One more bit of information: one out of every 20 runs or so, this doesn't segfault. So I inserted code to find the LLVMTypeKind of the variable call, and it's a different LLVMTypeKind from the return type of f. I don't think it should be.

答: Turns out that rather than using LLVMBuildBitCast, I should instead use LLVMConstIntToPtr. The thing that comes out of LLVMBuildBitCast looks like a function pointer but is corrupted in some way.

Body:
I'm using LLVM's C API. I think I must be using LLVMBuildCall wrong because most of the calls I make to it segfault. I'm posting a minimal example where this happens below. But I have other examples where I'm using much more complicated LLVMBuildCall calls and it doesn't segfault.

The code is a little long but most of it is boilerplate; maybe go down to the comment // Here's the function type we'll use. It's the call LLVMBuildCall(builder, f, params, PARAM_COUNT, "call") that segfaults. Here's the code:

#include <stdio.h>

#include <llvm-c/Analysis.h>
#include <llvm-c/Core.h>
#include <llvm-c/Target.h>
#include <llvm-c/TargetMachine.h>

int
main() {
    // a lot of setup...
    LLVMInitializeNativeTarget();
    LLVMInitializeNativeAsmPrinter();
    char* triple = LLVMGetDefaultTargetTriple();
    char* error;
    LLVMTargetRef target_ref;
    if (LLVMGetTargetFromTriple(triple, &target_ref, &error)) {
        printf("Error: %s\n", error);
        return 1;
    }
    LLVMTargetMachineRef tm_ref = LLVMCreateTargetMachine(
      target_ref,
      triple,
      "",
      "",
      LLVMCodeGenLevelDefault,
      LLVMRelocStatic,
      LLVMCodeModelJITDefault);
    LLVMDisposeMessage(triple);

    LLVMContextRef context = LLVMContextCreate();
    LLVMModuleRef module = LLVMModuleCreateWithNameInContext("module_name", context);
    LLVMBuilderRef builder = LLVMCreateBuilderInContext(context);

    LLVMTypeRef i64t = LLVMInt64TypeInContext(context);

    const int PARAM_COUNT = 1;

    LLVMTypeRef param_types[PARAM_COUNT] = {
      i64t,
    };

    // Here's the function type we'll use
    LLVMTypeRef func_type = LLVMFunctionType(i64t, param_types, PARAM_COUNT, 0);

    // start building it
    LLVMValueRef func = LLVMAddFunction(module, "func1", func_type);
    LLVMBasicBlockRef entry = LLVMAppendBasicBlockInContext(context, func, "entry");
    LLVMPositionBuilderAtEnd(builder, entry);

    LLVMValueRef c = LLVMConstInt(i64t, 0, 0);

    // If I try to call, I get a seg fault
    LLVMValueRef f = LLVMBuildBitCast(builder, c, func_type, "cast");
    LLVMValueRef params[PARAM_COUNT];
    for (int i = 0; i < PARAM_COUNT; i++) {
        params[i] = LLVMGetParam(f, i);
    }
    LLVMValueRef call = LLVMBuildCall(builder, f, params, PARAM_COUNT, "call");
    LLVMBuildRet(builder, call);

    // but if I comment the above and uncomment this, it works fine
    // LLVMBuildRet(builder, c);

    LLVMVerifyModule(module, LLVMAbortProcessAction, &error);
    LLVMDisposeMessage(error);
}

And how I run it:

$ llvm-config --version
8.0.0
$ clang++ trash.cpp `llvm-config --cflags --ldflags` `llvm-config --libs` `llvm-config --system-libs`
$ ./a.out
Segmentation fault: 11

FWIW, when I run valgrind's memcheck, I get this (with extra stuff snipped out):

==58974== Invalid read of size 8
==58974==    at 0x10084DA72: llvm::Use* llvm::copy<llvm::ArrayRef<llvm::Value*>&, llvm::Use*>(llvm::ArrayRef<llvm::Value*>&, llvm::Use*) (in ./a.out)
==58974==    by 0x10084D9E2: llvm::CallInst::init(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, llvm::Twine const&) (in ./a.out)
==58974==    by 0x100814CCA: llvm::CallInst::Create(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::ArrayRef<llvm::OperandBundleDefT<llvm::Value*> >, llvm::Twine const&, llvm::Instruction*) (in ./a.out)
==58974==    by 0x1008137FD: llvm::IRBuilder<llvm::ConstantFolder, llvm::IRBuilderDefaultInserter>::CreateCall(llvm::FunctionType*, llvm::Value*, llvm::ArrayRef<llvm::Value*>, llvm::Twine const&, llvm::MDNode*) (in ./a.out)
==58974==    by 0x1008137B9: LLVMBuildCall (in ./a.out)
==58974==    by 0x10000281A: main (trash.cpp:62)
==58974==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

So I guess something is accessing a null pointer.

One more bit of information: one out of every 20 runs or so, this doesn't segfault. So I inserted code to find the LLVMTypeKind of the variable call, and it's a different LLVMTypeKind from the return type of f. I don't think it should be.


问:
How to implement a share button in Flutter app?
In my app, I have a button and I need it to share Facebook when this button is clicked?</p>

答:
You can try this package:
https://pub.dev/packages/wc_flutter_share

This package supports sharing image + text both.

You can use this like:

```<code>await WcFlutterShare.share(
    sharePopupTitle: 'share',
    subject: 'This is subject',
    text: 'This is text',
    fileName: 'share.png',
    mimeType: 'image/png',
    bytesOfFile: bytes.buffer.asUint8List());
</code>```

Note: On facebook you can't share image and text at the same time. You can either share text or image.

Body:
You can try this package:
https://pub.dev/packages/wc_flutter_share

This package supports sharing image + text both.

You can use this like:

await WcFlutterShare.share(
    sharePopupTitle: 'share',
    subject: 'This is subject',
    text: 'This is text',
    fileName: 'share.png',
    mimeType: 'image/png',
    bytesOfFile: bytes.buffer.asUint8List());

Note: On facebook you can't share image and text at the same time. You can either share text or image.


问:
Is gl_FragDepthEXT supported by Three.js?
I was trying to use gl_FragDepthEXT in a shader but ran into issues. Is there something I have to do to enable this extension?</p>

答:
Yes, you are missing one requirement, when you are using a raw shader you must enable with the following string in your shader code:

"#extension GL_EXT_frag_depth : enable"

When using a THREE.ShaderMaterial the program string is partly auto-generated therefore the above string cannot be added early enough in your shader strings to avoid a shader compiler error so you enable with:

material.extensions.fragDepth = true

This will make gl_FragDepthEXT available as a fragment shader output if the extension is supported.


问:
Read-Only properties
I need help with "read-only" in swift. I tried various ways, but simply couldn't figure out how to compile it without errors. Here's the question and what i thought of.

Create a read-only computed property named isEquilateral that checks to see whether all three sides of a triangle are the same length and returns true if they are and false if they are not.

```<code>var isEquilateral: Int {

}
</code>```

答:
A read-only property is a property with getter but no setter. It is always used to return a value.

```<code>class ClassA {
    var one: Int {
        return 1
    }
    var two: Int {
        get { return 2 }
    }
    private(set) var three:Int = 3
    init() {
        one = 1//Cannot assign to property: 'one' is a get-only property
        two = 2//Cannot assign to property: 'two' is a get-only property
        three = 3//allowed to write
        print(one)//allowed to read
        print(two)//allowed to read
        print(three)//allowed to read
    }
}
class ClassB {
    init() {
        var a = ClassA()
        a.one = 1//Cannot assign to property: 'one' is a get-only property
        a.two = 2//Cannot assign to property: 'two' is a get-only property
        a.three = 3//Cannot assign to property: 'three' setter is inaccessible
        print(a.one)//allowed to read
        print(a.two)//allowed to read
        print(a.three)//allowed to read
    }
}
</code>```

Title: Read-Only properties

Body:
I need help with "read-only" in swift. I tried various ways, but simply couldn't figure out how to compile it without errors. Here's the question and what i thought of.

Create a read-only computed property named isEquilateral that checks to see whether all three sides of a triangle are the same length and returns true if they are and false if they are not.

var isEquilateral: Int {

}

Body:
A read-only property is a property with getter but no setter. It is always used to return a value.

class ClassA {
    var one: Int {
        return 1
    }
    var two: Int {
        get { return 2 }
    }
    private(set) var three:Int = 3
    init() {
        one = 1//Cannot assign to property: 'one' is a get-only property
        two = 2//Cannot assign to property: 'two' is a get-only property
        three = 3//allowed to write
        print(one)//allowed to read
        print(two)//allowed to read
        print(three)//allowed to read
    }
}
class ClassB {
    init() {
        var a = ClassA()
        a.one = 1//Cannot assign to property: 'one' is a get-only property
        a.two = 2//Cannot assign to property: 'two' is a get-only property
        a.three = 3//Cannot assign to property: 'three' setter is inaccessible
        print(a.one)//allowed to read
        print(a.two)//allowed to read
        print(a.three)//allowed to read
    }
}


问:
Why does jQuery has a "window=this" at the very begining and say it would speed up references to window?
When I open jQuery's source code I find this line.

```<code>var
// Will speed up references to window, and allows munging its name.
window = this
</code>```

Why and how this line will speed up?

答:
javascript functions have lexical scope

jQuery wraps its entire implementation in an anonymous function

when said function begins execution it is executing in the "global" scope (ie this == window).

"window = this;" simply creates a local identifier in that scope so that references to it do not have to "bubble up" outside of the local scope to resolve.

OwnerDisplayName: David

ContentLicense: CC BY-SA 2.5

Body:
When I open jQuery's source code I find this line.

var
// Will speed up references to window, and allows munging its name.
window = this

Why and how this line will speed up?


问:
How to use XML string input in SP to delete rows based on two column values
I'm trying to delete multiple rows from a table using XML input.  Delete is based on two column values: OwnerKey and QuestionNumber.  (Neither column contains unique values.)

The only way I can figure to make this work is to build a temporary table that contains the XML input values (ie - the 2 columns) and then issue a DELETE based on a JOIN of the temporary table and the target table.  [I'm all ears if someone has a better approach.]

The problem that I'm running into now is that the CREATE PROC fails with an "Invalid Column name" message - pointing to "QuestionNumber" - the second attribute in the XML string.

If I explicitly list both columns in the SELECT INTO statement, I get a syntax error - so I used SELECT *.   This doesn't work either.

Can anyone give me an example of how to do this?

```<code>XML Input string (formatted here for readability):
-- <Answers>
--     <WebUser OwnerKey="104" QuestionNumber="1"/>
--     <WebUser OwnerKey="104" QuestionNumber="3"/>
-- </Answers>
</code>```

SP:

```<code>CREATE PROCEDURE WebUserDeleteAnswer
    @DeleteXMLString text
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @hDoc int
    EXEC sp_xml_preparedocument @hDoc OUTPUT,
        @DeleteXMLString

    SELECT * INTO #temp
--      OwnerKey
--      INTO #temp
    FROM OPENXML(@hdoc, 'Answers/WebUser', 2)

    DELETE FROM WebUser
    WHERE ( WebUser.OwnerKey = OwnerKey
        AND WebUser.wu_QuestionNumber = **QuestionNumber**)

    DROP TABLE #temp

    EXEC sp_xml_removedocument @hDoc

END
GO
</code>```

Figured it out.  Needed to modify the SELECT and DELETE commands:

(Changed #temp to XmlTable for clarity)

```<code>    BEGIN
    DECLARE @hDoc int
    EXEC sp_xml_preparedocument @hDoc OUTPUT,
        @DeleteXMLString

    SELECT * INTO XmlTable
    FROM OPENXML(@hdoc, 'Answers/WebUser', 2)
    WITH (OwnerKey int '@OwnerKey',
          QuestionNumber int '@QuestionNumber')

    DELETE WebUser
    FROM WebUser
        INNER JOIN XmlTable ON
        (XmlTable.OwnerKey = WebUser.OwnerKey)
        AND (XmlTable.QuestionNumber = WebUser.wu_QuestionNumber)

    EXEC sp_xml_removedocument @hDoc
    DROP TABLE XmlTable
</code>```

答:
Figured it out.  Needed to change the DELETE command:
        BEGIN
        DECLARE @hDoc int
        EXEC sp_xml_preparedocument @hDoc OUTPUT,
            @DeleteXMLString</p>

```<code>    SELECT * INTO XmlTable
    FROM OPENXML(@hdoc, 'Answers/WebUser', 2)
    WITH (OwnerKey int '@OwnerKey',
          QuestionNumber int '@QuestionNumber')

    DELETE WebUser
    FROM WebUser
        INNER JOIN XmlTable ON
        (XmlTable.OwnerKey = WebUser.OwnerKey)
        AND (XmlTable.QuestionNumber = WebUser.wu_QuestionNumber)

    EXEC sp_xml_removedocument @hDoc
    DROP TABLE XmlTable
</code>```

Body:
I'm trying to delete multiple rows from a table using XML input.  Delete is based on two column values: OwnerKey and QuestionNumber.  (Neither column contains unique values.)

The only way I can figure to make this work is to build a temporary table that contains the XML input values (ie - the 2 columns) and then issue a DELETE based on a JOIN of the temporary table and the target table.  [I'm all ears if someone has a better approach.]

The problem that I'm running into now is that the CREATE PROC fails with an "Invalid Column name" message - pointing to "QuestionNumber" - the second attribute in the XML string.

If I explicitly list both columns in the SELECT INTO statement, I get a syntax error - so I used SELECT *.   This doesn't work either.

Can anyone give me an example of how to do this?

XML Input string (formatted here for readability):
-- <Answers>
--     <WebUser OwnerKey="104" QuestionNumber="1"/>
--     <WebUser OwnerKey="104" QuestionNumber="3"/>
-- </Answers>

SP:

CREATE PROCEDURE WebUserDeleteAnswer
    @DeleteXMLString text
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @hDoc int
    EXEC sp_xml_preparedocument @hDoc OUTPUT,
        @DeleteXMLString

    SELECT * INTO #temp
--      OwnerKey
--      INTO #temp
    FROM OPENXML(@hdoc, 'Answers/WebUser', 2)

    DELETE FROM WebUser
    WHERE ( WebUser.OwnerKey = OwnerKey
        AND WebUser.wu_QuestionNumber = **QuestionNumber**)

    DROP TABLE #temp

    EXEC sp_xml_removedocument @hDoc

END
GO

Figured it out.  Needed to modify the SELECT and DELETE commands:

(Changed #temp to XmlTable for clarity)

    BEGIN
    DECLARE @hDoc int
    EXEC sp_xml_preparedocument @hDoc OUTPUT,
        @DeleteXMLString

    SELECT * INTO XmlTable
    FROM OPENXML(@hdoc, 'Answers/WebUser', 2)
    WITH (OwnerKey int '@OwnerKey',
          QuestionNumber int '@QuestionNumber')

    DELETE WebUser
    FROM WebUser
        INNER JOIN XmlTable ON
        (XmlTable.OwnerKey = WebUser.OwnerKey)
        AND (XmlTable.QuestionNumber = WebUser.wu_QuestionNumber)

    EXEC sp_xml_removedocument @hDoc
    DROP TABLE XmlTable

Body:
Figured it out.  Needed to change the DELETE command:
        BEGIN
        DECLARE @hDoc int
        EXEC sp_xml_preparedocument @hDoc OUTPUT,
            @DeleteXMLString

    SELECT * INTO XmlTable
    FROM OPENXML(@hdoc, 'Answers/WebUser', 2)
    WITH (OwnerKey int '@OwnerKey',
          QuestionNumber int '@QuestionNumber')

    DELETE WebUser
    FROM WebUser
        INNER JOIN XmlTable ON
        (XmlTable.OwnerKey = WebUser.OwnerKey)
        AND (XmlTable.QuestionNumber = WebUser.wu_QuestionNumber)

    EXEC sp_xml_removedocument @hDoc
    DROP TABLE XmlTable


问:
How do I set the max height on a Flutter Horizontal Bar Chart?
I'm using the horizontal bar chart for flutter that autosizes the bar heights.

https://google.github.io/charts/flutter/example/bar_charts/horizontal_bar_label.html

When I have a single bar as in this example I want to fix a maxheight (e.g. 10px) for the bar.  How is this configured?

I'm looking at the constructor here but I haven't found a solution
https://pub.dev/documentation/charts_flutter/latest/flutter/BarChart-class.html

```<code>      child: SizedBox(
        width: 300.0,
        height: 250.0,
        child: charts.BarChart(
          [
            charts.Series<OrdinalSales, String>(
                id: 'Sales',
                domainFn: (OrdinalSales sales, _) => sales.year,
                measureFn: (OrdinalSales sales, _) => sales.sales,
                data: localData,
                colorFn: (_, __) =>
                    charts.MaterialPalette.green.shadeDefault,
                labelAccessorFn: (OrdinalSales sales, _) =>
                    'Category 1: ${sales.sales.toString()}')
          ],
          animate: true,
          vertical: false,
          barRendererDecorator: new charts.BarLabelDecorator<String>(labelPosition: charts.BarLabelPosition.inside
          ),
          domainAxis:
          new charts.OrdinalAxisSpec(renderSpec: new charts.NoneRenderSpec()),
        ),
      ),
</code>```

答:
Try to do this - </p>

```<code>ConstrainedBox(
  constraints: BoxConstraints.expand(height: 50.0), // adjust the height here
  child: Your_chart_here, // place your chart here
),
</code>```

Body:
I'm using the horizontal bar chart for flutter that autosizes the bar heights.

https://google.github.io/charts/flutter/example/bar_charts/horizontal_bar_label.html

When I have a single bar as in this example I want to fix a maxheight (e.g. 10px) for the bar.  How is this configured?

I'm looking at the constructor here but I haven't found a solution
https://pub.dev/documentation/charts_flutter/latest/flutter/BarChart-class.html

      child: SizedBox(
        width: 300.0,
        height: 250.0,
        child: charts.BarChart(
          [
            charts.Series<OrdinalSales, String>(
                id: 'Sales',
                domainFn: (OrdinalSales sales, _) => sales.year,
                measureFn: (OrdinalSales sales, _) => sales.sales,
                data: localData,
                colorFn: (_, __) =>
                    charts.MaterialPalette.green.shadeDefault,
                labelAccessorFn: (OrdinalSales sales, _) =>
                    'Category 1: ${sales.sales.toString()}')
          ],
          animate: true,
          vertical: false,
          barRendererDecorator: new charts.BarLabelDecorator<String>(labelPosition: charts.BarLabelPosition.inside
          ),
          domainAxis:
          new charts.OrdinalAxisSpec(renderSpec: new charts.NoneRenderSpec()),
        ),
      ),

Body:
Try to do this -

ConstrainedBox(
  constraints: BoxConstraints.expand(height: 50.0), // adjust the height here
  child: Your_chart_here, // place your chart here
),


问:
How to tell Java the correct file path in a JAR-file?
I have put all my JavaFX code into a executable JAR-file. Everything is inside there.

When I compile it with Eclipse IDE, it works, but when I try to execute the JAR-file, I get an error.

```<code>Caused by: javafx.fxml.LoadException:
file:/home/asus/program/JUSBPlotter/JUSBPlotter-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/se/danielmartensson/fxml/front.fxml
</code>```

When I have this Java code

```<code> Parent root = FXMLLoader.load(getClass().getResource("/se/danielmartensson/fxml/front.fxml"));
</code>```

There is nothing wrong with the FXML file.

```<code>fx:controller="se.danielmartensson.controller.Front"
</code>```

Also I get errors when I try to display a picture in JavaFX.

```<code>Caused by: java.io.FileNotFoundException: file:/home/asus/program/JUSBPlotter/JUSBPlotter-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/se/danielmartensson/pictures/computer.png (No such file or directory)
</code>```

When I have this Java code:

```<code>FileInputStream picture1 = new FileInputStream(getClass().getResource("/se/danielmartensson/pictures/computer.png").getFile());
</code>```

Question:
How can I tell Java the correct file path in JAR-file?

答:
One thing to remember is that resources are not the same thing as files, despite the fact they appear quite similar—especially before packaging an application. Once you package an application those resource files become entries in a JAR file which, while they can be thought of as files, cannot be accessed in the same way as files. In particular, the java.io.File API does not understand how to read those entries. You can, however, access these entries through the URL returned by Class#getResource(String) or the InputStream returned by Class#getResourceAsStream(String). Note the latter basically just finds the URL and, if it exists, calls URL#openStream(). The reason you can access JAR entries (i.e. resources) with the URL is due to the JarURLConnection and related classes; I won't go into detail about how URLs are handled by Java as that's out of scope for this answer.

Now, since you're trying to display an image in JavaFX I assume you're using the Image class. There are basically three ways you can tell an Image where the image resource is.

Use Image#<init>(String) where the argument URL has no scheme. In this case the class will treat the URL as a path relative to the root of the classpath and try to access the image accordingly. Basically, the argument is the same argument you'd give to Class#getResource(String), except that the path must be absolute (i.e. not relative to any class). This behavior is documented by the Image class:

All URLs supported by URL can be passed to the constructor. If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.

Note: If you're using modules then resource encapsulation comes into play when using this option. See GitHub Issue #441.

Use the same constructor as used above but pass a valid URL (i.e. it has a scheme). When using a resource, you can simply convert the URL returned by Class#getResource(Sring) into a String using URL#toExternalForm().

```<code>Image image = new Image(getClass().getResource(...).toExternalForm());
</code>```

Note: You can also use URL#toString() which returns the same value.

Use Image#<init>(InputStream). Here you can use Class#getResourceAsStream(String). Don't forget to close the InputStream when done with it.

```<code>try (InputStream is = getClass().getResourceAsStream(...)) {
    Image image = new Image(is);
}
</code>```

All this assumes that the resources have been properly packaged in your JAR file when you built it. If that's not the case, follow the advice given by José Pereda in the question comments first.

Note that one can access the entries of a ZIP/JAR file using the java.util.zip.* API, the java.util.jar.* API, or the Java NIO's ZipFileSystemProvider. Each of these, especially the last option, allow you to access the entries of a ZIP/JAR file similar to actual files because they're designed specifically to do so. However, when using resources in an application you should stick with Class#getResource(String) and related methods.

Body:
I have put all my JavaFX code into a executable JAR-file. Everything is inside there.

When I compile it with Eclipse IDE, it works, but when I try to execute the JAR-file, I get an error.

Caused by: javafx.fxml.LoadException:
file:/home/asus/program/JUSBPlotter/JUSBPlotter-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/se/danielmartensson/fxml/front.fxml

When I have this Java code

 Parent root = FXMLLoader.load(getClass().getResource("/se/danielmartensson/fxml/front.fxml"));

There is nothing wrong with the FXML file.

fx:controller="se.danielmartensson.controller.Front"

Also I get errors when I try to display a picture in JavaFX.

Caused by: java.io.FileNotFoundException: file:/home/asus/program/JUSBPlotter/JUSBPlotter-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/se/danielmartensson/pictures/computer.png (No such file or directory)

When I have this Java code:

FileInputStream picture1 = new FileInputStream(getClass().getResource("/se/danielmartensson/pictures/computer.png").getFile());

Question:
How can I tell Java the correct file path in JAR-file?

Body:
One thing to remember is that resources are not the same thing as files, despite the fact they appear quite similar—especially before packaging an application. Once you package an application those resource files become entries in a JAR file which, while they can be thought of as files, cannot be accessed in the same way as files. In particular, the java.io.File API does not understand how to read those entries. You can, however, access these entries through the URL returned by Class#getResource(String) or the InputStream returned by Class#getResourceAsStream(String). Note the latter basically just finds the URL and, if it exists, calls URL#openStream(). The reason you can access JAR entries (i.e. resources) with the URL is due to the JarURLConnection and related classes; I won't go into detail about how URLs are handled by Java as that's out of scope for this answer.

Now, since you're trying to display an image in JavaFX I assume you're using the Image class. There are basically three ways you can tell an Image where the image resource is.

Use Image#<init>(String) where the argument URL has no scheme. In this case the class will treat the URL as a path relative to the root of the classpath and try to access the image accordingly. Basically, the argument is the same argument you'd give to Class#getResource(String), except that the path must be absolute (i.e. not relative to any class). This behavior is documented by the Image class:

All URLs supported by URL can be passed to the constructor. If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.

Note: If you're using modules then resource encapsulation comes into play when using this option. See GitHub Issue #441.

Use the same constructor as used above but pass a valid URL (i.e. it has a scheme). When using a resource, you can simply convert the URL returned by Class#getResource(Sring) into a String using URL#toExternalForm().

Image image = new Image(getClass().getResource(...).toExternalForm());

Note: You can also use URL#toString() which returns the same value.

Use Image#<init>(InputStream). Here you can use Class#getResourceAsStream(String). Don't forget to close the InputStream when done with it.

try (InputStream is = getClass().getResourceAsStream(...)) {
    Image image = new Image(is);
}

All this assumes that the resources have been properly packaged in your JAR file when you built it. If that's not the case, follow the advice given by José Pereda in the question comments first.

Note that one can access the entries of a ZIP/JAR file using the java.util.zip.* API, the java.util.jar.* API, or the Java NIO's ZipFileSystemProvider. Each of these, especially the last option, allow you to access the entries of a ZIP/JAR file similar to actual files because they're designed specifically to do so. However, when using resources in an application you should stick with Class#getResource(String) and related methods.


问:
How to fix 'Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/swt/SWT' in Java
Ok, so I was following a tutorial, hoping to create a basic browser I could expand on. In the video, it worked fine, but a lot of people were saying they got this error. I tried it anyway, and I also have it. The error is:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/swt/SWT
</code>```

And my code is:

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

@SuppressWarnings("serial")
public class NeutrinoBrowser extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        UIUtils.setPreferredLookAndFeel();
        NativeInterface.open();

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    NeutrinoBrowser frame = new NeutrinoBrowser();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public NeutrinoBrowser() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BorderLayout(0, 0));

        final JWebBrowser browserArea = new JWebBrowser();
        browserArea.navigate("http://google.com");
        panel.add(browserArea, BorderLayout.CENTER);
    }

}

</code>```

I'm using JavaSE 1.8 and the library is The DJ Project
Any help is much appreciated. Thanks!

答:
That exception tells you that at run time your class path setup is incomplete.

You are missing the library (aka a JAR file) that contains the SWT library elements.

In case you are using the maven build system, see here for further details.

In case you are not using any build system: consider using one. In the meantime, identify the JAR(s) you need, download them manually and add them to your classpath.

Body:
Ok, so I was following a tutorial, hoping to create a basic browser I could expand on. In the video, it worked fine, but a lot of people were saying they got this error. I tried it anyway, and I also have it. The error is:

Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/swt/SWT

And my code is:

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

@SuppressWarnings("serial")
public class NeutrinoBrowser extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        UIUtils.setPreferredLookAndFeel();
        NativeInterface.open();

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    NeutrinoBrowser frame = new NeutrinoBrowser();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public NeutrinoBrowser() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(new BorderLayout(0, 0));

        final JWebBrowser browserArea = new JWebBrowser();
        browserArea.navigate("http://google.com");
        panel.add(browserArea, BorderLayout.CENTER);
    }

}

I'm using JavaSE 1.8 and the library is The DJ Project
Any help is much appreciated. Thanks!


问:
How to decode Bitmap from MediaStore using inSampleSize() and inJustDecodeBounds()
I need to decode image from MediaStore, but before doing this load smaller one using inSampleSize() option. MediaStore.Images.Media.getBitmap() does not provides any options for decoding. So I get to know how to read image size, and the apply inSampleSize() for image provided by MediaStore.</p>

答: Try this from official site: https://developer.android.com/topic/performance/graphics/load-bitmap. </p>


问:
Keeping nested anchor fixed while using width hover transition of div in CSS
I am currently trying to achieve something when on hover, the background colour will change and animate as a "push" when the width changes from 0% to 100%. However, with my solution, setting the div to be 0% causes the anchor tag to not stay in a single line (breaks). How do I fix this?

Fiddle: https://jsfiddle.net/9hd3v84r/

* {
  padding: 0;
  margin: 0;
}

.navrectangle {
  width: 20Vw;
  height: 100vh;
  background-image: linear-gradient(to right, #002067, #013d98);
}

/* NAV */

a {
  color: #fff;
  text-decoration: none;
  font-weight: 700;
}

img {
  padding-top: 8vh;
  width: 70%;
  margin: auto;
  display: block;
}

.textnav {
  padding-top: 6vh;
  display: block;
  list-style-type: none;
  font-size: 1.3vw;
}

.textnav a {
  margin-left: 3vw;
  width: 100%;
}

.textnav li {
  padding: 2vh 0vh;
  width: 100%;
}

.recpush {
  width: 0%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.recpush:hover {
  overflow: visible;
  background: #50d986;
  width: 110%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.textnav li:hover a {
  color: #002067;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navrectangle">
  <nav>
    <img src="media/Asset 1.png" alt="">
    <div class="textnav">
      <div class="recpush">
        <li>NUMBER ONE</li>
      </div>
      <div class="recpush">
        <li>NUMBER TWO</li>
      </div>
      <div class="recpush">
        <li>NUMBER 3</li>
      </div>
      <div class="recpush">
        <li>NUMBER 4</li>
      </div>
    </div>

  </nav>
</div></code>```

Thanks guys

答:
```<code><style>
.recpush li a {
    margin-left: 3vw;
    width: 100%;
    white-space: nowrap;
    float: left;
}
</style>
OR
<style>
.recpush li a {
    margin-left: 3vw;
    width: 100%;
    float: left;
    white-space: pre;
}
</style>
</code>```

Body:
I am currently trying to achieve something when on hover, the background colour will change and animate as a "push" when the width changes from 0% to 100%. However, with my solution, setting the div to be 0% causes the anchor tag to not stay in a single line (breaks). How do I fix this?

Fiddle: https://jsfiddle.net/9hd3v84r/

* {
  padding: 0;
  margin: 0;
}

.navrectangle {
  width: 20Vw;
  height: 100vh;
  background-image: linear-gradient(to right, #002067, #013d98);
}

/* NAV */

a {
  color: #fff;
  text-decoration: none;
  font-weight: 700;
}

img {
  padding-top: 8vh;
  width: 70%;
  margin: auto;
  display: block;
}

.textnav {
  padding-top: 6vh;
  display: block;
  list-style-type: none;
  font-size: 1.3vw;
}

.textnav a {
  margin-left: 3vw;
  width: 100%;
}

.textnav li {
  padding: 2vh 0vh;
  width: 100%;
}

.recpush {
  width: 0%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.recpush:hover {
  overflow: visible;
  background: #50d986;
  width: 110%;
  -webkit-transition: width 1s ease-in-out;
  -moz-transition: width 1s ease-in-out;
  -o-transition: width 1s ease-in-out;
  transition: width 1s ease-in-out;
}

.textnav li:hover a {
  color: #002067;
}

NUMBER ONE

NUMBER TWO

NUMBER 3

NUMBER 4

Thanks guys


问:
Calling stored procedure with parameter to return list
I have a stored procedure with parameters, which i want to submit the parameters in a view which returns a index of the list. How do i go about this in my controller

```<code>CREATE PROCEDURE [dbo].[spFlugReport]
(
   @AccNo INTEGER,
   @DateFrom DATE,
   @DateTo DATE
)
AS
BEGIN
    SELECT *
    FROM [dbo].[KIRData]
    WHERE AccNo = @AccNo
      AND StartDate >= @DateFrom
      AND EndDate <= @DateTo
      AND Prod = 'Air'
END
</code>```

C# code:

```<code>public ActionResult Report()
{
    using(DataModel db = new DataModel())
    {
        SqlParameter[] param = new SqlParameter[] {
            new SqlParameter("@AccNo ,"),
            new SqlParameter("@DateFrom ,"),
            new SqlParameter("@DateTo ,")
        };

    }
}
</code>```

答:
welcome to stack overflow. Here is a useful link that could help you to achieve what you need to do.

https://csharp-station.com/Tutorial/AdoDotNet/Lesson07

and here is one with a similar question to your problem How to execute a stored procedure within C# program

However, here is an quick example of what you need to pass a parameter to a stored procedure.

```<code>// create and open a connection object
SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

// 1.  create a command object identifying the stored procedure
SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

// execute the command
SqlDataReader rdr = cmd.ExecuteReader();
</code>```

Hope this helps you.

Body:
I have a stored procedure with parameters, which i want to submit the parameters in a view which returns a index of the list. How do i go about this in my controller

CREATE PROCEDURE [dbo].[spFlugReport]
(
   @AccNo INTEGER,
   @DateFrom DATE,
   @DateTo DATE
)
AS
BEGIN
    SELECT *
    FROM [dbo].[KIRData]
    WHERE AccNo = @AccNo
      AND StartDate >= @DateFrom
      AND EndDate <= @DateTo
      AND Prod = 'Air'
END

C# code:

public ActionResult Report()
{
    using(DataModel db = new DataModel())
    {
        SqlParameter[] param = new SqlParameter[] {
            new SqlParameter("@AccNo ,"),
            new SqlParameter("@DateFrom ,"),
            new SqlParameter("@DateTo ,")
        };

    }
}

Body:
welcome to stack overflow. Here is a useful link that could help you to achieve what you need to do.

https://csharp-station.com/Tutorial/AdoDotNet/Lesson07

and here is one with a similar question to your problem How to execute a stored procedure within C# program

However, here is an quick example of what you need to pass a parameter to a stored procedure.

// create and open a connection object
SqlConnection conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

// 1.  create a command object identifying the stored procedure
SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

// execute the command
SqlDataReader rdr = cmd.ExecuteReader();

Hope this helps you.


问:
Unable to access nested subfolder in HMVC CI
I just created two folder in modules (ui and admin)...unable to call the controller in url.

http://localhost:82/myproject/ui/home/userlogin

```<code>ui (folder)
 -home (folder)
    - home (controller)
      - userlogin (method)

admin (folder)
 -dsb (folder)
    - dsb (controller)
</code>```

答:
This is not possible in HMVC because HVC works based on module, and you are targeting in url  like ... https://localhost/site_name/module_name/method_name

module name having same name controller if you put again a sub module in module this will be not targeted. and more over I  suggest this is not good practice to do with HMVC

Body:
I just created two folder in modules (ui and admin)...unable to call the controller in url.

http://localhost:82/myproject/ui/home/userlogin

ui (folder)
 -home (folder)
    - home (controller)
      - userlogin (method)

admin (folder)
 -dsb (folder)
    - dsb (controller)


问:
AOSP ROM for Samsung Grand duos GT-i9082 Error loading kernel
I want to build an AOSP ROM for the Samsung Grand duos GT-i9082. I have the kernel, and device tree in cyanogenmod and AOSP sources. After compiling, I got the following error:

```<code>Install: out/host/linux-x86/bin/minigzip
Target ram disk: out/target/product/i9082/ramdisk.img
Target boot image: out/target/product/i9082/boot.img
Error: could not load kernel 'out/target/product/i9082/kernel'
make: *** [out/target/product/i9082/boot.img] Error 1
</code>```

How can I fix it?

答:
This reply is a bit late, but it looks as if you don't have a file named "kernel", in that folder.
If you want to get that kernel, you can either:

Compile it from source

Extract it from boot.img

1.
If you have any other devices search them up. You will find your kernel, it's usually on Github, or the manufacturer's website.
Here are some common places to get the source code for your kernel.

```<code>LG: http://opensource.lge.com/index

Samsung: http://opensource.samsung.com/

HTC: https://www.htcdev.com/devcenter/downloads

OnePlus: https://github.com/OnePlusOSS

Motorola: https://github.com/MotorolaMobilityLLC
</code>```

I can't give you a guide here on how to compile, because every device is different.
You're going to have to do a lot of research! it's worth it in the end, it took me weeks to figure out how to compile the kernel for my device.

Extract the kernel from boot.img (easier)

This guide: Unpack Repack boot.img (Kernel) Files And Modify Ramdisk
will help you accomplish this.
If you can't figure this out, then you probably shouldn't be trying to do this.

Body:
I want to build an AOSP ROM for the Samsung Grand duos GT-i9082. I have the kernel, and device tree in cyanogenmod and AOSP sources. After compiling, I got the following error:

Install: out/host/linux-x86/bin/minigzip
Target ram disk: out/target/product/i9082/ramdisk.img
Target boot image: out/target/product/i9082/boot.img
Error: could not load kernel 'out/target/product/i9082/kernel'
make: *** [out/target/product/i9082/boot.img] Error 1

How can I fix it?

Body:
This reply is a bit late, but it looks as if you don't have a file named "kernel", in that folder.
If you want to get that kernel, you can either:

Compile it from source

Extract it from boot.img

1.
If you have any other devices search them up. You will find your kernel, it's usually on Github, or the manufacturer's website.
Here are some common places to get the source code for your kernel.

LG: http://opensource.lge.com/index

Samsung: http://opensource.samsung.com/

HTC: https://www.htcdev.com/devcenter/downloads

OnePlus: https://github.com/OnePlusOSS

Motorola: https://github.com/MotorolaMobilityLLC

I can't give you a guide here on how to compile, because every device is different.
You're going to have to do a lot of research! it's worth it in the end, it took me weeks to figure out how to compile the kernel for my device.

Extract the kernel from boot.img (easier)

This guide: Unpack Repack boot.img (Kernel) Files And Modify Ramdisk
will help you accomplish this.
If you can't figure this out, then you probably shouldn't be trying to do this.


问:
Simple Laravel Passeport Route Testing
I encounter a small problem when performing unit tests for the default Passport 5.8 routes.

In fact I tested the route / oauth / clients in get mode:

```<code>/** @test */
   public function getOauthClients()
   {
       $user = factory(User::class)->make();
       $response = $this->actingAs($user)->getJson('/oauth/clients');
       $response->assertSuccessful();
   }
</code>```

But when I want to test the route provided by default in get mode: /oauth/token , I do not know what are the steps I need to follow.

Thank you in advance.

答:
You should try with:

```<code>Passport::actingAs(
    factory(User::class)->create()
);
$response = $this->getJson('/oauth/clients');
// ...
</code>```

Passport ship with some testing helpers for that purpose, like the actingAs method above.

Quoting from documentation:

Passport's actingAs method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the actingAs method is the user instance and the second is an array of scopes that should be granted to the user's token:

Title: Simple Laravel Passeport Route Testing

Body:
I encounter a small problem when performing unit tests for the default Passport 5.8 routes.

In fact I tested the route / oauth / clients in get mode:

/** @test */
   public function getOauthClients()
   {
       $user = factory(User::class)->make();
       $response = $this->actingAs($user)->getJson('/oauth/clients');
       $response->assertSuccessful();
   }

But when I want to test the route provided by default in get mode: /oauth/token , I do not know what are the steps I need to follow.

Thank you in advance.

Body:
You should try with:

Passport::actingAs(
    factory(User::class)->create()
);
$response = $this->getJson('/oauth/clients');
// ...

Passport ship with some testing helpers for that purpose, like the actingAs method above.

Quoting from documentation:

Passport's actingAs method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the actingAs method is the user instance and the second is an array of scopes that should be granted to the user's token:


问:
Whats the best way to use google credentials for production app?
I'm building a C# .net application for STT and I'm creating credentials manually. I find the documentation hugely confusing for me and I dont know how to add the credentials properly.

I added a project, created a json credential and downloaded and kept on a folder and pointing to it for manually with GoogleCredential for authorization and everythings working good. But this cant be a solution for a shipped app. Current approach:

```<code>GoogleCredential credentials =
GoogleCredential.FromFile(Path.Combine("*PATH"), "myProject-123XXXx32.json"));

        TextToSpeechClient client = TextToSpeechClient.Create(credentials);
</code>```

If I use a default credential json by environment variable then how my production app that is running on users machine will have credential?

So I have to put the json directly to my app? Isn't it less secure than using a key?

What should I use to authenticate my application with GoogleCredential?

答:
You can set credentials using Google KMS and consume it in your application https://cloud.google.com/kms/.

1a. Save the JSON in a KMS as a JSON for the VALUE of the KEY.

2a. Decrypt JSON in your code and consume it.

1b. Alternatively, you can make it consume credentials using Environment variables

2b. And just setup Environments in your environment where you app is being shipped.

3b. You can automate 2b step using some tool like serverless framework( https://serverless.com/framework/docs/providers/google/)

Body:
I'm building a C# .net application for STT and I'm creating credentials manually. I find the documentation hugely confusing for me and I dont know how to add the credentials properly.

I added a project, created a json credential and downloaded and kept on a folder and pointing to it for manually with GoogleCredential for authorization and everythings working good. But this cant be a solution for a shipped app. Current approach:

GoogleCredential credentials =
GoogleCredential.FromFile(Path.Combine("*PATH"), "myProject-123XXXx32.json"));

        TextToSpeechClient client = TextToSpeechClient.Create(credentials);

If I use a default credential json by environment variable then how my production app that is running on users machine will have credential?

So I have to put the json directly to my app? Isn't it less secure than using a key?

What should I use to authenticate my application with GoogleCredential?


问:
Problem with understanding a vector initialization
This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

```<code>std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}
</code>```

I receive the following error:
request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

```<code>int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}
</code>```

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

答:
You have a misunderstanding on how the std::vector::push_back function works. It basically appends a new object at the end of the vector. In particular, you don't need to index into the vector with std::vector::operator[]. Instead, change your snippet to

```<code>for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec.push_back(x);
}
</code>```

The solution you came up with does something that you probably don't intend, i.e., using a raw array of vectors: when transferring user input into the objects, it creates size vectors with one element each.

Body:
This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I receive the following error:
request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

Body:
You have a misunderstanding on how the std::vector::push_back function works. It basically appends a new object at the end of the vector. In particular, you don't need to index into the vector with std::vector::operator[]. Instead, change your snippet to

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec.push_back(x);
}

The solution you came up with does something that you probably don't intend, i.e., using a raw array of vectors: when transferring user input into the objects, it creates size vectors with one element each.


问:
Node js send meeting/calendar invite for gmail
I am trying to send calendar invite using node js.

I have tried nodemailer library and is sending mail with calendar invite

Like in reference to this question

but this is sending invite like

but I want send invite like

suggest some help if anyone knows better approach.

[update]
using google-calendar api
the output is showing like

答:
sendNotifications is deprecated, use sendUpdates. Notice it isn't boolean but string.

```<code>calendar.events.insert({
    auth: auth,
    calendarId: 'primary',
    resource: event,
    sendUpdates: 'all',
  }, function(err, event) {
    if (err) {
      console.log('There was an error contacting the Calendar service: ' + err);
      return;
    }
    console.log('Event created: %s', event.htmlLink);
  });
</code>```

From typescript signatures:

```<code>     * @param {boolean=} params.sendNotifications Deprecated. Please use sendUpdates instead.  Whether to send notifications about the creation of the new event. Note that some emails might still be sent even if you set the value to false. The default is false.
     * @param {string=} params.sendUpdates Whether to send notifications about the creation of the new event. Note that some emails might still be sent. The default is false.
</code>```

Body:
sendNotifications is deprecated, use sendUpdates. Notice it isn't boolean but string.

calendar.events.insert({
    auth: auth,
    calendarId: 'primary',
    resource: event,
    sendUpdates: 'all',
  }, function(err, event) {
    if (err) {
      console.log('There was an error contacting the Calendar service: ' + err);
      return;
    }
    console.log('Event created: %s', event.htmlLink);
  });

From typescript signatures:

     * @param {boolean=} params.sendNotifications Deprecated. Please use sendUpdates instead.  Whether to send notifications about the creation of the new event. Note that some emails might still be sent even if you set the value to false. The default is false.
     * @param {string=} params.sendUpdates Whether to send notifications about the creation of the new event. Note that some emails might still be sent. The default is false.


问:
How do I add classes to the classpath for MBean Explorer in eclipse
I have a web app being deployed in JBoss AS 6.0.0. I'm using the JBoss Tools plugin in eclipse 3.6. I have the server configured with the project and it runs OK. My app exposes some MBeans via JMX.

I'm using the MBean Explorer view to access the JMX beans. Some of my beans return instances of classes defined in my project. When I invoke these methods via the explorer view I get a ClassNotFound exception for these classes.

How can I add my classes to the classpath for the MBean Explorer view?

(If it easier to do this with eclipse-jmx plugin, I'm happy to use that instead.)

答: An alternative solution would be to implement your jmx beans using open types.  then you won't have problems like this.  this problem will repeat itself if you try to use any other tools to interact with your mbeans.  best practice with mbeans is to stick to open types so you don't have to worry about client-side issues.</p>