问:
Angular : Textfield with suggestion for ajax call response
I need to create a text field with suggestion, I found one of the example of it but it is with static data

```<code> <input list="users" name="users">
      <datalist id="users">
        <option value="Alice">
        <option value="Bob">
        <option value="Chuck">
        <option value="Chris">
        <option value="Duke">
        <option value="Emily">
      </datalist>
</code>```

say from service, I am getting all the above value in "userList" variable.

then how can i assign this value in angular to this input tag

答:
By using ngFor directive.</p>

```<code><input list="users" name="users">
      <datalist id="users">
        <option *ngFor="let user of userList" [value]="user">
      </datalist>
</code>```

Body:
I need to create a text field with suggestion, I found one of the example of it but it is with static data

 <input list="users" name="users">
      <datalist id="users">
        <option value="Alice">
        <option value="Bob">
        <option value="Chuck">
        <option value="Chris">
        <option value="Duke">
        <option value="Emily">
      </datalist>

say from service, I am getting all the above value in "userList" variable.

then how can i assign this value in angular to this input tag

Body:
By using ngFor directive.

<input list="users" name="users">
      <datalist id="users">
        <option *ngFor="let user of userList" [value]="user">
      </datalist>


来源: stackexchange

问:
Python sleep function does not catch interrupt signal
I cannot catch the INT signal in the main thread, please advise me how to fix the problem. I wish that the sleep method could be interrupted by CTRL+C, but it waits till the timer is ended..</p>

```<code>import pygtk
pygtk.require('2.0')

import gtk
import time
import urllib2
import re
import signal
import sys

import __main__

from time import ctime, strftime, localtime
from threading import Thread

myThread = None

class MyThread(Thread):

    def __init__(self, filename):
        Thread.__init__(self)
        self.filename = filename;
        self.terminate = False

    def StopProcess(self):
        self.terminate = True

    def run(self):
        while self.terminate <> True:
            time.sleep(5)
            self.terminate = True

def SignalHandler(signum, frame):
    if (myThread <> None):
        myThread.StopProcess()
    sys.exit()

if __name__ == "__main__":

    signal.signal(signal.SIGINT, SignalHandler)

    myThread = MyThread("aaa")
    myThread.start()
</code>```

答:
Signals are only delivered to one thread. Either only the first thread, or the first available thread depending on the operating system.

You'll have to implement you're own logic to shutdown the other threads, or make them daemon threads so they don't prevent the process from exiting.

ContentLicense: CC BY-SA 3.0

Body:
I cannot catch the INT signal in the main thread, please advise me how to fix the problem. I wish that the sleep method could be interrupted by CTRL+C, but it waits till the timer is ended..

import pygtk
pygtk.require('2.0')

import gtk
import time
import urllib2
import re
import signal
import sys

import __main__

from time import ctime, strftime, localtime
from threading import Thread

myThread = None

class MyThread(Thread):

    def __init__(self, filename):
        Thread.__init__(self)
        self.filename = filename;
        self.terminate = False

    def StopProcess(self):
        self.terminate = True

    def run(self):
        while self.terminate <> True:
            time.sleep(5)
            self.terminate = True

def SignalHandler(signum, frame):
    if (myThread <> None):
        myThread.StopProcess()
    sys.exit()

if __name__ == "__main__":

    signal.signal(signal.SIGINT, SignalHandler)

    myThread = MyThread("aaa")
    myThread.start()


问:
Kaltura error: kWidget is not defined at eval
I am trying to use the Kaltura API in a web app of mine written in angular, meteor. However I am getting a "kWidget is not defined at eval" error when I try to use it. A past project (not written by me) uses the Kaltura API, so I copied the small bit of embed code from that website into my web app.

The Kaltura API is currently working on this website (link to working site: here), but not on mine. I've tried looking through the site's source code via inspector, but I can't figure out why I am getting this error and the website is not.

Does anyone who has experience with Kaltura's API have any solutions? I've seen a couple answers on SO, but I couldn't make sense of them in my situation.

The code I include in my html view:

```<code>    <div id="kaltura_player_1476756849" style="width: 480px; height: 360px; margin:0 auto;"></div>
    <p><script>
    kWidget.embed({
      "targetId": "kaltura_player_1476756849",
      "wid": "_1971441",
      "uiconf_id": 35431201,
      "flashvars": {
        "streamerType": "auto"
      },
      "cache_st": 1476756849,
      "entry_id": "1_q52zk7l2"
    });
    </script></p>
</code>```

答:
Try below way it's solves my issue:</p>

```<code>$( document).ready(function() {
    window.setTimeout(function(){

       // your embed code
    }
}
</code>```

Body:
Try below way it's solves my issue:

