问:
How can I change the description of a existing changelist in command line?
The command "p4 change" prompts a editor and needs a form. But I want to do this in command line.

How can I achieve this?

答:
There's always the -i command:

Read a changelist description from standard input. Input must be in the same format used by the p4 change form.

As Bryan points out in his comment the best approach is probably to run change -o, redirect the output to a file, process the file with other shell commands, and then send that file back to the server with change -i.

Source

But you can always change the description when you submit:

p4 submit -d "description"

This only works on the default change list.

Source


来源: stackexchange

问:
How to error handle in fetchMore pagination?
Im trying to use fetchMore with react-infinite-scroll (https://www.npmjs.com/package/react-infinite-scroller). It works most of the times, but I want to be able to catch a server error and handle it. I am talking to a service that 'throttles' me a lot so what I want to do is I wait 1sek and I try again.

My problem is that I don't know where to handle the error if it's thrown in fetchMore, since it's not passed into the render function.

I have tried using try/catch on the fetchMore function itself, I did not catch the error.

Im using nextjs if that helps.

```<code>return (
    <Query query={GET_COLLECTION} variables={{ handle: collectionHandle, first: 10, orderBy: orderBy }}>
        {({ loading, error, data, fetchMore, refetch }) => {
            if (loading && !data.getCollection) return <CollectionListLoader />
            // Normally I refetch in handleError
            if (error) return handleError({ error, loader: <Loader fullscreen={true} type="logo" />, refetch })

            const collection = data.getCollection

            return (
                <InfiniteScroll
                    initialLoad={false}
                    loadMore={() => {
                        fetchMore({
                            query: GET_MORE_COLLECTION,
                            variables: { handle: collectionHandle, first: 10, after: collection.products[collection.products.length - 1].cursor, orderBy: orderBy },
                            updateQuery: appendQuery,
                        })
                    }}
                    hasMore={collection.productsHasNextPage}
                    loader={<Loader type="logo" key="loader" />}
                >
                    <div className="row">
                        {collection.products.map((p, i) => {
                            return (
                                <div className="col-6 col-md-4" key={i}>
                                    <Product product={p} collectionHandle={collectionHandle} />
                                </div>
                            )
                        })}
                    </div>
                </InfiniteScroll>
            )
        }}
    </Query>
)
</code>```

Actual: If an error is thrown in fetchMore, the infinite scroller loads indefinetly, and I cant handle the error

Expected: If an error is thrown in fetchMore, I catch it and can handle it

答: This doesn't appear to be documented by Apollo but fetchMore returns a promise so you can handle errors with .catch().

ContentLicense: CC BY-SA 4.0

Body:
Im trying to use fetchMore with react-infinite-scroll (https://www.npmjs.com/package/react-infinite-scroller). It works most of the times, but I want to be able to catch a server error and handle it. I am talking to a service that 'throttles' me a lot so what I want to do is I wait 1sek and I try again.

My problem is that I don't know where to handle the error if it's thrown in fetchMore, since it's not passed into the render function.

I have tried using try/catch on the fetchMore function itself, I did not catch the error.

Im using nextjs if that helps.

return (
    <Query query={GET_COLLECTION} variables={{ handle: collectionHandle, first: 10, orderBy: orderBy }}>
        {({ loading, error, data, fetchMore, refetch }) => {
            if (loading && !data.getCollection) return <CollectionListLoader />
            // Normally I refetch in handleError
            if (error) return handleError({ error, loader: <Loader fullscreen={true} type="logo" />, refetch })

            const collection = data.getCollection

            return (
                <InfiniteScroll
                    initialLoad={false}
                    loadMore={() => {
                        fetchMore({
                            query: GET_MORE_COLLECTION,
                            variables: { handle: collectionHandle, first: 10, after: collection.products[collection.products.length - 1].cursor, orderBy: orderBy },
                            updateQuery: appendQuery,
                        })
                    }}
                    hasMore={collection.productsHasNextPage}
                    loader={<Loader type="logo" key="loader" />}
                >

                        {collection.products.map((p, i) => {
                            return (

                                    <Product product={p} collectionHandle={collectionHandle} />

                            )
                        })}

                </InfiniteScroll>
            )
        }}
    </Query>
)

Actual: If an error is thrown in fetchMore, the infinite scroller loads indefinetly, and I cant handle the error

Expected: If an error is thrown in fetchMore, I catch it and can handle it


问:
How to filter Ansible 'find' output
I would like to view the list of symbolic links from some remote servers in the terminal, but a lot of information is being printed when I run the playbook.

This is ansible 2.7.12 running on an Ubuntu server. I am using 'find' module and file_type: link to get the softlink details.

Find is returning a lot of details with the return value key "files" but I just need the soft links and corresponding server name in the terminal.

```<code>---
# tasks file for application
- name: Get the current applications running
  find:
    paths: /path/to/app
    file_type: link
  register: find_result

- name: Print find output
  debug:
    var: find_result.results
</code>```

Actual Result:

```<code>ok: [client3.example.com] => {
    "find_result.files": [
        {
            "atime": 1559027986.555,
            "ctime": 1559027984.828,
            "dev": 64768,
            "gid": 0,
            "gr_name": "root",
            "inode": 4284972,
            "isblk": false,
            "ischr": false,
            "isdir": false,
            "isfifo": false,
            "isgid": false,
            "islnk": true,
            "isreg": false,
            "issock": false,
            "isuid": false,
            "mode": "0777",
            "mtime": 1559027984.828,
            "nlink": 1,
            "path": "/path/to/app/softlink.1",
            "pw_name": "root",
            "rgrp": true,
            ...
            ...
</code>```

Would like to get some filtered output in the terminal like:

```<code>ok: [client3.example.com] => {
    "find_result.files": [
        {
            "path": "/path/to/app/softlink.1",
},
</code>```

答:
There are a couple of ways of addressing this question.  You could use the map filter to extract just the path attribute from your results:

```<code>- name: Print find output
  debug:
    var: results.files|map(attribute='path')|list
</code>```

Given the sample data in your question, this would result in:

```<code>TASK [Print find output] *****************************************************************************************************************************************************
ok: [localhost] => {
    "results.files|map(attribute='path')|list": [
        "/path/to/app/softlink.1"
    ]
}
</code>```

You can also accomplish something similar using the json_query filter, which applies JMESPath queries to your data:

```<code>- name: Print find output
  debug:
    var: results.files|json_query('[*].path')
</code>```

Title: How to filter Ansible 'find' output

Body:
I would like to view the list of symbolic links from some remote servers in the terminal, but a lot of information is being printed when I run the playbook.

This is ansible 2.7.12 running on an Ubuntu server. I am using 'find' module and file_type: link to get the softlink details.

Find is returning a lot of details with the return value key "files" but I just need the soft links and corresponding server name in the terminal.

---
# tasks file for application
- name: Get the current applications running
  find:
    paths: /path/to/app
    file_type: link
  register: find_result

- name: Print find output
  debug:
    var: find_result.results

Actual Result:

ok: [client3.example.com] => {
    "find_result.files": [
        {
            "atime": 1559027986.555,
            "ctime": 1559027984.828,
            "dev": 64768,
            "gid": 0,
            "gr_name": "root",
            "inode": 4284972,
            "isblk": false,
            "ischr": false,
            "isdir": false,
            "isfifo": false,
            "isgid": false,
            "islnk": true,
            "isreg": false,
            "issock": false,
            "isuid": false,
            "mode": "0777",
            "mtime": 1559027984.828,
            "nlink": 1,
            "path": "/path/to/app/softlink.1",
            "pw_name": "root",
            "rgrp": true,
            ...
            ...

Would like to get some filtered output in the terminal like:

ok: [client3.example.com] => {
    "find_result.files": [
        {
            "path": "/path/to/app/softlink.1",
},

Body:
There are a couple of ways of addressing this question.  You could use the map filter to extract just the path attribute from your results:

- name: Print find output
  debug:
    var: results.files|map(attribute='path')|list

Given the sample data in your question, this would result in:

TASK [Print find output] *****************************************************************************************************************************************************
ok: [localhost] => {
    "results.files|map(attribute='path')|list": [
        "/path/to/app/softlink.1"
    ]
}

You can also accomplish something similar using the json_query filter, which applies JMESPath queries to your data:

- name: Print find output
  debug:
    var: results.files|json_query('[*].path')


问:
Docker container exibits different behavour when run automatically
I have a basic Python Docker container that uses the O365 library to retrieve mail from Office365.

```<code>FROM python:3
ADD requirements.txt ./
RUN pip install -r requirements.txt
ADD ./main ./main
CMD [ "python", "./main/main.py"]
</code>```

The first time you run this O365 library, you need to authorize it and it stores a o365_token.txt which it uses after that. That looks like this:

```<code>Visit the following url to give consent:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?resp....
Paste the authenticated url here:
</code>```

This also happened on my new Docker so I logged in to it through Bash:

docker run -it hvdveer/e2t-python bash

But now when I manually run it, it just utilizes the existing token and it works without verification. Deleting the token files and authorizing it again also doesn't work. Why does it ask for authorization when I run it automatically, but not when run it manually? Are these different users? How to I fix this?

答:
I fixed it!

The CMD is run from the root directory so it's looking for the token there. By changing the WORKDIR to the main of my program it now finds the token:

```<code>FROM python:3
ADD requirements.txt ./
RUN pip install -r requirements.txt
WORKDIR /main
ADD ./main .
CMD [ "python", "./main.py"]
</code>```

The reason why running it from root by hand and creating a token in root didn't solve the problem, is because those changes aren't saved. Apparently every time you close the image it forgets everything. Live and learn.

Body:
I have a basic Python Docker container that uses the O365 library to retrieve mail from Office365.

FROM python:3
ADD requirements.txt ./
RUN pip install -r requirements.txt
ADD ./main ./main
CMD [ "python", "./main/main.py"]

The first time you run this O365 library, you need to authorize it and it stores a o365_token.txt which it uses after that. That looks like this:

Visit the following url to give consent:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?resp....
Paste the authenticated url here:

This also happened on my new Docker so I logged in to it through Bash:

docker run -it hvdveer/e2t-python bash

But now when I manually run it, it just utilizes the existing token and it works without verification. Deleting the token files and authorizing it again also doesn't work. Why does it ask for authorization when I run it automatically, but not when run it manually? Are these different users? How to I fix this?

Body:
I fixed it!

The CMD is run from the root directory so it's looking for the token there. By changing the WORKDIR to the main of my program it now finds the token:

FROM python:3
ADD requirements.txt ./
RUN pip install -r requirements.txt
WORKDIR /main
ADD ./main .
CMD [ "python", "./main.py"]

The reason why running it from root by hand and creating a token in root didn't solve the problem, is because those changes aren't saved. Apparently every time you close the image it forgets everything. Live and learn.


问:
Spark ouput parquet size with SparkListener
I am using the onStageCompleted of the SparkListener, trying to mine out some usefull data from the accumulables.

I am interested in finding out the size of output for monitoring purposes.
While the input line count and bytes can be taken from the first stage's "internal.metrics.input.recordsRead" and "internal.metrics.shuffle.write.bytesWritten" and the output line count can be found from "internal.metrics.shuffle.write.recordsWritten" from my penultimate stage, I have no clue how to find the ouput bytes.

Decompressed or compressed is also would an option for me. I'm using Spark 2.10.

答:
Have a look at onTaskEnd, there is a bytesWritten property.
Databricks SparkTaskMetrics
might also be useful.


问:
Push Notification - Mobile to Mobile
I want to send message from one mobile to another mobile(Push Notification).
Firebase has a push notification service, but it's not directly between mobile to mobile.

It's either mobile to desktop(Upstream), or desktop to mobile(downstream).

Basically the app is supposed to send alert from one mobile to another.

I am beginner, would really appreciate if there's already a function for this.

答:
It is not possible at least not in Sweden because the mobile operators are doing som funky routings with the ip address. Because of this it is only possible to create an outgoing connection from a mobile phone. Even if you have the mobile ip address you cant lock on and get an in going connection.

This is why there are services like Firebase, Signal and others that offer the flexibility to solve this problem

Of course some operators offers static ip adress for an extra fee, that would make it possible to run anything incoming, but users in general does not subscriber to this since they have no use for it

Look forward to if someone can prove me wrong..

Title: Push Notification - Mobile to Mobile


问:
phpbb and filesystem storage
Can I save the images file on filesystem (no db) in phpbb?

thanks

答: Images (uploaded avatars and attachements) are stored on the filesystem by phpBB, more specifically within the store directory.

ContentLicense: CC BY-SA 2.5

Title: phpbb and filesystem storage

ContentLicense: CC BY-SA 3.0


问:
PyHook doesn't detect key pressed in some windows
I ran this PyHook sample code:

```<code>    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()
</code>```

To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.

Is there a way to listen to keypresses from a specific process? what should I do?

答:
Try using keyboard instead here is an example according to the keyboard page on Github. You have to run this with sudo through the command (in command prompt) sudo python file.py

```<code>import sys
sys.path.append('..')
import keyboard
def print_pressed_keys(e):
    line = ', '.join(str(code) for code in keyboard._pressed_events)
    # '\r' and end='' overwrites the previous line.
    # ' '*40 prints 40 spaces at the end to ensure the previous line is cleared.
    print('\r' + line + ' ' * 40k, end='')

keyboard.hook(print_pressed_keys)
keyboard.wait()
</code>```

Body:
I ran this PyHook sample code:

    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.

Is there a way to listen to keypresses from a specific process? what should I do?

Body:
Try using keyboard instead here is an example according to the keyboard page on Github. You have to run this with sudo through the command (in command prompt) sudo python file.py

import sys
sys.path.append('..')
import keyboard
def print_pressed_keys(e):
    line = ', '.join(str(code) for code in keyboard._pressed_events)
    # '\r' and end='' overwrites the previous line.
    # ' '*40 prints 40 spaces at the end to ensure the previous line is cleared.
    print('\r' + line + ' ' * 40k, end='')

keyboard.hook(print_pressed_keys)
keyboard.wait()


问:
How can i solve memory limit issue in r
I am worknig with 2 dataframes in r and when I try to merge them there is an erro: Error: cannot allocate vector of size 565.3 Mb

If I check: memory.limit()

memory.limit()
  [1] 1.759219e+13

My PC 8GB RAM.

What can I do to solve this issue??

答: If you need to merge large data frames in R, one good option is to do it in pieces of, say 10000 rows. If you're merging data frames x and y, loop over 10000-row pieces of x, merge (or rather use plyr::join) with y and immediately append these results to a sigle csv-file. After all pieces have been merged and written to file, read that csv-file. This is very memory-efficient with proper use of logical index vectors and well placed rm and gc calls. It's not fast though.</p>

Title: How can i solve memory limit issue in r


问:
Parallel async tasks not executing concurrently
I am trying to parallelise a set simulations of multi agent systems so they can utilise as many cpu cores as are available to me (currently 72). To do this I am trying to package each simulation as a separate asynchronous computation and then running them in parallel.

The following code is how I run the simulation. SimulationLst is a list of simulation initial states. Each simulation returns a list of integers which I then average over all the simulations. Each simulation has no side effects.

```<code>SimulationList
|> List.map (fun simulation -> async {return runSimulation simulation})
|> Async.Parallel
|> Async.RunSynchonously
|> Aray.toList
|> List.concat
|> List.average
</code>```

The problem is that when I run the program, the first four simulations start immediately but the next start very slowly one after another. The result is that the cpu utilisation starts off very poor and very slowly ramps up to use more cores.

What reasons could there be for these computations not starting immediately? Is it because I am doing this at quite a high level (ie simulation by simulation)? Would finer grain concurrency make this work better?

There is not much detail in this question about the code I'm using since there is a lot of it but please ask for more detail if it would help.

答: My guess would be that you're in a situation where the ThreadPool has a limited number of threads available to process tasks and so is slowly ramping up the thread count at a rate of 0.5/sec or 1/sec.  You should try adjusting the minimum ThreadPool thread count before running your code to see if that alleviates the problem.</p>

Body:
I am trying to parallelise a set simulations of multi agent systems so they can utilise as many cpu cores as are available to me (currently 72). To do this I am trying to package each simulation as a separate asynchronous computation and then running them in parallel.

The following code is how I run the simulation. SimulationLst is a list of simulation initial states. Each simulation returns a list of integers which I then average over all the simulations. Each simulation has no side effects.

SimulationList
|> List.map (fun simulation -> async {return runSimulation simulation})
|> Async.Parallel
|> Async.RunSynchonously
|> Aray.toList
|> List.concat
|> List.average

The problem is that when I run the program, the first four simulations start immediately but the next start very slowly one after another. The result is that the cpu utilisation starts off very poor and very slowly ramps up to use more cores.

What reasons could there be for these computations not starting immediately? Is it because I am doing this at quite a high level (ie simulation by simulation)? Would finer grain concurrency make this work better?

There is not much detail in this question about the code I'm using since there is a lot of it but please ask for more detail if it would help.


问:
Lex and Yacc without Dynamic Memory Allocation
I'm in the process of designing software to run in an embedded environment where the use of dynamic memory is prohibited.  Lex and Yacc are well suited for the application.

Can I configure Lex and Yacc to not use dynamic memory allocation at all?

Can I configure Lex and Yacc to use a predefined block of memory and therefor limit dynamic memory usage to that predefined space?

Can I limit the use of dynamic memory to program initialization only (i.e. when the program first runs)?

edit:
In response to TonyK, I want the parser to not use dynamic memory.

Thank you

答: You can use noyyalloc, noyyfree and noyyrealloc and then implement these yourself. </p>


问:
Is it possible to mount multiple volumes when starting minikube?
I tried this but didn't work:

```<code>minikube start --vm-driver=hyperkit --memory 8192 --mount \
               --mount-string /home/user/app1:/minikube-host/app1 \
               --mount-string /home/user/app2:/minikube-host/app2
</code>```

but only /home/user/app2 was mounted.

答:
There is no need for multiple volumes when starting in your case.

Also, minikube mount after start needs a terminal in running state(opened always).

You can mount /home/user -> /minikube-host. All the folders inside /home/user will be inside VM at /minikube-host.

/home/user/app1 will be available inside VM as
/minikube-host/app1

/home/user/app2 will be available inside VM as
/minikube-host/app2

minikube start --vm-driver=hyperkit --memory 8192 --mount \
               --mount-string /home/user:/minikube-host

Hope this helps !

Body:
I tried this but didn't work:

minikube start --vm-driver=hyperkit --memory 8192 --mount \
               --mount-string /home/user/app1:/minikube-host/app1 \
               --mount-string /home/user/app2:/minikube-host/app2

but only /home/user/app2 was mounted.


问:
Concatenate multiple HTML text inputs with stored variable
I am trying to create a simple html form which asks for some details from a user and once this has been submitted will add the text to some predetermined text in a text box.

Example of this...

Text box 1 - Enter Name
Text box 2 - Enter Age
Text box 3 - Enter Location

When this is submitted I would like this to be added preferably into a text box or even just output has text on an html page with other text already stored so the output would maybe be something like "Hello John, you are 25 years old and from London".

What I have is very basic:

```<code>    <html>
    <form>
    Name: <input type="text" name="name"><br>
    Age: <input type="text" name="age"><br>
    Location: <input type="text" name="location"><br>
    <input type="submit" value="Submit">
    </form>
    <html>
</code>```

Beyond this I'm unsure how to get all the values into another text box with the other predetermined text.

Any help or direction in this would be appreciated.

答:
function yes() {
var button = document.getElementById('test');
var name = document.getElementById('name');
var age = document.getElementById('age');
var location = document.getElementById('location');
    var str = 'Hello ' + name.value +
        ', you are ' + age.value +
        ' years old and from ' + location.value;
    document.getElementById('test').innerHTML=str;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<label>
    Enter name:
    <input id="name" />
</label>
<br />
<label>
    Enter age:
    <input id="age" />
</label>
<br />
<label>
    Enter location:
    <input id="location" />
</label>
<br />
<button onclick="yes()">Test</button>
<p id="test"></p>
</body>
</html></code>```

Body:
I am trying to create a simple html form which asks for some details from a user and once this has been submitted will add the text to some predetermined text in a text box.

Example of this...

Text box 1 - Enter Name
Text box 2 - Enter Age
Text box 3 - Enter Location

When this is submitted I would like this to be added preferably into a text box or even just output has text on an html page with other text already stored so the output would maybe be something like "Hello John, you are 25 years old and from London".

What I have is very basic:

    <form>
    Name: <input type="text" name="name">

    Age: <input type="text" name="age">

    Location: <input type="text" name="location">

    <input type="submit" value="Submit">
    </form>

Beyond this I'm unsure how to get all the values into another text box with the other predetermined text.

Any help or direction in this would be appreciated.

Body:
function yes() {
var button = document.getElementById('test');
var name = document.getElementById('name');
var age = document.getElementById('age');
var location = document.getElementById('location');
    var str = 'Hello ' + name.value +
        ', you are ' + age.value +
        ' years old and from ' + location.value;
    document.getElementById('test').innerHTML=str;
};

<html>
<body>
<label>
    Enter name:
    <input id="name" />
</label>
<br />
<label>
    Enter age:
    <input id="age" />
</label>
<br />
<label>
    Enter location:
    <input id="location" />
</label>
<br />
<button onclick="yes()">Test</button>
<p id="test"></p>
</body>
</html>


问:
Yahoo transforms height into min-height
I have just stumbled across the fact that Yahoo mail is transforming all height attributes into min-height. Is there a workaround for this?

```<code><div style="width:55px; height:55px; overflow:hidden;">
   <img alt="user pic" src="assets/main.jpeg" width="55px" />
</div>
</code>```

The goal of the code above is to hide the bottom part of the image if it's higher than 55px. I've tested this in hotmail and aol and it works fine. Only Yahoo seems to transform my height into min-height:

```<code><div style="width:55px; min-height:55px; overflow:hidden;">
</code>```

答:
As of now in May-2019 the Yahoo mail still transforms inline style height to min-height so what i have found as workaround is add max-height also in your inline style then it will works.

in my case i have image in my html and i just want it's height to set to 30px but yahoo transforms the height to min-height.

so it is becoming larger image but i want it to smaller so i have applied max-height in inline style and it worked.

see my img tag below i have applied max-height in inline style.

```<code><img src="<?php echo $url->assets ?>img/checked.png" style="height:30px;float: left;max-height:30px;" />
</code>```

Title: Yahoo transforms height into min-height

Body:
I have just stumbled across the fact that Yahoo mail is transforming all height attributes into min-height. Is there a workaround for this?

The goal of the code above is to hide the bottom part of the image if it's higher than 55px. I've tested this in hotmail and aol and it works fine. Only Yahoo seems to transform my height into min-height:

Body:
As of now in May-2019 the Yahoo mail still transforms inline style height to min-height so what i have found as workaround is add max-height also in your inline style then it will works.

in my case i have image in my html and i just want it's height to set to 30px but yahoo transforms the height to min-height.

so it is becoming larger image but i want it to smaller so i have applied max-height in inline style and it worked.

see my img tag below i have applied max-height in inline style.

<img src="<?php echo $url->assets ?>img/checked.png" style="height:30px;float: left;max-height:30px;" />


问:
select2: How to persist search term?
I would like for my select2 element to not clear out the searched term when I click away from the menu. I have searched a lot for this feature and it seems to have one day been possible, but it no longer works in version 4.0? I have also tried implementing this answer but it didn't seem to work.

My code currently is as follows:

```<code>$(document).ready(function () {
    function displayCurrentValue(selectedObject, currentSearchTerm) {
        return currentSearchTerm;
    }
    $("#reference").select2({
        nextSearchTerm: displayCurrentValue
    });
    $("#reference").select2({
        width: "100%",
        language: "pt-BR",
        ajax: {
            //omitted
        }
    });
});
</code>```

No matter what I try current behavior is:

Start typing a search

Click outside the dropdown

Click again to open the dropdown

Previous search is gone

Desired behavior is:

Previous search is preserved.

答:
A workaround that has worked for me:

To preserve last string query

```<code>$(document).on('select2:closing','.select2-hidden-accessible',function(){
    $(this).data('kmselect2LastSearch',$('.select2-search__field').val());
});
</code>```

To get and select last item according by last string query

```<code>$(document).on('select2:open','.select2-hidden-accessible',function(){
    if (typeof $(this).data('kmselect2LastSearch')=='undefined') {
        return;
    }
    var prevValue = $(this).data('kmselect2LastSearch');
    if ( prevValue != '' ) {
        $('.select2-search__field').val(prevValue).trigger('keydown').trigger('input');
    }
});
</code>```

Title: select2: How to persist search term?

Body:
I would like for my select2 element to not clear out the searched term when I click away from the menu. I have searched a lot for this feature and it seems to have one day been possible, but it no longer works in version 4.0? I have also tried implementing this answer but it didn't seem to work.

My code currently is as follows:

$(document).ready(function () {
    function displayCurrentValue(selectedObject, currentSearchTerm) {
        return currentSearchTerm;
    }
    $("#reference").select2({
        nextSearchTerm: displayCurrentValue
    });
    $("#reference").select2({
        width: "100%",
        language: "pt-BR",
        ajax: {
            //omitted
        }
    });
});

No matter what I try current behavior is:

Start typing a search

Click outside the dropdown

Click again to open the dropdown

Previous search is gone

Desired behavior is:

Previous search is preserved.

Body:
A workaround that has worked for me:

To preserve last string query

$(document).on('select2:closing','.select2-hidden-accessible',function(){
    $(this).data('kmselect2LastSearch',$('.select2-search__field').val());
});

To get and select last item according by last string query

$(document).on('select2:open','.select2-hidden-accessible',function(){
    if (typeof $(this).data('kmselect2LastSearch')=='undefined') {
        return;
    }
    var prevValue = $(this).data('kmselect2LastSearch');
    if ( prevValue != '' ) {
        $('.select2-search__field').val(prevValue).trigger('keydown').trigger('input');
    }
});


问:
Tkinter (Mac, Python 2.6): Image not visible with create_image and Menu item
I've defined a menu which should show an image (JPG, 250x250) in an item.

```<code>import Tkinter
from PIL import Image, ImageTk

def show_photo():
  img=Image.open("image.jpg")
  photo=ImageTk.PhotoImage(img)
  width=photo.width();
  height=photo.height()
  w=Tkinter.Toplevel(root)
  w.geometry(str(width+2)+'x'+str(height+2))
  w.title(str(width)+'x'+str(height))
  canvas=Tkinter.Canvas(w, bg="black", width=width, height=height)
  canvas.pack()
  img=canvas.create_image(0,0,anchor=Tkinter.NW,image=photo)
  xxx    # NameError

root=Tkinter.Tk()
mainmenu = Tkinter.Menu(root)
menu1 = Tkinter.Menu(mainmenu)
mainmenu.add_cascade(label="Menu 1", menu=menu1)
menu1.add_command(label="Show photo", command=show_photo)
root.config(menu=mainmenu)
root.mainloop()
</code>```

Unless I put a wrong line (here: xxx), the image doesn't appear, only a correct size black rectangle.

Any clue ?

Thanks by advance,
Eric.

答:
My guess is this: your image is in a local variable. When show_photo() exits, the image reference gets garbage-collected and thus the image gets destroyed. When that happens Tkinter is no longer able to show the image because the data is gone.

Try saving a reference to the image, either in a global or instance variable.

Body:
I've defined a menu which should show an image (JPG, 250x250) in an item.

import Tkinter
from PIL import Image, ImageTk

def show_photo():
  img=Image.open("image.jpg")
  photo=ImageTk.PhotoImage(img)
  width=photo.width();
  height=photo.height()
  w=Tkinter.Toplevel(root)
  w.geometry(str(width+2)+'x'+str(height+2))
  w.title(str(width)+'x'+str(height))
  canvas=Tkinter.Canvas(w, bg="black", width=width, height=height)
  canvas.pack()
  img=canvas.create_image(0,0,anchor=Tkinter.NW,image=photo)
  xxx    # NameError

root=Tkinter.Tk()
mainmenu = Tkinter.Menu(root)
menu1 = Tkinter.Menu(mainmenu)
mainmenu.add_cascade(label="Menu 1", menu=menu1)
menu1.add_command(label="Show photo", command=show_photo)
root.config(menu=mainmenu)
root.mainloop()

Unless I put a wrong line (here: xxx), the image doesn't appear, only a correct size black rectangle.

Any clue ?

Thanks by advance,
Eric.


问:
Oracle output results of query to file
Currently i am running multiple queries which spool the output to a file this can be a lengthy process, below are my current settings in sqlplus.

```<code>set feedback off
set heading off
set echo off
set termout OFF
set linesize 150
set long 1999999
set longchunk 1999999
set pagesize 0
spool results.sql
@queries.sql
spool off
set termout on
set echo on
set heading on
set feedback on
</code>```

I was wondering if there is any way i can speed up this process? Or is there a faster way of sending output of the queries to a file using sqlplus?

Thanks

答:
Clarifications

Can you please clarify the following

Is the sqlplus client on the same physical box (or virtual machine) that your database management system is on (more specifically, your ora and datafiles)?

Can you test your query by decreasing the size of the result set using fetch first n rows?

Time Complexity and Specifics

Why do you believe the bottleneck is spooling?  Before jumping to any conclusions about the causes of poor performance you may want to try an gather some timing statistics on your query.  I would modify your query to only return a subset of rows

```<code>SELECT * FROM scott.dept FETCH FIRST 10000 rows
</code>```

Optimizing your queries is highly depending on how your data is structure and how your routines run, so in order to optimize you need to be able to benchmark your performance changes.

You will then want to check the following two parameters

```<code>SHOW PARAMETER statistics_level
SHOW PARAMETER timed_statistics
</code>```

And you will also want to time your queries

```<code>SET TIMING ON
</code>```

Remember, all of this is simply to benchmark performance, you will need to revert these settings in production.

Keep in mind that running the same query multiple times will cause inconsistent performance metrics because of pooling / buffering / caching / etc.  You should query the v$statistics_level and investigate

Rows Processed

Sort (memory)

Sort (Disk)

physical reads

consistent get

I would SHUTDOWN IMMEDIATELY; STARTUP MOUNT; and then your an explain on your query multiple times.

```<code>EXPLAIN PLAN FOR SELECT * FROM SCOTT.DEPT;
</code>```

Check if the explain plan is changing on your subsequent calls.

Additionally, in certain circumstances you can force a cache of a table by running

```<code>SELECT * FROM SCOTT.DEPT CACHE;
</code>```

And then comparing it to the performance metrics of

```<code>SELECT * FROM SCOTT.DEPT NOCACHE;
</code>```

You may want to also keep the table in-memory indefinitely

```<code>ALTER TABLE *scott.dept* STORAGE (buffer_pool keep)
</code>```

If you don't see anything glaring then run an  explain plan for your query.  Run the explain multiple times in succession to see if anything changes.

Beyond that, you should also remember that running your query multiple times without flushing your buffers / clearing cache is going to give you unreliable readings.  If you aren't sure the spooling is the bottle neck, I would also suggest you run an explain plan for your query

There are also some tricks to increasing performance over time (assuming this routine is ran regularly).  If you with alter table *table_name* cache, run the query without spooling to a file, then running again alter table *table_name* nocache with spool you may be a more performant run, but again if this is feasible completely depends on your use cases.

Settings

While I doubt your issue here is going to be solved by any combination of settings, below are a few that may provide marginal benefits

set trimspool on

Removing white spaces in spool file to fill up linesize
2. set echo off
This may be pointless depending on whether your routine is fully automated or interactive
3. set verify off
This will remove substitution variables from your spool, but can speed up your process considerably... again, depending on your data
4. set autoprint off
This is another variable setting.  Off is the default setting, but you but assurance I would explicitly set it
5. set serveroutput off
6. SET TRIMOUT ON
Removes whitespaces filling linesize on out file
7.  set arraysize N
You are definitely going to tinker with this one.  N is the number of rows being fetched at a single time.  The size of this depends on the structure of your table

While these settings may increase the speed of your routines, performance is generally specific to your architecture and data set.

Title: Oracle output results of query to file

Body:
Currently i am running multiple queries which spool the output to a file this can be a lengthy process, below are my current settings in sqlplus.

set feedback off
set heading off
set echo off
set termout OFF
set linesize 150
set long 1999999
set longchunk 1999999
set pagesize 0
spool results.sql
@queries.sql
spool off
set termout on
set echo on
set heading on
set feedback on

I was wondering if there is any way i can speed up this process? Or is there a faster way of sending output of the queries to a file using sqlplus?

Thanks

Body:
Clarifications

Can you please clarify the following

Is the sqlplus client on the same physical box (or virtual machine) that your database management system is on (more specifically, your ora and datafiles)?

Can you test your query by decreasing the size of the result set using fetch first n rows?

Time Complexity and Specifics

Why do you believe the bottleneck is spooling?  Before jumping to any conclusions about the causes of poor performance you may want to try an gather some timing statistics on your query.  I would modify your query to only return a subset of rows

SELECT * FROM scott.dept FETCH FIRST 10000 rows

Optimizing your queries is highly depending on how your data is structure and how your routines run, so in order to optimize you need to be able to benchmark your performance changes.

You will then want to check the following two parameters

SHOW PARAMETER statistics_level
SHOW PARAMETER timed_statistics

And you will also want to time your queries

SET TIMING ON

Remember, all of this is simply to benchmark performance, you will need to revert these settings in production.

Keep in mind that running the same query multiple times will cause inconsistent performance metrics because of pooling / buffering / caching / etc.  You should query the v$statistics_level and investigate

Rows Processed

Sort (memory)

Sort (Disk)

physical reads

consistent get

I would SHUTDOWN IMMEDIATELY; STARTUP MOUNT; and then your an explain on your query multiple times.

EXPLAIN PLAN FOR SELECT * FROM SCOTT.DEPT;

Check if the explain plan is changing on your subsequent calls.

Additionally, in certain circumstances you can force a cache of a table by running

SELECT * FROM SCOTT.DEPT CACHE;

And then comparing it to the performance metrics of

SELECT * FROM SCOTT.DEPT NOCACHE;

You may want to also keep the table in-memory indefinitely

ALTER TABLE *scott.dept* STORAGE (buffer_pool keep)

If you don't see anything glaring then run an  explain plan for your query.  Run the explain multiple times in succession to see if anything changes.

Beyond that, you should also remember that running your query multiple times without flushing your buffers / clearing cache is going to give you unreliable readings.  If you aren't sure the spooling is the bottle neck, I would also suggest you run an explain plan for your query

There are also some tricks to increasing performance over time (assuming this routine is ran regularly).  If you with alter table *table_name* cache, run the query without spooling to a file, then running again alter table *table_name* nocache with spool you may be a more performant run, but again if this is feasible completely depends on your use cases.

Settings

While I doubt your issue here is going to be solved by any combination of settings, below are a few that may provide marginal benefits

set trimspool on

Removing white spaces in spool file to fill up linesize
2. set echo off
This may be pointless depending on whether your routine is fully automated or interactive
3. set verify off
This will remove substitution variables from your spool, but can speed up your process considerably... again, depending on your data
4. set autoprint off
This is another variable setting.  Off is the default setting, but you but assurance I would explicitly set it
5. set serveroutput off
6. SET TRIMOUT ON
Removes whitespaces filling linesize on out file
7.  set arraysize N
You are definitely going to tinker with this one.  N is the number of rows being fetched at a single time.  The size of this depends on the structure of your table

While these settings may increase the speed of your routines, performance is generally specific to your architecture and data set.


问:
How to convert a recursive array into a string using PHP?
I have an array with nested arrays inside that I need to convert into a string with a given format.

This is for a PHP website. I get the information from a database, it comes as an array, and I need to pass it to charts.js so that I can plot it.

This is the varDump I get when I query the DB:

```<code>array(4) { [0]=> array(2) { ["date"]=> string(19) "2019-05-19 00:00:00" ["price"]=> string(3) "120" } [1]=> array(2) { ["date"]=> string(19) "2019-05-12 00:00:00" ["price"]=> string(3) "100" } [2]=> array(2) { ["date"]=> string(19) "2019-05-05 00:00:00" ["price"]=> string(3) "120" } [3]=> array(2) { ["date"]=> string(19) "2019-04-28 00:00:00" ["price"]=> string(3) "110" } }
</code>```

This is what I would need as a result in a text string:

```<code>data: [{
    x: 2019-05-19 00:00:00,
    y: 120
}, {
    t: 2019-05-12 00:00:00,
    y: 100
}, {
    t: 2019-05-05 00:00:00,
    y: 120
}, {
    t: 2019-04-28 00:00:00,
    y: 110
}]
</code>```

答:
You can use array_map as below,

```<code>$temp = array_map(function ($item) {return array_combine(["x", "y"], $item); }, $temp);
</code>```

I created ['x','y'] to combine as key as replacement for $item's keys.

array_combine — Creates an array by using one array for keys and another for its values

Working demo.

Body:
I have an array with nested arrays inside that I need to convert into a string with a given format.

This is for a PHP website. I get the information from a database, it comes as an array, and I need to pass it to charts.js so that I can plot it.

This is the varDump I get when I query the DB:

array(4) { [0]=> array(2) { ["date"]=> string(19) "2019-05-19 00:00:00" ["price"]=> string(3) "120" } [1]=> array(2) { ["date"]=> string(19) "2019-05-12 00:00:00" ["price"]=> string(3) "100" } [2]=> array(2) { ["date"]=> string(19) "2019-05-05 00:00:00" ["price"]=> string(3) "120" } [3]=> array(2) { ["date"]=> string(19) "2019-04-28 00:00:00" ["price"]=> string(3) "110" } }

This is what I would need as a result in a text string:

data: [{
    x: 2019-05-19 00:00:00,
    y: 120
}, {
    t: 2019-05-12 00:00:00,
    y: 100
}, {
    t: 2019-05-05 00:00:00,
    y: 120
}, {
    t: 2019-04-28 00:00:00,
    y: 110
}]

Body:
You can use array_map as below,

$temp = array_map(function ($item) {return array_combine(["x", "y"], $item); }, $temp);

I created ['x','y'] to combine as key as replacement for $item's keys.

array_combine — Creates an array by using one array for keys and another for its values

Working demo.


问:
How to read image file from S3 bucket directly into memory?
I have the following code

```<code>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import boto3
s3 = boto3.resource('s3', region_name='us-east-2')
bucket = s3.Bucket('sentinel-s2-l1c')
object = bucket.Object('tiles/10/S/DG/2015/12/7/0/B01.jp2')
object.download_file('B01.jp2')
img=mpimg.imread('B01.jp2')
imgplot = plt.imshow(img)
plt.show(imgplot)
</code>```

and it works. But the problem it downloads file into current directory first. Is it possible to read file and decode it as image directly in RAM?

答:
Further development from Greg Merritt's answer to solve all errors in the comment section, using BytesIO instead of StringIO, using PIL Image instead of matplotlib.image.

The following function works for python3 and boto3. Similarly, write_image_to_s3 function is a bonus.

from PIL import Image
from io import BytesIO
import numpy as np

def read_image_from_s3(bucket, key, region_name='ap-southeast-1'):
    """Load image file from s3.

    Parameters
    ----------
    bucket: string
        Bucket name
    key : string
        Path in s3

    Returns
    -------
    np array
        Image array
    """
    s3 = boto3.resource('s3', region_name='ap-southeast-1')
    bucket = s3.Bucket(bucket)
    object = bucket.Object(key)
    response = object.get()
    file_stream = response['Body']
    im = Image.open(file_stream)
    return np.array(im)

def write_image_to_s3(img_array, bucket, key, region_name='ap-southeast-1'):
    """Write an image array into S3 bucket

    Parameters
    ----------
    bucket: string
        Bucket name
    key : string
        Path in s3

    Returns
    -------
    None
    """
    s3 = boto3.resource('s3', region_name)
    bucket = s3.Bucket(bucket)
    object = bucket.Object(key)
    file_stream = BytesIO()
    im = Image.fromarray(img_array)
    im.save(file_stream, format='jpeg')
    object.put(Body=file_stream.getvalue())
```

Body:
I have the following code

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import boto3
s3 = boto3.resource('s3', region_name='us-east-2')
bucket = s3.Bucket('sentinel-s2-l1c')
object = bucket.Object('tiles/10/S/DG/2015/12/7/0/B01.jp2')
object.download_file('B01.jp2')
img=mpimg.imread('B01.jp2')
imgplot = plt.imshow(img)
plt.show(imgplot)

and it works. But the problem it downloads file into current directory first. Is it possible to read file and decode it as image directly in RAM?


问:
Adding strings in lists together
I want to transform the list ["A","B","A","A","B"] to the list ["AB","BA","AA","AB"].

I have tried to define a new list in which the first element is deleted and then add the strings of the lists together. After which I plan to delete the last element of the new list to get the result.

```<code>lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]
</code>```

But all I get is

TypeError: 'list' object cannot be interpreted as an integer

Any help is welcome.

Edit : Thank you guys, all your solutions worked perfectly :)

答:
You can use map():

```<code>s = list(map(str.__add__, lst[:-1], lst[1:]))
</code>```

A bit better to use operator.concat() (thanks for advice, @MykolaZotko):

```<code>import operator

s = list(map(operator.concat, lst[:-1], lst[1:]))
</code>```

Upd.

I've decided to do some tests on bigger data.

```<code>import operator

lst = [...] # list with 10000 random uppercase letters

def test1():
    return list(map(operator.concat, lst[:-1], lst[1:]))

def test2():
    return [x + y for x, y in zip(lst, lst[1:])]

def test3():
    return [v + lst[i + 1] for i, v in enumerate(lst[:-1])]

def test4():
    s = ''.join(lst)
    return [s[i:i + 2] for i in range(len(s) - 1)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test1()", setup="from __main__ import test1, lst", number=10000))
    print(timeit.timeit("test2()", setup="from __main__ import test2, lst", number=10000))
    print(timeit.timeit("test3()", setup="from __main__ import test3, lst", number=10000))
    print(timeit.timeit("test4()", setup="from __main__ import test4, lst", number=10000))
</code>```

Results:

Python 2:

```<code>10.447159509
11.529946446
20.962497298000002
20.515838672
</code>```

Python 3:

```<code>10.370675522
11.429417197
20.836504865999995
20.422865353
</code>```

On bigger data map() is a bit (~9%) faster, but there's no significant difference between test1() and test2()

Title: Adding strings in lists together

Body:
I want to transform the list ["A","B","A","A","B"] to the list ["AB","BA","AA","AB"].

I have tried to define a new list in which the first element is deleted and then add the strings of the lists together. After which I plan to delete the last element of the new list to get the result.

lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]

But all I get is

TypeError: 'list' object cannot be interpreted as an integer

Any help is welcome.

Edit : Thank you guys, all your solutions worked perfectly :)

Body:
You can use map():

s = list(map(str.__add__, lst[:-1], lst[1:]))

A bit better to use operator.concat() (thanks for advice, @MykolaZotko):

import operator

s = list(map(operator.concat, lst[:-1], lst[1:]))

Upd.

I've decided to do some tests on bigger data.

import operator

lst = [...] # list with 10000 random uppercase letters

def test1():
    return list(map(operator.concat, lst[:-1], lst[1:]))

def test2():
    return [x + y for x, y in zip(lst, lst[1:])]

def test3():
    return [v + lst[i + 1] for i, v in enumerate(lst[:-1])]

def test4():
    s = ''.join(lst)
    return [s[i:i + 2] for i in range(len(s) - 1)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test1()", setup="from __main__ import test1, lst", number=10000))
    print(timeit.timeit("test2()", setup="from __main__ import test2, lst", number=10000))
    print(timeit.timeit("test3()", setup="from __main__ import test3, lst", number=10000))
    print(timeit.timeit("test4()", setup="from __main__ import test4, lst", number=10000))

Results:

Python 2:

10.447159509
11.529946446
20.962497298000002
20.515838672

Python 3:

10.370675522
11.429417197
20.836504865999995
20.422865353

On bigger data map() is a bit (~9%) faster, but there's no significant difference between test1() and test2()


问:
get passed variable from the url using php
I am trying to pass a variable to another page with url. I have several submit buttons inside my form. once I click on of them, all the other element names with their values are submitted along with the data of that specific submit button. Once I try to save it to the database, they last value is saved into the database, even if it is not the chosen one.

http://127.0.0.1/product-details.php?quantity=1&username=cabdiqani&time=1559032347&image=girl1.jpg&uprice=35&quantity=71&username=cabdiqani&time=1559032347&image=girl2.jpg&uprice=35&quantity=1&username=cabdiqani&time=1559032347&image=girl3.jpg&uprice=35

Only the last one is always saved. Even if the button I clicked is associated with the different quantity or unit price. I want to save only the data associated with the clicked button. Can someone help?

The code:

```<code>echo '<b class="btn btn-default get" style="color:black; border: 1px green solid; border-radius:15px;">Quantity:</b>
      <input type=text name="quantity" class="btn btn-default get" value=1 style="width:10%; background-color: #aec45d;color:black;">
      <input type=submit class="btn btn-default get" value="Dalbo oo Hel">'; ?>

      <input type="hidden" name="username" value="<?php echo $_SESSION['logged']; ?>">
      <input type="hidden" name="time" value="<?php echo time(); ?>">
      <input type="hidden" name="image" value="<?php echo "girl1.jpg"; ?>">
      <input type="hidden" name="uprice" value="<?php echo 35; ?>">
</code>```

答:
Use</p>

```<code><form method="POST" action="submit.php"
   <input type=text name="quantity" class="btn btn-default get" value=1 style="width:10%; background-color: #aec45d;color:black;">
   <input type="hidden" name="username" value="<?php echo $_SESSION['logged']; ?>">
   <input type="hidden" name="time" value="<?php echo time(); ?>">
   <input type="hidden" name="image" value="<?php echo "girl1.jpg"; ?>">
   <input type="hidden" name="uprice" value="<?php echo 35; ?>">
   <input type=submit class="btn btn-default get" value="Dalbo oo Hel">
</form>
</code>```

Body:
I am trying to pass a variable to another page with url. I have several submit buttons inside my form. once I click on of them, all the other element names with their values are submitted along with the data of that specific submit button. Once I try to save it to the database, they last value is saved into the database, even if it is not the chosen one.

http://127.0.0.1/product-details.php?quantity=1&username=cabdiqani&time=1559032347&image=girl1.jpg&uprice=35&quantity=71&username=cabdiqani&time=1559032347&image=girl2.jpg&uprice=35&quantity=1&username=cabdiqani&time=1559032347&image=girl3.jpg&uprice=35

Only the last one is always saved. Even if the button I clicked is associated with the different quantity or unit price. I want to save only the data associated with the clicked button. Can someone help?

The code:

echo 'Quantity:
      <input type=text name="quantity" class="btn btn-default get" value=1 style="width:10%; background-color: #aec45d;color:black;">
      <input type=submit class="btn btn-default get" value="Dalbo oo Hel">'; ?>

      <input type="hidden" name="username" value="<?php echo $_SESSION['logged']; ?>">
      <input type="hidden" name="time" value="<?php echo time(); ?>">
      <input type="hidden" name="image" value="<?php echo "girl1.jpg"; ?>">
      <input type="hidden" name="uprice" value="<?php echo 35; ?>">

Body:
Use

<form method="POST" action="submit.php"
   <input type=text name="quantity" class="btn btn-default get" value=1 style="width:10%; background-color: #aec45d;color:black;">
   <input type="hidden" name="username" value="<?php echo $_SESSION['logged']; ?>">
   <input type="hidden" name="time" value="<?php echo time(); ?>">
   <input type="hidden" name="image" value="<?php echo "girl1.jpg"; ?>">
   <input type="hidden" name="uprice" value="<?php echo 35; ?>">
   <input type=submit class="btn btn-default get" value="Dalbo oo Hel">
</form>


问:
Should I throw generic error in GraphQL Scalar?
I'm trying to define Scalar types in GraphQL and graphql-yoga for server. The problem is I'm trying to decide should I throw GraphQLError or just a TypeError in this scenario

Currently, I'm using generic Errors.

export const URIScalar = new GraphQLScalarType({
  name: 'URI',
  description: 'A URI whose scheme is \'http\' or \'https\'',
  serialize(value) {
    if (isURI(value)) {
      return value;
    } else {
      throw new Error('URI format is invalid');
    }
  },
  parseValue(value) {
    if (isURI(value)) {
      return value;
    } else {
      throw new Error('URI format is invalid');
    }
  },
  parseLiteral(ast) {
    if (ast.kind === 'StringValue') {
      if (isURI(ast.value)) {
        return ast.value;
      } else {
        throw new Error('URI format is invalid');
      }
    } else {
      throw new Error('URI type must be string');
    }
  },
});
```

答:
Generic errors are perfect, given the information within them are informative.

The client will receive the error as expected, and you'll be able to locate where within your software the error is coming from.

Custom errors are great for when you need more data associated with it, but what you have will work.


问:
Hide one of the checkbox group choices but stiil keep its functionallity activated
I have a basic shiny app below with a checkbox group and the printed results of it. I was wondering if it is possible to somehow hide one of the 3 choices (for example "1") but the printed result should still include "1".</p>

```<code>#ui.r
fluidPage(

  # Copy the chunk below to make a group of checkboxes
  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
    choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
    selected = 1),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

)
#server.r
function(input, output) {

  # You can access the values of the widget (as a vector)
  # with input$checkGroup, e.g.
  output$value <- renderPrint({ input$checkGroup })

}
</code>```

答:
With CSS:</p>

```<code>ui <- fluidPage(

  tags$head(
    tags$style(HTML("input[name=checkGroup][value='1'] { display: none }"))
  ),

  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
                     choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
                     selected = 1),
  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

)
</code>```

Body:
I have a basic shiny app below with a checkbox group and the printed results of it. I was wondering if it is possible to somehow hide one of the 3 choices (for example "1") but the printed result should still include "1".

#ui.r
fluidPage(

  # Copy the chunk below to make a group of checkboxes
  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
    choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
    selected = 1),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

)
#server.r
function(input, output) {

  # You can access the values of the widget (as a vector)
  # with input$checkGroup, e.g.
  output$value <- renderPrint({ input$checkGroup })

}

Body:
With CSS:

ui <- fluidPage(

  tags$head(
    tags$style(HTML("input[name=checkGroup][value='1'] { display: none }"))
  ),

  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
                     choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
                     selected = 1),
  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

)


问:
Flutter equvalent Android-Toggle-Switch
is any flutter widget like with this library in android java?

```<code><belka.us.androidtoggleswitch.widgets.MultipleToggleSwitch
        android:id="@+id/multiple_toggle_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:textToggleCenter="Center"
        custom:textToggleLeft="Left"
        custom:textToggleRight="Right"
        android:layout_gravity="center"
        custom:toggleWidth="82dp"/>
</code>```

i did try to search to find this implementation on flutter but i can't

答:
You can opt to create your own switch, the code below is a quick demonstration and I know it needs signification improvements to match the original library style:

```<code> int selectedIndex = 0 ;

 Center(
        child: Container(
          padding: EdgeInsets.all(2.0),
          color: Colors.grey[300],
          child: Row(
            children: <Widget>[
              RaisedButton(
                child: Text('OR'),
                textColor: Colors.white,
                color: selectedIndex == 0 ? Colors.indigo : Colors.grey,
                onPressed: (){
                  setState(() {
                    selectedIndex = 0 ;
                  });
                },
              ),
              RaisedButton(
                child: Text('XOR'),
                textColor: Colors.white,
                color: selectedIndex == 1 ? Colors.indigo : Colors.grey,
                onPressed: (){
                  setState(() {
                    selectedIndex = 1 ;
                  });
                },
              ),
              RaisedButton(
                child: Text('AND'),
                textColor: Colors.white,
                color: selectedIndex == 2 ? Colors.indigo : Colors.grey,
                onPressed: (){
                  setState(() {
                    selectedIndex = 2 ;
                  });
                },
              ),
            ],
          ),
        ),
      ),
</code>```

Title: Flutter equvalent Android-Toggle-Switch

Body:
is any flutter widget like with this library in android java?

<belka.us.androidtoggleswitch.widgets.MultipleToggleSwitch
        android:id="@+id/multiple_toggle_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:textToggleCenter="Center"
        custom:textToggleLeft="Left"
        custom:textToggleRight="Right"
        android:layout_gravity="center"
        custom:toggleWidth="82dp"/>

i did try to search to find this implementation on flutter but i can't

Body:
You can opt to create your own switch, the code below is a quick demonstration and I know it needs signification improvements to match the original library style:

 int selectedIndex = 0 ;

 Center(
        child: Container(
          padding: EdgeInsets.all(2.0),
          color: Colors.grey[300],
          child: Row(
            children: <Widget>[
              RaisedButton(
                child: Text('OR'),
                textColor: Colors.white,
                color: selectedIndex == 0 ? Colors.indigo : Colors.grey,
                onPressed: (){
                  setState(() {
                    selectedIndex = 0 ;
                  });
                },
              ),
              RaisedButton(
                child: Text('XOR'),
                textColor: Colors.white,
                color: selectedIndex == 1 ? Colors.indigo : Colors.grey,
                onPressed: (){
                  setState(() {
                    selectedIndex = 1 ;
                  });
                },
              ),
              RaisedButton(
                child: Text('AND'),
                textColor: Colors.white,
                color: selectedIndex == 2 ? Colors.indigo : Colors.grey,
                onPressed: (){
                  setState(() {
                    selectedIndex = 2 ;
                  });
                },
              ),
            ],
          ),
        ),
      ),


问:
Resize the JPanel width based on the JFrame size
I would like to know if there is a way to resize only the width of a panel by taking it from the frame size, whereas, for the height value, I would like to leave the default one.

Thanks in advance!

答:
Use the BorderLayout Luke!

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

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

public class BorderLayoutExample {

    public static void main(String[] args) {
        JTextArea area = new JTextArea(15, 40);
        JFrame frm = new JFrame("Horizontal resizing");
        // not required, because the default layout here is the BorderLayout.
        // but in common case you probably need to do it.
        frm.setLayout(new BorderLayout());
        // Use BorderLayout.SOUTH - when you want that the top space will not be unused.
        frm.add(new JScrollPane(area), BorderLayout.NORTH);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }
}
</code>```

When you resize the frame, only the width of the text area will be modified. For more information read about layout managers

Body:
Use the BorderLayout Luke!

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

public class BorderLayoutExample {

    public static void main(String[] args) {
        JTextArea area = new JTextArea(15, 40);
        JFrame frm = new JFrame("Horizontal resizing");
        // not required, because the default layout here is the BorderLayout.
        // but in common case you probably need to do it.
        frm.setLayout(new BorderLayout());
        // Use BorderLayout.SOUTH - when you want that the top space will not be unused.
        frm.add(new JScrollPane(area), BorderLayout.NORTH);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }
}

When you resize the frame, only the width of the text area will be modified. For more information read about layout managers


问:
What is the size of column of int(11) in mysql in bytes?
What is the size of column of int(11) in mysql in bytes?

And Maximum value that can be stored in this columns?

答:
An INT will always be 4 bytes no matter what length is specified.

TINYINT = 1 byte (8 bit)

SMALLINT = 2 bytes (16 bit)

MEDIUMINT = 3 bytes (24 bit)

INT = 4 bytes (32 bit)

BIGINT = 8 bytes (64 bit).

The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 stored as int(3) will still show as 12345, but if it was stored as int(10) it would still display as 12345, but you would have the option to pad the first five digits. For example, if you added ZEROFILL it would display as 0000012345.

... and the maximum value will be 2147483647 (Signed) or 4294967295 (Unsigned)


问:
Cleaning unwanted rows of a scrapy result
I am trying to scrape data using Scrapy and and clean the result of price from any unwanted characters with mapcompose.

The result I have so far gives me a clean price, without any unwanted characters like currency sign or any . or ,
But, it gives me "extra" empty rows.

```<code>import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import MapCompose, Join
from makelaars.items import MakelaarsItem

class BasicSpider(scrapy.Spider):
    name = 'basic'
    allowed_domains = ['web']
    start_urls = ['https://www.bouka-makelaars.nl/koopaanbod']

    def parse(self, response):
        l = ItemLoader(item=MakelaarsItem(), response=response)
        #Extracting the content using css selectors
        l.add_css('address', '.details.property-page-link > h2[class=address]::text')
        l.add_css('price', '.price::text',MapCompose(lambda i: i.replace('.', '')),re='[.0-9]+')

        return l.load_item()
</code>```

The output I got so far is:

```<code>{'address': [u'Wezelrade 143 B',
             u'Wilhelmina van Pruisenlaan 245',
             u'Suzannaland 206',
             u'Molenweide 32',
             u'Spiraeastraat 00 2e etage',
             u'Kerklaan 122',
             u'Brandtstraat 163 /163A',
             u'Wouwermanstraat 9 /11/13/15',
             u'Scheepersstraat 100 /102/102A',
             u'Honthorststraat 137 /135',
             u'Brandtstraat 151 151A'],
 'price': [u'119500',
           u'',
           u'',
           u'200000',
           u'',
           u'',
           u'269500',
           u'',
           u'',
           u'539500',
           u'',
           u'',
           u'200000',
           u'',
           u'',
           u'299000',
           u'280000',
           u'',
           u'',
           u'675000',
           u'',
           u'',
           u'495000',
           u'',
           u'',
           u'475000',
           u'',
           u'',
           u'350000']}
</code>```

答:
Since you only need to clean the prices list before exporting the results to a CSV, you can do the following:
(output is assumed to be the dict that contains what you've shown in the question)

```<code>output['price'] = [item for item in output['price'] if item]
# empty strings in python are considered False, while others are True
</code>```

Your updated output['price'] will be exactly 11 in length, as below:

```<code>['119500', '200000', '269500', '539500', '200000', '299000', '280000', '675000', '495000', '475000', '350000']
</code>```

Body:
I am trying to scrape data using Scrapy and and clean the result of price from any unwanted characters with mapcompose.

The result I have so far gives me a clean price, without any unwanted characters like currency sign or any . or ,
But, it gives me "extra" empty rows.

import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import MapCompose, Join
from makelaars.items import MakelaarsItem

class BasicSpider(scrapy.Spider):
    name = 'basic'
    allowed_domains = ['web']
    start_urls = ['https://www.bouka-makelaars.nl/koopaanbod']

    def parse(self, response):
        l = ItemLoader(item=MakelaarsItem(), response=response)
        #Extracting the content using css selectors
        l.add_css('address', '.details.property-page-link > h2[class=address]::text')
        l.add_css('price', '.price::text',MapCompose(lambda i: i.replace('.', '')),re='[.0-9]+')

        return l.load_item()

The output I got so far is:

{'address': [u'Wezelrade 143 B',
             u'Wilhelmina van Pruisenlaan 245',
             u'Suzannaland 206',
             u'Molenweide 32',
             u'Spiraeastraat 00 2e etage',
             u'Kerklaan 122',
             u'Brandtstraat 163 /163A',
             u'Wouwermanstraat 9 /11/13/15',
             u'Scheepersstraat 100 /102/102A',
             u'Honthorststraat 137 /135',
             u'Brandtstraat 151 151A'],
 'price': [u'119500',
           u'',
           u'',
           u'200000',
           u'',
           u'',
           u'269500',
           u'',
           u'',
           u'539500',
           u'',
           u'',
           u'200000',
           u'',
           u'',
           u'299000',
           u'280000',
           u'',
           u'',
           u'675000',
           u'',
           u'',
           u'495000',
           u'',
           u'',
           u'475000',
           u'',
           u'',
           u'350000']}

Body:
Since you only need to clean the prices list before exporting the results to a CSV, you can do the following:
(output is assumed to be the dict that contains what you've shown in the question)

output['price'] = [item for item in output['price'] if item]
# empty strings in python are considered False, while others are True

Your updated output['price'] will be exactly 11 in length, as below:

['119500', '200000', '269500', '539500', '200000', '299000', '280000', '675000', '495000', '475000', '350000']


问:
how to access the object in my array on function call
I created an array of objects with different properties but I am having problem displaying each properties of my object on the webpage. I have tried but I don't know where the problem is.

I have tried to access the objects individually but still not working please check the problem

//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");

//Event listeners
continued.addEventListener('click', continueAfterIntro);
start.addEventListener('click', startQuiz);

//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;

//Array object declaration
let questions = [{
  question: "Who is the president Nigeria?",
  choiceA: "Muhamadu Buhari",
  choiceB: "Osibajo",
  choiceC: "Obasanjo",
  choiceD: "Green,Red,Green",
  correct: "A"
}, {
  question: "Who is the governor of oyo state?",
  choiceA: "Abiola Ajumobi",
  choiceB: "Seyi makinde",
  choiceC: "Alao Akala",
  choiceD: "Green,Red,Green",
  correct: "B"
}, {
  question: "What are the colors of the Nigerian Flag?",
  choiceA: "Green,White,Blue",
  choiceB: "Blue,White,Green",
  choiceC: "Green,White,Green",
  choiceD: "Green,Red,Green",
  correct: "C"
}];

function continueAfterIntro() {
  intro.style.display = 'none';
  startt.style.display = 'block';
  wel.innerHTML = `Hi ${name}`;
}

function renderQuestion() {
  let q = questions[runningQuestion];
  question.innerHTML = "
" + q.question + "
";
  choiceA.innerHTML = q.choiceA;
  choiceB.innerHTML = q.choiceB;
  choiceC.innerHTML = q.choiceC;
}

function startQuiz() {
  startt.style.display = "none";
  quiz.style.display = "block";
  renderQuestion();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="" id="introduction">
    <div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
    <div id="para1">
      <p>Hey there i'm AFO by name whats yours</p>
    </div>
    <div id="name-button">
      <span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
      <span id="continue"><input type="button" value="Continue" id="continue"></span>
    </div>
  </div>
  <div id="startt" style="display: none">
    <p id="wel"></p>
    <div id="start">Start Quiz!</div>
  </div>
  <div id="quiz" style="display: none">
    <div id="question"></div>
    <div id="choices">
      A.
      <div class="choice" id="A" onclick="checkAnswer('A')"></div>
      B.
      <div class="choice" id="B" onclick="checkAnswer('B')"></div>
      C.
      <div class="choice" id="C" onclick="checkAnswer('C')"></div>
      D.
      <div class="choice" id="D" onclick="checkAnswer('D')"></div>
    </div>
    <div id="timer">
      <div id="counter"></div>
      <div id="btimeGauge"></div>
      <div id="timeGauge"></div>
    </div>
    <div id="progress"></div>
  </div>
  <div id="scoreContainer" style="display: none"></div>
</div></code>```

The function renderQuestion should display the questions and the choices on the webpage

答:
When i run your project i got ReferenceError.

```<code>Uncaught ReferenceError: Cannot access 'questions' before initialization
</code>```

That means you can't play around with Questions Array before initialization. For example:

```<code>const questionsLength = questions.length;  // REFERENCE ERROR.
const questions = ['a', 'b', 'c'];
console.log(questionsLength);
</code>```

Declare Questions Array before you inspect length:

```<code>const questions = ['a', 'b', 'c'];
const questionsLength = questions.length;
console.log(questionsLenght) // Returns 3
</code>```

Working example:

//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");

//Event listeners
continued.addEventListener('click',continueAfterIntro);
start.addEventListener('click',startQuiz);

//Array object declaration
let questions = [
    {
        question : "Who is the president Nigeria?",
        choiceA : "Muhamadu Buhari",
        choiceB : "Osibajo",
        choiceC : "Obasanjo",
        choiceD : "Green,Red,Green",
        correct : "A"
    },{
        question : "Who is the governor of oyo state?",
        choiceA : "Abiola Ajumobi",
        choiceB : "Seyi makinde",
        choiceC : "Alao Akala",
        choiceD : "Green,Red,Green",
        correct : "B"
    },{
        question : "What are the colors of the Nigerian Flag?",
        choiceA : "Green,White,Blue",
        choiceB : "Blue,White,Green",
        choiceC : "Green,White,Green",
        choiceD : "Green,Red,Green",
        correct : "C"
    }
];
//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;

function continueAfterIntro(){
    intro.style.display = 'none';
    startt.style.display = 'block';
    wel.innerHTML = `Hi ${name}`;
}

function renderQuestion(){
    let q = questions[runningQuestion];
    question.innerHTML = "
"+ q.question +"
";
    choiceA.innerHTML = q.choiceA;
    choiceB.innerHTML = q.choiceB;
    choiceC.innerHTML = q.choiceC;
}

function startQuiz(){
    startt.style.display = "none";
    quiz.style.display = "block";
    renderQuestion();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
        <link rel="stylesheet" href="quiz.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <div id="container">
                    <div class="" id="introduction">
                        <div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
                        <div id="para1"><p>Hey there i'm AFO by name whats yours</p> </div>
                        <div id="name-button">
                        <span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
                        <span id="continue"><input type="button" value="Continue" id="continue"></span>
                    </div>
                    </div>
                    <div id="startt" style="display: none">
                        <p id="wel"></p>
                <div id="start" >Start Quiz!</div>
            </div>
                <div id="quiz" style="display: none">
                    <div id="question"></div>
                    <div id="choices">
                       A.<div class="choice" id="A" onclick="checkAnswer('A')"></div>
                       B.<div class="choice" id="B" onclick="checkAnswer('B')"></div>
                       C.<div class="choice" id="C" onclick="checkAnswer('C')"></div>
                       D.<div class="choice" id="D" onclick="checkAnswer('D')"></div>
                    </div>
                    <div id="timer">
                            <div id="counter"></div>
                            <div id="btimeGauge"></div>
                            <div id="timeGauge"></div>
                        </div>
                    <div id="progress"></div>
                </div>
                <div id="scoreContainer" style="display: none"></div>
            </div>
</body>
</html></code>```

What ReferenceError mean MDN#ReferenceError

Body:
I created an array of objects with different properties but I am having problem displaying each properties of my object on the webpage. I have tried but I don't know where the problem is.

I have tried to access the objects individually but still not working please check the problem

//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");

//Event listeners
continued.addEventListener('click', continueAfterIntro);
start.addEventListener('click', startQuiz);

//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;

//Array object declaration
let questions = [{
  question: "Who is the president Nigeria?",
  choiceA: "Muhamadu Buhari",
  choiceB: "Osibajo",
  choiceC: "Obasanjo",
  choiceD: "Green,Red,Green",
  correct: "A"
}, {
  question: "Who is the governor of oyo state?",
  choiceA: "Abiola Ajumobi",
  choiceB: "Seyi makinde",
  choiceC: "Alao Akala",
  choiceD: "Green,Red,Green",
  correct: "B"
}, {
  question: "What are the colors of the Nigerian Flag?",
  choiceA: "Green,White,Blue",
  choiceB: "Blue,White,Green",
  choiceC: "Green,White,Green",
  choiceD: "Green,Red,Green",
  correct: "C"
}];

function continueAfterIntro() {
  intro.style.display = 'none';
  startt.style.display = 'block';
  wel.innerHTML = `Hi ${name}`;
}

function renderQuestion() {
  let q = questions[runningQuestion];
  question.innerHTML = "
" + q.question + "
";
  choiceA.innerHTML = q.choiceA;
  choiceB.innerHTML = q.choiceB;
  choiceC.innerHTML = q.choiceC;
}

function startQuiz() {
  startt.style.display = "none";
  quiz.style.display = "block";
  renderQuestion();
}

Hey there i'm AFO by name whats yours

      <input type="text" id="name" placeholder="Type Your Name Here">
      <input type="button" value="Continue" id="continue">

Start Quiz!

      A.

      B.

      C.

      D.

The function renderQuestion should display the questions and the choices on the webpage

Body:
When i run your project i got ReferenceError.

Uncaught ReferenceError: Cannot access 'questions' before initialization

That means you can't play around with Questions Array before initialization. For example:

const questionsLength = questions.length;  // REFERENCE ERROR.
const questions = ['a', 'b', 'c'];
console.log(questionsLength);

Declare Questions Array before you inspect length:

const questions = ['a', 'b', 'c'];
const questionsLength = questions.length;
console.log(questionsLenght) // Returns 3

Working example:

//Get the id's of all elements
const intro = document.getElementById("introduction");
const continued = document.getElementById("continue");
const name = document.getElementById("name").value;
const wel = document.getElementById("wel")
const startt = document.getElementById("startt");
const start = document.getElementById("start");
const quiz = document.getElementById("quiz");
const question = document.getElementById("question");
const qImg = document.getElementById("qImg");
const choiceA = document.getElementById("A");
const choiceB = document.getElementById("B");
const choiceC = document.getElementById("C");
const choiceD = document.getElementById("D");
const counter = document.getElementById("counter");
const timeGauge = document.getElementById("timeGauge");
const progress = document.getElementById("progress");
const scoreDiv = document.getElementById("scoreContainer");

//Event listeners
continued.addEventListener('click',continueAfterIntro);
start.addEventListener('click',startQuiz);

//Array object declaration
let questions = [
    {
        question : "Who is the president Nigeria?",
        choiceA : "Muhamadu Buhari",
        choiceB : "Osibajo",
        choiceC : "Obasanjo",
        choiceD : "Green,Red,Green",
        correct : "A"
    },{
        question : "Who is the governor of oyo state?",
        choiceA : "Abiola Ajumobi",
        choiceB : "Seyi makinde",
        choiceC : "Alao Akala",
        choiceD : "Green,Red,Green",
        correct : "B"
    },{
        question : "What are the colors of the Nigerian Flag?",
        choiceA : "Green,White,Blue",
        choiceB : "Blue,White,Green",
        choiceC : "Green,White,Green",
        choiceD : "Green,Red,Green",
        correct : "C"
    }
];
//variable declarations
const lastQuestion = questions.length - 1;
var runningQuestion = 0;
var secs = 0;
var mins = 0;
var hrs = 0;
const questionTime = 60; // 60s
const gaugeWidth = 180; // 180px
const gaugeUnit = gaugeWidth / questionTime;
let TIMER;
let score = 0;

function continueAfterIntro(){
    intro.style.display = 'none';
    startt.style.display = 'block';
    wel.innerHTML = `Hi ${name}`;
}

function renderQuestion(){
    let q = questions[runningQuestion];
    question.innerHTML = "<p>"+ q.question +"</p>";
    choiceA.innerHTML = q.choiceA;
    choiceB.innerHTML = q.choiceB;
    choiceC.innerHTML = q.choiceC;
}

function startQuiz(){
    startt.style.display = "none";
    quiz.style.display = "block";
    renderQuestion();
}

<!DOCTYPE html>
<html lang="en">
<head>
        <link rel="stylesheet" href="quiz.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <div id="container">
                    <div class="" id="introduction">
                        <div id="pimg"><img src="pic/thumbs.png" alt="WELCOME FACE"></div>
                        <div id="para1"><p>Hey there i'm AFO by name whats yours</p> </div>
                        <div id="name-button">
                        <span id="iName"><input type="text" id="name" placeholder="Type Your Name Here"></span>
                        <span id="continue"><input type="button" value="Continue" id="continue"></span>
                    </div>
                    </div>
                    <div id="startt" style="display: none">
                        <p id="wel"></p>
                <div id="start" >Start Quiz!</div>
            </div>
                <div id="quiz" style="display: none">
                    <div id="question"></div>
                    <div id="choices">
                       A.<div class="choice" id="A" onclick="checkAnswer('A')"></div>
                       B.<div class="choice" id="B" onclick="checkAnswer('B')"></div>
                       C.<div class="choice" id="C" onclick="checkAnswer('C')"></div>
                       D.<div class="choice" id="D" onclick="checkAnswer('D')"></div>
                    </div>
                    <div id="timer">
                            <div id="counter"></div>
                            <div id="btimeGauge"></div>
                            <div id="timeGauge"></div>
                        </div>
                    <div id="progress"></div>
                </div>
                <div id="scoreContainer" style="display: none"></div>
            </div>
</body>
</html>

What ReferenceError mean MDN#ReferenceError


问:
How to convert "Wed Apr 10 03:48:00 PDT 2019" to 2019-04-10 03:48:00 in scala?
I have value like following "Wed Apr 10 03:48:00 PDT 2019" and want to convert or parse in 2019-04-10 03:48:00.

My excepted result is:

```<code>2019-04-10 03:53:02
</code>```

答:
You should just use DateTimeFormatter:

```<code>val dateString = "Wed Apr 10 03:48:00 PDT 2019"

val dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH)

val parsed = ZonedDateTime.parse(dateString , dtf)

val formatted = DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss").format(parsed)
</code>```

Remember to pass explicitly Locale as the second argument to DateTimeFormatter.ofPattern because this code might fail on parsing Apr part on a computer with different default locale!

Body:
I have value like following "Wed Apr 10 03:48:00 PDT 2019" and want to convert or parse in 2019-04-10 03:48:00.

My excepted result is:

2019-04-10 03:53:02

Body:
You should just use DateTimeFormatter:

val dateString = "Wed Apr 10 03:48:00 PDT 2019"

val dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH)

val parsed = ZonedDateTime.parse(dateString , dtf)

val formatted = DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss").format(parsed)

Remember to pass explicitly Locale as the second argument to DateTimeFormatter.ofPattern because this code might fail on parsing Apr part on a computer with different default locale!


问:
multiple directives with export as
```<code><form novalidate class="mt-2" #paramForm="ngForm" [formGroup]="form" (ngSubmit)="onSubmit(form)">
</code>```

I got the following hint from webstorm:

Is there a way to access ngForm instance exported by formGroupDirective?

答:
You should only use either one of those:

```<code>#paramForm="ngForm"         // This pertains to Template Driven Form

or

[formGroup]="form"         // This pertains to Reactive Form
</code>```

So if you are using a Template driven form where you will specify the controls on [(ngModel)] on your template, use #paramForm="ngForm"

```<code><form novalidate
      class="mt-2"
      #paramForm="ngForm"
      (ngSubmit)="onSubmit(form)">
</code>```

But if not and you are using a Reactive form where you specify your FormControls on your component by either using a FormBuilder/FormGroup/FormControl, use [formGroup]="form"

```<code><form novalidate
      class="mt-2"
      [formGroup]="form"
      (ngSubmit)="onSubmit(form)">
</code>```

Have created a Stackblitz as per your concern below. Hope this helps.

Title: multiple directives with export as

Body:
<form novalidate class="mt-2" #paramForm="ngForm" [formGroup]="form" (ngSubmit)="onSubmit(form)">

I got the following hint from webstorm:

Is there a way to access ngForm instance exported by formGroupDirective?

Body:
You should only use either one of those:

#paramForm="ngForm"         // This pertains to Template Driven Form

or

[formGroup]="form"         // This pertains to Reactive Form

So if you are using a Template driven form where you will specify the controls on [(ngModel)] on your template, use #paramForm="ngForm"

<form novalidate
      class="mt-2"
      #paramForm="ngForm"
      (ngSubmit)="onSubmit(form)">

But if not and you are using a Reactive form where you specify your FormControls on your component by either using a FormBuilder/FormGroup/FormControl, use [formGroup]="form"

<form novalidate
      class="mt-2"
      [formGroup]="form"
      (ngSubmit)="onSubmit(form)">

Have created a Stackblitz as per your concern below. Hope this helps.


问:
TSQL copy table data to another table with custom values
I have 2 tables with identical columns expect one which is userId. I want to copy all the data from the first table into the second one and add custom userId to the column that is missing. Thus far without success.

The query is shown below. Insert Quality, Quantity, Supplier and UserId (which doesn't exist in the table im getting data)

```<code>`DECLARE @UserId int = 5611; -- add this to all the data from dbo.GasStation

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT * FROM dbo.GasStation -- UserId doesn't exist in this table
-- Add somehow @UserId to all the data i'm getting from GasStation in order to satisfy the column UserId in the NewGasStation`
</code>```

All the data i'm getting from dbo.GasStation to be inserted to dbo.NewGasStation adding this custom UserId to all the results.

答:
Instead of * list the columns in your SELECT explicitly and add the variable to that list.

```<code>DECLARE @userid integer = 5611;

INSERT INTO dbo.newgasstation
           (quality,
            quantity,
            supplier,
            userid)
           SELECT quality,
                  quantity,
                  supplier,
                  @userid
                  FROM dbo.gasstation;
</code>```

Body:
I have 2 tables with identical columns expect one which is userId. I want to copy all the data from the first table into the second one and add custom userId to the column that is missing. Thus far without success.

The query is shown below. Insert Quality, Quantity, Supplier and UserId (which doesn't exist in the table im getting data)

`DECLARE @UserId int = 5611; -- add this to all the data from dbo.GasStation

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT * FROM dbo.GasStation -- UserId doesn't exist in this table
-- Add somehow @UserId to all the data i'm getting from GasStation in order to satisfy the column UserId in the NewGasStation`

All the data i'm getting from dbo.GasStation to be inserted to dbo.NewGasStation adding this custom UserId to all the results.

Body:
Instead of * list the columns in your SELECT explicitly and add the variable to that list.

DECLARE @userid integer = 5611;

INSERT INTO dbo.newgasstation
           (quality,
            quantity,
            supplier,
            userid)
           SELECT quality,
                  quantity,
                  supplier,
                  @userid
                  FROM dbo.gasstation;


答:
Just add @UserId to the SELECT list:

```<code>INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
    SELECT Quality, Quantity, Supplier, @UserId
    FROM dbo.GasStation ;
</code>```

Title: TSQL copy table data to another table with custom values

Body:
Just add @UserId to the SELECT list:

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
    SELECT Quality, Quantity, Supplier, @UserId
    FROM dbo.GasStation ;