问:
How to initialize a library in react-native
I'm trying to work with this react-native library, and in the documentation it says this:

Initialize Library
Somewhere high up in your project and way before calling any other method exposed by this library, your index file or equivalent is a good spot, ensure you initialize the library with your public key as follows:

```<code>import RNPaystack from 'react-native-paystack';

RNPaystack.init({ publicKey: 'YOUR_PUBLIC_KEY_HERE' });
</code>```

How do I do this, without getting null object is not a function.
In my app.js I tried it with useEffect, tried with componentwillmount , tried several ways, same error.
I feel I'm doing it wrongly.
Can someone tell how to initialize a library properly in react native.

Thanks :)

答: This is most likely happening because you haven't linked the native modules properly. That's expected as you mentioned you're using Expo, which doesn't allow you to add custom native code. If you want to use this library, you'll have to eject from Expo. See the docs.</p>

Body:
I'm trying to work with this react-native library, and in the documentation it says this:

Initialize Library
Somewhere high up in your project and way before calling any other method exposed by this library, your index file or equivalent is a good spot, ensure you initialize the library with your public key as follows:

import RNPaystack from 'react-native-paystack';

RNPaystack.init({ publicKey: 'YOUR_PUBLIC_KEY_HERE' });

How do I do this, without getting null object is not a function.
In my app.js I tried it with useEffect, tried with componentwillmount , tried several ways, same error.
I feel I'm doing it wrongly.
Can someone tell how to initialize a library properly in react native.

Thanks :)


来源: stackexchange

问:
error when trying to use keras.utils.plot_model
I am trying to make a plot/graph of deep learning model in Python using Keras package but unfortunately it keeps giving me an error which is not very informative.

I run python on Linux with Python 3.5.2, Anaconda 4.2.0, Keras 2.1.6 and I use tensorflow-gpu 1.7.0 Backend.

Here is the error message:

```<code>keras.utils.plot_model(unet, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB')

['dot', '-Tps', '/tmp/tmphesl1j0c'] return code: 127

stdout, stderr:
 b''
b'dot: error while loading shared libraries: libexpat.so.0: cannot open shared object file: No such file or directory\n'

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-60bb0e3b97bd> in <module>()
----> 1 keras.utils.plot_model(unet, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB')

/.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in plot_model(model, to_file, show_shapes, show_layer_names, rankdir)
    132             'LR' creates a horizontal plot.
    133     """
--> 134     dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
    135     _, extension = os.path.splitext(to_file)
    136     if not extension:

/.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in model_to_dot(model, show_shapes, show_layer_names, rankdir)
     53     from ..models import Sequential
     54
---> 55     _check_pydot()
     56     dot = pydot.Dot()
     57     dot.set('rankdir', rankdir)

/.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in _check_pydot()
     24         # Attempt to create an image of a blank graph
     25         # to check the pydot/graphviz installation.
---> 26         pydot.Dot.create(pydot.Dot())
     27     except OSError:
     28         raise OSError(

/.../anaconda3-4.2.0/lib/python3.5/site-packages/pydot.py in create(self, prog, format, encoding)
   1882                      out=stdout_data,
   1883                      err=stderr_data))
-> 1884         assert p.returncode == 0, p.returncode
   1885         return stdout_data

AssertionError: 127
</code>```

I would really appreciate if somebody could help me with this error.

Note: both pydot and graphviz are intalled

答: I solved the issue commenting line 117 program += extension in pydot.py

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a plot/graph of deep learning model in Python using Keras package but unfortunately it keeps giving me an error which is not very informative.

I run python on Linux with Python 3.5.2, Anaconda 4.2.0, Keras 2.1.6 and I use tensorflow-gpu 1.7.0 Backend.

Here is the error message:

keras.utils.plot_model(unet, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB')

['dot', '-Tps', '/tmp/tmphesl1j0c'] return code: 127

stdout, stderr:
 b''
b'dot: error while loading shared libraries: libexpat.so.0: cannot open shared object file: No such file or directory\n'

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-60bb0e3b97bd> in <module>()
----> 1 keras.utils.plot_model(unet, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB')

/.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in plot_model(model, to_file, show_shapes, show_layer_names, rankdir)
    132             'LR' creates a horizontal plot.
    133     """
--> 134     dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
    135     _, extension = os.path.splitext(to_file)
    136     if not extension:

/.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in model_to_dot(model, show_shapes, show_layer_names, rankdir)
     53     from ..models import Sequential
     54
---> 55     _check_pydot()
     56     dot = pydot.Dot()
     57     dot.set('rankdir', rankdir)

/.../anaconda3-4.2.0/lib/python3.5/site-packages/keras/utils/vis_utils.py in _check_pydot()
     24         # Attempt to create an image of a blank graph
     25         # to check the pydot/graphviz installation.
---> 26         pydot.Dot.create(pydot.Dot())
     27     except OSError:
     28         raise OSError(

/.../anaconda3-4.2.0/lib/python3.5/site-packages/pydot.py in create(self, prog, format, encoding)
   1882                      out=stdout_data,
   1883                      err=stderr_data))
-> 1884         assert p.returncode == 0, p.returncode
   1885         return stdout_data

AssertionError: 127

I would really appreciate if somebody could help me with this error.

Note: both pydot and graphviz are intalled


问:
How do you pass a url as a REST GET parameter in FLASK
So this is my code.

```<code>from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
app.config['DEBUG'] = True
api = Api(app)

# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app

class Default(Resource):
   def get(self, name):
    """Renders a sample page."""
    return "Hello " + name

class LiveStats(Resource):
  def get(self, url):
    return "Trying to get " + url

    # data = request.get(url)
    # return data

api.add_resource(Default, '/default/<string:name>') # Route_1
api.add_resource(LiveStats, '/liveStats/<path:url>') # Route_2

if __name__ == '__main__':
 import os
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
    PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
    PORT = 5555
app.run(HOST, PORT)
</code>```

Now firstly this post helped a lot. how-to-pass-urls-as-parameters-in-a-get-request-within-python-flask-restplus

Changing what I originally had.

```<code> api.add_resource(LiveStats, '/liveStats/<string:url>') # Route_2
</code>```

to this

```<code>api.add_resource(LiveStats, '/liveStats/<path:url>') # Route_2
</code>```

got rid of 404 errors that I had but now I am noticing that it's not passing all of the url.

Example if I try this

localhost:60933/liveStats/http://address/Statistics?NoLogo=1%26KSLive=1

I get this

Trying to get http://address/Statistics

so it has taken off ?NoLogo=1%26KSLive=1

How do you prevent this?

答:
All characters after the ? are considered parameters. From the docs:

To access parameters submitted in the URL (?key=value) you can use the args attribute:

searchword = request.args.get('key', '')

We recommend accessing URL
  parameters with get or by catching the KeyError because users might
  change the URL and presenting them a 400 bad request page in that case
  is not user friendly.

For a full list of methods and attributes of the request object, head
  over to the Request documentation.

Maybe you could encode the query string in a way that you can retrieve it as a single parameter on the back end, but not sure it would be useful.

If you don't want to access the args individually, you can access the full query string:

```<code>request.query_string
</code>```

Putting this all together I think this will work for you:

class LiveStats(Resource):
  def get(self, url):
    return "Trying to get " + url + request.query_string
```

Body:
So this is my code.

from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
app.config['DEBUG'] = True
api = Api(app)

# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app

class Default(Resource):
   def get(self, name):
    """Renders a sample page."""
    return "Hello " + name

class LiveStats(Resource):
  def get(self, url):
    return "Trying to get " + url

    # data = request.get(url)
    # return data

api.add_resource(Default, '/default/<string:name>') # Route_1
api.add_resource(LiveStats, '/liveStats/<path:url>') # Route_2

if __name__ == '__main__':
 import os
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
    PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
    PORT = 5555
app.run(HOST, PORT)

Now firstly this post helped a lot. how-to-pass-urls-as-parameters-in-a-get-request-within-python-flask-restplus

Changing what I originally had.

 api.add_resource(LiveStats, '/liveStats/<string:url>') # Route_2

to this

api.add_resource(LiveStats, '/liveStats/<path:url>') # Route_2

got rid of 404 errors that I had but now I am noticing that it's not passing all of the url.

Example if I try this

localhost:60933/liveStats/http://address/Statistics?NoLogo=1%26KSLive=1

I get this

Trying to get http://address/Statistics

so it has taken off ?NoLogo=1%26KSLive=1

How do you prevent this?

Body:
All characters after the ? are considered parameters. From the docs:

To access parameters submitted in the URL (?key=value) you can use the args attribute:

searchword = request.args.get('key', '')

We recommend accessing URL
  parameters with get or by catching the KeyError because users might
  change the URL and presenting them a 400 bad request page in that case
  is not user friendly.

For a full list of methods and attributes of the request object, head
  over to the Request documentation.

Maybe you could encode the query string in a way that you can retrieve it as a single parameter on the back end, but not sure it would be useful.

If you don't want to access the args individually, you can access the full query string:

request.query_string

Putting this all together I think this will work for you:

class LiveStats(Resource):
  def get(self, url):
    return "Trying to get " + url + request.query_string


问:
How to remove whitespace from a expression using a function with const char* pointer
I am working with a small piece of code and want to remove all the whitespaces from a simple expression. I am taking char array expression and passing it to an function with const char* pointer,but i am not able to remove the whitespace. here is what i tried, but didn't get desired output.

```<code>#include <iostream>

using namespace std;

void evaluate(const char *expression){

if (*expression == '\0') cout<<"Invalid"<<endl;

while(*expression){
    if(*expression == ' '){
        *expression++ ;
    }
    expression++;
 }

cout<<expression;

}

int main()
{
    char expr[] = "1 + 2 * 3";
    evaluate(expr);
    return 0;
}
</code>```

It will be great if someone can help me with this.
Thanks in advance.

答:
```<code>*expression++
</code>```

This only increments the pointer (and needlessly evaluates what it was pointing at). It does not modify the original character array.

If you want the expression in memory without spaces, rather than just for output purposes, I suggest that you build a new array with the spaces removed.

Body:
I am working with a small piece of code and want to remove all the whitespaces from a simple expression. I am taking char array expression and passing it to an function with const char* pointer,but i am not able to remove the whitespace. here is what i tried, but didn't get desired output.

#include <iostream>

using namespace std;

void evaluate(const char *expression){

if (*expression == '\0') cout<<"Invalid"<<endl;

while(*expression){
    if(*expression == ' '){
        *expression++ ;
    }
    expression++;
 }

cout<<expression;

}

int main()
{
    char expr[] = "1 + 2 * 3";
    evaluate(expr);
    return 0;
}

It will be great if someone can help me with this.
Thanks in advance.

Body:
*expression++

This only increments the pointer (and needlessly evaluates what it was pointing at). It does not modify the original character array.

If you want the expression in memory without spaces, rather than just for output purposes, I suggest that you build a new array with the spaces removed.


问:
c# linq: how to retrieve pieces of data from a returned record
So i have the query:

```<code> var query =
                from product in db.LUT_ProductInfos
                where product.flavor == flavor && product.Container == container
                select flavor;
</code>```

which is returning 1 record (it should always return one record). How do i pull individual attribute values from the result? For example, if it returns 1 record with 3 columns like firstName lastName phoneNumber, and i want to do something with each of the values like

```<code>string fName = firstName
string lName = lastName
int pNumber = phoneNumber
</code>```

without getting into data mapping for objects, what is the most direct way to extract those values from the result variable query

答:
```<code>var singleResult =
            (from product in db.LUT_ProductInfos
            where product.flavor == flavor && product.Container == container
            select flavor).Single();
string fName = singleResult.firstName
string lName = singleResult.lastName
int pNumber = singleResult.phoneNumber
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So i have the query:

 var query =
                from product in db.LUT_ProductInfos
                where product.flavor == flavor && product.Container == container
                select flavor;

which is returning 1 record (it should always return one record). How do i pull individual attribute values from the result? For example, if it returns 1 record with 3 columns like firstName lastName phoneNumber, and i want to do something with each of the values like

string fName = firstName
string lName = lastName
int pNumber = phoneNumber

without getting into data mapping for objects, what is the most direct way to extract those values from the result variable query


问:
Avoid composer's autoload.php to parse all files
Here is my problem: I have upgraded a complex application to PHP 7.4, and yes, I didn't test thoroughly enough.

Now I would like to run on task with an older PHP version, but it cannot parse all of my vendor files. Here is the error and the line. It's a new feature of PHP 7.4.

PHP Parse error:  syntax error, unexpected '?', expecting variable (T_VARIABLE) in .\vendor\sentry\sentry\src\functions.php on line 25

```<code> function captureMessage(string $message, ?Severity $level = null): ?string
</code>```

Until now I thought, that Composers vendor\autoload.php loads classes and functions in the vendor directory only on demand. Unused classes and therefore the offending files written in PHP 7.4 would not be loaded.

Unfortunately, I notice, that require_once('./vendor/autoload.php') is enough to see the parse error. Is it possible to configure Composer in a way, that it does not preload the vendor files, but loads them only once the classes or functions are requested ?

答:
In your composer.json, you can add platform into your config, to force it to resolve dependencies to a specific version of PHP.

https://getcomposer.org/doc/06-config.md#platform

```<code>"config": {
    "platform": {
        "php": "5.6"
    },
},
</code>```

Body:
Here is my problem: I have upgraded a complex application to PHP 7.4, and yes, I didn't test thoroughly enough.

Now I would like to run on task with an older PHP version, but it cannot parse all of my vendor files. Here is the error and the line. It's a new feature of PHP 7.4.

PHP Parse error:  syntax error, unexpected '?', expecting variable (T_VARIABLE) in .\vendor\sentry\sentry\src\functions.php on line 25

 function captureMessage(string $message, ?Severity $level = null): ?string

Until now I thought, that Composers vendor\autoload.php loads classes and functions in the vendor directory only on demand. Unused classes and therefore the offending files written in PHP 7.4 would not be loaded.

Unfortunately, I notice, that require_once('./vendor/autoload.php') is enough to see the parse error. Is it possible to configure Composer in a way, that it does not preload the vendor files, but loads them only once the classes or functions are requested ?

Body:
In your composer.json, you can add platform into your config, to force it to resolve dependencies to a specific version of PHP.

https://getcomposer.org/doc/06-config.md#platform

"config": {
    "platform": {
        "php": "5.6"
    },
},


问:
"dest.on is not a function" using postcss-rtl with gulp v4
I'm trying to transform a css document into rtl (right-to-left) using postcss-rtl and automate this using gulp. This is the error I get when I run gulp watch:

```<code>TypeError: dest.on is not a function
    at DestroyableTransform.Readable.pipe (D:\Projects\BootstrapRTL\node_modules\readable-stream\lib\_stream_readable.js:564:8)
    at rtlize (D:\Projects\BootstrapRTL\gulpfile.js:39:8)
    at rtlize (D:\Projects\BootstrapRTL\node_modules\undertaker\lib\set-task.js:13:15)
    at bound (domain.js:422:14)
    at runBound (domain.js:435:12)
    at asyncRunner (D:\Projects\BootstrapRTL\node_modules\async-done\index.js:55:18)
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
</code>```

This is my code for the specific function:

```<code>const gulp = require("gulp");
const postcss = require("postcss");
const rtl = require("postcss-rtl");

function rtlize() {
  return (
    // 1. Get the css file
    gulp
      .src("./css/main.css")
      // 2. Rtlize the css file
      .pipe(postcss(rtl()))
      // 3. Export the css file
      .pipe(gulp.dest("./css/rtl"))
  );
}

exports.rtlize = rtlize;
</code>```

答:
Change this:

See https://www.npmjs.com/package/postcss-rtl#with-gulp; from the docs:

```<code>.pipe( postcss( [ rtl( options ) ]) )  // should be like this
</code>```

Notice rtl is in an array.  Not .pipe(postcss(rtl())) as you have.

Body:
I'm trying to transform a css document into rtl (right-to-left) using postcss-rtl and automate this using gulp. This is the error I get when I run gulp watch:

TypeError: dest.on is not a function
    at DestroyableTransform.Readable.pipe (D:\Projects\BootstrapRTL\node_modules\readable-stream\lib\_stream_readable.js:564:8)
    at rtlize (D:\Projects\BootstrapRTL\gulpfile.js:39:8)
    at rtlize (D:\Projects\BootstrapRTL\node_modules\undertaker\lib\set-task.js:13:15)
    at bound (domain.js:422:14)
    at runBound (domain.js:435:12)
    at asyncRunner (D:\Projects\BootstrapRTL\node_modules\async-done\index.js:55:18)
    at processTicksAndRejections (internal/process/task_queues.js:75:11)

This is my code for the specific function:

const gulp = require("gulp");
const postcss = require("postcss");
const rtl = require("postcss-rtl");

function rtlize() {
  return (
    // 1. Get the css file
    gulp
      .src("./css/main.css")
      // 2. Rtlize the css file
      .pipe(postcss(rtl()))
      // 3. Export the css file
      .pipe(gulp.dest("./css/rtl"))
  );
}

exports.rtlize = rtlize;

Body:
Change this:

See https://www.npmjs.com/package/postcss-rtl#with-gulp; from the docs:

.pipe( postcss( [ rtl( options ) ]) )  // should be like this

Notice rtl is in an array.  Not .pipe(postcss(rtl())) as you have.


问:
Django url unit test comparison of expected view function fails
```<code>class TestsUrls(SimpleTestCase):

def test_index_url_is_resolved(self):
    url = reverse('index')
    self.assertEquals(resolve(url).func, index)
</code>```

I am trying to unit test url to see if it returns the expected view. This assertion fails even though it looks like the functions are the same. I am using function based views, not class based views. Does that have something to do with it?

```<code>AssertionError: <function index at 0x11db7cb70> != <function index at 0x11d860ae8>
</code>```

答:
It's not clear how you get index, but resolve(url).func returns an instance of the python object that is the function. Everything in python are objects, also functions, so you get an instance in memory. When you compare the two objects, you are comparing different instances of the same function. As you can see their addresses in memory are different.

So instead of directly comparing them, compare their name and module:

```<code>f = resolve(url).func
self.assertEqual(f.__name__, index.__name__)
self.assertEqual(f.__module__, index.__module__)
</code>```

Body:
class TestsUrls(SimpleTestCase):

def test_index_url_is_resolved(self):
    url = reverse('index')
    self.assertEquals(resolve(url).func, index)

I am trying to unit test url to see if it returns the expected view. This assertion fails even though it looks like the functions are the same. I am using function based views, not class based views. Does that have something to do with it?

AssertionError: <function index at 0x11db7cb70> != <function index at 0x11d860ae8>

Body:
It's not clear how you get index, but resolve(url).func returns an instance of the python object that is the function. Everything in python are objects, also functions, so you get an instance in memory. When you compare the two objects, you are comparing different instances of the same function. As you can see their addresses in memory are different.

So instead of directly comparing them, compare their name and module:

f = resolve(url).func
self.assertEqual(f.__name__, index.__name__)
self.assertEqual(f.__module__, index.__module__)


问:
Is there specific reason for naming PWM channels as LEDC in Arduino
Out of curiosity, why the PWM channels in ARDUINO  are named LEDC ?</p>

答:
ESP32 is not an Arduino, and it does not make sense to emulate Arduino's analogWrite completely for an ESP32, when adding support for ESP32 PWM to the Arduino IDE. (Besides the fact that analogWrite` is a misleading name anyway)

Why-questions are always complicated (I know by my granddaughter) so additionally to

Why did they call it "ledcXyz"

I'd rather add

Why is there the "sigmaDelta" Extension as well

if we talk about the espressif Arduino Extension


问:
Button not appearing in my Linear Layout
I have a button inside of a LinearLayout that is oriented vertically. Not sure why the button doesn't show up?</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<com.commonsware.cwac.tlv.TouchListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tlv="http://schemas.android.com/apk/res/org.stocktwits.activity"

    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:drawSelectorOnTop="false"
    tlv:normal_height="64dip"
    tlv:grabber="@+id/icon"
    tlv:remove_mode="slideRight"
android:layout_height="wrap_content"/>
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>
</code>```

答: android:height="wrap_content" has no meaning for vertically-scrollable widgets like ListView. Use android:layout_weight with your LinearLayout or a RelativeLayout to achieve whatever look you are trying to achieve.

Body:
I have a button inside of a LinearLayout that is oriented vertically. Not sure why the button doesn't show up?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<com.commonsware.cwac.tlv.TouchListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tlv="http://schemas.android.com/apk/res/org.stocktwits.activity"

    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:drawSelectorOnTop="false"
    tlv:normal_height="64dip"
    tlv:grabber="@+id/icon"
    tlv:remove_mode="slideRight"
android:layout_height="wrap_content"/>
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>


问:
Error connecting to websockets NodeJS Express server
I have an express server with websockets configured:

```<code>/tmp/ws-test $ cat httpServer.js
const express = require('express');
const WebSocket = require('ws');

const app = express();
const port = 8080;

app.get('/', function(req, res, next) {
  return res.send('Hello World!');
});

const wss = new WebSocket.Server({ server: app });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });
  ws.send('something from server');
});

app.listen(port, function(err) {
  if (err) {
    throw err;
  }
  console.log(`listening on port ${port}!`);
});
</code>```

It runs as expected:

```<code>/tmp/ws-test $ node httpServer.js
listening on port 8080!
</code>```

I have a client:

```<code>/tmp/ws-test $ cat client.js
const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
  ws.send('something from client');
});

ws.on('message', function incoming(data) {
  console.log(`received: ${data}`);
});
</code>```

It errors:

```<code>/tmp/ws-test $ node client.js
events.js:180
      throw er; // Unhandled 'error' event
      ^

Error: Unexpected server response: 200
    at ClientRequest.<anonymous> (/private/tmp/ws-test/node_modules/ws/lib/websocket.js:579:7)
    at ClientRequest.emit (events.js:203:13)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:575:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:17)
    at Socket.socketOnData (_http_client.js:449:22)
    at Socket.emit (events.js:203:13)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:276:11)
    at Socket.Readable.push (_stream_readable.js:210:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:166:17)
Emitted 'error' event at:
    at abortHandshake (/private/tmp/ws-test/node_modules/ws/lib/websocket.js:697:15)
    at ClientRequest.<anonymous> (/private/tmp/ws-test/node_modules/ws/lib/websocket.js:579:7)
    [... lines matching original stack trace ...]
    at Socket.Readable.push (_stream_readable.js:210:10)
</code>```

In the client I also tried using http for the web socket connection.

```<code>const ws = new WebSocket('http://localhost:8080');
</code>```

But it throws the same error.

Why is the client erroring on connection to the server?

答:
You should pass an http server instance to WebSocket.Server constructor instead of an instance of express application:

```<code>const express = require('express');
const WebSocket = require('ws');
const http = require('http');

const app = express();
const port = 8080;

const server = http.createServer(app);

app.get('/', function(req, res, next) {
    return res.send('Hello World!');
});

const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
    });
    ws.send('something from server');
});

server.listen(port, function(err) {
    if (err) {
        throw err;
    }
    console.log(`listening on port ${port}!`);
});
</code>```

Body:
I have an express server with websockets configured:

/tmp/ws-test $ cat httpServer.js
const express = require('express');
const WebSocket = require('ws');

const app = express();
const port = 8080;

app.get('/', function(req, res, next) {
  return res.send('Hello World!');
});

const wss = new WebSocket.Server({ server: app });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });
  ws.send('something from server');
});

app.listen(port, function(err) {
  if (err) {
    throw err;
  }
  console.log(`listening on port ${port}!`);
});

It runs as expected:

/tmp/ws-test $ node httpServer.js
listening on port 8080!

I have a client:

/tmp/ws-test $ cat client.js
const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
  ws.send('something from client');
});

ws.on('message', function incoming(data) {
  console.log(`received: ${data}`);
});

It errors:

/tmp/ws-test $ node client.js
events.js:180
      throw er; // Unhandled 'error' event
      ^

Error: Unexpected server response: 200
    at ClientRequest.<anonymous> (/private/tmp/ws-test/node_modules/ws/lib/websocket.js:579:7)
    at ClientRequest.emit (events.js:203:13)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:575:27)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:17)
    at Socket.socketOnData (_http_client.js:449:22)
    at Socket.emit (events.js:203:13)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:276:11)
    at Socket.Readable.push (_stream_readable.js:210:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:166:17)
Emitted 'error' event at:
    at abortHandshake (/private/tmp/ws-test/node_modules/ws/lib/websocket.js:697:15)
    at ClientRequest.<anonymous> (/private/tmp/ws-test/node_modules/ws/lib/websocket.js:579:7)
    [... lines matching original stack trace ...]
    at Socket.Readable.push (_stream_readable.js:210:10)

In the client I also tried using http for the web socket connection.

const ws = new WebSocket('http://localhost:8080');

But it throws the same error.

Why is the client erroring on connection to the server?

Body:
You should pass an http server instance to WebSocket.Server constructor instead of an instance of express application:

const express = require('express');
const WebSocket = require('ws');
const http = require('http');

const app = express();
const port = 8080;

const server = http.createServer(app);

app.get('/', function(req, res, next) {
    return res.send('Hello World!');
});

const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
    });
    ws.send('something from server');
});

server.listen(port, function(err) {
    if (err) {
        throw err;
    }
    console.log(`listening on port ${port}!`);
});


问:
how can I dynamically fill the other selections with the only options that have the same id?
if I had three selections dropdown, and I select an option in one of the three selections, how can I dynamically fill the other selections with the only options that have the same id?</p>

答:
Let's say you want to create a 2 dropdowns to select a car brand and populate the second one with the corresponding cars models.

First, you need an array (or dataset) that contains all brands. Then, you should populate the dropdowns with that data.

const models = [{
    0: 'Uno',
    1: 'Eco Sport'
  },
  {
    0: 'Camaro',
    1: 'Prisma'
  },
  {
    0: 'i10',
    1: 'i20'
  }];

const selectBrands = document.getElementById('brands');
const selectModels = document.getElementById('models');

// Add an change event listener into the brands' select
selectBrands.addEventListener('change', (event) => {
  const brandId = event.target.value;
  const brandModels = models[brandId];

  // Clear the input
  selectModels.innerHTML = '<option value="">Select a model</option>';

  // Populate the input with the corresponding brand models
  Object.keys(brandModels).forEach((idx) => {
    const option = document.createElement('option');
    option.text = brandModels[idx];
    selectModels.options.add(option);
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="brands" id="brands">
  <option value="">Select a brand</option>
  <option value="0">Fiat</option>
  <option value="1">GM</option>
  <option value="2">Hyundai</option>
</select>
<br />
<select name="models" id="models">
  <option value="">Select a model</option>
</select></code>```

If you need a 3rd dropdown, just repeat the same approach used to make the relation between the 1st and the 2nd one.

Body:
Let's say you want to create a 2 dropdowns to select a car brand and populate the second one with the corresponding cars models.

First, you need an array (or dataset) that contains all brands. Then, you should populate the dropdowns with that data.

const models = [{
    0: 'Uno',
    1: 'Eco Sport'
  },
  {
    0: 'Camaro',
    1: 'Prisma'
  },
  {
    0: 'i10',
    1: 'i20'
  }];

const selectBrands = document.getElementById('brands');
const selectModels = document.getElementById('models');

// Add an change event listener into the brands' select
selectBrands.addEventListener('change', (event) => {
  const brandId = event.target.value;
  const brandModels = models[brandId];

  // Clear the input
  selectModels.innerHTML = '<option value="">Select a model</option>';

  // Populate the input with the corresponding brand models
  Object.keys(brandModels).forEach((idx) => {
    const option = document.createElement('option');
    option.text = brandModels[idx];
    selectModels.options.add(option);
  });

});

<select name="brands" id="brands">
  <option value="">Select a brand</option>
  <option value="0">Fiat</option>
  <option value="1">GM</option>
  <option value="2">Hyundai</option>
</select>
<br />
<select name="models" id="models">
  <option value="">Select a model</option>
</select>

If you need a 3rd dropdown, just repeat the same approach used to make the relation between the 1st and the 2nd one.


答:
Your original assumption was correct: in general, the PHP autoloader only loads classes when they are used, and Composer simply provides an implementation of that autoloader.

However, Composer also includes a feature to unconditionally load a file. This is used when a package contains functions, constants, or configuration, which cannot be loaded on-demand (because PHP's autoloader only handles classes).

One of the packages you are using uses this feature, so every time you include vendor/autoload.php, the file it specifies is required. In the error message shown, we can see the package name sentry/sentry, and in that package's composer.json, we can see this:

```<code>"autoload": {
    "files": [
        "src/functions.php"
    ],
    "psr-4": {
        "Sentry\\": "src/"
    }
},
</code>```

The best way around this is probably to downgrade this dependency, and any others which include code that only runs under PHP 7.4. To do this, you can simply re-run composer update on your older version of PHP, and it will only pick up packages which support that version.

You can also specify the platform option in your composer.json to always request dependencies for an older PHP version, even when you are running Composer under PHP 7.4. However, there is a risk that the resulting dependencies will be incompatible with PHP 7.4.

Title: Avoid composer's autoload.php to parse all files

Body:
Your original assumption was correct: in general, the PHP autoloader only loads classes when they are used, and Composer simply provides an implementation of that autoloader.

However, Composer also includes a feature to unconditionally load a file. This is used when a package contains functions, constants, or configuration, which cannot be loaded on-demand (because PHP's autoloader only handles classes).

One of the packages you are using uses this feature, so every time you include vendor/autoload.php, the file it specifies is required. In the error message shown, we can see the package name sentry/sentry, and in that package's composer.json, we can see this:

"autoload": {
    "files": [
        "src/functions.php"
    ],
    "psr-4": {
        "Sentry\\": "src/"
    }
},

The best way around this is probably to downgrade this dependency, and any others which include code that only runs under PHP 7.4. To do this, you can simply re-run composer update on your older version of PHP, and it will only pick up packages which support that version.

You can also specify the platform option in your composer.json to always request dependencies for an older PHP version, even when you are running Composer under PHP 7.4. However, there is a risk that the resulting dependencies will be incompatible with PHP 7.4.


问:
How Do I Expand A Cell in MUI-Datatables to display additional content?
I want a user to be able to click a row in the MUI-Datatable, so they can see additional content. The current renderExpandableRow function has the right styling, but I don't want a new row. I want the cell in the first column to show additional data. Is there a way to do this?

Note: I'm also going to need buttons that will expand all/collapse all, so I need a solution flexible enough to do that.

答:
I found a solution to my question.

I made the first column's content a Button using customBodyRender. The column with expandable content became the second column. This column has a customBodyRender with a Collapse component. I store in my component's state all ids of my data objects and whether or not they are expanded. When the Button is clicked, my component's state is updated, which in turn changes whether or not the Collapse component is open.

I also used customToolbar in the table options to generate an expand all/collapse all button, which just sets the state of all rows to expanded/collapsed.


问:
Bootstrap 4 - How to achieve this layout
I'm currently working on a website and I have come across with the following problem thinking the best practice to achieve the following layout using Bootstrap 4. (Wrapped in Red)

As you can see the first column is a col-md-7 and the other one is col-md-5. However, the first column includes an image and it has to touch the left corner of the page. However, the right column has to have the standard width and column size. To give you more insight following is what I'm trying to achieve.

```<code>[JS Fiddle][2]
</code>```

答:
You mean something like that using align-self-start class?

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

.image {
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<div class="container">
  <div class="row d-flex">
    <div class="col image">
      Image
    </div>
    <div class="col align-self-start">
      Test
    </div>
  </div>
</div></code>```

Body:
I'm currently working on a website and I have come across with the following problem thinking the best practice to achieve the following layout using Bootstrap 4. (Wrapped in Red)

As you can see the first column is a col-md-7 and the other one is col-md-5. However, the first column includes an image and it has to touch the left corner of the page. However, the right column has to have the standard width and column size. To give you more insight following is what I'm trying to achieve.

[JS Fiddle][2]

Body:
You mean something like that using align-self-start class?

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

.image {
  height: 200px;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<div class="container">
  <div class="row d-flex">
    <div class="col image">
      Image
    </div>
    <div class="col align-self-start">
      Test
    </div>
  </div>
</div>


问:
replace several matches of a substring with their indexes
assuming that you have a string with multiple occurrences of the same substring what would be the best one-liner to replace the matches with their another substring which contains the index of the math as well? As an example, let's say you have the following string: This is a test. and we want to replace all the occurrences of is with X and their index to have something like: ThX-0 X-1 a test.

Any ideas on this?

答:
Here is one alternative gnu-awk one liner:

```<code>echo 'This is a test.' | awk -v RS='[iI][sS]' '{ORS = "X-" i++} 1'
</code>```

```<code>ThX-0 X-1 a test.
</code>```

To reset counter for each line:

```<code>printf '%s\n%s\n' 'This is a test.' 'This is another this' |
awk -v RS='[iI][sS]' '/\n/{i=0} {ORS = "X-" i++} 1'
</code>```

```<code>ThX-0 X-1 a test.
ThX-0 X-1 another thX-2
</code>```

Body:
Here is one alternative gnu-awk one liner:

echo 'This is a test.' | awk -v RS='[iI][sS]' '{ORS = "X-" i++} 1'

ThX-0 X-1 a test.

To reset counter for each line:

printf '%s\n%s\n' 'This is a test.' 'This is another this' |
awk -v RS='[iI][sS]' '/\n/{i=0} {ORS = "X-" i++} 1'

ThX-0 X-1 a test.
ThX-0 X-1 another thX-2


问:
Exchange data.table columns with most prevalent value of columns
I have data

```<code>test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)
</code>```

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

```<code>test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)
</code>```

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

```<code>test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]
</code>```

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

```<code>test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))
</code>```

答:
I was able to make an OK solution, but if somebody can do it more elegantly, for example not going through the step of storting a list in refLevel below, please let me know! I'm very interested in learning data.table properly!

```<code>#solution:
test = data.table(a = c(1,1,3,4,5,6), b = c("a", "be", "a", "c", "d", "c"), c = rep(1, 6))
test2 = unique(test, by="a")
funPrev = function(x){unlist(as.data.table(x)[, .N, by=x][order(-N)][1,1], use.names = F)}
refLevel = lapply(test[, c("b", "c")], funPrev)
test2[, c("b", "c") := refLevel]
</code>```

...and using a function (if anybody see any un-necessary step, please let me know):

```<code>genData = function(dt, var_unique, vars_prev){

  data = copy(dt)
  data = unique(data, by = var_unique)

  funPrev = function(x){unlist(as.data.table(x)[, .N, by=x][order(-N)][1,1], use.names = F)}

  refLevel = lapply(dt[, .SD, .SDcols = vars_prev], funPrev)
  data[, (vars_prev) := refLevel]

  return(data)
}
test2 = genData(test, "a", c("b", "c"))
</code>```

Body:
I have data

test = data.table(
  a = c(1,1,3,4,5,6),
  b = c("a", "be", "a", "c", "d", "c"),
  c = rep(1, 6)
)

I wish to take the unique values of column a, store it in another data.table, and afterwards fill in the remaining columns with the most prevalent values of those remaining columns, such that my resulting data.table would be:

test2 = data.table(a = c(1,3,4,5,6), b = "a", c = 1)

Column be has equal amounts of "a" and "c", but it doesn't matter which is chosen in those cases.

Attempt so far:

test2 = unique(test, by = "a")
test2[, c("b", "c") := lapply(.SD, FUN = function(x){test2[, .N, by = x][order(-N)][1,1]}), .SDcols = c("b", "c")]

EDIT: I would preferrably like a generic solution that is compatible with a function where I specify the column to be "uniqued", and the rest of the columns are with the single most prevalent value. Hence my use of lapply and .SD =)

EDIT2: as @MichaelChirico points out, how do we keep the class. With the following data.table some of the solutions does not work, although solution of @chinsoon12 does work:

test = data.table(a = c(1,1,3,4,5,6),
                  b = c("a", "be", "a", "c", "d", "c"),
                  c = rep(1, 6),
                  d = as.Date("2019-01-01"))

Body:
I was able to make an OK solution, but if somebody can do it more elegantly, for example not going through the step of storting a list in refLevel below, please let me know! I'm very interested in learning data.table properly!

#solution:
test = data.table(a = c(1,1,3,4,5,6), b = c("a", "be", "a", "c", "d", "c"), c = rep(1, 6))
test2 = unique(test, by="a")
funPrev = function(x){unlist(as.data.table(x)[, .N, by=x][order(-N)][1,1], use.names = F)}
refLevel = lapply(test[, c("b", "c")], funPrev)
test2[, c("b", "c") := refLevel]

...and using a function (if anybody see any un-necessary step, please let me know):

genData = function(dt, var_unique, vars_prev){

  data = copy(dt)
  data = unique(data, by = var_unique)

  funPrev = function(x){unlist(as.data.table(x)[, .N, by=x][order(-N)][1,1], use.names = F)}

  refLevel = lapply(dt[, .SD, .SDcols = vars_prev], funPrev)
  data[, (vars_prev) := refLevel]

  return(data)
}
test2 = genData(test, "a", c("b", "c"))


问:
I am getting a "no access" error after Oauth facebook login
My buttons pop up and let me login but when it goes to redirect me to the next page, I get an error stating no access from the api and another error saying name isn't defined, I know name is defined because I had this working once before with the same code but then vscode did something stupid and broke it. Here is my code.

```<code>    import React, {Component} from 'react';
    import FacebookLogin from 'react-facebook-login';
    import GoogleLogin from 'react-google-login';
    import {PostData} from '../../services/PostData';
    import {Redirect} from 'react-router-dom';
    import './Welcome.css';

    class Welcome extends Component {
      constructor (props) {
        super (props);
        this.state = {
          loginError: false,
          redirect: false,
        };
        this.signup = this.signup.bind (this);
      }

      signup (res, type) {
        let postData;
        if (type === 'facebook' && res.email) {
          postData = {
            name: res.name,
            provider: type,
            email: res.email,
            provider_id: res.id,
            token: res.accessToken,
            provider_pic: res.picture.data.url,
          };
        }

        if (type === 'google' && res.w3.U3) {
          postData = {
            name: res.w3.ig,
            provider: type,
            email: res.w3.U3,
            provider_id: res.El,
            token: res.Zi.access_token,
            provider_pic: res.w3.Paa,
          };
        }

        if (postData) {
          PostData ('signup', postData).then (result => {
            let responseJson = result;
            sessionStorage.setItem ('userData', JSON.stringify (responseJson));
            this.setState ({redirect: true});
          });
        } else {
        }
      }

      render () {
        if (this.state.redirect || sessionStorage.getItem ('userData')) {
          return <Redirect to={'/home'} />;
        }

        const responseFacebook = response => {
          console.log ('facebook console');
          console.log (response);
          this.signup (response, 'facebook');
        };

        const responseGoogle = response => {
          console.log ('google console');
          console.log (response);
          this.signup (response, 'google');
        };

        return (
          <div>
            <FacebookLogin
              appId="2580971392000123"
              autoLoad={false}
              fields="name,email,picture"
              callback={responseFacebook}
            />
            <br /><br />

            <GoogleLogin
              clientId="234567891765550-duk7c1do3705dlj8i6dnsr27oe7rlaq3.apps.googleusercontent.com"
              buttonText="Login with Google"
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
            />

          </div>
        );
      }
    }

    export default Welcome;
</code>```

So it goes from the welcome component to the Home component, here is the code for  Home where the error is.

    import React, {Component} from 'react';
    import './Home.css';
    import {Redirect} from 'react-router-dom';
    class Home extends Component {
      constructor (props) {
        super (props);
        this.state = {
          name: '',
          redirect: false,
          products: [],
          pid: '',
        };
      }

      componentDidMount () {
        let data = JSON.parse (sessionStorage.getItem ('userData'));
        console.log (data);

        this.setState ({name: data.userData.name});
      }

      render () {
        if (!sessionStorage.getItem ('userData') || this.state.redirect) {
          return <Redirect to={'/'} />;
        }

        if (this.state.pid > 0) {
          return <Redirect to={'/checkout'} />;
        }

        return (

            Welcome {this.state.name}

        );
      }
    }

    export default Home;
```

<p>Here is the error I am getting: </p>

<pre class="lang-js prettyprint-override"><code>    [HMR] Waiting for update signal from WDS...
    react-dom.development.js:20718 Download the React DevTools for a better development experience:
    log.js:24 [HMR] Waiting for update signal from WDS...
    Home.js:17 {error: {…}}error: {text: "No access"}__proto__: Object
    Home.js:19 Uncaught TypeError: Cannot read property 'name' of undefined
        at Home.componentDidMount (Home.js:19)
        at commitLifeCycles (react-dom.development.js:16855)
        at commitAllLifeCycles (react-dom.development.js:18210)
        at HTMLUnknownElement.callCallback (react-dom.development.js:149)
        at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
        at invokeGuardedCallback (react-dom.development.js:256)
        at commitRoot (react-dom.development.js:18418)
        at completeRoot (react-dom.development.js:19875)
        at performWorkOnRoot (react-dom.development.js:19804)
        at performWork (react-dom.development.js:19712)
</code>```

I am new to React and coding in general, so sorry in advance if I sound stupid.

答:
This error means you don't have a valid token/login. Judging by the error Cannot read property 'name' of undefined, I'd say you're trying to get the name property from an object that does not contain it or does not exist (which is more likely). You may have defined name, but that definition is outside the scope of the name call.

The Problem

You are trying to set name in postData to res.name, but res.name is never defined.

The Solution

Find where res is created, and create or add the name property in the constructor.

Body:
My buttons pop up and let me login but when it goes to redirect me to the next page, I get an error stating no access from the api and another error saying name isn't defined, I know name is defined because I had this working once before with the same code but then vscode did something stupid and broke it. Here is my code.

    import React, {Component} from 'react';
    import FacebookLogin from 'react-facebook-login';
    import GoogleLogin from 'react-google-login';
    import {PostData} from '../../services/PostData';
    import {Redirect} from 'react-router-dom';
    import './Welcome.css';

    class Welcome extends Component {
      constructor (props) {
        super (props);
        this.state = {
          loginError: false,
          redirect: false,
        };
        this.signup = this.signup.bind (this);
      }

      signup (res, type) {
        let postData;
        if (type === 'facebook' && res.email) {
          postData = {
            name: res.name,
            provider: type,
            email: res.email,
            provider_id: res.id,
            token: res.accessToken,
            provider_pic: res.picture.data.url,
          };
        }

        if (type === 'google' && res.w3.U3) {
          postData = {
            name: res.w3.ig,
            provider: type,
            email: res.w3.U3,
            provider_id: res.El,
            token: res.Zi.access_token,
            provider_pic: res.w3.Paa,
          };
        }

        if (postData) {
          PostData ('signup', postData).then (result => {
            let responseJson = result;
            sessionStorage.setItem ('userData', JSON.stringify (responseJson));
            this.setState ({redirect: true});
          });
        } else {
        }
      }

      render () {
        if (this.state.redirect || sessionStorage.getItem ('userData')) {
          return <Redirect to={'/home'} />;
        }

        const responseFacebook = response => {
          console.log ('facebook console');
          console.log (response);
          this.signup (response, 'facebook');
        };

        const responseGoogle = response => {
          console.log ('google console');
          console.log (response);
          this.signup (response, 'google');
        };

        return (

            <FacebookLogin
              appId="2580971392000123"
              autoLoad={false}
              fields="name,email,picture"
              callback={responseFacebook}
            />

            <GoogleLogin
              clientId="234567891765550-duk7c1do3705dlj8i6dnsr27oe7rlaq3.apps.googleusercontent.com"
              buttonText="Login with Google"
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
            />

        );
      }
    }

    export default Welcome;

So it goes from the welcome component to the Home component, here is the code for  Home where the error is.

    import React, {Component} from 'react';
    import './Home.css';
    import {Redirect} from 'react-router-dom';
    class Home extends Component {
      constructor (props) {
        super (props);
        this.state = {
          name: '',
          redirect: false,
          products: [],
          pid: '',
        };
      }

      componentDidMount () {
        let data = JSON.parse (sessionStorage.getItem ('userData'));
        console.log (data);

        this.setState ({name: data.userData.name});
      }

      render () {
        if (!sessionStorage.getItem ('userData') || this.state.redirect) {
          return <Redirect to={'/'} />;
        }

        if (this.state.pid > 0) {
          return <Redirect to={'/checkout'} />;
        }

        return (

            Welcome {this.state.name}

        );
      }
    }

    export default Home;

Here is the error I am getting:

    [HMR] Waiting for update signal from WDS...
    react-dom.development.js:20718 Download the React DevTools for a better development experience:
    log.js:24 [HMR] Waiting for update signal from WDS...
    Home.js:17 {error: {…}}error: {text: "No access"}__proto__: Object
    Home.js:19 Uncaught TypeError: Cannot read property 'name' of undefined
        at Home.componentDidMount (Home.js:19)
        at commitLifeCycles (react-dom.development.js:16855)
        at commitAllLifeCycles (react-dom.development.js:18210)
        at HTMLUnknownElement.callCallback (react-dom.development.js:149)
        at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
        at invokeGuardedCallback (react-dom.development.js:256)
        at commitRoot (react-dom.development.js:18418)
        at completeRoot (react-dom.development.js:19875)
        at performWorkOnRoot (react-dom.development.js:19804)
        at performWork (react-dom.development.js:19712)

I am new to React and coding in general, so sorry in advance if I sound stupid.


问:
jQuery, optimal usage question
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

```<code>var thingy = $('#thingy');
</code>```

Further down in the code, is there any difference in reusing thingy:

```<code>thingy.empty();
</code>```

versus just making the jQuery again? :

```<code>$('#thingy').empty();
</code>```

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.

答:
Generally speaking, you will want to "cache" the results of the selector as long as you're sure they won't be changing.

Your example is fairly trivial, in that the #id selector is already quite efficient (essentially, it just passes it straight to a document.getElementById() call.

As others have mentioned, you start to see the savings when you use less performant selectors (such as $('.class') ).

By using variables in this way, you're able to save a lot of additional processing. ex:

```<code>var tree = $('.bigTree');

// Do random stuff with tree
// ...

var segment = tree.find('.subsection');

// Do random stuff with segment...
</code>```

In the above example, the variable "segment" is able to use the results of the variable tree, without having to access the whole DOM again, saving you that bit of performance. While trivial examples like this are rarely worth the effort, making sure you are doing this sort of thing for bits of code (such as loops) can help speed up your application significantly.

Of course, make sure that if you are dynamically updating the DOM, that you are using a "fresh" selector to ensure you pick up any changes :)

Title: jQuery, optimal usage question

Body:
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

var thingy = $('#thingy');

Further down in the code, is there any difference in reusing thingy:

thingy.empty();

versus just making the jQuery again? :

$('#thingy').empty();

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.

Body:
Generally speaking, you will want to "cache" the results of the selector as long as you're sure they won't be changing.

Your example is fairly trivial, in that the #id selector is already quite efficient (essentially, it just passes it straight to a document.getElementById() call.

As others have mentioned, you start to see the savings when you use less performant selectors (such as $('.class') ).

By using variables in this way, you're able to save a lot of additional processing. ex:

var tree = $('.bigTree');

// Do random stuff with tree
// ...

var segment = tree.find('.subsection');

// Do random stuff with segment...

In the above example, the variable "segment" is able to use the results of the variable tree, without having to access the whole DOM again, saving you that bit of performance. While trivial examples like this are rarely worth the effort, making sure you are doing this sort of thing for bits of code (such as loops) can help speed up your application significantly.

Of course, make sure that if you are dynamically updating the DOM, that you are using a "fresh" selector to ensure you pick up any changes :)


问:
How to split path and file names from multiple items from a list
This is a list below

```<code>list = ['C:/Users/user/Desktop/1.docx', 'C:/Users/user/Desktop/2.docx',
'C:/Users/user/Desktop/3.docx']
</code>```

I want to split path and file names from the list like this:

```<code>pathlist = ['C:/Users/user/Desktop/'], and filelist = ['1.docx', '2.docx', '3.docx']
</code>```

Any help and suggestions will be appreciated

答:
import os
pathlist = list(set(os.path.dirname(name) for name in list))
filelist = list(set(os.path.basename(name) for name in list))
```

Body:
This is a list below

list = ['C:/Users/user/Desktop/1.docx', 'C:/Users/user/Desktop/2.docx',
'C:/Users/user/Desktop/3.docx']

I want to split path and file names from the list like this:

pathlist = ['C:/Users/user/Desktop/'], and filelist = ['1.docx', '2.docx', '3.docx']

Any help and suggestions will be appreciated


问:
Conditional background color on a n row
so I have this table where I would like to only background color the 4th row. I tried many things however I am unable to color a single individual row.

here is my style

```<code> tableRow: {
    borderTopColor: Colors.dividerColor,
    borderTopWidth: 1,
    flex: 1,
    flexDirection: 'row',
    padding: Spacing.globalPaddingSmall,
    // backgroundColor: "red" I want only to color the 4th row
  },
</code>```

and here is my table

```<code>  <View style={tableStyles.tableRow}>
    <Text style={tableStyles.tableTextFirst}>{sensor}</Text>
                        <Text style={tableStyles.tableText}>{daily}</Text>
                        <Text style={tableStyles.tableText}>{weekley}</Text>
                        <Text style={tableStyles.tableText}>{monthley}</Text>
    <Text style={tableStyles.tableText}>{average}</Text> //only color this one
  </View>
</code>```

答:
add:

```<code>redRow: {
  backgroundColor: "red"
}
</code>```

to your styles and then use it like this

<Text style={[tableStyles.redRow, tableStyles.tableText]}>{average}</Text>

see example: https://facebook.github.io/react-native/docs/style

Title: Conditional background color on a n row

Body:
so I have this table where I would like to only background color the 4th row. I tried many things however I am unable to color a single individual row.

here is my style

 tableRow: {
    borderTopColor: Colors.dividerColor,
    borderTopWidth: 1,
    flex: 1,
    flexDirection: 'row',
    padding: Spacing.globalPaddingSmall,
    // backgroundColor: "red" I want only to color the 4th row
  },

and here is my table

  <View style={tableStyles.tableRow}>
    <Text style={tableStyles.tableTextFirst}>{sensor}</Text>
                        <Text style={tableStyles.tableText}>{daily}</Text>
                        <Text style={tableStyles.tableText}>{weekley}</Text>
                        <Text style={tableStyles.tableText}>{monthley}</Text>
    <Text style={tableStyles.tableText}>{average}</Text> //only color this one
  </View>

Body:
add:

redRow: {
  backgroundColor: "red"
}

to your styles and then use it like this

<Text style={[tableStyles.redRow, tableStyles.tableText]}>{average}</Text>

see example: https://facebook.github.io/react-native/docs/style


问:
How I do properly import serial data from arduino using pycharm
I am newbie in python.

After I installed python 3.8 latest version, libraries ...etc
Pycharm IDE, and for every time you create project you have to install packages so your code look nice with no red line under.
after I spent hours trying to find whats going on, Error, visual studio  ++14 and not 15 or 19.

The code line, import serial doesn't seem recognized by pycharm or by python.

I have read many people having the same problem but few were successful to solve, other are still not.

My Problem is that I need to plot data from arduino using python over serial.

Anyone have an idea how to solve the import serial not working?

The code implemented:

```<code>import serial                       , error
import numpy as np                package not found but managed to install it and have to install it again
import matplotlib.pyplot as plt
%matplotlib qt

ser = serial.Serial('COM4',9600)   Syntax error
</code>```

Just tried to install matplotlib package, I got this error

```<code>ModuleNotFoundError: No module named 'Cython'
</code>```

An hour ago did work just fine downloading the package.

Any recommendation for another python IDE than pycharm ?

答: U can use anaconda navigator. It comes with many inbuilt libraries such as pandas numpy matlab etc according to me it is best to use anaconda navigator in which u can either use spyder ide or jyputer notebook do upvode if u found helpful </p>

Body:
I am newbie in python.

After I installed python 3.8 latest version, libraries ...etc
Pycharm IDE, and for every time you create project you have to install packages so your code look nice with no red line under.
after I spent hours trying to find whats going on, Error, visual studio  ++14 and not 15 or 19.

The code line, import serial doesn't seem recognized by pycharm or by python.

I have read many people having the same problem but few were successful to solve, other are still not.

My Problem is that I need to plot data from arduino using python over serial.

Anyone have an idea how to solve the import serial not working?

The code implemented:

import serial                       , error
import numpy as np                package not found but managed to install it and have to install it again
import matplotlib.pyplot as plt
%matplotlib qt

ser = serial.Serial('COM4',9600)   Syntax error

Just tried to install matplotlib package, I got this error

ModuleNotFoundError: No module named 'Cython'

An hour ago did work just fine downloading the package.

Any recommendation for another python IDE than pycharm ?


问:
Use Single Quote instead of colons in Ruby/Rails
I'm trying to get this test to pass:

```<code> it "returns an object with the correct fields" do
      expected_response = {"animal_time": @curr_time.strftime("%F %T"), "animals":{}}
      expect(AnimalHaircutSession.latest_for(@animal_haircut)).to eq(expected_response)
  end
</code>```

When running the test I get this error:

```<code> expected: {:animal_time=>"2020-02-14 09:48:30", :animals=>{}}
 got: {"animal_time"=>"2020-02-14 16:48:30", "animals"=>{}}
</code>```

Why is it converting my expected response to colons and how can I set my expected response to use single quotes?

答:
In Ruby colons are used to define hashes with symbols for keys . The keys will be cast into symbols.

```<code>{ "foo": "bar" } == { :foo => "bar" } # true
{ "foo": "bar" } != { "foo" => "bar" } # true
</code>```

If you want to define a hash where the keys are not symbols use hash-rockets (=>).

```<code>it "returns an object with the correct fields" do
  expected_response = {
    "animal_time" => @curr_time.strftime("%F %T"),
    "animals" => {}
  }
  expect(AnimalHaircutSession.latest_for(@animal_haircut)).to eq(expected_response)
end
</code>```

While Ruby will allow you to mix hash-rockets and colons in a hash it's generally not considered good form.

Body:
I'm trying to get this test to pass:

 it "returns an object with the correct fields" do
      expected_response = {"animal_time": @curr_time.strftime("%F %T"), "animals":{}}
      expect(AnimalHaircutSession.latest_for(@animal_haircut)).to eq(expected_response)
  end

When running the test I get this error:

 expected: {:animal_time=>"2020-02-14 09:48:30", :animals=>{}}
 got: {"animal_time"=>"2020-02-14 16:48:30", "animals"=>{}}

Why is it converting my expected response to colons and how can I set my expected response to use single quotes?

Body:
In Ruby colons are used to define hashes with symbols for keys . The keys will be cast into symbols.

{ "foo": "bar" } == { :foo => "bar" } # true
{ "foo": "bar" } != { "foo" => "bar" } # true

If you want to define a hash where the keys are not symbols use hash-rockets (=>).

it "returns an object with the correct fields" do
  expected_response = {
    "animal_time" => @curr_time.strftime("%F %T"),
    "animals" => {}
  }
  expect(AnimalHaircutSession.latest_for(@animal_haircut)).to eq(expected_response)
end

While Ruby will allow you to mix hash-rockets and colons in a hash it's generally not considered good form.


问:
Solution for SpecificationError: nested renamer is not supported while agg() along with groupby()
```<code>def stack_plot(data, xtick, col2='project_is_approved', col3='total'):
    ind = np.arange(data.shape[0])

    plt.figure(figsize=(20,5))
    p1 = plt.bar(ind, data[col3].values)
    p2 = plt.bar(ind, data[col2].values)

    plt.ylabel('Projects')
    plt.title('Number of projects aproved vs rejected')
    plt.xticks(ind, list(data[xtick].values))
    plt.legend((p1[0], p2[0]), ('total', 'accepted'))
    plt.show()

def univariate_barplots(data, col1, col2='project_is_approved', top=False):
    # Count number of zeros in dataframe python: https://stackoverflow.com/a/51540521/4084039
    temp = pd.DataFrame(project_data.groupby(col1)[col2].agg(lambda x: x.eq(1).sum())).reset_index()

    # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
    temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

    temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

    temp.sort_values(by=['total'],inplace=True, ascending=False)

    if top:
        temp = temp[0:top]

    stack_plot(temp, xtick=col1, col2=col2, col3='total')
    print(temp.head(5))
    print("="*50)
    print(temp.tail(5))

univariate_barplots(project_data, 'school_state', 'project_is_approved', False)
</code>```

Error:

```<code>SpecificationError                        Traceback (most recent call last)
<ipython-input-21-2cace8f16608> in <module>()
----> 1 univariate_barplots(project_data, 'school_state', 'project_is_approved', False)

<ipython-input-20-856fcc83737b> in univariate_barplots(data, col1, col2, top)
      4
      5     # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
----> 6     temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']
      7     print (temp['total'].head(2))
      8     temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, *args, **kwargs)
    251             # but not the class list / tuple itself.
    252             func = _maybe_mangle_lambdas(func)
--> 253             ret = self._aggregate_multiple_funcs(func)
    254             if relabeling:
    255                 ret.columns = columns

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in _aggregate_multiple_funcs(self, arg)
    292             # GH 15931
    293             if isinstance(self._selected_obj, Series):
--> 294                 raise SpecificationError("nested renamer is not supported")
    295
    296             columns = list(arg.keys())

SpecificationError: **nested renamer is not supported**
</code>```

答:
Do you get the same error if you change

```<code>temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']
</code>```

to

```<code>temp['total'] = project_data.groupby(col1)[col2].agg(total=('total','count')).reset_index()['total']
</code>```

Body:
def stack_plot(data, xtick, col2='project_is_approved', col3='total'):
    ind = np.arange(data.shape[0])

    plt.figure(figsize=(20,5))
    p1 = plt.bar(ind, data[col3].values)
    p2 = plt.bar(ind, data[col2].values)

    plt.ylabel('Projects')
    plt.title('Number of projects aproved vs rejected')
    plt.xticks(ind, list(data[xtick].values))
    plt.legend((p1[0], p2[0]), ('total', 'accepted'))
    plt.show()

def univariate_barplots(data, col1, col2='project_is_approved', top=False):
    # Count number of zeros in dataframe python: https://stackoverflow.com/a/51540521/4084039
    temp = pd.DataFrame(project_data.groupby(col1)[col2].agg(lambda x: x.eq(1).sum())).reset_index()

    # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
    temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

    temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

    temp.sort_values(by=['total'],inplace=True, ascending=False)

    if top:
        temp = temp[0:top]

    stack_plot(temp, xtick=col1, col2=col2, col3='total')
    print(temp.head(5))
    print("="*50)
    print(temp.tail(5))

univariate_barplots(project_data, 'school_state', 'project_is_approved', False)

Error:

SpecificationError                        Traceback (most recent call last)
<ipython-input-21-2cace8f16608> in <module>()
----> 1 univariate_barplots(project_data, 'school_state', 'project_is_approved', False)

<ipython-input-20-856fcc83737b> in univariate_barplots(data, col1, col2, top)
      4
      5     # Pandas dataframe grouby count: https://stackoverflow.com/a/19385591/4084039
----> 6     temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']
      7     print (temp['total'].head(2))
      8     temp['Avg'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'Avg':'mean'})).reset_index()['Avg']

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in aggregate(self, func, *args, **kwargs)
    251             # but not the class list / tuple itself.
    252             func = _maybe_mangle_lambdas(func)
--> 253             ret = self._aggregate_multiple_funcs(func)
    254             if relabeling:
    255                 ret.columns = columns

~\AppData\Roaming\Python\Python36\site-packages\pandas\core\groupby\generic.py in _aggregate_multiple_funcs(self, arg)
    292             # GH 15931
    293             if isinstance(self._selected_obj, Series):
--> 294                 raise SpecificationError("nested renamer is not supported")
    295
    296             columns = list(arg.keys())

SpecificationError: **nested renamer is not supported**

Body:
Do you get the same error if you change

temp['total'] = pd.DataFrame(project_data.groupby(col1)[col2].agg({'total':'count'})).reset_index()['total']

to

temp['total'] = project_data.groupby(col1)[col2].agg(total=('total','count')).reset_index()['total']


问:
text-file manipulation in bash
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

```<code>cat data.txt | dot -Tpng > image.png
</code>```

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

答:
You can just feed your data to echo, loading data.text via ``s.   In a modern shell you can use the $() construct as well.

One echo process, one cat process, one dot process:

```<code>echo digraph {`cat data.text`} | dot -Tpng > image.png
</code>```

Title: text-file manipulation in bash

Body:
so I have this file that contains some data. that I use to create a graph using graphviz.
the problem is that I need to open a file and put a curly braces at the end and beginning of the file. I also write digraph before the opening braces.

than run my script to create the graph.

cat data.txt | dot -Tpng > image.png

The problem is that I would like to automate the first step and add digraph { at the begining and }  at the end withing my script that create the graph.

Body:
You can just feed your data to echo, loading data.text via ``s.   In a modern shell you can use the $() construct as well.

One echo process, one cat process, one dot process:

echo digraph {`cat data.text`} | dot -Tpng > image.png