$( document).ready(function() {
    window.setTimeout(function(){

       // your embed code
    }
}

ContentLicense: CC BY-SA 4.0


问:
Is there any public SQL Server with sample databases
I study the SQL Server technologies, and want to try connect to remote server.

Did anybody knows a public server with sample databases for testing?
The Google didn't help me, at the moment.

答:
A view solutions from researchgate:

https://www.freemysqlhosting.net/

https://cloud.google.com/sql/

https://www.freesqldatabase.com/

https://free.caspio.com/

https://elements.heroku.com/addons/heroku-postgresql


问:
Python grep and cut
In Linux, it's easy to get certain string by using tools such as grep, cut, or awk.

This show version sample is taken from https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst9300/software/release/16-6/configuration_guide/sys_mgmt/b_166_sys_mgmt_9300_cg/b_166_sys_mgmt_9300_cg_chapter_01.html

```<code>wolf@linux:~$ cat shver
cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S

wolf@linux:~$
</code>```

grep and cut

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2
 C9300-48P
 C9300-48P
wolf@linux:~$
</code>```

Remove extra space (If there's better solution, let me know)

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2
C9300-48P
C9300-48P
wolf@linux:~$
</code>```

Select the 1st output

```<code>wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2 | head -1
C9300-48P
wolf@linux:~$
</code>```

That was in Linux. I was planning to write similar code in Python.

My attempt which still didn't work at the moment.

Define shver string

```<code>>>> shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
... Processor board ID FCW2049G03S
... 2048K bytes of non-volatile configuration memory.
... 8388608K bytes of physical memory.
... 1638400K bytes of Crash Files at crashinfo:.
... 11264000K bytes of Flash at flash:.
... 0K bytes of WebUI ODM Files at webui:.
... Model Number                       : C9300-48P
...
... Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
... Motherboard Assembly Number        : 73-17956-04
... Motherboard Serial Number          : FOC20465ABU
... Model Revision Number              : P4B
... Motherboard Revision Number        : 04
... Model Number                       : C9300-48P
... System Serial Number               : FCW2049G03S
... '''
>>>
</code>```

verify it

```<code>>>> shver
'cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.\nProcessor board ID FCW2049G03S\n2048K bytes of non-volatile configuration memory.\n8388608K bytes of physical memory.\n1638400K bytes of Crash Files at crashinfo:.\n11264000K bytes of Flash at flash:.\n0K bytes of WebUI ODM Files at webui:.\nModel Number                       : C9300-48P\n\nBase Ethernet MAC Address          : 04:6c:9d:01:3b:80\nMotherboard Assembly Number        : 73-17956-04\nMotherboard Serial Number          : FOC20465ABU\nModel Revision Number              : P4B\nMotherboard Revision Number        : 04\nModel Number                       : C9300-48P\nSystem Serial Number               : FCW2049G03S\n'
>>>
</code>```

create a list

```<code>>>> shver_list = shver.splitlines()
>>> shver_list
['cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.', 'Processor board ID FCW2049G03S', '2048K bytes of non-volatile configuration memory.', '8388608K bytes of physical memory.', '1638400K bytes of Crash Files at crashinfo:.', '11264000K bytes of Flash at flash:.', '0K bytes of WebUI ODM Files at webui:.', 'Model Number                       : C9300-48P', '', 'Base Ethernet MAC Address          : 04:6c:9d:01:3b:80', 'Motherboard Assembly Number        : 73-17956-04', 'Motherboard Serial Number          : FOC20465ABU', 'Model Revision Number              : P4B', 'Motherboard Revision Number        : 04', 'Model Number                       : C9300-48P', 'System Serial Number               : FCW2049G03S']
>>>
</code>```

Next step is to find out if string 'Model Number' is there or not and print out that line

```<code>>>> if 'Model Number' in shver_list:
...     'yes'
... else:
...     'no'
...
'no'
>>>
</code>```

How do I print out the line contains 'Model Number'?

```<code>>>> for i in shver_list:
...     if 'Model Number' in shver_list:
...             i
...
>>>
</code>```

Desired Output

```<code>C9300-48P
</code>```

答:
You have to filter the entries in your list. If you filter directly, you are looking for lines that are literally "Model Number".

This would print all lines that contain the substring "Model Number".

```<code>modelnumbers = [line for line in shver_list if 'Model Number' in line]
print(modelnumbers)`
</code>```

To get the desired output, you use the first result, and strip away everthing not needed.

```<code>print(modelnumbers[0].split(":")[1].strip())
</code>```

Title: Python grep and cut

Body:
In Linux, it's easy to get certain string by using tools such as grep, cut, or awk.

This show version sample is taken from https://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst9300/software/release/16-6/configuration_guide/sys_mgmt/b_166_sys_mgmt_9300_cg/b_166_sys_mgmt_9300_cg_chapter_01.html

wolf@linux:~$ cat shver
cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
Processor board ID FCW2049G03S
2048K bytes of non-volatile configuration memory.
8388608K bytes of physical memory.
1638400K bytes of Crash Files at crashinfo:.
11264000K bytes of Flash at flash:.
0K bytes of WebUI ODM Files at webui:.
Model Number                       : C9300-48P

Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
Motherboard Assembly Number        : 73-17956-04
Motherboard Serial Number          : FOC20465ABU
Model Revision Number              : P4B
Motherboard Revision Number        : 04
Model Number                       : C9300-48P
System Serial Number               : FCW2049G03S

wolf@linux:~$

grep and cut

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2
 C9300-48P
 C9300-48P
wolf@linux:~$

Remove extra space (If there's better solution, let me know)

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2
C9300-48P
C9300-48P
wolf@linux:~$

Select the 1st output

wolf@linux:~$ grep 'Model Number' shver | cut -d : -f 2 | cut -d ' ' -f 2 | head -1
C9300-48P
wolf@linux:~$

That was in Linux. I was planning to write similar code in Python.

My attempt which still didn't work at the moment.

Define shver string

>>> shver = '''cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.
... Processor board ID FCW2049G03S
... 2048K bytes of non-volatile configuration memory.
... 8388608K bytes of physical memory.
... 1638400K bytes of Crash Files at crashinfo:.
... 11264000K bytes of Flash at flash:.
... 0K bytes of WebUI ODM Files at webui:.
... Model Number                       : C9300-48P
...
... Base Ethernet MAC Address          : 04:6c:9d:01:3b:80
... Motherboard Assembly Number        : 73-17956-04
... Motherboard Serial Number          : FOC20465ABU
... Model Revision Number              : P4B
... Motherboard Revision Number        : 04
... Model Number                       : C9300-48P
... System Serial Number               : FCW2049G03S
... '''
>>>

verify it

>>> shver
'cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.\nProcessor board ID FCW2049G03S\n2048K bytes of non-volatile configuration memory.\n8388608K bytes of physical memory.\n1638400K bytes of Crash Files at crashinfo:.\n11264000K bytes of Flash at flash:.\n0K bytes of WebUI ODM Files at webui:.\nModel Number                       : C9300-48P\n\nBase Ethernet MAC Address          : 04:6c:9d:01:3b:80\nMotherboard Assembly Number        : 73-17956-04\nMotherboard Serial Number          : FOC20465ABU\nModel Revision Number              : P4B\nMotherboard Revision Number        : 04\nModel Number                       : C9300-48P\nSystem Serial Number               : FCW2049G03S\n'
>>>

create a list

>>> shver_list = shver.splitlines()
>>> shver_list
['cisco C9300-48P (X86) processor with 818597K/6147K bytes of memory.', 'Processor board ID FCW2049G03S', '2048K bytes of non-volatile configuration memory.', '8388608K bytes of physical memory.', '1638400K bytes of Crash Files at crashinfo:.', '11264000K bytes of Flash at flash:.', '0K bytes of WebUI ODM Files at webui:.', 'Model Number                       : C9300-48P', '', 'Base Ethernet MAC Address          : 04:6c:9d:01:3b:80', 'Motherboard Assembly Number        : 73-17956-04', 'Motherboard Serial Number          : FOC20465ABU', 'Model Revision Number              : P4B', 'Motherboard Revision Number        : 04', 'Model Number                       : C9300-48P', 'System Serial Number               : FCW2049G03S']
>>>

Next step is to find out if string 'Model Number' is there or not and print out that line

>>> if 'Model Number' in shver_list:
...     'yes'
... else:
...     'no'
...
'no'
>>>

How do I print out the line contains 'Model Number'?

>>> for i in shver_list:
...     if 'Model Number' in shver_list:
...             i
...
>>>

Desired Output

C9300-48P

Body:
You have to filter the entries in your list. If you filter directly, you are looking for lines that are literally "Model Number".

This would print all lines that contain the substring "Model Number".

modelnumbers = [line for line in shver_list if 'Model Number' in line]
print(modelnumbers)`

To get the desired output, you use the first result, and strip away everthing not needed.

print(modelnumbers[0].split(":")[1].strip())


问:
Events with QGraphicsItemGroup
In my application I want to use QGraphicsItemGroup for grouping items into one item.

I played with it a little and not sure using it because when I want to catch events, events are merged together but I want to handle specific event with specific child.

How can I achieve this?

答:
The question doesn't specify which version of Qt is concerned and there is a correct answer for Qt4. Here is an answer for Qt5 (it works for PyQt5 and I guess it'll work also in C++). The solution was to reimplement sceneEvent, reimplementing a specialized event-catcher such as contextMenuEvent was not sufficient.

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets

class GraphicsItem(QtWidgets.QGraphicsItem):
    def __init__(self,
               rect: QtCore.QRectF,
               name: str,
               parent: QtWidgets.QGraphicsItem = None):
        super().__init__(parent)
        self._name = name
        self._rect = rect

    def boundingRect(self):
        return self._rect

    def paint(self,
              painter: QtGui.QPainter,
              option: QtWidgets.QStyleOptionGraphicsItem,
              widget: QtWidgets.QWidget = None):
        painter.setPen(QtGui.QPen(QtCore.Qt.NoPen))
        painter.setBrush(QtGui.QBrush(QtCore.Qt.red))
        painter.drawRect(self._rect)

    def sceneEvent(self, event: QtCore.QEvent):
        if (event.type() == QtCore.QEvent.GraphicsSceneContextMenu):
            self.contextMenuEvent(event)
        event.accept()
        return True

    def contextMenuEvent(self, event: QtWidgets.QGraphicsSceneContextMenuEvent):
        print(f'contextMenuEvent in "{self._name}"')

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self._scene = QtWidgets.QGraphicsScene()

        layout = QtWidgets.QHBoxLayout()
        self._view = QtWidgets.QGraphicsView(self._scene)
        layout.addWidget(self._view)

        self._widget = QtWidgets.QWidget()
        self._widget.setLayout(layout)

        group = QtWidgets.QGraphicsItemGroup()
        self._scene.addItem(group)

        scene_item = GraphicsItem(QtCore.QRectF(0, 0, 100, 100), 'in scene')
        self._scene.addItem(scene_item)

        group_item = GraphicsItem(QtCore.QRectF(150, 0, 100, 100), 'in group')
        group.addToGroup(group_item)

        group_item = GraphicsItem(QtCore.QRectF(300, 0, 100, 100), '2nd in group')
        group.addToGroup(group_item)

        self.setCentralWidget(self._widget)
        self.setWindowTitle('contextMenuEvent with QGraphicsItemGroup')

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)

    mainWindow = MainWindow()
    mainWindow.setGeometry(100, 100, 800, 500)
    mainWindow.show()

    sys.exit(app.exec_())
</code>```

ContentLicense: CC BY-SA 2.5

Title: Events with QGraphicsItemGroup

Body:
The question doesn't specify which version of Qt is concerned and there is a correct answer for Qt4. Here is an answer for Qt5 (it works for PyQt5 and I guess it'll work also in C++). The solution was to reimplement sceneEvent, reimplementing a specialized event-catcher such as contextMenuEvent was not sufficient.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets

class GraphicsItem(QtWidgets.QGraphicsItem):
    def __init__(self,
               rect: QtCore.QRectF,
               name: str,
               parent: QtWidgets.QGraphicsItem = None):
        super().__init__(parent)
        self._name = name
        self._rect = rect

    def boundingRect(self):
        return self._rect

    def paint(self,
              painter: QtGui.QPainter,
              option: QtWidgets.QStyleOptionGraphicsItem,
              widget: QtWidgets.QWidget = None):
        painter.setPen(QtGui.QPen(QtCore.Qt.NoPen))
        painter.setBrush(QtGui.QBrush(QtCore.Qt.red))
        painter.drawRect(self._rect)

    def sceneEvent(self, event: QtCore.QEvent):
        if (event.type() == QtCore.QEvent.GraphicsSceneContextMenu):
            self.contextMenuEvent(event)
        event.accept()
        return True

    def contextMenuEvent(self, event: QtWidgets.QGraphicsSceneContextMenuEvent):
        print(f'contextMenuEvent in "{self._name}"')

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self._scene = QtWidgets.QGraphicsScene()

        layout = QtWidgets.QHBoxLayout()
        self._view = QtWidgets.QGraphicsView(self._scene)
        layout.addWidget(self._view)

        self._widget = QtWidgets.QWidget()
        self._widget.setLayout(layout)

        group = QtWidgets.QGraphicsItemGroup()
        self._scene.addItem(group)

        scene_item = GraphicsItem(QtCore.QRectF(0, 0, 100, 100), 'in scene')
        self._scene.addItem(scene_item)

        group_item = GraphicsItem(QtCore.QRectF(150, 0, 100, 100), 'in group')
        group.addToGroup(group_item)

        group_item = GraphicsItem(QtCore.QRectF(300, 0, 100, 100), '2nd in group')
        group.addToGroup(group_item)

        self.setCentralWidget(self._widget)
        self.setWindowTitle('contextMenuEvent with QGraphicsItemGroup')

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)

    mainWindow = MainWindow()
    mainWindow.setGeometry(100, 100, 800, 500)
    mainWindow.show()

    sys.exit(app.exec_())


问:
Typescript: How do I declare a generic class factory that maps enums to types in the safest way?
I am trying to figure out the best way to assign types to this generic class factory.
I've copied some of this code from another question: https://stackoverflow.com/a/47933133
It's relatively straightforward to map an enum value to a class. I can't however seem to figure out how to go one step further and type my creation method so that it realizes if the class I am creating does not in fact take the parameters that I've passed in.
(I realize this is a convoluted and contrived way to construct an instance. I think I've distilled down something I'm trying to do in my app in the real world to this question though.)

class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

const paramsMap = {
    [Kind.DogKind]: DogParams,
    [Kind.CatKind]: CatParams,
}
type ParamsMap = typeof paramsMap;

function getAnimalClasses<K extends Kind>(key: K, params: ParamsMap[K]): [KindMap[K], ParamsMap[K]] {
    const klass = kindMap[key];
    return [klass, params];
}

// Cool: Typescript knows that dogStuff is of type [typeof Dog, typeof DogParams]
const dogStuff = getAnimalClasses(Kind.DogKind, DogParams);

// Now imagine I want to instantiate and init my class in a type-safe way:
function getAnimalInstance<K extends Kind>(key: K, params: InstanceType<ParamsMap[K]>): InstanceType<KindMap[K]> {
    const animalKlass = kindMap[key];

    // animalInstance : Dog | Cat
    const animalInstance = new animalKlass() as InstanceType<KindMap[K]>;

    // By this line, Typescript just knows that animalInstance has a method called init that takes `DogParams & CatParams`. That makes sense to me, but it's not what I want.
    // QUESTION: The following gives an error. Is there a type-safe way that I can make this method call and ensure that my maps and my `init` method signatures are
    // are consistent throughout my app? Do I need more generic parameters of this function?
    animalInstance.init(params);

    return animalInstance;
}

// This works too: It knows that I have to pass in CatParams if I am passing in CatKind
// It also knows that `cat` is an instance of the `Cat` class.
const cat = getAnimalInstance(Kind.CatKind, new CatParams());
```

<p>Playground Link</p>

<p>See the actual question in the code above.</p>

<hr>

<p><strong>UPDATE May 29, 2020:</strong></p>

<p>@Kamil Szot points out that I don't have proper type safety in my non-overloaded function in the first place: </p>

```    // Should be an error but is not:
    const cat = getAnimalInstance((() => Kind.DogKind)(), new CatParams());
```

<p>So, we really do need overloads, as he suggests, but I don't want to write them manually. So, here's what I've got now. I think that this is as good as it's going to get, but I wish I could define another type that made auto-generating these overloads less verbose and made it so that I didn't have to duplicate the function signature of my function implementation twice.</p>

```// We can use UnionToIntersection to auto-generate our overloads
// Learned most of this technique here: https://stackoverflow.com/a/53173508/544130
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

const autoOverloadedCreator: UnionToIntersection<
    Kind extends infer K ?
    K extends Kind ?
    // I wish there was a way not to have to repeat the signature of getAnimalInstance here though!
    (key: K, p: InstanceType<ParamsMap[K]>) => InstanceType<KindMap[K]> :
    never : never
> = getAnimalInstance;

// This works, and has overload intellisense!
let cat2 = autoOverloadedCreator(Kind.CatKind, new CatParams());

// And this properly gives an error
const yayThisIsAnErrorAlso = autoOverloadedCreator((() => Kind.DogKind)(), new CatParams());

// Note that this type is different from our ManuallyOverloadedFuncType though:
// type createFuncType = ((key: Kind.DogKind, p: DogParams) => Dog) & ((key: Kind.CatKind, p: CatParams) => Cat)
type CreateFuncType = typeof autoOverloadedCreator;
```

Playground Link

答:
Two different more general solutions can be seen at the end of the question and in accepted answer.

I'm leaving this answer as well because it contains more readable and easier to understand solution, however it requires you to define function overload for each Kind manually.

Discussion

Try defining your your inits like this:

```<code>public init<P extends DogParams>(params: P) { }
//..
public init<C extends CatParams>(params: C) { }
</code>```

It shouldn't change much but now TypeScript won't even allow you to make any call to init() on animalInstance (of type Dog | Cat) like so:

```<code>function f(): Dog | Cat {
    return new Dog();
}
const dc: Dog | Cat = f();
dc.init(new DogParams());
// ^ here is the error
</code>```

because

```<code>This expression is not callable.
Each member of the union type '(<P extends DogParams>(params: P) => void) | (<C extends CatParams>(params: C) => void)' has signatures,
but none of those signatures are compatible with each other.(2349)
</code>```

Or you can go even simpler and declare like that:

```<code>public init(params: string) { } // inside class Dog
//..
public init(params: number) { } // inside class Cat
</code>```

and now here

```<code>const dc: Dog | Cat = f();
dc.init(5);
</code>```

dc.init has signature of init(params: never): void and you can't call it as well.

I think the only way you can make a call to init in a type safe manner is if you do manual, runtime type checking and make separate manual casts and calls for each case like so:

```<code>const dc: Dog | Cat = f();
if (dc instanceof Dog) {
    dc.init("5");
} else if(dc instanceof Cat) {
    dc.init(5);
} else {
   throw Exception("I should implement call to init() of "+dc); // this will alert you if you add new kind of animal but forget to add it here.
</code>```

If you prefer to be warned at compile time about forgetting to implement new type in this manual piece of code you might achieve that by using Discriminated Unions and exhaustiveness checking but you'll need compiler to be able to tell if the init() was called or not, for example by returning something from init().

```<code>// .. inside class Dog
public kind: Kind = Kind.DogKind;
public init(params: string) { return true; }

// .. inside class Cat
public kind: Kind = Kind.CatKind;
public init(params: number) { return true; }
// ..

const dc: Dog | Cat = f();
enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
//    HamsterKind = 'HamsterKind'  // after uncommenting this, compiler alerts that function below does not always return boolean, and you know that you should implement the call to init() for new Kind there
}
(():boolean => {
    switch (dc.kind) {
        case Kind.DogKind: return (dc as Dog).init("5");
        case Kind.CatKind: return (dc as Cat).init(5);
    }
})();
</code>```

Solution

Personally I'd go with something like this:

```<code>class DogParam {
    public n: number = 0;
}
class CatParam {
    public n: string = "a";
}

class Dog {
    init(p: DogParam) { }
}
class Cat {
    init(p: CatParam) { }
}

enum Kind {
    Dog, Cat //, Hamster  // if you add new kind compiler will fail
                          // inside function a(), while trying to
                          // get kindMap[k], because key k is potentially not
                          // present in kindMap, and when you add it to
                          // kindMap you still need to add new overload for
                          // function a() to be able to use new Kind in your
                          // code so at no point compiler lets you forget to
                          // add anything
}
const kindMap = {
    [Kind.Dog]: Dog,
    [Kind.Cat]: Cat
}

// The only drawback of this solution is that you have to list those
// overloads manually.
function a(k: Kind.Dog, p: DogParam): Dog;
function a(k: Kind.Cat, p: CatParam): Cat;
function a(k: Kind, p: any) {
    var ins = new kindMap[k];
    ins.init(p as any); // safe because overloads ensure it can be called
    return ins;         // just for matching params
}

function f(): Kind {
    return Kind.Cat;
}

a(Kind.Dog, new DogParam()); // works
a(Kind.Cat, new DogParam()); // error because mismatch
a(f(), new DogParam());      // error because kind undetermined
a(f(), new CatParam());      // error because kind undetermined
a(f() as Kind.Dog, new DogParam());      // works, but hey, it's your fault
                                         // doing the wrong cast here manually
</code>```

Playground link

Additional benefit of this solution is that it doesn't generate any unnecessary runtime code.

Body:
I am trying to figure out the best way to assign types to this generic class factory.
I've copied some of this code from another question: https://stackoverflow.com/a/47933133
It's relatively straightforward to map an enum value to a class. I can't however seem to figure out how to go one step further and type my creation method so that it realizes if the class I am creating does not in fact take the parameters that I've passed in.
(I realize this is a convoluted and contrived way to construct an instance. I think I've distilled down something I'm trying to do in my app in the real world to this question though.)

class Dog {
    public dogName: string = ""
    public init(params: DogParams) { }
}
class Cat {
    public catName: string = ""
    public init(params: CatParams) { }
}
class DogParams { public dogValues: number = 0 }
class CatParams { public catValue: number = 0}

enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
}

const kindMap = {
    [Kind.DogKind]: Dog,
    [Kind.CatKind]: Cat,
};
type KindMap = typeof kindMap;

const paramsMap = {
    [Kind.DogKind]: DogParams,
    [Kind.CatKind]: CatParams,
}
type ParamsMap = typeof paramsMap;

function getAnimalClasses<K extends Kind>(key: K, params: ParamsMap[K]): [KindMap[K], ParamsMap[K]] {
    const klass = kindMap[key];
    return [klass, params];
}

// Cool: Typescript knows that dogStuff is of type [typeof Dog, typeof DogParams]
const dogStuff = getAnimalClasses(Kind.DogKind, DogParams);

// Now imagine I want to instantiate and init my class in a type-safe way:
function getAnimalInstance<K extends Kind>(key: K, params: InstanceType<ParamsMap[K]>): InstanceType<KindMap[K]> {
    const animalKlass = kindMap[key];

    // animalInstance : Dog | Cat
    const animalInstance = new animalKlass() as InstanceType<KindMap[K]>;

    // By this line, Typescript just knows that animalInstance has a method called init that takes `DogParams & CatParams`. That makes sense to me, but it's not what I want.
    // QUESTION: The following gives an error. Is there a type-safe way that I can make this method call and ensure that my maps and my `init` method signatures are
    // are consistent throughout my app? Do I need more generic parameters of this function?
    animalInstance.init(params);

    return animalInstance;
}

// This works too: It knows that I have to pass in CatParams if I am passing in CatKind
// It also knows that `cat` is an instance of the `Cat` class.
const cat = getAnimalInstance(Kind.CatKind, new CatParams());

<a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=57&pc=62#code/MYGwhgzhAEAiD2BzaBvAUNT0AOBXARiAJbDQAmSAcmALYCmAXNBAC4BORAdsgLzQBE-DFjyES0LkRYAKbGDa0ITBIgAK8xQEpU0AL5p9oSDADCYFqmGZRxUsHPV6TVh27Q+gqzgK2JnKbIaNErQZizqCsHaKHoGaEZQcEgRijo24hSIAGpgILh0IZy4NPh0bO7QAAyxCabmKcFpPuL2LDl5jNBFJWUVlfpodN3QANJcZJZYSYhjnBN8AOQqs2QLADReYSsVC1vj63Hx8Jys0ADW4wCyYNgV6FMA2isAdMvjALrKSBuPL3tzn1C5g2ugA3G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IuH2wUJDRB9aAFKBkbA-4yDQM873skAIHfesmyLiwNtaCXGrprgGII6Bh1h6ANrCCXal+uzaYsNc5UwpPJ7oXdyTb20cpr-EfJPIA" rel="nofollow noreferrer">Playground Link

See the actual question in the code above.

UPDATE May 29, 2020:

@Kamil Szot points out that I don't have proper type safety in my non-overloaded function in the first place:

    // Should be an error but is not:
    const cat = getAnimalInstance((() => Kind.DogKind)(), new CatParams());

So, we really do need overloads, as he suggests, but I don't want to write them manually. So, here's what I've got now. I think that this is as good as it's going to get, but I wish I could define another type that made auto-generating these overloads less verbose and made it so that I didn't have to duplicate the function signature of my function implementation twice.

// We can use UnionToIntersection to auto-generate our overloads
// Learned most of this technique here: https://stackoverflow.com/a/53173508/544130
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

const autoOverloadedCreator: UnionToIntersection<
    Kind extends infer K ?
    K extends Kind ?
    // I wish there was a way not to have to repeat the signature of getAnimalInstance here though!
    (key: K, p: InstanceType<ParamsMap[K]>) => InstanceType<KindMap[K]> :
    never : never
> = getAnimalInstance;

// This works, and has overload intellisense!
let cat2 = autoOverloadedCreator(Kind.CatKind, new CatParams());

// And this properly gives an error
const yayThisIsAnErrorAlso = autoOverloadedCreator((() => Kind.DogKind)(), new CatParams());

// Note that this type is different from our ManuallyOverloadedFuncType though:
// type createFuncType = ((key: Kind.DogKind, p: DogParams) => Dog) & ((key: Kind.CatKind, p: CatParams) => Cat)
type CreateFuncType = typeof autoOverloadedCreator;

<a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=103&pc=1#code/MYGwhgzhAEAiD2BzaBvAUNT0AOBXARiAJbDQAmSAcmALYCmAXNBAC4BORAdsgLzQBE-DFjyES0LkRYAKbGDa0ITBIgAK8xQEpU0AL5p9oSDADCYFqmGZRxUsHPV6TVh27Q+gqzgK2JnKbIaNErQZizqCsHaKHoGaEZQcEgRijo24hSIAGpgILh0IZy4NPh0bO7QAAyxCabmKcFpPuL2LDl5j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LtrtaKhc9oxS6PvE2eK5qJhhB2O2zAiCIE4OYNJNsZT+yErdfVjkzaZwZV4c0loAKXNugc6CgpHrPVLa+1CD0nRPVHrXKYWbeg1p5mgUN56e6B37rC9pMAfpsD+raV8Ex2xDiSX4A0+tBxGzoIykAcpsksD-hUBtSTm3QpDk8pk4xZ6R0MQvWOZ4E6UJgNgTuMIiH+Vlg5GNOoO5BTrq0+DnTumCbYPKEARMyO6XgI2sglG7FjLEhM7RE8VjT00PR+eizF6wsiuStse6vothBQNTF-ZZI5QCp3VGC1flKJABsijZA9nigObSu9tczxeVwfg9zwBPNhsfVadTYinEqSiGplQ2h1IFqfep55rypFqbCMgryLa6CBeC55PkaJyPUsU+o5TMK0BAA" rel="nofollow noreferrer">Playground Link

Body:
Two different more general solutions can be seen at the end of the question and in accepted answer.

I'm leaving this answer as well because it contains more readable and easier to understand solution, however it requires you to define function overload for each Kind manually.

Discussion

Try defining your your inits like this:

public init<P extends DogParams>(params: P) { }
//..
public init<C extends CatParams>(params: C) { }

It shouldn't change much but now TypeScript won't even allow you to make any call to init() on animalInstance (of type Dog | Cat) like so:

function f(): Dog | Cat {
    return new Dog();
}
const dc: Dog | Cat = f();
dc.init(new DogParams());
// ^ here is the error

because

This expression is not callable.
Each member of the union type '(<P extends DogParams>(params: P) => void) | (<C extends CatParams>(params: C) => void)' has signatures,
but none of those signatures are compatible with each other.(2349)

Or you can go even simpler and declare like that:

public init(params: string) { } // inside class Dog
//..
public init(params: number) { } // inside class Cat

and now here

const dc: Dog | Cat = f();
dc.init(5);

dc.init has signature of init(params: never): void and you can't call it as well.

I think the only way you can make a call to init in a type safe manner is if you do manual, runtime type checking and make separate manual casts and calls for each case like so:

const dc: Dog | Cat = f();
if (dc instanceof Dog) {
    dc.init("5");
} else if(dc instanceof Cat) {
    dc.init(5);
} else {
   throw Exception("I should implement call to init() of "+dc); // this will alert you if you add new kind of animal but forget to add it here.

If you prefer to be warned at compile time about forgetting to implement new type in this manual piece of code you might achieve that by using Discriminated Unions and exhaustiveness checking but you'll need compiler to be able to tell if the init() was called or not, for example by returning something from init().

// .. inside class Dog
public kind: Kind = Kind.DogKind;
public init(params: string) { return true; }

// .. inside class Cat
public kind: Kind = Kind.CatKind;
public init(params: number) { return true; }
// ..

const dc: Dog | Cat = f();
enum Kind {
    DogKind = 'DogKind',
    CatKind = 'CatKind',
//    HamsterKind = 'HamsterKind'  // after uncommenting this, compiler alerts that function below does not always return boolean, and you know that you should implement the call to init() for new Kind there
}
(():boolean => {
    switch (dc.kind) {
        case Kind.DogKind: return (dc as Dog).init("5");
        case Kind.CatKind: return (dc as Cat).init(5);
    }
})();

Solution

Personally I'd go with something like this:

class DogParam {
    public n: number = 0;
}
class CatParam {
    public n: string = "a";
}

class Dog {
    init(p: DogParam) { }
}
class Cat {
    init(p: CatParam) { }
}

enum Kind {
    Dog, Cat //, Hamster  // if you add new kind compiler will fail
                          // inside function a(), while trying to
                          // get kindMap[k], because key k is potentially not
                          // present in kindMap, and when you add it to
                          // kindMap you still need to add new overload for
                          // function a() to be able to use new Kind in your
                          // code so at no point compiler lets you forget to
                          // add anything
}
const kindMap = {
    [Kind.Dog]: Dog,
    [Kind.Cat]: Cat
}

// The only drawback of this solution is that you have to list those
// overloads manually.
function a(k: Kind.Dog, p: DogParam): Dog;
function a(k: Kind.Cat, p: CatParam): Cat;
function a(k: Kind, p: any) {
    var ins = new kindMap[k];
    ins.init(p as any); // safe because overloads ensure it can be called
    return ins;         // just for matching params
}

function f(): Kind {
    return Kind.Cat;
}

a(Kind.Dog, new DogParam()); // works
a(Kind.Cat, new DogParam()); // error because mismatch
a(f(), new DogParam());      // error because kind undetermined
a(f(), new CatParam());      // error because kind undetermined
a(f() as Kind.Dog, new DogParam());      // works, but hey, it's your fault
                                         // doing the wrong cast here manually

<a href="https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=50&pc=82#code/MYGwhgzhAEAiD2BzACmATmAttA3gWAChpjoAHAVwCMQBLYaAOwC5HzNKBTN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nofollow noreferrer">Playground link

Additional benefit of this solution is that it doesn't generate any unnecessary runtime code.


问:
Scrape a Wikipedia table using beautifulsoup
I've been trying to scrape a table on Wikipedia using Beautifulsoup, but encountered some problems.

Page: https://en.wikipedia.org/wiki/New_York_City
Table:
enter image description here

Table: "Racial composition"

In the page source, the table seems to start at row 1470.

Here's the code I tried first:

```<code>website_url = requests.get('https://en.wikipedia.org/wiki/New_York_City').text
soup = BeautifulSoup(website_url,'lxml')
table = soup.find('table',{'class':'wikitable sortable collapsible'})

headers = [header.text for header in table.find_all('th')]

table_rows = table.find_all('tr')
rows = []
for row in table_rows:
   td = row.find_all('td')
   row = [row.text for row in td]
   rows.append(row)

with open('NYC_DEMO.csv', 'w') as f:
   writer = csv.writer(f)
   writer.writerow(headers)
   writer.writerows(row for row in rows if row)
</code>```

And here's the error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-e6000bdafe11> in <module>
      3 table = soup.find('table',{'class':'wikitable sortable collapsible'})
      4
----> 5 headers = [header.text for header in table.find_all('th')]
      6
      7 table_rows = table.find_all('tr')

AttributeError: 'NoneType' object has no attribute 'find_all'
</code>```

I suppose this is code from the Wikipedia page that we'd need to get:

```<code><tbody><tr>
<th>Racial composition</th>
<th>2010<sup id="cite_ref-QuickFacts2010_226-1" class="reference"><a href="#cite_note-QuickFacts2010-226">[224]</a></sup></th>
<th>1990<sup id="cite_ref-pop_228-0" class="reference"><a href="#cite_note-pop-228">[226]</a></sup></th>
<th>1970<sup id="cite_ref-pop_228-1" class="reference"><a href="#cite_note-pop-228">[226]</a></sup></th>
<th>1940<sup id="cite_ref-pop_228-2" class="reference"><a href="#cite_note-pop-228">[226]</a></sup>
</th></tr>
<tr>
<td><a href="/wiki/White_American" class="mw-redirect" title="White American">White</a></td>
<td>44.0%</td>
<td>52.3%</td>
<td>76.6%</td>
<td>93.6%
</td></tr>
<tr>
...
</code>```

I'm guessing it can't locate the right table? There's quite some tables on that page so how do I correctly point towards that table?

Thanks in advance for your help.

答:
I'm guessing it can't locate the right table?

That seems to be the case, yes. If you check the value of table, you'll see that it is None, and that's why calling find_all on it fails.

If you check the table on the page, you'll see that its classes are wikitable collapsible collapsed mw-collapsible mw-made-collapsible, and there's no sortable class in there. This is why your program doesn't find any matching table element.

There's quite some tables on that page so how do I correctly point towards that table?

First, you you can hook up to some unique identifier, such as an id of the element, but there's none available in your case. Had it had any thead, or a caption of some sort, you could have tried with that, but again, it's not the case.

Then, you need to go further up the DOM tree, and check its parents if they have any uniquely identifiers. With the plan being that you add the parent in the selector. Unfortunately, the body of Wikipedia articles seem to be wrapped in just one big element, without semantically separating the sections. This makes it harder to scrape.

At this point, I would say you're left with just looking at the browser page and thinking about how you would naturally identify the table (non-programatically). You look at it and see it's got the Racial composition in the heading. And you can grab it with something like

table_heading = soup.find('th', text='Racial composition')      # this gives you the `th`
if table_heading:
    table = table_heading.find_parents('table')
```

There might be some other beautifulsoup APIs I don't know, but you can drop this in your code and it should work.

Body:
I've been trying to scrape a table on Wikipedia using Beautifulsoup, but encountered some problems.

Page: https://en.wikipedia.org/wiki/New_York_City
Table:
enter image description here

Table: "Racial composition"

In the page source, the table seems to start at row 1470.

Here's the code I tried first:

website_url = requests.get('https://en.wikipedia.org/wiki/New_York_City').text
soup = BeautifulSoup(website_url,'lxml')
table = soup.find('table',{'class':'wikitable sortable collapsible'})

headers = [header.text for header in table.find_all('th')]

table_rows = table.find_all('tr')
rows = []
for row in table_rows:
   td = row.find_all('td')
   row = [row.text for row in td]
   rows.append(row)

with open('NYC_DEMO.csv', 'w') as f:
   writer = csv.writer(f)
   writer.writerow(headers)
   writer.writerows(row for row in rows if row)

And here's the error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-e6000bdafe11> in <module>
      3 table = soup.find('table',{'class':'wikitable sortable collapsible'})
      4
----> 5 headers = [header.text for header in table.find_all('th')]
      6
      7 table_rows = table.find_all('tr')

AttributeError: 'NoneType' object has no attribute 'find_all'

I suppose this is code from the Wikipedia page that we'd need to get:

Racial composition
2010[224]
1990[226]
1970[226]
1940[226]

White
44.0%
52.3%
76.6%
93.6%

...

I'm guessing it can't locate the right table? There's quite some tables on that page so how do I correctly point towards that table?

Thanks in advance for your help.

Body:
I'm guessing it can't locate the right table?

That seems to be the case, yes. If you check the value of table, you'll see that it is None, and that's why calling find_all on it fails.

If you check the table on the page, you'll see that its classes are wikitable collapsible collapsed mw-collapsible mw-made-collapsible, and there's no sortable class in there. This is why your program doesn't find any matching table element.

There's quite some tables on that page so how do I correctly point towards that table?

First, you you can hook up to some unique identifier, such as an id of the element, but there's none available in your case. Had it had any thead, or a caption of some sort, you could have tried with that, but again, it's not the case.

Then, you need to go further up the DOM tree, and check its parents if they have any uniquely identifiers. With the plan being that you add the parent in the selector. Unfortunately, the body of Wikipedia articles seem to be wrapped in just one big element, without semantically separating the sections. This makes it harder to scrape.

At this point, I would say you're left with just looking at the browser page and thinking about how you would naturally identify the table (non-programatically). You look at it and see it's got the Racial composition in the heading. And you can grab it with something like

table_heading = soup.find('th', text='Racial composition')      # this gives you the `th`
if table_heading:
    table = table_heading.find_parents('table')

There might be some other beautifulsoup APIs I don't know, but you can drop this in your code and it should work.


问:
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code

```<code>inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
</code>```

I don't understand this part

```<code>void(*pfn)(void*)
</code>```

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

答: pfn is a function pointer whose return type is void and argument's type is void*

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?


问:
How to apply a CSS filter to a background image
I have a JPEG file that I'm using as a background image for a search page, and I'm using CSS to set it because I'm working within Backbone.js contexts:

```<code>background-image: url("whatever.jpg");
</code>```

I want to apply a CSS 3 blur filter only to the background, but I'm not sure how to style just that one element. If I try:

```<code>-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
</code>```

just underneath background-image in my CSS, it styles the whole page, rather than just the background. Is there a way to select just the image and apply the filter to that? Alternatively, is there a way to just turn the blur off for every other element on the page?

答:
Without using the pseudo-class from

body{
    background:#cecece;
    font-family: "Scope One", serif;
    font-size: 12px;
    color:black;
    margin:0 auto;
    height:100%;
    width:100%;
    background-image:
       linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.81)),
        url(https://i.imgur.com/2rRMQh7.jpg);
       -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body></body></code>```

Body:
I have a JPEG file that I'm using as a background image for a search page, and I'm using CSS to set it because I'm working within Backbone.js contexts:

background-image: url("whatever.jpg");

I want to apply a CSS 3 blur filter only to the background, but I'm not sure how to style just that one element. If I try:

-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);

just underneath background-image in my CSS, it styles the whole page, rather than just the background. Is there a way to select just the image and apply the filter to that? Alternatively, is there a way to just turn the blur off for every other element on the page?

Body:
Without using the pseudo-class from

body{
    background:#cecece;
    font-family: "Scope One", serif;
    font-size: 12px;
    color:black;
    margin:0 auto;
    height:100%;
    width:100%;
    background-image:
       linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.81)),
        url(https://i.imgur.com/2rRMQh7.jpg);
       -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

<body></body>


问:
Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams?
I have the following sample result when I query a database :

```<code>dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]
</code>```

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

```<code>{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }
</code>```

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

```<code>
    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

</code>```

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

答:
```<code>public static void main(String[] args) {
    List<HashMap<String, String>> input = new ArrayList<>();

    HashMap<String, String> subinput1 = new HashMap<>();
    subinput1.put("name", "name1");
    subinput1.put("rollno", "rollno1");
    input.add(subinput1);

    HashMap<String, String> subinput2 = new HashMap<>();
    subinput2.put("name", "name2");
    subinput2.put("rollno", "rollno2");
    input.add(subinput2);

    //Test key conflict
    HashMap<String, String> subinput3 = new HashMap<>();
    subinput2.put("name", "name3");
    subinput2.put("rollno", "rollno2");
    input.add(subinput2);

    System.out.println("input:"+ JSONObject.toJSONString(input));

    HashMap<String, HashMap<String, String>> result = (HashMap<String, HashMap<String, String>>)
       input.stream()
            .collect(Collectors.toMap(
                v -> (String) v.get("rollno"),
                Function.identity(),(oldValue, newValue) -> newValue
            ));
    //fastjson  hashmap-toString use =
    System.out.println(JSONObject.toJSONString(result));
}
</code>```

Body:
I have the following sample result when I query a database :

dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks


问:
npm command not found error while running docker container
I am trying some something out with gitlab-runner image,

```<code>    FROM gitlab/gitlab-runner:alpine
    WORKDIR /app
    COPY . /app
    RUN apk add yarn && yarn install

    RUN yarn --version        # this layer prints 1.16.0

    RUN ng build --prod
    EXPOSE 3000
    CMD ["yarn", "run", "start"]
</code>```

above is the docker file I have created

```<code>    docker build -t runner:1 .
</code>```

I was able to build the image successfully

```<code>    docker run -p 3000:3000 runner:1
</code>```

but when I try to run the container it gives me below error

```<code>`*FATAL: Command yarn not found.*`
</code>```

not sure about the behavior, if it is able to install yarn (apk add yarn) in base images and install the dependencies using yarn install then how it is not able to find the yarn command while running the container? Where I am going wrong.

Also at which directory yarn is installed in the alpine ?

I know it is not an efficient docker file, but I am trying to run the container first before optimizing it.

答:
It outputs the version. It means the yarn is installed already. You could find the path the same as you find the version.

RUN which yarn

```<code>Step 6/10 : RUN which yarn
 ---> Running in 0f633b81f2ed
/usr/bin/yarn
</code>```

We can see the /usr/bin/ has added to PATH.

```<code> Step 7/11 : RUN echo $PATH
 ---> Running in fc3f40b6bfd9
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code>```

But I couldn't figure out why isn't reading yarn from the PATH.

So, we have set the PATH explicitly in our Dockerfile.

```<code>ENV PATH=${PATH}
</code>```

But still, the issue persists. Now we have to separate yarn and commands as ENTRYPOINT and CMD respectively in the Dockerfile.

```<code>ENTRYPOINT ["yarn"]
CMD ["run", "start"]
</code>```

Updated Dockerfile

```<code>FROM gitlab/gitlab-runner:alpine

ENV PATH=${PATH}

WORKDIR /app
COPY . /app
RUN apk add yarn && yarn install

RUN yarn --version        # this layer prints 1.16.0
RUN ng build --prod

EXPOSE 3000
ENTRYPOINT ["yarn"]
CMD ["run", "start"]
---

$ docker run -p 3000:3000 harik8/yarn:latest
yarn run v1.16.0
error Couldn't find a package.json file in "/app"
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

The behaviours of the base image look unusual. It'd be better to go through it.

Body:
I am trying some something out with gitlab-runner image,

    FROM gitlab/gitlab-runner:alpine
    WORKDIR /app
    COPY . /app
    RUN apk add yarn && yarn install

    RUN yarn --version        # this layer prints 1.16.0

    RUN ng build --prod
    EXPOSE 3000
    CMD ["yarn", "run", "start"]

above is the docker file I have created

    docker build -t runner:1 .

I was able to build the image successfully

    docker run -p 3000:3000 runner:1

but when I try to run the container it gives me below error

`*FATAL: Command yarn not found.*`

not sure about the behavior, if it is able to install yarn (apk add yarn) in base images and install the dependencies using yarn install then how it is not able to find the yarn command while running the container? Where I am going wrong.

Also at which directory yarn is installed in the alpine ?

I know it is not an efficient docker file, but I am trying to run the container first before optimizing it.

Body:
It outputs the version. It means the yarn is installed already. You could find the path the same as you find the version.

RUN which yarn

Step 6/10 : RUN which yarn
 ---> Running in 0f633b81f2ed
/usr/bin/yarn

We can see the /usr/bin/ has added to PATH.

 Step 7/11 : RUN echo $PATH
 ---> Running in fc3f40b6bfd9
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

But I couldn't figure out why isn't reading yarn from the PATH.

So, we have set the PATH explicitly in our Dockerfile.

ENV PATH=${PATH}

But still, the issue persists. Now we have to separate yarn and commands as ENTRYPOINT and CMD respectively in the Dockerfile.

ENTRYPOINT ["yarn"]
CMD ["run", "start"]

Updated Dockerfile

FROM gitlab/gitlab-runner:alpine

ENV PATH=${PATH}

WORKDIR /app
COPY . /app
RUN apk add yarn && yarn install

RUN yarn --version        # this layer prints 1.16.0
RUN ng build --prod

EXPOSE 3000
ENTRYPOINT ["yarn"]
CMD ["run", "start"]
---

$ docker run -p 3000:3000 harik8/yarn:latest
yarn run v1.16.0
error Couldn't find a package.json file in "/app"
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

The behaviours of the base image look unusual. It'd be better to go through it.


问:
How to curve a line in react native
How can i achieve a curve line in react native.
like this

I tried border radius but could not achieve this result.Thanks.

答:
This is how you can achieve a curved line in react-native.</p>

```<code><View style={{ marginTop: 100 }}>
  <View style={styles.container} />
  <View style={styles.curvedLine} />
</View>

const styles = StyleSheet.create({
  container: {
    width: "100%",
    height: 75,
    borderRadius: 12,
    backgroundColor: "blue",
  },
  curvedLine: {
    width: "20%",
    height: 100,
    position: "absolute",
    bottom: -25,
    left: "40%",
    borderRadius: 35,
    backgroundColor: "black",
    transform: [{ scaleX: 5 }, { scaleY: 1 }],
  },
});
</code>```

Title: How to curve a line in react native

Body:
This is how you can achieve a curved line in react-native.

<View style={{ marginTop: 100 }}>
  <View style={styles.container} />
  <View style={styles.curvedLine} />
</View>

const styles = StyleSheet.create({
  container: {
    width: "100%",
    height: 75,
    borderRadius: 12,
    backgroundColor: "blue",
  },
  curvedLine: {
    width: "20%",
    height: 100,
    position: "absolute",
    bottom: -25,
    left: "40%",
    borderRadius: 35,
    backgroundColor: "black",
    transform: [{ scaleX: 5 }, { scaleY: 1 }],
  },
});


问:
Unable to load a pdf file which has special characters(!@#) in file path. Webview Xamarin forms
I am working on loading a pdf file in Xamarin through Web view. When the file path has special characters in it, pdf file is not loading.

Below is the code.

if (e.NewElement is PDFView pdfWebView)
            {

```<code>            this.Control.Settings.JavaScriptEnabled = true;
            this.Control.Settings.AllowFileAccess = true;
            this.Control.Settings.AllowUniversalAccessFromFileURLs = true;
            Control.LoadUrl($"file:///android_asset/pdfjs/web/viewer.html?file=file://{pdfWebView.Uri}");
        }
</code>```

答:
You are not specifying what you are using, but from the file path, I can safely assume that you are using PDF.js. If that's the case, then you'll need to URL encode the filename.
According to the FAQ page:

You can modify the defaultUrl app option in the web/app_options.js file or you can append the ?file= query string to the viewer URL, e.g. http://mozilla.github.com/pdf.js/web/viewer.html?file=compressed.tracemonkey-pldi-09.pdf. In the latter case, the PDF path/URL must be encoded using encodeURIComponent()

So, you will simply need to call encodeURIComponent() on your path.

Edit: You must encode the URI with the js function encodeURIComponent(), because there are some differences how the js function encodes the path, and how C# encodes it.

E.g. Comparing WebUtility.UrlEcode docs with encodeURIComponent docs, we can see that most of the escapes are similar. What is being escaped is:

encodeURIComponent() escapes all characters except: A-Z a-z 0-9 - _ . ! ~ * ' ( )

So far so good. Unfortunately, both methods escape differently the " " (space) symbol.

C#'s method UrlEncode does this:

Each ' ' (space) character is converted to a + (plus) character.

JS' function encodeURIComponent does this:

console.log(encodeURI("ABC abc 123")); // ABC%20abc%20123 (the space gets encoded as %20)

Body:
I am working on loading a pdf file in Xamarin through Web view. When the file path has special characters in it, pdf file is not loading.

Below is the code.

if (e.NewElement is PDFView pdfWebView)
            {

            this.Control.Settings.JavaScriptEnabled = true;
            this.Control.Settings.AllowFileAccess = true;
            this.Control.Settings.AllowUniversalAccessFromFileURLs = true;
            Control.LoadUrl($"file:///android_asset/pdfjs/web/viewer.html?file=file://{pdfWebView.Uri}");
        }


答: This is a function pointer returning nothing and taking a void pointer (see the section called void pointers).

Title: Can someone explain the parameter void(*pfn)(void*)?


问:
How To Add More Than 50 Domains in Google Recaptcha
I am using Google Recaptcha V2 for my site and I have added 50 domains to support the Captcha on these domains. But I have more than 50 domains to add for and I can't do in google recaptcha admin.
So any solutions/suggestions for this?

答:
After doing quite a research, I found that we simply can't add more than 50 domains per key site/secret key pair.
However, we can add 50 such key pairs per google account and then create a JSON containing list of domains and its site/secret key pair like

```<code>{
   "CaptchaGroups":{
      "Group 1":{
         "CaptchaSiteKey":"group 1 site key",
         "CaptchaSecretKey":"group 1 secret key",
         "Domains":[
            "domain1.com",
            "domain2.co",
            "domain3.edu"
         ]
      },
      "Group 2":{
         "CaptchaSiteKey":"group 2 site key",
         "CaptchaSecretKey":"group 2 secret key",
         "Domains":[
            "domain4.com",
            "domain5.co",
            "domain6.edu",
            "localhost"
         ]
      }
   }
}
</code>```

Then in code we can read the appropriate domain and use the site/secret key pair to use.

Body:
After doing quite a research, I found that we simply can't add more than 50 domains per key site/secret key pair.
However, we can add 50 such key pairs per google account and then create a JSON containing list of domains and its site/secret key pair like

{
   "CaptchaGroups":{
      "Group 1":{
         "CaptchaSiteKey":"group 1 site key",
         "CaptchaSecretKey":"group 1 secret key",
         "Domains":[
            "domain1.com",
            "domain2.co",
            "domain3.edu"
         ]
      },
      "Group 2":{
         "CaptchaSiteKey":"group 2 site key",
         "CaptchaSecretKey":"group 2 secret key",
         "Domains":[
            "domain4.com",
            "domain5.co",
            "domain6.edu",
            "localhost"
         ]
      }
   }
}

Then in code we can read the appropriate domain and use the site/secret key pair to use.


问:
Divs not spanning vertically using CSS Grid
I'm trying to make a simple layout as I'm learning CSS Grid.

The layout should be as follows:

"header header header"

"adv content content"

"adv footer footer"

What I'm getting is this:

"header header header"

"adv content content"

".   footer footer"

The div "adv" never takes the vertical space, doesn't matter if I do it using template-areas as above or using grid-row and columns as the code below.
In fact, I'm not able to manipulate any of my divs vertically. I cannot make them span several rows. Can somebody maybe tell me what I'm doing wrong?

body {
  background: dimgray;
}

div {
  height: 200px;
  font-size: 50px;
  font-family: sans-serif;
  color: floralwhite;
}

.header {
  background-color: lightcoral;
  grid-column: 1 / 4;
}

/*Div having the issue below*/

.adv {
  background-color: blue;
  grid-row: 2/4;
  /*Expecting to span from row 2 to 4, but not happening.*/
}

/*Div having the issue above*/

.content {
  background: pink;
  grid-column: 2/4;
}

.footer {
  background-color: salmon;
  grid-column: 2/4;
}

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">

    <div class="header">header
    </div>

    <div class="adv">adv
      <!--Div with the issue-->
    </div>

    <div class="content">content
    </div>

    <div class="footer">footer</div>

  </div>
</body></code>```

答: Your grid layout is fine, the problem is with: div {height: 200}, remove the height and it will work as expected.

Body:
I'm trying to make a simple layout as I'm learning CSS Grid.

The layout should be as follows:

"header header header"

"adv content content"

"adv footer footer"

What I'm getting is this:

"header header header"

"adv content content"

".   footer footer"

The div "adv" never takes the vertical space, doesn't matter if I do it using template-areas as above or using grid-row and columns as the code below.
In fact, I'm not able to manipulate any of my divs vertically. I cannot make them span several rows. Can somebody maybe tell me what I'm doing wrong?

body {
  background: dimgray;
}

div {
  height: 200px;
  font-size: 50px;
  font-family: sans-serif;
  color: floralwhite;
}

.header {
  background-color: lightcoral;
  grid-column: 1 / 4;
}

/*Div having the issue below*/

.adv {
  background-color: blue;
  grid-row: 2/4;
  /*Expecting to span from row 2 to 4, but not happening.*/
}

/*Div having the issue above*/

.content {
  background: pink;
  grid-column: 2/4;
}

.footer {
  background-color: salmon;
  grid-column: 2/4;
}

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

header

adv

content

footer


问:
Mongo atlas error while connecting on digitalocean
I edited the mongodb.conf, enabled the auth and inseting on bind_ip the ip of my droplet.

When I tried to connect to mongo --host XXXX it connects but can not find my users or database. for example:

$ mongo --host

MongoDB shell version v3.6.3

connectingto:mongodb://hostXXXX:27017/

MongoDB server version:3.6.3

db.system.users.find()

Error:error:{

"ok":0

"errmsg":"not authorized on test to execute command {find:"system.users", filter {}, $db: "test"},

"code":13,

"codeName":"Unauthorized"

}

答:
In modern versions of MongoDB there will be no system.users collection in the 'test' database, all user credential information is stored in the 'admin' database.

Atlas also restricts access to user credential information, so you probably won't be able to query that collection either.

If you need to find out about the current user, you can use the connectionStatus database command.

If you need to list or manage users programatically, you might find the API useful.


问:
How does WCF + SSL working with load balancing?
If SSL is handled by a load balancer, do I still need to configure it in the WCF serviceCertificate node?  My scenario is to use message level security.  If someone can explain how load balancing with wcf and ssl works, that would be very nice.</p>

答:
WCF requires security tokens to be passed over a secure transport if the message itself is not signed/encrypted. Since traffic is HTTP between your Big-IP and your individual web servers, you need a way to have security tokens that you know are secured between the client and the Big-IP up front still be passed to your server farm. There's a couple ways to do that depending on what version of WCF you're using:

If you're using WCF 4.0 you can just create a custom binding and set the AllowInsecureTransport property on the built in SecurityBindingElement to signify that you don't care that the transport isn't secure.

If you're using WCF 3.5 you have to "lie" about security with a custom TransportSecurityBindingElement on the server side. You can read my old post about this here.

FWIW, they created a hotfix release for 3.5 SP1 that adds the AllowInsecureTransport to that version, but I don't know if your company will allow you to install custom hotfixes.


问:
Use asyncio with neovim remote plugins
I want to write a vim plugin that listens to Server-sent events. Since I am most fluent with python3 and use neovim, I figured it would be a good idea to use the neovim remote plugin API.

Obviously, listening for messages from the network must not be blocking, so asyncio must be involved somehow. But I was not able to figure out how to combine the two. Somewhere I would have to run an event loop. However, pynvim already runs its own event loop, so I probably should hook into that.

@pynvim.plugin
class MyPlugin:
    def __init__(self, nvim):
        self.nvim = nvim

    @pynvim.command('Connect', nargs='1')
    async def connect(self, args):
        url = base_url + args[0]
        async with sse_client.EventSource(url) as event_source:
            for raw in event_source:
                try:
                    msg = json.loads(raw)
                except json.JSONDecodeError:
                    continue
                do_something(msg)
```

This example doesn't work. The Connect command is not available in neovim (it was before I made it async).

答:
Not sure if this is the best answer, but this is what I have found to work:

asyncio seems to keep a reference to the current loop, so asyncio.ensure_future() can be used to schedule async code. However, that async code will crash if it tries to access vim internals. In order to do that, you need to call yet another callback with nvim.async_call().

@pynvim.plugin
class MyPlugin:
    def __init__(self, nvim):
        self.nvim = nvim

    async def _connect(self, url):
        async with sse_client.EventSource(url) as event_source:
            for raw in event_source:
                try:
                    msg = json.loads(raw)
                except json.JSONDecodeError:
                    continue
                self.nvim.async_call(do_something, msg)

    @pynvim.command('Connect', nargs='1')
    def connect(self, args):
        url = base_url + args[0]
        asyncio.ensure_future(self._connect(url))
```

Title: Use asyncio with neovim remote plugins

Body:
I want to write a vim plugin that listens to Server-sent events. Since I am most fluent with python3 and use neovim, I figured it would be a good idea to use the neovim remote plugin API.

Obviously, listening for messages from the network must not be blocking, so asyncio must be involved somehow. But I was not able to figure out how to combine the two. Somewhere I would have to run an event loop. However, pynvim already runs its own event loop, so I probably should hook into that.

@pynvim.plugin
class MyPlugin:
    def __init__(self, nvim):
        self.nvim = nvim

    @pynvim.command('Connect', nargs='1')
    async def connect(self, args):
        url = base_url + args[0]
        async with sse_client.EventSource(url) as event_source:
            for raw in event_source:
                try:
                    msg = json.loads(raw)
                except json.JSONDecodeError:
                    continue
                do_something(msg)

This example doesn't work. The Connect command is not available in neovim (it was before I made it async).


问:
How to show a snackbar or toast after a user logs in
How can i show a snackbar or a toast when i user logs in <code>['you have successfully logged in!']</code>or it can be how can i show a snackbar or toast after a navigation. </p>

答:
I would recommend you to use the Flushbar Plugin: https://pub.dev/packages/flushbar
You can call it with </p>

```<code>Flushbar(
    title:  "You have successfully logged in!",
    duration:  Duration(seconds: 3),)..show(context)
</code>```

Body: How can i show a snackbar or a toast when i user logs in ['you have successfully logged in!']or it can be how can i show a snackbar or toast after a navigation.

Body:
I would recommend you to use the Flushbar Plugin: https://pub.dev/packages/flushbar
You can call it with

Flushbar(
    title:  "You have successfully logged in!",
    duration:  Duration(seconds: 3),)..show(context)


答:
The issue is it will not return a table with class="wikitable sortable collapsible" because it's not explicitly in the html. you would need to use regex to find classes that CONTAIN that substring, as that would work. Secondly, .find() will only return the first element it finds. Unless the table you are trying to grab has a specific, and unique attribute to identify it, using .find() won't work. If there are multiple elements, you need to use .find_all(), and even then you'd need to iterate through those to get the table you want.

As someone stated, you could also use pandas' .read_html(). This will return all the table tags in a list, then it's a matter of finding the index posiotn of the table you want. I provided both options for you:

Using Pandas:

```<code>import pandas as pd

url = 'https://en.wikipedia.org/wiki/New_York_City'

df = pd.read_html(url)[9]
df.to_csv('NYC_DEMO.csv',index=False)
</code>```

Using BeautifulSoup:

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/New_York_City'
website_url = requests.get(url).text
soup = BeautifulSoup(website_url,'html.parser')
tables = soup.find_all('table')
for table in tables:
    if 'Racial composition' in table.text:
        headers = [header.text.strip() for header in table.find_all('th')]
        rows = []
        table_rows = table.find_all('tr')
        for row in table_rows:
           td = row.find_all('td')
           row = [row.text for row in td]
           rows.append(row)

df = pd.DataFrame(rows, columns=headers)
</code>```

Output:

```<code>print (df)
                 Racial composition 2010[224] 1990[226]   1970[226] 1940[226]
0                             White     44.0%     52.3%       76.6%     93.6%
1                     —Non-Hispanic     33.3%     43.2%  62.9%[227]     92.0%
2         Black or African American     25.5%     28.7%       21.1%      6.1%
3  Hispanic or Latino (of any race)     28.6%     24.4%  16.2%[227]      1.6%
4                             Asian     12.7%      7.0%        1.2%         –
</code>```

Title: Scrape a Wikipedia table using beautifulsoup

Body:
The issue is it will not return a table with class="wikitable sortable collapsible" because it's not explicitly in the html. you would need to use regex to find classes that CONTAIN that substring, as that would work. Secondly, .find() will only return the first element it finds. Unless the table you are trying to grab has a specific, and unique attribute to identify it, using .find() won't work. If there are multiple elements, you need to use .find_all(), and even then you'd need to iterate through those to get the table you want.

As someone stated, you could also use pandas' .read_html(). This will return all the table tags in a list, then it's a matter of finding the index posiotn of the table you want. I provided both options for you:

Using Pandas:

import pandas as pd

url = 'https://en.wikipedia.org/wiki/New_York_City'

df = pd.read_html(url)[9]
df.to_csv('NYC_DEMO.csv',index=False)

Using BeautifulSoup:

import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/New_York_City'
website_url = requests.get(url).text
soup = BeautifulSoup(website_url,'html.parser')
tables = soup.find_all('table')
for table in tables:
    if 'Racial composition' in table.text:
        headers = [header.text.strip() for header in table.find_all('th')]
        rows = []
        table_rows = table.find_all('tr')
        for row in table_rows:
           td = row.find_all('td')
           row = [row.text for row in td]
           rows.append(row)

df = pd.DataFrame(rows, columns=headers)

Output:

print (df)
                 Racial composition 2010[224] 1990[226]   1970[226] 1940[226]
0                             White     44.0%     52.3%       76.6%     93.6%
1                     —Non-Hispanic     33.3%     43.2%  62.9%[227]     92.0%
2         Black or African American     25.5%     28.7%       21.1%      6.1%
3  Hispanic or Latino (of any race)     28.6%     24.4%  16.2%[227]      1.6%
4                             Asian     12.7%      7.0%        1.2%         –


问:
Detail explanation of all states in BottomSheetBehavior Android
There are around six different states in BottomSheetBehavior. I did not get any proper explanation of them.

Like I don't understand difference between STATE_HIDDEN and STATE_COLLAPSED?

Similarly what is difference between STATE_SETTLING and STATE_DRAGGING?

Also what is the use of STATE_HALF_EXPANDED?

答:
STATE_COLLAPSED -> bottomsheet is visible but only showing its peek height. This state is usually the ‘resting position’ of a Bottom Sheet. The peek height is chosen by the developer and should be enough to indicate there is extra content, allow the user to trigger an action or expand the bottom sheet.

STATE_HIDDEN -> bottomsheet is no longer visible on screen

STATE_EXPANDED -> bottom sheet is visible and its maximum height and it is neither dragging or settling

STATE_DRAGGING -> The user is actively dragging the bottom sheet up or down.

STATE_SETTLING -> bottomsheet is settling to specific height after a drag/swipe gesture. This will be the peek height, expanded height, or 0, in case the user action caused the bottom sheet to hide.

STATE_HALF_EXPANDED -> The sheet is half-expanded(half visible).  (only applicable if behavior_fitToContents has been set to false).

For more information, you can visit here


问:
How to insert data from html form into database without using HTML POST method?
Hi I would like to know if there is any other way using javascript or something to enter the user input directly to database without using POST method.</p>

答: If the result that you want is for the javascript itself to connect to the database and run the queries, then I believe the answer is no. However, this is something you would never ever want to do because it means the user would have full access to the database.

OwnerDisplayName: johnnaples

OwnerDisplayName: OverloadUT


问:
Placing 3 div's Side by Side
I want to place 3 divs side by side using CSS. I have gone through many posts on SO, but not getting the thing working for my project.

```<code>#quotescointainer{
    width: 100%;
    font-size: 12px;
}
#quotesleft{
    float:left;
    width: 33%;
    background-color: white;
}
#quotescenter{
    background-color:white;
    width: 33%;
}
#quotesright{
    float:left;
    width: 33%;
}
</code>```

The above does not place the div's in the correct place. I cannot seem to figure out the mistake I am making.

答:
I recently asked this exact same question.

Here is a link:

Inline div elements

Here is my accepted answer:

Set the CSS display style to
  display:inline-block;.

This allows the element to keep it's
  block-like functionality, while also
  allowing it to be displayed inline.
  It's a half-way house between the two.

(But note that there are some
  compatibility issues with older
  versions of IE)

Title: Placing 3 div's Side by Side

Body:
I want to place 3 divs side by side using CSS. I have gone through many posts on SO, but not getting the thing working for my project.

#quotescointainer{
    width: 100%;
    font-size: 12px;
}
#quotesleft{
    float:left;
    width: 33%;
    background-color: white;
}
#quotescenter{
    background-color:white;
    width: 33%;
}
#quotesright{
    float:left;
    width: 33%;
}

The above does not place the div's in the correct place. I cannot seem to figure out the mistake I am making.


问:
Binding two data frames and removing same row numbers in R
I have two data frames of equal number of rows (639) but differing column lengths (DF1: 5, DF2: 2500), the rows in DF1 correspond to the rows in DF2.

Some rows in DF2 will be removed due to several NAs, but I have no information on which ones are removed. cbind() does not allow me to bind the DFs together due to the now differing row lengths. However, I also need the rows to correspond, so if row 47 is removed in DF2, it must also be removed in DF1 upon merge. My assumption is that there can be some workaround with row.names but I am not sure how to execute it. Help would be appreciated. Examples of DFs below:

DF1:

```<code>    pp trialNo  item trialTarget trial
1 pp01       1  M012      script     1
2 pp01       2 BS016      script     2
3 pp01       3  M007      script     3
4 pp01       4 BS010      script     4
5 pp01       5  M006      script     5
6 pp01       6 BS018      script     6
</code>```

DF2:

```<code>    V1  V2  V3  V4  V5  V6
1: 764 764 763 763 762 763
2: 714 714 711 708 705 704
3: 872 871 869 867 867 871
4: 730 728 727 724 722 719
5: 789 786 788 790 792 790
6: 922 923 928 933 938 938
</code>```

And assuming row 3 in DF2 is removed, I would expect this after binding:

```<code>    pp trialNo  item trialTarget trial  V1  V2  V3  V4  V5  V6
1 pp01       1  M012      script     1 764 764 763 763 762 763
2 pp01       2 BS016      script     2 714 714 711 708 705 704
4 pp01       4 BS010      script     4 730 728 727 724 722 719
5 pp01       5  M006      script     5 789 786 788 790 792 790
6 pp01       6 BS018      script     6 922 923 928 933 938 938
</code>```

Thanks in advance.

Body:
I have two data frames of equal number of rows (639) but differing column lengths (DF1: 5, DF2: 2500), the rows in DF1 correspond to the rows in DF2.

Some rows in DF2 will be removed due to several NAs, but I have no information on which ones are removed. cbind() does not allow me to bind the DFs together due to the now differing row lengths. However, I also need the rows to correspond, so if row 47 is removed in DF2, it must also be removed in DF1 upon merge. My assumption is that there can be some workaround with row.names but I am not sure how to execute it. Help would be appreciated. Examples of DFs below:

DF1:

    pp trialNo  item trialTarget trial
1 pp01       1  M012      script     1
2 pp01       2 BS016      script     2
3 pp01       3  M007      script     3
4 pp01       4 BS010      script     4
5 pp01       5  M006      script     5
6 pp01       6 BS018      script     6

DF2:

    V1  V2  V3  V4  V5  V6
1: 764 764 763 763 762 763
2: 714 714 711 708 705 704
3: 872 871 869 867 867 871
4: 730 728 727 724 722 719
5: 789 786 788 790 792 790
6: 922 923 928 933 938 938

And assuming row 3 in DF2 is removed, I would expect this after binding:

    pp trialNo  item trialTarget trial  V1  V2  V3  V4  V5  V6
1 pp01       1  M012      script     1 764 764 763 763 762 763
2 pp01       2 BS016      script     2 714 714 711 708 705 704
4 pp01       4 BS010      script     4 730 728 727 724 722 719
5 pp01       5  M006      script     5 789 786 788 790 792 790
6 pp01       6 BS018      script     6 922 923 928 933 938 938

Thanks in advance.

Body:
You could create a row index in each of the dataframe.

df1$row <- 1:nrow(df1)
df2$row <- 1:nrow(df2)

Then remove 3rd row in df2.

df2 <- df2[-3, ]

You can then merge by row column both the dataframes.

merge(df1, df2, by = 'row')

#  row   pp trialNo  item trialTarget trial  V1  V2  V3  V4  V5  V6
#1   1 pp01       1  M012      script     1 764 764 763 763 762 763
#2   2 pp01       2 BS016      script     2 714 714 711 708 705 704
#3   4 pp01       4 BS010      script     4 730 728 727 724 722 719
#4   5 pp01       5  M006      script     5 789 786 788 790 792 790
#5   6 pp01       6 BS018      script     6 922 923 928 933 938 938

data

df1 <- structure(list(pp = c("pp01", "pp01", "pp01", "pp01", "pp01",
"pp01"), trialNo = 1:6, item = c("M012", "BS016", "M007", "BS010",
"M006", "BS018"), trialTarget = c("script", "script", "script",
"script", "script", "script"), trial = 1:6, row = 1:6), row.names = c(NA,
-6L), class = "data.frame")

df2 <- structure(list(V1 = c(764L, 714L, 872L, 730L, 789L, 922L), V2 = c(764L,
714L, 871L, 728L, 786L, 923L), V3 = c(763L, 711L, 869L, 727L,
788L, 928L), V4 = c(763L, 708L, 867L, 724L, 790L, 933L), V5 = c(762L,
705L, 867L, 722L, 792L, 938L), V6 = c(763L, 704L, 871L, 719L,
790L, 938L)), class = "data.frame", row.names = c(NA, -6L))


问:
How to delete CRLFs on a specific line with a loop in Python
I have a file like this:

```<code>"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (CR LF)
Line3Column2 (CR LF)"|"Line3 Column3 (CR LF)
Line3 Column3"|"Line2"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)
</code>```

I want to delete the CRLF on line 3, 4 to have the line 5 on the line 4 and the line 4 on the line 3.

BUT i don't want to delete the CRLF on line 5 otherwise my line 3 and my line 4 will be on the same line...

Finally i want :

```<code>"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (̶C̶R̶L̶F̶) Line3Column2 (̶C̶R̶L̶F̶) "|"Line3 Column3 (̶C̶R̶L̶F̶) Line3 Column3"|"Line3"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)
</code>```

I tried to make a loop (when i have a line with a pipe number < header then i delete his CRLF and then i restart from the beginning) but it doesn't work...

答:
You could use something like this:

def clean_up(lines):
    clean_lines = []
    for line in lines:
        cols = line.split('|')
        replaced_except_last = (col.replace('\r\n', '') for col in cols[:-1])
        cols[:-1] = replaced_except_last
        # join them back or do anything you want
        clean_lines.append('|'.join(cols))
    return clean_lines
```

<p>The idea is that we replace the unneeded CRLF in all columns except the last one.</p>

<p>Optionally, you could make this a generator too, which could help if your file is very large and you don't feel like loading it into memory an extra time.</p>

<pre class="lang-py prettyprint-override"><code>def clean_up(lines):
   for line in lines:
       cols = line.split('|')
       cols[:-1] = (col.replace('\r\n', '') for col in cols[:-1])
       yield '|'.join(cols) # if you want to get the list, "yield cols"
</code>```

and then you use it like

with open('filename') as file:
    # the file will be passed in line-by-line
    for clean_line in clean_up(file):
        print(clean_line)
```

Body:
I have a file like this:

"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (CR LF)
Line3Column2 (CR LF)"|"Line3 Column3 (CR LF)
Line3 Column3"|"Line2"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)

I want to delete the CRLF on line 3, 4 to have the line 5 on the line 4 and the line 4 on the line 3.

BUT i don't want to delete the CRLF on line 5 otherwise my line 3 and my line 4 will be on the same line...

Finally i want :

"Headers1"|"Headers2"|"Headers3"|"Headers4"(CR LF)
"Line1"|"Line1"|"Line1"|"Line1"(CR LF)
"Line2"|"Line2"|"Line2"|"Line2"(CR LF)
"Line3"|"Line3Column2 (̶C̶R̶L̶F̶) Line3Column2 (̶C̶R̶L̶F̶) "|"Line3 Column3 (̶C̶R̶L̶F̶) Line3 Column3"|"Line3"(CR LF)
"Line4"|"Line4"|"Line4"|"Line4"(CR LF)

I tried to make a loop (when i have a line with a pipe number < header then i delete his CRLF and then i restart from the beginning) but it doesn't work...

Body:
You could use something like this:

def clean_up(lines):
    clean_lines = []
    for line in lines:
        cols = line.split('|')
        replaced_except_last = (col.replace('\r\n', '') for col in cols[:-1])
        cols[:-1] = replaced_except_last
        # join them back or do anything you want
        clean_lines.append('|'.join(cols))
    return clean_lines

The idea is that we replace the unneeded CRLF in all columns except the last one.

Optionally, you could make this a generator too, which could help if your file is very large and you don't feel like loading it into memory an extra time.

def clean_up(lines):
   for line in lines:
       cols = line.split('|')
       cols[:-1] = (col.replace('\r\n', '') for col in cols[:-1])
       yield '|'.join(cols) # if you want to get the list, "yield cols"

and then you use it like

with open('filename') as file:
    # the file will be passed in line-by-line
    for clean_line in clean_up(file):
        print(clean_line)